file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
QTofflineTemplate.py
self.mainWindow = QtGui.QMainWindow() self.mainWindow.setWindowTitle('pyqtgraph example: PlotWidget') self.mainWindow.resize(720,640) self.GuiWiget = QtGui.QWidget() self.mainWindow.setCentralWidget(self.GuiWiget) layout = QtGui.QVBoxLayout() secondLayout = QtGui.QHBoxLayout() thirdLayout = QtGui.QHBoxL...
''' construct GUI ''' self.numOfDataToPlot = 500 #nuber of point of x self.ScalerNum = 2 # every self.ScalerNum we sample once - not used self.numofPlotWidget=3 self.plotNum = 3 # how many line to plot in a plot widget self.plotWidgetList = [] self.penStyleList= [[(0,0,200),(200,200,100),(195,46,21...
identifier_body
QTofflineTemplate.py
return np.sum(np.abs(A-B)) class MyRealTimePlot(): def __init__(self,dataSource = None,nameList=['Plot1','Plot2','Plot3','Plot4','Plot5','Plot6']): ''' construct GUI ''' self.numOfDataToPlot = 500 #nuber of point of x self.ScalerNum = 2 # every self.ScalerNum we sample once - not used self.numofPl...
def absDist(A,B):
random_line_split
search.py
game import Directions from pacman import Actions as pacmanActions from pacman import PacmanRules as pacmanrules s = Directions.SOUTH w = Directions.WEST n = Directions.NORTH e = Directions.EAST """ My OWN Class for Analyzing the Consistency of Heuristic used in A* Method """ class Analyzer : """ This clas...
(self, actions): """ actions: A list of actions to take This method returns the total cost of a particular sequence of actions. The sequence must be composed of legal moves. """ util.raiseNotDefined() def tinyMazeSearch(problem): """ Returns a sequence of move...
getCostOfActions
identifier_name
search.py
""" foodCoordinates = [] hasGatheredNeededData = False foodGridMap = None def __init__(self , problem , actions ): self.problem = problem self.startState = problem.getStartState() self.actions = actions self.coordinates = [] self.states = [] self.path ...
return actions else: newFringeItem = (startState , actions , costs) fringe.push(newFringeItem,costs)
random_line_split
search.py
from pacman import Actions as pacmanActions from pacman import PacmanRules as pacmanrules s = Directions.SOUTH w = Directions.WEST n = Directions.NORTH e = Directions.EAST """ My OWN Class for Analyzing the Consistency of Heuristic used in A* Method """ class Analyzer : """ This class is implemented to che...
state , action , stateCost = node if( ( state in visitedNodes) == False ) : newNode = state , actions + [action] , cost + stateCost priority = cost + stateCost fringe.push( newNode , priority )
conditional_block
search.py
game import Directions from pacman import Actions as pacmanActions from pacman import PacmanRules as pacmanrules s = Directions.SOUTH w = Directions.WEST n = Directions.NORTH e = Directions.EAST """ My OWN Class for Analyzing the Consistency of Heuristic used in A* Method """ class Analyzer : """ This clas...
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to underst...
""" Returns a sequence of moves that solves tinyMaze. For any other maze, the sequence of moves will be incorrect, so only use this for tinyMaze. """ from game import Directions s = Directions.SOUTH w = Directions.WEST return [s, s, w, s, w, w, s, w]
identifier_body
controller.go
with configurable hostnames and serving certificates. // // Cluster-admins may provide a custom hostname and serving certificate for a route // by creating a spec.componentRoute entry in the ingresses.config.openshift.io/cluster // resource. If a componentRoute entry exists in the status.componentRoutes list with // a...
// aggregatedComponeRoute contains information from the ComponentRouteSpec // and ComponentRouteStatus to generate the required Role and RoleBinding. type aggregatedComponentRoute struct { Name string Hash string ServingCertificateName string ConsumingUsers []configv1.C...
{ // Copy the list of consuming users. consumingUsersCopy := make([]configv1.ConsumingUser, len(status.ConsumingUsers)) copy(consumingUsersCopy, status.ConsumingUsers) return aggregatedComponentRoute{ Name: spec.Name, Hash: util.Hash(namespacedName(spec.Namespace, spec.Name)...
identifier_body
controller.go
matching namespace and name this controller will generate: // - A role that grants get/list/watch permissions for the secret defined in the spec. // - A roleBinding that binds the aforementioned role to each consumingUser specified // in the corresponding status entry. func New(mgr manager.Manager, config Config, even...
func allComponentRouteResources() []client.ListOption { return []client.ListOption{ client.HasLabels{componentRouteHashLabelKey}, client.InNamespace(operatorcontroller.GlobalUserSpecifiedConfigNamespace),
random_line_split
controller.go
with configurable hostnames and serving certificates. // // Cluster-admins may provide a custom hostname and serving certificate for a route // by creating a spec.componentRoute entry in the ingresses.config.openshift.io/cluster // resource. If a componentRoute entry exists in the status.componentRoutes list with // a...
componentRoutes := []aggregatedComponentRoute{} for _, componentRouteSpec := range componentRouteSpecs { hash := util.Hash(namespacedName(componentRouteSpec.Namespace, componentRouteSpec.Name)) if componentRouteStatus, ok := componentRouteHashToComponentRouteStatus[hash]; ok { componentRoute := newAggregated...
{ componentRouteHash := util.Hash(namespacedName(componentRouteStatus.Namespace, componentRouteStatus.Name)) componentRouteHashToComponentRouteStatus[componentRouteHash] = componentRouteStatus }
conditional_block
controller.go
routes with configurable hostnames and serving certificates. // // Cluster-admins may provide a custom hostname and serving certificate for a route // by creating a spec.componentRoute entry in the ingresses.config.openshift.io/cluster // resource. If a componentRoute entry exists in the status.componentRoutes list wi...
(spec configv1.ComponentRouteSpec, status configv1.ComponentRouteStatus) aggregatedComponentRoute { // Copy the list of consuming users. consumingUsersCopy := make([]configv1.ConsumingUser, len(status.ConsumingUsers)) copy(consumingUsersCopy, status.ConsumingUsers) return aggregatedComponentRoute{ Name: ...
newAggregatedComponentRoute
identifier_name
stream_inference.py
(MovingAvgPerf): def tick(self): super().tick(monotonic()) def fps_str(self, text='fps'): if len(self.times) == 1: fps = 0 else: fps = len(self.times) / (self.times[-1] - self.times[0]) return '%.2f %s' % (fps, text) class RunningMeanStdDev(): """Online mean and std dev. """ ...
MovingWindowPerf
identifier_name
stream_inference.py
if len(self.times) == 1: fps = 0 else: fps = len(self.times) / (self.times[-1] - self.times[0]) return '%.2f %s' % (fps, text) class RunningMeanStdDev(): """Online mean and std dev. """ def __init__(self, n=0, m=0.0, S=0.0): self.n = n self.m = m self.S = S ...
def tick(self): super().tick(monotonic()) def fps_str(self, text='fps'):
random_line_split
stream_inference.py
+ margin end_y = pos[1] - txt_size[0][1] - margin cv2.rectangle(img, pos, (end_x, end_y), bg_color, thickness) cv2.putText(img, text, pos, font_face, scale, color, 1, cv2.LINE_AA) buffer_size_s = 10 samplerate = 16000 window_length = int(0.025 * samplerate) n_fft = 512 hop_length = int(0.01 * samplerate)...
break
conditional_block
stream_inference.py
1: fps = 0 else: fps = len(self.times) / (self.times[-1] - self.times[0]) return '%.2f %s' % (fps, text) class RunningMeanStdDev(): """Online mean and std dev. """ def __init__(self, n=0, m=0.0, S=0.0): self.n = n self.m = m self.S = S def mean(self): ...
def stream_inference_of_microphone_audio(args): """ The spectrum sits in a buffer with width spec_buffer_pad + spec_buffer_w . The first spec_buffer_pad of it is a copy of the last spec_buffer_pad of it. """ with sd.InputStream(device=args.device, channels=1, callback=update_spectrogram, ...
with sd.InputStream(device=args.device, channels=1, callback=update_spectrogram, blocksize=samples_buffer_block_size, samplerate=samplerate): while True: sleep(0.02) cv2.imshow("Press 'q' to quit", np.asarray((spec_buffer * 255).astype(np...
identifier_body
flickr_speech.py
train_features_var["fbank"] = np.array([ +9.80457338, 11.02937828, 12.10755132, 11.95119139, 12.28248128, 13.20537295, 14.11372048, 15.14463048, 15.78990233, 15.72936093, 15.36991563, 15.08655164, 14.52818211, 14.26114153, 14.22071484, 14.07992226, 13.87976692, 13.91862834, 14.09054846, 13.93680669, ...
train_speakers = self.faudio_metadata[2][x_train_idx] valid_speaker_indices = np.where(np.invert(np.isin( self.faudio_metadata[2], train_speakers)))[0]
conditional_block
flickr_speech.py
-04, +1.25535136e-03, -1.09850116e-03, +8.23052806e-05, +1.83033459e-03, +1.21922030e-03, -1.84041176e-03, +6.59660647e-05, -9.16896159e-04, -1.48896116e-03, -1.10792069e-03, -6.03055868e-04, +7.30406810e-04, +4.05984679e-04, +2.76476503e-04, -1.50802754e-05, +7.71538868e-05]) train_features_var["mfcc"...
""" super().__init__(**kwargs) logging.log(logging.INFO, f"Creating Flickr audio experiment") assert features in ["mf
"""TODO `features` one of `["mfcc", "fbank"]`. `keywords_split` one of `['one_shot_evaluation', 'one_shot_development', 'background_train', 'background_dev', 'background_test']`. `speaker_mode` options: "baseline" - randomly choose learning and evaluation sampl...
identifier_body
flickr_speech.py
train_global_mean["fbank"] = 17.509969510358815 train_global_var["fbank"] = 14.452916650749247 # statistics per feature dimension train_features_mean = {} # pylint: disable=invalid-name train_features_var = {} # pylint: disable=invalid-name train_features_mean["mfcc"] = np.array([ +1.32153148e-01, +5.34269911e-...
train_global_var["mfcc"] = 0.3567110590621045
random_line_split
flickr_speech.py
-04, +1.25535136e-03, -1.09850116e-03, +8.23052806e-05, +1.83033459e-03, +1.21922030e-03, -1.84041176e-03, +6.59660647e-05, -9.16896159e-04, -1.48896116e-03, -1.10792069e-03, -6.03055868e-04, +7.30406810e-04, +4.05984679e-04, +2.76476503e-04, -1.50802754e-05, +7.71538868e-05]) train_features_var["mfcc"...
(base.Experiment): def __init__(self, features="mfcc", keywords_split="one_shot_evaluation", embed_dir=None, preprocess_func=None, speaker_mode="baseline", **kwargs): """TODO `features` one of `["mfcc", "fbank"]`. `keywords_split` one of `['one_shot_evalu...
FlickrSpeech
identifier_name
UserController.go
atar,u.Intro,i.Document", "i.Status=1") if err != nil { helper.Logger.Error(err.Error()) } this.Data["Seo"] = models.NewSeo().GetByPage("PC-Ucenter-Coin", "่ดขๅฏŒ่ฎฐๅฝ•โ€”ไผšๅ‘˜ไธญๅฟƒ-"+user["Username"].(string), "ไผšๅ‘˜ไธญๅฟƒ,่ดขๅฏŒ่ฎฐๅฝ•,"+user["Username"].(string), "่ดขๅฏŒ่ฎฐๅฝ•โ€”ไผšๅ‘˜ไธญๅฟƒ-"+user["Username"].(string), this.Sys.Site) this.TplName = "coin.htm...
} // ๅ‘้€้‚ฎไปถ func (this *UserController) SendMail() { if len(this.Ctx.GetCookie(beego.AppConfig.String("SessionName"))) == 0 { this.Redirect("/", 302) return } //ๅ‘้€้‚ฎไปถ็š„็ฑปๅž‹๏ผšๆณจๅ†Œ(reg)ๅ’Œๆ‰พๅ›žๅฏ†็ (findpwd) t := this.GetString("type") if t != "reg" && t != "findpwd" { this.ResponseJson(false, "้‚ฎไปถๅ‘้€็ฑปๅž‹ไธๆญฃ็กฎ") } valid := vali...
this.SetCookieLogin(uid) this.ResponseJson(true, "ไผšๅ‘˜ๆณจๅ†ŒๆˆๅŠŸ")
random_line_split
UserController.go
6-01-02 15:04:05"), this.Sys.Sign), } models.NewCoinLog().LogRecord(log) } this.ResponseJson(true, fmt.Sprintf("ๆญๅ–œๆ‚จ๏ผŒไปŠๆ—ฅ็ญพๅˆฐๆˆๅŠŸ๏ผŒ้ข†ๅ–ไบ† %v ไธช้‡‘ๅธ", this.Sys.Sign)) } // ๆฃ€ๆต‹็”จๆˆทๆ˜ฏๅฆๅทฒ็™ปๅฝ• func (this *UserController) CheckLogin() { if this.BaseController.IsLogin > 0 { this.ResponseJson(true, "ๅทฒ็™ปๅฝ•") } this.ResponseJson(false, "ๆ‚จๅฝ“...
nix()) orm.NewOrm().Update(&doc, "Title", "Keywords", "Description") orm.NewOrm().Update(&info, "Pid", "Cid", "ChanelId", "Price") //ๅŽŸๅˆ†็ฑป-1 models.Regulate(models.GetTableCategory(), "Cnt", -1, fmt.Sprintf("Id in(%v,%v,%v)", info.ChanelId, info.Cid, info.Pid)) //ๆ–ฐๅˆ†็ฑป+1 models.Regulate(models.GetTableCategory(...
identifier_body
UserController.go
๏ผŒ่ฏทๅ…ˆ็™ปๅฝ•") } var data = models.Sign{ Uid: this.IsLogin, Date: time.Now().Format("20060102"), } _, err := orm.NewOrm().Insert(&data) if err != nil { this.ResponseJson(false, "็ญพๅˆฐๅคฑ่ดฅ๏ผŒๆ‚จไปŠๅคฉๅทฒ็ญพๅˆฐ") } if err = models.Regulate(models.GetTableUserInfo(), "Coin", this.Sys.Sign, fmt.Sprintf("Id=%v", this.IsLogin)); err =...
e.Now(
identifier_name
UserController.go
) } this.ResponseJson(true, fmt.Sprintf("ๆญๅ–œๆ‚จ๏ผŒไปŠๆ—ฅ็ญพๅˆฐๆˆๅŠŸ๏ผŒ้ข†ๅ–ไบ† %v ไธช้‡‘ๅธ", this.Sys.Sign)) } // ๆฃ€ๆต‹็”จๆˆทๆ˜ฏๅฆๅทฒ็™ปๅฝ• func (this *UserController) CheckLogin() { if this.BaseController.IsLogin > 0 { this.ResponseJson(true, "ๅทฒ็™ปๅฝ•") } this.ResponseJson(false, "ๆ‚จๅฝ“ๅ‰ๅค„ไบŽๆœช็™ปๅฝ•็Šถๆ€๏ผŒ่ฏทๅ…ˆ็™ปๅฝ•") } // ๅˆ›ๅปบๆ”ถ่—ๅคน func (this *UserController) CreateCollectFolder...
this.Redirect("/user", 302) }
conditional_block
nosuicide.py
def run(self): self.estimate() print(self.estimates) return self.estimates def run_crosscheck(self): self.estimate() print(self.crosscheck_estimates) return self.crosscheck_estimates def run_process(X, Y, test_data, ids, vectorizer): runner = StrangeClassifier(X = X, Y = Y, test_data = t...
process_arrays.append(pool.apply_async(run_process, [
random_line_split
nosuicide.py
('utf8')) if labels: Y[index] = sl[2] index += 1 td.close() if labels: return (X, Y) else: return X def vectorize_data(**args): total_data_pts = len(args['td']) all_docs = np.zeros( total_data_pts * 2, dtype = [('id', 'u2'), ('text', 'S16000')] ) all_docs...
if self.ids is not None: self.estimates[:, 0] = self.ids self.estimates[:, 1] = results_proba[:, 1] else: self.crosscheck_estimates = { 'labels': classifier.predict(self.test_data), 'proba': results_proba[:, 1] } # inverted_vocab = {_id:w for (w,_id) in self.vectoriz...
classifier = BernoulliNB() #classifier = MultinomialNB(alpha = 0.02) #classifier = DecisionTreeClassifier(class_weight = { 0: 1, 1: 9 }) #classifier = KNeighborsClassifier(n_neighbors=50, metric='minkowski', p=3) # classifier = RandomForestClassifier( # max_depth = 32, # n_estimators = 64, ...
identifier_body
nosuicide.py
(X, Y, vectorizer, Classifier): # culling? #return (X, Y) print('WTF2', X.shape, Y.shape) myTmpClassifier = Classifier(X = X, Y = Y, test_data = X, vectorizer = vectorizer) new_X_train = None new_Y_train = [] threshold = 1 - 1 / X.shape[1] ** 2 my_full_estimates = myTmpClassifier.run_crosscheck() my_e...
geld_data
identifier_name
nosuicide.py
else: pass #print(row) #print(td[1][idx]) new_Y_train = np.array(new_Y_train) print('SHAPE', new_X_train.shape) return (new_X_train, new_Y_train) def load_text_data(total_pts, labels = True, **args): with open(os.path.abspath(os.path.dirname(__file__) + './' + args['filename']), 'r') a...
if new_X_train is None: new_X_train = X[idx] else: new_X_train = vstack([new_X_train, X[idx]]) new_Y_train.append(Y[idx])
conditional_block
binres_test.go
8:] debugIndex := 8 for len(buf) > 0
return bx, nil } checkMarshal := func(res encoding.BinaryMarshaler, bsize int) { b, err := res.MarshalBinary() if err != nil { t.Error(err) } idx := debugIndices[res] a := bin[idx : idx+bsize] if !bytes.Equal(a, b) { x, y := len(a), len(b) if x != y { t.Errorf("%v: %T: byte length does no...
{ k, err := bx.unmarshalBinaryKind(buf) if err != nil { return nil, err } debugIndices[k.(encoding.BinaryMarshaler)] = debugIndex debugIndex += k.size() buf = buf[k.size():] }
conditional_block
binres_test.go
[8:] debugIndex := 8 for len(buf) > 0 { k, err := bx.unmarshalBinaryKind(buf) if err != nil { return nil, err } debugIndices[k.(encoding.BinaryMarshaler)] = debugIndex debugIndex += k.size() buf = buf[k.size():] } return bx, nil } checkMarshal := func(res encoding.BinaryMarshaler, bsize...
(a []TableRef) (b []uint32) { for _, x := range a { b = append(b, uint32(x)) } return } func compareUint32s(t *testing.T, a, b []uint32) error { var err error if len(a) != len(b) { err = fmt.Errorf("lengths do not match") } n := len(a) if n < len(b) { n = len(b) } var buf bytes.Buffer buf.WriteStrin...
rtou
identifier_name
binres_test.go
[8:] debugIndex := 8 for len(buf) > 0 { k, err := bx.unmarshalBinaryKind(buf) if err != nil { return nil, err } debugIndices[k.(encoding.BinaryMarshaler)] = debugIndex debugIndex += k.size() buf = buf[k.size():] } return bx, nil } checkMarshal := func(res encoding.BinaryMarshaler, bsize...
func (a byAttrName) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byAttrName) Less(i, j int) bool { return a[i].Name < a[j].Name } func compareElements(have, want *XML) error { h, w := have.iterElements(), want.iterElements() buf := new(bytes.Buffer) for { a, b := <-h, <-w if a == nil || b == nil { ...
{ return len(a) }
identifier_body
binres_test.go
bttr.RawValue || attr.TypedValue.Type != bttr.TypedValue.Type || attr.TypedValue.Value != bttr.TypedValue.Value { // single exception to check for minSdkVersion which has peculiar output from aapt // but following same format of all other like-types appears to work correctly. // BUG(dskinner) this ...
if uint32(typ.headerByteSize)-typ.config.size != uint32(xtyp.headerByteSize)-uint32(xtyp.config.size) { t.Fatal("fixed size header portions don't match") } if len(typ.indices) != len(xtyp.indices) { t.Fatal("typ.indices length don't match")
random_line_split
train_transformer_navigation.py
= None): caption = self.wrap_caption(caption) fig, ax = plt.subplots(2,2, figsize=(16,16)) # gs = gridspec.GridSpec(2, 2, width_ratios=[2, 1]) text_ax = ax[0,1] text_ax.axis([0, 1, 0, 1]) text_ax.text(0.2, 0.02, caption, fontsize = 12) text_ax.axis("off") ...
# save arg config to checkpoint_dir with open(pathlib.Path(args.checkpoint_dir).joinpath("config.yaml"), "w") as f1: dump_args = copy.deepcopy(args)
random_line_split
train_transformer_navigation.py
debug_image_top_k = None if debug_image_threshold < 0: debug_image_threshold = None self.debug_image_top_k = debug_image_top_k self.debug_image_threshold = debug_image_threshold def split_large_batch(self, batch): large_bsz = batch['path_state'].shape[0] small_b...
def compute_patch_loss(self, inputs, outputs, next_to_prev_weight = [1.0, 1.0]): """ compute per-patch for each patch """ bsz, w, h, __ = inputs['input_image'].shape pred_next_image = outputs["next_position"] path_state = inputs['path_state'].reshape(bsz, 1, w, ...
raise AssertionError(f"invalid score type {self.score_type}")
conditional_block
train_transformer_navigation.py
debug_image_top_k = None if debug_image_threshold < 0: debug_image_threshold = None self.debug_image_top_k = debug_image_top_k self.debug_image_threshold = debug_image_threshold def split_large_batch(self, batch): large_bsz = batch['path_state'].shape[0] small_b...
(self, inputs, outputs, next_to_prev_weight = [1.0, 1.0]): """ compute per-patch for each patch """ bsz, w, h, __ = inputs['input_image'].shape pred_next_image = outputs["next_position"] path_state = inputs['path_state'].reshape(bsz, 1, w, h).float() true_nex...
compute_patch_loss
identifier_name
train_transformer_navigation.py
debug_image_top_k = None if debug_image_threshold < 0: debug_image_threshold = None self.debug_image_top_k = debug_image_top_k self.debug_image_threshold = debug_image_threshold def split_large_batch(self, batch): large_bsz = batch['path_state'].shape[0] small_b...
true_path = path_state.detach().numpy() true_path = np.tile(true_path.reshape(512, 512, 1), (1,1,3)).astype(float) true_ax = ax[0,0] true_ax.imshow(true_path) pred_path = torch.softmax(pred_path, dim=0) pred_path = pred_path[1,:,:] pred_path = pred_path.cpu()....
caption = self.wrap_caption(caption) fig, ax = plt.subplots(2,2, figsize=(16,16)) # gs = gridspec.GridSpec(2, 2, width_ratios=[2, 1]) text_ax = ax[0,1] text_ax.axis([0, 1, 0, 1]) text_ax.text(0.2, 0.02, caption, fontsize = 12) text_ax.axis("off") props = dict(...
identifier_body
bridge_contract.go
DataDir: datadir, BootstrapNodes: bootstrapNodes, NetworkName: networkConfig.NetworkName, NetworkID: networkConfig.NetworkID, GenesisBlock: networkConfig.GenesisBlock, }) if err != nil { return nil, err } err = lc.LoadAccount(accountJSON, accountPass) if err != nil { return nil, err ...
caller, err := contract.NewTokenCaller(networkConfig.ContractAddress, lc.Client) if err != nil { return nil, err } contract, abi, err := bindTTFT20(networkConfig.ContractAddress, lc.Client, lc.Client, lc.Client) if err != nil { return nil, err } w := &stellarWallet{ network: stellarNetwork, } if ste...
{ return nil, err }
conditional_block
bridge_contract.go
) TxHash() common.Hash { return w.txHash } // BlockHash of the containing block func (w WithdrawEvent) BlockHash() common.Hash { return w.blockHash } // BlockHeight of the containing block func (w WithdrawEvent) BlockHeight() uint64 { return w.blockHeight } // SubscribeWithdraw subscribes to new Withdraw events o...
GetTransactionEffects
identifier_name
bridge_contract.go
return err } defer sub.Unsubscribe() for { select { case err = <-sub.Err(): return err case transfer := <-sink: log.Debug("Noticed transfer event", "from", transfer.From, "to", transfer.To, "amount", transfer.Tokens) } } } // SubscribeMint subscribes to new Mint events on the given contract. This c...
return bridge.balance, err }
random_line_split
bridge_contract.go
DataDir: datadir, BootstrapNodes: bootstrapNodes, NetworkName: networkConfig.NetworkName, NetworkID: networkConfig.NetworkID, GenesisBlock: networkConfig.GenesisBlock, }) if err != nil { return nil, err } err = lc.LoadAccount(accountJSON, accountPass) if err != nil { return nil, err ...
// TxHash hash of the transaction func (w WithdrawEvent) TxHash() common.Hash { return w.txHash } // BlockHash of the containing block func (w WithdrawEvent) BlockHash() common.Hash { return w.blockHash } // BlockHeight of the containing block func (w WithdrawEvent) BlockHeight() uint64 { return w.blockHeight } ...
{ return w.network }
identifier_body
train_fcn.py
(data_index=None,cut_shape=None,data_type=['MCIc','MCInc'],pre_dir='/home/anzeng/rhb/fmri_data', num_batches = 256*5,voxnet_point=None,test_size = 6,brain_map=[217]): # fr = open(cfg.output, 'w') tf.reset_default_graph() time_dim = 80 # ๆŒ‘้€‰ๆ—ถ้—ด็‰‡ไธชๆ•ฐ batch_size = 8 dataset = fMRI_data(data_typ...
main
identifier_name
train_fcn.py
#SVM index ######################### svm_index = {} train_len = 0 test_len = 0 for d_type in data_type: t_dir = os.path.join(pre_dir,d_type) t_len = os.listdir(t_dir) t_len = len(t_len) train_index = list(range(t_len)) test_index = data_index[d_type]['tes...
if batch_index % 64 or train_evaluation.ACC >= 0.8 == 0: ######SVMๅˆ†็ฑปๅ™จ#################### svm_feature = np.zeros((train_len+test_len,128)) svm_label = np.zeros(train_len+test_len) for x in range(train_len): ...
train_evaluation = evaluation() for x in range(num_accuracy_batches): voxs, labels = dataset.train.random_sampling.get_time_batch(session,voxnet,cut_shape,time_dim=time_dim,batch_size=batch_size) feed_dict = {FCNs[0]: voxs, voxnet[0]:voxnet_data,voxnet.keep_prob:1...
conditional_block
train_fcn.py
_index = {'train':train_index,'test':test_index} train_len += len(train_index) test_len += len(test_index) svm_index[d_type] = _index print(train_len) print(test_len) print(svm_index) svm_dataset = fMRI_data(data_type,data_index = svm_index,varbass=False,dir=pre_dir) ...
tf.reset_default_graph() time_dim = 80 # ๆŒ‘้€‰ๆ—ถ้—ด็‰‡ไธชๆ•ฐ batch_size = 8 dataset = fMRI_data(data_type,data_index=data_index,varbass=False,dir=pre_dir) #SVM index ######################### svm_index = {} train_len = 0 test_len = 0 for d_type in data_type: t_dir = os.path.join(pre_...
identifier_body
train_fcn.py
#SVM index ######################### svm_index = {} train_len = 0 test_len = 0 for d_type in data_type: t_dir = os.path.join(pre_dir,d_type) t_len = os.listdir(t_dir) t_len = len(t_len) train_index = list(range(t_len)) test_index = data_index[d_type]['tes...
p['learning_rate']: learning_rate, FCNs.training: True,p['data_value']:data_value} session.run(p['train'], feed_dict=feed_dict) if batch_index and batch_index % 32 == 0: print("{} batch: {}".format(datetime.datetime.now(), batch_index)) ...
if batch_index > weights_decay_after and batch_index % 256 == 0: session.run(p['weights_decay'], feed_dict=feed_dict) voxs, labels = dataset.train.oversampling.get_time_batch(session,voxnet,cut_shape,time_dim=time_dim,batch_size=batch_size) feed_dict = {FCNs[0]: voxs...
random_line_split
emulatorlauncher.py
DolphinGenerator from generators.pcsx2.pcsx2Generator import Pcsx2Generator from generators.scummvm.scummvmGenerator import ScummVMGenerator from generators.dosbox.dosboxGenerator import DosBoxGenerator from generators.dosboxx.dosboxxGenerator import DosBoxxGenerator from generators.vice.viceGenerator import ViceGener...
# the resolution must be changed before configuration while the configuration may depend on it (ie bezels) wantedGameMode = generators[system.config['emulator']].getResolutionMode(system.config) systemMode = videoMode.getCurrentMode() resolutionChanged = False exitCode = -1 try: eslog.l...
slog.log("emulator: {}".format(system.config["emulator"]))
conditional_block
emulatorlauncher.py
DolphinGenerator from generators.pcsx2.pcsx2Generator import Pcsx2Generator from generators.scummvm.scummvmGenerator import ScummVMGenerator from generators.dosbox.dosboxGenerator import DosBoxGenerator from generators.dosboxx.dosboxxGenerator import DosBoxxGenerator from generators.vice.viceGenerator import ViceGener...
folder, event, args): if not os.path.isdir(folder): return for file in os.listdir(folder): if os.path.isdir(os.path.join(folder, file)): callExternalScripts(os.path.join(folder, file), event, args) else: if os.access(os.path.join(folder, file), os.X_OK): ...
allExternalScripts(
identifier_name
emulatorlauncher.py
DolphinGenerator from generators.pcsx2.pcsx2Generator import Pcsx2Generator from generators.scummvm.scummvmGenerator import ScummVMGenerator from generators.dosbox.dosboxGenerator import DosBoxGenerator from generators.dosboxx.dosboxxGenerator import DosBoxxGenerator from generators.vice.viceGenerator import ViceGener...
def signal_handler(signal, frame): global proc print('Exiting') if proc: print('killing proc') proc.kill() if __name__ == '__main__': proc = None signal.signal(signal.SIGINT, signal_handler) parser = argparse.ArgumentParser(description='emulator-launcher script') maxnbpla...
lobal proc command.env.update(os.environ) eslog.log("command: {}".format(str(command))) eslog.log("command: {}".format(str(command.array))) eslog.log("env: {}".format(str(command.env))) proc = subprocess.Popen(command.array, env=command.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) exitc...
identifier_body
emulatorlauncher.py
import DolphinGenerator from generators.pcsx2.pcsx2Generator import Pcsx2Generator from generators.scummvm.scummvmGenerator import ScummVMGenerator from generators.dosbox.dosboxGenerator import DosBoxGenerator from generators.dosboxx.dosboxxGenerator import DosBoxxGenerator from generators.vice.viceGenerator import Vi...
system.config["emulator-forced"] = True # tip to indicated that the emulator was forced if args.core is not None: system.config["core"] = args.core system.config["core-forced"] = True eslog.debug("Settings: {}".format(system.config)) if "emulator" in system.config and "core" in syst...
if args.emulator is not None: system.config["emulator"] = args.emulator
random_line_split
BattleState.ts
080; this.scale.pageAlignVertically = true; this.scale.pageAlignHorizontally = true; } create() { //speler niet laten bewegen speler.setCanPlayerMove(false); //scale verhogen speler.scale.set(4); this.CreateBackgroun...
this.world.remove(speler); this.world.remove(speler.getPortrait()); for (var i = 0; i < this.enemies.length; i++) { //Element van wereld en enemies array verwijderen. this.enemies.splice(i, 1); } //Hele state opschonen ...
speler.scale.set(2);
random_line_split
BattleState.ts
080; this.scale.pageAlignVertically = true; this.scale.pageAlignHorizontally = true; } create() { //speler niet laten bewegen speler.setCanPlayerMove(false); //scale verhogen speler.scale.set(4); this.CreateBackgroun...
} HandleSkip() { this.attackingUnit = speler; this.NextTurn(); } HandleFlee() { this.attackingUnit = speler; var randomNumber: number; randomNumber = this.game.rnd.integerInRange(0, 100); if (randomNumber > 75) { ...
this.NextTurn(); }
conditional_block
BattleState.ts
080; this.scale.pageAlignVertically = true; this.scale.pageAlignHorizontally = true; } create() { //speler niet laten bewegen speler.setCanPlayerMove(false); //scale verhogen speler.scale.set(4); this.CreateBackgroun...
HandleAiAttack(attacker: Unit, target: Unit) { this.attackingUnit = attacker; this.game.sound.play("attack"); //Random damage genereren voor AI. ai kunnen geen skills gebruiken. var damage: number; damage = this.game.rnd.integerInRange(0, 20); ...
if (this.canAttack) { this.canAttack = false; this.attackingUnit = this.queue.poll(); this.attackingUnit.attack(); this.game.sound.play("attack"); target.SetCurrentHealth(target.GetCurrentHealth() - this.playerDamage); ...
identifier_body
BattleState.ts
080; this.scale.pageAlignVertically = true; this.scale.pageAlignHorizontally = true; } create() { //speler niet laten bewegen speler.setCanPlayerMove(false); //scale verhogen speler.scale.set(4); this.CreateBackgroun...
{ this.itemsDiv.classList.add("hidden"); this.ActionsDiv.classList.remove("hidden"); } ChooseItem(e) { var naam = e.srcElement.innerText; var item: Item; item = new Item(); item.SetName(naam); speler.GetInventory().Use...
deItems()
identifier_name
trans_norm.py
, target_weights = model.get_batch( train_set, bucket_id) _, step_loss, _ = model.step(sess, encoder_inputs, decoder_inputs, target_weights, bucket_id, False) step_time += (time.time() - start_time) / FLAGS.steps_per_checkpoint loss += step_loss / FLAGS.ste...
main
identifier_name
trans_norm.py
, encoder_inputs, decoder_inputs, target_weights, bucket_id, False) step_time += (time.time() - start_time) / FLAGS.steps_per_checkpoint loss += step_loss / FLAGS.steps_per_checkpoint current_step += 1 # Once in a while, we save checkpoint, print statistics, a...
train() # eval_test()
conditional_block
trans_norm.py
_checkpoint", 200, "How many training steps to do per checkpoint.") tf.app.flags.DEFINE_boolean("decode", False, "Set to True for interactive decoding.") tf.app.flags.DEFINE_boolean("self_test", False, "Run a self-test if this is set to...
def read_data(filename_queue): """ This function reads the TFRecords file and returns a single sample tensor. The returned tensor will generally be added to a queue. """ reader = tf.RecordReader() _, serialized_sample = reader.read(filename_queue) context_features, sequences = tf.parse_single_sequence...
with open(vocab_path) as ifi: vocab_size = len(ifi.readlines()) FLAGS.__setattr__(lang + '_vocab_size', vocab_size)
identifier_body
trans_norm.py
_model(session, forward_only): """Create translation model and initialize or load parameters in session.""" print(FLAGS.en_vocab_size, FLAGS.fr_vocab_size) model = seq2seq_model.Seq2SeqModel( FLAGS.en_vocab_size, FLAGS.fr_vocab_size, _buckets, FLAGS.size, FLAGS.num_layers, FLAGS.max_gradient_norm, FLA...
random_line_split
program.go
:"splitter,omitempty" json:"splitter,omitempty"` } type Crawl struct { *URL Types []*Type `yaml:"types,omitempty" json:"types,omitempty"` InitElement *Elem `yaml:"init_element,omitempty" json:"init_element,omitempty"` CrawlElement *Elem `yaml:"crawl_element,omitempty" json:"crawl_element,omitempty"` } ...
defer resp.Body.Close() gzipReader, err := gzip.NewReader(resp.Body) if err != nil { e <- err return } defer gzipReader.Close() // Load the HTML document doc, err := goquery.NewDocumentFromReader(gzipReader) if err != nil { e <- err return } // Find items ...
{ var wg sync.WaitGroup wg.Add(len(c.Types)) e := make(chan error, len(c.Types)) for idx, crawlType := range c.Types { go func(idx int, crawlType *CrawlType) { crawlInitURL := crawlType.BaseURL + crawlType.TypeURL + crawlType.InitSuffixURL crawlName := crawlType.Name crawlContent := crawlType.InitElemen...
identifier_body
program.go
&GreatFireURL{ BaseURL: r.Crawl.URL.BaseURL, TypeURL: rawType.TypeURL, SuffixURL: r.Crawl.URL.SuffixURL, InitSuffixURL: r.Crawl.URL.InitSuffixURL, }, Name: rawType.Name, IsCrawl: rawType.IsCrawl, From: rawType.From, To: raw...
resultSlice := make([]string, 0, len(resultMap)) ipSlice := make([]string, 0, len(resultMap)) ipReg := regexp.MustCompile(c.Filter.Regexp.IP)
random_line_split
program.go
:"splitter,omitempty" json:"splitter,omitempty"` } type Crawl struct { *URL Types []*Type `yaml:"types,omitempty" json:"types,omitempty"` InitElement *Elem `yaml:"init_element,omitempty" json:"init_element,omitempty"` CrawlElement *Elem `yaml:"crawl_element,omitempty" json:"crawl_element,omitempty"` } ...
(rawResultChan chan map[*string]int) { var wg sync.WaitGroup workerPool := make(chan struct{}, c.Customize.CPUCores) for _, crawlType := range c.Types { for _, url := range crawlType.CrawlList { workerPool <- struct{}{} wg.Add(1) go func(url string, crawlType *CrawlType) { defer func() { if err...
Crawl
identifier_name
program.go
"` } type Filter struct { Regexp *FilterType `yaml:"regexp,omitempty" json:"regexp,omitempty"` Percent int `yaml:"percent,omitempty" json:"percent,omitempty"` } type Customize struct { CPUCores int `yaml:"cpu_cores,omitempty" json:"cpu_cores,omitempty"` MaxCapacity int `yaml:"max_capacity,...
{ workerPool <- struct{}{} wg.Add(1) go func(url string, crawlType *CrawlType) { defer func() { if err := recover(); err != nil { log.Printf("Goroutine panic: fetching %v : %v\n", url, err) } }() container := crawlType.CrawlElement.Container content := crawlType.CrawlElement.C...
conditional_block
Querybox.ts
keywords in order to broaden the query (see * [Coveo Query Syntax Reference](http://www.coveo.com/go?dest=adminhelp70&lcid=9&context=10005)). * * Default value is `false`. */ enableQuestionMarks: ComponentOptions.buildBooleanOption({ defaultValue: false }), /** * If {@link Querybox.op...
getCursor
identifier_name
Querybox.ts
='CoveoQuerybox'></input>` * will not). * * See also the {@link Searchbox} component, which can automatically instantiate a Querybox component along with an * optional {@link SearchButton} component. */ export class Querybox extends Component { static ID = 'Querybox'; /** * The options for the Querybox. ...
* **Note:** * > Only the basic expression of the query (see {@link q}) can be converted to a partial match expression. * * **Example:** * > If the partialMatchKeywords option is `7`, the basic expression will have to contain at least 7 keywords * > to be converted to a partial match expres...
* * See also {@link Querybox.options.partialMatchThreshold}. * * Default value is `5`. *
random_line_split
Querybox.ts
feature. * * Default value is `false`. */ enableSearchAsYouType: ComponentOptions.buildBooleanOption({ defaultValue: false }), /** * If {@link Querybox.options.enableSearchAsYouType} is `true`, specifies the delay (in milliseconds) between a * key press and a query being triggered. ...
{ this.usageAnalytics.logSearchEvent<IAnalyticsNoMeta>(analyticsActionCauseList.searchboxClear, {}); this.triggerNewQuery(false); }
conditional_block
battle.py
falls within the target will the damage be applied. """ if weapon_size <= target_size: return damage return (target_size ** 2) / (weapon_size ** 2) def true_damage(damage, weapon_size, target_size, source_debuff, target_debuff): """ Calculates true damage based on parameters. """...
else: continue return [logi_shield, logi_armor] def repair_fleet(input_fleet): """ Have logistics ships do their job and repair other ships in the fleet """ logistics = logi_subfleet(input_fleet) logi_shield = logistics[0] logi_armor = logistics[1] if (logi_shield =...
logi_armor.append(ship)
conditional_block
battle.py
falls within the target will the damage be applied. """ if weapon_size <= target_size: return damage return (target_size ** 2) / (weapon_size ** 2) def true_damage(damage, weapon_size, target_size, source_debuff, target_debuff): """ Calculates true damage based on parameters. """...
(attacker_ship, victim_ship): """ Do a ship attack. Apply the attacker's schema onto the victim_ship as an attack and return a new Ship object as the result. """ if not is_ship_alive(victim_ship): # save us some time, it should be the same dead ship. return victim_ship if ...
ship_attack
identifier_name
battle.py
that falls within the target will the damage be applied. """ if weapon_size <= target_size: return damage return (target_size ** 2) / (weapon_size ** 2) def true_damage(damage, weapon_size, target_size, source_debuff, target_debuff): """ Calculates true damage based on parameters. ...
return ship.attributes.hull > 0 # though it can't be < 0 def grab_debuffs(source, target_in): """ Retuns a dict of applied debufs calculated from ship schema as well as ship attributes. Source is ShipSchema target_in is a Ship """ inactive = {} sensor_str = target_in.schema.sensor_...
# If and when flag systems become advanced enough **FUN** things can # be applied to make this check more hilarious.
random_line_split
battle.py
that falls within the target will the damage be applied. """ if weapon_size <= target_size: return damage return (target_size ** 2) / (weapon_size ** 2) def true_damage(damage, weapon_size, target_size, source_debuff, target_debuff): """ Calculates true damage based on parameters. ...
if not target.debuffs.get('inactive', {}).get('ECM', 0): if sensor_str == 0 or \ random.random() < (float(source.ECM) / sensor_str): inactive['ECM'] = source.ECM if source.web: if target.debuffs.get('inactive', {}).get('web', 0) < source.web: ...
""" Retuns a dict of applied debufs calculated from ship schema as well as ship attributes. Source is ShipSchema target_in is a Ship """ inactive = {} sensor_str = target_in.schema.sensor_strength target = target_in # I'm sure there's a list comprehension thing that could be used ...
identifier_body
lib.rs
#[derive(Debug, Clone, Copy, PartialEq)] pub enum Repeatability { /// High repeatability 0.04ยฐC High, /// Medium repeatability 0.08ยฐC Medium, /// Low repeatability 0.15ยฐC Low, } impl Default for Repeatability { fn default() -> Self { Repeatability::Low } } /// Possible peripher...
// write and read private methods /// Write an I2C command to the sensor fn send_command(&mut self, command: Command) -> Result<(), Error<E>> { self.i2c .write(self.address, &command.as_bytes()) .map_err(Error::I2C) } /// Read and check the CRC. /// Returns a Result...
self.i2c }
identifier_body
lib.rs
/// Return the maximum measurement duration according to repeatability /// in microseconds fn measurement_duration_us(repeat: Repeatability) -> u16; } #[doc(hidden)] // Type states for one-shot and continuous modes. pub mod marker { pub mod mode { #[derive(Debug)] pub struct OneShot(())...
// 20 // }
random_line_split
lib.rs
#[derive(Debug, Clone, Copy, PartialEq)] pub enum Repeatability { /// High repeatability 0.04ยฐC High, /// Medium repeatability 0.08ยฐC Medium, /// Low repeatability 0.15ยฐC Low, } impl Default for Repeatability { fn default() -> Self { Repeatability::Low } } /// Possible peripher...
ConversionRate::_10Hz => { match r { Repeatability::High => [0x27, 0x37], Repeatability::Medium => [0x27, 0x21], Repeatability::Low => [0x27, 0x2A], } }...
match r { Repeatability::High => [0x23, 0x34], Repeatability::Medium => [0x23, 0x22], Repeatability::Low => [0x23, 0x29], } },
conditional_block
lib.rs
}, ConversionRate::_1Hz => { match r { Repeatability::High => [0x21, 0x30], Repeatability::Medium => [0x21, 0x26], Repeatability::Low => [0x21, 0x2D], ...
eatability(&mut s
identifier_name
enhance.py
,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-111.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];-5120900 -9998100...
table=str(address_csv), in_x_field='x', in_y_field='y', out_layer=f'{table_name}_temp', spatial_reference=UTM, in_z_field=None ) else: print(' skipping') print(' creating feature class') if not arcpy.Exists(f'{tab...
print(f'1. creating points from csv as {table_name}') if not arcpy.Exists(f'{table_name}_step_1'): arcpy.management.MakeXYEventLayer(
random_line_split
enhance.py
298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-111.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];-5120900 -9998100 ...
(parent_folder): """enhances the csv table data from the identity tables :param parent_folder: The parent path to the csv files to enhance :type parent_folder: Path """ parent_folder = Path(parent_folder).resolve() address_csv_files = sorted(parent_folder.glob('*.csv')) print(f'enhancing {...
enhance
identifier_name
enhance.py
298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-111.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];-5120900 -9998100 ...
else: print(' skipping') step = step + 1 continue step = step + 1 print(f'completed: {default_timer() - start}') return f'{table_name}_step_{step}' def prepare_output(table): """prepares the output by splitting the primary key and the other fi...
arcpy.analysis.Identity( in_features=f'{table_name}_step_{step}', identity_features=enhance_table_name, out_feature_class=f'{table_name}_step_{step + 1}', join_attributes='NO_FID', cluster_tolerance=None, relationship='NO_RE...
conditional_block
enhance.py
5199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-111.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];-5120900 -9998100 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecisi...
"""prepares the output by splitting the primary key and the other field """ print('adding type field') absolute_table = str(Path(arcpy.env.workspace) / table) fields = arcpy.ListFields(absolute_table) if 'type' in [field.name.lower() for field in fields]: print(' skipping') retu...
identifier_body
ViewFichaFinanceira.js
_once('scripts/AjaxRequest.js'); require_once('scripts/widgets/windowAux.widget.js'); require_once('scripts/widgets/dbmessageBoard.widget.js');
this.oWindowAux = null; this.oGridValoresMensais = null; this.oDadosFicha = { sDescricao : null, iOrgao : null, iUnidade : null, iRecurso : null, iAnexo : null, nValorOrcado : null, nValorTotal : null, nValor...
ViewFichaFinanceira = function(sNomeInstancia) { this.sNomeInstancia = sNomeInstancia; this.iCodigo = null;
random_line_split
ViewFichaFinanceira.js
LabelProgramar.innerHTML = 'A Programar: '; var oDivGrid = document.createElement('div'); oDivGrid.id = 'divGridValoresMensais'; var oBotaoSalvar = document.createElement('input'); oBotaoSalvar.setAttribute('type', 'button'); oBotaoSalvar.setAttribute('value', 'Salvar'); oBotaoSalvar.setAttrib...
this.buildContainer(); } }
conditional_block
channelmessage.go
FetchMessageIds(q *request.Query) ([]int64, error) { query := &bongo.Query{ Selector: map[string]interface{}{ "account_id": q.AccountId, "type_constant": q.Type, }, Pluck: "id", Pagination: *bongo.NewPagination(q.Limit, q.Skip), Sort: map[string]string{ "created_at": "DESC", }, } query...
cm.Payload = gorm.Hstore{} }
conditional_block
channelmessage.go
, err } if account == nil { return false, fmt.Errorf("account is nil, accountId:%d", c.AccountId) } if account.IsTroll { return true, nil } return false, nil } // Tests are done func (c *ChannelMessage) getAccountId() (int64, error) { if c.AccountId != 0 { return c.AccountId, nil } if c.Id == 0 { ...
} // Tests are done func bodyLenCheck(body string) error { if len(body) < config.MustGet().Limits.MessageBodyMinLen { return fmt.Errorf("message body length should be greater than %d, yours is %d ", config.MustGet().Limits.MessageBodyMinLen, len(body)) } return nil } type messageResponseStruct struct { Index ...
} return cm.AccountId, nil
random_line_split
channelmessage.go
bool, error) { if query.AccountId == 0 { return false, nil } channel := NewChannel() if err := channel.FetchPinnedActivityChannel(query.AccountId, query.GroupName); err != nil { if err == bongo.RecordNotFound { return false, nil } return false, err } cml := NewChannelMessageList() q := &bongo.Query...
opulatePayload(
identifier_name
channelmessage.go
query.Selector["initial_channel_id"] = q.GroupChannelId } if q.AccountId != 0 { query.Selector["account_id"] = q.AccountId } query.AddScope(ExcludeFields(q.Exclude)) query.AddScope(StartFrom(q.From)) query.AddScope(TillTo(q.To)) return query } func (c *ChannelMessage) FetchMessagesByChannelId(channelId i...
newCm := NewChannelMessage() *newCm = *c channelIntegration := c.GetPayload(ChannelMessagePayloadKeyIntegration) if channelIntegration != nil && *channelIntegration != "" { id, err := strconv.ParseInt(*channelIntegration, 10, 64) if err != nil { return c, err } i, err := Cache.Integration.ByChannelInt...
identifier_body
softmax.rs
{} must be less than logits.shape().len() {}", axis, logits.shape().len() ); Softmax { logits, output, axis } } } impl OpSpecification for Softmax { type InstanceType = SoftmaxInstance; fn type_name(&self) -> &'static str { "Softmax" } fn inputs(&self) -> IndexSet<Node> { indexset![self.logits.cl...
(&self, mapping: &IndexMap<Node, Node>) -> Self { Self { logits: mapping.get(&self.logits).unwrap_or(&self.logits).clone(), output_grad: mapping.get(&self.output_grad).unwrap_or(&self.output_grad).clone(), logits_grad: mapping.get(&self.logits_grad).unwrap_or(&self.logits_grad).clone(), axis: self.axis, ...
clone_with_nodes_changed
identifier_name
softmax.rs
{} must be less than logits.shape().len() {}", axis, logits.shape().len() ); Softmax { logits, output, axis } } } impl OpSpecification for Softmax { type InstanceType = SoftmaxInstance; fn type_name(&self) -> &'static str { "Softmax" } fn inputs(&self) -> IndexSet<Node> { indexset![self.logits.cl...
}) } } /// SoftmaxBack OpInstance #[derive(Clone, Debug)] pub struct SoftmaxBackInstance { logits: NodeID, logits_grad: NodeID, output_grad: NodeID, axis: usize, } impl OpInstance for SoftmaxBackInstance { fn type_name(&self) -> &'static str { "SoftmaxBack" } fn as_specification(&self, graph: &Graph) -> ...
axis: self.axis,
random_line_split
softmax.rs
{} must be less than logits.shape().len() {}", axis, logits.shape().len() ); Softmax { logits, output, axis } } } impl OpSpecification for Softmax { type InstanceType = SoftmaxInstance; fn type_name(&self) -> &'static str { "Softmax" } fn inputs(&self) -> IndexSet<Node> { indexset![self.logits.cl...
} /// Softmax OpInstance #[derive(Clone, Debug)] pub struct SoftmaxInstance { logits: NodeID, output: NodeID, axis: usize, } impl OpInstance for SoftmaxInstance { fn type_name(&self) -> &'static str { "Softmax" } fn as_specification(&self, graph: &Graph) -> Box<dyn Any> { Box::new(Softmax { logits: gra...
{ Ok(SoftmaxInstance { logits: self.logits.id(), output: self.output.id(), axis: self.axis, }) }
identifier_body
softmax.rs
{} must be less than logits.shape().len() {}", axis, logits.shape().len() ); Softmax { logits, output, axis } } } impl OpSpecification for Softmax { type InstanceType = SoftmaxInstance; fn type_name(&self) -> &'static str { "Softmax" } fn inputs(&self) -> IndexSet<Node> { indexset![self.logits.cl...
ctx.merge_output_shape(&self.logits_grad, &logits_shape.slice().into()) } fn execute(&self, ctx: &ExecutionContext) -> Result<(), ExecutionError> { Zip::from(ctx.get_output(&self.logits_grad).lanes_mut(Axis(self.axis))) .and(ctx.get_input(&self.logits).lanes(Axis(self.axis))) .and(ctx.get_input(&self.out...
{ return Err(format!("SoftmaxBack requires the output grad to have the shape of the logits: logits:{:?} output_grad:{:?}, axis: {}", logits_shape.slice(), output_grad_shape.slice(), self.axis).into()); }
conditional_block
Image_Video_Download_fromnew_API.py
.parse import m3u8 from pathlib import Path import re import ffmpeg import os headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} def download(video_url): video_player_url_prefix = 'https://twitter.com/i/videos/tweet...
if hasattr(e,'reason'): print (e.reason) except urllib.error.HTTPError as e: if hasattr(e,'code'): print(e.code) if hasattr(e,'reason'): print(e.reason) print('HTTPError!!!') def wr...
print (e.code)
conditional_block
Image_Video_Download_fromnew_API.py
.parse import m3u8 from pathlib import Path import re import ffmpeg import os headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} def
(video_url): video_player_url_prefix = 'https://twitter.com/i/videos/tweet/' video_host = '' output_dir = './output' # Parse the tweet ID video_url = video_url.split('?', 1)[0] tweet_user = video_url.split('/')[3] tweet_id = video_url.split('/')[5] # Grab the video client HTML vide...
download
identifier_name
Image_Video_Download_fromnew_API.py
.parse import m3u8 from pathlib import Path import re import ffmpeg import os headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} def download(video_url): video_player_url_prefix = 'https://twitter.com/i/videos/tweet...
js_file_response = requests.get(js_file_url) # Pull the bearer token out bearer_token_pattern = re.compile('Bearer ([a-zA-Z0-9%-])+') bearer_token = bearer_token_pattern.search(js_file_response.text) bearer_token = bearer_token.group(0) # Talk to the API to get the m3u8 URL api_string = 'h...
js_file_url = js_file_soup.find('script')['src']
random_line_split
Image_Video_Download_fromnew_API.py
.parse import m3u8 from pathlib import Path import re import ffmpeg import os headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} def download(video_url): video_player_url_prefix = 'https://twitter.com/i/videos/tweet...
def find_unique_tweets(unique_tweet_ids,all_tweets): unique_tweets =[] for current_tweet in all_tweets: if str(current_tweet['id']) not in unique_tweet_ids: unique_tweets.append(current_tweet) return unique_tweets def collect_tweets
''' Function that appends tweets to a file. ''' with open(filename, 'a') as f: for tweet in tweets: json.dump(tweet, f) f.write('\n')
identifier_body
main.go
([]int, cst.FindNameMaxResults) highestCost := cst.MaxInt for indexInit := range matchCosts { matchCosts[indexInit] = cst.MaxInt } for indexProject, project := range *projects { currentCost := tools.EditDistance(searchStr, project.Name) if currentCost == 0 { matchCosts[0] = currentCost matchProjects[0...
func filterLvl21InCursusUser(cursusUsers *[]reqAPI42.API42CursusUser) *[]*reqAPI42.API42User { if cursusUsers == nil { return nil } usersLvl21 := make([]*reqAPI42.API42User, 0) for index, cursusUser := range *cursusUsers { if cursusUser.Level >= 21.0 { usersLvl21 = append(usersLvl21, &(*cursusUsers)[index]...
{ if locations == nil { return nil } usersLogged := make(map[uint]*reqAPI42.API42Location) for index := range *locations { if (*locations)[index].User.ID == me.ID { continue } usersLogged[(*locations)[index].User.ID] = &(*locations)[index] } return &usersLogged }
identifier_body
main.go
([]int, cst.FindNameMaxResults) highestCost := cst.MaxInt for indexInit := range matchCosts { matchCosts[indexInit] = cst.MaxInt } for indexProject, project := range *projects { currentCost := tools.EditDistance(searchStr, project.Name) if currentCost == 0 { matchCosts[0] = currentCost matchProjects[0...
} } } matchStrings := make([]string, 0) for _, parent := range matchParent { matchStrings = append(matchStrings, parent.this.Name) } return matchParent, matchStrings, false } func getIndexNameChoice(items []string) int { items = append(items, "Cancel") prompt := promptui.Select{ Label: "Found these...
{ copy(matchCosts[indexMatchCost+1:], matchCosts[indexMatchCost:]) copy(matchParent[indexMatchCost+1:], matchParent[indexMatchCost:]) matchCosts[indexMatchCost] = currentCost matchParent[indexMatchCost] = (*parents)[indexProject] if indexMatchCost+1 == cst.FindNameMaxResults { highestCost...
conditional_block
main.go
make([]int, cst.FindNameMaxResults) highestCost := cst.MaxInt for indexInit := range matchCosts { matchCosts[indexInit] = cst.MaxInt } for indexProject, project := range *projects { currentCost := tools.EditDistance(searchStr, project.Name) if currentCost == 0 { matchCosts[0] = currentCost matchProje...
log.Fatal().Err(err).Msg("PromptUI: failed") } var realProjectsToSearch *[]*reqAPI42.API42Project if indexAction == 0 { parentProjectName := askStringClean("Please, enter the parent project name: ") parentFind, parentsFindNames, fullMatch := findProjectParentName(parentProjectName, &allProjects.parents) if ...
random_line_split
main.go
(searchStr string, projects *[]*reqAPI42.API42Project) ([]*reqAPI42.API42Project, []string, bool) { matchProjects := make([]*reqAPI42.API42Project, cst.FindNameMaxResults) matchCosts := make([]int, cst.FindNameMaxResults) highestCost := cst.MaxInt for indexInit := range matchCosts { matchCosts[indexInit] = cst.M...
findProjectName
identifier_name
analyserUtil.go
) { return govaluate.ParseTokens(statement, nil) } type function struct { t token argc int } func newFunction(t token, argc int) *function { f := function{t: t} switch t.Kind { case govaluate.NUMERIC, govaluate.CLAUSE, govaluate.CLAUSE_CLOSE: f.argc = 0 case govaluate.PREFIX: f.argc = 1 case govaluate....
cators = a
identifier_name
analyserUtil.go
indicatorMap["macdhist"] = makeMACD(true) indicatorMap["macdoscillator"] = makeMACD(true) // RSI indicatorMap["rsi"] = makeRSI() // Close Price funcClose := makeClosePrice() indicatorMap["close"] = funcClose indicatorMap["price"] = funcClose indicatorMap["closeprice"] = funcClose // Increase indicatorMap[...
indicatorMap["macd"] = makeMACD(false)
random_line_split
analyserUtil.go
= funcMoneyFlow indicatorMap["mFlow"] = funcMoneyFlow indicatorMap["mflow"] = funcMoneyFlow // Zero funcIsZero := makeIsZero() indicatorMap["isZero"] = funcIsZero indicatorMap["iszero"] = funcIsZero indicatorMap["zero"] = funcIsZero } func cacheRules() { appendRuleComparer := func(op string, ctor func(lhs, r...
tokens)[fcnNameIdx]]++ tokenIdx += idxToSkip } else { // ์ธ์ž๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ ๊ด„ํ˜ธ๋ฅผ ์ƒ๋žตํ•˜๊ธฐ๋„ ํ•จ // ์ด์— ๋Œ€ํ•œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ if tokenIdx < endIdx && (*tokens)[tokenIdx+1].Kind != govaluate.CLAUSE { result[t] = 0 tokenIdx++ continue } startedSearch = true fcnNameIdx = tokenIdx result[t] = 0 tokenId...
:= subFuncArgs[subFunc] result[subFunc] = subArgc } result[(*
conditional_block
analyserUtil.go
funcMoneyFlow indicatorMap["mFlow"] = funcMoneyFlow indicatorMap["mflow"] = funcMoneyFlow // Zero funcIsZero := makeIsZero() indicatorMap["isZero"] = funcIsZero indicatorMap["iszero"] = funcIsZero indicatorMap["zero"] = funcIsZero } func cacheRules() { appendRuleComparer := func(op string, ctor func(lhs, rhs...
return closeMap, err } func reorderTokenByPostfix(tokens []token) ([]function, erro r) { // Convert tokens into techan strategy // Tokens are reordered by postfix notation // operators: // functions: 8 // -: 7(Negation) // * /: 6 // + -: 5 // < <= == >= >: 4 // &...
lausePair) err = nil for idx, tok := range *tokens { if tok.Kind == govaluate.CLAUSE { stack = append(stack, &clausePair{idx, -1}) } else if tok.Kind == govaluate.CLAUSE_CLOSE { if len(stack) == 0 { return nil, newError("Invalid pairing of clauses: Pairs do not match.") } popped := stack[len(stac...
identifier_body
index.umd.js
webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns);...
buildResource
identifier_name
index.umd.js
modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/...
if (typeof id === 'string' && method instanceof Object) { result = parameters; parameters = method; method = id; id = null; } return this.axios(result, { url: this.url + (id ? '/' + id : ''), method: "post", data: { call: { method, param...
call(id, method = {}, parameters = {}, result = null) {
random_line_split
index.umd.js
object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!_...
get(params = {}, response = null, url = this.url) { return this.axios(response, { url, method: "get", params }); } post(data = {}, response = null, url = this.url) { return this.axios(response, { url, method: "post", data: { data } }); } /**...
{ return record instanceof Array ? this.index(params, record.splice(0, record.length, ...(initial || [])) && record).then(data => data.data) : this.load(record.id, params, record); }
identifier_body
mod.rs
be spawned on it by calling the [`spawn`][`Executor::spawn`] /// method on the `ThreadPool`. Note that since this executor moves futures between different /// threads, the future in question *must* be [`Send`]. /// /// # Examples /// ``` /// use std::io; /// use threader::{ /// executor::Executor, /// thread_p...
(&mut self, shutdown: usize) { self.shutdown = true; for (_, handle) in &self.workers { handle.state.store(shutdown, Ordering::Release); handle.unparker.unpark(); } while let Some((thread, _)) = self.workers.pop() { let _ = thread.join(); } ...
shutdown_priv
identifier_name
mod.rs
be spawned on it by calling the [`spawn`][`Executor::spawn`] /// method on the `ThreadPool`. Note that since this executor moves futures between different /// threads, the future in question *must* be [`Send`]. /// /// # Examples /// ``` /// use std::io; /// use threader::{ /// executor::Executor, /// thread_p...
}); CustomFuture { waker, shared } } } impl Future for CustomFuture { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { if self.shared.load(Ordering::SeqCst) { ...
{ waker.wake(); shared_thread.store(true, Ordering::SeqCst); }
conditional_block