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
mod.rs
//------------------------------------------------------------------------------- // URL: //------------------------------------------------------------------------------- use std::path::Path; use time; use reader; pub const ID: i32 = 8; pub const DIR: &str = "array/dutchflag"; //--------------------------------...
} }
{ elements[mid] = elements[high]; elements[high] = element; high -= 1; }
conditional_block
write_all.rs
use std::path::Path; use clap::{App, SubCommand, Arg, ArgMatches}; use futures::prelude::*; use attaca::Repository; use attaca::trace::Trace; use errors::*; use trace::Progress; const HELP_STR: &'static str = r#" This test will first hashsplit and marshal a file; then, it will attempt to connect to a remote and se...
matches, Progress::new(Some("_debug".to_string())), ) } }
repository,
random_line_split
write_all.rs
use std::path::Path; use clap::{App, SubCommand, Arg, ArgMatches}; use futures::prelude::*; use attaca::Repository; use attaca::trace::Trace; use errors::*; use trace::Progress; const HELP_STR: &'static str = r#" This test will first hashsplit and marshal a file; then, it will attempt to connect to a remote and se...
pub fn go<P: AsRef<Path>>( repository: &mut Repository, conf_dir: P, matches: &ArgMatches, ) -> Result<()> { let conf = conf_dir.as_ref().join("ceph.conf"); let keyring = conf_dir.as_ref().join("ceph.client.admin.keyring"); // HACK: Ignore errors if adding the remote fails (it will fail if t...
{ let path = matches.value_of("INPUT").unwrap(); let context = repository.remote("_debug", trace)?; let chunk_stream = context.split_file(path); let hash_future = context.write_file(chunk_stream); let write_future = context.close(); write_future.join(hash_future).wait()?; Ok(()) }
identifier_body
write_all.rs
use std::path::Path; use clap::{App, SubCommand, Arg, ArgMatches}; use futures::prelude::*; use attaca::Repository; use attaca::trace::Trace; use errors::*; use trace::Progress; const HELP_STR: &'static str = r#" This test will first hashsplit and marshal a file; then, it will attempt to connect to a remote and se...
}
{ run( repository, matches, Progress::new(Some("_debug".to_string())), ) }
conditional_block
write_all.rs
use std::path::Path; use clap::{App, SubCommand, Arg, ArgMatches}; use futures::prelude::*; use attaca::Repository; use attaca::trace::Trace; use errors::*; use trace::Progress; const HELP_STR: &'static str = r#" This test will first hashsplit and marshal a file; then, it will attempt to connect to a remote and se...
<T: Trace>(repository: &mut Repository, matches: &ArgMatches, trace: T) -> Result<()> { let path = matches.value_of("INPUT").unwrap(); let context = repository.remote("_debug", trace)?; let chunk_stream = context.split_file(path); let hash_future = context.write_file(chunk_stream); let write_future...
run
identifier_name
wallaby.js
var wallabify = require('wallabify'); var wallabyPostprocessor = wallabify({ // browserify options, such as // insertGlobals: false } // you may also pass an initializer function to chain other // browserify options, such as transformers // , b => b.exclude('mkdirp').transform(require('babelify')) ); m...
tests: [ {pattern: 'test/specs/*.spec.js', load: false}, {pattern: 'test/specs/deepCopy.js', load: false} ], postprocessor: wallabyPostprocessor, bootstrap: function () { // required to trigger tests loading window.__moduleBundler.loadTests(); } }; };
{pattern: 'index.js', load: false}, {pattern: 'isVoid.js', load: false}, {pattern: 'safe*.js', load: false} ],
random_line_split
LoadState.js
/** * Loads all assets used by the game */
this.state.start('play'); }; this.preload = function() { this.load.spritesheet('runner', 'assets/runner.png?5', 64, 56); // Public domain, http://opengameart.org/content/classic-hero-and-baddies-pack this.load.spritesheet('healer', 'assets/healer.png?6', 80, 80); // Public doming, http://opengameart.org/conten...
var LoadState = function() { this.create = function() {
random_line_split
tables.state.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. *
* This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License *...
* This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. *
random_line_split
ui.google.translation.js
var NFLCIME; var module; // get the NFLCIME object try { var p = window; do { p = p.parent; if(p.NFLCIME) { NFLCIME = p.NFLCIME; break; } } while(p != p.parent); } catch(e) { } function loadStyleSheets() { var interface_css = 'ui.iframe.css'; var module_css = 'ui.google.translation.css'...
evt.returnValue = result; } ); break; case 'firefox': case 'safari': element.addEventListener(eventName, handler, function(evt) { var result = handler.call(self, evt); if(result != undefined && result == false) { evt.preventDefault(); } } ); break;...
random_line_split
ui.google.translation.js
var NFLCIME; var module; // get the NFLCIME object try { var p = window; do { p = p.parent; if(p.NFLCIME) { NFLCIME = p.NFLCIME; break; } } while(p != p.parent); } catch(e) { } function loadStyleSheets() { var interface_css = 'ui.iframe.css'; var module_css = 'ui.google.translation.css'...
(isoCode) { var source = element('source-language'); var textbox = element('input-text'); source.value = isoCode; if(source.value == isoCode) { sourceLanguage = isoCode; // set the lang attribute so built-in spell-checker work correctly textbox.setAttribute('lang', isoCode); if(isoCode) { // act...
setSourceLanguage
identifier_name
ui.google.translation.js
var NFLCIME; var module; // get the NFLCIME object try { var p = window; do { p = p.parent; if(p.NFLCIME) { NFLCIME = p.NFLCIME; break; } } while(p != p.parent); } catch(e) { } function loadStyleSheets() { var interface_css = 'ui.iframe.css'; var module_css = 'ui.google.translation.css'...
else { textbox.setAttribute('NFLCIME', 'off'); } } else { return false; } return true; } function setDestinationLanguage(isoCode) { var dest = element('destination-language'); var translation = element('translation'); dest.value = isoCode; if(dest.value == isoCode) { destinationLanguage = ...
{ // activate IME functionalities textbox.setAttribute('NFLCIME', 'on'); NFLCIME.dispatchEvent( { type:'LanguageRescan' } ); }
conditional_block
ui.google.translation.js
var NFLCIME; var module; // get the NFLCIME object try { var p = window; do { p = p.parent; if(p.NFLCIME) { NFLCIME = p.NFLCIME; break; } } while(p != p.parent); } catch(e) { } function loadStyleSheets() { var interface_css = 'ui.iframe.css'; var module_css = 'ui.google.translation.css'...
attachDOMHandler(element('frame-drag-bar'), 'dblclick', function(evt) { if(evt.target.className != 'corner-button') module.toggleCollapse() }); // load google translate module if(window.google) { google.load('language', '2', { language:'en', callback:onGoogleAPILoad } ); } // attach handlers to page element...
{ // get the minimum width and height from the body tag var minWidth = document.body.getAttribute('minWidth'); var minHeight = document.body.getAttribute('minHeight'); var options = {}; if(minWidth) options.minWidth = parseInt(minWidth); if(minHeight) options.minHeight = parseInt(minHeight); module.applyL...
identifier_body
metatype.py
self.field = field self.value = value self.width = width self.name = name self.language = language self.collection = container self.container = container self.ip = ip self.user = user self.lock = lock class Metatype(object): joiner...
warn("collections argument is deprecated, use container", DeprecationWarning) if container is not None: raise ValueError("container and collection cannot be used together") container = collection
conditional_block
metatype.py
quot;', '34', 'quotation mark'], # finance ['&cent;', '162', 'cent sign'], ['&euro;', '8364', 'euro sign'], ['&pound;', '163', 'pound sign'], ['&yen;', '165', 'yen sign'], # signs ['&copy;', '169', 'copyright sign'], ['&reg;', '174', 'registered sign'], ['&trade;', '8482', 'trade mar...
['&tilde;', '732', 'small tilde'], ['&deg;', '176', 'degree sign'], ['&minus;', '8722', 'minus sign'], ['&plusmn;', '177', 'plus-minus sign'], ['&divide;', '247', 'division sign'], ['&frasl;', '8260', 'fraction slash'], ['&times;', '215', 'multiplication sign'], ['&sup1;', '185', 'supers...
random_line_split
metatype.py
def getMaskEditorHTML(self, field, metadatatype=None, language=None): return "" @classmethod def isContainer(cls): return False def isFieldType(self): return True def getName(self): return "" def getInformation(self): return {"moduleversion": "1.0"} ...
"""Prepare value for the database from update request params. :param field: associated field :param params: dict which contains POST form values :param item: field name prepended with language specifier. Is the same as field name for non-multilingual fields. """ # just fetch th...
identifier_body
metatype.py
(self, field, value="", width=400, name="", lock=0, language=None, collection=None, container=None, user=None, ip=""): if collection is not None: warn("collections argument is deprecated, use container", DeprecationWarning) if container is not None: raise ValueError("cont...
__init__
identifier_name
imageindifferentdir.py
# Copyright (c) 2012 The Khronos Group Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publis...
# Please feed your node list here: tagLst = '' attrName = '' attrVal = '' dataToCheck = '' class SimpleJudgingObject: def __init__(self, _tagLst, _attrName, _attrVal, _data): self.tagList = _tagLst self.attrName = _attrName self.attrVal = _attrVal self.dataToCheck = _data...
random_line_split
imageindifferentdir.py
# Copyright (c) 2012 The Khronos Group Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publ...
# Compare the rendered images between import and export, and if passed, # compare images against reference test if ( self.__assistant.CompareRenderedImages(context) ): self.__assistant.CompareImagesAgainst(context, "image_2_texture_same_effect") ...
self.status_baseline = False return False
conditional_block
imageindifferentdir.py
# Copyright (c) 2012 The Khronos Group Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publ...
(self, _tagLst, _attrName, _attrVal, _data): self.tagList = _tagLst self.attrName = _attrName self.attrVal = _attrVal self.dataToCheck = _data self.status_baseline = False self.status_superior = False self.status_exemplary = False self.__assistant ...
__init__
identifier_name
imageindifferentdir.py
# Copyright (c) 2012 The Khronos Group Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publ...
# To pass intermediate you need to pass basic, this object could also include additional # tests that were specific to the intermediate badge. def JudgeSuperior(self, context): self.status_superior = self.status_baseline return self.status_superior # To pass ad...
self.__assistant.CheckCrashes(context) # Import/export/validate must exist and pass, while Render must only exist. self.__assistant.CheckSteps(context, ["Import", "Export", "Validate"], ["Render"]) if (self.__assistant.GetResults() == False): self.status_baseline = F...
identifier_body
auth.guard.ts
/* Wajibu is an online web app that collects,analyses, aggregates and visualizes sentiments from the public pertaining the government of a nation. This tool allows citizens to contribute to the governance talk by airing out their honest views about the state of the nation and in particular the people placed in governme...
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean>{ return Observable.of(this.session.getSession()) .take(1) .map(d => d.isSet) .do(isSet => { ...
{}
identifier_body
auth.guard.ts
/* Wajibu is an online web app that collects,analyses, aggregates and visualizes sentiments from the public pertaining the government of a nation. This tool allows citizens to contribute to the governance talk by airing out their honest views about the state of the nation and in particular the people placed in governme...
.take(1) .map(d => d.isDeployed) .do(isDeployed => { if (!isDeployed) this.router.navigate(["dash"]) }) } }
random_line_split
auth.guard.ts
/* Wajibu is an online web app that collects,analyses, aggregates and visualizes sentiments from the public pertaining the government of a nation. This tool allows citizens to contribute to the governance talk by airing out their honest views about the state of the nation and in particular the people placed in governme...
(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> { return Observable.of(this.session.getDeploy()) .take(1) .map(d => d.isDeployed) ...
canActivateChild
identifier_name
generation.py
# Copyright 2012 Energid Technologies from energid_nlp import logic GENERATION_PROPOSITION = '$generate'
class Error(Exception): pass class Generator: def __init__(self, kb): self.kb = kb def generate_prim(self, concept): if isinstance(concept, logic.Description): return self.generate_prim(concept.base) elif isinstance(concept, logic.Expr): return self.generate_prim(concept.op) else: ...
random_line_split
generation.py
# Copyright 2012 Energid Technologies from energid_nlp import logic GENERATION_PROPOSITION = '$generate' class Error(Exception):
class Generator: def __init__(self, kb): self.kb = kb def generate_prim(self, concept): if isinstance(concept, logic.Description): return self.generate_prim(concept.base) elif isinstance(concept, logic.Expr): return self.generate_prim(concept.op) else: result = '%s' % (concept,...
pass
identifier_body
generation.py
# Copyright 2012 Energid Technologies from energid_nlp import logic GENERATION_PROPOSITION = '$generate' class Error(Exception): pass class Generator: def __init__(self, kb): self.kb = kb def generate_prim(self, concept): if isinstance(concept, logic.Description): return self.generate_prim(c...
else: return self.generate_prim(concept) def generate_template(self, concept, template): result_string = '' start = 0 while start < len(template): slot_start = template.find('{', start) if slot_start == -1: # No more slot refs result_string = result_string + templat...
return self.generate_template(concept, template.op)
conditional_block
generation.py
# Copyright 2012 Energid Technologies from energid_nlp import logic GENERATION_PROPOSITION = '$generate' class
(Exception): pass class Generator: def __init__(self, kb): self.kb = kb def generate_prim(self, concept): if isinstance(concept, logic.Description): return self.generate_prim(concept.base) elif isinstance(concept, logic.Expr): return self.generate_prim(concept.op) else: result...
Error
identifier_name
08_switchMACTable.js
"use strict"; var checkAuth = require("./lib/checkAuth"); var pug = require("pug"); var async = require("async"); var models = require("./models"); module.exports = function(app){ //////////////////////////////////////////////////////////////////////////////// app.get("/listSwitchesMACTable", checkAuth, function(...
case "sortByLocation": sortBy = (req.body.order == "asc")?"location.building location.floor location.room":"-location.building location.floor location.room"; break; default: sortBy = "location.building location.floor location.room"; break; } models.switches .find(...
case "sortBySNMPName": sortBy = (req.body.order == "asc")?"snmpInfo.snmpName":"-snmpInfo.snmpName"; break;
random_line_split
08_switchMACTable.js
"use strict"; var checkAuth = require("./lib/checkAuth"); var pug = require("pug"); var async = require("async"); var models = require("./models"); module.exports = function(app){ //////////////////////////////////////////////////////////////////////////////// app.get("/listSwitchesMACTable", checkAuth, function(...
else { if (req.session && req.session.username) sAMAccountName = req.session.username; }; res.render("listSwitchesMACTable", { "title": "Список коммутаторов", "session": sAMAccountName, "authType": req.session.authType }); }); ///////////////////////////////////////////////...
{ sAMAccountName = req.user.displayName; }
conditional_block
nonlinear_elliptic_problem.py
# Copyright (C) 2015-2022 by the RBniCS authors # # This file is part of RBniCS. # # SPDX-License-Identifier: LGPL-3.0-or-later from rbnics.problems.base import NonlinearProblem from rbnics.problems.elliptic import EllipticProblem from rbnics.backends import product, sum, transpose NonlinearEllipticProblem_Base = Non...
# Perform a truth evaluation of the output def _compute_output(self): self._output = transpose(self._solution) * sum(product(self.compute_theta("s"), self.operator["s"]))
problem = self.problem assembled_operator = dict() assembled_operator["a"] = sum(product(problem.compute_theta("a"), problem.operator["a"])) assembled_operator["dc"] = sum(product(problem.compute_theta("dc"), problem.operator["dc"])) return assembled_operator["a"] + assem...
identifier_body
nonlinear_elliptic_problem.py
# Copyright (C) 2015-2022 by the RBniCS authors # # This file is part of RBniCS. # # SPDX-License-Identifier: LGPL-3.0-or-later from rbnics.problems.base import NonlinearProblem from rbnics.problems.elliptic import EllipticProblem from rbnics.backends import product, sum, transpose NonlinearEllipticProblem_Base = Non...
self._output = transpose(self._solution) * sum(product(self.compute_theta("s"), self.operator["s"]))
random_line_split
nonlinear_elliptic_problem.py
# Copyright (C) 2015-2022 by the RBniCS authors # # This file is part of RBniCS. # # SPDX-License-Identifier: LGPL-3.0-or-later from rbnics.problems.base import NonlinearProblem from rbnics.problems.elliptic import EllipticProblem from rbnics.backends import product, sum, transpose NonlinearEllipticProblem_Base = Non...
(self, solution): problem = self.problem assembled_operator = dict() assembled_operator["a"] = sum(product(problem.compute_theta("a"), problem.operator["a"])) assembled_operator["dc"] = sum(product(problem.compute_theta("dc"), problem.operator["dc"])) return a...
jacobian_eval
identifier_name
match_args.rs
use std::os; fn increase(number: i32) { println!("{}", number + 1); } fn
(number: i32) { println!("{}", number - 1); } fn help() { println!("usage: match_args <string> Check whether given string is the answer. match_args {{increase|decrease}} <integer> Increase or decrease given integer by one."); } fn main() { let args = os::args(); match args.as_slice() { ...
decrease
identifier_name
match_args.rs
use std::os; fn increase(number: i32) { println!("{}", number + 1); } fn decrease(number: i32) { println!("{}", number - 1); } fn help() { println!("usage: match_args <string> Check whether given string is the answer. match_args {{increase|decrease}} <integer> Increase or decrease given integer b...
}; // parse the command match cmd.as_slice() { "increase" => increase(number), "decrease" => decrease(number), _ => { println!("error: invalid command"); help(); }, } ...
return; },
random_line_split
match_args.rs
use std::os; fn increase(number: i32) { println!("{}", number + 1); } fn decrease(number: i32) { println!("{}", number - 1); } fn help()
fn main() { let args = os::args(); match args.as_slice() { // no arguments passed [ref name] => { println!("My name is '{}'. Try passing some arguments!", name); }, // one argument passed [_, ref string] => { if string.as_slice() == "42" { ...
{ println!("usage: match_args <string> Check whether given string is the answer. match_args {{increase|decrease}} <integer> Increase or decrease given integer by one."); }
identifier_body
sectorComponentSpec.js
'use strict'; describe('sector-component', function () { var controller, scope, backEndServer;
toEqualData: function (expected) { return angular.equals(this.actual, expected); } }); }); beforeEach(module('testSPA.sectorComponent')); beforeEach(inject(function ($rootScope, $controller) { backEndServer = { data: {}, done: fals...
beforeEach(function () { this.addMatchers({
random_line_split
_sets-set.js
'use strict'; var setPrototypeOf = require('es5-ext/object/set-prototype-of') , mixin = require('es5-ext/object/mixin-prototypes') , iterator = require('es6-iterator/valid-iterable') , forOf = require('es6-iterator/for-of') , toArray = require('es5-ext/array/t...
delete: d(function (set) { if (!this.has(set)) return false; del.call(this, set); this.__master__._onSetDelete(set); return true; }) });
this.__master__._onSetsClear(sets); }),
random_line_split
views.py
import locale from atom.ext.guardian.views import RaisePermissionRequiredMixin from braces.views import ( FormValidMessageMixin, LoginRequiredMixin, SelectRelatedMixin, UserFormKwargsMixin, ) from cached_property import cached_property from dateutil.relativedelta import relativedelta from django.conf i...
class EventUpdateView( RaisePermissionRequiredMixin, UserFormKwargsMixin, FormValidMessageMixin, UpdateView ): model = Event form_class = EventForm template_name = "events/form.html" permission_required = ["cases.can_add_record"] def get_permission_object(self): return self._object.c...
return _("Success added new event %(event)s") % ({"event": self.object})
identifier_body
views.py
import locale from atom.ext.guardian.views import RaisePermissionRequiredMixin from braces.views import ( FormValidMessageMixin, LoginRequiredMixin, SelectRelatedMixin, UserFormKwargsMixin, ) from cached_property import cached_property from dateutil.relativedelta import relativedelta from django.conf i...
return cal def get_start(self): return now() + relativedelta(months=+self.window) def get_end(self): return now() + relativedelta(months=-self.window) def get_queryset(self): qs = super().get_queryset() qs = qs.filter(time__lt=self.get_start()) qs = qs.fil...
cal.add_component(component)
conditional_block
views.py
import locale from atom.ext.guardian.views import RaisePermissionRequiredMixin from braces.views import ( FormValidMessageMixin, LoginRequiredMixin, SelectRelatedMixin, UserFormKwargsMixin, ) from cached_property import cached_property from dateutil.relativedelta import relativedelta from django.conf i...
(self): return [self.get_event(x) for x in self.get_queryset()] def get_icalendar(self): from icalendar import Calendar cal = Calendar() cal["summary"] = "Events for {}".format(self.request.user) cal["dtstart"] = self.get_start() cal["dtend"] = self.get_end() ...
get_subcomponents
identifier_name
views.py
import locale from atom.ext.guardian.views import RaisePermissionRequiredMixin from braces.views import ( FormValidMessageMixin, LoginRequiredMixin, SelectRelatedMixin, UserFormKwargsMixin, ) from cached_property import cached_property from dateutil.relativedelta import relativedelta from django.conf i...
def render_to_response(self, *args, **kwargs): response = HttpResponse(content_type="application/force-download") response["Content-Disposition"] = "attachment; filename=calendar.ics" response.write(self.get_icalendar().to_ical()) return response
random_line_split
AuraContext.js
. that.currentAction = new Action(null, ""+that.num, null, null, false, null, false); if(config["libraryDefs"]) { defs = config["libraryDefs"]; for (i = 0; i < defs.length; i++)
} if (config["componentDefs"]) { defs = config["componentDefs"]; for (i = 0; i < defs.length; i++) { if (defs[i]["descriptor"]) { $A.componentService.saveComponentConfig(defs[i]); } ...
{ $A.componentService.saveLibraryConfig(defs[i]); }
conditional_block
AuraContext.js
paths. that.currentAction = new Action(null, ""+that.num, null, null, false, null, false); if(config["libraryDefs"]) { defs = config["libraryDefs"]; for (i = 0; i < defs.length; i++) { $A.componentService.saveLibraryConfig(defs[i]); ...
* * @return {GlobalValueProviders} * @private */ Aura.Context.AuraContext.prototype.getGlobalValueProvider = function(type) { return this.globalValueProviders.getValueProvider(type); }; /** * JSON representation of context for server requests. * * This must remain in sync with AuraTestingUtil so that we can...
/** * Provides access to global value providers. * For example, <code>$A.get("$Label.Related_Lists.task_mode_today");</code> gets the label value.
random_line_split
viewer.js
var g_pagerAssessments = null; /** * Modal VIewer **/ var g_assessmentModalWidget = null; function AssessmentModalWidget() { this.composeContent = function(data) { if(data == null || Object.keys(data).length == 0) { alert(ALERTS["no_assessment"]); return; } var assessments = []; for(var key in data)...
{ var page = 1; listAssessments(page, onListAssessmentsSuccess, onListAssessmentsError); }
identifier_body
viewer.js
var g_pagerAssessments = null; /** * Modal VIewer **/ var g_assessmentModalWidget = null; function AssessmentModalWidget() { this.composeContent = function(data) { if(data == null || Object.keys(data).length == 0) { alert(ALERTS["no_assessment"]); return; } var assessments = []; for(var key in data)...
}; } AssessmentModalWidget.inherits(BaseModalWidget); function initAssessmentModalWidget(par){ g_assessmentModalWidget = new AssessmentModalWidget(); g_assessmentModalWidget.appendTo(par, false); } function onQueryAssessmentsSuccess(data) { g_assessmentModalWidget.refresh(data); g_assessmentModalWidget.show(...
{ var assessment = assessments[i]; var row = $("<tr class='assessments-viewer-row'>").appendTo(tbl); $('<td>', { text: assessment.content }).appendTo(row); var fromCell = $("<td>").appendTo(row); var iconSlot = $("<img>", { src: assessment.fromPlayer.avatar, "class": "assessments-viewer-av...
conditional_block
viewer.js
var g_pagerAssessments = null; /** * Modal VIewer **/ var g_assessmentModalWidget = null; function AssessmentModalWidget() { this.composeContent = function(data) { if(data == null || Object.keys(data).length == 0) { alert(ALERTS["no_assessment"]); return; } var assessments = []; for(var key in data)...
(err) { } function generateAssessmentsListParams(pager, page) { if (page == null) return null; var token = getToken(); if (token == null) { focusLogin(); return; } var params = {}; params[g_keyToken] = token; var pageSt = page - 2; var pageEd = page + 2; var offset = pageSt < 1 ? (pageSt - 1) : 0; pa...
onListAssessmentsError
identifier_name
viewer.js
var g_pagerAssessments = null; /** * Modal VIewer **/ var g_assessmentModalWidget = null; function AssessmentModalWidget() { this.composeContent = function(data) { if(data == null || Object.keys(data).length == 0) { alert(ALERTS["no_assessment"]); return; } var assessments = []; for(var key in data)...
if (pager.filters != null) { for (var i = 0; i < pager.filters.length; ++i) { var filter = pager.filters[i]; params[filter.key] = filter.selector.val(); } } if (pager.extraParams == null) return params; for (var key in pager.extraParams) { params[key] = pager.extraParams[key]; } return params; } ...
if (pager.nItems != null) params[g_keyNumItems] = pager.nItems; if (g_activityId != null) params[g_keyActivityId] = g_activityId;
random_line_split
util.py
# Copyright 2016-2018 Michael Peters # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
return profiled_func # annotate a function with @print_models def print_models(func): def printed_func(*args, **kwargs): model = func(*args, **kwargs) cv_keys = ('mean_test_score', 'std_test_score', 'params') for r, _ in enumerate(model.cv_results_['mean_test_score']): prin...
p = cProfile.Profile() try: p.enable() result = func(*args, **kwargs) p.disable() return result finally: p.print_stats()
identifier_body
util.py
# Copyright 2016-2018 Michael Peters # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
print('Best parameters: %s' % model.best_params_) print('Best accuracy: %.2f' % model.best_score_) return model return printed_func # https://www.pro-football-reference.com/about/win_prob.htm def mov_to_win_percent(u, m=11, offset=0): u = u + offset return 1 - norm.cdf(0.5, loc=u, ...
print("%0.3f +/- %0.2f %r" % (model.cv_results_[cv_keys[0]][r], model.cv_results_[cv_keys[1]][r] / 2.0, model.cv_results_[cv_keys[2]][r]))
conditional_block
util.py
# Copyright 2016-2018 Michael Peters # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
(*args, **kwargs): model = func(*args, **kwargs) cv_keys = ('mean_test_score', 'std_test_score', 'params') for r, _ in enumerate(model.cv_results_['mean_test_score']): print("%0.3f +/- %0.2f %r" % (model.cv_results_[cv_keys[0]][r], model.cv_r...
printed_func
identifier_name
util.py
# Copyright 2016-2018 Michael Peters # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# limitations under the License. import cProfile from scipy.stats import norm # annotate a function with @profile to see where it's spending the most time def profile(func): def profiled_func(*args, **kwargs): p = cProfile.Profile() try: p.enable() result = func(*args,...
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and
random_line_split
PawnBuildPath.py
import json import sublime import sublime_plugin from .edit import Edit class PawnBuildPathCommand(sublime_plugin.TextCommand): def run(self, edit): self.view.window().show_input_panel( "Working directory that contains pawncc.exe", "C:\\Pawno\\", self.onPawnPathDone, ...
"$file", "-o$file_path/$file_base_name", "-;+", "-(+", "-d3" ], "file_regex": r"(.*?)\(([0-9]*)[- 0-9]*\)", "selector": "source.pwn", "working_dir": path } with Edit(view) as ...
"pawncc.exe",
random_line_split
PawnBuildPath.py
import json import sublime import sublime_plugin from .edit import Edit class
(sublime_plugin.TextCommand): def run(self, edit): self.view.window().show_input_panel( "Working directory that contains pawncc.exe", "C:\\Pawno\\", self.onPawnPathDone, None, None ) def onPawnPathDone(self, path): view = self....
PawnBuildPathCommand
identifier_name
PawnBuildPath.py
import json import sublime import sublime_plugin from .edit import Edit class PawnBuildPathCommand(sublime_plugin.TextCommand): def run(self, edit): self.view.window().show_input_panel( "Working directory that contains pawncc.exe", "C:\\Pawno\\", self.onPawnPathDone, ...
view.set_name("Pawn.sublime-build") view.run_command("save")
view = self.view.window().new_file() path = path.replace("\\", "/") obj = { "cmd": [ "pawncc.exe", "$file", "-o$file_path/$file_base_name", "-;+", "-(+", "-d3" ], "file_re...
identifier_body
PageFormController.js
PageModule.controller('PageFormController', function PageFormController($scope, $http, $q) { /** * * @type {String} */ var rootUrl = ''; /** * * @returns {void} */ $scope.generateSlug = function() { var pageHeader = $('#Page_header').val(); $http({ ...
* @param {String} url * @returns {void} */ $scope.init = function(url) { rootUrl = url; }; });
}; /** *
random_line_split
worklet.rs
{:?}.", module_url.0, err); promise.reject_error(Error::Syntax); return promise; } }; debug!("Adding Worklet module {}.", module_url_record);
// Steps 6-12 in parallel. let pending_tasks_struct = PendingTasksStruct::new(); let global = self.window.upcast::<GlobalScope>(); let pool = ScriptThread::worklet_thread_pool(); pool.fetch_and_invoke_a_worklet_script(global.pipeline_id(), ...
random_line_split
worklet.rs
letData>, // Channels to send control messages to the three threads. control_sender_0: Sender<WorkletControl>, control_sender_1: Sender<WorkletControl>, control_sender_2: Sender<WorkletControl>, } impl Drop for WorkletThreadPool { fn drop(&mut self) { let _ = self.cold_backup_sender.send(Wo...
{ let (our_swapper, their_swapper) = swapper(); sender.send(WorkletData::FinishSwapRoles(their_swapper)).unwrap(); let _ = our_swapper.swap(&mut self.role); }
conditional_block
worklet.rs
(&self) -> WorkletId { self.worklet_id } #[allow(dead_code)] pub fn worklet_global_scope_type(&self) -> WorkletGlobalScopeType { self.global_type } } impl WorkletMethods for Worklet { #[allow(unrooted_must_root)] /// https://drafts.css-houdini.org/worklets/#dom-worklet-addmodul...
worklet_id
identifier_name
worklet.rs
?}.", module_url.0, err); promise.reject_error(Error::Syntax); return promise; } }; debug!("Adding Worklet module {}.", module_url_record); // Steps 6-12 in parallel. let pending_tasks_struct = PendingTasksStruct::new(); let global = s...
} /// https://drafts.css-houdini.org/worklets/#pending-tasks-struct #[derive(Clone, Debug)] struct PendingTasksStruct(Arc<AtomicIsize>); impl PendingTasksStruct { fn new() -> PendingTasksStruct { PendingTasksStruct(Arc::new(AtomicIsize::new(WORKLET_THREAD_POOL_SIZE as isize))) } fn set_counter_t...
{ WorkletId(servo_rand::random()) }
identifier_body
led.rs
//! Easy use of LEDs. use peripheral; /// All the LEDs. pub static LEDS: [Led; 4] = [Led { i: 12 }, Led { i: 13 }, Led { i: 14 }, Led { i: 15 }];
/// A single LED. pub struct Led { i: u8, } impl Led { /// Turns the LED on. pub fn on(&self) { let bsrr = &peripheral::gpiod().bsrr; match self.i { 12 => bsrr.write(|w| w.bs12(true)), 13 => bsrr.write(|w| w.bs13(true)), 14 => bsrr.write(|w| w.bs14(true))...
random_line_split
led.rs
//! Easy use of LEDs. use peripheral; /// All the LEDs. pub static LEDS: [Led; 4] = [Led { i: 12 }, Led { i: 13 }, Led { i: 14 }, Led { i: 15 }]; /// A single LED. pub struct Led { i: u8, } impl Led { /// Turns the LED on...
/// Turns the LED off. pub fn off(&self) { let bsrr = &peripheral::gpiod().bsrr; match self.i { 12 => bsrr.write(|w| w.br12(true)), 13 => bsrr.write(|w| w.br13(true)), 14 => bsrr.write(|w| w.br14(true)), 15 => bsrr.write(|w| w.br15(true)), ...
{ let bsrr = &peripheral::gpiod().bsrr; match self.i { 12 => bsrr.write(|w| w.bs12(true)), 13 => bsrr.write(|w| w.bs13(true)), 14 => bsrr.write(|w| w.bs14(true)), 15 => bsrr.write(|w| w.bs15(true)), _ => {} } }
identifier_body
led.rs
//! Easy use of LEDs. use peripheral; /// All the LEDs. pub static LEDS: [Led; 4] = [Led { i: 12 }, Led { i: 13 }, Led { i: 14 }, Led { i: 15 }]; /// A single LED. pub struct Led { i: u8, } impl Led { /// Turns the LED on...
() { let gpiod = peripheral::gpiod_mut(); let rcc = peripheral::rcc_mut(); // RCC: Enable GPIOD rcc.ahb1enr.modify(|_, w| w.gpioden(true)); // GPIOD: Configure pins 12-15 as outputs gpiod.moder.modify(|_, w| { w.moder12(0b01) .moder13(0b01) .moder14(0b01) ...
init
identifier_name
list.module.ts
// (C) Copyright 2015 Martin Dougiamas // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agre...
import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { TranslateModule } from '@ngx-translate/core'; import { CoreDirectivesModule } from '@directives/directives.module'; import { AddonNotesListPage } from './list'; import { AddonNotesComponentsModule } from '../../component...
// See the License for the specific language governing permissions and // limitations under the License.
random_line_split
list.module.ts
// (C) Copyright 2015 Martin Dougiamas // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agre...
{}
AddonNotesListPageModule
identifier_name
_hastagbase.py
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2010 Nick Hall # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any...
(self, db, obj): """ Apply the rule. Return True for a match. """ if self.tag_handle is None: return False return self.tag_handle in obj.get_tag_list()
apply
identifier_name
_hastagbase.py
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2010 Nick Hall # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any...
Apply the rule. Return True for a match. """ if self.tag_handle is None: return False return self.tag_handle in obj.get_tag_list()
""" Rule that checks for an object with a particular tag. """ labels = [ 'Tag:' ] name = 'Objects with the <tag>' description = "Matches objects with the given tag" category = _('General filters') def prepare(self, db): """ Prepare the rule. Things we want to...
identifier_body
_hastagbase.py
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2010 Nick Hall # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any...
""" Rule that checks for an object with a particular tag. """ labels = [ 'Tag:' ] name = 'Objects with the <tag>' description = "Matches objects with the given tag" category = _('General filters') def prepare(self, db): """ Prepare the rule. Things we wan...
class HasTagBase(Rule):
random_line_split
_hastagbase.py
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2010 Nick Hall # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any...
def apply(self, db, obj): """ Apply the rule. Return True for a match. """ if self.tag_handle is None: return False return self.tag_handle in obj.get_tag_list()
self.tag_handle = tag.get_handle()
conditional_block
worklet.rs
PendingTasksStruct::new(); let global = self.window.upcast::<GlobalScope>(); let pool = ScriptThread::worklet_thread_pool(); pool.fetch_and_invoke_a_worklet_script( global.pipeline_id(), self.worklet_id, self.global_type, self.window.origin().imm...
(Uuid); malloc_size_of_is_0!(WorkletId); impl WorkletId { fn new() -> WorkletId { WorkletId(servo_rand::random_uuid()) } } /// <https://drafts.css-houdini.org/worklets/#pending-tasks-struct> #[derive(Clone, Debug)] struct PendingTasksStruct(Arc<AtomicIsize>); impl PendingTasksStruct { fn new() -...
WorkletId
identifier_name
worklet.rs
WorkletControl> { let (control_sender, control_receiver) = channel(); // TODO: name this thread thread::spawn(move || { // TODO: add a new IN_WORKLET thread state? // TODO: set interrupt handler? // TODO: configure the JS runtime (e.g. discourage GC, encourage...
random_line_split
yue.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js function
(n: number): number { return 5; } export default [ 'yue', [ ['上午', '下午'], , ], , [ ['日', '一', '二', '三', '四', '五', '六'], ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'], , ['日', '一', '二', '三', '四', '五', '六'] ], , [ ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12...
plural
identifier_name
yue.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js function plural(n: number...
export default [ 'yue', [ ['上午', '下午'], , ], , [ ['日', '一', '二', '三', '四', '五', '六'], ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'], , ['日', '一', '二', '三', '四', '五', '六'] ], , [ ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], [ '1月', '2月', '3月', '...
{ return 5; }
identifier_body
yue.ts
/**
* Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js function plural(n: number): number { return 5; } export default [ 'yue', [ ['上午...
* @license * Copyright Google Inc. All Rights Reserved. *
random_line_split
list.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("List", inherited=True) %> ${hel...
% endif ${helpers.predefined_type( "list-style-image", "url::ImageUrlOrNone", engines="gecko servo-2013", initial_value="computed::url::ImageUrlOrNone::none()", initial_specified_value="specified::url::ImageUrlOrNone::none()", animation_value_type="discrete", spec="https://drafts.csswg.org...
{helpers.predefined_type( "list-style-type", "ListStyleType", "computed::ListStyleType::disc()", engines="gecko", initial_specified_value="specified::ListStyleType::disc()", animation_value_type="discrete", boxed=True, spec="https://drafts.csswg.org/css-li...
conditional_block
list.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("List", inherited=True) %> ${hel...
)} // TODO(pcwalton): Implement the full set of counter styles per CSS-COUNTER-STYLES [1] 6.1: // // decimal-leading-zero, armenian, upper-armenian, lower-armenian, georgian, lower-roman, // upper-roman // // [1]: http://dev.w3.org/csswg/css-counter-styles/ % if engine in ["servo-2013", "servo-2020"]: ${he...
engines="gecko servo-2013 servo-2020", servo_2020_pref="layout.2020.unimplemented", animation_value_type="discrete", spec="https://drafts.csswg.org/css-lists/#propdef-list-style-position", servo_restyle_damage="rebuild_and_reflow",
random_line_split
nodejs-dom.ts
import { IDom } from './dom'; import { IGlobal } from './global'; declare module './global' { interface IGlobal { window: any; document: any; } } /** * Represents the core APIs of the DOM. */ export class NodeJsDom implements IDom { constructor(public global: IGlobal) { this.Element = global.Elemen...
removeNode(node: Node, parentNode?: Node): void { if (node.parentNode) { node.parentNode.removeChild(node); } else { parentNode.removeChild(node); } } }
} }
random_line_split
nodejs-dom.ts
import { IDom } from './dom'; import { IGlobal } from './global'; declare module './global' { interface IGlobal { window: any; document: any; } } /** * Represents the core APIs of the DOM. */ export class NodeJsDom implements IDom { constructor(public global: IGlobal) { this.Element = global.Elemen...
createTemplateFromMarkup(markup: string): HTMLTemplateElement { let parser = this.global.document.createElement('div'); parser.innerHTML = markup; let temp = parser.firstElementChild; if (!temp || temp.nodeName !== 'TEMPLATE') { throw new Error('Template markup must be wrapped in a <template> ...
{ return element.nextElementSibling; }
identifier_body
nodejs-dom.ts
import { IDom } from './dom'; import { IGlobal } from './global'; declare module './global' { interface IGlobal { window: any; document: any; } } /** * Represents the core APIs of the DOM. */ export class NodeJsDom implements IDom { constructor(public global: IGlobal) { this.Element = global.Elemen...
return node; } adoptNode(node: Node): Node { return this.global.document.adoptNode(node); } appendNode(newNode: Node, parentNode?: Node): void { (parentNode || this.global.document.body).appendChild(newNode); } replaceNode(newNode: Node, node: Node, parentNode?: Node): void { if (node.pa...
{ destination.appendChild(node); }
conditional_block
nodejs-dom.ts
import { IDom } from './dom'; import { IGlobal } from './global'; declare module './global' { interface IGlobal { window: any; document: any; } } /** * Represents the core APIs of the DOM. */ export class NodeJsDom implements IDom { constructor(public global: IGlobal) { this.Element = global.Elemen...
(element: Element): CSSStyleDeclaration { return this.global.window.getComputedStyle(element); } getElementById(id: string): Element { return this.global.document.getElementById(id); } querySelector<E extends Element = Element>(query: string): E | null { return this.global.document.querySelector(que...
getComputedStyle
identifier_name
events.rs
#[macro_use(with_assets)] extern crate Lattice; use Lattice::window::{Window}; use Lattice::view::{View, Text}; use std::rc::Rc; use std::cell::{RefCell,Cell}; use std::sync::Mutex; #[macro_use] extern crate lazy_static; lazy_static! { static ref text_clicked: Mutex<Cell<bool>> = Mutex::new(Cell::new(false)); ...
else {[0.0, 0.0, 0.0, 0.0]})) .hovered(move |e| { let lh = left_hovered.lock().unwrap().set(true); }) .color([0.4, 0.4, 1.0, 1.0]) .scale(2.0, "em") .width(25.0, "%") .translate_x(150.0, "px") .tr...
{[0.8,0.8,0.8,0.8]}
conditional_block
events.rs
#[macro_use(with_assets)] extern crate Lattice; use Lattice::window::{Window}; use Lattice::view::{View, Text}; use std::rc::Rc; use std::cell::{RefCell,Cell}; use std::sync::Mutex; #[macro_use] extern crate lazy_static; lazy_static! { static ref text_clicked: Mutex<Cell<bool>> = Mutex::new(Cell::new(false)); ...
.translate_y(150.0, "px")); lh.set(false); v.append(Text::new("assets/Macondo-Regular.ttf", "click text") .shadow((if tc.get() {[-3,-3,3,3]} else {[0,0,0,0]}), (if tc.get() {[0.8,0.8,0.8,1.0]} else {[0.0,0.0,0.0,0.0]})) .clicked(move |e|...
{ let mut w = Window::new("Premadeath").set_fullscreen(true); with_assets!(w); w.start(|events| { let mut v = View::new(); let lh = left_hovered.lock().unwrap(); let tc = text_clicked.lock().unwrap(); v.append(Text::new("assets/Macondo-Regular.ttf", "hover text") ...
identifier_body
events.rs
#[macro_use(with_assets)] extern crate Lattice; use Lattice::window::{Window}; use Lattice::view::{View, Text}; use std::rc::Rc; use std::cell::{RefCell,Cell}; use std::sync::Mutex; #[macro_use] extern crate lazy_static; lazy_static! { static ref text_clicked: Mutex<Cell<bool>> = Mutex::new(Cell::new(false)); ...
() { let mut w = Window::new("Premadeath").set_fullscreen(true); with_assets!(w); w.start(|events| { let mut v = View::new(); let lh = left_hovered.lock().unwrap(); let tc = text_clicked.lock().unwrap(); v.append(Text::new("assets/Macondo-Regular.ttf", "hover text") ...
main
identifier_name
events.rs
#[macro_use(with_assets)] extern crate Lattice; use Lattice::window::{Window}; use Lattice::view::{View, Text}; use std::rc::Rc; use std::cell::{RefCell,Cell}; use std::sync::Mutex; #[macro_use] extern crate lazy_static; lazy_static! { static ref text_clicked: Mutex<Cell<bool>> = Mutex::new(Cell::new(false)); ...
tc.set(true); }) .color([1.0, 0.4, 0.4, 1.0]) .scale(3.0, "em") .width(40.0, "%") .align("right") .translate_x(50.0, "%") .translate_y(30.0, "%")); v }); }
(if tc.get() {[0.8,0.8,0.8,1.0]} else {[0.0,0.0,0.0,0.0]})) .clicked(move |e| { let tc = text_clicked.lock().unwrap();
random_line_split
test_node_to_node_quota.py
from copy import copy import pytest from plenum.common.stacks import nodeStackClass from plenum.common.util import randomString from stp_core.loop.eventually import eventually from stp_core.network.auth_mode import AuthMode from stp_core.network.port_dispenser import genHa from stp_core.test.helper import Printer, pr...
received_msgs = stackB._receiveFromListener(Quota(count=stackA.listenerQuota, size=stackA.listenerSize)) assert received_msgs < tconf.NODE_TO_NODE_STACK_QUOTA
stackA.send(msg, 'Beta')
conditional_block
test_node_to_node_quota.py
from copy import copy import pytest from plenum.common.stacks import nodeStackClass from plenum.common.util import randomString from stp_core.loop.eventually import eventually from stp_core.network.auth_mode import AuthMode from stp_core.network.port_dispenser import genHa from stp_core.test.helper import Printer, pr...
(looper, tdir, tconf, connected_nodestacks): stacks, motors = connected_nodestacks stackA = stacks[0] stackB = stacks[1] msg = 'some test messages' limit_size = (tconf.NODE_TO_NODE_STACK_QUOTA - 10) * len(msg) stackB.listenerSize = limit_size for i in range(tconf.NODE_TO_NODE_STACK_QUOTA + 1...
test_limit_by_msg_size
identifier_name
test_node_to_node_quota.py
from copy import copy import pytest from plenum.common.stacks import nodeStackClass from plenum.common.util import randomString from stp_core.loop.eventually import eventually from stp_core.network.auth_mode import AuthMode from stp_core.network.port_dispenser import genHa from stp_core.test.helper import Printer, pr...
def test_set_quota(tdir, tconf, registry): changed_val = 100000 tconf.NODE_TO_NODE_STACK_QUOTA = changed_val stack = create_fake_nodestack(tdir, tconf, registry) assert stack.listenerQuota == tconf.NODE_TO_NODE_STACK_QUOTA def test_set_size(tdir, tconf, registry): changed_val = 100000 tconf....
random_line_split
test_node_to_node_quota.py
from copy import copy import pytest from plenum.common.stacks import nodeStackClass from plenum.common.util import randomString from stp_core.loop.eventually import eventually from stp_core.network.auth_mode import AuthMode from stp_core.network.port_dispenser import genHa from stp_core.test.helper import Printer, pr...
def test_limit_by_msg_size(looper, tdir, tconf, connected_nodestacks): stacks, motors = connected_nodestacks stackA = stacks[0] stackB = stacks[1] msg = 'some test messages' limit_size = (tconf.NODE_TO_NODE_STACK_QUOTA - 10) * len(msg) stackB.listenerSize = limit_size for i in range(tconf...
stacks, motors = connected_nodestacks stackA = stacks[0] stackB = stacks[1] msg = 'some test messages' for i in range(tconf.NODE_TO_NODE_STACK_QUOTA + 10): stackA.send(msg, 'Beta') received_msgs = stackB._receiveFromListener(Quota(count=stackA.listenerQuota, size=stackA.listenerSize)) as...
identifier_body
__init__.py
alt = True if not alt: # Primary method using win32com df = shell.SHGetDesktopFolder() pidl = df.ParseDisplayName(0, None, "::{450d8fba-ad25-11d0-98a8-0800361b1103}")[1] path = shell.SHGetPathFromIDList(pidl) else: # Alternate method using ctypes rather than wi...
""" Makes replacement key """ return "$$%s$$" % (name)
identifier_body
__init__.py
'): # Try the primary method on 32-bit windows try: from win32com.shell import shell alt = False except ImportError: try: import ctypes dll = ctypes.windll.shell32 alt = True except: raise Exception("Could not find 'My Documents'"...
return args ############################################################################# # TODO queryNumInwardIters appears to be unused and should probably be deleted # from here altogether; it's likely an artifact of the legacy vision support. #def queryNumInwardIters(configPath, radialLength, numRepetitions=...
args.append((argName, descriptions.get(argName, "")))
conditional_block
__init__.py
(s=None, additional='', stream=sys.stdout, frame='-'): """Utility function to display nice titles It automatically extracts the name of the function/method it is called from and you can add additional text. title() will then print the name of the function/method and the additional text surrounded by tow lines ...
title
identifier_name
__init__.py
The information is the tuple (function/method name, filename, class) The class will be None if the caller is just a function and not an object method. depth: how far back in the callstack to go to extract the caller info """ f = sys._getframe(depth) method_name = f.f_code.co_name filename = f.f_code.c...
def getCallerInfo(depth=2): """Utility function to get information about function callers
random_line_split
sync_npm.py
# -*- coding: utf-8 -*- """Define the top-level function for the ``sync-npm`` cli. """ from __future__ import absolute_import, division, print_function, unicode_literals import time from aspen import log from gratipay import wireup from gratipay.sync_npm import consume_change_stream, get_last_seq, production_change_...
% (last_seq, sleep_for) ) time.sleep(sleep_for) # avoid a busy loop if thrashing except KeyboardInterrupt: return
"""This function is installed via an entrypoint in ``setup.py`` as ``sync-npm``. Usage:: sync-npm """ env = wireup.env() db = wireup.db(env) while 1: with sentry.teller(env): last_seq = get_last_seq(db) log("Picking up with npm sync at {}.".format(last_se...
identifier_body
sync_npm.py
# -*- coding: utf-8 -*- """Define the top-level function for the ``sync-npm`` cli. """ from __future__ import absolute_import, division, print_function, unicode_literals import time from aspen import log from gratipay import wireup from gratipay.sync_npm import consume_change_stream, get_last_seq, production_change_...
with sentry.teller(env): last_seq = get_last_seq(db) log("Picking up with npm sync at {}.".format(last_seq)) stream = production_change_stream(last_seq) consume_change_stream(stream, db) try: last_seq = get_last_seq(db) sleep_for = 60 ...
conditional_block
sync_npm.py
# -*- coding: utf-8 -*- """Define the top-level function for the ``sync-npm`` cli. """ from __future__ import absolute_import, division, print_function, unicode_literals import time from aspen import log from gratipay import wireup from gratipay.sync_npm import consume_change_stream, get_last_seq, production_change_...
% (last_seq, sleep_for) ) time.sleep(sleep_for) # avoid a busy loop if thrashing except KeyboardInterrupt: return
sleep_for = 60 log( 'Encountered an error, will pick up with %s in %s seconds (Ctrl-C to exit) ...'
random_line_split
sync_npm.py
# -*- coding: utf-8 -*- """Define the top-level function for the ``sync-npm`` cli. """ from __future__ import absolute_import, division, print_function, unicode_literals import time from aspen import log from gratipay import wireup from gratipay.sync_npm import consume_change_stream, get_last_seq, production_change_...
(): """This function is installed via an entrypoint in ``setup.py`` as ``sync-npm``. Usage:: sync-npm """ env = wireup.env() db = wireup.db(env) while 1: with sentry.teller(env): last_seq = get_last_seq(db) log("Picking up with npm sync at {}.".format...
main
identifier_name
HtmlClipboardFormat.py
# Copyright (c) 2008, Humanized, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of ...
( self, html ): """ Initializes the class to represent html. """ # Preconditions: assert( type( html ) == unicode ) # The internal storage format is platonic unicode. self.html = html @classmethod def fromClipboardHtml( cls, clipboardHtml ):...
__init__
identifier_name
HtmlClipboardFormat.py
# Copyright (c) 2008, Humanized, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of ...
else: fragment = sourceHtml html = self._createHtmlPage( fragment ) fragment = fragment.encode( "utf-8" ) html = html.encode( "utf-8" ) assert html == html.decode( "utf-8" ).encode( "utf-8" ), \ "Encoding got out of whack in HtmlClipboardFor...
htmlheader, fragment = sourceHtml.split( "<body>" ) fragment, footer = fragment.split( "</body>" ) htmlheader = htmlheader + "<body>" footer = "</body>" + footer fragment = "".join( [self.START_FRAG, fragment, ...
conditional_block
HtmlClipboardFormat.py
# Copyright (c) 2008, Humanized, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of ...
select an arbitrary chunk of formatted text that might not be valid HTML. For instance selecting half-way through a bolded word would contain no </b> tag. The solution is to encase the fragment in a valid HTML document. You can read more about this at: http://msdn.microsoft.com/workshop/networ...
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ The Win32 clipboard uses a special format for handling HTML. The basic problem that the special format is trying to solve is that the user can
random_line_split
HtmlClipboardFormat.py
# Copyright (c) 2008, Humanized, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of ...
"<body>%s</body>\n" \ "</html>" # These regexps find the character offsets of the fragment strings (see # below) from the HTML clipboard format header. START_RE = "StartFragment:(\d+)" END_RE = "EndFragment:(\d+)" # The Clipboard HTML format uses the following comment strin...
""" Encapsulates the conversation between the clipboard HTML format and standard HTML format. """ # The 1.0 HTML clipboard header format. HEADER_FORMAT = \ "Version:1.0\r\n" \ "StartHTML:%(htmlStart)09d\r\n" \ "EndHTML:%(htmlEnd)09d\r\n" \ "StartFragment:%(...
identifier_body
coerce-date-property.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {DateAdapter} from '@angular/material/core'; /** * Function that attempts to coerce a value to a date using...
throw Error(`Datepicker: Value must be either a date object recognized by the DateAdapter or ` + `an ISO 8601 string. Instead got: ${value}`); }
{ return value; }
conditional_block