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 |
|---|---|---|---|---|
wavent.py | out + skips[args.wavenet_blocks - 2 - i][:,(2**args.dilation_layers_per_block - 1)*(i+1):]
for i in range(3):
out = lib.ops.conv1d("out_{}".format(i+1), out, args.dim, args.dim, 1, non_linearity='relu')
out = lib.ops.conv1d("final", out, args.dim, args.q_levels, 1, non_linearity='identity')
retu... | 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 |
# 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 | **args.dilation_layers_per_block - 1)*args.wavenet_blocks + 1# How many samples per frame
#GLOBAL_NORM = args.global_norm
DIM = args.dim # Model dimensionality.
Q_LEVELS = args.q_levels # How many levels to use when discretizing samples. e.g. 256 = 8-bit scalar quantization
Q_TYPE = args.q_type # log- or linear-scale
#... | 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 | (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 | _.contains(availableTypesNames, parsed.type)) {
throw new Error('invalid type "' + typeString + '", must be [' + availableTypesNames.join(',') + ']');
}
// parse rage string
rangeString = rangeString.replace(/\s*/g, '');
if (rangeString) {
range = rangeString.split(',');
if (range.length === 1... | random_line_split | ||
utils.js | Name = ruleName.trim();
if (!_.contains(options.rules, ruleName)) {
throw new Error('unavailable rule "' + ruleName + '"');
}
if (ruleName === 'required' || ruleName === 'optional') {
if (object.validation.required !== VALIDATION_REQUIRED_DEFVAL) {
throw new Error('required/optional rules conflict');
... | }
// 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... | {
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 | use crate::isolation::is_isolated;
use crate::isolation::isolated;
use crate::isolation::Platform;
use crate::runtime::set_runtime;
use crate::types::MachineOpts;
use crate::types::RuntimeOpts;
use crate::types::VMArgs;
use crate::utils::console_output_path_for_tpx;
use crate::utils::log_command;
use crate::vm::VM;
ty... | {
/// 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 | use crate::isolation::is_isolated;
use crate::isolation::isolated;
use crate::isolation::Platform;
use crate::runtime::set_runtime;
use crate::types::MachineOpts;
use crate::types::RuntimeOpts;
use crate::types::VMArgs;
use crate::utils::console_output_path_for_tpx;
use crate::utils::log_command;
use crate::vm::VM;
ty... |
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 | ;
use crate::isolation::is_isolated;
use crate::isolation::isolated;
use crate::isolation::Platform;
use crate::runtime::set_runtime;
use crate::types::MachineOpts;
use crate::types::RuntimeOpts;
use crate::types::VMArgs;
use crate::utils::console_output_path_for_tpx;
use crate::utils::log_command;
use crate::vm::VM;
... | )
.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:: | .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 | /xisbn/' + isbn;
GM_xmlhttpRequest({
method: 'GET',
url: wbUrl,
headers: {
'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3',
'Accept': 'application/atom+xml,application/xml,text/xml',
},
onload: function(responseDetails) {
if(DEBUG) GM_log(responseDetails... | 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 | }
});
}
//loop through all the isbns
//this gets called back after each search to do next isbn
function getBookStatuses(){
isbnsIndex++;
if(DEBUG) GM_log("getBookStatuses"+isbnsIndex+ " " + isbns.length);
if (isbnsIndex < isbns.length){
if(VERBOSE) updateStatusHTML("Searching for ISBN "+ isbns[... | {
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 | /xisbn/' + isbn;
GM_xmlhttpRequest({
method: 'GET',
url: wbUrl,
headers: {
'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3',
'Accept': 'application/atom+xml,application/xml,text/xml',
},
onload: function(responseDetails) {
if(DEBUG) GM_log(responseDetails... | (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 | => EINVAL,
TimedOut => ETIMEDOUT,
WriteZero => EAGAIN,
Interrupted => EINTR,
Other | _ => EIO,
})
}
/// 9P error type which is convertible to an errno.
///
/// The value of `Error::errno()` will be used for Rlerror.
///
/// # Protocol
/// 9P2000.L
#[derive(Debug... | }
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 | => EINVAL,
TimedOut => ETIMEDOUT,
WriteZero => EAGAIN,
Interrupted => EINTR,
Other | _ => EIO,
})
}
/// 9P error type which is convertible to an errno.
///
/// The value of `Error::errno()` will be used for Rlerror.
///
/// # Protocol
/// 9P2000.L
#[derive(Debug... |
}
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 | (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 | ] = "currentLangCode"
[currentText] = "final_transcript"
[triggerChange] = "triggerChange"
[totalScore] = "totalScore"
[overall_comment] = "overall_comment"
(recognize) = toggleRecording($event)
(file_context) = recognizeRecording($event)
(calculate_... | (){
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 | <any>,
private ioService:IoService,
private fileService: FileService,
private testService: TestService,
private subTestsService: SubTestsService
) {
}
/**
* Initialize the component.
*/
public ngOnInit... |
public calculateTotal(event: string){ | random_line_split | |
test.container.ts | Recording($event)
(file_context) = recognizeRecording($event)
(calculate_total) = calculateTotal($event)>
</app-test-component>
<app-loader *ngIf = "isLoading" [message] = "message"></app-loader>
`
})
export class TestContainer implements OnInit {
/**
* The username for the currently ... | {
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 | = "currentLangCode"
[currentText] = "final_transcript"
[triggerChange] = "triggerChange"
[totalScore] = "totalScore"
[overall_comment] = "overall_comment"
(recognize) = toggleRecording($event)
(file_context) = recognizeRecording($event)
(calculate_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 | attempt to generate conflicting headers failed then remove witness
witnessesToRemove = append(witnessesToRemove, e.WitnessIndex)
case errBadWitness:
// these are all melevolent errors and should result in removing the
// witness
c.logger.Info("witness returned an error during header comparison, removing... | (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 | attempt to generate conflicting headers failed then remove witness
witnessesToRemove = append(witnessesToRemove, e.WitnessIndex)
case errBadWitness:
// these are all melevolent errors and should result in removing the
// witness
c.logger.Info("witness returned an error during header comparison, removing... | // 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 | to generate conflicting headers failed then remove witness
witnessesToRemove = append(witnessesToRemove, e.WitnessIndex)
case errBadWitness:
// these are all melevolent errors and should result in removing the
// witness
c.logger.Info("witness returned an error during header comparison, removing...",
... |
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 | attempt to generate conflicting headers failed then remove witness
witnessesToRemove = append(witnessesToRemove, e.WitnessIndex)
case errBadWitness:
// these are all melevolent errors and should result in removing the
// witness
c.logger.Info("witness returned an error during header comparison, removing... | var isTargetHeight bool
isTargetHeight, lightBlock, err = c.getTargetBlockOrLatest(ctx, h.Height, witness)
if err != nil {
errc <- err
return
}
// if the witness caught up and has returned a block of the target height then we can
// break from this switch case and continue to verify the hashes
if i... | {
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 | null) {
// this.wrapper.getClassIntrospector().get(object.constructor);
// }
}
public get$java_lang_String(key : string) : TemplateModel {
if(this.object.hasOwnProperty(key)) {
const value = this.object[key];
if(typeof value === 'function') {
... | random_line_split | ||
BeanModel.ts | // return model;
// }
// let fd : any = /* get */classInfo.get(key);
// if(fd != null) {
// retval = this.invokeThroughDescriptor(fd, classInfo);
// if(retval === BeanModel.UNKNOWN_$LI$() && model === nullModel) ... | keys | identifier_name | |
BeanModel.ts | MethodsShadowItems()) {
// let fd : any = /* get */classInfo.get(key);
// if(fd != null) {
// retval = this.invokeThroughDescriptor(fd, classInfo);
// } else {
// retval = this.invokeGenericGet(classInfo, clazz, key);
// ... | {
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 | .onsubmit = saveNotifications;
}
function users_collapse(me) {
}
function users_expand(me) {
}
function sendEmail() {
var eemail = escape_plus($('email').value);
AjaxAsyncPostRequest(document.location, "email=" + eemail, sendEmailCB);
}
function sendEmailCB(response) {
// TODO: Before email is set, notification... |
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 | .onsubmit = saveNotifications;
}
function users_collapse(me) {
}
function users_expand(me) {
}
function sendEmail() {
var eemail = escape_plus($('email').value);
AjaxAsyncPostRequest(document.location, "email=" + eemail, sendEmailCB);
}
function sendEmailCB(response) {
// TODO: Before email is set, notification... |
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 | .onsubmit = saveNotifications;
}
function users_collapse(me) {
}
function users_expand(me) {
}
function sendEmail() {
var eemail = escape_plus($('email').value);
AjaxAsyncPostRequest(document.location, "email=" + eemail, sendEmailCB);
}
function sendEmailCB(response) {
// TODO: Before email is set, notification... | () {
// 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 | .onsubmit = saveNotifications;
}
function users_collapse(me) {
}
| 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 | Config.middleTo,
to: chartConfig.max,
color: chartConfig.orderDirection === 2 ?
Terrasoft.DashboardGaugeScaleColor.min : Terrasoft.DashboardGaugeScaleColor.max
}
];
},
/**
* @private
*/
applyGaugeChartConfig: function(config) {
var chartConfig = this.chartConfig;
var plotBands = this.getGa... | 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 | style: {
color: dataLabelColor
}
}
}
},
yAxis: {
min: chartConfig.min,
max: chartConfig.max,
tickPositions: [chartConfig.min, chartConfig.middleFrom, chartConfig.middleTo, chartConfig.max],
plotBands: plotBands
}
});
},
/**
* @private
*/
getSortableValueByI... | caption = Terrasoft.LS.MobileChartDashboardItemEmptyValueText;
}
| conditional_block | |
robots.py | (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 | robots denied', 1)
return 'no robots'
me = self.robotname
with stats.record_burn('robots is_allowed', url=schemenetloc):
if pathplus.startswith('//') and ':' in pathplus:
pathplus = 'htp://' + pathplus
check = robots.allowed(pathplus, me)
... | if self.robotslogfd: | random_line_split | |
robots.py | :
json_log['action_lines'] = action_lines
if text:
json_log['size'] = len(text)
def is_plausible_robots(body_bytes):
'''
Did you know that some sites have a robots.txt that's a 100 megabyte video file?
file magic mimetype is 'text' or similar -- too expensive, 3ms per call
'''
... |
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 | :
json_log['action_lines'] = action_lines
if text:
json_log['size'] = len(text)
def is_plausible_robots(body_bytes):
'''
Did you know that some sites have a robots.txt that's a 100 megabyte video file?
file magic mimetype is 'text' or similar -- too expensive, 3ms per call
'''
... |
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 | .ReadFile(fileName)
if err != nil {
return errors.Wrapf(err, "failed to read config file: %s", fileName)
}
configs = append(configs, string(b))
}
if configTOML := env.Config.Get(); configTOML != "" {
configs = append(configs, configTOML)
}
o.ConfigStrings = configs
secrets := []string{}
for _, fileN... | AutoPprofMutexProfileFraction | identifier_name | |
config_general.go | )
}
//go:embed legacy.env
var emptyStringsEnv string
// validateEnv returns an error if any legacy environment variables are set, unless a v2 equivalent exists with the same value.
func validateEnv() (err error) {
defer func() {
if err != nil {
_, err = utils.MultiErrorList(err)
err = fmt.Errorf("invalid env... | {
return &passwordConfig{keystore: g.keystorePassword, vrf: g.vrfPassword}
} | identifier_body | |
config_general.go | Strings []string
SecretsStrings []string
Config
Secrets
// OverrideFn is a *test-only* hook to override effective values.
OverrideFn func(*Config, *Secrets)
SkipEnv bool
}
func (o *GeneralConfigOpts) Setup(configFiles []string, secretsFiles []string) error {
configs := []string{}
for _, fileName := range c... |
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 | ConfigStrings []string
SecretsStrings []string
Config
Secrets
// OverrideFn is a *test-only* hook to override effective values.
OverrideFn func(*Config, *Secrets)
SkipEnv bool
}
func (o *GeneralConfigOpts) Setup(configFiles []string, secretsFiles []string) error {
configs := []string{}
for _, fileName := ... | }
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 | ::Deserialize::deserialize(deserializer)?;
Ok(Entity::from_bits(id))
}
}
impl fmt::Debug for Entity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}v{}", self.index, self.generation)
}
}
impl SparseSetIndex for Entity {
#[inline]
fn sparse_set_index(&self)... | alloc_at | identifier_name | |
mod.rs | 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;
AllocAtWithoutReplacement::DidNotExist
} ... | ///
/// This does not include entities that have been reserved but have never been
/// allocated yet.
/// | random_line_split | |
mod.rs | <'a> core::iter::ExactSizeIterator for ReserveEntitiesIterator<'a> {}
impl<'a> core::iter::FusedIterator for ReserveEntitiesIterator<'a> {}
/// A [`World`]'s internal metadata store on all of its entities.
///
/// Contains metadata on:
/// - The generation of every entity.
/// - The alive/dead status of a particular... | {
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 | = range_end - IdCursor::try_from(count).unwrap();
let freelist_range = range_start.max(0) as usize..range_end.max(0) as usize;
let (new_id_start, new_id_end) = if range_start >= 0 {
// We satisfied all requests from the freelist.
(0, 0)
} else {
// We need ... | {
// SAFETY: Caller guarantees that `index` a valid entity index
self.meta.get_unchecked_mut(index as usize).location = location;
} | identifier_body | |
windows.rs | sync::mpsc;
use futures::sync::oneshot;
use futures::{Async, Future, IntoFuture, Poll, Stream};
use tokio_reactor::{Handle, PollEvented};
use mio::Ready;
use self::winapi::shared::minwindef::*;
use self::winapi::um::wincon::*;
use IoFuture;
extern "system" {
fn SetConsoleCtrlHandler(HandlerRoutine: usize, Add: BO... | () -> 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 | sync::mpsc;
use futures::sync::oneshot;
use futures::{Async, Future, IntoFuture, Poll, Stream};
use tokio_reactor::{Handle, PollEvented};
use mio::Ready;
use self::winapi::shared::minwindef::*;
use self::winapi::um::wincon::*;
use IoFuture;
extern "system" {
fn SetConsoleCtrlHandler(HandlerRoutine: usize, Add: BO... | 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 | / (int(dataframe.shape[0]) * int(dataframe.shape[1])) * 100
print("le dataframe est rempli à ",format(pourcentage_values,".2f"),"%\n")
def print_samples(data_frame,number_of_rows):
display(data_frame.sample(number_of_rows,random_state = 148625))
def index_str_contains(index,dataframe,regex_var):
new_inde... | 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 | titre = titre + year
elif not index:
countries = dataframe['Country Code'].tolist()
z = dataframe[column].tolist()
layout = dict(geo={'scope': 'world'})
scl = [[0.0, 'darkblue'],[0.2, 'cornflowerblue'],[0.4, 'cornflowerblue'],\
[0.6, 'orange'],[0.8, 'orange'],[1.0, 're... | taframe2= dataframe2.rename(columns={year:new_column+"_"+year})
| conditional_block | |
annexe.py | ]) / (int(dataframe.shape[0]) * int(dataframe.shape[1])) * 100
print("le dataframe est rempli à ",format(pourcentage_values,".2f"),"%\n")
def print_samples(data_frame,number_of_rows):
display(data_frame.sample(number_of_rows,random_state = 148625))
def index_str_contains(index,dataframe,regex_var):
new_in... | 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 | _values):
new_dataframe = pd.DataFrame([])
for value in list_values:
new_dataframe = pd.concat([new_dataframe,dataframe.loc[dataframe['Indicator Name'] == value]])
return new_dataframe
def replace_ESC(dataframe, value_or_number=0):
if value_or_number == 0:
new_dataframe = dataframe.repl... | 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 | // light nodes have zero warmup time for pull/pushsync protocols
warmupTime := o.WarmupTime
if !o.FullNodeMode {
warmupTime = 0
}
b = &Bee{
p2pCancel: p2pCancel,
errorLogWriter: logger.WriterLevel(logrus.ErrorLevel),
tracerCloser: tracerCloser,
}
var debugAPIService *debugapi.Service
if o.Debug... | {
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 | b.ethClientCloser = swapBackend.Close
b.transactionCloser = tracerCloser
b.transactionMonitorCloser = transactionMonitor
}
if o.SwapEnable {
chequebookFactory, err = InitChequebookFactory(
logger,
swapBackend,
chainID,
transactionService,
o.SwapFactoryAddress,
o.SwapLegacyFactoryAddresses,
... | {
return nil, fmt.Errorf("invalid payment tolerance: %s", paymentTolerance)
} | conditional_block | |
node.go | "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 | Spec); err != nil {
return nil, fmt.Errorf("pullsync protocol: %w", err)
}
multiResolver := multiresolver.NewMultiResolver(
multiresolver.WithConnectionConfigs(o.ResolverConnectionCfgs),
multiresolver.WithLogger(o.Logger),
)
b.resolverCloser = multiResolver
var apiService api.Service
if o.APIAddr != "" {
... | Shutdown | identifier_name | |
graphics2.js | queleto);
pivotPoint.add(this[nombre].esqueleto);
splineHelperObjects.push(self.figuras[nombre].esqueleto)
return nombre;
};
//VARIEBLE PARA CONTROLES DE LA INTERFAZ
var speed=0.025;
var speed_around=0.025;
var menu = {
background: backgroundScene,
baldosas: tile_color,
Rubik: true,
r... | useMove( ev | identifier_name | |
graphics2.js | RandomInt(3*cube_width,4*cube_width));
let posIniZ = Math.pow(-1,getRandomInt(0,2))*(getRandomInt(3*cube_width,4*cube_width));
let normIni = Math.sqrt((Math.pow(posIniX,2)+(Math.pow(posIniZ,2))));
let angleIni = getRandomInt(1,361);
//altura
this[nombre].esqueleto.position.y = getRandomInt(2*cube_w... | selected_object.material.color.setHex(shape_params.color);
};
| identifier_body | |
graphics2.js | 7 ].color.setHex(0x4b3621);
}else if(i==2){
//pintar arriba
geometryC.faces[ 4 ].color.setHex(0xffffff);
geometryC.faces[ 5 ].color.setHex(0xffffff);
}
if(j==0){
//pintar atras
... | renderer.setSize( window.innerWidth, window.innerHeight*escala );
| random_line_split | |
graphics2.js | color
var black_material = new THREE.MeshPhongMaterial({ map: THREE.ImageUtils.loadTexture("resources/madera.jpg") }); //fixed color
var color_material = new THREE.MeshPhongMaterial({ color:tile_color, side: THREE.DoubleSide, flatShading: true }); //to change with gui
var black_color = -1;
//Ch... | if(k==0){
//pintar izq
geometryC.faces[ 2 ].color.setHex(0x00ff55);
geometryC.faces[ 3 ].color.setHex(0x00ff55);
}else if(k==2){
//pintar der
geometryC.faces[ 0 ].color.setHex(0xffff00);
... |
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 | intergenic': "complementBed -i {input[0]} -g <(cut -f 1-2 {input[1]} | sort -k1,1) | awk 'BEGIN{{OFS=\"\\t\"}}{{$(NF+1)=\"intergenic\";print}}' > {output}"
}
def strfdelta(tdelta, fmt):
d = {"days": tdelta.days}
d["hours"], rem = divmod(tdelta.seconds, 3600)
d["minutes"], d["seconds"] = divmod(rem, 60)
... | 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 | genic': "complementBed -i {input[0]} -g <(cut -f 1-2 {input[1]} | sort -k1,1) | awk 'BEGIN{{OFS=\"\\t\"}}{{$(NF+1)=\"intergenic\";print}}' > {output}"
}
def strfdelta(tdelta, fmt):
d = {"days": tdelta.days}
d["hours"], rem = divmod(tdelta.seconds, 3600)
d["minutes"], d["seconds"] = divmod(rem, 60)
retu... |
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 | intergenic': "complementBed -i {input[0]} -g <(cut -f 1-2 {input[1]} | sort -k1,1) | awk 'BEGIN{{OFS=\"\\t\"}}{{$(NF+1)=\"intergenic\";print}}' > {output}"
}
def strfdelta(tdelta, fmt):
d = {"days": tdelta.days}
d["hours"], rem = divmod(tdelta.seconds, 3600)
d["minutes"], d["seconds"] = divmod(rem, 60)
... | if 'gene' in line:
n_skipped['gene'] = n_skipped.get('gene', 0) + 1
continue
rchr, rstart, rend, rid, rflag, rstrand, rtstart, rtend, rrgb, rbcount, rbsizes, rbstarts, achr, astart, aend, ael, covg = line.strip().split("\t")
if uniq and int(rflag) != 1... | 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 | genic': "complementBed -i {input[0]} -g <(cut -f 1-2 {input[1]} | sort -k1,1) | awk 'BEGIN{{OFS=\"\\t\"}}{{$(NF+1)=\"intergenic\";print}}' > {output}"
}
def strfdelta(tdelta, fmt):
d = {"days": tdelta.days}
d["hours"], rem = divmod(tdelta.seconds, 3600)
d["minutes"], d["seconds"] = divmod(rem, 60)
retu... | (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 | ;
}
}
class SnakeTile extends Sprite {
constructor(x, y, width, height, trueX, trueY) {
super(x, y);
this.width = width;
this.height = height;
this.trueX = trueX;
this.trueY = trueY;
}
draw() {
ctx.fillStyle = "#888888";
ctx.fillRect(this.x, this.y, this.width, this.height);
c... |
}
}
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 | ;
}
}
class SnakeTile extends Sprite {
constructor(x, y, width, height, trueX, trueY) {
super(x, y);
this.width = width;
this.height = height;
this.trueX = trueX;
this.trueY = trueY;
}
draw() {
ctx.fillStyle = "#888888";
ctx.fillRect(this.x, this.y, this.width, this.height);
c... | () {
//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 | 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 | .is_null())]
//! #[pre(no_doc)]
//! #[pre(no_debug_assert)]
//! #[inline(always)]
//! #[allow(non_snake_case)]
//! pub(crate) fn NonNull__impl__new_unchecked__() {}
//!
//! #[pre(valid_ptr(src, r))]
//! #[inline(always)]
//! pub(crate) unsafe fn read<T>(sr... | arguments: PathArguments::None,
});
| random_line_split | |
extern_crate.rs | into
//!
//! ```rust,ignore
//! #[doc = "..."]
//! mod pre_std {
//! #[allow(unused_imports)]
//! use pre::pre;
//! #[allow(unused_imports)]
//! #[doc(no_inline)]
//! pub(crate) use std::*;
//!
//! #[doc = "..."]
//! pub(crate) mod ptr {
//! #[allow(unused_imports)]
//! use ... | stream
}
}
/// 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 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 | into
//!
//! ```rust,ignore
//! #[doc = "..."]
//! mod pre_std {
//! #[allow(unused_imports)]
//! use pre::pre;
//! #[allow(unused_imports)]
//! #[doc(no_inline)]
//! pub(crate) use std::*;
//!
//! #[doc = "..."]
//! pub(crate) mod ptr {
//! #[allow(unused_imports)]
//! use ... | (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 | into
//!
//! ```rust,ignore
//! #[doc = "..."]
//! mod pre_std {
//! #[allow(unused_imports)]
//! use pre::pre;
//! #[allow(unused_imports)]
//! #[doc(no_inline)]
//! pub(crate) use std::*;
//!
//! #[doc = "..."]
//! pub(crate) mod ptr {
//! #[allow(unused_imports)]
//! use ... | 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 | _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):
self.left = left
def set_label(self, label):
... | # 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 | def set_label(self, label):
self.label = label
def get_label(self):
return self.label
def print_nice_tree_indented(self, level=0):
if self is None:
print(str(level) + ' none')
return
print(str(level) + ' ' + str(self.bag) + ' ' + str(self.get_bag_type()) + ' ' + s... | return False | conditional_block | |
TreeDecomposition.py | _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):
self.left = left
def set_label(self, label):
... | (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 |
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 | Server {
private constructor() {}
private static _instance: WebServer
static get Instance(): WebServer {
return this._instance || (this._instance = new this())
}
/**
* The Express app.
*/
app: express.Express
/**
* The underlying HTTP(S) server.
*/
server: h... | 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 | {
private constructor() {}
private static _instance: WebServer
static get | (): 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 | {
private constructor() {}
private static _instance: WebServer
static get Instance(): WebServer {
return this._instance || (this._instance = new this())
}
/**
* The Express app.
*/
app: express.Express
/**
* The underlying HTTP(S) server.
*/
server: http.Se... |
try {
// Error inside another .error property?
if (error | {
status = 500
} | conditional_block |
app.js |
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 | = window.innerWidth,
// windowHeight = window.innerHeight,
// contextMenuWidth,
// contextMenuHeight,
// contextMenuLeftPos = 0,
// contextMenuTopPos = 0,
// $w = $($window),
// caretClass = {
// topRight: 'context-caret-top-right',
// topLeft: 'context-caret-top-left',
// bo... | {
str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
n += 2;
} | conditional_block | |
app.js | && Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date);
};
parseISOString = function parseISOString(s) {
var b;
b = s.replace(dateObjPrefix, '').replace('"', '').split(/\D+/);
return new Date(parseInt(b[0]));
}; //return (console.log("parse:" + new Date(b[0], b[1] -1, b[2], b[3]... | // * 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 | (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 | 'show';
const MATCH_CARD = 'match';
const NO_MATCH_CARD = 'no-match';
const FONT_AWESOME = 'fa';
const STARS = 'stars';
const EMPTY_STAR = 'fa-star-o';
const FULL_STAR = 'fa-star';
const CHECK_ICON = 'fa-check';
const CHECK_MARK = 'check-mark';
const GREEN_BTN = 'green-btn';
const TIMER = 'timer';
const MOVES_COUNTER ... |
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 | 'show';
const MATCH_CARD = 'match';
const NO_MATCH_CARD = 'no-match';
const FONT_AWESOME = 'fa';
const STARS = 'stars';
const EMPTY_STAR = 'fa-star-o';
const FULL_STAR = 'fa-star';
const CHECK_ICON = 'fa-check';
const CHECK_MARK = 'check-mark';
const GREEN_BTN = 'green-btn';
const TIMER = 'timer';
const MOVES_COUNTER ... | setTimeout(finishGame, FINISH_GAME_DELAY);
openedCardsCounter = 0;
}
} else {
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_MA... | {
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 | 'show';
const MATCH_CARD = 'match';
const NO_MATCH_CARD = 'no-match';
const FONT_AWESOME = 'fa';
const STARS = 'stars';
const EMPTY_STAR = 'fa-star-o';
const FULL_STAR = 'fa-star';
const CHECK_ICON = 'fa-check';
const CHECK_MARK = 'check-mark';
const GREEN_BTN = 'green-btn';
const TIMER = 'timer';
const MOVES_COUNTER ... | () {
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 | 'show';
const MATCH_CARD = 'match';
const NO_MATCH_CARD = 'no-match';
const FONT_AWESOME = 'fa';
const STARS = 'stars';
const EMPTY_STAR = 'fa-star-o';
const FULL_STAR = 'fa-star';
const CHECK_ICON = 'fa-check';
const CHECK_MARK = 'check-mark';
const GREEN_BTN = 'green-btn';
const TIMER = 'timer';
const MOVES_COUNTER ... |
}
// 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 | input;
mod item;
mod matcher;
mod model;
mod options;
mod orderedvec;
mod output;
pub mod prelude;
mod previewer;
mod query;
mod reader;
mod selection;
mod spinlock;
mod theme;
mod util;
//------------------------------------------------------------------------------
pub trait AsAny {
fn as_any(&self) -> &dyn Any... |
}
//------------------------------------------------------------------------------
// 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 | mod input;
mod item;
mod matcher;
mod model;
mod options;
mod orderedvec;
mod output;
pub mod prelude;
mod previewer;
mod query;
mod reader;
mod selection;
mod spinlock;
mod theme;
mod util;
//------------------------------------------------------------------------------
pub trait AsAny {
fn as_any(&self) -> &dyn ... | /// 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 | mod input;
mod item;
mod matcher;
mod model;
mod options;
mod orderedvec;
mod output;
pub mod prelude;
mod previewer;
mod query;
mod reader;
mod selection;
mod spinlock;
mod theme;
mod util;
//------------------------------------------------------------------------------
pub trait AsAny {
fn as_any(&self) -> &dyn ... | () -> 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 | keyword passed in via ROBOT_keyword')
return False
# run user picked Robot keyword
elog('debug', '====== Robot keyword {} with args: {}'.format(keyword, my_args))
res = RobotBuiltIn().run_keyword_and_return_status(keyword, *my_args)
return res
def _update_events(self, ... | # 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 | standard logging for easy debugging
. arg handling
. iteration/duration/timeout/exception handling
- Extensible to add new events in a consistent style
"""
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self):
# get the event/check methods/functions from a register file
... | return res
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
... | '''
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 | logging for easy debugging
. arg handling
. iteration/duration/timeout/exception handling
- Extensible to add new events in a consistent style
"""
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self):
# get the event/check methods/functions from a register file
#self.ev... |
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 | ().run_keyword_and_return_status(keyword, *my_args)
return res
def _update_events(self, events):
'''
updagate events to ee's attribute 'events_registered'
'''
registered_events = {}
for event in events:
registered_events[event] = {}
for action... | _confirm_event_state | identifier_name | |
dynamic_store.rs | ynamicStoreContext,
SCDynamicStoreCopyKeyList, SCDynamicStoreCopyValue, SCDynamicStoreCreateRunLoopSource,
SCDynamicStoreCreateWithOptions, SCDynamicStoreGetTypeID, SCDynamicStoreRef,
SCDynamicStoreRemoveValue, SCDynamicStoreSetNotificationKeys, SCDynamicStoreSetValue,
},
dynamic_store_c... |
}
}
/// 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 | ::CFString,
};
use std::{ffi::c_void, ptr};
/// Struct describing the callback happening when a watched value in the dynamic store is changed.
pub struct SCDynamicStoreCallBackContext<T> {
/// The callback function that will be called when a watched value in the dynamic store is
/// changed.
pub callout: S... | {
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 | ynamicStoreContext,
SCDynamicStoreCopyKeyList, SCDynamicStoreCopyValue, SCDynamicStoreCreateRunLoopSource,
SCDynamicStoreCreateWithOptions, SCDynamicStoreGetTypeID, SCDynamicStoreRef,
SCDynamicStoreRemoveValue, SCDynamicStoreSetNotificationKeys, SCDynamicStoreSetValue,
},
dynamic_store_c... | (
&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 | ynamicStoreContext,
SCDynamicStoreCopyKeyList, SCDynamicStoreCopyValue, SCDynamicStoreCreateRunLoopSource,
SCDynamicStoreCreateWithOptions, SCDynamicStoreGetTypeID, SCDynamicStoreRef,
SCDynamicStoreRemoveValue, SCDynamicStoreSetNotificationKeys, SCDynamicStoreSetValue,
},
dynamic_store_c... | 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 | let view = RefCell::new(Vec::with_capacity(len));
let s = FilteredList { data, filter, view };
let _ = s.refresh();
s
}
/// Refresh the view
///
/// Re-applies the filter (`O(n)` where `n` is the number of data elements).
/// Calling this directly may be useful in ca... |
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 | let view = RefCell::new(Vec::with_capacity(len));
let s = FilteredList { data, filter, view };
let _ = s.refresh();
s
}
/// Refresh the view
///
/// Re-applies the filter (`O(n)` where `n` is the number of data elements).
/// Calling this directly may be useful in ca... |
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 | let view = RefCell::new(Vec::with_capacity(len));
let s = FilteredList { data, filter, view };
let _ = s.refresh();
s
}
/// Refresh the view
///
/// Re-applies the filter (`O(n)` where `n` is the number of data elements).
/// Calling this directly may be useful in ca... | (&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 | let view = RefCell::new(Vec::with_capacity(len));
let s = FilteredList { data, filter, view };
let _ = s.refresh();
s
}
/// Refresh the view
///
/// Re-applies the filter (`O(n)` where `n` is the number of data elements).
/// Calling this directly may be useful in ca... | }
}
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 | ,
(FluentValue::Custom(s), FluentValue::Custom(s2)) => s == s2,
_ => false,
}
}
}
impl<'s> Clone for FluentValue<'s> {
fn clone(&self) -> Self {
match self {
FluentValue::String(s) => FluentValue::String(s.clone()),
FluentValue::Number(s) => Fluen... | from | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.