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
decl.go
// Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package noder import ( "go/constant" "cmd/compile/internal/base" "cmd/compile/internal/ir" "cmd/compile/internal/syntax" "cmd/compile/internal/typecheck"...
(info *types2.Info, decl *syntax.ImportDecl) *types2.PkgName { if name := decl.LocalPkgName; name != nil { return info.Defs[name].(*types2.PkgName) } return info.Implicits[decl].(*types2.PkgName) } func (g *irgen) constDecl(out *ir.Nodes, decl *syntax.ConstDecl) { g.pragmaFlags(decl.Pragma, 0) for _, name := r...
pkgNameOf
identifier_name
decl.go
// Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package noder import ( "go/constant" "cmd/compile/internal/base" "cmd/compile/internal/ir" "cmd/compile/internal/syntax" "cmd/compile/internal/typecheck"...
// // type T U // // //go:notinheap // type U struct { … } // // we mark both T and U as NotInHeap. If we instead used just // g.typ(otyp.Underlying()), then we'd instead set T's underlying // type directly to the struct type (which is not marked NotInHeap) // and fail to mark T as NotInHeap. // // Also, we...
ntyp.SetNotInHeap(true) } // We need to use g.typeExpr(decl.Type) here to ensure that for // chained, defined-type declarations like:
random_line_split
decl.go
// Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package noder import ( "go/constant" "cmd/compile/internal/base" "cmd/compile/internal/ir" "cmd/compile/internal/syntax" "cmd/compile/internal/typecheck"...
for _, pos := range pragma.Pos { if pos.Flag&pragma.Flag != 0 { base.ErrorfAt(g.makeXPos(pos.Pos), "misplaced compiler directive") } } if len(pragma.Embeds) > 0 { for _, e := range pragma.Embeds { base.ErrorfAt(g.makeXPos(e.Pos), "misplaced go:embed directive") } } }
identifier_body
test_automl.py
# pylint: disable=C0321,C0103,E1221,C0301,E1305,E1121,C0302,C0330 # -*- coding: utf-8 -*- """ https://github.com/mljar/mljar-supervised python test_automl.py train > zlog/log_titanic_train.txt 2>&1 python test_automl.py predict > zlog/log_titanic_predict.txt 2>&1 conda install -c conda-forge fastparquet...
(df=None, col=None, pars={}): """ Example of custom Processor """ from source.util_feature import save, load prefix = 'col_myfun`' if 'path_pipeline' in pars : #### Inference time LOAD previous pars prepro = load(pars['path_pipeline'] + f"/{prefix}_model.pkl" ) pars ...
pd_col_myfun
identifier_name
test_automl.py
# pylint: disable=C0321,C0103,E1221,C0301,E1305,E1121,C0302,C0330 # -*- coding: utf-8 -*- """ https://github.com/mljar/mljar-supervised python test_automl.py train > zlog/log_titanic_train.txt 2>&1 python test_automl.py predict > zlog/log_titanic_predict.txt 2>&1 conda install -c conda-forge fastparquet...
col_pars = {'prefix' : prefix , 'path' : pars.get('path_pipeline_export', pars.get('path_pipeline', None)) } col_pars['cols_new'] = { 'col_myfun' : cols_new ### list } return df_new, col_pars ##################################################################################### ########...
save(prepro, pars['path_pipeline_export'] + f"/{prefix}_model.pkl" ) save(cols_new, pars['path_pipeline_export'] + f"/{prefix}.pkl" ) save(pars_new, pars['path_pipeline_export'] + f"/{prefix}_pars.pkl" )
conditional_block
test_automl.py
# pylint: disable=C0321,C0103,E1221,C0301,E1305,E1121,C0302,C0330 # -*- coding: utf-8 -*- """ https://github.com/mljar/mljar-supervised python test_automl.py train > zlog/log_titanic_train.txt 2>&1 python test_automl.py predict > zlog/log_titanic_predict.txt 2>&1 conda install -c conda-forge fastparquet...
def pre_process_fun(y): ### Before the prediction is done return int(y) model_dict = {'model_pars': { ### LightGBM API model ####################################### 'model_class': model_class ,'model_pars' : { 'total_time_limit' : 20, 'algorithm...
return int(y)
identifier_body
test_automl.py
# pylint: disable=C0321,C0103,E1221,C0301,E1305,E1121,C0302,C0330 # -*- coding: utf-8 -*- """ https://github.com/mljar/mljar-supervised python test_automl.py train > zlog/log_titanic_train.txt 2>&1 python test_automl.py predict > zlog/log_titanic_predict.txt 2>&1 conda install -c conda-forge fastparquet...
run_preprocess.run_preprocess(config_name = config_name, config_path = m['config_path'], n_sample = nsample if nsample is not None else m['n_sample'], ### Optonal mode...
print(mdict) from source import run_preprocess
random_line_split
mod.rs
use std::{ cell::{Ref, RefCell}, ops::RangeInclusive, rc::Rc, }; pub type Time = f32; use crate::Pose; /// Aggregate of [`ColumnData`] that can only be added and not deleted. /// Length of all [`ColumnData`] are equal, making this effectively a 2D table. pub type DataSet<T = f32> = Vec<ColumnData<T>>; //...
(timeseries: TimeSeries<T>) -> Self { Self { time: timeseries.time, data: vec![timeseries.data], } } } impl<T: Clone> TimeTable<T> { pub fn new(time: Vec<Time>, data: Vec<T>) -> Self { TimeSeries::new(time, data).into() } #[allow(dead_code)] pub fn g...
from_timeseries
identifier_name
mod.rs
use std::{ cell::{Ref, RefCell}, ops::RangeInclusive, rc::Rc, }; pub type Time = f32; use crate::Pose; /// Aggregate of [`ColumnData`] that can only be added and not deleted. /// Length of all [`ColumnData`] are equal, making this effectively a 2D table. pub type DataSet<T = f32> = Vec<ColumnData<T>>; //...
pub fn get_range_raw(&self, start: Time, end: Time) -> Option<Vec<Time>> { self.get_range(start, end) .map(|range| self.vec[range].to_vec()) } /// Length of the time vector pub fn len(&self) -> usize { self.vec.len() } } #[derive(Debug, Default)] pub struct TimeTable<...
{ if start < end { if let Some(start) = self.get_index(start) { if let Some(end) = self.get_index_under(end) { return Some(start..=end); } } } None }
identifier_body
mod.rs
use std::{ cell::{Ref, RefCell}, ops::RangeInclusive, rc::Rc, }; pub type Time = f32; use crate::Pose; /// Aggregate of [`ColumnData`] that can only be added and not deleted. /// Length of all [`ColumnData`] are equal, making this effectively a 2D table. pub type DataSet<T = f32> = Vec<ColumnData<T>>; //...
} /// Similar to [`get_index`], but only returns time index that is smaller than the input time. /// This is useful when making sure the returned time index never exceeds the given time, as /// in [`get_range`] /// /// [`get_index`]: Self::get_index /// [`get_range`]: Self::get_range f...
{ // unwrap here is ok, since time_changed always ensures cache is not None Some(self.cache.unwrap().1) }
conditional_block
mod.rs
use std::{ cell::{Ref, RefCell}, ops::RangeInclusive, rc::Rc, }; pub type Time = f32; use crate::Pose; /// Aggregate of [`ColumnData`] that can only be added and not deleted. /// Length of all [`ColumnData`] are equal, making this effectively a 2D table. pub type DataSet<T = f32> = Vec<ColumnData<T>>; //...
// self.cache = Some((time, index)); index }) } else { // unwrap here is ok, since time_changed always ensures cache is not None Some(self.cache.unwrap().1) } } /// Similar to [`get_index`], but only returns time index that is ...
if self.time_changed(time) { self.vec.iter().position(|&t| t >= time).map(|index| {
random_line_split
main.rs
// Copyright 2021 The Simlin Authors. All rights reserved. // Use of this source code is governed by the Apache License, // Version 2.0, that can be found in the LICENSE file. use std::fs::File; use std::io::{BufReader, Write}; use std::rc::Rc; use pico_args::Arguments; use simlin_compat::engine::builtins::Loc; use ...
else { let results = simulate(&project); if !args.is_no_output { results.print_tsv(); } } }
{ if args.reference.is_none() { eprintln!("missing required argument --reference FILE"); std::process::exit(1); } let ref_path = args.reference.unwrap(); let reference = load_csv(&ref_path, b'\t').unwrap(); let results = simulate(&project); result...
conditional_block
main.rs
// Copyright 2021 The Simlin Authors. All rights reserved. // Use of this source code is governed by the Apache License, // Version 2.0, that can be found in the LICENSE file. use std::fs::File; use std::io::{BufReader, Write}; use std::rc::Rc; use pico_args::Arguments; use simlin_compat::engine::builtins::Loc; use ...
fn main() { let args = match parse_args() { Ok(args) => args, Err(err) => { eprintln!("error: {}", err); usage(); } }; let file_path = args.path.unwrap_or_else(|| "/dev/stdin".to_string()); let file = File::open(&file_path).unwrap(); let mut reader = ...
vm.into_results() }
random_line_split
main.rs
// Copyright 2021 The Simlin Authors. All rights reserved. // Use of this source code is governed by the Apache License, // Version 2.0, that can be found in the LICENSE file. use std::fs::File; use std::io::{BufReader, Write}; use std::rc::Rc; use pico_args::Arguments; use simlin_compat::engine::builtins::Loc; use ...
() -> ! { let argv0 = std::env::args() .next() .unwrap_or_else(|| "<mdl>".to_string()); die!( concat!( "mdl {}: Simulate system dynamics models.\n\ \n\ USAGE:\n", " {} [SUBCOMMAND] [OPTION...] PATH\n", "\n\ OPTIONS:\n", ...
usage
identifier_name
snippet-bot.ts
// Copyright 2020 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
// If the head repo is null, we can not proceed. if ( context.payload.pull_request.head.repo === undefined || context.payload.pull_request.head.repo === null ) { logger.info( `The head repo is undefined for ${context.payload.pull_request.url}, exiting.` ); ...
logger.info( `The pull request ${context.payload.pull_request.url} is closed, exiting.` ); return; }
conditional_block
snippet-bot.ts
// Copyright 2020 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
(dir: string, allFiles: string[]) { const files = (await pfs.readdir(dir)).map(f => path.join(dir, f)); for (const f of files) { if (!(await pfs.stat(f)).isDirectory()) { allFiles.push(f); } } await Promise.all( files.map( async f => (await pfs.stat(f)).isDirectory() && getFiles(f, allFi...
getFiles
identifier_name
snippet-bot.ts
// Copyright 2020 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
xport = (app: Probot) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any app.on('schedule.repository' as any, async context => { const owner = context.payload.organization.login; const repo = context.payload.repository.name; const configOptions = await getConfig<ConfigurationOptions>( ...
return `<!-- probot comment [${installationId}]-->`; } e
identifier_body
snippet-bot.ts
// Copyright 2020 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
configuration, parseResults, pull_request.base.repo.full_name, pull_request.base.ref ); const removeUsedTagViolations = [ ...(removingUsedTagsViolations.get('REMOVE_USED_TAG') as Violation[]), ...(removingUsedTagsViolations.get( 'REMOVE_CONFLICTING_TAG' ) as Violation[]), ]; co...
result,
random_line_split
class_system_1_1_class_type.js
var class_system_1_1_class_type = [ [ "ClassType", "class_system_1_1_class_type.html#a6b4c4fc5b96b487e7a01ffd474996be0", null ], [ "~ClassType", "class_system_1_1_class_type.html#a9bd32e140623554f512e1606a11f3e28", null ], [ "Clone", "class_system_1_1_class_type.html#ae07dbc768b7946e4791f76ae093d983b", null...
[ "m_copyOperator", "class_system_1_1_class_type.html#a908aaf2b4a33416ecf6fe4bda27ecd9a", null ], [ "m_decrementOperator", "class_system_1_1_class_type.html#a86fde0d4bc7adb2916588b4c424685d2", null ], [ "m_decrementOperatorConst", "class_system_1_1_class_type.html#a44606633d535d3cc9d1d63d061d62519", null ],...
[ "m_classUserData", "class_system_1_1_class_type.html#a8e410f39f3a150f214a4f93b6f9e4273", null ], [ "m_complementOperator", "class_system_1_1_class_type.html#a39bc6cb62342bd90a8681b0112ee9eaf", null ], [ "m_complementOperatorConst", "class_system_1_1_class_type.html#aac639396e1a7aa5bf5121a4dbd0f65e6", null...
random_line_split
ui.rs
use std::collections::{HashSet, HashMap, VecDeque}; use std::any::{Any, TypeId}; use std::rc::Rc; use std::cell::RefCell; use cassowary::Constraint; use cassowary::strength::*; use glutin; use window::Window; use app::App; use widget::{WidgetRef, WidgetBuilder}; use layout::{LimnSolver, LayoutChanged, LayoutVars, Ex...
pub fn needs_redraw(&self) -> bool { self.needs_redraw } pub(super) fn draw_if_needed(&mut self) { if self.needs_redraw { self.draw(); self.needs_redraw = false; } } fn draw(&mut self) { let window_size = self.window.borrow_mut().size_f32()...
{ self.needs_redraw = true; }
identifier_body
ui.rs
use std::collections::{HashSet, HashMap, VecDeque}; use std::any::{Any, TypeId}; use std::rc::Rc; use std::cell::RefCell; use cassowary::Constraint; use cassowary::strength::*; use glutin; use window::Window; use app::App; use widget::{WidgetRef, WidgetBuilder}; use layout::{LimnSolver, LayoutChanged, LayoutVars, Ex...
(root: WidgetRef) -> Self { WidgetsDfsPostReverse { stack: vec![root], discovered: HashSet::new(), finished: HashSet::new(), } } } impl Iterator for WidgetsDfsPostReverse { type Item = WidgetRef; fn next(&mut self) -> Option<WidgetRef> { while let...
new
identifier_name
ui.rs
use std::collections::{HashSet, HashMap, VecDeque}; use std::any::{Any, TypeId}; use std::rc::Rc; use std::cell::RefCell; use cassowary::Constraint; use cassowary::strength::*; use glutin; use window::Window; use app::App; use widget::{WidgetRef, WidgetBuilder}; use layout::{LimnSolver, LayoutChanged, LayoutVars, Ex...
} None } } // Iterates in reverse of draw order, that is, depth first post order, // with siblings in reverse of insertion order struct WidgetsDfsPostReverse { stack: Vec<WidgetRef>, discovered: HashSet<WidgetRef>, finished: HashSet<WidgetRef>, } impl WidgetsDfsPostReverse { fn ne...
{ return Some(widget_ref.clone()); }
conditional_block
ui.rs
use std::collections::{HashSet, HashMap, VecDeque}; use std::any::{Any, TypeId}; use std::rc::Rc; use std::cell::RefCell; use cassowary::Constraint; use cassowary::strength::*; use glutin; use window::Window; use app::App; use widget::{WidgetRef, WidgetBuilder}; use layout::{LimnSolver, LayoutChanged, LayoutVars, Ex...
dfs: WidgetsDfsPostReverse, } impl WidgetsUnderCursor { fn new(point: Point, root: WidgetRef) -> Self { WidgetsUnderCursor { point: point, dfs: WidgetsDfsPostReverse::new(root), } } } impl Iterator for WidgetsUnderCursor { type Item = WidgetRef; fn next(&mut ...
} pub struct WidgetsUnderCursor { point: Point,
random_line_split
differ_test.go
// Copyright (c) 2018 Couchbase, 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 applicable law or agreed to in writin...
fmt.Println("============== Test case start: TestLoadSameFile =================") assert := assert.New(t) file1 := "/tmp/test1.bin" file2 := "/tmp/test2.bin" defer os.Remove(file1) defer os.Remove(file2) entries := 10000 err := genSameFiles(entries, file1, file2) assert.Equal(nil, err) differ := NewFilesD...
func TestLoadSameFile(t *testing.T) {
random_line_split
differ_test.go
// Copyright (c) 2018 Couchbase, 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 applicable law or agreed to in writin...
return retSlice } func genSameFiles(numOfRecords int, fileName1, fileName2 string) error { data := genMultipleRecords(numOfRecords) err := ioutil.WriteFile(fileName1, data, 0644) if err != nil { return err } err = ioutil.WriteFile(fileName2, data, 0644) if err != nil { return err } return nil } func...
{ _, _, _, _, _, _, _, _, record, _, _ := genTestData(true, false) retSlice = append(retSlice, record...) }
conditional_block
differ_test.go
// Copyright (c) 2018 Couchbase, 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 applicable law or agreed to in writin...
(t *testing.T) { assert := assert.New(t) var outputFileTemp string = "/tmp/xdcrDiffer.tmp" defer os.Remove(outputFileTemp) key, seqno, _, _, _, _, _, _, data, _, _ := genTestData(true, false) err := ioutil.WriteFile(outputFileTemp, data, 0644) assert.Nil(err) differ := NewFilesDiffer(outputFileTemp, "", nil, ...
TestLoader
identifier_name
differ_test.go
// Copyright (c) 2018 Couchbase, 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 applicable law or agreed to in writin...
func verifyMisMatch(mismatchKeys []string, differ *FilesDiffer) bool { for _, key := range mismatchKeys { found := false for _, onePair := range differ.BothExistButMismatch { if key == onePair[0].Key { found = true break } } if !found { return false } } return true } func TestLoader(t *...
{ var mismatchedKeyNames []string data := genMultipleRecords(numOfRecords - mismatchCnt) err := ioutil.WriteFile(fileName1, data, 0644) if err != nil { return mismatchedKeyNames, err } err = ioutil.WriteFile(fileName2, data, 0644) if err != nil { return mismatchedKeyNames, err } // Now create mismatched...
identifier_body
ndt-server_test.go
package main import ( "context" "io/ioutil" "log" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "runtime" "sync" "testing" "time" "github.com/m-lab/go/osx" "github.com/m-lab/go/prometheusx/promtest" "github.com/m-lab/go/rtx" pipe "gopkg.in/m-lab/pipe.v3" ) // Get a bunch of open port...
} } func Test_ContextCancelsMain(t *testing.T) { // Set up certs and the environment vars for the commandline. cleanup := setupMain() defer cleanup() // Set up the global context for main() ctx, cancel = context.WithCancel(context.Background()) before := runtime.NumGoroutine() // Run main, but cancel it ver...
{ f() }
conditional_block
ndt-server_test.go
package main import ( "context" "io/ioutil" "log" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "runtime" "sync" "testing" "time" "github.com/m-lab/go/osx" "github.com/m-lab/go/prometheusx/promtest" "github.com/m-lab/go/rtx" pipe "gopkg.in/m-lab/pipe.v3" ) // Get a bunch of open port...
cmd: "timeout 45s node ./testdata/unittest_client.js --server=localhost " + " --port=" + wssAddr + " --protocol=wss --acceptinvalidcerts --abort-c2s-early --tests=22 & " + "sleep 25", }, // Test NDT7 clients { name: "Test the ndt7 protocol", cmd: "timeout 45s ndt7-client -no-verify -hostname...
name: "Upload & Download ndt5 WSS with S2C Timeout",
random_line_split
ndt-server_test.go
package main import ( "context" "io/ioutil" "log" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "runtime" "sync" "testing" "time" "github.com/m-lab/go/osx" "github.com/m-lab/go/prometheusx/promtest" "github.com/m-lab/go/rtx" pipe "gopkg.in/m-lab/pipe.v3" ) // Get a bunch of open port...
func Test_MainIntegrationTest(t *testing.T) { if testing.Short() { t.Skip("Integration tests take too long") } // Set up certs and the environment vars for the commandline. cleanup := setupMain() defer cleanup() // Set up the global context for main() ctx, cancel = context.WithCancel(context.Background()) ...
{ promtest.LintMetrics(t) }
identifier_body
ndt-server_test.go
package main import ( "context" "io/ioutil" "log" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "runtime" "sync" "testing" "time" "github.com/m-lab/go/osx" "github.com/m-lab/go/prometheusx/promtest" "github.com/m-lab/go/rtx" pipe "gopkg.in/m-lab/pipe.v3" ) // Get a bunch of open port...
(t *testing.T) { promtest.LintMetrics(t) } func Test_MainIntegrationTest(t *testing.T) { if testing.Short() { t.Skip("Integration tests take too long") } // Set up certs and the environment vars for the commandline. cleanup := setupMain() defer cleanup() // Set up the global context for main() ctx, cancel =...
TestMetrics
identifier_name
basic_model.py
import time import sys sys.path.insert(0,"/content/FakeNewsPropagation") import matplotlib import numpy as np from sklearn import preprocessing, svm from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score...
get_classificaton_results_tpnf("data/features", "politifact", time_interval=None, use_cache=False) print("\n\n Working on Gossipcop Data \n") get_classificaton_results_tpnf("data/features", "gossipcop", time_interval=None, use_cache=False) # Filter the graphs by time interval (for early fake news dete...
#dump_random_forest_feature_importance("data/features", "politifact") print("\n\n Working on Politifact Data \n")
random_line_split
basic_model.py
import time import sys sys.path.insert(0,"/content/FakeNewsPropagation") import matplotlib import numpy as np from sklearn import preprocessing, svm from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score...
(classifier_name, X_train, X_test, y_train, y_test): accuracy_values = [] precision_values = [] recall_values = [] f1_score_values = [] for i in range(6): classifier_clone = get_classifier_by_name(classifier_name) classifier_clone.fit(X_train, y_train) predicted_output = cl...
train_model
identifier_name
basic_model.py
import time import sys sys.path.insert(0,"/content/FakeNewsPropagation") import matplotlib import numpy as np from sklearn import preprocessing, svm from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score...
def get_classificaton_results_tpnf_by_time(news_source: str): # Time Interval in hours for early-fake news detection time_intervals = [3, 6, 12, 24, 36, 48, 60, 72, 84, 96] for time_interval in time_intervals: print("=============Time Interval : {} ==========".format(time_interval)) sta...
include_micro = True include_macro = True include_structural = True include_temporal = True include_linguistic = True sample_feature_array = get_TPNF_dataset(data_dir, news_source, include_micro, include_macro, include_structural, include_temporal, inclu...
identifier_body
basic_model.py
import time import sys sys.path.insert(0,"/content/FakeNewsPropagation") import matplotlib import numpy as np from sklearn import preprocessing, svm from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score...
else: return KNeighborsClassifier(n_neighbors=3) def train_model(classifier_name, X_train, X_test, y_train, y_test): accuracy_values = [] precision_values = [] recall_values = [] f1_score_values = [] for i in range(6): classifier_clone = get_classifier_by_name(classifier_name) ...
return AdaBoostClassifier(n_estimators=100, random_state=0)
conditional_block
check.rs
//! Consensus check functions use std::{collections::HashSet, sync::Arc}; use chrono::{DateTime, Utc}; use zebra_chain::{ amount::{Amount, Error as AmountError, NonNegative}, block::{Block, Hash, Header, Height}, parameters::{Network, NetworkUpgrade}, transaction, work::{difficulty::ExpandedDiffi...
/// Returns `Ok(())` if the block subsidy in `block` is valid for `network` /// /// [3.9]: https://zips.z.cash/protocol/protocol.pdf#subsidyconcepts pub fn subsidy_is_valid(block: &Block, network: Network) -> Result<(), BlockError> { let height = block.coinbase_height().ok_or(SubsidyError::NoCoinbase)?; let c...
{ // # Consensus // // > `solution` MUST represent a valid Equihash solution. // // https://zips.z.cash/protocol/protocol.pdf#blockheader header.solution.check(header) }
identifier_body
check.rs
//! Consensus check functions use std::{collections::HashSet, sync::Arc}; use chrono::{DateTime, Utc}; use zebra_chain::{ amount::{Amount, Error as AmountError, NonNegative}, block::{Block, Hash, Header, Height}, parameters::{Network, NetworkUpgrade}, transaction, work::{difficulty::ExpandedDiffi...
( block: &Block, network: Network, block_miner_fees: Amount<NonNegative>, ) -> Result<(), BlockError> { let height = block.coinbase_height().ok_or(SubsidyError::NoCoinbase)?; let coinbase = block.transactions.get(0).ok_or(SubsidyError::NoCoinbase)?; let transparent_value_balance: Amount = subsi...
miner_fees_are_valid
identifier_name
check.rs
//! Consensus check functions use std::{collections::HashSet, sync::Arc}; use chrono::{DateTime, Utc}; use zebra_chain::{ amount::{Amount, Error as AmountError, NonNegative}, block::{Block, Hash, Header, Height}, parameters::{Network, NetworkUpgrade}, transaction, work::{difficulty::ExpandedDiffi...
// // https://zips.z.cash/protocol/protocol.pdf#blockheader header.solution.check(header) } /// Returns `Ok(())` if the block subsidy in `block` is valid for `network` /// /// [3.9]: https://zips.z.cash/protocol/protocol.pdf#subsidyconcepts pub fn subsidy_is_valid(block: &Block, network: Network) -> Result...
// # Consensus // // > `solution` MUST represent a valid Equihash solution.
random_line_split
check.rs
//! Consensus check functions use std::{collections::HashSet, sync::Arc}; use chrono::{DateTime, Utc}; use zebra_chain::{ amount::{Amount, Error as AmountError, NonNegative}, block::{Block, Hash, Header, Height}, parameters::{Network, NetworkUpgrade}, transaction, work::{difficulty::ExpandedDiffi...
} /// Returns `Ok(())` if the miner fees consensus rule is valid. /// /// [7.1.2]: https://zips.z.cash/protocol/protocol.pdf#txnconsensus pub fn miner_fees_are_valid( block: &Block, network: Network, block_miner_fees: Amount<NonNegative>, ) -> Result<(), BlockError> { let height = block.coinbase_heigh...
{ // Future halving, with no founders reward or funding streams Ok(()) }
conditional_block
alias.rs
import syntax::{ast, ast_util}; import ast::{ident, fn_ident, node_id}; import syntax::codemap::span; import syntax::visit; import visit::vt; import core::{vec, option}; import std::list; import option::{some, none, is_none}; import list::list; // This is not an alias-analyser (though it would merit from becoming one,...
} } ast::pat_box(p) { let ty = ty::node_id_to_type(tcx, pat.id); let m = alt ty::struct(tcx, ty) { ty::ty_box(mt) { mt.mut != ast::imm } }; walk(tcx, m ? some(contains(ty)) : mut, p, set); } ast::pat_uniq(p...
let ty = ty::node_id_to_type(tcx, pat.id); for f in fs { let m = ty::get_field(tcx, ty, f.ident).mt.mut != ast::imm; walk(tcx, m ? some(contains(ty)) : mut, f.pat, set);
random_line_split
alias.rs
import syntax::{ast, ast_util}; import ast::{ident, fn_ident, node_id}; import syntax::codemap::span; import syntax::visit; import visit::vt; import core::{vec, option}; import std::list; import option::{some, none, is_none}; import list::list; // This is not an alias-analyser (though it would merit from becoming one...
} // Local Variables: // mode: rust // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // End:
{ cx.tcx.sess.span_err(sp, err); }
conditional_block
alias.rs
import syntax::{ast, ast_util}; import ast::{ident, fn_ident, node_id}; import syntax::codemap::span; import syntax::visit; import visit::vt; import core::{vec, option}; import std::list; import option::{some, none, is_none}; import list::list; // This is not an alias-analyser (though it would merit from becoming one...
fn check_lval(cx: @ctx, dest: @ast::expr, sc: scope, v: vt<scope>) { alt dest.node { ast::expr_path(p) { let def = cx.tcx.def_map.get(dest.id); let dnum = ast_util::def_id_of_def(def).node; for b in sc.bs { if b.root_var == some(dnum) { let inv = @{reason:...
{ let def = cx.tcx.def_map.get(id); if !def_is_local(def) { ret; } let my_defnum = ast_util::def_id_of_def(def).node; let my_local_id = local_id_of_node(cx, my_defnum); let var_t = ty::expr_ty(cx.tcx, ex); for b in sc.bs { // excludes variables introduced since the alias was made ...
identifier_body
alias.rs
import syntax::{ast, ast_util}; import ast::{ident, fn_ident, node_id}; import syntax::codemap::span; import syntax::visit; import visit::vt; import core::{vec, option}; import std::list; import option::{some, none, is_none}; import list::list; // This is not an alias-analyser (though it would merit from becoming one...
(from: option::t<unsafe_ty>) -> [unsafe_ty] { alt from { some(t) { [t] } _ { [] } } } fn find_invalid(id: node_id, lst: list<@invalid>) -> option::t<@invalid> { let cur = lst; while true { alt cur { list::nil. { break; } list::cons(head, tail) { if head.node_id =...
unsafe_set
identifier_name
core.go
package core import ( "errors" "fmt" "regexp" "unicode/utf8" dht "gx/ipfs/QmSY3nkMNLzh9GdbFKK5tT7YMfLpf52iUZ8ZRkr29MJaa5/go-libp2p-kad-dht" libp2p "gx/ipfs/QmTW4SdgBWq9GjsBsHeUx8WuGxzhgzAf88UMH2w62PC8yK/go-libp2p-crypto" ma "gx/ipfs/QmTZBfrPJmjWsCvHEtX5FE6KimVJhsJg5sBbqEFYf4UZtL/go-multiaddr" cid "gx/ipfs/QmT...
// RegressionNetworkEnabled indicates whether the node is operating with regression parameters func (n *OpenBazaarNode) RegressionNetworkEnabled() bool { return n.RegressionTestEnable } // SeedNode - publish to IPNS func (n *OpenBazaarNode) SeedNode() error { n.seedLock.Lock() ipfs.UnPinDir(n.IpfsNode, n.RootHash)...
{ return n.TestnetEnable }
identifier_body
core.go
package core import ( "errors" "fmt" "regexp" "unicode/utf8" dht "gx/ipfs/QmSY3nkMNLzh9GdbFKK5tT7YMfLpf52iUZ8ZRkr29MJaa5/go-libp2p-kad-dht" libp2p "gx/ipfs/QmTW4SdgBWq9GjsBsHeUx8WuGxzhgzAf88UMH2w62PC8yK/go-libp2p-crypto" ma "gx/ipfs/QmTZBfrPJmjWsCvHEtX5FE6KimVJhsJg5sBbqEFYf4UZtL/go-multiaddr" cid "gx/ipfs/QmT...
(interval time.Duration) { if interval == 0 { return } ticker := time.NewTicker(interval) go func() { for range ticker.C { n.UpdateFollow() n.SeedNode() } }() } /*EncryptMessage This is a placeholder until the libsignal is operational. For now we will just encrypt outgoing offline messages with the ...
SetUpRepublisher
identifier_name
core.go
package core import ( "errors" "fmt" "regexp" "unicode/utf8" dht "gx/ipfs/QmSY3nkMNLzh9GdbFKK5tT7YMfLpf52iUZ8ZRkr29MJaa5/go-libp2p-kad-dht" libp2p "gx/ipfs/QmTW4SdgBWq9GjsBsHeUx8WuGxzhgzAf88UMH2w62PC8yK/go-libp2p-crypto" ma "gx/ipfs/QmTZBfrPJmjWsCvHEtX5FE6KimVJhsJg5sBbqEFYf4UZtL/go-multiaddr" cid "gx/ipfs/QmT...
err := n.sendToPushNodes(hash) if err != nil { log.Error(err) return } inflightPublishRequests++ err = ipfs.Publish(n.IpfsNode, hash) inflightPublishRequests-- if inflightPublishRequests == 0 { if err != nil { log.Error(err) n.Broadcast <- repo.StatusNotification{Status: "error publishing"} } e...
{ n.Broadcast <- repo.StatusNotification{Status: "publishing"} }
conditional_block
core.go
package core import ( "errors" "fmt" "regexp" "unicode/utf8" dht "gx/ipfs/QmSY3nkMNLzh9GdbFKK5tT7YMfLpf52iUZ8ZRkr29MJaa5/go-libp2p-kad-dht" libp2p "gx/ipfs/QmTW4SdgBWq9GjsBsHeUx8WuGxzhgzAf88UMH2w62PC8yK/go-libp2p-crypto" ma "gx/ipfs/QmTZBfrPJmjWsCvHEtX5FE6KimVJhsJg5sBbqEFYf4UZtL/go-multiaddr" cid "gx/ipfs/QmT...
continue } c, err := cid.Decode(s) if err != nil { continue } graph = append(graph, c) } } } for _, p := range n.PushNodes { go n.retryableSeedStoreToPeer(p, hash, graph) } return nil } func (n *OpenBazaarNode) retryableSeedStoreToPeer(pid peer.ID, graphHash string, graph []ci...
random_line_split
BaceraGeneTestingProjectExpressGrid.js
var rowEditing = Ext.create('Ext.grid.plugin.RowEditing',{ pluginId:'rowEditing', saveBtnText: '保存', cancelBtnText: "取消", autoCancel: false, clicksToEdit:2 //双击进行修改 1-单击 2-双击 0-可取消双击/单击事件 }); Ext.define('Rds.bacera.panel.BaceraGeneTestingProjectExpr...
method: "POST", headers: { 'Content-Type': 'application/json' }, jsonData: { id:s.record.data.id, num:s.record.data.test_number, expressnum:s.record.data.expressnum, recive:s.record.data.recive, expresstime:(Ext.Date.format(new Date(), 'Y-m-d')), cas...
Ext.Ajax.request({ url:"bacera/Gene/saveGeneExpress.do",
conditional_block
BaceraGeneTestingProjectExpressGrid.js
var rowEditing = Ext.create('Ext.grid.plugin.RowEditing',{ pluginId:'rowEditing', saveBtnText: '保存', cancelBtnText: "取消", autoCancel: false, clicksToEdit:2 //双击进行修改 1-单击 2-双击 0-可取消双击/单击事件 }); Ext.define('Rds.bacera.panel.BaceraGeneTestingProjectExpr...
expresstype:s.record.data.expresstype, expressremark:s.record.data.expressremark }, success: function (response, options) { response = Ext.JSON.decode(response.responseText); if (response==false) { Ext.MessageBox.alert("错误信息"...
em_names,
identifier_name
BaceraGeneTestingProjectExpressGrid.js
var rowEditing = Ext.create('Ext.grid.plugin.RowEditing',{ pluginId:'rowEditing', saveBtnText: '保存', cancelBtnText: "取消", autoCancel: false, clicksToEdit:2 //双击进行修改 1-单击 2-双击 0-可取消双击/单击事件 }); Ext.define('Rds.bacera.panel.BaceraGeneTestingProjectExpr...
expresstype:s.record.data.expresstype, expressremark:s.record.data.expressremark }, success: function (response, options) { response = Ext.JSON.decode(response.responseText); if (response==false) { Ext.MessageBox.alert("错误信息", "修改...
identifier_body
BaceraGeneTestingProjectExpressGrid.js
var rowEditing = Ext.create('Ext.grid.plugin.RowEditing',{ pluginId:'rowEditing', saveBtnText: '保存', cancelBtnText: "取消", autoCancel: false, clicksToEdit:2 //双击进行修改 1-单击 2-双击 0-可取消双击/单击事件 }); Ext.define('Rds.bacera.panel.BaceraGeneTestingProjectExpr...
consumer_sex:consumer_sex.getValue().trim() //consumer_phone:consumer_phone.getValue().trim() }); } } }); me.selModel = Ext.create('Ext.selection.CheckboxModel',{ // mode: 'SINGLE' }); me.bbar = Ext.create('Ext.PagingToolbar', { store : me.store,...
charge_standard_name:charge_standard_name.getValue().trim(),
random_line_split
main.rs
#[macro_use] extern crate failure; use nbted::unstable::{data, read, string_read, string_write, write}; use nbted::Result; use std::env; use std::fs::File; use std::io; use std::io::{BufReader, BufWriter}; use std::path::Path; use std::process::exit; use std::process::Command; use getopts::Options; use tempdir::Tem...
/// Main entrypoint for program. /// /// Returns an integer representing the program's exit status. fn run_cmdline() -> Result<i32> { let args: Vec<String> = env::args().collect(); let mut opts = Options::new(); let _: &Options = opts.optflagopt("e", "edit", "edit a NBT file with your $EDITOR. If [FI...
{ match run_cmdline() { Ok(ret) => { exit(ret); } Err(e) => { eprintln!("{}", e.backtrace()); eprintln!("Error: {}", e); for e in e.iter_chain().skip(1) { eprintln!(" caused by: {}", e); } eprintln!("F...
identifier_body
main.rs
#[macro_use] extern crate failure; use nbted::unstable::{data, read, string_read, string_write, write}; use nbted::Result; use std::env; use std::fs::File; use std::io; use std::io::{BufReader, BufWriter}; use std::path::Path; use std::process::exit; use std::process::Command; use getopts::Options; use tempdir::Tem...
Some(x) => { let mut x = x.to_os_string(); x.push(".txt"); x } None => bail!("Error reading file name"), }; let tmp_path = tmpdir.path().join(tmp); { let mut f = File::create(&tmp_path).context("Unable to create temporary file")?; ...
* to the temporary file */ let tmpdir = TempDir::new("nbted").context("Unable to create temporary directory")?; let tmp = match Path::new(input).file_name() {
random_line_split
main.rs
#[macro_use] extern crate failure; use nbted::unstable::{data, read, string_read, string_write, write}; use nbted::Result; use std::env; use std::fs::File; use std::io; use std::io::{BufReader, BufWriter}; use std::path::Path; use std::process::exit; use std::process::Command; use getopts::Options; use tempdir::Tem...
else { bail!("Internal error: No action selected. (Please report this.)"); } } /// When the user wants to edit a specific file in place /// /// Returns an integer representing the program's exit status. fn edit(input: &str, output: &str) -> Result<i32> { /* First we read the NBT data from the input */...
{ edit(&input, &output) }
conditional_block
main.rs
#[macro_use] extern crate failure; use nbted::unstable::{data, read, string_read, string_write, write}; use nbted::Result; use std::env; use std::fs::File; use std::io; use std::io::{BufReader, BufWriter}; use std::path::Path; use std::process::exit; use std::process::Command; use getopts::Options; use tempdir::Tem...
(tmp_path: &Path) -> Result<data::NBTFile> { let editor = match env::var("VISUAL") { Ok(x) => x, Err(_) => match env::var("EDITOR") { Ok(x) => x, Err(_) => bail!("Unable to find $EDITOR"), }, }; let mut cmd = Command::new(editor); let _: &mut Command = cm...
open_editor
identifier_name
rtio.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn new<'a>(io: &'a mut IoFactory) -> LocalIo<'a> { LocalIo { factory: io } } /// Returns the underlying I/O factory as a trait reference. #[inline] pub fn get<'a>(&'a mut self) -> &'a mut IoFactory { // FIXME(pcwalton): I think this is actually sound? Could borrow check ...
{ match LocalIo::borrow() { None => Err(io::standard_error(io::IoUnavailable)), Some(mut io) => f(io.get()), } }
identifier_body
rtio.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn id(&self) -> libc::pid_t; fn kill(&mut self, signal: int) -> IoResult<()>; fn wait(&mut self) -> ProcessExit; } pub trait RtioPipe { fn read(&mut self, buf: &mut [u8]) -> IoResult<uint>; fn write(&mut self, buf: &[u8]) -> IoResult<()>; fn clone(&self) -> ~RtioPipe:Send; } pub trait RtioUnix...
fn truncate(&mut self, offset: i64) -> IoResult<()>; } pub trait RtioProcess {
random_line_split
rtio.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ /// Path to file to be opened pub path: Path, /// Flags for file access mode (as per open(2)) pub flags: int, /// File creation mode, ignored unless O_CREAT is passed as part of flags pub mode: int } /// Description of what to do when a file handle is closed pub enum CloseBehavior { /// ...
FileOpenConfig
identifier_name
traffic_signal.rs
use crate::options::TrafficSignalStyle; use crate::render::{DrawCtx, DrawTurnGroup, BIG_ARROW_THICKNESS}; use crate::ui::UI; use ezgui::{ Button, Color, Composite, DrawBoth, EventCtx, GeomBatch, GfxCtx, Line, ManagedWidget, ModalMenu, Outcome, Text, }; use geom::{Circle, Distance, Duration, Polygon}; use map_mo...
pub struct TrafficSignalDiagram { pub i: IntersectionID, composite: Composite, current_phase: usize, } impl TrafficSignalDiagram { pub fn new( i: IntersectionID, current_phase: usize, ui: &UI, ctx: &EventCtx, ) -> TrafficSignalDiagram { TrafficSignalDiagram...
{ let protected_color = ctx .cs .get_def("turn protected by traffic signal", Color::GREEN); let yield_color = ctx.cs.get_def( "turn that can yield by traffic signal", Color::rgba(255, 105, 180, 0.8), ); let signal = ctx.map.get_traffic_signal(i); for (id, crosswalk) ...
identifier_body
traffic_signal.rs
use crate::options::TrafficSignalStyle; use crate::render::{DrawCtx, DrawTurnGroup, BIG_ARROW_THICKNESS}; use crate::ui::UI; use ezgui::{ Button, Color, Composite, DrawBoth, EventCtx, GeomBatch, GfxCtx, Line, ManagedWidget, ModalMenu, Outcome, Text, }; use geom::{Circle, Distance, Duration, Polygon}; use map_mo...
.iter() .map(|r| ui.primary.map.get_r(*r).get_name()) .collect::<BTreeSet<_>>(); let len = road_names.len(); // TODO Some kind of reusable TextStyle thing // TODO Need to wrap this txt.add(Line("").roboto().size(21).fg(Color::WHITE.alpha(0.54))); ...
.roads
random_line_split
traffic_signal.rs
use crate::options::TrafficSignalStyle; use crate::render::{DrawCtx, DrawTurnGroup, BIG_ARROW_THICKNESS}; use crate::ui::UI; use ezgui::{ Button, Color, Composite, DrawBoth, EventCtx, GeomBatch, GfxCtx, Line, ManagedWidget, ModalMenu, Outcome, Text, }; use geom::{Circle, Distance, Duration, Polygon}; use map_mo...
TurnPriority::Banned => {} } } } } if time_left.is_none() { return; } let radius = Distance::meters(0.5); let box_width = (2.5 * radius).inner_meters(); let box_height = (6.5 * radius).inner_meters(); let center = ctx.map.get...
{ batch.extend( yield_color, turn.geom .make_arrow_outline( BIG_ARROW_THICKNESS * 2.0, BIG_ARROW_THICKNESS / 2.0, ...
conditional_block
traffic_signal.rs
use crate::options::TrafficSignalStyle; use crate::render::{DrawCtx, DrawTurnGroup, BIG_ARROW_THICKNESS}; use crate::ui::UI; use ezgui::{ Button, Color, Composite, DrawBoth, EventCtx, GeomBatch, GfxCtx, Line, ManagedWidget, ModalMenu, Outcome, Text, }; use geom::{Circle, Distance, Duration, Polygon}; use map_mo...
(&mut self, ctx: &mut EventCtx, ui: &mut UI, menu: &mut ModalMenu) { if self.current_phase != 0 && menu.action("select previous phase") { self.change_phase(self.current_phase - 1, ui, ctx); } if self.current_phase != ui.primary.map.get_traffic_signal(self.i).phases.len() - 1 ...
event
identifier_name
source.py
import copy from dataclasses import dataclass from typing import Literal, Union import matplotlib.pyplot as plt import numpy as np from astropy.utils import lazyproperty from matplotlib.patches import Circle, Ellipse from photutils.aperture import * from photutils.isophote import Ellipse as IsoEllipse from photutils.i...
(Source): """Extended source (comet, galaxy or lensed source)""" @property def _symbol(self): return chr(11053) def plot(self, radius=None, **kwargs): """Plot Ellipse on source Parameters ---------- radius : int, optional extension to minor/major ax...
ExtendedSource
identifier_name
source.py
import copy from dataclasses import dataclass from typing import Literal, Union import matplotlib.pyplot as plt import numpy as np from astropy.utils import lazyproperty from matplotlib.patches import Circle, Ellipse from photutils.aperture import * from photutils.isophote import Ellipse as IsoEllipse from photutils.i...
def rectangular_annulus(self, r0, r1, scale=False): if scale: a0 = 2 * r0 * self.a a1, b1 = 2 * r1 * self.a, 2 * r1 * self.b else: a0 = r0 a1, b1 = r1, r1 * self.eccentricity a0 = np.max([0.01, a0]) a1 = np.max([a0 + 0.001, a1]) ...
if scale: a0 = r0 * self.a a1, b1 = r1 * self.a, r1 * self.b else: a0 = (r0,) a1, b1 = r1, r1 * self.eccentricity return EllipticalAnnulus(self.coords, a0, a1, b1, theta=self.orientation)
identifier_body
source.py
import copy from dataclasses import dataclass from typing import Literal, Union import matplotlib.pyplot as plt import numpy as np from astropy.utils import lazyproperty from matplotlib.patches import Circle, Ellipse from photutils.aperture import * from photutils.isophote import Ellipse as IsoEllipse from photutils.i...
def annulus(self, rin, rout, scale=False): if self.type == "PointSource": return CircularAnnulus(self.coords, rin, rout) else: return [source.annulus(rin, rout, scale=scale) for source in self.sources] def plot(self, *args, **kwargs): for s in self.sources: ...
return [source.aperture(r, scale=scale) for source in self.sources]
conditional_block
source.py
import copy from dataclasses import dataclass from typing import Literal, Union import matplotlib.pyplot as plt import numpy as np from astropy.utils import lazyproperty from matplotlib.patches import Circle, Ellipse from photutils.aperture import * from photutils.isophote import Ellipse as IsoEllipse from photutils.i...
*label_coords, self.i, c=c, ha="center", va="top", fontsize=fontsize ) def aperture(self, r=1, scale=True): return self.rectangular_aperture(r, scale=scale) def annulus(self, r0=1.05, r1=1.4, scale=True): return self.rectangular_annulus(r0, r1, scale=scale) @datac...
plt.text(
random_line_split
util.rs
// Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0. use std::{fmt::Write, path::Path, sync::Arc, thread, time::Duration}; use encryption_export::{data_key_manager_from_config, DataKeyManager}; use engine_rocks::{RocksEngine, RocksStatistics}; use engine_test::raft::RaftTestEngine; use engine_traits::{C...
let base_tick_interval = cluster.cfg.raft_store.raft_base_tick_interval.0; if let Some(election_ticks) = election_ticks { cluster.cfg.raft_store.raft_election_timeout_ticks = election_ticks; } let election_ticks = cluster.cfg.raft_store.raft_election_timeout_ticks as u32; let election_timeo...
{ cluster.cfg.raft_store.raft_base_tick_interval = ReadableDuration::millis(base_tick_ms); }
conditional_block
util.rs
// Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0. use std::{fmt::Write, path::Path, sync::Arc, thread, time::Duration}; use encryption_export::{data_key_manager_from_config, DataKeyManager}; use engine_rocks::{RocksEngine, RocksStatistics}; use engine_test::raft::RaftTestEngine; use engine_traits::{C...
election_timeout } pub fn wait_for_synced( cluster: &mut Cluster<ServerCluster<RocksEngine>, RocksEngine>, node_id: u64, region_id: u64, ) { let mut storage = cluster .sim .read() .unwrap() .storages .get(&node_id) .unwrap() .clone(); let...
// check < abnormal < max leader missing duration. cluster.cfg.raft_store.peer_stale_state_check_interval = ReadableDuration(election_timeout * 3); cluster.cfg.raft_store.abnormal_leader_missing_duration = ReadableDuration(election_timeout * 4); cluster.cfg.raft_store.max_leader_missing_duration...
random_line_split
util.rs
// Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0. use std::{fmt::Write, path::Path, sync::Arc, thread, time::Duration}; use encryption_export::{data_key_manager_from_config, DataKeyManager}; use engine_rocks::{RocksEngine, RocksStatistics}; use engine_test::raft::RaftTestEngine; use engine_traits::{C...
pub fn must_get_value(resp: &RaftCmdResponse) -> Vec<u8> { if resp.get_header().has_error() { panic!("failed to read {:?}", resp); } assert_eq!(resp.get_responses().len(), 1); assert_eq!(resp.get_responses()[0].get_cmd_type(), CmdType::Get); assert!(resp.get_responses()[0].has_get()); ...
{ let data_set: Vec<_> = (1..500) .map(|i| { ( format!("key{:08}", i).into_bytes(), format!("value{}", i).into_bytes(), ) }) .collect(); for kvs in data_set.chunks(50) { let requests = kvs.iter().map(|(k, v)| new_put_cf_cmd(...
identifier_body
util.rs
// Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0. use std::{fmt::Write, path::Path, sync::Arc, thread, time::Duration}; use encryption_export::{data_key_manager_from_config, DataKeyManager}; use engine_rocks::{RocksEngine, RocksStatistics}; use engine_test::raft::RaftTestEngine; use engine_traits::{C...
(config: &mut Config) { let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR")); let cfg = &mut config.security.encryption; cfg.data_encryption_method = EncryptionMethod::Aes128Ctr; cfg.data_key_rotation_period = ReadableDuration(Duration::from_millis(100)); cfg.master_key = test_util::new_test_fi...
configure_for_encryption
identifier_name
generate_feature.py
import os import cv2 import dlib import numpy as np import math import matplotlib.pyplot as plt from scipy import signal import pandas as pd import datetime from RWCSV import rw_csv detector_face_cut = cv2.CascadeClassifier('F:/data/haarcascade_frontalface_default.xml') detector = dlib.get_frontal_face_det...
= frame img = frame rects = detector(img_gray, 0) face_key_point = np.empty([0, 1, 2], dtype=np.float32) for i in range(len(rects)): landmarks = np.matrix([[p.x, p.y] for p in predictor(img, rects[i]).parts()]) for idx, point in enumerate(landmarks): pos = (point[0, 0...
img_gray
identifier_name
generate_feature.py
import os import cv2 import dlib import numpy as np import math import matplotlib.pyplot as plt from scipy import signal import pandas as pd import datetime from RWCSV import rw_csv detector_face_cut = cv2.CascadeClassifier('F:/data/haarcascade_frontalface_default.xml') detector = dlib.get_frontal_face_det...
if c > 40: y = 1.4 if c > 50: y = 1.5 print('检测到人脸') x = faces[0][0] y = faces[0][1] w = faces[0][2] h = faces[0][3] # temp_img = img[y:y + h - 1, x:x + w - 1] return x, y, w, h def face_detector(frame): img_gray = frame im...
random_line_split
generate_feature.py
import os import cv2 import dlib import numpy as np import math import matplotlib.pyplot as plt from scipy import signal import pandas as pd import datetime from RWCSV import rw_csv detector_face_cut = cv2.CascadeClassifier('F:/data/haarcascade_frontalface_default.xml') detector = dlib.get_frontal_face_det...
c > 40: y = 1.4 if c > 50: y = 1.5 print('检测到人脸') x = faces[0][0] y = faces[0][1] w = faces[0][2] h = faces[0][3] # temp_img = img[y:y + h - 1, x:x + w - 1] return x, y, w, h def face_detector(frame): img_gray = frame img = frame ...
if
conditional_block
generate_feature.py
import os import cv2 import dlib import numpy as np import math import matplotlib.pyplot as plt from scipy import signal import pandas as pd import datetime from RWCSV import rw_csv detector_face_cut = cv2.CascadeClassifier('F:/data/haarcascade_frontalface_default.xml') detector = dlib.get_frontal_face_det...
path, temp_label): print(video_path) eyebrow_index = np.array([18, 19, 20, 23, 24, 25], dtype=np.int8) nose_index = np.array([30], dtype=np.int8) mouth_index = np.array([48, 51, 54, 57], dtype=np.int8) point_index = np.concatenate([eyebrow_index, nose_index]) point_index = np.concatenate([...
(path) total_frame = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) column0 = page1[:, 0:1].reshape((-1)) s = int(s) idx = np.argwhere(column0 == s) first_idx = idx[0][0] convert_s = page1[first_idx][2] column0 = page2[:, 0:1].reshape((-1)) idx = np.argwhere(column0 == int(code[1:])) ...
identifier_body
server.go
package shardmaster import "../raft" import "../labrpc" import "sync" import "../labgob" import "log" //import "fmt" const Debug = 0 func DPrintf(format string, a ...interface{}) (n int, err error) { if Debug > 0 { log.Printf(format, a...) } return } func TPrintf(format string, a ...interface{}) (n int, err ...
} func Max(x, y int) int { if x > y { return x } return y } func (sm *ShardMaster) OnApplyEntry(m *raft.ApplyMsg) { ops := m.Command.(Op) dup, ok := sm.GetDuplicate(ops.ClientId, ops.Method) sm.Lock() defer sm.Unlock() if !ok || (dup != ops.RequestId) { switch ops.Method { case "Leave": fallthrough...
message.CommandTerm) } // continue } }
conditional_block
server.go
package shardmaster import "../raft" import "../labrpc" import "sync" import "../labgob" import "log" //import "fmt" const Debug = 0 func DPrintf(format string, a ...interface{}) (n int, err error) { if Debug > 0 { log.Printf(format, a...) } return } func TPrintf(format string, a ...interface{}) (n int, err ...
r) OnApplyEntry(m *raft.ApplyMsg) { ops := m.Command.(Op) dup, ok := sm.GetDuplicate(ops.ClientId, ops.Method) sm.Lock() defer sm.Unlock() if !ok || (dup != ops.RequestId) { switch ops.Method { case "Leave": fallthrough case "Join": fallthrough case "Move": if len(ops.Config) > len(sm.configs) { ...
x } return y } func (sm *ShardMaste
identifier_body
server.go
package shardmaster import "../raft" import "../labrpc" import "sync" import "../labgob" import "log" //import "fmt" const Debug = 0 func DPrintf(format string, a ...interface{}) (n int, err error) { if Debug > 0 { log.Printf(format, a...) } return } func TPrintf(format string, a ...interface{}) (n int, err ...
sm.Lock() defer sm.Unlock() if sm.RaftBecomeFollower(m) { for index, ch := range sm.requestHandlers { delete(sm.requestHandlers, index) ch <- *m } } } func (sm *ShardMaster) receivingApplyMsg() { for { select { case m := <-sm.applyCh: if m.CommandValid { DPrintf("receivingApplyMsg r...
pplyMsg) {
identifier_name
server.go
package shardmaster import "../raft" import "../labrpc" import "sync" import "../labgob" import "log" //import "fmt" const Debug = 0 func DPrintf(format string, a ...interface{}) (n int, err error) { if Debug > 0 { log.Printf(format, a...) } return } func TPrintf(format string, a ...interface{}) (n int, err ...
func (sm *ShardMaster) Raft() *raft.Raft { return sm.rf } func (sm *ShardMaster) await(index int, term int, op Op) (success bool) { awaitChan := sm.registerIndexHandler(index) for { select { case message := <-awaitChan: if sm.RaftBecomeFollower(&message) { return false } if (message.CommandValid =...
sm.rf.Kill() // Your code here, if desired. } // needed by shardkv tester
random_line_split
multiexp.rs
use super::error::{GPUError, GPUResult}; use super::locks; use super::sources; use super::utils; use crate::bls::Engine; use crate::multicore::Worker; use crate::multiexp::{multiexp as cpu_multiexp, FullDensity}; use ff::{PrimeField, ScalarEngine}; use groupy::{CurveAffine, CurveProjective}; use log::{error, info}; use...
<G>( &mut self, pool: &Worker, bases: Arc<Vec<G>>, exps: Arc<Vec<<<G::Engine as ScalarEngine>::Fr as PrimeField>::Repr>>, skip: usize, n: usize, ) -> GPUResult<<G as CurveAffine>::Projective> where G: CurveAffine, <G as groupy::CurveAffine>::Engine...
multiexp
identifier_name
multiexp.rs
use super::error::{GPUError, GPUResult}; use super::locks; use super::sources; use super::utils; use crate::bls::Engine; use crate::multicore::Worker; use crate::multiexp::{multiexp as cpu_multiexp, FullDensity}; use ff::{PrimeField, ScalarEngine}; use groupy::{CurveAffine, CurveProjective}; use log::{error, info}; use...
} MAX_WINDOW_SIZE } fn calc_best_chunk_size(max_window_size: usize, core_count: usize, exp_bits: usize) -> usize { // Best chunk-size (N) can also be calculated using the same logic as calc_window_size: // n = e^window_size * window_size * 2 * core_count / exp_bits (((max_window_size as f64).exp(...
{ return w; }
conditional_block
multiexp.rs
use super::error::{GPUError, GPUResult}; use super::locks; use super::sources; use super::utils; use crate::bls::Engine; use crate::multicore::Worker; use crate::multiexp::{multiexp as cpu_multiexp, FullDensity}; use ff::{PrimeField, ScalarEngine}; use groupy::{CurveAffine, CurveProjective}; use log::{error, info}; use...
}) .collect(); if kernels.is_empty() { return Err(GPUError::Simple("No working GPUs found!")); } info!( "Multiexp: {} working device(s) selected. (CPU utilization: {})", kernels.len(), get_cpu_utilization() ); ...
} res.ok()
random_line_split
multiexp.rs
use super::error::{GPUError, GPUResult}; use super::locks; use super::sources; use super::utils; use crate::bls::Engine; use crate::multicore::Worker; use crate::multiexp::{multiexp as cpu_multiexp, FullDensity}; use ff::{PrimeField, ScalarEngine}; use groupy::{CurveAffine, CurveProjective}; use log::{error, info}; use...
fn exp_size<E: Engine>() -> usize { std::mem::size_of::<<E::Fr as ff::PrimeField>::Repr>() } impl<E> SingleMultiexpKernel<E> where E: Engine, { pub fn create(d: opencl::Device, priority: bool) -> GPUResult<SingleMultiexpKernel<E>> { let src = sources::kernel::<E>(d.brand() == opencl::Brand::Nvidi...
{ let aff_size = std::mem::size_of::<E::G1Affine>() + std::mem::size_of::<E::G2Affine>(); let exp_size = exp_size::<E>(); let proj_size = std::mem::size_of::<E::G1>() + std::mem::size_of::<E::G2>(); ((((mem as f64) * (1f64 - MEMORY_PADDING)) as usize) - (2 * core_count * ((1 << MAX_WINDOW_SIZE) ...
identifier_body
pso.rs
// Copyright 2015 The Gfx-rs Developers. // // 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 law or ag...
} impl Error for CreationError { fn description(&self) -> &str { "Could not create PSO on device." } } /// Color output configuration of the PSO. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] pub struct ColorInfo { /// Color ...
{ write!(f, "{}", self.description()) }
identifier_body
pso.rs
// Copyright 2015 The Gfx-rs Developers. // // 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 law or ag...
self.set_dimensions(dim); } fn set_dimensions(&mut self, dim: texture::Dimensions) { debug_assert!(self.dimensions.map(|d| d == dim).unwrap_or(true)); self.dimensions = Some(dim); } /// Get the rendering view (returns values > 0) pub fn get_view(&self) -> (u16, u16, u16) {...
{ self.stencil = Some(view.clone()); }
conditional_block
pso.rs
// Copyright 2015 The Gfx-rs Developers. // // 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 law or ag...
<R: Resources> { /// Array of color target views pub colors: [Option<R::RenderTargetView>; MAX_COLOR_TARGETS], /// Depth target view pub depth: Option<R::DepthStencilView>, /// Stencil target view pub stencil: Option<R::DepthStencilView>, /// Rendering dimensions pub dimensions: Option<t...
PixelTargetSet
identifier_name
pso.rs
// Copyright 2015 The Gfx-rs Developers. // // 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 law or ag...
UnorderedViewSlot, SamplerSlot, Primitive, Resources}; use {format, state as s, texture}; use shade::Usage; use std::error::Error; use std::fmt; /// Maximum number of vertex buffers used in a PSO definition. pub const MAX_VERTEX_BUFFERS: usize = 4; /// An offset inside a vertex buffer, in bytes. pub type Bu...
use {ConstantBufferSlot, ColorSlot, ResourceViewSlot,
random_line_split
PyGenTools.py
""" PyGenTools.py by John Dorsey. PyGenTools.py contains tools that work on python generators without handling their items (comparing items, etc.). """ import traceback import itertools from collections import deque class ExhaustionError(Exception): """ ExhaustionError is raised when a function that eats item...
(inputIndex, inputGen): #used in MarkovTools. if inputIndex == None: raise ValueError("inputIndex can't be None.") return arrTakeLast(genTakeOnly(inputGen, inputIndex+1), 1)[0] def sentinelize(inputSeq, sentinel=None, loopSentinel=False, failFun=None): """ Signals the end of a generator by yielding an ...
valueAtIndexInGen
identifier_name
PyGenTools.py
""" PyGenTools.py by John Dorsey. PyGenTools.py contains tools that work on python generators without handling their items (comparing items, etc.). """ import traceback import itertools from collections import deque class ExhaustionError(Exception): """ ExhaustionError is raised when a function that eats item...
inputGen = makeGen(inputSeq) if useLookahead: previousItem = None index = None for index,currentItem in enumerate(inputGen): #assert currentItem is not None, "can't handle Nones in inputSeq yet." if index == 0: previousItem = currentItem elif index == 1: yield to...
return (tagToApply, workingItem)
identifier_body
PyGenTools.py
""" PyGenTools.py by John Dorsey. PyGenTools.py contains tools that work on python generators without handling their items (comparing items, etc.). """ import traceback import itertools from collections import deque class ExhaustionError(Exception): """ ExhaustionError is raised when a function that eats item...
try: result = [item for item in thing] except KeyboardInterrupt: raise KeyboardInterrupt("PyGenTools.makeArr was stuck on " + str(thing) + ".") return result def handleOnExhaustion(methodName, yieldedCount, targetCount, onExhaustion): if isinstance(onExhaustion,Exception): raise onExhaustion e...
def makeArr(thing): if type(thing) == list: return thing
random_line_split
PyGenTools.py
""" PyGenTools.py by John Dorsey. PyGenTools.py contains tools that work on python generators without handling their items (comparing items, etc.). """ import traceback import itertools from collections import deque class ExhaustionError(Exception): """ ExhaustionError is raised when a function that eats item...
""" def getAccumulatorFun(thing): if type(thing) == str: result = eval("(lambda x,y: x{}y)".format(thing)) elif type(thing) == type((lambda x: x)): result = thing else: raise TypeError("must be string or function.") return result """ def accumulate(inputSeq, inputFun): inputSeq = makeGen(input...
raise ValueError("unsupported type: " + str(type(inputSeq)) + ".")
conditional_block
IPC.js
/* global Main, StatusLight */ /** * --------- * IPC class * --------- * @constructor * @param {number} id **/ function IPC(id) { this._id = id; this._numRetries = 0; this._tokenPos = 0; this._lastTime = new Date().getTime(); return this; } IPC.prototype.run = function() { var lastClientP...
} this.postDisconnectClients(); } IPC.prototype.postConnectClients = function() { if (IPC.connected) return; for (var i = 0; i < IPC.clients.length; i++) { IPC.clients[i]._feed.handleConnect(); } } IPC.prototype.postDisconnectClients = function() { if (!IPC.connected) re...
{ client._state = IPC_Client.STATE_START; }
conditional_block
IPC.js
/* global Main, StatusLight */ /** * --------- * IPC class * --------- * @constructor * @param {number} id **/ function
(id) { this._id = id; this._numRetries = 0; this._tokenPos = 0; this._lastTime = new Date().getTime(); return this; } IPC.prototype.run = function() { var lastClientProcess = new Date().getTime(); if (IPC.clients.length > 0) { if (this.socketConnect()) { this.postConnectC...
IPC
identifier_name
IPC.js
/* global Main, StatusLight */ /** * --------- * IPC class * --------- * @constructor * @param {number} id **/ function IPC(id) { this._id = id; this._numRetries = 0; this._tokenPos = 0; this._lastTime = new Date().getTime(); return this; } IPC.prototype.run = function() { var lastClientP...
/** * @param {Array} fi */ IPC_Client.prototype.add = function(fi) { this._feedItems.push(fi); if (this._feedItems.length > 5000) { console.warn("Feed client not flushing data.", this._feedItems.length); this.flush(); } } IPC_Client.prototype.flush = function() { this._feed.add(this._...
{ this._id = id; this._data = feed._dataBlock; this._feed = feed; this._feedItems = []; this._state = IPC_Client.STATE_START; }
identifier_body
IPC.js
/* global Main, StatusLight */ /** * --------- * IPC class * --------- * @constructor * @param {number} id **/ function IPC(id) { this._id = id; this._numRetries = 0; this._tokenPos = 0; this._lastTime = new Date().getTime(); return this; } IPC.prototype.run = function() { var lastClientP...
* @static * @param {IPC_Client} client */ IPC.clientLogin = function(client) { client._tag = IPC.ipcTag + "," + client._id; var str = JSON.stringify({'type': 'subscribe', 'client_id': client._id, 'user': IPC.userName, 'sid': IPC.sid, 'page_key': Main.getParams()["page_key"], 'app': client._feed._name, 'ipc_t...
} } } /**
random_line_split
ejob_soa.py
# -*- coding : utf-8 -*- from odoo import fields, models, api, tools, _ #Cashier Management class ejob_cashier(models.Model): _name = 'ejob.cashier' _description = 'Customer SOA' _order = "id desc" @api.depends('orders') def _compute_charges(self): if not self.ids: #Update ca...
else: raise UserError('Error! There are no invoices generated for these charges.') class custom_account_invoice(models.Model): _inherit = "account.invoice" payment_id = fields.Many2one('e.job.orders', string="Payment Record") date_invoice = fields.Date(string='Invoice Date', ...
for invoice in rec.invoices: invoice.unlink() rec.update({'state':'new'}) #Reset all Charges to draft #for order in rec.orders: # order.update({'state':'draft'}) self.env.user.notify_info('All generated invoices are c...
conditional_block
ejob_soa.py
# -*- coding : utf-8 -*- from odoo import fields, models, api, tools, _ #Cashier Management class
(models.Model): _name = 'ejob.cashier' _description = 'Customer SOA' _order = "id desc" @api.depends('orders') def _compute_charges(self): if not self.ids: #Update calculated fields self.update({ 'total_items_count': 0, 'total_service...
ejob_cashier
identifier_name
ejob_soa.py
# -*- coding : utf-8 -*- from odoo import fields, models, api, tools, _ #Cashier Management class ejob_cashier(models.Model): _name = 'ejob.cashier' _description = 'Customer SOA' _order = "id desc" @api.depends('orders') def _compute_charges(self): if not self.ids: #Update ca...
#Update calculated fields payment.update({ 'total_paid': total_paid, }) @api.depends('orders') def _compute_total_services(self): for rec in self: service_total = 0.0 for line in rec.charge_line_ids: charge_tota...
for pay in payment.payments: total_paid += pay.amount
random_line_split
ejob_soa.py
# -*- coding : utf-8 -*- from odoo import fields, models, api, tools, _ #Cashier Management class ejob_cashier(models.Model): _name = 'ejob.cashier' _description = 'Customer SOA' _order = "id desc" @api.depends('orders') def _compute_charges(self): if not self.ids: #Update ca...
@api.model def _default_currency(self): return self.env.user.company_id.currency_id or None @api.model def _get_pricelist(self): return self.partner_id.property_product_pricelist # and table.partner_id.property_product_pricelist.id or None name = fields.Char('Payment Ref#') p...
for payment in self: if payment.payment_type == 'Down Payment': payment.balance = 0 elif payment.payment_type == 'A/R Payment': payment.balance = 0 else: payment.balance = payment.total_services_fee - payment.total_paid
identifier_body
extension.ts
// The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import * as vscode from 'vscode'; import { StructCommandManager } from './struct_command_manager' import { EditCommandManager } from './edit_command_manager'; import { runTestCase...
(){ count_speech = []; var count =0; var j =0; for (var i=0;i<manager.struct_command_list.length;i++){ var line = manager.struct_command_list[i]; if (line.startsWith("#comment" || line.indexOf("cursor here")!=-1)|| line.startsWith("#if_branch_end;;")|| line.startsWith("#else_branch_end") || line.startsWith("#fu...
map_speech_to_struct_command
identifier_name
extension.ts
// The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import * as vscode from 'vscode'; import { StructCommandManager } from './struct_command_manager' import { EditCommandManager } from './edit_command_manager'; import { runTestCase...
function initManager() { language = "c"; manager = new StructCommandManager(language, true); editManager = new EditCommandManager(manager,count_lines,count_speech); } function listen() { displayCode([""]); // env: {GOOGLE_APPLICATION_CREDENTIALS: cred} const child = spawn('node', ['speech_recognizer.js'], ...
{ var userSpecs = getUserSpecs(user); cwd = userSpecs[0]; cred = userSpecs[1]; ast_cwd = userSpecs[2]; }
identifier_body