file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
ledger_cleanup_service.rs
//! The `ledger_cleanup_service` drops older ledger data to limit disk space usage use solana_ledger::blockstore::Blockstore; use solana_ledger::blockstore_db::Result as BlockstoreResult; use solana_measure::measure::Measure; use solana_metrics::datapoint_debug; use solana_sdk::clock::Slot; use std::string::ToString; ...
//send a signal to kill all but 5 shreds, which will be in the newest slots let mut last_purge_slot = 0; sender.send(50).unwrap(); LedgerCleanupService::cleanup_ledger(&receiver, &blockstore, 5, &mut last_purge_slot, 10) .unwrap(); //check that 0-40 don't exist ...
let blockstore = Arc::new(blockstore); let (sender, receiver) = channel();
random_line_split
space_group.py
# Copyright 2021 The NetKet Authors - All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
return PermutationGroup(perms, degree=self.lattice.n_nodes) @struct.property_cached def rotation_group(self) -> PermutationGroup: """The group of rotations (i.e. point group symmetries with determinant +1) as a `PermutationGroup` acting on the sites of `self.lattice`.""" perms ...
perm = self.lattice.id_from_position(p.preimage(self.lattice.positions)) perms.append(Permutation(perm, name=str(p)))
conditional_block
space_group.py
# Copyright 2021 The NetKet Authors - All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
def translation_group( self, axes: Optional[Union[int, Sequence[int]]] = None ) -> PermutationGroup: """ The group of valid translations of `self.lattice` as a `PermutationGroup` acting on the sites of the same. """ if axes is None: return self._full...
""" The group of valid translations of `self.lattice` as a `PermutationGroup` acting on the sites of the same. """ return reduce( PermutationGroup.__matmul__, [self._translations_along_axis(i) for i in range(self.lattice.ndim)], )
identifier_body
space_group.py
# Copyright 2021 The NetKet Authors - All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
(self, permutation: Array, displacement: Array): r""" Creates a `Translation` from a permutation array and a displacement vector Arguments: permutation: a 1D array listing :math:`g^{-1}(x)` for all :math:`0\le x < N` (i.e., `V[permutation]` permutes the ...
__init__
identifier_name
space_group.py
# Copyright 2021 The NetKet Authors - All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
if isinstance(p, Identity): perms.append(Identity()) else: # note that we need the preimages in the permutation perm = self.lattice.id_from_position(p.preimage(self.lattice.positions)) perms.append(Permutation(perm, name=str(p))) ...
""" perms = [] for p in self.point_group_:
random_line_split
basic_model.py
from collections import defaultdict # from torchtext.vocab import Vocab from torch.utils.data.dataset import Dataset, TensorDataset from pathlib import Path from collections import Counter import pandas as pd import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as opt...
# taken from the paper MLP_HIDDEN_DIM = 100 EPOCHS = 150 WORD_EMBEDDING_DIM = 100 POS_EMBEDDING_DIM = 25 HIDDEN_DIM = 125 LEARNING_RATE = 0.01 EARLY_STOPPING = 10 # num epochs with no validation acc improvement to stop training PATH = "./basic_model_best_params" cross_entropy_loss = nn.CrossEntropyLoss(reduction='me...
import matplotlib.pyplot as plt from chu_liu_edmonds import * from os import path
random_line_split
basic_model.py
from collections import defaultdict # from torchtext.vocab import Vocab from torch.utils.data.dataset import Dataset, TensorDataset from pathlib import Path from collections import Counter import pandas as pd import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as opt...
(self, lstm_dim, mlp_hidden_dim): super(MLP, self).__init__() self.first_mlp = SplittedMLP(lstm_dim, mlp_hidden_dim) self.non_linearity = nn.Tanh() self.second_mlp = nn.Linear(mlp_hidden_dim, 1, bias=True) # will output a score of a pair def forward(self, lstm_out): senten...
__init__
identifier_name
basic_model.py
from collections import defaultdict # from torchtext.vocab import Vocab from torch.utils.data.dataset import Dataset, TensorDataset from pathlib import Path from collections import Counter import pandas as pd import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as opt...
else: main()
hyper_parameter_tuning()
conditional_block
basic_model.py
from collections import defaultdict # from torchtext.vocab import Vocab from torch.utils.data.dataset import Dataset, TensorDataset from pathlib import Path from collections import Counter import pandas as pd import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as opt...
class MLP(nn.Module): def __init__(self, lstm_dim, mlp_hidden_dim): super(MLP, self).__init__() self.first_mlp = SplittedMLP(lstm_dim, mlp_hidden_dim) self.non_linearity = nn.Tanh() self.second_mlp = nn.Linear(mlp_hidden_dim, 1, bias=True) # will output a score of a pair de...
heads_hidden = self.fc_h(lstm_out) mods_hidden = self.fc_m(lstm_out) return heads_hidden, mods_hidden
identifier_body
main.go
package main import ( "encoding/json" "fmt" "math" "math/rand" "net/http" "os" "sort" "strings" "time" m3o "github.com/micro/services/clients/go" db "github.com/micro/services/clients/go/db" user "github.com/micro/services/clients/go/user" uuid "github.com/satori/go.uuid" ) var client = m3o.NewClient(os...
func main() { http.HandleFunc("/upvotePost", voteWrapper(true, false)) http.HandleFunc("/downvotePost", voteWrapper(false, false)) http.HandleFunc("/upvoteComment", voteWrapper(true, true)) http.HandleFunc("/downvoteComment", voteWrapper(false, true)) http.HandleFunc("/posts", posts) http.HandleFunc("/post", po...
{ if err != nil { w.WriteHeader(500) fmt.Println(err) } if i == nil { i = map[string]interface{}{} } if err != nil { i = map[string]interface{}{ "error": err.Error(), } } bs, _ := json.Marshal(i) fmt.Fprintf(w, fmt.Sprintf("%v", string(bs))) }
identifier_body
main.go
package main import ( "encoding/json" "fmt" "math" "math/rand" "net/http" "os" "sort" "strings" "time" m3o "github.com/micro/services/clients/go" db "github.com/micro/services/clients/go/db" user "github.com/micro/services/clients/go/user" uuid "github.com/satori/go.uuid" ) var client = m3o.NewClient(os...
func post(w http.ResponseWriter, req *http.Request) { if cors(w, req) { return } decoder := json.NewDecoder(req.Body) var t PostRequest err := decoder.Decode(&t) if err != nil { respond(w, nil, err) return } if t.Post.Sub == "" || t.Post.Title == "" { respond(w, nil, fmt.Errorf("both title and sub are...
}, err) }
random_line_split
main.go
package main import ( "encoding/json" "fmt" "math" "math/rand" "net/http" "os" "sort" "strings" "time" m3o "github.com/micro/services/clients/go" db "github.com/micro/services/clients/go/db" user "github.com/micro/services/clients/go/user" uuid "github.com/satori/go.uuid" ) var client = m3o.NewClient(os...
order := math.Log10(math.Max(math.Abs(score), 1)) var created int64 switch v := m["created"].(type) { case string: t, err := time.Parse(time.RFC3339, v) if err != nil { fmt.Println(err) } created = t.Unix() case float64: created = int64(v) case int64: created = v } seconds := created - 11340280...
{ sign = -1 }
conditional_block
main.go
package main import ( "encoding/json" "fmt" "math" "math/rand" "net/http" "os" "sort" "strings" "time" m3o "github.com/micro/services/clients/go" db "github.com/micro/services/clients/go/db" user "github.com/micro/services/clients/go/user" uuid "github.com/satori/go.uuid" ) var client = m3o.NewClient(os...
(w http.ResponseWriter, i interface{}, err error) { if err != nil { w.WriteHeader(500) fmt.Println(err) } if i == nil { i = map[string]interface{}{} } if err != nil { i = map[string]interface{}{ "error": err.Error(), } } bs, _ := json.Marshal(i) fmt.Fprintf(w, fmt.Sprintf("%v", string(bs))) } func...
respond
identifier_name
tcp.rs
// "Tifflin" Kernel - Networking Stack // - By John Hodge (thePowersGang) // // Modules/network/tcp.rs //! Transmission Control Protocol (Layer 4) use shared_map::SharedMap; use kernel::sync::Mutex; use kernel::lib::ring_buffer::{RingBuf,AtomicRingBuf}; use core::sync::atomic::{AtomicUsize, Ordering}; use crate::nic::S...
ConnectionState::Finished => return, }; self.state_update(quad, new_state); } fn state_update(&mut self, quad: &Quad, new_state: ConnectionState) { if self.state != new_state { log_trace!("{:?} {:?} -> {:?}", quad, self.state, new_state); self.state = new_state; // TODO: If transitioning to `Fi...
ConnectionState::TimeWait => self.state,
random_line_split
tcp.rs
// "Tifflin" Kernel - Networking Stack // - By John Hodge (thePowersGang) // // Modules/network/tcp.rs //! Transmission Control Protocol (Layer 4) use shared_map::SharedMap; use kernel::sync::Mutex; use kernel::lib::ring_buffer::{RingBuf,AtomicRingBuf}; use core::sync::atomic::{AtomicUsize, Ordering}; use crate::nic::S...
else if hdr.flags & FLAG_FIN != 0 { // FIN received, start a clean shutdown self.next_rx_seq += 1; // TODO: Signal to user that the connection is closing (EOF) ConnectionState::CloseWait } else { if pkt.remain() == 0 { // Pure ACK, no change if hdr.flags == FLAG_ACK { log_t...
{ // RST received, do an unclean close (reset by peer) // TODO: Signal to user that the connection is closing (error) ConnectionState::ForceClose }
conditional_block
tcp.rs
// "Tifflin" Kernel - Networking Stack // - By John Hodge (thePowersGang) // // Modules/network/tcp.rs //! Transmission Control Protocol (Layer 4) use shared_map::SharedMap; use kernel::sync::Mutex; use kernel::lib::ring_buffer::{RingBuf,AtomicRingBuf}; use core::sync::atomic::{AtomicUsize, Ordering}; use crate::nic::S...
(local_addr: Address, local_port: u16, remote_addr: Address, remote_port: u16) -> Quad { Quad { local_addr, local_port, remote_addr, remote_port } } fn send_packet(&self, seq: u32, ack: u32, flags: u8, window_size: u16, data: &[u8]) { // Make a header // TODO: Any options required? let options_bytes =...
new
identifier_name
tcp.rs
// "Tifflin" Kernel - Networking Stack // - By John Hodge (thePowersGang) // // Modules/network/tcp.rs //! Transmission Control Protocol (Layer 4) use shared_map::SharedMap; use kernel::sync::Mutex; use kernel::lib::ring_buffer::{RingBuf,AtomicRingBuf}; use core::sync::atomic::{AtomicUsize, Ordering}; use crate::nic::S...
fn send_packet(&self, seq: u32, ack: u32, flags: u8, window_size: u16, data: &[u8]) { // Make a header // TODO: Any options required? let options_bytes = &[]; let opts_len_rounded = ((options_bytes.len() + 3) / 4) * 4; let hdr = PktHeader { source_port: self.local_port, dest_port: self.remote_port, ...
{ Quad { local_addr, local_port, remote_addr, remote_port } }
identifier_body
kegweblib.py
from builtins import str import pytz from django.conf import settings from django.template import ( Library, Node, TemplateSyntaxError, Variable, VariableDoesNotExist, ) from django.template.defaultfilters import pluralize from django.urls import reverse from django.utils import timezone from djang...
(parser, token): """{% timeago <timestamp> %}""" tokens = token.contents.split() if len(tokens) != 2: raise TemplateSyntaxError("%s requires 2 tokens" % tokens[0]) return TimeagoNode(tokens[1]) class TimeagoNode(Node): def __init__(self, timestamp_varname): self._timestamp_varname ...
timeago
identifier_name
kegweblib.py
from builtins import str import pytz from django.conf import settings from django.template import ( Library, Node, TemplateSyntaxError, Variable, VariableDoesNotExist, ) from django.template.defaultfilters import pluralize from django.urls import reverse from django.utils import timezone from djang...
@classmethod def format(cls, amount, units, make_badge=False): if amount < 0: amount = 0 ctx = { "units": units, "amount": amount, "title": "%s %s" % (amount, units), "extra_css": "badge " if make_badge else "", } retu...
tv = Variable(self._volume_varname) try: num = float(tv.resolve(context)) except (VariableDoesNotExist, ValueError): num = "unknown" unit = "mL" make_badge = "badge" in self._extra_args return self.format(num, unit, make_badge)
identifier_body
kegweblib.py
from builtins import str import pytz from django.conf import settings from django.template import ( Library, Node, TemplateSyntaxError, Variable, VariableDoesNotExist, ) from django.template.defaultfilters import pluralize from django.urls import reverse from django.utils import timezone from djang...
return context["guest_info"]["name"] # chart @register.tag("chart") def chart(parser, tokens): """{% chart <charttype> <obj> width height %}""" tokens = tokens.contents.split() if len(tokens) < 4: raise TemplateSyntaxError("chart requires at least 4 arguments") charttype = tokens[1]...
return '<a href="%s">%s</a>' % ( reverse("kb-drinker", args=[user.username]), user.get_full_name(), )
conditional_block
kegweblib.py
from builtins import str import pytz from django.conf import settings from django.template import ( Library, Node, TemplateSyntaxError, Variable, VariableDoesNotExist, ) from django.template.defaultfilters import pluralize from django.urls import reverse from django.utils import timezone from djang...
c = {} if not hasattr(picture_or_pictures, "__iter__"): c["gallery_pictures"] = [picture_or_pictures] else: c["gallery_pictures"] = picture_or_pictures c["thumb_size"] = thumb_size c["gallery_id"] = gallery_id return c @register.inclusion_tag("kegweb/badge.html") def badge(amou...
@register.inclusion_tag("kegweb/picture-gallery.html") def gallery(picture_or_pictures, thumb_size="span2", gallery_id=""):
random_line_split
ddpg-per.py
import tensorflow as tf import numpy as np import gym import os ##################### hyper parameters #################### # Hyper Parameters ENV_NAME = 'Pendulum-v0' EPISODE = 200 STEP = 200 TEST = 5 LR_A = 0.001 # learning rate for actor LR_C = 0.002 # learning rate for critic MEMORY_SIZE = 10000 steps = [] ep...
date_target_q_network(self, episode): # update target Q netowrk by soft_replace if episode % REPLACE_TARGET_FREQ == 0: self.sess.run(self.soft_replace) # print('episode '+str(episode) +', target Q network params replaced!') def load_network(self, saver, load_path): c...
able_scope(scope): n_l1 = 30 w1_s = tf.get_variable('w1_s', [self.s_dim, n_l1], trainable=trainable) w1_a = tf.get_variable('w1_a', [self.a_dim, n_l1], trainable=trainable) b1 = tf.get_variable('b1', [1, n_l1], trainable=trainable) net = tf.nn.relu(tf.matmul(s...
identifier_body
ddpg-per.py
import tensorflow as tf import numpy as np import gym import os ##################### hyper parameters #################### # Hyper Parameters ENV_NAME = 'Pendulum-v0' EPISODE = 200 STEP = 200 TEST = 5 LR_A = 0.001 # learning rate for actor LR_C = 0.002 # learning rate for critic MEMORY_SIZE = 10000 steps = [] ep...
r, s_): transition = np.hstack((s, a, r, s_)) self.memory.store(transition) self.pointer += 1 def _build_a(self, s, scope, trainable): with tf.variable_scope(scope): net = tf.layers.dense(s, 30, activation=tf.nn.relu, name='l1', trainable=trainable) # new_ac...
tion(self, s, a,
identifier_name
ddpg-per.py
import tensorflow as tf import numpy as np import gym import os ##################### hyper parameters #################### # Hyper Parameters ENV_NAME = 'Pendulum-v0' EPISODE = 200 STEP = 200 TEST = 5 LR_A = 0.001 # learning rate for actor LR_C = 0.002 # learning rate for critic MEMORY_SIZE = 10000 steps = [] ep...
for episode in range(EPISODE): state = env.reset() ep_reward = 0 # train for step in range(STEP): if RENDER: env.render() action = agent.choose_action(state, with_noise) action = np.clip(np.random.normal(action, var), -2, 2) ...
agent = DDPG(a_dim, s_dim, a_bound) total_steps = 0 var = 3
random_line_split
ddpg-per.py
import tensorflow as tf import numpy as np import gym import os ##################### hyper parameters #################### # Hyper Parameters ENV_NAME = 'Pendulum-v0' EPISODE = 200 STEP = 200 TEST = 5 LR_A = 0.001 # learning rate for actor LR_C = 0.002 # learning rate for critic MEMORY_SIZE = 10000 steps = [] ep...
lf.learn_step += 1 def store_transition(self, s, a, r, s_): transition = np.hstack((s, a, r, s_)) self.memory.store(transition) self.pointer += 1 def _build_a(self, s, scope, trainable): with tf.variable_scope(scope): net = tf.layers.dense(s, 30, activation=tf.nn.re...
tch_memory, ISWeights = self.memory.sample(self.per_batch_size) # sample for learning batch_states = batch_memory[:,0:3] batch_actions = batch_memory[:,3:4] batch_rewards = [data[4] for data in batch_memory] batch_states_ = batch_memory[:,5:8] bs = np.array(b...
conditional_block
bot.js
(function () { "use strict"; const fs = require("fs"); const request = require("request"); require("/code/keys/load-keys.js")(); const Utils = require("/code/global-modules/utils.js"); let CytubeConstructor = require("./my-modules/cytube.js")(Utils); const DiscordConstructor = require("./my-modules/discord.js"...
+ (client.BAN_EVASION_FLAGS[chan] ? client.CFG.BAN_EVASION_CHARACTER : ""); if (Utils.globalCheck(msg, client.CFG.GLOBAL_BANPHRASES)) { for (const phrase of client.CFG.GLOBAL_BANPHRASES) { msg = msg.replace(new RegExp(phrase, "gi"), "[REDACTED]"); } } this._reply("send", Utils.saf...
random_line_split
bot.js
(function () { "use strict"; const fs = require("fs"); const request = require("request"); require("/code/keys/load-keys.js")(); const Utils = require("/code/global-modules/utils.js"); let CytubeConstructor = require("./my-modules/cytube.js")(Utils); const DiscordConstructor = require("./my-modules/discord.js"...
if (command.blacklist && command.blacklist.some(i => i === chan)) { evt.reply("This command cannot be executed in this channel."); console.log("CMD REQUEST FAILED - CHANNEL BLACKLISTED"); } else if (command.whitelist && !command.whitelist.some(i => i === chan)) { evt.reply("This command cannot be executed...
t.reply(":z message too long."); console.log("CMD REQUEST FAILED - MESSAGE TOO LONG", args.join(" ").length); } else
conditional_block
jpt_location.py
import dataclasses import time from typing import Optional, List, Tuple import jpt import numpy as np import pybullet import tf import pycram.designators.location_designator import pycram.task from pycram.costmaps import OccupancyCostmap, plot_grid from pycram.plan_failures import PlanFailure class JPTCostmapLocati...
(self, sample: np.ndarray) -> Location: """ Convert a numpy array sampled from the JPT to a costmap-location :param sample: The drawn sample :return: The usable costmap-location """ sample_dict = {variable.name: value for variable, value in zip(self.model.variables, samp...
sample_to_location
identifier_name
jpt_location.py
import dataclasses import time from typing import Optional, List, Tuple import jpt import numpy as np import pybullet import tf import pycram.designators.location_designator import pycram.task from pycram.costmaps import OccupancyCostmap, plot_grid from pycram.plan_failures import PlanFailure class JPTCostmapLocati...
# load model from path if path: self.model = jpt.trees.JPT.load(path) # initialize member for visualized objects self.visual_ids: List[int] = [] def evidence_from_occupancy_costmap(self) -> List[jpt.variables.LabelAssignment]: """ Create a list of boxe...
self.model = model
conditional_block
jpt_location.py
import dataclasses import time from typing import Optional, List, Tuple import jpt import numpy as np import pybullet import tf import pycram.designators.location_designator import pycram.task from pycram.costmaps import OccupancyCostmap, plot_grid from pycram.plan_failures import PlanFailure class JPTCostmapLocati...
def sample(self, amount: int = 1) -> np.ndarray: """ Sample from the locations that fit the CostMap and are not occupied. :param amount: The amount of samples to draw :return: A numpy array containing the samples drawn from the tree. """ evidence = self.create_evid...
""" Create evidence usable for JPTs where type and status are set if wanted. :param use_success: Rather to set success or not :return: The usable label-assignment """ evidence = dict() evidence["type"] = {self.target.type} if use_success: evidence["...
identifier_body
jpt_location.py
import dataclasses import time from typing import Optional, List, Tuple import jpt
import pycram.designators.location_designator import pycram.task from pycram.costmaps import OccupancyCostmap, plot_grid from pycram.plan_failures import PlanFailure class JPTCostmapLocation(pycram.designators.location_designator.CostmapLocation): """Costmap Locations using Joint Probability Trees (JPTs). JPT...
import numpy as np import pybullet import tf
random_line_split
main.go
package core import ( "context" "crypto/tls" "fmt" genesisUploader "github.com/MinterTeam/explorer-genesis-uploader/core" genesisEnv "github.com/MinterTeam/explorer-genesis-uploader/env" "github.com/MinterTeam/minter-explorer-api/v2/coins" "github.com/MinterTeam/minter-explorer-extender/v2/address" "github.com...
func (ext *Extender) saveTransactions(blockHeight uint64, blockCreatedAt time.Time, transactions []*api_pb.TransactionResponse) { // Save transactions err := ext.transactionService.HandleTransactionsFromBlockResponse(blockHeight, blockCreatedAt, transactions) if err != nil { ext.log.Panic(err) } } func (ext *E...
{ if response.Height == 1 { return } var links []*models.BlockValidator for _, v := range response.Validators { vId, err := ext.validatorRepository.FindIdByPk(helpers.RemovePrefix(v.PublicKey)) if err != nil { ext.log.Error(err) } helpers.HandleError(err) link := models.BlockValidator{ ValidatorID...
identifier_body
main.go
package core import ( "context" "crypto/tls" "fmt" genesisUploader "github.com/MinterTeam/explorer-genesis-uploader/core" genesisEnv "github.com/MinterTeam/explorer-genesis-uploader/env" "github.com/MinterTeam/minter-explorer-api/v2/coins" "github.com/MinterTeam/minter-explorer-extender/v2/address" "github.com...
if result > critical { bigQueryLog, err := os.OpenFile("big_query.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666) if err != nil { eh.log.Error("error opening file: %v", err) } // don't forget to close it defer bigQueryLog.Close() eh.log.SetReportCaller(false) eh.log.SetFormatter(&logrus.JSONFormatter{}...
random_line_split
main.go
package core import ( "context" "crypto/tls" "fmt" genesisUploader "github.com/MinterTeam/explorer-genesis-uploader/core" genesisEnv "github.com/MinterTeam/explorer-genesis-uploader/env" "github.com/MinterTeam/minter-explorer-api/v2/coins" "github.com/MinterTeam/minter-explorer-extender/v2/address" "github.com...
(response *api_pb.BlockResponse) { // Save validators if not exist err := ext.validatorService.HandleBlockResponse(response) if err != nil { ext.log.Panic(err) } // Save block err = ext.blockService.HandleBlockResponse(response) if err != nil { ext.log.Panic(err) } ext.linkBlockValidator(response) //fi...
handleBlockResponse
identifier_name
main.go
package core import ( "context" "crypto/tls" "fmt" genesisUploader "github.com/MinterTeam/explorer-genesis-uploader/core" genesisEnv "github.com/MinterTeam/explorer-genesis-uploader/env" "github.com/MinterTeam/minter-explorer-api/v2/coins" "github.com/MinterTeam/minter-explorer-extender/v2/address" "github.com...
} func (ext *Extender) handleEventResponse(blockHeight uint64, response *api_pb.BlockResponse) { if len(response.Events) > 0 { //Save events err := ext.eventService.HandleEventResponse(blockHeight, response) if err != nil { ext.log.Fatal(err) } } } func (ext *Extender) linkBlockValidator(response *api_p...
{ start := ext.env.TxChunkSize * i end := start + ext.env.TxChunkSize if end > len(response.Transactions) { end = len(response.Transactions) } layout := "2006-01-02T15:04:05Z" blockTime, err := time.Parse(layout, response.Time) if err != nil { ext.log.Panic(err) } ext.saveTransactions(response...
conditional_block
utils.py
import numbers import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms from numpy import asarray import numpy as np from numpy.lib.stride_tricks import as_strided from skimage import feature from skimage.filters import threshold_otsu from sklearn.utils import check_random_stat...
else: s_h, s_w = stride step = (s_h, s_w, n_colors) extracted_patches = _extract_patches(image, patch_shape=(p_h, p_w, n_colors), extraction_step=step) n_patches = _compute_n_patches(i_h, i_w, p_h, p_w, stri...
step = stride s_h = stride s_w = stride
conditional_block
utils.py
import numbers import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms from numpy import asarray import numpy as np from numpy.lib.stride_tricks import as_strided from skimage import feature from skimage.filters import threshold_otsu from sklearn.utils import check_random_stat...
def clean_patches(patches, th=2000): indices = [] for i, patch in enumerate(patches): if patch.shape[-1] == 3: patch = patch / 255 num_features = feature.canny(patch.mean(axis=2), sigma=2).sum() else: num_features = feature.canny(patch, sigma=2).sum() ...
if isinstance(stride, numbers.Number): s_h = stride s_w = stride else: s_h, s_w = stride n_h = (i_h - p_h) // s_h + 1 n_w = (i_w - p_w) // s_w + 1 all_patches = n_h * n_w if max_patches: if (isinstance(max_patches, numbers.Integral) and max_patches <...
identifier_body
utils.py
import numbers import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms from numpy import asarray import numpy as np from numpy.lib.stride_tricks import as_strided from skimage import feature from skimage.filters import threshold_otsu from sklearn.utils import check_random_stat...
patches = extracted_patches patches = patches.reshape(-1, p_h, p_w, n_colors) # remove the color dimension if useless if patches.shape[-1] == 1: patches = patches.reshape((n_patches, p_h, p_w)) # return clean_patches(patches, th) return patches def _compute_n_patches(i_h, i_w, p_...
random_line_split
utils.py
import numbers import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms from numpy import asarray import numpy as np from numpy.lib.stride_tricks import as_strided from skimage import feature from skimage.filters import threshold_otsu from sklearn.utils import check_random_stat...
(Dataset): def __init__(self, dataset, col_transform=None, bin_transform=None): self.dataset = dataset self.col_transform = col_transform self.bin_transform = bin_transform def __getitem__(self, index): x1, y1 = self.dataset[index] if self.bin_transform: x2 ...
BinColorDataset
identifier_name
reaper-rush.rs
#[macro_use] extern crate clap; use rand::prelude::*; use rust_sc2::prelude::*; use std::{cmp::Ordering, collections::HashSet}; #[bot] #[derive(Default)] struct ReaperRushAI { reapers_retreat: HashSet<u64>, last_loop_distributed: u32, } impl Player for ReaperRushAI { fn on_start(&mut self) -> SC2Result<()> { if...
} } if self.counter().all().count(UnitTypeId::Barracks) < 4 && self.can_afford(UnitTypeId::Barracks, false) { if let Some(location) = self.find_placement( UnitTypeId::Barracks, main_base, PlacementOptions { step: 4, ..Default::default() }, ) { if let Some(builder) = self...
builder.build(UnitTypeId::SupplyDepot, location, false); self.subtract_resources(UnitTypeId::SupplyDepot, false); return; }
random_line_split
reaper-rush.rs
#[macro_use] extern crate clap; use rand::prelude::*; use rust_sc2::prelude::*; use std::{cmp::Ordering, collections::HashSet}; #[bot] #[derive(Default)] struct ReaperRushAI { reapers_retreat: HashSet<u64>, last_loop_distributed: u32, } impl Player for ReaperRushAI { fn on_start(&mut self) -> SC2Result<()> { if...
(&mut self) { if self.minerals < 50 || self.supply_left == 0 { return; } if self.supply_workers < 22 && self.can_afford(UnitTypeId::SCV, true) { if let Some(cc) = self .units .my .townhalls .iter() .find(|u| u.is_ready() && u.is_almost_idle()) { cc.train(UnitTypeId::SCV, false); ...
train
identifier_name
reaper-rush.rs
#[macro_use] extern crate clap; use rand::prelude::*; use rust_sc2::prelude::*; use std::{cmp::Ordering, collections::HashSet}; #[bot] #[derive(Default)] struct ReaperRushAI { reapers_retreat: HashSet<u64>, last_loop_distributed: u32, } impl Player for ReaperRushAI { fn on_start(&mut self) -> SC2Result<()> { if...
else { None }; for u in &idle_workers { if let Some(closest) = deficit_geysers.closest(u) { let tag = closest.tag(); deficit_geysers.remove(tag); u.gather(tag, false); } else if let Some(closest) = deficit_minings.closest(u) { u.gather( mineral_fields .closer(11.0, closest) ...
{ let minerals = mineral_fields.filter(|m| bases.iter().any(|base| base.is_closer(11.0, *m))); if minerals.is_empty() { None } else { Some(minerals) } }
conditional_block
reaper-rush.rs
#[macro_use] extern crate clap; use rand::prelude::*; use rust_sc2::prelude::*; use std::{cmp::Ordering, collections::HashSet}; #[bot] #[derive(Default)] struct ReaperRushAI { reapers_retreat: HashSet<u64>, last_loop_distributed: u32, } impl Player for ReaperRushAI { fn on_start(&mut self) -> SC2Result<()> { if...
fn throw_mine(&self, reaper: &Unit, target: &Unit) -> bool { if reaper.has_ability(AbilityId::KD8ChargeKD8Charge) && reaper.in_ability_cast_range(AbilityId::KD8ChargeKD8Charge, target, 0.0) { reaper.command( AbilityId::KD8ChargeKD8Charge, Target::Pos(target.position()), false, ); true }...
{ if self.minerals < 50 || self.supply_left == 0 { return; } if self.supply_workers < 22 && self.can_afford(UnitTypeId::SCV, true) { if let Some(cc) = self .units .my .townhalls .iter() .find(|u| u.is_ready() && u.is_almost_idle()) { cc.train(UnitTypeId::SCV, false); self.sub...
identifier_body
p_test.go
package p import ( "strings" "testing" "github.com/lSimul/php2go/lang" "github.com/lSimul/php2go/p/test" "github.com/z7zmey/php-parser/node" "github.com/z7zmey/php-parser/node/expr" "github.com/z7zmey/php-parser/node/name" "github.com/z7zmey/php-parser/node/stmt" "github.com/z7zmey/php-parser/php7" ) func ...
tests := []struct { source []byte expected string }{ // Sandbox { source: []byte(`<?php function fc() { $a = 1 + 2; } `), expected: `func fc() { a := 1 + 2 }`, }, // examples/04.php { source: []byte(`<?php function fc() { $a = 2 + 3 + 4 * 2; echo $a * $a; } ...
tt.Helper()
random_line_split
p_test.go
package p import ( "strings" "testing" "github.com/lSimul/php2go/lang" "github.com/lSimul/php2go/p/test" "github.com/z7zmey/php-parser/node" "github.com/z7zmey/php-parser/node/expr" "github.com/z7zmey/php-parser/node/name" "github.com/z7zmey/php-parser/node/stmt" "github.com/z7zmey/php-parser/php7" ) func ...
} func unaryOp(t *testing.T) { t.Helper() parent := lang.NewCode(nil) parser := fileParser{parser: &parser{}} for _, n := range []node.Node{ test.Plus(test.String(`"test"`)), test.Plus(test.String(`""`)), } { e := parser.expression(parent, n) if e.Parent() != parent { t.Error("Parent not set.") } ...
{ expr := parser.expression(nil, test.BinaryOp(left, c.op, right)) op, ok := expr.(*lang.BinaryOp) if !ok { t.Fatal("Expected binary operation, something else found.") } if op.Operation != c.op { t.Errorf("'%s' expected, '%s' found.", c.op, op.Operation) } if !op.Type().Equal(c.ret) { t.Errorf("'...
conditional_block
p_test.go
package p import ( "strings" "testing" "github.com/lSimul/php2go/lang" "github.com/lSimul/php2go/p/test" "github.com/z7zmey/php-parser/node" "github.com/z7zmey/php-parser/node/expr" "github.com/z7zmey/php-parser/node/name" "github.com/z7zmey/php-parser/node/stmt" "github.com/z7zmey/php-parser/php7" ) func ...
(tt *testing.T) { tt.Helper() tests := []struct { source []byte expected string }{ // Sandbox { source: []byte(`<?php function fc() { $a = 1 + 2; } `), expected: `func fc() { a := 1 + 2 }`, }, // examples/04.php { source: []byte(`<?php function fc() { $a = 2 + 3 +...
testMain
identifier_name
p_test.go
package p import ( "strings" "testing" "github.com/lSimul/php2go/lang" "github.com/lSimul/php2go/p/test" "github.com/z7zmey/php-parser/node" "github.com/z7zmey/php-parser/node/expr" "github.com/z7zmey/php-parser/node/name" "github.com/z7zmey/php-parser/node/stmt" "github.com/z7zmey/php-parser/php7" ) func ...
{ r := strings.Split(ref, "\n") o := strings.Split(out, "\n") i, j := 0, 0 for i < len(r) && j < len(o) { c := true s1 := strings.TrimLeft(r[i], "\t") if s1 == "" { i++ c = false } s2 := strings.TrimLeft(o[j], "\t") if s2 == "" { j++ c = false } if !c { continue } if s1 != s2 { ...
identifier_body
repo_polling.go
package polling import ( "database/sql" "encoding/json" "errors" "fmt" "math/rand" "regexp" "strings" "sync" "time" "github.com/ovh/cds/engine/api/application" "github.com/ovh/cds/engine/api/cache" "github.com/ovh/cds/engine/api/database" "github.com/ovh/cds/engine/api/pipeline" "github.com/ovh/cds/engi...
var quit chan bool var atLeastOne bool for i := range pollers { p := &pollers[i] b, _ := repositoriesmanager.CheckApplicationIsAttached(db, p.Name, w.ProjectKey, p.Application.Name) if !b || p.Application.RepositoriesManager == nil || p.Application.RepositoryFullname == "" { continue } if !p.Applicatio...
if err != nil { return false, nil, err }
random_line_split
repo_polling.go
package polling import ( "database/sql" "encoding/json" "errors" "fmt" "math/rand" "regexp" "strings" "sync" "time" "github.com/ovh/cds/engine/api/application" "github.com/ovh/cds/engine/api/cache" "github.com/ovh/cds/engine/api/database" "github.com/ovh/cds/engine/api/pipeline" "github.com/ovh/cds/engi...
} //LoadExecutions returns all executions in database func LoadExecutions(db database.QueryExecuter) ([]WorkerExecution, error) { query := ` select poller_execution.id, application.name, pipeline.name, poller_execution.execution_date, poller_execution.status, poller_execution.data from poller_execution, applicat...
{ db := database.DB() if db == nil { time.Sleep(30 * time.Minute) continue } execs, _ := LoadExecutions(db) for i := range execs { tenDaysAGo := time.Now().Add(-10 * 24 * time.Hour) if execs[i].Execution.Before(tenDaysAGo) { deleteExecution(db, &execs[i]) } } time.Sleep(1 * time.Hour)...
conditional_block
repo_polling.go
package polling import ( "database/sql" "encoding/json" "errors" "fmt" "math/rand" "regexp" "strings" "sync" "time" "github.com/ovh/cds/engine/api/application" "github.com/ovh/cds/engine/api/cache" "github.com/ovh/cds/engine/api/database" "github.com/ovh/cds/engine/api/pipeline" "github.com/ovh/cds/engi...
func deleteExecution(db database.QueryExecuter, e *WorkerExecution) error { query := ` delete from poller_execution where id = $1 ` if _, err := db.Exec(query, e.ID); err != nil { return err } return nil } //ExecutionCleaner is globale goroutine to remove all old polling traces func ExecutionCleaner() { f...
{ query := ` update poller_execution set status = $2, data = $3 where id = $1 ` data, _ := json.Marshal(e.Events) if _, err := db.Exec(query, e.ID, e.Status, data); err != nil { return err } return nil }
identifier_body
repo_polling.go
package polling import ( "database/sql" "encoding/json" "errors" "fmt" "math/rand" "regexp" "strings" "sync" "time" "github.com/ovh/cds/engine/api/application" "github.com/ovh/cds/engine/api/cache" "github.com/ovh/cds/engine/api/database" "github.com/ovh/cds/engine/api/pipeline" "github.com/ovh/cds/engi...
(tx *sql.Tx, rm *sdk.RepositoriesManager, poller *sdk.RepositoryPoller, e sdk.VCSPushEvent, projectData *sdk.Project) (bool, error) { client, err := repositoriesmanager.AuthorizedClient(tx, projectData.Key, rm.Name) if err != nil { return false, err } // Create pipeline args var args []sdk.Parameter args = appe...
TriggerPipeline
identifier_name
keycap.js
import Vue from 'vue/dist/vue.js' import KeyCustomizer from './components/KeyCustomizer.vue' import KeySelector from './components/KeySelector.vue' import NavBar from './components/NavBar.vue' import KeycapProductInfo from './components/KeycapProductInfo' Vue.config.productionTip = false var customKey = new Vue({ e...
var selectKey = function (e) { var target = e.target; if (target.className){ if (target.classList.contains('key-face')) { customKey.changeKey(target.getAttribute('name')) } } e.stopPropagation() } document.body.addEventListener('click', selectKey, false); document.body.addEventListener('touch', s...
{ var surface = document.querySelector('.restrictRect').getBoundingClientRect() interact('.moveableText') .draggable({ onmove: window.dragMoveListener, snap: { targets: [{}], range:20, relativePoints: [ //{ x: 0 , y: 0 } // snap relative to the element's top...
identifier_body
keycap.js
import Vue from 'vue/dist/vue.js' import KeyCustomizer from './components/KeyCustomizer.vue' import KeySelector from './components/KeySelector.vue' import NavBar from './components/NavBar.vue' import KeycapProductInfo from './components/KeycapProductInfo' Vue.config.productionTip = false var customKey = new Vue({ e...
() { return {transform: 'translate(' + this.surfaces[this.currentView].img.x + 'px,' + this.surfaces[this.currentView].img.y + 'px)'} } }, mounted: function () { var self = this; fetch('https://us-central1-hotsguide-188315.cloudfunctions.net/function-1?board=keyboard-104&sides=true'...
transformImg
identifier_name
keycap.js
import Vue from 'vue/dist/vue.js' import KeyCustomizer from './components/KeyCustomizer.vue' import KeySelector from './components/KeySelector.vue' import NavBar from './components/NavBar.vue' import KeycapProductInfo from './components/KeycapProductInfo' Vue.config.productionTip = false var customKey = new Vue({ e...
canvg('canvas', svg_xml, {useCORS: true}); var context = canvas.getContext('2d'); console.log(img.width) console.log(img.height) context.drawImage(img, self.surfaces[thisSurface].img.x, self.surfaces[thisSurface].img.y, self.surfaces[thi...
var thisSurface = surface img.onload = function () { var svg_xml = (new XMLSerializer()).serializeToString(newSvg);
random_line_split
keycap.js
import Vue from 'vue/dist/vue.js' import KeyCustomizer from './components/KeyCustomizer.vue' import KeySelector from './components/KeySelector.vue' import NavBar from './components/NavBar.vue' import KeycapProductInfo from './components/KeycapProductInfo' Vue.config.productionTip = false var customKey = new Vue({ e...
else { itemsSpan = document.createElement('span') itemsSpan.innerHTML = ' ('+cartItems.length+')' itemsSpan.setAttribute('style','color:blue;') cartLink.appendChild(itemsSpan) } }) }, setColor: function(color) { document.querySelector('.key...
{ itemsSpan.innerHTML = ' ('+cartItems.length+')' }
conditional_block
replicator.go
// Copyright (c) 2016-2018 iQIYI.com. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required b...
func (r *Replicator) replicateLocal( policy int, device *ring.Device, partition string, nodes *NodeChain) { rehashed, localHash := r.getLocalHash(policy, device.Device, partition, nil) r.stat.rehashed += rehashed attempts := int(r.rings[policy].ReplicaCount()) - 1 for node := nodes.Next(); node != nil && attemp...
{ url := fmt.Sprintf("http://%s:%d/%s/%s", node.Ip, node.Port, node.Device, partition) if len(suffixes) > 0 { url = fmt.Sprintf("%s/%s", url, strings.Join(suffixes, "-")) } req, err := http.NewRequest(common.REPLICATE, url, nil) if err != nil { r.logger.Error("unable to create diff request", zap.String(...
identifier_body
replicator.go
// Copyright (c) 2016-2018 iQIYI.com. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required b...
( policy int, device *ring.Device, partition string, nodes *NodeChain) { rehashed, localHash := r.getLocalHash(policy, device.Device, partition, nil) r.stat.rehashed += rehashed attempts := int(r.rings[policy].ReplicaCount()) - 1 for node := nodes.Next(); node != nil && attempts > 0; node = nodes.Next() { attem...
replicateLocal
identifier_name
replicator.go
// Copyright (c) 2016-2018 iQIYI.com. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required b...
msg := &SyncMsg{ LocalDevice: device.Device, Host: node.Ip, Port: int32(node.Port), Device: node.Device, Policy: uint32(policy), Partition: partition, Suffixes: suffixes, } ctx, cancel := context.WithCancel(context.Background()) defer cancel() reply, err := r...
if remoteHash[s] != h { suffixes = append(suffixes, s) } }
random_line_split
replicator.go
// Copyright (c) 2016-2018 iQIYI.com. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required b...
} return hashes, nil } func (r *Replicator) replicateLocal( policy int, device *ring.Device, partition string, nodes *NodeChain) { rehashed, localHash := r.getLocalHash(policy, device.Device, partition, nil) r.stat.rehashed += rehashed attempts := int(r.rings[policy].ReplicaCount()) - 1 for node := nodes.Nex...
{ hashes[suff.(string)] = "" }
conditional_block
fleet.go
package cbcluster import ( "bytes" "encoding/json" "fmt" "html/template" "io/ioutil" "log" "net/http" "path" "path/filepath" "strings" "time" "github.com/coreos/fleet/schema" "github.com/coreos/go-systemd/unit" "github.com/tleyden/go-etcd/etcd" ) const ( UNIT_NAME_NODE = "couchbase_node" UNIT_NAM...
(allUnits bool) error { ttlSeconds := uint64(300) _, err := c.etcdClient.Set(KEY_REMOVE_REBALANCE_DISABLED, "true", ttlSeconds) if err != nil { return err } // call ManipulateUnits with a function that will stop them unitDestroyer := func(unit *schema.Unit) error { // stop the unit by updating desiredState...
DestroyUnits
identifier_name
fleet.go
package cbcluster import ( "bytes" "encoding/json" "fmt" "html/template" "io/ioutil" "log" "net/http" "path" "path/filepath" "strings" "time" "github.com/coreos/fleet/schema" "github.com/coreos/go-systemd/unit" "github.com/tleyden/go-etcd/etcd" ) const ( UNIT_NAME_NODE = "couchbase_node" UNIT_NAM...
func (c CouchbaseFleet) GenerateUnits(outputDir string) error { // generate node unit nodeFleetUnit, err := c.generateNodeFleetUnitFile() if err != nil { return err } filename := fmt.Sprintf("%v@.service", UNIT_NAME_NODE) path := filepath.Join(outputDir, filename) if err := ioutil.WriteFile(path, []byte(n...
{ stringContainsAny := func(s string, filters []string) bool { for _, filter := range filters { if strings.Contains(s, filter) { return true } } return false } for _, unit := range units { if stringContainsAny(unit.Name, filters) { filteredUnits = append(filteredUnits, unit) } } return f...
identifier_body
fleet.go
package cbcluster import ( "bytes" "encoding/json" "fmt" "html/template" "io/ioutil" "log" "net/http" "path" "path/filepath" "strings" "time" "github.com/coreos/fleet/schema" "github.com/coreos/go-systemd/unit" "github.com/tleyden/go-etcd/etcd" ) const ( UNIT_NAME_NODE = "couchbase_node" UNIT_NAM...
// dirty hack to solve problem: the cluster might have // 2 nodes which just finished rebalancing, and a third node // that joins and triggers another rebalance. thus, it will briefly // go into "no rebalances happening" state, followed by a rebalance. // if we see the "no rebalances happening state", we'll be ...
{ return err }
conditional_block
fleet.go
package cbcluster import ( "bytes" "encoding/json" "fmt" "html/template" "io/ioutil" "log" "net/http" "path" "path/filepath" "strings" "time" "github.com/coreos/fleet/schema" "github.com/coreos/go-systemd/unit" "github.com/tleyden/go-etcd/etcd" ) const ( UNIT_NAME_NODE = "couchbase_node" UNIT_NAM...
// generate sidekick unit sidekickFleetUnit, err := c.generateSidekickFleetUnitFile("%i") if err != nil { return err } filename = fmt.Sprintf("%v@.service", UNIT_NAME_SIDEKICK) path = filepath.Join(outputDir, filename) if err := ioutil.WriteFile(path, []byte(sidekickFleetUnit), 0644); err != nil { return e...
random_line_split
aplicacao.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ##################################################### # Camada Física da Computação # Henry Rocha # 11/08/2019 # Exemplo de uso do ArgParse e do TkInter. ##################################################### import sys import time import argparse from enlace import * fro...
while True: # Faz a recepção dos dados print("\n[LOG] Recebendo dados...") keywordRecognized = False receiveBuffer = bytearray() # Espera até receber uma keyword. while not keywordRecognized: rxBuffer, nRx = com.getData(1) re...
com.enable() # LOG print("[LOG] Comunicação inicializada.") print("[LOG] Porta: {}".format(com.fisica.name))
random_line_split
aplicacao.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ##################################################### # Camada Física da Computação # Henry Rocha # 11/08/2019 # Exemplo de uso do ArgParse e do TkInter. ##################################################### import sys import time import argparse from enlace import * fro...
def __init__(self, serialName, debug=False): self.com = enlace(serialName) self.com.enable() self.debug = debug self.fileName = None self.results = [] if debug: print("[LOG] Comunicação inicializada.") print("[LOG] Porta: {}".format(self.com....
ent():
identifier_name
aplicacao.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ##################################################### # Camada Física da Computação # Henry Rocha # 11/08/2019 # Exemplo de uso do ArgParse e do TkInter. ##################################################### import sys import time import argparse from enlace import * fro...
enlace... variável COM possui todos os métodos e propriedades do enlace, que funciona em threading com = enlace("/dev/ttyACM1") # Repare que o metodo construtor recebe um string (nome) # Ativa comunicacão com.enable() # LOG print("[LOG] Comunicação inicializada.") print("[LOG] Porta: {}".fo...
ame) # Repare que o metodo construtor recebe um string (nome) # Ativa comunicacão com.enable() # LOG print("[LOG] Comunicação inicializada.") print("[LOG] Porta: {}".format(com.fisica.name)) shouldClose = False while not shouldClose: # Verifica se o arquivo a ser transferido foi pa...
identifier_body
aplicacao.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ##################################################### # Camada Física da Computação # Henry Rocha # 11/08/2019 # Exemplo de uso do ArgParse e do TkInter. ##################################################### import sys import time import argparse from enlace import * fro...
ualiza dados da transmissão. txSize = com.tx.getStatus() print("[LOG] Transmitido...............{} bytes.".format(int(txSize))) # Esperando pela resposta. Sabemos que ela deve ser o tamanho da arquivo. print("[LOG] Esperando pela resposta do servidor com o tamanho do arquivo.") ...
# At
conditional_block
lib.rs
//! A slab allocator implementation for small objects //! (< architecture page size). //! //! The organization is as follows (top-down): //! //! * A `ZoneAllocator` manages many `SCAllocator` and can //! satisfy requests for different allocation sizes. //! * A `SCAllocator` allocates objects of exactly one size. /...
/// Check if the current `idx` is allocated. /// /// # Notes /// In case `idx` is 3 and allocation size of slab is /// 8. The corresponding object would start at &data + 3 * 8. fn is_allocated(&mut self, idx: usize) -> bool { let base_idx = idx / 64; let bit_idx = idx % 64; ...
{ unsafe { for (base_idx, b) in self.bitfield.iter().enumerate() { let bitval = *b; if bitval == u64::max_value() { continue; } else { let negated = !bitval; let first_free = negated.trailing_...
identifier_body
lib.rs
//! A slab allocator implementation for small objects //! (< architecture page size). //! //! The organization is as follows (top-down): //! //! * A `ZoneAllocator` manages many `SCAllocator` and can //! satisfy requests for different allocation sizes. //! * A `SCAllocator` allocates objects of exactly one size. /...
(current_size: usize) -> Option<usize> { match current_size { 0...8 => Some(8), 9...16 => Some(16), 17...32 => Some(32), 33...64 => Some(64), 65...128 => Some(128), 129...256 => Some(256), 257...512 => Some(512), 513...
get_max_size
identifier_name
lib.rs
//! A slab allocator implementation for small objects //! (< architecture page size). //! //! The organization is as follows (top-down): //! //! * A `ZoneAllocator` manages many `SCAllocator` and can //! satisfy requests for different allocation sizes. //! * A `SCAllocator` allocates objects of exactly one size. /...
} ptr::null_mut() } /// Allocates a block of memory with respect to `alignment`. /// /// In case of failure will try to grow the slab allocator by requesting /// additional pages and re-try the allocation once more before we give up. pub fn allocate<'b>(&'b mut self, layout: L...
{ continue; }
conditional_block
lib.rs
//! A slab allocator implementation for small objects //! (< architecture page size). //! //! The organization is as follows (top-down): //! //! * A `ZoneAllocator` manages many `SCAllocator` and can //! satisfy requests for different allocation sizes. //! * A `SCAllocator` allocates objects of exactly one size. /...
SCAllocator::new(32, pager), SCAllocator::new(64, pager), SCAllocator::new(128, pager), SCAllocator::new(256, pager), SCAllocator::new(512, pager), SCAllocator::new(1024, pager), SCAllocator::new(2048, pager)...
ZoneAllocator { pager: pager, slabs: [ SCAllocator::new(8, pager), SCAllocator::new(16, pager),
random_line_split
ip6.py
# $Id: ip6.py 87 2013-03-05 19:41:04Z andrewflnr@gmail.com $ # -*- coding: utf-8 -*- """Internet Protocol, version 6.""" from __future__ import print_function from __future__ import absolute_import from . import dpkt from . import ip from .compat import compat_ord class IP6(dpkt.Packet): """Internet Protocol, ve...
self.length = (self.len + 1) * 8 options = [] index = 0 while index < self.length - 2: opt_type = compat_ord(self.data[index]) # PAD1 option if opt_type == 0: index += 1 continue opt_length = compat_ord(s...
('len', 'B', 0) # option data length in 8 octect units (ignoring first 8 octets) so, len 0 == 64bit header ) def unpack(self, buf): dpkt.Packet.unpack(self, buf)
random_line_split
ip6.py
# $Id: ip6.py 87 2013-03-05 19:41:04Z andrewflnr@gmail.com $ # -*- coding: utf-8 -*- """Internet Protocol, version 6.""" from __future__ import print_function from __future__ import absolute_import from . import dpkt from . import ip from .compat import compat_ord class IP6(dpkt.Packet): """Internet Protocol, ve...
next_ext_hdr = self.nxt while next_ext_hdr in ext_hdrs: ext = ext_hdrs_cls[next_ext_hdr](buf) self.extension_hdrs[next_ext_hdr] = ext self.all_extension_headers.append(ext) buf = buf[ext.length:] next_ext_hdr = getattr(ext, 'nxt', None) ...
buf = self.data
conditional_block
ip6.py
# $Id: ip6.py 87 2013-03-05 19:41:04Z andrewflnr@gmail.com $ # -*- coding: utf-8 -*- """Internet Protocol, version 6.""" from __future__ import print_function from __future__ import absolute_import from . import dpkt from . import ip from .compat import compat_ord class IP6(dpkt.Packet): """Internet Protocol, ve...
def test_ip6_extension_headers(): p = (b'\x60\x00\x00\x00\x00\x3c\x2b\x40\x20\x48\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' b'\xde\xca\x20\x47\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xca\xfe\x06\x04\x00\x02' b'\x00\x00\x00\x00\x20\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x...
s = (b'\x00\x00\x01\x00\x00\x00\x00\x44\xe2\x4f\x9e\x68\xf3\xcd\xb1\x5f\x61\x65\x42\x8b\x78\x0b' b'\x4a\xfd\x13\xf0\x15\x98\xf5\x55\x16\xa8\x12\xb3\xb8\x4d\xbc\x16\xb2\x14\xbe\x3d\xf9\x96' b'\xd4\xa0\x39\x1f\x85\x74\x25\x81\x83\xa6\x0d\x99\xb6\xba\xa3\xcc\xb6\xe0\x9a\x78\xee\xf2' b'\xaf\x9a')...
identifier_body
ip6.py
# $Id: ip6.py 87 2013-03-05 19:41:04Z andrewflnr@gmail.com $ # -*- coding: utf-8 -*- """Internet Protocol, version 6.""" from __future__ import print_function from __future__ import absolute_import from . import dpkt from . import ip from .compat import compat_ord class IP6(dpkt.Packet): """Internet Protocol, ve...
(self): return (self._v_fc_flow >> 20) & 0xff @fc.setter def fc(self, v): self._v_fc_flow = (self._v_fc_flow & ~0xff00000) | (v << 20) @property def flow(self): return self._v_fc_flow & 0xfffff @flow.setter def flow(self, v): self._v_fc_flow = (self._v_fc_flow ...
fc
identifier_name
schema.go
// Copyright (c) 2017-2018 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicabl...
tableSchema.Lock() m.RUnlock() enumDict, columnExist := tableSchema.EnumDicts[columnName] if !columnExist { tableSchema.Unlock() return } enumDict.Dict[newEnumCase] = len(enumDict.ReverseDict) enumDict.ReverseDict = append(enumDict.ReverseDict, newEnumCase) tableSchema.EnumDicts[columnName] = enumDict tab...
return }
random_line_split
schema.go
// Copyright (c) 2017-2018 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicabl...
tableSchema.createEnumDict(column.Name, enumCases) newEnumColumns = append(newEnumColumns, column.Name) } } var oldPreloadingDays int newPreloadingDays := column.Config.PreloadingDays // preloading will be triggered if // 1. this is a new column and PreloadingDays > 0 // 2. this is a ol...
{ enumCases = append(enumCases, *column.DefaultValue) // default value is already appended, start watching from 1 startEnumID = 1 }
conditional_block
schema.go
// Copyright (c) 2017-2018 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicabl...
(table *metaCom.Table) *TableSchema { tableSchema := &TableSchema{ Schema: *table, ColumnIDs: make(map[string]int), EnumDicts: make(map[string]EnumDict), ValueTypeByColumn: make([]memCom.DataType, len(table.Columns)), PrimaryKeyColumnTypes: make([]memCom.DataType, l...
NewTableSchema
identifier_name
schema.go
// Copyright (c) 2017-2018 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicabl...
// GetArchivingSortColumns makes a copy of the Schema.ArchivingSortColumns so // callers don't have to hold a read lock to access it. func (t *TableSchema) GetArchivingSortColumns() []int { t.RLock() defer t.RUnlock() return t.Schema.ArchivingSortColumns } // FetchSchema fetches schema from metaStore and updates ...
{ nonNilDefaultByColumn := make([]bool, len(t.Schema.Columns)) for columnID, column := range t.Schema.Columns { nonNilDefaultByColumn[columnID] = column.DefaultValue != nil } return nonNilDefaultByColumn }
identifier_body
util.py
# Copyright 2018 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
# Depth evaluation utils # Mostly based on the code written by Clement Godard: # https://github.com/mrharicot/monodepth/blob/master/utils/evaluation_utils.py def compute_errors(gt, pred): thresh = np.maximum((gt / pred), (pred / gt)) a1 = (thresh < 1.25).mean() a2 = (thresh < 1.25 ** 2).mean() a3 =...
"""Pack depth predictions as a single .npy file""" test_images = read_text_lines(test_file) save_name = 'pred_depth.npy' output_file = os.path.join(pred_dir, save_name) img_height = 128 img_width = 416 all_pred = np.zeros((len(test_images), img_height, img_width)) for i, img_path in enum...
identifier_body
util.py
# Copyright 2018 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
(path): # taken from https://github.com/hunse/kitti float_chars = set("0123456789.e+- ") data = {} with open(path, 'r') as f: for line in f.readlines(): key, value = line.split(':', 1) value = value.strip() data[key] = value if float_chars.issupers...
read_calib_file
identifier_name
util.py
# Copyright 2018 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
else: return 'Empty list.' elif isinstance(obj, tuple): if obj: return 'Tuple of %d... %s' % (len(obj), info(obj[0])) else: return 'Empty tuple.' else: if is_a_numpy_array(obj): return 'Array with shape: %s, dtype: %s' % (obj.shape...
return 'List of %d... %s' % (len(obj), info(obj[0]))
conditional_block
util.py
# Copyright 2018 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
gt_files = [] gt_calib = [] im_sizes = [] im_files = [] cams = [] num_probs = 0 for filename in files: filename = filename.split()[0] splits = filename.split('/') # camera_id = filename[-1] # 2 is left, 3 is right date = splits[0] im_id = spl...
def read_file_data(files, data_root):
random_line_split
gogo_fast_api.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: gogo_fast_api.proto package gogoapi import ( fmt "fmt" proto "github.com/gogo/protobuf/proto" types "github.com/gogo/protobuf/types" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fm...
func (m *Http) GetFullyDecodeReservedExpansion() bool { if m != nil { return m.FullyDecodeReservedExpansion } return false } func (m *Http) GetAnyData() *types.Any { if m != nil { return m.AnyData } return nil } // HttpRule . type HttpRule struct { Selector string `protobuf:"bytes,1,opt,name=selector,pro...
{ if m != nil { return m.Rules } return nil }
identifier_body
gogo_fast_api.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: gogo_fast_api.proto package gogoapi import ( fmt "fmt" proto "github.com/gogo/protobuf/proto" types "github.com/gogo/protobuf/types" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fm...
return nil } func (m *Http) GetFullyDecodeReservedExpansion() bool { if m != nil { return m.FullyDecodeReservedExpansion } return false } func (m *Http) GetAnyData() *types.Any { if m != nil { return m.AnyData } return nil } // HttpRule . type HttpRule struct { Selector string `protobuf:"bytes,1,opt,nam...
{ return m.Rules }
conditional_block
gogo_fast_api.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: gogo_fast_api.proto package gogoapi import ( fmt "fmt" proto "github.com/gogo/protobuf/proto" types "github.com/gogo/protobuf/types" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fm...
func (m *HttpRule) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_HttpRule.Marshal(b, m, deterministic) } func (m *HttpRule) XXX_Merge(src proto.Message) { xxx_messageInfo_HttpRule.Merge(m, src) } func (m *HttpRule) XXX_Size() int { return xxx_messageInfo_HttpRule.Size(m) } func (...
return xxx_messageInfo_HttpRule.Unmarshal(m, b) }
random_line_split
gogo_fast_api.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: gogo_fast_api.proto package gogoapi import ( fmt "fmt" proto "github.com/gogo/protobuf/proto" types "github.com/gogo/protobuf/types" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fm...
() string { if m != nil { return m.Selector } return "" } func (m *HttpRule) GetGet() string { if x, ok := m.GetPattern().(*HttpRule_Get); ok { return x.Get } return "" } func (m *HttpRule) GetPut() string { if x, ok := m.GetPattern().(*HttpRule_Put); ok { return x.Put } return "" } func (m *HttpRule)...
GetSelector
identifier_name
app.js
/** * Created by yj on 16/4/29. */ /** * 最小堆 */ class MinHeap{ constructor(cmp){ this.cmp = cmp; this.queue = [] } push(val){ this.queue.push(val); } peek(){ if(this.empty()){ throw new Error("Can't peek an empty heap"); } return this....
(let i = 0; i < rows; i++) { html += '<tr>'; for (let j = 0; j < cols; j++) { html += '<td class="map-box" data-type="empty">'; } html += '</tr>'; } this.rows = rows; this.cols = cols; this.$el.innerHTML = html; this...
for
identifier_name
app.js
/** * Created by yj on 16/4/29. */ /** * 最小堆 */ class MinHeap{ constructor(cmp){ this.cmp = cmp; this.queue = [] } push(val){ this.queue.push(val); } peek(){ if(this.empty()){ throw new Error("Can't peek an empty heap"); } return this....
this.$el.style.top = y * 20 + 'px'; } getPos() { return {x: this.x, y: this.y}; } } /** * 玩家类 */ class Player extends Character{ constructor(selector) { super(selector) } /** * 异步移动,实现动画效果 * @param pos */ goto(pos) { this.x = pos.x; t...
this.$el.style.left = x * 20 + 'px';
conditional_block
app.js
/** * Created by yj on 16/4/29. */ /** * 最小堆 */ class MinHeap{ constructor(cmp){ this.cmp = cmp; this.queue = [] } push(val){ this.queue.push(val); } peek(){ if(this.empty()){ throw new Error("Can't peek an empty heap"); } return this....
run_async(handler, args) { let promise = new Promise((resolve, reject)=> { this.queue.push({ handler, args, callback: function (err, data) { if (err) { reject(err); } else { resolv...
[next]) .catch(err =>{ console.error(err) }) } let target = this.target.getPos() if(dst.x == target.x && dst.y == target.y) { this.run_async(function(){ this.fire('gameover'); // 游戏结束加载下一关卡 }); } ...
identifier_body
app.js
/** * Created by yj on 16/4/29. */ /** * 最小堆 */ class MinHeap{ constructor(cmp){ this.cmp = cmp; this.queue = [] } push(val){ this.queue.push(val); } peek(){ if(this.empty()){ throw new Error("Can't peek an empty heap"); } return this....
throw new Error('map is full'); } Utils.shuffle(positions); let player = positions[0]; let target = positions[1]; this.player.setPos(player); this.target.setPos(target); } setEnemy(){ } /** * 随机的修建障碍物 //todo 建筑迷宫算法 */ randBuild()...
} } let len = positions.length; if (len < 2) {
random_line_split
parse_tweet_data.py
# ______________________________________________________________________________________________________________________ # this code is **************************************(U) UNCLASSIFIED*************************************************** # ____________________________________________________________________________...
df['stripped_tweet'] = edit_tweets df['tweet_length'] = df['tweet_text'].str.len() df['include_topic_model'] = include df['stripped_tweet_length'] = df['include_topic_model'].str.len() sub_df = df.loc[df['include_topic_model'] == '1'] outfile = path_split[1] + '_' + path_split[3] + '_sorted_...
include.append('0')
conditional_block
parse_tweet_data.py
# ______________________________________________________________________________________________________________________ # this code is **************************************(U) UNCLASSIFIED*************************************************** # ____________________________________________________________________________...
(df, num=30): '''Takes an input data frame and creates inventories for that data frame, sorted by date. First automatically calls the sort function to sort the data frame by the default (date). Inputs: Pandas data frame imported from *.csv or *.pkl file Number of inventories to split into. ...
split_df
identifier_name
parse_tweet_data.py
# ______________________________________________________________________________________________________________________ # this code is **************************************(U) UNCLASSIFIED*************************************************** # ____________________________________________________________________________...
outfile = path_split[1] + '_' + path_split[3] + '_sorted_strip_' + lang + '_' + today + '.pkl' # save new data frame under *.pkl file ext_path = os.path.join(path, '1_DataFrames') sub_df.to_pickle(os.path.join(ext_path, outfile)) return sub_df def extract_content(df, label='All_Languages'): '...
df['stripped_tweet_length'] = df['include_topic_model'].str.len() sub_df = df.loc[df['include_topic_model'] == '1']
random_line_split
parse_tweet_data.py
# ______________________________________________________________________________________________________________________ # this code is **************************************(U) UNCLASSIFIED*************************************************** # ____________________________________________________________________________...
def main(): print('Start time: ' + str(datetime.now())) infile = 'Twitter_Russia_1906_sorted_strip_en_200929.pkl' inpath = os.path.join(path, '1_DataFrames') infilepath = os.path.join(inpath, infile) stripped_en = pd.read_pickle(infilepath) print(stripped_en.head()['unique_id_ida']) # ...
'''Takes an input data frame and generates a histogram of number of tweets binned by month. Inputs: Pandas data frame imported from *.csv or *.pkl file Input parameter called "increment", which determined by what time interval the tweets are organized Outputs: Histogram ''' date_bounds = p...
identifier_body
09_XGBC_img.py
# -*- coding: utf-8 -*- """ Created on Sun Jul 28 19:17:34 2019 @author: Logan Rowe """ import numpy as np import os import sys import pandas as pd from pandas.plotting import scatter_matrix from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import StandardScaler from sklearn.pipeline imp...
# ============================================================================= # Run again with more estimators and early stopping to check for over fitting # ============================================================================= params['n_estimators']=100 clf=xgboost.XGBClassifier(**params) eval_set=[(...
X=dp.numpy_to_pd(X_raw,column_names) # ============================================================================= # SPLIT DATA INTO TEST AND TRAIN BOTH BALANCED # WITH RESPECT TO (NON)BOWTIES # ============================================================================= split=S...
conditional_block
09_XGBC_img.py
# -*- coding: utf-8 -*- """ Created on Sun Jul 28 19:17:34 2019 @author: Logan Rowe """ import numpy as np import os import sys import pandas as pd from pandas.plotting import scatter_matrix from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import StandardScaler from sklearn.pipeline imp...
seeking=True if seeking: X=dp.numpy_to_pd(X_raw,column_names) # ============================================================================= # SPLIT DATA INTO TEST AND TRAIN BOTH BALANCED # WITH RESPECT TO (NON)BOWTIES # ==============================================================...
column_names=c1+c2+c3+c4
random_line_split
data_tensorboard.py
import tensorflow as tf from tensorflow import keras import numpy as np import os import cv2 from tensorflow.keras.preprocessing.image import ImageDataGenerator """ crop_top takes as an input img which is an array of shape (x, y, 3) and percentage of picture to crop """ def crop_top(img, percent=0.15): offset =...
return batch_x, batch_y, weights def __len__(self): return int(np.ceil(len(self.datasets[0]) / float(self.batch_size))) # returns the numer of batches that we will have def on_epoch_end(self): 'Updates indexes after each epoch' if self.shuffle == True: for v in se...
self.on_epoch_end() # schuffle traing set self.n = 0 # set to zero
conditional_block
data_tensorboard.py
import tensorflow as tf from tensorflow import keras import numpy as np import os import cv2 from tensorflow.keras.preprocessing.image import ImageDataGenerator """ crop_top takes as an input img which is an array of shape (x, y, 3) and percentage of picture to crop """ def
(img, percent=0.15): offset = int(img.shape[0] * percent) #cut the top portion of image return img[offset:] # return image """ central_crop takes as an input img which is an array of shape (x, y, 3) """ def central_crop(img): size = min(img.shape[0], img.shape[1]) # min of x and y offset_h = int((img.s...
crop_top
identifier_name
data_tensorboard.py
import tensorflow as tf from tensorflow import keras import numpy as np import os import cv2 from tensorflow.keras.preprocessing.image import ImageDataGenerator """ crop_top takes as an input img which is an array of shape (x, y, 3) and percentage of picture to crop """ def crop_top(img, percent=0.15): offset =...
""" _process_csv_file take as an input a file in our case these are train_split.txt and test_split.txt (names may differ) """ def _process_csv_file(file): with open(file, 'r') as fr: # open file files = fr.readlines() # read lines return files class BalanceCovidDataset(keras.utils.Sequence): 'G...
img = random_ratio_resize(img) #defina above img = _augmentation_transform.random_transform(img) # Applies a random transformation to an image. return img
identifier_body