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
decl.go
same path as would be computed by // parseImportPath. switch pkgNameOf(g.info, decl).Imported().Path() { case "unsafe": p.importedUnsafe = true case "embed": p.importedEmbed = true } } // pkgNameOf returns the PkgName associated with the given ImportDecl. func
(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
same path as would be computed by // parseImportPath. switch pkgNameOf(g.info, decl).Imported().Path() { case "unsafe": p.importedUnsafe = true case "embed": p.importedEmbed = true } } // pkgNameOf returns the PkgName associated with the given ImportDecl. func pkgNameOf(info *types2.Info, decl *syntax.Import...
// // 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
type, since those are the methods // that will be stenciled. typ = orig } meth := typecheck.Lookdot1(fn, typecheck.Lookup(decl.Name.Value), typ, typ.Methods(), 0) meth.SetNointerface(true) } } if decl.Body != nil && fn.Pragma&ir.Noescape != 0 { base.ErrorfAt(fn.Pos(), "can only use //go:noescap...
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
1.3.1 which is incompatible. seaborn==0.10.1, but you'll have seaborn 0.10.0 which is incompatible. shap==0.36.0, but you'll have shap 0.35.0 which is incompatible. tabulate==0.8.7, but you'll have tabulate 0.8.6 which is incompatible. xgboost==1.2.0, but you'll have xgboost 1.3.3 which is incompatible. """ imp...
(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
.7, but you'll have tabulate 0.8.6 which is incompatible. xgboost==1.2.0, but you'll have xgboost 1.3.3 which is incompatible. """ import warnings, copy, os, sys warnings.filterwarnings('ignore') #################################################################################### ###### Path #####################...
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
1.3.1 which is incompatible. seaborn==0.10.1, but you'll have seaborn 0.10.0 which is incompatible. shap==0.36.0, but you'll have shap 0.35.0 which is incompatible. tabulate==0.8.7, but you'll have tabulate 0.8.6 which is incompatible. xgboost==1.2.0, but you'll have xgboost 1.3.3 which is incompatible. """ imp...
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
2_data/tree/main/" #### Remote Data directory m['path_data_train'] = dir_data_url + f'/input/{data_name}/train/' m['path_data_test'] = dir_data_url + f'/input/{data_name}/test/' #m['path_data_val'] = dir_data + f'/input/{data_name}/test/' #### train output path m['path_train_outpu...
print(mdict) from source import run_preprocess
random_line_split
mod.rs
> { data: Vec<T>, name: Option<String>, } impl<T> ColumnData<T> { pub fn from_vec(data: impl Into<Vec<T>>) -> Self { Self { data: data.into(), name: None, } } pub fn len(&self) -> usize { self.data.len() } pub fn add(&mut self, element: 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
> { data: Vec<T>, name: Option<String>, } impl<T> ColumnData<T> { pub fn from_vec(data: impl Into<Vec<T>>) -> Self { Self { data: data.into(), name: None, } } pub fn len(&self) -> usize { self.data.len() } pub fn add(&mut self, element: 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
> { data: Vec<T>, name: Option<String>, } impl<T> ColumnData<T> { pub fn from_vec(data: impl Into<Vec<T>>) -> Self { Self { data: data.into(), name: None, } } pub fn len(&self) -> usize { self.data.len() } pub fn add(&mut self, element: 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
> { data: Vec<T>, name: Option<String>, } impl<T> ColumnData<T> { pub fn from_vec(data: impl Into<Vec<T>>) -> Self { Self { data: data.into(), name: None, } } pub fn len(&self) -> usize { self.data.len() } pub fn add(&mut self, element: 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
} else { eprintln!("error: unknown subcommand {}", subcommand); usage(); } args.output = parsed.value_from_str("--output").ok(); args.reference = parsed.value_from_str("--reference").ok(); args.is_no_output = parsed.contains("--no-output"); args.is_model_only = parsed.contains("--m...
{ 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
(EXIT_FAILURE) } } ); fn usage() -> ! { 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", ...
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
(EXIT_FAILURE) } } ); fn
() -> ! { 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
in use', summary: '', text: removeUsedTagViolationsDetail, }; } commentBody += '**The end of the violation section. All the stuff below is FYI purposes only.**\n\n'; commentBody += '---\n'; } if (removeSampleBrowserViolations.length > 0) { let summary = 'You are about ...
logger.info( `The pull request ${context.payload.pull_request.url} is closed, exiting.` ); return; }
conditional_block
snippet-bot.ts
(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
}, }); if (mismatchedTags) { checkParams.conclusion = 'failure'; checkParams.output = { title: 'Mismatched region tag detected.', summary: 'Some new files have mismatched region tag', text: failureMessages.join('\n'), }; } // post the status of commit linting to the PR, using...
return `<!-- probot comment [${installationId}]-->`; } e
identifier_body
snippet-bot.ts
DashIndex = archiveDir.lastIndexOf('-'); if (lastDashIndex !== -1) { commitHash = archiveDir.substr(lastDashIndex + 1); } logger.info(`Using commit hash "${commitHash}"`); const files = await getFiles(archiveDir, []); let mismatchedTags = false; const failureMessages: string[] = []; ...
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
", null ], [ "GetDecrementOperator", "class_system_1_1_class_type.html#a43afdac1cb4865f7ee9c9f3d3a9a63fd", null ], [ "GetDecrementOperatorConst", "class_system_1_1_class_type.html#aa8a2c74edae7d00983a803026ef54b09", null ], [ "GetDestructor", "class_system_1_1_class_type.html#abd9a681a73daa4bb4f1e5094cab437...
[ "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
If true, the constraint that matches the root layout size to the window size /// is required. This can be useful for debugging but can result in panics from resizing the window. const WINDOW_CONSTRAINT_REQUIRED: bool = false; pub struct Ui { pub(crate) root: WidgetRef, widget_map: HashMap<WidgetId, WidgetRef>...
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
If true, the constraint that matches the root layout size to the window size /// is required. This can be useful for debugging but can result in panics from resizing the window. const WINDOW_CONSTRAINT_REQUIRED: bool = false; pub struct Ui { pub(crate) root: WidgetRef, widget_map: HashMap<WidgetId, WidgetRef>...
(root: Widget
new
identifier_name
ui.rs
If true, the constraint that matches the root layout size to the window size /// is required. This can be useful for debugging but can result in panics from resizing the window. const WINDOW_CONSTRAINT_REQUIRED: bool = false; pub struct Ui { pub(crate) root: WidgetRef, widget_map: HashMap<WidgetId, WidgetRef>...
} 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
If true, the constraint that matches the root layout size to the window size /// is required. This can be useful for debugging but can result in panics from resizing the window. const WINDOW_CONSTRAINT_REQUIRED: bool = false; pub struct Ui { pub(crate) root: WidgetRef, widget_map: HashMap<WidgetId, WidgetRef>...
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
.Intn(max-min) } // serialize mutation into []byte // format: // keyLen - 2 bytes // key - length specified by keyLen // seqno - 8 bytes // revId - 8 bytes // cas - 8 bytes // flags - 4 bytes // expiry - 4 bytes // opCode - 1 bytes // hash - 64 bytes func genTestData(regularMutation, colFilter...
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
n(max-min) } // serialize mutation into []byte // format: // keyLen - 2 bytes // key - length specified by keyLen // seqno - 8 bytes // revId - 8 bytes // cas - 8 bytes // flags - 4 bytes // expiry - 4 bytes // opCode - 1 bytes // hash - 64 bytes func genTestData(regularMutation, colFilters bo...
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
.Intn(max-min) } // serialize mutation into []byte // format: // keyLen - 2 bytes // key - length specified by keyLen // seqno - 8 bytes // revId - 8 bytes // cas - 8 bytes // flags - 4 bytes // expiry - 4 bytes // opCode - 1 bytes // hash - 64 bytes func genTestData(regularMutation, colFilter...
(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
n(max-min) } // serialize mutation into []byte // format: // keyLen - 2 bytes // key - length specified by keyLen // seqno - 8 bytes // revId - 8 bytes // cas - 8 bytes // flags - 4 bytes // expiry - 4 bytes // opCode - 1 bytes // hash - 64 bytes func genTestData(regularMutation, colFilters bo...
f2, err := os.OpenFile(fileName2, os.O_APPEND|os.O_WRONLY, 644) if err != nil { return mismatchedKeyNames, err } defer f2.Close() for i := 0; i < mismatchCnt; i++ { key, seqno, revId, cas, flags, expiry, opCode, _, oneData, colId, _ := genTestData(true, false) mismatchedDataMut := &dcp.Mutation{ Vbno: ...
{ 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
a temp directory. dir, err := ioutil.TempDir("", "TestNdtServerMain") rtx.Must(err, "Could not create tempdir") certFile := "cert.pem" keyFile := "key.pem" rtx.Must( pipe.Run( pipe.Script("Create private key and self-signed certificate", pipe.Exec("openssl", "genrsa", "-out", keyFile), pipe.Exec("o...
} } 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
=test@email.address"), ), ), "Failed to generate server key and certs") // Set up the command-line args via environment variables: ports := getOpenPorts(4) for _, ev := range []struct{ key, value string }{ {"NDT7_ADDR", ports[0]}, {"NDT5_ADDR", ports[1]}, {"NDT5_WS_ADDR", ports[2]}, {"NDT5_WSS_ADDR",...
name: "Upload & Download ndt5 WSS with S2C Timeout",
random_line_split
ndt-server_test.go
a temp directory. dir, err := ioutil.TempDir("", "TestNdtServerMain") rtx.Must(err, "Could not create tempdir") certFile := "cert.pem" keyFile := "key.pem" rtx.Must( pipe.Run( pipe.Script("Create private key and self-signed certificate", pipe.Exec("openssl", "genrsa", "-out", keyFile), pipe.Exec("o...
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
a temp directory. dir, err := ioutil.TempDir("", "TestNdtServerMain") rtx.Must(err, "Could not create tempdir") certFile := "cert.pem" keyFile := "key.pem" rtx.Must( pipe.Run( pipe.Script("Create private key and self-signed certificate", pipe.Exec("openssl", "genrsa", "-out", keyFile), pipe.Exec("o...
(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
(accuracy) precision_values.append(precision) recall_values.append(recall) f1_score_values.append(f1_score_val) print_metrics(np.mean(accuracy_values), np.mean(precision_values), np.mean(recall_values), np.mean(f1_score_values)) def print_metrics(accuracy, precision, recall, f1_score_val)...
#dump_random_forest_feature_importance("data/features", "politifact") print("\n\n Working on Politifact Data \n")
random_line_split
basic_model.py
, get_train_test_split, get_dataset_feature_names matplotlib.use('agg') import matplotlib.pyplot as plt def get_classifier_by_name(classifier_name): if classifier_name == "GaussianNB": return GaussianNB() elif classifier_name == "LogisticRegression": return LogisticRegression(solver='lbfgs') ...
(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
, get_train_test_split, get_dataset_feature_names matplotlib.use('agg') import matplotlib.pyplot as plt def get_classifier_by_name(classifier_name): if classifier_name == "GaussianNB": return GaussianNB() elif classifier_name == "LogisticRegression": return LogisticRegression(solver='lbfgs') ...
# Build a forest and compute the feature importances forest = ExtraTreesClassifier(n_estimators=100, random_state=0) forest.fit(X_train, y_train) importances = forest.feature_importances_ std = np.std([tree.feature_importances_ for tree in forest.estimators_], axis=0) indices ...
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
, get_train_test_split, get_dataset_feature_names matplotlib.use('agg') import matplotlib.pyplot as plt def get_classifier_by_name(classifier_name): if classifier_name == "GaussianNB": return GaussianNB() elif classifier_name == "LogisticRegression": return LogisticRegression(solver='lbfgs') ...
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
> The first transaction in a block MUST be a coinbase transaction, // > and subsequent transactions MUST NOT be coinbase transactions. // // <https://zips.z.cash/protocol/protocol.pdf#blockheader> // // > A transaction that has a single transparent input with a null prevout // > field, is calle...
/// 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
// > The first transaction in a block MUST be a coinbase transaction, // > and subsequent transactions MUST NOT be coinbase transactions. // // <https://zips.z.cash/protocol/protocol.pdf#blockheader> // // > A transaction that has a single transparent input with a null prevout // > field, is ca...
( 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
// > The first transaction in a block MUST be a coinbase transaction, // > and subsequent transactions MUST NOT be coinbase transactions. // // <https://zips.z.cash/protocol/protocol.pdf#blockheader> // // > A transaction that has a single transparent input with a null prevout // > field, is ca...
// // 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
> The first transaction in a block MUST be a coinbase transaction, // > and subsequent transactions MUST NOT be coinbase transactions. // // <https://zips.z.cash/protocol/protocol.pdf#blockheader> // // > A transaction that has a single transparent input with a null prevout // > field, is calle...
} /// 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
}; *sc.invalid = list::cons(inv, @*sc.invalid); } } } else if b.node_id == my_defnum { test_scope(cx, sc, b, p); } } } fn check_lval(cx: @ctx, dest: @ast::expr, sc: scope, v: vt<scope>) { alt dest.node { ast::expr_path(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
{ alt ex.node { ast::expr_path(_) { ret some(ast_util::def_id_of_def(cx.tcx.def_map.get(ex.id)).node); } _ { ret none; } } } fn ty_can_unsafely_include(cx: ctx, needle: unsafe_ty, haystack: ty::t, mut: bool) -> bool { fn get_mut(cur: bool, mt: ty::mt) -...
{ cx.tcx.sess.span_err(sp, err); }
conditional_block
alias.rs
_semi(ex, _) { v.visit_expr(ex, sc, v); } } } visit::visit_expr_opt(b.node.expr, sc, v); } fn add_bindings_for_let(cx: ctx, &bs: [binding], loc: @ast::local) { alt loc.node.init { some(init) { if init.op == ast::init_move { err(cx, loc.span, "can not ...
{ 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
sc.invalid, sc.bs); checker(); let new_invalid = filter_invalid(*sc.invalid, sc.bs); // Have to check contents of loop again if it invalidated an alias if list::len(orig_invalid) < list::len(new_invalid) { let old_silent = cx.silent; cx.silent = true; checker(); cx.silent...
unsafe_set
identifier_name
core.go
x{1f1ee}\\x{1f1f0}-" + "\\x{1f1f5}\\x{1f1f7}\\x{1f1fa}-\\x{1f1ff}]|\\x{1f1e9}[\\x{1f1ea}\\x{1f1ec}" + "\\x{1f1ef}\\x{1f1f0}\\x{1f1f2}\\x{1f1f4}\\x{1f1ff}]|\\x{1f1ea}[\\x{1f1e6}" + "\\x{1f1e8}\\x{1f1ea}\\x{1f1ec}\\x{1f1ed}\\x{1f1f7}-\\x{1f1fa}]|\\x{1f1eb}[" + "\\x{1f1ee}-\\x{1f1f0}\\x{1f1f2}\\x{1f1f4}\\x{1f1f7}]|\\x...
{ return n.TestnetEnable }
identifier_body
core.go
}-\\x{1f1f9}\\x{1f1fc}\\x{1f1fe}]|" + "\\x{1f1f6}\\x{1f1e6}|\\x{1f1f7}[\\x{1f1ea}\\x{1f1f4}\\x{1f1f8}\\x{1f1fa}" + "\\x{1f1fc}]|\\x{1f1f8}[\\x{1f1e6}-\\x{1f1ea}\\x{1f1ec}-\\x{1f1f4}\\x{1f1f7}-" + "\\x{1f1f9}\\x{1f1fb}\\x{1f1fd}-\\x{1f1ff}]|\\x{1f1f9}[\\x{1f1e6}\\x{1f1e8}" + "\\x{1f1e9}\\x{1f1eb}-\\x{1f1ed}\\x{1f1ef...
SetUpRepublisher
identifier_name
core.go
1f1fe}]|\\x{1f1ed}[\\x{1f1f0}\\x{1f1f2}\\x{1f1f3}\\x{1f1f7}" + "\\x{1f1f9}\\x{1f1fa}]|\\x{1f1ee}[\\x{1f1e8}-\\x{1f1ea}\\x{1f1f1}-\\x{1f1f4}" + "\\x{1f1f6}-\\x{1f1f9}]|\\x{1f1ef}[\\x{1f1ea}\\x{1f1f2}\\x{1f1f4}\\x{1f1f5}]" + "|\\x{1f1f0}[\\x{1f1ea}\\x{1f1ec}-\\x{1f1ee}\\x{1f1f2}\\x{1f1f3}\\x{1f1f5}" + "\\x{1f1f7}\\x{...
{ n.Broadcast <- repo.StatusNotification{Status: "publishing"} }
conditional_block
core.go
e8}" + "\\x{1f1ee}\\x{1f1f0}\\x{1f1f7}-\\x{1f1fb}\\x{1f1fe}]|\\x{1f1f2}[\\x{1f1e6}" + "\\x{1f1e8}-\\x{1f1ed}\\x{1f1f0}-\\x{1f1ff}]|\\x{1f1f3}[\\x{1f1e6}\\x{1f1e8}" + "\\x{1f1ea}-\\x{1f1ec}\\x{1f1ee}\\x{1f1f1}\\x{1f1f4}\\x{1f1f5}\\x{1f1f7}" + "\\x{1f1fa}\\x{1f1ff}]|\\x{1f1f4}\\x{1f1f2}|\\x{1f1f5}[\\x{1f1e6}\\x{1f1ea...
random_line_split
BaceraGeneTestingProjectExpressGrid.js
width:'20%', labelWidth : 40, fieldLabel : '到 ', labelAlign : 'left', emptyText : '请选择日期', format : 'Y-m-d', value : Ext.Date.add(new Date(), Ext.Date.DAY,1), listeners:{ 'select':function(){ var start = Ext.getCmp('gene_express_starttime').getValue(); var endDate = Ext.g...
Ext.Ajax.request({ url:"bacera/Gene/saveGeneExpress.do",
conditional_block
BaceraGeneTestingProjectExpressGrid.js
(); var endDate = Ext.getCmp('gene_express_endtime').getValue(); if (start > endDate) { Ext.getCmp('gene_express_starttime').setValue(endDate); } } } }); me.store = Ext.create('Ext.data.Store',{ fields:['id','add_time','consumer_name'...
em_names,
identifier_name
BaceraGeneTestingProjectExpressGrid.js
_standard_name'], proxy: { type: 'jsonajax', actionMethods:{read:'POST'}, url: 'bacera/Gene/queryallpage.do', params:{ }, reader: { type: 'json', root:'data', to...
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
.form.field.ComboBox({ fieldLabel : '性别', width:'20%', labelWidth : 70, editable : false, triggerAction : 'all', displayField : 'Name', labelAlign : 'left', valueField : 'Code', store : new Ext.data.ArrayStore( { fields : ['Name','Code' ], data : [['全部',''],['男','M' ],['女','F...
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
/// 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
.optflagopt("r", "reverse", "reverse a file in text format to NBT format. Adding an argument to this is the same as specifying --input", "FILE"); let _: &Options = opts.optopt( "i", "input", "specify the input file, defaults to stdin", "FILE", ); let _: &Options = opts.optopt...
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
flagopt("r", "reverse", "reverse a file in text format to NBT format. Adding an argument to this is the same as specifying --input", "FILE"); let _: &Options = opts.optopt( "i", "input", "specify the input file, defaults to stdin", "FILE", ); let _: &Options = opts.optopt( ...
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
flagopt("r", "reverse", "reverse a file in text format to NBT format. Adding an argument to this is the same as specifying --input", "FILE"); let _: &Options = opts.optopt( "i", "input", "specify the input file, defaults to stdin", "FILE", ); let _: &Options = opts.optopt( ...
(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
Send); fn pausable_idle_callback(&mut self, ~Callback:Send) -> ~PausableIdleCallback:Send; fn remote_callback(&mut self, ~Callback:Send) -> ~RemoteCallback:Send; /// The asynchronous I/O services. Not all event loops may provide one. fn io<'a>(&'a mut self) -> Option<&'a m...
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
but this will happen asynchronously on the local event /// loop). CloseAsynchronously, } pub struct LocalIo<'a> { factory: &'a mut IoFactory, } #[unsafe_destructor] impl<'a> Drop for LocalIo<'a> { fn drop(&mut self) { // FIXME(pcwalton): Do nothing here for now, but eventually we may want ...
fn truncate(&mut self, offset: i64) -> IoResult<()>; } pub trait RtioProcess {
random_line_split
rtio.rs
Send); fn pausable_idle_callback(&mut self, ~Callback:Send) -> ~PausableIdleCallback:Send; fn remote_callback(&mut self, ~Callback:Send) -> ~RemoteCallback:Send; /// The asynchronous I/O services. Not all event loops may provide one. fn io<'a>(&'a mut self) -> Option<&'a m...
{ /// 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
GfxCtx, Line, ManagedWidget, ModalMenu, Outcome, Text, }; use geom::{Circle, Distance, Duration, Polygon}; use map_model::{IntersectionID, Phase, TurnPriority}; use std::collections::BTreeSet; // Only draws a box when time_left is present pub fn draw_signal_phase( phase: &Phase, i: IntersectionID, tim...
batch.push( protected_color, signal.turn_groups[g] .geom .make_arrow(BIG_ARROW_THICKNESS * 2.0) .unwrap(), ); } } ...
{ 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
GfxCtx, Line, ManagedWidget, ModalMenu, Outcome, Text, }; use geom::{Circle, Distance, Duration, Polygon}; use map_model::{IntersectionID, Phase, TurnPriority}; use std::collections::BTreeSet; // Only draws a box when time_left is present pub fn draw_signal_phase( phase: &Phase, i: IntersectionID, tim...
.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
fxCtx, Line, ManagedWidget, ModalMenu, Outcome, Text, }; use geom::{Circle, Distance, Duration, Polygon}; use map_model::{IntersectionID, Phase, TurnPriority}; use std::collections::BTreeSet; // Only draws a box when time_left is present pub fn draw_signal_phase( phase: &Phase, i: IntersectionID, time_...
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
GfxCtx, Line, ManagedWidget, ModalMenu, Outcome, Text, }; use geom::{Circle, Distance, Duration, Polygon}; use map_model::{IntersectionID, Phase, TurnPriority}; use std::collections::BTreeSet; // Only draws a box when time_left is present pub fn draw_signal_phase( phase: &Phase, i: IntersectionID, tim...
(&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
semi-major/minor length defined by the source itself Parameters ---------- n : float offset added to the major and minor axis (major axis of the plotted ellipse will be `Source.a + n`) c : str, optional color of the circle, by default color ax : Axe, opt...
ExtendedSource
identifier_name
source.py
An skimage RegionProperties containing the source keep_region: bool, optional whether to keep region object in source **kwargs: other sources attributes to set """ source = cls( a=region.axis_major_length / 2, b=region.axis_minor_length / ...
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
r1 = r1 return CircularAnnulus(self.coords, r0, r1) def elliptical_annulus(self, r0, r1, scale=False): if scale: a0 = r0 * self.a a1, b1 = r1 * self.a, r1 * self.b else: a0 = (r0,) a1, b1 = r1, r1 * self.eccentricity return...
return [source.aperture(r, scale=scale) for source in self.sources]
conditional_block
source.py
+ self.b)] plt.text( *label_coord, self.i, c=c, ha="center", va="top", fontsize=fontsize ) def circular_aperture(self, r, scale=True): """`photutils.aperture.CircularAperture` centered on the source Parameters ---------- r : float ...
plt.text(
random_line_split
util.rs
_key_manager_from_config(&cfg.security.encryption, dir.path().to_str().unwrap()) .unwrap() .map(Arc::new); let cache = cfg.storage.block_cache.build_shared_cache(); let env = cfg .build_shared_rocks_env(key_manager.clone(), limiter) .unwrap(); let sst_worker = LazyWo...
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
data_key_manager_from_config(&cfg.security.encryption, dir.path().to_str().unwrap()) .unwrap() .map(Arc::new); let cache = cfg.storage.block_cache.build_shared_cache(); let env = cfg .build_shared_rocks_env(key_manager.clone(), limiter) .unwrap(); let sst_worker = L...
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
len); let mut reqs = vec![]; for _ in 0..batch_size / 74 + 1 { key.clear(); let key_id = range.next().unwrap(); write!(key, "{:09}", key_id).unwrap(); rng.fill_bytes(&mut value); // plus 1 for the extra encoding prefix len += key.l...
{ 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
_key_manager_from_config(&cfg.security.encryption, dir.path().to_str().unwrap()) .unwrap() .map(Arc::new); let cache = cfg.storage.block_cache.build_shared_cache(); let env = cfg .build_shared_rocks_env(key_manager.clone(), limiter) .unwrap(); let sst_worker = LazyWo...
(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
y, x) c += 1 if c > 10: y = 1.1 if c > 20: y = 1.2 if c > 30: y = 1.3 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 ...
= 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
, y, x) c += 1 if c > 10: y = 1.1 if c > 20: y = 1.2 if c > 30: y = 1.3
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
y, x) c += 1 if c > 10: y = 1.1 if c > 20: y = 1.2 if c > 30: y = 1.3
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
y, x) c += 1 if c > 10: y = 1.1 if c > 20: y = 1.2 if c > 30: y = 1.3 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 ...
column1[i] = column1[i][0:-2] if column1[i][-1] == '_': column1[i] = column1[i][0:-1] # print(column1) idx = np.argwhere(column1 == convert_code) express_list = [] for i in range(idx.shape[0]): current = idx[i][0] + base_idx start = page0[current][2] ...
(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
4) } sm.duplicate[clientId][method] = requestId } type Op struct { // Your data here. Method string Config []Config RequestId int64 ClientId int64 } func Clone(a, b *Config) { b.Num = a.Num for i,gid := range a.Shards { b.Shards[i] = gid } for gid := range a.Groups { // 假定了一个group中的机器不变 b.Groups[g...
message.CommandTerm) } // continue } }
conditional_block
server.go
RequestId int64 ClientId int64 } func Clone(a, b *Config) { b.Num = a.Num for i,gid := range a.Shards { b.Shards[i] = gid } for gid := range a.Groups { // 假定了一个group中的机器不变 b.Groups[gid] = a.Groups[gid] } } func (sm *ShardMaster) AppendConfigAfterJoinNolock(args *JoinArgs) []Config { newConfig := Confi...
x } return y } func (sm *ShardMaste
identifier_body
server.go
[int][]string{} lastConfig := sm.configs[len(sm.configs) - 1] Clone(&lastConfig, &newConfig) newConfig.Num = len(sm.configs) for _,gid := range args.GIDs { delete(newConfig.Groups,gid) } DPrintf("NewConfigAfterLeave, lastConfig=%+v, newConfig=%+v, args=%+v", lastConfig, newConfig, args) sm.RebalanceNolock(&...
pplyMsg) {
identifier_name
server.go
} val, ok := clientRequest[method] return val, ok } func (sm *ShardMaster) SetDuplicateNolock(clientId int64, method string, requestId int64) { _, haveClient := sm.duplicate[clientId] if !haveClient { sm.duplicate[clientId] = make(map[string]int64) } sm.duplicate[clientId][method] = requestId } type Op s...
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)
sm.rf.Kill() // Your code here, if desired. } // needed by shardkv tester
random_line_split
multiexp.rs
.max(0f64) .min(1f64) } // Multiexp kernel for a single GPU pub struct SingleMultiexpKernel<E> where E: Engine, { program: opencl::Program, core_count: usize, n: usize, priority: bool, _phantom: std::marker::PhantomData<E::Fr>, } fn calc_num_groups(core_count: usize, num_wind...
<G>( &mut self
multiexp
identifier_name
multiexp.rs
.max(0f64) .min(1f64) } // Multiexp kernel for a single GPU pub struct SingleMultiexpKernel<E> where E: Engine, { program: opencl::Program, core_count: usize, n: usize, priority: bool, _phantom: std::marker::PhantomData<E::Fr>, } fn calc_num_groups(core_count: usize, num_wind...
} 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
) .max(0f64) .min(1f64) } // Multiexp kernel for a single GPU pub struct SingleMultiexpKernel<E> where E: Engine, { program: opencl::Program, core_count: usize, n: usize, priority: bool, _phantom: std::marker::PhantomData<E::Fr>, } fn calc_num_groups(core_count: usize, num_wi...
}) .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
.max(0f64) .min(1f64) } // Multiexp kernel for a single GPU pub struct SingleMultiexpKernel<E> where E: Engine, { program: opencl::Program, core_count: usize, n: usize, priority: bool, _phantom: std::marker::PhantomData<E::Fr>, } fn calc_num_groups(core_count: usize, num_wind...
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
governing permissions and // limitations under the License. //! Raw Pipeline State Objects //! //! This module contains items used to create and manage a raw pipeline state object. Most users //! will want to use the typed and safe `PipelineState`. See the `pso` module inside the `gfx` //! crate. use {MAX_COLOR_TARG...
} 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
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 BufferOffset = usize; /// Error types happening upon PSO creation on the device side. #[derive(Clone, Debug, PartialEq)] pub struct Cre...
{ self.stencil = Some(view.clone()); }
conditional_block
pso.rs
governing permissions and // limitations under the License. //! Raw Pipeline State Objects //! //! This module contains items used to create and manage a raw pipeline state object. Most users //! will want to use the typed and safe `PipelineState`. See the `pso` module inside the `gfx` //! crate. use {MAX_COLOR_TARG...
<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
language governing permissions and // limitations under the License. //! Raw Pipeline State Objects //! //! This module contains items used to create and manage a raw pipeline state object. Most users //! will want to use the typed and safe `PipelineState`. See the `pso` module inside the `gfx` //! crate. use {MAX_C...
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
Count, onExhaustion="partial"): #just like genTakeOnly, but bundle the taken items together into an array. assert isinstance(onExhaustion,Exception) or onExhaustion in ["fail","ExhaustionError","warn+partial","partial"] result = [item for item in genTakeOnly(inputGen,targetCount)] if len(result) < targetCount: ...
(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
): #might be used in MarkovTools someday. stopSignalCount = 0 for item in inputGen: yield item if stopFun(item): stopSignalCount += 1 if stopSignalCount >= stopSignalsNeeded: return print("PyGenTools.genTakeUntil ran out of items.") def arrTakeLast(inputGen, count): if count == N...
return (tagToApply, workingItem)
identifier_body
PyGenTools.py
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
Count, onExhaustion="partial"): #just like genTakeOnly, but bundle the taken items together into an array. assert isinstance(onExhaustion,Exception) or onExhaustion in ["fail","ExhaustionError","warn+partial","partial"] result = [item for item in genTakeOnly(inputGen,targetCount)] if len(result) < targetCount: ...
""" 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
._statusLights.changeStatus(1); } if (data.length === 0) return; var newDate = new Date().getTime(); var b = (newDate - this._lastTime) > 500; if (b) { this._lastTime = newDate; if (IPC.currentClient) { if (IPC.currentClient._feed && IPC.currentClient._feed._name ...
} 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
(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
.length; i++) { var client = IPC.clients[i]; if (client._state !== IPC_Client.STATE_LOGOUT) { client._state = IPC_Client.STATE_START; } } return true; } var self = this; this._numRetries++; if (this._numRetries > IPC.MAX_CONNECTION_...
{ this._id = id; this._data = feed._dataBlock; this._feed = feed; this._feedItems = []; this._state = IPC_Client.STATE_START; }
identifier_body
IPC.js
} switch (c0) { case '+': /* * possible incoming error codes STREAM_ERR_TIMEOUT 0 STREAM_ERR_WINDOW_LIMIT 1 * STREAM_ERR_DUPLICATE_PAGE 2 STREAM_ERR_CLIENT_VERSION 3 STREAM_ERR_INVALID_SID 4 * STREAM_ERR_NOT_AVAILABLE 5 STREAM_ERR_NOT_AUTHENTICATED 6 ...
} } } /**
random_line_split
ejob_soa.py
.depends('orders') def _compute_charges(self): if not self.ids: #Update calculated fields self.update({ 'total_items_count': 0, 'total_services_fee': 0.0, 'total_discount': 0.0, }) return True for paymen...
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
(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
api.depends('orders') def _compute_charges(self): if not self.ids: #Update calculated fields self.update({ 'total_items_count': 0, 'total_services_fee': 0.0, 'total_discount': 0.0, }) return True for pay...
#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
api.depends('orders') def _compute_charges(self): if not self.ids: #Update calculated fields self.update({ 'total_items_count': 0, 'total_services_fee': 0.0, 'total_discount': 0.0, }) return True for pay...
@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
var microphone = true; var codeBuffer = ""; var errorFlag = false; var language = ""; var cwd = ""; var ast_cwd = ""; var cred = ""; var datatypes = ["int", "float", "long", "double", "char"]; // this method is called when your extension is activated // your extension is activated the very first time the command is...
(){ 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
microphone = true; var codeBuffer = ""; var errorFlag = false; var language = ""; var cwd = ""; var ast_cwd = ""; var cred = ""; var datatypes = ["int", "float", "long", "double", "char"]; // this method is called when your extension is activated // your extension is activated the very first time the command is ex...
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