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
wavent.py
#!/usr/bin/env python """ WaveNets Audio Generation Model How-to-run example: sampleRNN$ THEANO_FLAGS=mode=FAST_RUN,device=gpu1,floatX=float32,lib.cnmem=.95 python models/one_tier/wavent.py --dim 64 --q_levels 256 --q_type linear --which_set MUSIC --batch_size 8 --wavenet_blocks 4 --dilation_layers_per_block 10 --seq...
if total_iters % 500 == 0: print total_iters, total_iters += 1 try: # Take as many mini-batches as possible from train set mini_batch = tr_feeder.next() except StopIteration: # Mini-batches are finished. Load it again. # Basically, one epoch. tr_feeder = tra...
conditional_block
wavent.py
#!/usr/bin/env python """ WaveNets Audio Generation Model How-to-run example: sampleRNN$ THEANO_FLAGS=mode=FAST_RUN,device=gpu1,floatX=float32,lib.cnmem=.95 python models/one_tier/wavent.py --dim 64 --q_levels 256 --q_type linear --which_set MUSIC --batch_size 8 --wavenet_blocks 4 --dilation_layers_per_block 10 --seq...
# No default value here. Indicate every single arguement. parser = argparse.ArgumentParser( description='two_tier.py\nNo default value! Indicate every argument.') # Hyperparameter arguements: parser.add_argument('--exp', help='Experiment name', type=str, required=False, default='_...
fvalue = float(value) if fvalue < 0 or fvalue > 1: raise argparse.ArgumentTypeError("%s is not in [0, 1] interval!" % value) return fvalue
identifier_body
wavent.py
#!/usr/bin/env python """ WaveNets Audio Generation Model How-to-run example: sampleRNN$ THEANO_FLAGS=mode=FAST_RUN,device=gpu1,floatX=float32,lib.cnmem=.95 python models/one_tier/wavent.py --dim 64 --q_levels 256 --q_type linear --which_set MUSIC --batch_size 8 --wavenet_blocks 4 --dilation_layers_per_block 10 --seq...
cost = cost * lib.floatX(numpy.log2(numpy.e)) ### Getting the params, grads, updates, and Theano functions ### params = lib.get_params(cost, lambda x: hasattr(x, 'param') and x.param==True) lib.print_params_info(params, path=FOLDER_PREFIX) grads = T.grad(cost, wrt=params, disconnected_inputs='warn') grads = [T.clip(g...
cost = cost / target_mask.sum() # By default we report cross-entropy cost in bits. # Switch to nats by commenting out this line: # log_2(e) = 1.44269504089
random_line_split
wavent.py
#!/usr/bin/env python """ WaveNets Audio Generation Model How-to-run example: sampleRNN$ THEANO_FLAGS=mode=FAST_RUN,device=gpu1,floatX=float32,lib.cnmem=.95 python models/one_tier/wavent.py --dim 64 --q_levels 256 --q_type linear --which_set MUSIC --batch_size 8 --wavenet_blocks 4 --dilation_layers_per_block 10 --seq...
(value): fvalue = float(value) if fvalue < 0 or fvalue > 1: raise argparse.ArgumentTypeError("%s is not in [0, 1] interval!" % value) return fvalue # No default value here. Indicate every single arguement. parser = argparse.ArgumentParser( description='two_tier.py\n...
check_unit_interval
identifier_name
utils.js
"use strict"; var _ = require('lodash'); var DirectiveFactory = require('./directive').factory; var METHODS_EXP = /^GET|PUT|POST|DELETE|OPTIONS|HEAD|CONNECT|TRACE$/i; var VALIDATION_REQUIRED_DEFVAL = true; var mkobj = function (k, v) { var o = {}; o[k] = v; return o; }; var tryCascadeFuncCall = function (name, ...
throw new Error('has invalid format "' + route +'", must be "METHOD URI_PATTERN"'); } route = { method: segments[0], url: segments[1] == null ? '' : segments[1] }; } if (!METHODS_EXP.test(route.method)) { throw new Error('has invalid method name "' + route.method + '"'); ...
random_line_split
utils.js
"use strict"; var _ = require('lodash'); var DirectiveFactory = require('./directive').factory; var METHODS_EXP = /^GET|PUT|POST|DELETE|OPTIONS|HEAD|CONNECT|TRACE$/i; var VALIDATION_REQUIRED_DEFVAL = true; var mkobj = function (k, v) { var o = {}; o[k] = v; return o; }; var tryCascadeFuncCall = function (name, ...
// parse filters string var FILTER_FORMAT_EXP = /^([a-zA-Z_]+)(.*)$/i; if (filtersString) { var filterSegments = filtersString.replace(/^\|/, '').split(/\s*\|\s*/g); _.each(filterSegments, function (part) { var name = part.replace(FILTER_FORMAT_EXP, '$1'); var params = parseParamsJSON(part...
{ range = rangeString.split(','); if (range.length === 1) { max = min = +range[0]; } else if (range.length === 2) { min = range[0].length ? +range[0] : undefined; max = range[1].length ? +range[1] : undefined; } if (!range.length || range.length > 2 || (max !== null && !...
conditional_block
main.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ mod disk; mod isolation; mod net; mod runtime; mod share; mod ssh; mod types; mod utils; mod vm; use std::env; use std::ffi::OsS...
{ /// Json-encoded file for VM machine configuration #[arg(long)] machine_spec: JsonFile<MachineOpts>, /// Json-encoded file describing paths of binaries required by VM #[arg(long)] runtime_spec: JsonFile<RuntimeOpts>, #[clap(flatten)] vm_args: VMArgs, } /// Spawn a container and execu...
RunCmdArgs
identifier_name
main.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ mod disk; mod isolation; mod net; mod runtime; mod share; mod ssh; mod types; mod utils; mod vm; use std::env; use std::ffi::OsS...
if !orig_args.output_dirs.is_empty() { return Err(anyhow!( "Test command must not specify --output-dirs. \ This will be parsed from env and test command parameters instead." )); } let envs = get_test_envs(cli_envs); #[derive(Debug, Parser)] struct TestArgsPa...
{ return Err(anyhow!("Test command must specify --timeout-secs.")); }
conditional_block
main.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ mod disk; mod isolation; mod net; mod runtime; mod share; mod ssh; mod types; mod utils; mod vm; use std::env; use std::ffi::OsS...
) .init(); Platform::set()?; debug!("Args: {:?}", env::args()); let cli = Cli::parse(); match &cli.command { Commands::Isolate(args) => respawn(args), Commands::Run(args) => run(args), Commands::Test(args) => test(args), } } #[cfg(test)] mod test { use ...
.with( tracing_subscriber::EnvFilter::builder() .with_default_directive(LevelFilter::INFO.into()) .from_env() .expect("Invalid logging level set by env"),
random_line_split
4167.user.js
// ==UserScript== // @name Amazon-Hennepin County Library Lookup // @version 1.3 // @description slightly modified version of - v1.3 Search the Seattle Public Library Catalog from Amazon book listings by fatknowledge. // @include http://*.amazon.* // ==/UserScript== // revision history: ...
getBookStatuses(); } else if ( libraryDueBack.test(page) ) { var due = page.match(libraryDueBack)[1]; setLibraryHTML( libraryUrlPattern, isbn, "Due back " + due, libraryFormat + " due back on " + due + " at "+ libraryName, "#AA7700" // dark ye...
random_line_split
4167.user.js
// ==UserScript== // @name Amazon-Hennepin County Library Lookup // @version 1.3 // @description slightly modified version of - v1.3 Search the Seattle Public Library Catalog from Amazon book listings by fatknowledge. // @include http://*.amazon.* // ==/UserScript== // revision history: ...
function updateStatusHTML(text) { var splStatusDiv = document.getElementById('splLinkyStatusHTML'); if (splStatusDiv == null) { return; } if (splStatusDiv.firstChild){ splStatusDiv.removeChild(splStatusDiv.firstChild); } splStatusDiv.appendChild(document.createTextNode(text)); } //add status of...
{ var title_node = getTitleNode(); if(!title_node) { if(DEBUG) GM_log("can't find title node"); return null; } var h1_node = title_node.parentNode; var br = document.createElement('br'); //the div for library status when found var splLinkyDiv = document.createElement(...
identifier_body
4167.user.js
// ==UserScript== // @name Amazon-Hennepin County Library Lookup // @version 1.3 // @description slightly modified version of - v1.3 Search the Seattle Public Library Catalog from Amazon book listings by fatknowledge. // @include http://*.amazon.* // ==/UserScript== // revision history: ...
(libraryUrlPattern, isbn){ if(DEBUG) GM_log('Searching: '+libraryUrlPattern + isbn); var libraryAvailability = /Checked In/; var libraryOnOrder = /(\d+) Copies On Order/; var libraryInProcess = /Pending/; var libraryTransitRequest = /Transit Request/; var libraryBeingHeld = /Being held/; var libraryH...
getBookStatus
identifier_name
error.rs
//! 9P error representations. //! //! In 9P2000 errors are represented as strings. //! All the error strings in this module are imported from include/net/9p/error.c of Linux kernel. //! //! By contrast, in 9P2000.L, errors are represented as numbers (errno). //! Using the Linux system errno numbers is the expected beha...
} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::No(ref e) => write!(f, "System error: {}", e.desc()), Error::Io(ref e) => write!(f, "I/O error: {}", e), } } } impl stderror::Error for Error { fn description...
random_line_split
error.rs
//! 9P error representations. //! //! In 9P2000 errors are represented as strings. //! All the error strings in this module are imported from include/net/9p/error.c of Linux kernel. //! //! By contrast, in 9P2000.L, errors are represented as numbers (errno). //! Using the Linux system errno numbers is the expected beha...
} impl From<nix::Error> for Error { fn from(e: nix::Error) -> Self { Error::No(e.errno()) } } /// The system errno definitions. /// /// # Protocol /// 9P2000.L pub mod errno { extern crate nix; pub use self::nix::errno::Errno::*; } /// 9P error strings imported from Linux. /// /// # Protocol...
{ Error::No(e) }
identifier_body
error.rs
//! 9P error representations. //! //! In 9P2000 errors are represented as strings. //! All the error strings in this module are imported from include/net/9p/error.c of Linux kernel. //! //! By contrast, in 9P2000.L, errors are represented as numbers (errno). //! Using the Linux system errno numbers is the expected beha...
(e: &io::Error) -> nix::errno::Errno { e.raw_os_error() .map(nix::errno::from_i32) .unwrap_or_else(|| match e.kind() { NotFound => ENOENT, PermissionDenied => EPERM, ConnectionRefused => ECONNREFUSED, ConnectionReset => ECONNRESET, Connecti...
errno_from_ioerror
identifier_name
test.container.ts
import {Component, OnInit} from "@angular/core"; import {select, Store} from "@ngrx/store"; import { Observable } from "rxjs"; import { SubTest, defaultSubTest, subTests, Test } from "../../../core/domain/tests.model"; import * as fromState from "../../../core/state"; import * as TestAction from "../../../core/state/t...
(){ this.recordAudio.stopRecording(); this.transcript_array = {}; this.current_seq = 0; this.final_transcript = this.interim_transcript; let me = this; let file_name:string = me.currentTestId + '_' + me.currentTest; this.isLoading = true; /** Combining all chunks into one single fil...
stopRecording
identifier_name
test.container.ts
import {Component, OnInit} from "@angular/core"; import {select, Store} from "@ngrx/store"; import { Observable } from "rxjs"; import { SubTest, defaultSubTest, subTests, Test } from "../../../core/domain/tests.model"; import * as fromState from "../../../core/state"; import * as TestAction from "../../../core/state/t...
this.isLoading = true; this.message = 'Saving tests data, please wait!'; if (event){ this.totalScore = this.subTests$[2].time * (80/(80 - this.subTests$[2].deletions + this.subTests$[2].additions)); /** * Update all sub tests data once recognition is finished */ this.subTest...
public calculateTotal(event: string){
random_line_split
test.container.ts
import {Component, OnInit} from "@angular/core"; import {select, Store} from "@ngrx/store"; import { Observable } from "rxjs"; import { SubTest, defaultSubTest, subTests, Test } from "../../../core/domain/tests.model"; import * as fromState from "../../../core/state"; import * as TestAction from "../../../core/state/t...
} public recognizeRecording(event: fileType){ let me = this; let file_name:string = me.currentTestId + '_' + event.subTest; me.currentTest = event.subTest; this.isLoading = true; this.message = 'Transcribing, please be patient!' switch (event.subTest) { case 0: me....
{ console.log('Setting language to: ', this.currentLangCode); this.final_transcript = ''; this.onStart(); this.ignore_onend = false; this.start_timestamp = new Date(); this.currentTest = event.selectedTest; console.log('Setting template by : ', this.currentTest); switc...
conditional_block
test.container.ts
import {Component, OnInit} from "@angular/core"; import {select, Store} from "@ngrx/store"; import { Observable } from "rxjs"; import { SubTest, defaultSubTest, subTests, Test } from "../../../core/domain/tests.model"; import * as fromState from "../../../core/state"; import * as TestAction from "../../../core/state/t...
/** * Initialize the component. */ public ngOnInit() { this.store$.pipe(select(fromState.selectCurrentPatient)).subscribe( (patient) => { if (patient) { this.currentPatientId = patient.patient_id; this.currentLangCode = patient.lang_code; } ...
{ }
identifier_body
detector.go
package light import ( "bytes" "context" "errors" "fmt" "time" "github.com/tendermint/tendermint/light/provider" "github.com/tendermint/tendermint/types" ) // The detector component of the light client detects and handles attacks on the light client. // More info here: // tendermint/docs/architecture/adr-047-...
(ctx context.Context, ev *types.LightClientAttackEvidence, receiver provider.Provider) { err := receiver.ReportEvidence(ctx, ev) if err != nil { c.logger.Error("Failed to report evidence to provider", "ev", ev, "provider", receiver) } } // handleConflictingHeaders handles the primary style of attack, which is whe...
sendEvidence
identifier_name
detector.go
package light import ( "bytes" "context" "errors" "fmt" "time" "github.com/tendermint/tendermint/light/provider" "github.com/tendermint/tendermint/types" ) // The detector component of the light client detects and handles attacks on the light client. // More info here: // tendermint/docs/architecture/adr-047-...
// We are suspecting that the primary is faulty, hence we hold the witness as the source of truth // and generate evidence against the primary that we can send to the witness commonBlock, trustedBlock := witnessTrace[0], witnessTrace[len(witnessTrace)-1] evidenceAgainstPrimary := newLightClientAttackEvidence(primar...
random_line_split
detector.go
package light import ( "bytes" "context" "errors" "fmt" "time" "github.com/tendermint/tendermint/light/provider" "github.com/tendermint/tendermint/types" ) // The detector component of the light client detects and handles attacks on the light client. // More info here: // tendermint/docs/architecture/adr-047-...
c.logger.Debug("Matching header received by witness", "height", h.Height, "witness", witnessIndex) errc <- nil } // sendEvidence sends evidence to a provider on a best effort basis. func (c *Client) sendEvidence(ctx context.Context, ev *types.LightClientAttackEvidence, receiver provider.Provider) { err := receive...
{ errc <- errConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex} }
conditional_block
detector.go
package light import ( "bytes" "context" "errors" "fmt" "time" "github.com/tendermint/tendermint/light/provider" "github.com/tendermint/tendermint/types" ) // The detector component of the light client detects and handles attacks on the light client. // More info here: // tendermint/docs/architecture/adr-047-...
// sendEvidence sends evidence to a provider on a best effort basis. func (c *Client) sendEvidence(ctx context.Context, ev *types.LightClientAttackEvidence, receiver provider.Provider) { err := receiver.ReportEvidence(ctx, ev) if err != nil { c.logger.Error("Failed to report evidence to provider", "ev", ev, "prov...
{ lightBlock, err := witness.LightBlock(ctx, h.Height) switch err { // no error means we move on to checking the hash of the two headers case nil: break // the witness hasn't been helpful in comparing headers, we mark the response and continue // comparing with the rest of the witnesses case provider.ErrNoRe...
identifier_body
BeanModel.ts
/* Generated from Java with JSweet 2.2.0-SNAPSHOT - http://www.jsweet.org */ import {CollectionAndSequence} from '../../core/CollectionAndSequence'; import {_DelayedFTLTypeDescription} from '../../core/_DelayedFTLTypeDescription'; import {_DelayedJQuote} from '../../core/_DelayedJQuote'; import {_TemplateModelException...
} if(this.object != null && (this.object instanceof Array)) { return /* isEmpty */((<any>this.object).length == 0); } // if((this.object != null && (this.object instanceof Object)) && this.wrapper.is2324Bugfixed()) { // return !(<Iterator><any>this.object).hasNext...
random_line_split
BeanModel.ts
/* Generated from Java with JSweet 2.2.0-SNAPSHOT - http://www.jsweet.org */ import {CollectionAndSequence} from '../../core/CollectionAndSequence'; import {_DelayedFTLTypeDescription} from '../../core/_DelayedFTLTypeDescription'; import {_DelayedJQuote} from '../../core/_DelayedJQuote'; import {_TemplateModelException...
() : TemplateCollectionModel { return new CollectionAndSequence(new SimpleSequence(this.keySet(), this.wrapper)); } public values() : TemplateCollectionModel { let values : Array<any> = <any>([]); let it : TemplateModelIterator = this.keys().iterator(); while((it.hasNext())) { ...
keys
identifier_name
BeanModel.ts
/* Generated from Java with JSweet 2.2.0-SNAPSHOT - http://www.jsweet.org */ import {CollectionAndSequence} from '../../core/CollectionAndSequence'; import {_DelayedFTLTypeDescription} from '../../core/_DelayedFTLTypeDescription'; import {_DelayedJQuote} from '../../core/_DelayedJQuote'; import {_TemplateModelException...
/** * Returns the same as {link #getWrappedObject()}; to ensure that, this method will be final starting from 2.4. * This behavior of {link BeanModel} is assumed by some FreeMarker code. * @param {*} hint * @return {Object} */ public getAdaptedObject(hint : any) : any { return...
{ if(typeof this.object === 'string') { return (<string>this.object).length === 0; } if(this.object != null && (this.object instanceof Array)) { return /* isEmpty */((<any>this.object).length == 0); } // if((this.object != null && (this.object instanceof O...
identifier_body
users.js
// needs dom.js, selector.js and ajax.js (all included in main) var groupSelector = null; // Using window.onload because an onclick="..." handler doesn't give the // handler a this-variable var old_load = window.onload; window.onload = function() { if (old_load) old_load(); $('password_button').parentNode.onsubmit ...
return {"added": added, "addable": addable}; } function groupSelectorInit() { groupSelector = new Selector({ "selectorId": "memberof", "urlPrefix": base_url + "groups/show/", "initCallback": initGroups, "addCallback": addMemberToGroupAjax, "removeCallback": removeMemberFromGroupAjax, "canLink": fu...
{ var group = groups[group_idx]; if (group.getAttribute("member") == "true") added[added.length] = group.getAttribute("name"); else addable[addable.length] = group.getAttribute("name"); }
conditional_block
users.js
// needs dom.js, selector.js and ajax.js (all included in main) var groupSelector = null; // Using window.onload because an onclick="..." handler doesn't give the // handler a this-variable var old_load = window.onload; window.onload = function() { if (old_load) old_load(); $('password_button').parentNode.onsubmit ...
function setIsAdminCB(response) { LogResponse(response); var setIsAdmin = FindResponse(response, 'setIsAdmin'); if (!setIsAdmin.success) { $('is_admin').checked = ! $('is_admin').checked; } } function checkPasswords() { // Again some cleaning up. this.firstChild.innerHTML = 'Password'; // Make sure the chan...
{ // this function is called when the checkbox is already changed. // the checkbox reflects the desired (new) value. Don't negate! var newvalue = $('is_admin').checked; AjaxAsyncPostRequest(document.location, "setIsAdmin=" + newvalue, setIsAdminCB); }
identifier_body
users.js
// needs dom.js, selector.js and ajax.js (all included in main) var groupSelector = null; // Using window.onload because an onclick="..." handler doesn't give the // handler a this-variable var old_load = window.onload; window.onload = function() { if (old_load) old_load(); $('password_button').parentNode.onsubmit ...
() { // this function is called when the checkbox is already changed. // the checkbox reflects the desired (new) value. Don't negate! var newvalue = $('is_admin').checked; AjaxAsyncPostRequest(document.location, "setIsAdmin=" + newvalue, setIsAdminCB); } function setIsAdminCB(response) { LogResponse(response); v...
setIsAdmin
identifier_name
users.js
// needs dom.js, selector.js and ajax.js (all included in main) var groupSelector = null; // Using window.onload because an onclick="..." handler doesn't give the // handler a this-variable var old_load = window.onload; window.onload = function() { if (old_load) old_load(); $('password_button').parentNode.onsubmit ...
AjaxAsyncPostRequest(document.location, "email=" + eemail, sendEmailCB); } function sendEmailCB(response) { // TODO: Before email is set, notifications are disabled LogResponse(response); reloadNotifications(); } function sendSendPasswordMail() { AjaxAsyncPostLog(document.location, "sendPasswordMail=1"); } fun...
function users_expand(me) { } function sendEmail() { var eemail = escape_plus($('email').value);
random_line_split
MobileChartDashboardItemConfigGenerator.Mobile.js
/** * @class Terrasoft.configuration.ChartDashboardItemConfigGenerator * Config generator of chart dashboard item. */ Ext.define("Terrasoft.configuration.ChartDashboardItemConfigGenerator", { extend: "Terrasoft.BaseDashboardItemConfigGenerator", alternateClassName: "Terrasoft.ChartDashboardItemConfigGenerator", ...
if (valueIsNotEmpty) { return result.join(Terrasoft.LS.MobileChartDashboardItemDatePartSeparator); } } return null; }, //endregion //region Methods: Protected /** * Gets default colors for dashboard. * @protected * @virtual */ getColors: function() { var colors = []; for (var colorName...
random_line_split
MobileChartDashboardItemConfigGenerator.Mobile.js
/** * @class Terrasoft.configuration.ChartDashboardItemConfigGenerator * Config generator of chart dashboard item. */ Ext.define("Terrasoft.configuration.ChartDashboardItemConfigGenerator", { extend: "Terrasoft.BaseDashboardItemConfigGenerator", alternateClassName: "Terrasoft.ChartDashboardItemConfigGenerator", ...
return caption; }, //endregion //region Methods: Public /** * Generates chart dashboard item config. * @param {Object} config Configuration object. * @param {Object} config.chartConfig Chart config. * @param {Object} config.chartData Chart data. * @return {Object} Chart dashboard item config. */ ge...
caption = Terrasoft.LS.MobileChartDashboardItemEmptyValueText; }
conditional_block
robots.py
''' Stuff related to robots.txt processing ''' import asyncio import time import random import json import logging import urllib.parse import hashlib import re import reppy.robots #import magic from .urls import URL from . import stats from . import fetcher from . import config from . import post_fetch from . impor...
(b): if b[:3] == b'\xef\xbb\xbf': # utf-8, e.g. microsoft.com's sitemaps return b[3:] elif b[:2] in (b'\xfe\xff', b'\xff\xfe'): # utf-16 BE and LE, respectively return b[2:] else: return b def robots_facets(text, robotname, json_log): user_agents = re.findall(r'^ \s* User-Age...
strip_bom
identifier_name
robots.py
''' Stuff related to robots.txt processing ''' import asyncio import time import random import json import logging import urllib.parse import hashlib import re import reppy.robots #import magic from .urls import URL from . import stats from . import fetcher from . import config from . import post_fetch from . impor...
json_log['host'] = schemenetloc print(json.dumps(json_log, sort_keys=True), file=self.robotslogfd)
if self.robotslogfd:
random_line_split
robots.py
''' Stuff related to robots.txt processing ''' import asyncio import time import random import json import logging import urllib.parse import hashlib import re import reppy.robots #import magic from .urls import URL from . import stats from . import fetcher from . import config from . import post_fetch from . impor...
if f.response.history: redir_history = [str(h.url) for h in f.response.history] redir_history.append(str(f.response.url)) json_log['redir_history'] = redir_history stats.stats_sum('robots fetched', 1) # If the url was redirected to a different host/robots....
json_log['error'] = 'max tries exceeded, final exception is: ' + f.last_exception self.jsonlog(schemenetloc, json_log) self.in_progress.discard(schemenetloc) return None
conditional_block
robots.py
''' Stuff related to robots.txt processing ''' import asyncio import time import random import json import logging import urllib.parse import hashlib import re import reppy.robots #import magic from .urls import URL from . import stats from . import fetcher from . import config from . import post_fetch from . impor...
def __del__(self): #if self.magic is not None: # self.magic.close() if self.robotslogfd: self.robotslogfd.close() def check_cached(self, url, quiet=False): schemenetloc = url.urlsplit.scheme + '://' + url.urlsplit.netloc try: robots = self.d...
self.robotname = robotname self.session = session self.datalayer = datalayer self.max_tries = config.read('Robots', 'MaxTries') self.max_robots_page_size = int(config.read('Robots', 'MaxRobotsPageSize')) self.in_progress = set() # magic is 3 milliseconds per call, too exp...
identifier_body
config_general.go
package chainlink import ( _ "embed" "fmt" "math/big" "net/url" "os" "path/filepath" "strings" "sync" "time" "github.com/pkg/errors" "go.uber.org/multierr" "go.uber.org/zap/zapcore" ocrnetworking "github.com/smartcontractkit/libocr/networking" "github.com/smartcontractkit/chainlink/v2/core/chains/cosm...
() int { return int(*g.c.AutoPprof.MutexProfileFraction) } func (g *generalConfig) AutoPprofPollInterval() models.Duration { return *g.c.AutoPprof.PollInterval } func (g *generalConfig) AutoPprofProfileRoot() string { s := *g.c.AutoPprof.ProfileRoot if s == "" { s = filepath.Join(g.RootDir(), "pprof") } retur...
AutoPprofMutexProfileFraction
identifier_name
config_general.go
package chainlink import ( _ "embed" "fmt" "math/big" "net/url" "os" "path/filepath" "strings" "sync" "time" "github.com/pkg/errors" "go.uber.org/multierr" "go.uber.org/zap/zapcore" ocrnetworking "github.com/smartcontractkit/libocr/networking" "github.com/smartcontractkit/chainlink/v2/core/chains/cosm...
func (g *generalConfig) Prometheus() coreconfig.Prometheus { return &prometheusConfig{s: g.secrets.Prometheus} } func (g *generalConfig) Mercury() coreconfig.Mercury { return &mercuryConfig{s: g.secrets.Mercury} } func (g *generalConfig) Threshold() coreconfig.Threshold { return &thresholdConfig{s: g.secrets.Thr...
{ return &passwordConfig{keystore: g.keystorePassword, vrf: g.vrfPassword} }
identifier_body
config_general.go
package chainlink import ( _ "embed" "fmt" "math/big" "net/url" "os" "path/filepath" "strings" "sync" "time" "github.com/pkg/errors" "go.uber.org/multierr" "go.uber.org/zap/zapcore" ocrnetworking "github.com/smartcontractkit/libocr/networking" "github.com/smartcontractkit/chainlink/v2/core/chains/cosm...
cfg := &generalConfig{ inputTOML: input, effectiveTOML: effective, secretsTOML: secrets, c: &o.Config, secrets: &o.Secrets, } if lvl := o.Config.Log.Level; lvl != nil { cfg.logLevelDefault = zapcore.Level(*lvl) } return cfg, nil } func (o *GeneralConfigOpts) parse() (err err...
{ return nil, err }
conditional_block
config_general.go
package chainlink import ( _ "embed" "fmt" "math/big" "net/url" "os" "path/filepath" "strings" "sync" "time" "github.com/pkg/errors" "go.uber.org/multierr" "go.uber.org/zap/zapcore" ocrnetworking "github.com/smartcontractkit/libocr/networking" "github.com/smartcontractkit/chainlink/v2/core/chains/cosm...
} func (g *generalConfig) LogConfiguration(log coreconfig.LogfFn) { log("# Secrets:\n%s\n", g.secretsTOML) log("# Input Configuration:\n%s\n", g.inputTOML) log("# Effective Configuration, with defaults applied:\n%s\n", g.effectiveTOML) } // ConfigTOML implements chainlink.ConfigV2 func (g *generalConfig) ConfigTOM...
if ok { err = multierr.Append(err, fmt.Errorf("environment variable %s must not be set: %v", k, v2.ErrUnsupported)) } } return
random_line_split
mod.rs
//! Entity handling types. //! //! An **entity** exclusively owns zero or more [component] instances, all of different types, and can dynamically acquire or lose them over its lifetime. //! //! **empty entity**: Entity with zero components. //! **pending entity**: Entity reserved, but not flushed yet (see [`Entities::f...
(&mut self, entity: Entity) -> Option<EntityLocation> { self.verify_flushed(); let loc = if entity.index as usize >= self.meta.len() { self.pending.extend((self.meta.len() as u32)..entity.index); let new_free_cursor = self.pending.len() as IdCursor; *self.free_cursor...
alloc_at
identifier_name
mod.rs
//! Entity handling types. //! //! An **entity** exclusively owns zero or more [component] instances, all of different types, and can dynamically acquire or lose them over its lifetime. //! //! **empty entity**: Entity with zero components. //! **pending entity**: Entity reserved, but not flushed yet (see [`Entities::f...
/// [`World`]: crate::world::World #[inline] pub fn total_count(&self) -> usize { self.meta.len() } /// The count of currently allocated entities. #[inline] pub fn len(&self) -> u32 { self.len } /// Checks if any entity is currently active. #[inline] pub fn ...
/// /// This does not include entities that have been reserved but have never been /// allocated yet. ///
random_line_split
mod.rs
//! Entity handling types. //! //! An **entity** exclusively owns zero or more [component] instances, all of different types, and can dynamically acquire or lose them over its lifetime. //! //! **empty entity**: Entity with zero components. //! **pending entity**: Entity reserved, but not flushed yet (see [`Entities::f...
else if let Some(index) = self.pending.iter().position(|item| *item == entity.index) { self.pending.swap_remove(index); let new_free_cursor = self.pending.len() as IdCursor; *self.free_cursor.get_mut() = new_free_cursor; self.len += 1; AllocAtWithoutReplaceme...
{ self.pending.extend((self.meta.len() as u32)..entity.index); let new_free_cursor = self.pending.len() as IdCursor; *self.free_cursor.get_mut() = new_free_cursor; self.meta .resize(entity.index as usize + 1, EntityMeta::EMPTY); self.len += 1; ...
conditional_block
mod.rs
//! Entity handling types. //! //! An **entity** exclusively owns zero or more [component] instances, all of different types, and can dynamically acquire or lose them over its lifetime. //! //! **empty entity**: Entity with zero components. //! **pending entity**: Entity reserved, but not flushed yet (see [`Entities::f...
/// Increments the `generation` of a freed [`Entity`]. The next entity ID allocated with this /// `index` will count `generation` starting from the prior `generation` + the specified /// value + 1. /// /// Does nothing if no entity with this `index` has been allocated yet. pub(crate) fn reserv...
{ // SAFETY: Caller guarantees that `index` a valid entity index self.meta.get_unchecked_mut(index as usize).location = location; }
identifier_body
windows.rs
//! Windows-specific types for signal handling. //! //! This module is only defined on Windows and contains the primary `Event` type //! for receiving notifications of events. These events are listened for via the //! `SetConsoleCtrlHandler` function which receives events of the type //! `CTRL_C_EVENT` and `CTRL_BREAK_...
() -> IoFuture<Event> { Event::ctrl_break_handle(&Handle::current()) } /// Creates a new stream listening for the `CTRL_BREAK_EVENT` events. /// /// This function will register a handler via `SetConsoleCtrlHandler` and /// deliver notifications to the returned stream. pub fn ctrl_break_...
ctrl_break
identifier_name
windows.rs
//! Windows-specific types for signal handling. //! //! This module is only defined on Windows and contains the primary `Event` type //! for receiving notifications of events. These events are listened for via the //! `SetConsoleCtrlHandler` function which receives events of the type //! `CTRL_C_EVENT` and `CTRL_BREAK_...
self.reg.clear_read_ready(Ready::readable())?; self.reg .get_ref() .inner .borrow() .as_ref() .unwrap() .1 .set_readiness(mio::Ready::empty()) .expect("failed to set readiness"); Ok(Async::Ready(Some(...
}
random_line_split
annexe.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import plotly.graph_objs as go import seaborn as sns FICHIERS = ["EdStatsCountry.csv","EdStatsCountry-Series.csv","EdStatsData.csv","EdStatsFootNote.csv" ,"EdStatsSeries.csv"] LOCALISATION ='F:/cour/OC/projet2/' INDEX = ["secondary","...
ataframe,titre,index=False,year='2001',column='Income Group'): if index: countries = dataframe.index.tolist() z = dataframe[year].tolist() titre = titre + year elif not index: countries = dataframe['Country Code'].tolist() z = dataframe[column].tolist() layout = dict(...
oropleth_map(d
identifier_name
annexe.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import plotly.graph_objs as go import seaborn as sns FICHIERS = ["EdStatsCountry.csv","EdStatsCountry-Series.csv","EdStatsData.csv","EdStatsFootNote.csv" ,"EdStatsSeries.csv"] LOCALISATION ='F:/cour/OC/projet2/' INDEX = ["secondary","...
for code in VALUES_NOT_WANTED: try: dataframe2 = dataframe2.drop([code],axis = 0) except: pass return dataframe2 def transforme_for_scatterplot(dataframe): df1 = dataframe.reset_index() df11 = df1.drop(df1.columns.difference(["Country Code","predic...
taframe2= dataframe2.rename(columns={year:new_column+"_"+year})
conditional_block
annexe.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import plotly.graph_objs as go import seaborn as sns FICHIERS = ["EdStatsCountry.csv","EdStatsCountry-Series.csv","EdStatsData.csv","EdStatsFootNote.csv" ,"EdStatsSeries.csv"] LOCALISATION ='F:/cour/OC/projet2/' INDEX = ["secondary","...
except: pass return dataframe2 def rank_dataframe(dataframe,new_column): dataframe2 = last_value(dataframe,new_column) dataframe2 = dataframe2.sort_values(by=new_column,ascending=False) maxi = float(dataframe2.iloc[0]) part = maxi/4 part2 = part part3 = part*2 ...
dataframe2 = dataframe2.drop([code],axis = 0)
random_line_split
annexe.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import plotly.graph_objs as go import seaborn as sns FICHIERS = ["EdStatsCountry.csv","EdStatsCountry-Series.csv","EdStatsData.csv","EdStatsFootNote.csv" ,"EdStatsSeries.csv"] LOCALISATION ='F:/cour/OC/projet2/' INDEX = ["secondary","...
def potential_years_study(dataframe1,dataframe2,selected_countries): dataframe = dataframe1.join(dataframe2,how='outer') dataframe.fillna(1,inplace=True) multiple_row = len(dataframe2.columns) new_col_list = [] if multiple_row>1: for column in range(len(dataframe2.columns)): ...
taframe2 = dataframe.copy() for country in NOT_IN_STUDY_YEARS: dataframe2.drop(dataframe2[dataframe2["Country Code"] == country].index,inplace =True) return dataframe2
identifier_body
node.go
// Copyright 2020 The Swarm 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 node defines the concept of a Bee node // by bootstrapping and injecting all necessary // dependencies. package node import ( "context" "crypto...
func (b *Bee) Shutdown(ctx context.Context) error { var mErr error // if a shutdown is already in process, return here b.shutdownMutex.Lock() if b.shutdownInProgress { b.shutdownMutex.Unlock() return ErrShutdownInProgress } b.shutdownInProgress = true b.shutdownMutex.Unlock() // halt kademlia while shut...
{ tracer, tracerCloser, err := tracing.NewTracer(&tracing.Options{ Enabled: o.TracingEnabled, Endpoint: o.TracingEndpoint, ServiceName: o.TracingServiceName, }) if err != nil { return nil, fmt.Errorf("tracer: %w", err) } p2pCtx, p2pCancel := context.WithCancel(context.Background()) defer func() { ...
identifier_body
node.go
// Copyright 2020 The Swarm 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 node defines the concept of a Bee node // by bootstrapping and injecting all necessary // dependencies. package node import ( "context" "crypto...
paymentEarly, ok := new(big.Int).SetString(o.PaymentEarly, 10) if !ok { return nil, fmt.Errorf("invalid payment early: %s", paymentEarly) } acc, err := accounting.NewAccounting( paymentThreshold, paymentTolerance, paymentEarly, logger, stateStore, pricing, big.NewInt(refreshRate), p2ps, ) if e...
{ return nil, fmt.Errorf("invalid payment tolerance: %s", paymentTolerance) }
conditional_block
node.go
// Copyright 2020 The Swarm 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 node defines the concept of a Bee node // by bootstrapping and injecting all necessary // dependencies. package node import ( "context" "crypto...
"github.com/ethersphere/bee/pkg/traversal" "github.com/hashicorp/go-multierror" ma "github.com/multiformats/go-multiaddr" "github.com/sirupsen/logrus" "golang.org/x/sync/errgroup" ) type Bee struct { p2pService io.Closer p2pHalter p2p.Halter p2pCancel context.CancelF...
"github.com/ethersphere/bee/pkg/topology" "github.com/ethersphere/bee/pkg/topology/kademlia" "github.com/ethersphere/bee/pkg/topology/lightnode" "github.com/ethersphere/bee/pkg/tracing" "github.com/ethersphere/bee/pkg/transaction"
random_line_split
node.go
// Copyright 2020 The Swarm 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 node defines the concept of a Bee node // by bootstrapping and injecting all necessary // dependencies. package node import ( "context" "crypto...
(ctx context.Context) error { err := p.node.Shutdown(ctx) if err != nil { return err } ps, err := os.FindProcess(syscall.Getpid()) if err != nil { return err } return ps.Kill() }
Shutdown
identifier_name
graphics2.js
//VAIABLES GLOBALES //OBTIENE EL OBJETO SELECCIONADO CON CLICK //var ONFOCUS_OBJECT; //OBTIENE LA LUZ SELECCIONADA DEL MENU var ONFOCUS_LIGHT; var KEYDOWN; var FUNCTION; var selected_object = null; var aux; var picking_method = 'transform'; // instantiate raycaster var ray...
ent ) { mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; } // callback event for mouse down function onDocumentMouseDown( event ) { // event.preventDefault(); event.stopPropagation(); raycaster.setFromCamera( ...
useMove( ev
identifier_name
graphics2.js
//VAIABLES GLOBALES //OBTIENE EL OBJETO SELECCIONADO CON CLICK //var ONFOCUS_OBJECT; //OBTIENE LA LUZ SELECCIONADA DEL MENU var ONFOCUS_LIGHT; var KEYDOWN; var FUNCTION; var selected_object = null; var aux; var picking_method = 'transform'; // instantiate raycaster var ray...
// update and render loop var isHex = function (posible_hex) { let re = /[0-9A-Fa-f]{6}/g; if (re.test(posible_hex)) { return true; } else { return false; } } // callback for event to change color function changeBackgroundColor(){ let ...
selected_object.material.color.setHex(shape_params.color); };
identifier_body
graphics2.js
//VAIABLES GLOBALES //OBTIENE EL OBJETO SELECCIONADO CON CLICK //var ONFOCUS_OBJECT; //OBTIENE LA LUZ SELECCIONADA DEL MENU var ONFOCUS_LIGHT; var KEYDOWN; var FUNCTION; var selected_object = null; var aux; var picking_method = 'transform'; // instantiate raycaster var ray...
//PERMITE QUE SE VEAN LAS SOMBRAS renderer.shadowMap.enabled = true; renderer.setSize(window.innerWidth,window.innerHeight); document.body.appendChild(renderer.domElement); //mouseOrbit = new THREE.OrbitControls(camera, renderer.domElement); mouseOrbit = new THREE.OrbitControls( camera...
renderer.setSize( window.innerWidth, window.innerHeight*escala );
random_line_split
graphics2.js
//VAIABLES GLOBALES //OBTIENE EL OBJETO SELECCIONADO CON CLICK //var ONFOCUS_OBJECT; //OBTIENE LA LUZ SELECCIONADA DEL MENU var ONFOCUS_LIGHT; var KEYDOWN; var FUNCTION; var selected_object = null; var aux; var picking_method = 'transform'; // instantiate raycaster var ray...
} } } var addRubikCube = function(){ var geometry = new THREE.BoxGeometry( 4, 4, 4 ); var material = new THREE.MeshBasicMaterial( {color: 0x000000} ); cubeMesh = new THREE.Mesh( geometry, material ); cubeMesh.position.y = 3; cuboRubik.position.y =-7.5; cuboRubik.position.x ...
let geometryC = new THREE.BoxGeometry(cube_width, cube_width, cube_width ); if(i==0){ //pintar abajo geometryC.faces[ 6 ].color.setHex(0x4b3621); geometryC.faces[ 7 ].color.setHex(0x4b3621); }else if(i==2){ ...
conditional_block
read-genome-coverage.py
#!/usr/bin/env python from __future__ import print_function, division, unicode_literals import os import sys import json import logging import tempfile import itertools import traceback import subprocess as sp from os.path import basename from datetime import datetime from argparse import ArgumentParser, FileType PRE...
update_counts(element, tot_counts, cont_counts, split_counts, is_split) break for k,v in n_skipped.iteritems(): log.info("Skipped {1} {0} lines".format(k, v)) return (tot_counts, cont_counts, split_counts) def write_output(stats, out, output_format='tsv', json_indent=4): i...
prev_rid = rid is_split = int(rbcount) > 1 except StopIteration:
random_line_split
read-genome-coverage.py
#!/usr/bin/env python from __future__ import print_function, division, unicode_literals import os import sys import json import logging import tempfile import itertools import traceback import subprocess as sp from os.path import basename from datetime import datetime from argparse import ArgumentParser, FileType PRE...
else: elem = element[0] split_counts[elem] = split_counts.get(elem, 0) + 1 else: cont_counts['total'] = cont_counts.get('total', 0) + 1 if len(element) > 1: if 'intergenic' in element: elem = 'others' else: elem = 'exonic_intronic'...
if len(set(element)) == 1: elem = element[0] else: if 'intergenic' in element: elem = 'others' else: elem = 'exonic_intronic'
conditional_block
read-genome-coverage.py
#!/usr/bin/env python from __future__ import print_function, division, unicode_literals import os import sys import json import logging import tempfile import itertools import traceback import subprocess as sp from os.path import basename from datetime import datetime from argparse import ArgumentParser, FileType PRE...
def write_output(stats, out, output_format='tsv', json_indent=4): if not args.ID: args.ID = basename(args.bam) if output_format == 'tsv': for k, v in stats.iteritems(): for k1, v1 in v.iteritems(): line_array = [args.ID, k, str(k1), str(v1)] out.wri...
n_skipped = {} newRead = False # keep track of different reads prev_rid = None # read id of the previous read is_split = False # check if current read is a split element = [] # list with all elements intersecting the read cont_counts = {} # Continuous read counts split_count...
identifier_body
read-genome-coverage.py
#!/usr/bin/env python from __future__ import print_function, division, unicode_literals import os import sys import json import logging import tempfile import itertools import traceback import subprocess as sp from os.path import basename from datetime import datetime from argparse import ArgumentParser, FileType PRE...
(genome=None, prefix='gencov'): """Annotation preprocessing. Provide a bed file with the following elements: - projected exons - projected genes - introns - integenic regions """ all_bed = prefix + ".all.bed" if not os.path.exists(all_bed) or os.stat(all_bed).st_si...
gtf_processing
identifier_name
main.js
/*** * Defines a rectangular object that can be rendered on the screen */ class Sprite { /** * * @param {number} x the x position of the top left corner * @param {number} y the y position of the top left corner */ constructor(x, y) { this.x = x; this.y = y; } /*** * Render the sprite a...
} } function draw() { //sprites on the top are drawn last //sprites added most recently are at the end of the list for(const sprite of sprites) { sprite.draw(); } } function clear() { ctx.clearRect(0, 0, canvas.width, canvas.height); } function render() { clear(); draw(); } function end_game(win) { ...
{ if (sprite.test_click(pos.x, pos.y, event.button)) { //needs to be unreversed return } }
conditional_block
main.js
/*** * Defines a rectangular object that can be rendered on the screen */ class Sprite { /** * * @param {number} x the x position of the top left corner * @param {number} y the y position of the top left corner */ constructor(x, y) { this.x = x; this.y = y; } /*** * Render the sprite a...
() { //updates all the tiles by 1 turn passed for (let i = 0; i < this.width; i++) { for (let j = 0; j < this.height; j++) { if (this.grid[i][j] > 0) { this.grid[i][j] = (this.grid[i][j] + 1) % this.length; } } } let nextX = 0; let nextY = 0; //next find th...
step_turn
identifier_name
main.js
/*** * Defines a rectangular object that can be rendered on the screen */ class Sprite { /** * * @param {number} x the x position of the top left corner * @param {number} y the y position of the top left corner */ constructor(x, y) { this.x = x; this.y = y; } /*** * Render the sprite a...
left_click() {} right_click() {} test_click(x, y, button) { if (x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.height) { if (button === 0) { this.left_click(); } else if (button === 2) { this.right_click() } return true; } return ...
this.width = width; this.height = height; }
random_line_split
extern_crate.rs
//! Provides handling of `extern_crate` attributes. //! //! # What the generated code looks like //! //! ```rust,ignore //! #[pre::extern_crate(std)] //! mod pre_std { //! mod ptr { //! #[pre(valid_ptr(src, r))] //! unsafe fn read<T>(src: *const T) -> T; //! //! impl<T> NonNull<T> { //! ...
// Update the spans of the `::` tokens to lie in the function for punct in path .segments .pairs_mut() .map(|p| p.into_tuple().1) .flatten() { punct.spans = [function.span(); 2]; } let mut args_list = TokenStream::new(); args_list.append_separated( ...
arguments: PathArguments::None, });
random_line_split
extern_crate.rs
//! Provides handling of `extern_crate` attributes. //! //! # What the generated code looks like //! //! ```rust,ignore //! #[pre::extern_crate(std)] //! mod pre_std { //! mod ptr { //! #[pre(valid_ptr(src, r))] //! unsafe fn read<T>(src: *const T) -> T; //! //! impl<T> NonNull<T> { //! ...
} /// Generates the code for a function inside a `extern_crate` module. fn render_function( function: &ForeignItemFn, tokens: &mut TokenStream, path: &Path, visibility: &TokenStream, ) { tokens.append_all(&function.attrs); let doc_header = generate_extern_crate_fn_docs(path, &function.sig, fun...
{ let mut stream = TokenStream::new(); stream.append_all(&self.attrs); let vis = &self.visibility; stream.append_all(quote! { #vis }); stream.append_all(quote! { mod }); stream.append(self.ident.clone()); let mut content = TokenStream::new(); content.appe...
identifier_body
extern_crate.rs
//! Provides handling of `extern_crate` attributes. //! //! # What the generated code looks like //! //! ```rust,ignore //! #[pre::extern_crate(std)] //! mod pre_std { //! mod ptr { //! #[pre(valid_ptr(src, r))] //! unsafe fn read<T>(src: *const T) -> T; //! //! impl<T> NonNull<T> { //! ...
(input: ParseStream) -> syn::Result<Self> { let attrs = input.call(Attribute::parse_outer)?; let visibility = input.parse()?; let mod_token = input.parse()?; let ident = input.parse()?; let content; let braces = braced!(content in input); let mut impl_blocks = V...
parse
identifier_name
extern_crate.rs
//! Provides handling of `extern_crate` attributes. //! //! # What the generated code looks like //! //! ```rust,ignore //! #[pre::extern_crate(std)] //! mod pre_std { //! mod ptr { //! #[pre(valid_ptr(src, r))] //! unsafe fn read<T>(src: *const T) -> T; //! //! impl<T> NonNull<T> { //! ...
else if <ItemUse as Parse>::parse(&content.fork()).is_ok() { imports.push(content.parse()?); } else if <ForeignItemFn as Parse>::parse(&content.fork()).is_ok() { functions.push(content.parse()?); } else { modules.push(content.parse().map_err(|err|...
{ impl_blocks.push(content.parse()?); }
conditional_block
TreeDecomposition.py
# class to implement the nice tree decomposition conversion # from paper # 'Solving connectivity problems parameterized by treewidth in # single exponential time' [Cygan,Nederlof,Pilipczuk,Rooij,Wojtaszczyk] # TODO assert isIstance etc, class name, class functions, bag as set # TODO getTreewidth from BagType import B...
# execute inorder_edge_bag for each edge def edge_bags(ntree, edges): for edge in edges: inorder_edge_bag(ntree, edge, False) # this function traverse the tree in-order # for each edge of the initial graph and # should place an extra 'introduce edge bag' # above the first node which contains the edge def ...
return False
random_line_split
TreeDecomposition.py
# class to implement the nice tree decomposition conversion # from paper # 'Solving connectivity problems parameterized by treewidth in # single exponential time' [Cygan,Nederlof,Pilipczuk,Rooij,Wojtaszczyk] # TODO assert isIstance etc, class name, class functions, bag as set # TODO getTreewidth from BagType import B...
return True def contains_edge(edge, bag): return len(set(edge).intersection(set(bag))) == 2 def increment_index(): global index index += 1 def save_header(file): file.write("graph NiceTreeDecomposition {\n") file.write("size=\"1,1\";\n") file.write("node [shape=box];\n") def...
return False
conditional_block
TreeDecomposition.py
# class to implement the nice tree decomposition conversion # from paper # 'Solving connectivity problems parameterized by treewidth in # single exponential time' [Cygan,Nederlof,Pilipczuk,Rooij,Wojtaszczyk] # TODO assert isIstance etc, class name, class functions, bag as set # TODO getTreewidth from BagType import B...
(ntree, edges): for edge in edges: inorder_edge_bag(ntree, edge, False) # this function traverse the tree in-order # for each edge of the initial graph and # should place an extra 'introduce edge bag' # above the first node which contains the edge def inorder_edge_bag(ntree, edge, found): if not found...
edge_bags
identifier_name
TreeDecomposition.py
# class to implement the nice tree decomposition conversion # from paper # 'Solving connectivity problems parameterized by treewidth in # single exponential time' [Cygan,Nederlof,Pilipczuk,Rooij,Wojtaszczyk] # TODO assert isIstance etc, class name, class functions, bag as set # TODO getTreewidth from BagType import B...
def __str__(self): return str(self.bag) def get_right(self): return self.right def get_left(self): return self.left def get_bag(self): return self.bag def set_right(self, right): self.right = right def set_left(self, left...
return self.bag_type
identifier_body
webserver.ts
// Strautomator: WebServer import {strava, paypal} from "strautomator-core" import express = require("express") import _ from "lodash" import fs = require("fs") import http = require("http") import https = require("https") import logger from "anyhow" import path = require("path") const settings = require("setmeup").se...
try { if (!strava.webhooks.current || strava.webhooks.current.callbackUrl != strava.webhooks.callbackUrl) { try { await strava.webhooks.cancelWebhook() } catch (cancelEx) { logger.warn("WebServer.setupWebhooks", "Could not cance...
random_line_split
webserver.ts
// Strautomator: WebServer import {strava, paypal} from "strautomator-core" import express = require("express") import _ from "lodash" import fs = require("fs") import http = require("http") import https = require("https") import logger from "anyhow" import path = require("path") const settings = require("setmeup").se...
(): WebServer { return this._instance || (this._instance = new this()) } /** * The Express app. */ app: express.Express /** * The underlying HTTP(S) server. */ server: http.Server // INIT // ----------------------------------------------------------------------...
Instance
identifier_name
webserver.ts
// Strautomator: WebServer import {strava, paypal} from "strautomator-core" import express = require("express") import _ from "lodash" import fs = require("fs") import http = require("http") import https = require("https") import logger from "anyhow" import path = require("path") const settings = require("setmeup").se...
try { // Error inside another .error property? if (error.error && !error.message && !error.error_description && !error.reason) { error = error.error } if (_.isString(error)) { message = {message: error} } else { ...
{ status = 500 }
conditional_block
app.js
"use strict"; function _typeof(obj)
var app; app = angular.module('app', ['angularMoment', 'ngCookies', 'ngStorage', 'angular-loading-bar', 'ui.bootstrap', 'ngContextMenu', 'ngSidebarJS', 'ng.ckeditor', 'ng.multicombo'], ["$locationProvider", "$sceProvider", function ($locationProvider, $sceProvider) { $locationProvider.html5Mode(true); }]); //$scePr...
{ "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typ...
identifier_body
app.js
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj ...
return str; }; /* Custom functions */ angular.isEmpty = function (val) { return angular.isUndefined(val) || val === null || val === ''; }; angular.isDateValid = function (date) { if (date === void 0 || date === null) { return false; } if (!moment(date).isValid()) { return; } if (moment(...
{ str += String.fromCharCode(parseInt(hex.substr(n, 2), 16)); n += 2; }
conditional_block
app.js
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj ...
// * Removing context menu DOM from page. // * @return {[type]} [description] // */ // function removeContextMenu() { // $('.custom-context-menu').remove(); // } // /** // * Apply new css class for right positioning. // * @param {[type]} cssClass [description] // * @return {[type]}...
// divider.className = 'divider' // fragment.appendChild(divider); // } // /**
random_line_split
app.js
"use strict"; function
(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol"...
_typeof
identifier_name
app.js
'use strict'; // IDs constants const GAME_CONTAINER = 'game-container'; const WELCOME_SCREEN = 'welcome-screen'; const START_GAME = 'start-game'; const FINISH_GAME = 'finish-game'; const START_BTN = 'start-btn'; // Classes constants const CONTAINER = 'container'; const DECK = 'deck'; const CARD = 'card'; const OPEN_C...
return array; } /* * * Event listners functions * */ function startListener(event) { document.querySelector(`#${WELCOME_SCREEN}`).style.display = 'none'; event.currentTarget.removeEventListener('click', startListener); startGame(); } function cardsListener(event) { const { target } = event; const { ...
currentIndex -= 1; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; }
random_line_split
app.js
'use strict'; // IDs constants const GAME_CONTAINER = 'game-container'; const WELCOME_SCREEN = 'welcome-screen'; const START_GAME = 'start-game'; const FINISH_GAME = 'finish-game'; const START_BTN = 'start-btn'; // Classes constants const CONTAINER = 'container'; const DECK = 'deck'; const CARD = 'card'; const OPEN_C...
// Shuffle function from http://stackoverflow.com/a/2450976 function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; while (currentIndex !== 0) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; ...
{ const [firstCard, secondCard] = pairOfCards; const typeOfFirst = firstCard.firstElementChild.classList[1]; const typeOfSecond = secondCard.firstElementChild.classList[1]; // Check if the pair of cards match or else no match if (typeOfFirst === typeOfSecond) { firstCard.classList.add(MATCH_CARD); se...
identifier_body
app.js
'use strict'; // IDs constants const GAME_CONTAINER = 'game-container'; const WELCOME_SCREEN = 'welcome-screen'; const START_GAME = 'start-game'; const FINISH_GAME = 'finish-game'; const START_BTN = 'start-btn'; // Classes constants const CONTAINER = 'container'; const DECK = 'deck'; const CARD = 'card'; const OPEN_C...
() { const moves = document.querySelector(`.${MOVES_COUNTER}`); let movesNumber = Number(moves.innerText); moves.innerText = ++movesNumber; const stars = document.querySelectorAll(`.${STARS}>li`); // Based on the number of moves replace the FULL_STAR with EMPTY_STAR switch (movesNumber) { case 10: ...
updateScorePanel
identifier_name
app.js
'use strict'; // IDs constants const GAME_CONTAINER = 'game-container'; const WELCOME_SCREEN = 'welcome-screen'; const START_GAME = 'start-game'; const FINISH_GAME = 'finish-game'; const START_BTN = 'start-btn'; // Classes constants const CONTAINER = 'container'; const DECK = 'deck'; const CARD = 'card'; const OPEN_C...
} // Shuffle function from http://stackoverflow.com/a/2450976 function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; while (currentIndex !== 0) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; ...
{ setTimeout(() => { firstCard.classList.add(NO_MATCH_CARD); secondCard.classList.add(NO_MATCH_CARD); }, NO_MATCH_DELAY); setTimeout(() => { firstCard.classList.remove(OPEN_CARD, SHOW_CARD, NO_MATCH_CARD); secondCard.classList.remove(OPEN_CARD, SHOW_CARD, NO_MATCH_CARD); }, HIDI...
conditional_block
lib.rs
#[macro_use] extern crate lazy_static; #[macro_use] extern crate log; use std::any::Any; use std::borrow::Cow; use std::fmt::Display; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread; use crossbeam::channel::{Receiver, Sender}; use tuikit::prelude::{Event as TermEvent, *}; pub use crate::ansi::AnsiS...
} //------------------------------------------------------------------------------ // Display Context pub enum Matches<'a> { None, CharIndices(&'a [usize]), CharRange(usize, usize), ByteRange(usize, usize), } pub struct DisplayContext<'a> { pub text: &'a str, pub score: i32, pub matches: ...
{ Cow::Borrowed(self.as_ref()) }
identifier_body
lib.rs
#[macro_use] extern crate lazy_static; #[macro_use] extern crate log; use std::any::Any; use std::borrow::Cow; use std::fmt::Display; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread; use crossbeam::channel::{Receiver, Sender}; use tuikit::prelude::{Event as TermEvent, *}; pub use crate::ansi::AnsiS...
/// want, you could still use `downcast` to retain the pointer to the original struct. fn output(&self) -> Cow<str> { self.text() } /// we could limit the matching ranges of the `get_text` of the item. /// providing (start_byte, end_byte) of the range fn get_matching_ranges(&self) -> Op...
/// Get output text(after accept), default to `text()` /// Note that this function is intended to be used by the caller of skim and will not be used by /// skim. And since skim will return the item back in `SkimOutput`, if string is not what you
random_line_split
lib.rs
#[macro_use] extern crate lazy_static; #[macro_use] extern crate log; use std::any::Any; use std::borrow::Cow; use std::fmt::Display; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread; use crossbeam::channel::{Receiver, Sender}; use tuikit::prelude::{Event as TermEvent, *}; pub use crate::ansi::AnsiS...
() -> Self { CaseMatching::Smart } } #[derive(PartialEq, Eq, Clone, Debug)] #[allow(dead_code)] pub enum MatchRange { ByteRange(usize, usize), // range of bytes Chars(Vec<usize>), // individual character indices matched } pub type Rank = [i32; 4]; #[derive(Clone)] pub struct MatchResult { ...
default
identifier_name
eventEngine.py
""" Copyright (C) 2015-2016, Juniper Networks, Inc. All rights reserved. Authors: jpzhao, bphillips, ajaykv Description: Toby Network Event Engine. """ # pylint: disable=locally-disabled,undefined-variable,invalid-name import re #import copy import os import sys #import types #import pprint import time impor...
#raise Exception('event failed with error: ' + str(error)) elog('error', 'event failed with error: ' + str(error)) return False return True def _confirm_event_state(self, event, **kwargs): ''' check to confirm event status ''' if not kwarg...
# return True/false or raise exception when failed?? #ret = False if error > 0 else True if error > 0: # Todo: an eventException to standardize error msg
random_line_split
eventEngine.py
""" Copyright (C) 2015-2016, Juniper Networks, Inc. All rights reserved. Authors: jpzhao, bphillips, ajaykv Description: Toby Network Event Engine. """ # pylint: disable=locally-disabled,undefined-variable,invalid-name import re #import copy import os import sys #import types #import pprint import time impor...
def _update_events(self, events): ''' updagate events to ee's attribute 'events_registered' ''' registered_events = {} for event in events: registered_events[event] = {} for action in events[event]: # trigger or check if events[eve...
''' call Robot keyword inside event engine ''' # TBD: if it is Toby keyword, call them directly with Python code? my_args = [] keyword = None if kwargs: for key, val in kwargs.items(): if key == 'ROBOT_keyword': keyword = va...
identifier_body
eventEngine.py
""" Copyright (C) 2015-2016, Juniper Networks, Inc. All rights reserved. Authors: jpzhao, bphillips, ajaykv Description: Toby Network Event Engine. """ # pylint: disable=locally-disabled,undefined-variable,invalid-name import re #import copy import os import sys #import types #import pprint import time impor...
else: raise Exception('missing mandatory argument "{}" in event "{}"'.\ format(default_targ, event)) ## adjust args depending on the type of method if trigger_method['type'].get('ROBOT_keyword'): trg_kwargs['ROBOT_keyw...
trg_kwargs.update({targ: tval}) # take registered default value
conditional_block
eventEngine.py
""" Copyright (C) 2015-2016, Juniper Networks, Inc. All rights reserved. Authors: jpzhao, bphillips, ajaykv Description: Toby Network Event Engine. """ # pylint: disable=locally-disabled,undefined-variable,invalid-name import re #import copy import os import sys #import types #import pprint import time impor...
(self, event, **kwargs): ''' check to confirm event status ''' if not kwargs.get('enable_check'): return True self.status = True func_list = self._get_event_functions(event) st_check = False if func_list.get('check'): check_kwargs ...
_confirm_event_state
identifier_name
dynamic_store.rs
// Copyright 2017 Amagicom AB. // // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to...
} } /// Sets the value of the given key. Overwrites existing values. /// Returns `true` on success, false on failure. pub fn set<S: Into<CFString>, V: CFPropertyListSubClass>(&self, key: S, value: V) -> bool { self.set_raw(key, &value.into_CFPropertyList()) } /// Sets the valu...
{ None }
conditional_block
dynamic_store.rs
// Copyright 2017 Amagicom AB. // // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to...
} /// The raw callback used by the safe `SCDynamicStore` to convert from the `SCDynamicStoreCallBack` /// to the `SCDynamicStoreCallBackT` unsafe extern "C" fn convert_callback<T>( store_ref: SCDynamicStoreRef, changed_keys_ref: CFArrayRef, context_ptr: *mut c_void, ) { let store = SCDynamicStore::wra...
{ unsafe { let run_loop_source_ref = SCDynamicStoreCreateRunLoopSource( kCFAllocatorDefault, self.as_concrete_TypeRef(), 0, ); CFRunLoopSource::wrap_under_create_rule(run_loop_source_ref) } }
identifier_body
dynamic_store.rs
// Copyright 2017 Amagicom AB. // // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to...
( &self, callback_context: SCDynamicStoreCallBackContext<T>, ) -> SCDynamicStoreContext { // move the callback context struct to the heap and "forget" it. // It will later be brought back into the Rust typesystem and freed in // `release_callback_context` let info_ptr...
create_context
identifier_name
dynamic_store.rs
// Copyright 2017 Amagicom AB. // // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to...
let info_ptr = Box::into_raw(Box::new(callback_context)); SCDynamicStoreContext { version: 0, info: info_ptr as *mut _ as *mut c_void, retain: None, release: Some(release_callback_context::<T>), copyDescription: None, } } } declar...
// It will later be brought back into the Rust typesystem and freed in // `release_callback_context`
random_line_split
filter_list.rs
// 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 in the LICENSE-APACHE file or at: // https://www.apache.org/licenses/LICENSE-2.0 //! Filter-list view widget use super::{driver, Driver, Li...
result } fn iter_vec_from(&self, start: usize, limit: usize) -> Vec<(Self::Key, Self::Item)> { let view = self.view.borrow(); let end = self.len().min(start + limit); if start >= end { return Vec::new(); } let mut v = Vec::with_capacity(end - start);...
{ // remove the updated item from our filtered list self.view.borrow_mut().retain(|item| item != key); }
conditional_block
filter_list.rs
// 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 in the LICENSE-APACHE file or at: // https://www.apache.org/licenses/LICENSE-2.0 //! Filter-list view widget use super::{driver, Driver, Li...
fn update_self(&self) -> Option<UpdateHandle> { self.refresh() } } impl<K, M, T: ListData + UpdatableHandler<K, M> + 'static, F: Filter<T::Item>> UpdatableHandler<K, M> for FilteredList<T, F> { fn handle(&self, key: &K, msg: &M) -> Option<UpdateHandle> { self.data.handle(key, msg) ...
{ self.filter.update_handle() }
identifier_body
filter_list.rs
// 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 in the LICENSE-APACHE file or at: // https://www.apache.org/licenses/LICENSE-2.0 //! Filter-list view widget use super::{driver, Driver, Li...
(&self) -> usize { self.view.borrow().len() } fn contains_key(&self, key: &Self::Key) -> bool { self.get_cloned(key).is_some() } fn get_cloned(&self, key: &Self::Key) -> Option<Self::Item> { // Check the item against our filter (probably O(1)) instead of using // our fi...
len
identifier_name
filter_list.rs
// 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 in the LICENSE-APACHE file or at: // https://www.apache.org/licenses/LICENSE-2.0 //! Filter-list view widget use super::{driver, Driver, Li...
} } impl< D: Directional, T: ListData + UpdHandler<T::Key, V::Msg>, F: Filter<T::Item>, V: Driver<T::Item>, > FilterListView<D, T, F, V> { /// Construct a new instance with explicit direction and view pub fn new_with_dir_driver(direction: D, view: V, data: T, filter: F) -...
/// Set the direction of contents pub fn set_direction(&mut self, direction: Direction) -> TkAction { self.list.set_direction(direction)
random_line_split
mod.rs
//! `types` module contains types necessary for Fluent runtime //! value handling. //! The core struct is [`FluentValue`] which is a type that can be passed //! to the [`FluentBundle::format_pattern`](crate::bundle::FluentBundle) as an argument, it can be passed //! to any Fluent Function, and any function may return i...
(v: Option<T>) -> Self { match v { Some(v) => v.into(), None => FluentValue::None, } } }
from
identifier_name