file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
msi.py
"""SCons.Tool.packaging.msi The msi packager. """ # # Copyright (c) 2001 - 2014 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # with...
(root): """ generates globally unique identifiers for parts of the xml which need them. Component tags have a special requirement. Their UUID is only allowed to change if the list of their contained resources has changed. This allows for clean removal and proper updates. To handle this require...
generate_guids
identifier_name
msi.py
"""SCons.Tool.packaging.msi The msi packager. """ # # Copyright (c) 2001 - 2014 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # with...
id = [c for c in s if c in charset] # did we already generate an id for this file? try: return id_set[id][s] except KeyError: # no we did not so initialize with the id if id not in id_set: id_set[id] = { s : id } # there is a collision, generate an id which is unique by...
s += '_'+s
conditional_block
msi.py
"""SCons.Tool.packaging.msi The msi packager. """ # # Copyright (c) 2001 - 2014 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # with...
def is_dos_short_file_name(file): """ examine if the given file is in the 8.3 form. """ fname, ext = os.path.splitext(file) proper_ext = len(ext) == 0 or (2 <= len(ext) <= 4) # the ext contains the dot proper_fname = file.isupper() and len(fname) <= 8 return proper_ext and proper_fname def g...
""" Some parts of .wxs need an Id attribute (for example: The File and Directory directives. The charset is limited to A-Z, a-z, digits, underscores, periods. Each Id must begin with a letter or with a underscore. Google for "CNDL0015" for information about this. Requirements: * the string created...
identifier_body
aws_common.py
from functools import reduce from typing import TYPE_CHECKING, List, Optional, Union import boto3 from boto3.session import Session from datahub.configuration import ConfigModel from datahub.configuration.common import AllowDenyPattern from datahub.emitter.mce_builder import DEFAULT_ENV if TYPE_CHECKING: from m...
(self) -> "GlueClient": return self.get_session().client("glue") def get_sagemaker_client(self) -> "SageMakerClient": return self.get_session().client("sagemaker") def make_s3_urn(s3_uri: str, env: str, suffix: Optional[str] = None) -> str: if not s3_uri.startswith("s3://"): raise Va...
get_glue_client
identifier_name
aws_common.py
from functools import reduce from typing import TYPE_CHECKING, List, Optional, Union import boto3 from boto3.session import Session from datahub.configuration import ConfigModel from datahub.configuration.common import AllowDenyPattern from datahub.emitter.mce_builder import DEFAULT_ENV if TYPE_CHECKING: from m...
def get_s3_client(self) -> "S3Client": return self.get_session().client("s3") def get_glue_client(self) -> "GlueClient": return self.get_session().client("glue") def get_sagemaker_client(self) -> "SageMakerClient": return self.get_session().client("sagemaker") def make_s3_urn(s...
if ( self.aws_access_key_id and self.aws_secret_access_key and self.aws_session_token ): return Session( aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key, aws_session_token=s...
identifier_body
aws_common.py
from functools import reduce from typing import TYPE_CHECKING, List, Optional, Union import boto3 from boto3.session import Session from datahub.configuration import ConfigModel from datahub.configuration.common import AllowDenyPattern from datahub.emitter.mce_builder import DEFAULT_ENV if TYPE_CHECKING: from m...
return Session( aws_access_key_id=credentials["AccessKeyId"], aws_secret_access_key=credentials["SecretAccessKey"], aws_session_token=credentials["SessionToken"], region_name=self.aws_region, ) else: return Sess...
credentials = reduce( lambda new_credentials, role_arn: assume_role( role_arn, self.aws_region, new_credentials ), self.aws_role, {}, )
conditional_block
aws_common.py
from functools import reduce from typing import TYPE_CHECKING, List, Optional, Union import boto3 from boto3.session import Session from datahub.configuration import ConfigModel from datahub.configuration.common import AllowDenyPattern from datahub.emitter.mce_builder import DEFAULT_ENV if TYPE_CHECKING: from m...
else: return Session(region_name=self.aws_region) def get_s3_client(self) -> "S3Client": return self.get_session().client("s3") def get_glue_client(self) -> "GlueClient": return self.get_session().client("glue") def get_sagemaker_client(self) -> "SageMakerClient": ...
region_name=self.aws_region, )
random_line_split
main.ts
import { GameTypes, setMinTimeBetweenRequests, Ranks} from "hive-api"; import { BotFramework, Updater } from "lergins-bot-framework"; import * as path from "path"; import { DiscordWebhook } from "./notifications/DiscordWebhook"; import { TwitterBot } from "./notifications/TwitterBot"; import { Stats } from "./Stats"; ...
(updater: Updater) { return bot.addUpdater(updater) } export function start() { return bot.start() } export function send(type: string, message: any) { bot.send(type, message) } async function main() { setMinTimeBetweenRequests((await bot.config().get('min_time_between_requests')) || 1400); process.on('SI...
addUpdater
identifier_name
main.ts
import { GameTypes, setMinTimeBetweenRequests, Ranks} from "hive-api"; import { BotFramework, Updater } from "lergins-bot-framework";
import { CurrPlayerUpdater } from "./updater/CurrPlayerUpdater"; import { AchievementUpdater } from "./updater/AchievementUpdater"; import { GamePlayersUpdater } from "./updater/GamePlayersUpdater"; import { MapUpdater } from "./updater/MapUpdater"; import { MedalUpdater } from "./updater/MedalUpdater"; import { Player...
import * as path from "path"; import { DiscordWebhook } from "./notifications/DiscordWebhook"; import { TwitterBot } from "./notifications/TwitterBot"; import { Stats } from "./Stats";
random_line_split
main.ts
import { GameTypes, setMinTimeBetweenRequests, Ranks} from "hive-api"; import { BotFramework, Updater } from "lergins-bot-framework"; import * as path from "path"; import { DiscordWebhook } from "./notifications/DiscordWebhook"; import { TwitterBot } from "./notifications/TwitterBot"; import { Stats } from "./Stats"; ...
} main().catch((e) => console.error(e));
{ console.warn(`!!! DEBUG MODE !!!`) }
conditional_block
main.ts
import { GameTypes, setMinTimeBetweenRequests, Ranks} from "hive-api"; import { BotFramework, Updater } from "lergins-bot-framework"; import * as path from "path"; import { DiscordWebhook } from "./notifications/DiscordWebhook"; import { TwitterBot } from "./notifications/TwitterBot"; import { Stats } from "./Stats"; ...
export function send(type: string, message: any) { bot.send(type, message) } async function main() { setMinTimeBetweenRequests((await bot.config().get('min_time_between_requests')) || 1400); process.on('SIGTERM', async () => { Stats.print(); await Stats.saveToGoogleSheets(); ...
{ return bot.start() }
identifier_body
server.js
var EXPRESS=require("EXPRESS"), PATH=require("path"), FS=require("fs"), CLUSTER=require("cluster"), Q=require("q"), HDMA=require("./nodejs/api/hdma"), CONFIG=require("./nodejs/config"), LOGGER=require("./nodejs/config/logger.js"), NUMCPU=2, //require("os").cpus().length, models={ geoviewer: null }, domain=...
} /** //cluster if(CLUSTER.isMaster){ for(var i=0;i<NUMCPU;i++){ CLUSTER.fork(); } Q.all([HDMA.mongodb.connect("localhost:27017", "HDMA"), HDMA.mongodb.connect("localhost:27017", "IBSS")]).then(function(results){ console.log(results); //console.log(b); }).catch(function(err){ console.log("error", e...
{ port=value; }
conditional_block
server.js
var EXPRESS=require("EXPRESS"), PATH=require("path"), FS=require("fs"), CLUSTER=require("cluster"), Q=require("q"), HDMA=require("./nodejs/api/hdma"), CONFIG=require("./nodejs/config"), LOGGER=require("./nodejs/config/logger.js"), NUMCPU=2, //require("os").cpus().length, models={ geoviewer: null }, domain=...
{ app=EXPRESS(); server=app.listen(port); io=require("socket.io").listen(server, {resource:"/socket/socket.io", log:false});//, transports:["xhr-polling"]}); //because we are using iis7 as the main web server which does not support websocket. we need to change to long-polling for socket. please refer to http://schm...
identifier_body
server.js
var EXPRESS=require("EXPRESS"), PATH=require("path"), FS=require("fs"), CLUSTER=require("cluster"), Q=require("q"), HDMA=require("./nodejs/api/hdma"), CONFIG=require("./nodejs/config"), LOGGER=require("./nodejs/config/logger.js"), NUMCPU=2, //require("os").cpus().length, models={ geoviewer: null }, domain=...
//app.setMaxListeners(0); //io.setMaxListeners(0); //passport required config //app.use(EXPRESS.static("public")) app.use(EXPRESS.cookieParser()); app.use(EXPRESS.session({secret:'hdma@SDSU'})); // session secret app.use(app.router) //---------------------------------------------------------------------------...
//jsonp app.set("jsonp callback", true); //maxlistener
random_line_split
server.js
var EXPRESS=require("EXPRESS"), PATH=require("path"), FS=require("fs"), CLUSTER=require("cluster"), Q=require("q"), HDMA=require("./nodejs/api/hdma"), CONFIG=require("./nodejs/config"), LOGGER=require("./nodejs/config/logger.js"), NUMCPU=2, //require("os").cpus().length, models={ geoviewer: null }, domain=...
(){ app=EXPRESS(); server=app.listen(port); io=require("socket.io").listen(server, {resource:"/socket/socket.io", log:false});//, transports:["xhr-polling"]}); //because we are using iis7 as the main web server which does not support websocket. we need to change to long-polling for socket. please refer to http://sc...
init
identifier_name
mod.rs
pub mod md5; pub mod sha1; pub trait Hasher { /** * Reset the hasher's state. */ fn reset(&mut self); /** * Provide input data. */ fn update(&mut self, data: &[u8]); /** * Retrieve digest result. The output must be large enough to contains result * size (from output_...
(&self) -> Vec<u8> { let size = self.output_size(); let mut buf = Vec::from_elem(size, 0u8); self.output(buf.as_mut_slice()); buf } } pub trait Hashable { /** * Feed the value to the hasher passed in parameter. */ fn feed<H: Hasher>(&self, h: &mut H); /...
digest
identifier_name
mod.rs
pub mod md5; pub mod sha1; pub trait Hasher { /** * Reset the hasher's state. */ fn reset(&mut self); /** * Provide input data. */ fn update(&mut self, data: &[u8]); /** * Retrieve digest result. The output must be large enough to contains result * size (from output_...
}
{ h.update(*self) }
identifier_body
mod.rs
pub mod md5; pub mod sha1; pub trait Hasher { /** * Reset the hasher's state. */ fn reset(&mut self); /** * Provide input data. */ fn update(&mut self, data: &[u8]); /** * Retrieve digest result. The output must be large enough to contains result * size (from output_...
* Get the block size in bytes. */ fn block_size(&self) -> uint { (self.block_size_bits() + 7) / 8 } fn digest(&self) -> Vec<u8> { let size = self.output_size(); let mut buf = Vec::from_elem(size, 0u8); self.output(buf.as_mut_slice()); buf } } ...
(self.output_size_bits() + 7) / 8 } /**
random_line_split
feature_column_lib.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
# See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """FeatureColumns: tools for ingesting and representing features.""" from __future__ import absolute_import from __future__ import divi...
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
random_line_split
validate-changelog.ts
#!/usr/bin/env ts-node import * as Path from 'path' import * as Fs from 'fs' import Ajv, { ErrorObject } from 'ajv' function handleError(error: string) { console.error(error) process.exit(-1) } function formatErrors(errors: ErrorObject[]): string
const repositoryRoot = Path.dirname(__dirname) const changelogPath = Path.join(repositoryRoot, 'changelog.json') // eslint-disable-next-line no-sync const changelog = Fs.readFileSync(changelogPath, 'utf8') let changelogObj = null try { changelogObj = JSON.parse(changelog) } catch { handleError( 'Unable to ...
{ return errors .map(error => { const { dataPath, message } = error const additionalProperties = error.params as any const additionalProperty = additionalProperties.additionalProperty as string let additionalPropertyText = '' if (additionalProperty != null) { additionalProp...
identifier_body
validate-changelog.ts
#!/usr/bin/env ts-node import * as Path from 'path' import * as Fs from 'fs' import Ajv, { ErrorObject } from 'ajv' function handleError(error: string) { console.error(error) process.exit(-1) } function formatErrors(errors: ErrorObject[]): string { return errors .map(error => { const { dataPath, mes...
'^([0-9]+.[0-9]+.[0-9]+)(-beta[0-9]+|-test[0-9]+)?$': { type: 'array', items: { type: 'string', }, uniqueItems: true, }, }, additionalProperties: false, }, }, } const ajv = new Ajv({ allErrors: true, uniqueItems: true }) const valida...
patternProperties: {
random_line_split
validate-changelog.ts
#!/usr/bin/env ts-node import * as Path from 'path' import * as Fs from 'fs' import Ajv, { ErrorObject } from 'ajv' function handleError(error: string) { console.error(error) process.exit(-1) } function formatErrors(errors: ErrorObject[]): string { return errors .map(error => { const { dataPath, mes...
console.log('The changelog is totally fine')
{ handleError(`Errors: \n${formatErrors(validate.errors)}`) }
conditional_block
validate-changelog.ts
#!/usr/bin/env ts-node import * as Path from 'path' import * as Fs from 'fs' import Ajv, { ErrorObject } from 'ajv' function
(error: string) { console.error(error) process.exit(-1) } function formatErrors(errors: ErrorObject[]): string { return errors .map(error => { const { dataPath, message } = error const additionalProperties = error.params as any const additionalProperty = additionalProperties.additionalPrope...
handleError
identifier_name
tests.py
from reviewboard.accounts.models import LocalSiteProfile from reviewboard.reviews.models import ReviewRequest class ProfileTests(TestCase): """Testing the Profile model.""" fixtures = ['test_users'] def test_is_profile_visible_with_public(self): """Testing User.is_profile_public with public profi...
from django.contrib.auth.models import User from djblets.testing.decorators import add_fixtures from djblets.testing.testcases import TestCase
random_line_split
tests.py
from django.contrib.auth.models import User from djblets.testing.decorators import add_fixtures from djblets.testing.testcases import TestCase from reviewboard.accounts.models import LocalSiteProfile from reviewboard.reviews.models import ReviewRequest class ProfileTests(TestCase): """Testing the Profile model."...
@add_fixtures(['test_reviewrequests', 'test_scmtools', 'test_site']) def test_is_star_unstar_updating_count_correctly(self): """Testing if star, unstar affect review request counts correctly.""" user1 = User.objects.get(username='admin') profile1 = user1.get_profile() review_re...
"""Testing User.is_profile_public with private profiles.""" user1 = User.objects.get(username='admin') user2 = User.objects.get(username='doc') profile = user1.get_profile() profile.is_private = True profile.save() self.assertFalse(user1.is_profile_visible(user2)) ...
identifier_body
tests.py
from django.contrib.auth.models import User from djblets.testing.decorators import add_fixtures from djblets.testing.testcases import TestCase from reviewboard.accounts.models import LocalSiteProfile from reviewboard.reviews.models import ReviewRequest class ProfileTests(TestCase): """Testing the Profile model."...
(self): """Testing if star, unstar affect review request counts correctly.""" user1 = User.objects.get(username='admin') profile1 = user1.get_profile() review_request = ReviewRequest.objects.public()[0] site_profile = profile1.site_profiles.get(local_site=None) profile1...
test_is_star_unstar_updating_count_correctly
identifier_name
sort-tree.component.ts
import { Directive, EventEmitter, ViewChild } from '@angular/core'; import { MatSnackBar } from '@angular/material/snack-bar'; import { Title } from '@angular/platform-browser'; import { TranslateService } from '@ngx-translate/core'; import { SortDefinition } from 'app/core/ui-services/base-sort.service'; import { Pr...
import { BaseViewModel } from './base-view-model'; export interface SortTreeFilterOption extends Identifiable { label: string; id: number; state: boolean; } /** * Abstract Sort view for hierarchic item trees */ @Directive() export abstract class SortTreeViewComponentDirective<V extends BaseViewModel> ...
import { CanComponentDeactivate } from 'app/shared/utils/watch-for-changes.guard'; import { BaseViewComponentDirective } from './base-view';
random_line_split
sort-tree.component.ts
import { Directive, EventEmitter, ViewChild } from '@angular/core'; import { MatSnackBar } from '@angular/material/snack-bar'; import { Title } from '@angular/platform-browser'; import { TranslateService } from '@ngx-translate/core'; import { SortDefinition } from 'app/core/ui-services/base-sort.service'; import { Pr...
/** * Function to open a prompt dialog, so the user will be warned if they have * made changes and not saved them. * * @returns The result from the prompt dialog. */ public async canDeactivate(): Promise<boolean> { if (this.hasChanged) { const title = this.translat...
{ this.changeState.emit(nextState); }
identifier_body
sort-tree.component.ts
import { Directive, EventEmitter, ViewChild } from '@angular/core'; import { MatSnackBar } from '@angular/material/snack-bar'; import { Title } from '@angular/platform-browser'; import { TranslateService } from '@ngx-translate/core'; import { SortDefinition } from 'app/core/ui-services/base-sort.service'; import { Pr...
(nextNumberOfSeenNodes: [number, number]): void { this.seenNodes = nextNumberOfSeenNodes; } /** * Function to emit if the nodes should be expanded or collapsed. * * @param nextState Is the next state, expanded or collapsed, the nodes should be. */ public onStateChange(nextState:...
onChangeAmountOfItems
identifier_name
sort-tree.component.ts
import { Directive, EventEmitter, ViewChild } from '@angular/core'; import { MatSnackBar } from '@angular/material/snack-bar'; import { Title } from '@angular/platform-browser'; import { TranslateService } from '@ngx-translate/core'; import { SortDefinition } from 'app/core/ui-services/base-sort.service'; import { Pr...
} /** * Function to set an info if changes has been made. * * @param hasChanged Boolean received from the tree to see that changes has been made. */ public receiveChanges(hasChanged: boolean): void { this.hasChanged = hasChanged; } /** * Function to receive the ne...
{ this.osSortTree.setSubscription(); }
conditional_block
usage.rs
use crate as utils; use rustc_hir as hir; use rustc_hir::def::Res; use rustc_hir::intravisit; use rustc_hir::intravisit::{NestedVisitorMap, Visitor}; use rustc_hir::HirIdSet; use rustc_hir::{Expr, ExprKind, HirId, Path}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; use rustc_middle::hir::map::Ma...
} }
{ intravisit::walk_expr(self, expr); }
conditional_block
usage.rs
use crate as utils; use rustc_hir as hir; use rustc_hir::def::Res; use rustc_hir::intravisit; use rustc_hir::intravisit::{NestedVisitorMap, Visitor}; use rustc_hir::HirIdSet; use rustc_hir::{Expr, ExprKind, HirId, Path}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; use rustc_middle::hir::map::Ma...
let mut finder = ParamBindingIdCollector { binding_hir_ids: Vec::new(), }; finder.visit_param(param); for hir_id in &finder.binding_hir_ids { hir_ids.push(*hir_id); } } hir_ids } } impl<'tcx> intravisit::Visi...
random_line_split
usage.rs
use crate as utils; use rustc_hir as hir; use rustc_hir::def::Res; use rustc_hir::intravisit; use rustc_hir::intravisit::{NestedVisitorMap, Visitor}; use rustc_hir::HirIdSet; use rustc_hir::{Expr, ExprKind, HirId, Path}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; use rustc_middle::hir::map::Ma...
(&mut self) -> intravisit::NestedVisitorMap<Self::Map> { intravisit::NestedVisitorMap::OnlyBodies(self.cx.tcx.hir()) } } struct ReturnBreakContinueMacroVisitor { seen_return_break_continue: bool, } impl ReturnBreakContinueMacroVisitor { fn new() -> ReturnBreakContinueMacroVisitor { ReturnB...
nested_visit_map
identifier_name
usage.rs
use crate as utils; use rustc_hir as hir; use rustc_hir::def::Res; use rustc_hir::intravisit; use rustc_hir::intravisit::{NestedVisitorMap, Visitor}; use rustc_hir::HirIdSet; use rustc_hir::{Expr, ExprKind, HirId, Path}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; use rustc_middle::hir::map::Ma...
} impl<'tcx> intravisit::Visitor<'tcx> for ParamBindingIdCollector { type Map = Map<'tcx>; fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) { if let hir::PatKind::Binding(_, hir_id, ..) = pat.kind { self.binding_hir_ids.push(hir_id); } intravisit::walk_pat(self, pat); ...
{ let mut hir_ids: Vec<hir::HirId> = Vec::new(); for param in body.params.iter() { let mut finder = ParamBindingIdCollector { binding_hir_ids: Vec::new(), }; finder.visit_param(param); for hir_id in &finder.binding_hir_ids { ...
identifier_body
tree.js
import {extend} from "lodash"; import SeqCollection from "../model/SeqCollection"; const TreeHelper = function(msa) { this.msa = msa; return this; }; var tf = {loadTree: function(cb) { return this.msa.g.package.loadPackages(["msa-tnt", "biojs-io-newick"], cb); }, showTree: function(newickStr)...
model: nodes, sel: sel, msa: this.msa }); // remove top collection nodes.models.forEach((e) => { delete e.collection; return Object.setPrototypeOf(e, require("backbone-thin").Model.prototype); }); this.msa.seqs.reset(nodes.models); //@m...
var m = new mt.adapters.msa({
random_line_split
tree.js
import {extend} from "lodash"; import SeqCollection from "../model/SeqCollection"; const TreeHelper = function(msa) { this.msa = msa; return this; }; var tf = {loadTree: function(cb) { return this.msa.g.package.loadPackages(["msa-tnt", "biojs-io-newick"], cb); }, showTree: function(newickStr)...
const seqs = this.msa.seqs.toJSON(); //adapt tree ids to sequence ids function iterateTree(nwck){ if(nwck.children != null){ nwck.children.forEach(x => iterateTree(x)); } else { //found a leave let seq = seqs.filter(s => s.name === nwck.name)[0]; ...
{ console.log('A tree already exists. It will be overridden.'); treeDiv = this.msa.el.getElementsByClassName('tnt_groupDiv')[0].parentNode; treeDiv.innerHTML = ''; }
conditional_block
tree.js
import {extend} from "lodash"; import SeqCollection from "../model/SeqCollection"; const TreeHelper = function(msa) { this.msa = msa; return this; }; var tf = {loadTree: function(cb) { return this.msa.g.package.loadPackages(["msa-tnt", "biojs-io-newick"], cb); }, showTree: function(newickStr)...
(nwck){ if(nwck.children != null){ nwck.children.forEach(x => iterateTree(x)); } else { //found a leave let seq = seqs.filter(s => s.name === nwck.name)[0]; if(seq != null){ if(typeof seq.id === 'number'){ //no tree has been uploaded so ...
iterateTree
identifier_name
tree.js
import {extend} from "lodash"; import SeqCollection from "../model/SeqCollection"; const TreeHelper = function(msa) { this.msa = msa; return this; }; var tf = {loadTree: function(cb) { return this.msa.g.package.loadPackages(["msa-tnt", "biojs-io-newick"], cb); }, showTree: function(newickStr)...
}; extend(TreeHelper.prototype , tf); export default TreeHelper;
{ return require(pkg); }
identifier_body
moh-731-resource.service.ts
import { of as observableOf, Observable } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { Injectable } from '@angular/core'; // tslint:disable-next-line:import-blacklist import { Subject } from 'rxjs/Rx'; import { AppSettingsService } from '../app-settings/app-settings.service'; import { DataCa...
else { report = 'MOH-731-report-2017'; } const urlParams: HttpParams = new HttpParams() .set('locationUuids', locationUuids) .set('startDate', startDate) .set('endDate', endDate) .set('reportName', report) .set('isAggregated', aggregated); const request = this.http ...
{ report = 'MOH-731-report'; }
conditional_block
moh-731-resource.service.ts
import { of as observableOf, Observable } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { Injectable } from '@angular/core'; // tslint:disable-next-line:import-blacklist import { Subject } from 'rxjs/Rx'; import { AppSettingsService } from '../app-settings/app-settings.service'; import { DataCa...
}
{ let report = ''; let aggregated = 'false'; if (isAggregated) { aggregated = 'true'; } if (isLegacyReport) { report = 'MOH-731-report'; } else { report = 'MOH-731-report-2017'; } const urlParams: HttpParams = new HttpParams() .set('locationUuids', locationUuids...
identifier_body
moh-731-resource.service.ts
import { of as observableOf, Observable } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { Injectable } from '@angular/core'; // tslint:disable-next-line:import-blacklist import { Subject } from 'rxjs/Rx'; import { AppSettingsService } from '../app-settings/app-settings.service'; import { DataCa...
( public http: HttpClient, public appSettingsService: AppSettingsService, public cacheService: DataCacheService ) {} public getMoh731Report( locationUuids: string, startDate: string, endDate: string, isLegacyReport: boolean, isAggregated: boolean, cacheTtl: number = 0 ): Obser...
constructor
identifier_name
moh-731-resource.service.ts
import { of as observableOf, Observable } from 'rxjs'; import { catchError, map } from 'rxjs/operators';
import { DataCacheService } from '../shared/services/data-cache.service'; import { HttpParams, HttpClient } from '@angular/common/http'; @Injectable() export class Moh731ResourceService { private _url = 'MOH-731-report'; public get url(): string { return this.appSettingsService.getEtlRestbaseurl().trim() + thi...
import { Injectable } from '@angular/core'; // tslint:disable-next-line:import-blacklist import { Subject } from 'rxjs/Rx'; import { AppSettingsService } from '../app-settings/app-settings.service';
random_line_split
ctrl_c_handler.py
# Copyright 2015 Google Inc. All Rights Reserved. """Context manager to help with Control-C handling during critical commands.""" import signal from googlecloudsdk.calliope import exceptions from googlecloudsdk.core import log from googlecloudsdk.test.lib import exit_code class CancellableTestSection(object): ""...
(self, matrix_id, testing_api_helper): self._old_handler = None self._matrix_id = matrix_id self._testing_api_helper = testing_api_helper def __enter__(self): self._old_handler = signal.getsignal(signal.SIGINT) signal.signal(signal.SIGINT, self._Handler) return self def __exit__(self, typ,...
__init__
identifier_name
ctrl_c_handler.py
# Copyright 2015 Google Inc. All Rights Reserved. """Context manager to help with Control-C handling during critical commands."""
import signal from googlecloudsdk.calliope import exceptions from googlecloudsdk.core import log from googlecloudsdk.test.lib import exit_code class CancellableTestSection(object): """Cancel a test matrix if CTRL-C is typed during a section of code. While within this context manager, the CTRL-C signal is caught...
random_line_split
ctrl_c_handler.py
# Copyright 2015 Google Inc. All Rights Reserved. """Context manager to help with Control-C handling during critical commands.""" import signal from googlecloudsdk.calliope import exceptions from googlecloudsdk.core import log from googlecloudsdk.test.lib import exit_code class CancellableTestSection(object): ""...
log.status.write('\n\nCancelling test [{id}]...\n\n' .format(id=self._matrix_id)) self._testing_api_helper.CancelTestMatrix(self._matrix_id) raise exceptions.ExitCodeNoError(exit_code=exit_code.MATRIX_CANCELLED)
identifier_body
plotCorrelation.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import argparse import numpy as np import matplotlib matplotlib.use('Agg') matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['svg.fonttype'] = 'none' from deeptools import cm # noqa: F401 import matplotlib.pyplot as plt from deeptools.correlation im...
def heatmap_options(): """ Options for generating the correlation heatmap """ parser = argparse.ArgumentParser(add_help=False) heatmap = parser.add_argument_group('Heatmap options') heatmap.add_argument('--plotHeight', help='Plot height in cm. (Default: %(default)s)'...
""" Options specific for creating the scatter plot """ parser = argparse.ArgumentParser(add_help=False) scatter_opts = parser.add_argument_group('Scatter plot options') scatter_opts.add_argument('--xRange', help='The X axis range. The default scales these such that the...
identifier_body
plotCorrelation.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import argparse import numpy as np import matplotlib matplotlib.use('Agg') matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['svg.fonttype'] = 'none' from deeptools import cm # noqa: F401 import matplotlib.pyplot as plt from deeptools.correlation im...
if args.plotFile is None and args.outFileCorMatrix is None: sys.exit("At least one of --plotFile and --outFileCorMatrix must be specified!\n") corr = Correlation(args.corData, args.corMethod, labels=args.labels, remove_outliers=args....
args = parse_arguments().parse_args(args)
random_line_split
plotCorrelation.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import argparse import numpy as np import matplotlib matplotlib.use('Agg') matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['svg.fonttype'] = 'none' from deeptools import cm # noqa: F401 import matplotlib.pyplot as plt from deeptools.correlation im...
(): """ Options specific for creating the scatter plot """ parser = argparse.ArgumentParser(add_help=False) scatter_opts = parser.add_argument_group('Scatter plot options') scatter_opts.add_argument('--xRange', help='The X axis range. The default scales these such ...
scatterplot_options
identifier_name
plotCorrelation.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import argparse import numpy as np import matplotlib matplotlib.use('Agg') matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['svg.fonttype'] = 'none' from deeptools import cm # noqa: F401 import matplotlib.pyplot as plt from deeptools.correlation im...
if args.outFileCorMatrix: o = open(args.outFileCorMatrix, "w") o.write("#plotCorrelation --outFileCorMatrix\n") corr.save_corr_matrix(o) o.close()
if args.whatToPlot == 'scatterplot': corr.plot_scatter(args.plotFile, plot_title=args.plotTitle, image_format=args.plotFileFormat, xRange=args.xRange, yRange=args.yRange, ...
conditional_block
bs.js
For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'forms', 'bs', { button: { title: 'Button Properties', text: 'Text (Value)', type: 'Type', typeBtn: 'Button', typeSbm: 'Submit', typeRst: 'Reset' }, checkboxAndRadio: { checkboxTitle: 'Checkbox Propert...
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
random_line_split
test_histotoolsbase.py
from ROOT import TH1I, gROOT, kRed, kBlue import unittest import tempfile import shutil import os from varial.extensions.cmsrun import Sample from varial.wrappers import HistoWrapper from varial.history import History from varial import analysis from varial import settings from varial import diskio class TestHistoTo...
def setUp(self): super(TestHistoToolsBase, self).setUp() test_fs = "fileservice/" if not os.path.exists(test_fs): test_fs = "varial/test/" + test_fs settings.DIR_FILESERVICE = test_fs if (not os.path.exists(test_fs + "tt.root")) \ or (not os.path.exists(test...
identifier_body
test_histotoolsbase.py
from ROOT import TH1I, gROOT, kRed, kBlue import unittest import tempfile import shutil import os from varial.extensions.cmsrun import Sample from varial.wrappers import HistoWrapper from varial.history import History from varial import analysis from varial import settings from varial import diskio class TestHistoTo...
os.system('rm -r %s' % self.test_dir)
conditional_block
test_histotoolsbase.py
from ROOT import TH1I, gROOT, kRed, kBlue import unittest import tempfile import shutil import os from varial.extensions.cmsrun import Sample from varial.wrappers import HistoWrapper from varial.history import History from varial import analysis from varial import settings from varial import diskio class TestHistoTo...
(self): super(TestHistoToolsBase, self).tearDown() del self.test_wrp diskio.close_open_root_files() gROOT.Reset() if os.path.exists(self.test_dir): os.system('rm -r %s' % self.test_dir)
tearDown
identifier_name
test_histotoolsbase.py
from ROOT import TH1I, gROOT, kRed, kBlue import unittest import tempfile import shutil import os from varial.extensions.cmsrun import Sample from varial.wrappers import HistoWrapper from varial.history import History from varial import analysis from varial import settings from varial import diskio class TestHistoTo...
] analysis.active_samples = analysis.all_samples.keys() # create a test wrapper h1 = TH1I("h1", "H1", 2, .5, 4.5) h1.Fill(1) h1.Fill(3,2) hist = History("test_op") # create some fake history hist.add_args([History("fake_input_A"), History("fake_input_B")]...
"tt gamma", "z jets"
random_line_split
debugkarma.conf.js
module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], files: [ 'src/bobril.js', ...
// available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 8765, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR ||...
// test results reporter to use // possible values: 'dots', 'progress'
random_line_split
mediawiki.js
// mediawiki add categories /*jslint node: true */ 'use strict'; var qs = require('querystring'); var utils = require('../utils'); var bot = require('nodemw'); exports.search = function(api, context, callback) { if (api.indexOf('mediawiki.category.') === 0) { if (api === 'mediawiki.category.wikipedia')
} };
{ var bot = require('nodemw'), method = 'http://', host = 'en.wikipedia.org', apiPath = '/w', articlePath = '/wiki', client = new bot({ server: host, path: apiPath }); context.referers = 'http://en.wikipedia.org/w/api.php'; client.getPagesInCategory(context.query, function(pages...
conditional_block
mediawiki.js
// mediawiki add categories /*jslint node: true */ 'use strict'; var qs = require('querystring');
var utils = require('../utils'); var bot = require('nodemw'); exports.search = function(api, context, callback) { if (api.indexOf('mediawiki.category.') === 0) { if (api === 'mediawiki.category.wikipedia') { var bot = require('nodemw'), method = 'http://', host = 'en.wikipedia.org', apiPath = '/w', article...
random_line_split
index.ts
/* MIT License Copyright (c) 2020 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modi...
SOFTWARE. */ export { NotFoundScene } from './NotFoundScene'
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
random_line_split
urn.ts
/**
*/ const encodedSlashRegExp = new RegExp(encodeURIComponent('/'), 'g'); /** * Replaces any occurrence of / with the encoded equivalent * @param {string} urn * @return {string} */ export const encodeForwardSlash = (urn: string): string => urn.replace(/\//g, () => encodeURIComponent('/')); /** * Replaces encoded s...
* Cached RegExp object for a global search of / * @type {RegExp}
random_line_split
shift.py
import numpy from chainer.backends import cuda from chainer import function_node from chainer.utils import type_check def _pair(x): if hasattr(x, '__getitem__'): return x return x, x class Shift(function_node.FunctionNode): def __init__(self, ksize=3, dilate=1): super(Shift, self).__in...
int ky = (group_idx / kw) - kh / 2; int kx = (group_idx % kw) - kw / 2; if (group_idx >= n_groups) { ky = 0; kx = 0; } int in_row = -ky * dy + out_row; int in_col = -kx * dx + out_col; ...
group_idx = n_groups - 1; } else if (group_idx == n_groups - 1) { group_idx = (n_groups - 1) / 2; }
random_line_split
shift.py
import numpy from chainer.backends import cuda from chainer import function_node from chainer.utils import type_check def _pair(x): if hasattr(x, '__getitem__'): return x return x, x class Shift(function_node.FunctionNode): def
(self, ksize=3, dilate=1): super(Shift, self).__init__() self.kh, self.kw = _pair(ksize) if self.kh % 2 != 1: raise ValueError('kh must be odd') if self.kw % 2 != 1: raise ValueError('kw must be odd') self.dy, self.dx = _pair(dilate) def check_type_fo...
__init__
identifier_name
shift.py
import numpy from chainer.backends import cuda from chainer import function_node from chainer.utils import type_check def _pair(x): if hasattr(x, '__getitem__'): return x return x, x class Shift(function_node.FunctionNode): def __init__(self, ksize=3, dilate=1): super(Shift, self).__in...
def shift(x, ksize=3, dilate=1): """Shift function. See: `Shift: A Zero FLOP, Zero Parameter Alternative to Spatial \ Convolutions <https://arxiv.org/abs/1711.08141>`_ Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variab...
return shift(grad_outputs[0], ksize=(self.kh, self.kw), dilate=(-self.dy, -self.dx)),
identifier_body
shift.py
import numpy from chainer.backends import cuda from chainer import function_node from chainer.utils import type_check def _pair(x): if hasattr(x, '__getitem__'):
return x, x class Shift(function_node.FunctionNode): def __init__(self, ksize=3, dilate=1): super(Shift, self).__init__() self.kh, self.kw = _pair(ksize) if self.kh % 2 != 1: raise ValueError('kh must be odd') if self.kw % 2 != 1: raise ValueError('kw ...
return x
conditional_block
markdown.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let input_str = load_or_return!(input, 1, 2); let mut collector = Collector::new(input.to_string(), libs, externs, true); find_testable_code(input_str.as_slice(), &mut collector); test_args.insert(0, "rustdoctest".to_string()); testing::test_main(test_args.as_slice(), collector.tests); 0 }
identifier_body
markdown.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) { let mut metadata = Vec::new(); for line in s.lines() { if line.starts_with("%") { // remove %<whitespace> metadata.push(line[1..].trim_left()) } else { let line_start_byte = s.subslice_offset(line); ret...
extract_leading_metadata
identifier_name
markdown.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<title>{title}</title> {css} {in_header} </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> {before_content} <h1 class="title">{title}</h1> {text}...
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc">
random_line_split
ecg.py
# Copyright (c) 2017, MD2K Center of Excellence # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditio...
def rr_interval_update(rpeak_temp1: List[DataPoint], rr_ave: float, min_size: int = 8) -> float: """ :param min_size: 8 last R-peaks are checked to compute the running rr interval average :param rpeak_temp1: R peak locations :param rr_ave: previous rr-interv...
""" filter ecg datastream first and compute rr-interval datastream from the ecg datastream :param ecg:ecg datastream :param ecg_quality : ecg quality annotated datastream :param fs: sampling frequency :return: rr-interval datastream """ ecg_filtered = filter_bad_ecg(ecg, ecg_quality) #...
identifier_body
ecg.py
# Copyright (c) 2017, MD2K Center of Excellence # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditio...
(ecg: DataStream, ecg_quality: DataStream) -> DataStream: """ This function combines the raw ecg and ecg data quality datastream and only keeps those datapoints that are assigned acceptable in data quality :param ecg: raw ecg datastream :param ecg_quality: ecg quality datastream ...
filter_bad_ecg
identifier_name
ecg.py
# Copyright (c) 2017, MD2K Center of Excellence # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditio...
else: # R peak checking if threshold_1 <= mov_win_int_signal[peak_location_in_signal_array[ind_rpeak]] < 3 * sig_lev: rpeak_array_indices.append(peak_location_in_signal_array[ind_rpeak]) rpeak_inds_in_peak_array.append(ind_rpeak) sig_lev =...
threshold_1 = noise_lev + 0.25 * (sig_lev - noise_lev) threshold_2 = 0.5 * threshold_1 ind_rpeak += 1
conditional_block
ecg.py
# Copyright (c) 2017, MD2K Center of Excellence # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditio...
ecg_filtered.data = ecg_filtered_array return ecg_filtered def compute_rr_intervals(ecg: DataStream, ecg_quality: DataStream, fs: float) -> DataStream: """ filter ecg datastream first and compute rr-interval datastream from the ecg datastream :par...
ecg_filtered_array.append(ecg.data[i]) final_index = i initial_index = final_index
random_line_split
Gruntfile.js
module.exports = function (grunt) { grunt.initConfig({ // Builds Sass sass: { dev: { options: { style: 'expanded', sourcemap: true, includePaths: [ 'govuk_modules/govuk_template/assets/stylesheets', 'govuk_modules/govuk_frontend_toolkit/styl...
} }, // nodemon watches for changes and restarts app nodemon: { dev: { script: 'server.js', options: { ext: 'js, json', ignore: ['node_modules/**', 'app/assets/**', 'app/components/**', 'app/lib/**', 'public/**'], args: grunt.option.flags() ...
options: { spawn: false }
random_line_split
jquery.compat-1.3.js
/* * Compatibility Plugin for jQuery 1.3 (on top of jQuery 1.4) * All code copied from jQuery 1.4 * By John Resig * Dual licensed under MIT and GPL. */ (function(jQuery) { // .add() is no longer equivalent to .concat() // Results are now returned in document order jQuery.fn.add = function( selector, context )...
if ( xml && data.documentElement.nodeName === "parsererror" ) { throw "parsererror"; } // Allow a pre-filtering function to sanitize the response // s is checked to keep backwards compatibility if ( s && s.dataFilter ) { data = s.dataFilter( data, type ); } // The filter can actually parse the re...
var ct = xhr.getResponseHeader("content-type") || "", xml = type === "xml" || !type && ct.indexOf("xml") >= 0, data = xml ? xhr.responseXML : xhr.responseText;
random_line_split
jquery.compat-1.3.js
/* * Compatibility Plugin for jQuery 1.3 (on top of jQuery 1.4) * All code copied from jQuery 1.4 * By John Resig * Dual licensed under MIT and GPL. */ (function(jQuery) { // .add() is no longer equivalent to .concat() // Results are now returned in document order jQuery.fn.add = function( selector, context )...
}); } return oldval.apply( this, arguments ); }; // jQuery.browser.version now exclusively matches based upon the rendering engine jQuery.browser.version = (navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1]; // jQuery.ajax() is now strict about JSON input (mus...
{ this.value = val; }
conditional_block
jquery.compat-1.3.js
/* * Compatibility Plugin for jQuery 1.3 (on top of jQuery 1.4) * All code copied from jQuery 1.4 * By John Resig * Dual licensed under MIT and GPL. */ (function(jQuery) { // .add() is no longer equivalent to .concat() // Results are now returned in document order jQuery.fn.add = function( selector, context )...
(orig, ret) { var i = 0; ret.each(function() { if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) { return; } var oldData = jQuery.data( orig[i++] ), events = oldData && oldData.events; if ( events ) { for ( var type in events ) { for ( var handler in events[ type ] ) { jQuery....
cloneCopyEvent
identifier_name
jquery.compat-1.3.js
/* * Compatibility Plugin for jQuery 1.3 (on top of jQuery 1.4) * All code copied from jQuery 1.4 * By John Resig * Dual licensed under MIT and GPL. */ (function(jQuery) { // .add() is no longer equivalent to .concat() // Results are now returned in document order jQuery.fn.add = function( selector, context )...
// jQuery.data(elem) no longer returns an ID, // returns the data object instead. jQuery.data = function( elem, name, data ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { return; } elem = elem == window ? windowData : elem; var id = elem[ jQuery.expando ], cache = jQuer...
{ var i = 0; ret.each(function() { if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) { return; } var oldData = jQuery.data( orig[i++] ), events = oldData && oldData.events; if ( events ) { for ( var type in events ) { for ( var handler in events[ type ] ) { jQuery.event.add( t...
identifier_body
lib.rs
#[derive(Debug, PartialEq)] pub struct Clock { hours: i16, minutes: i16, } impl Clock { pub fn new(hours: i16, minutes: i16) -> Self { Clock { hours, minutes }.normalize() } pub fn add_minutes(mut self, n: i16) -> Self { self.minutes += n; self.normalize() } pub fn...
fn normalize(mut self) -> Self { self.hours += self.minutes / 60; self.minutes %= 60; self.hours %= 24; if self.minutes < 0 { self.hours -= 1; self.minutes += 60; } if self.hours < 0 { self.hours += 24; } self ...
{ format!("{:02}:{:02}", self.hours, self.minutes) }
identifier_body
lib.rs
#[derive(Debug, PartialEq)] pub struct Clock { hours: i16, minutes: i16, } impl Clock { pub fn new(hours: i16, minutes: i16) -> Self { Clock { hours, minutes }.normalize() } pub fn add_minutes(mut self, n: i16) -> Self { self.minutes += n; self.normalize() } pub fn...
self } }
{ self.hours += 24; }
conditional_block
lib.rs
#[derive(Debug, PartialEq)] pub struct Clock { hours: i16, minutes: i16, } impl Clock { pub fn new(hours: i16, minutes: i16) -> Self { Clock { hours, minutes }.normalize() } pub fn add_minutes(mut self, n: i16) -> Self { self.minutes += n; self.normalize() } pub fn...
(mut self) -> Self { self.hours += self.minutes / 60; self.minutes %= 60; self.hours %= 24; if self.minutes < 0 { self.hours -= 1; self.minutes += 60; } if self.hours < 0 { self.hours += 24; } self } }
normalize
identifier_name
lib.rs
#[derive(Debug, PartialEq)] pub struct Clock {
minutes: i16, } impl Clock { pub fn new(hours: i16, minutes: i16) -> Self { Clock { hours, minutes }.normalize() } pub fn add_minutes(mut self, n: i16) -> Self { self.minutes += n; self.normalize() } pub fn to_string(&self) -> String { format!("{:02}:{:02}", se...
hours: i16,
random_line_split
TaskItem.tsx
/// <reference path="../../../webclient.d.ts"/> import * as React from 'react'; import {Task, TaskStatus, Executor, IExecutorEditState} from '../model'; import ExecutorEditor from './ExecutorEditor'; interface ITaskItemProps extends React.Props<TaskItem> { task : Task; editState : {[executorId:...
</div> ) } }
{renderStatus(task.status)} <a style={{cursor: 'pointer', float: 'right', marginRight: '5px'}} onClick={this.toggle}>Executors</a> </div> {collapsed === false && <div>{renderExecutors(executorsFn())}</div>}
random_line_split
TaskItem.tsx
/// <reference path="../../../webclient.d.ts"/> import * as React from 'react'; import {Task, TaskStatus, Executor, IExecutorEditState} from '../model'; import ExecutorEditor from './ExecutorEditor'; interface ITaskItemProps extends React.Props<TaskItem> { task : Task; editState : {[executorId:...
this.setState({collapsed}); }; onSaveExecutor = (id: number, name: string) => { const {task} = this.props; this.props.onSaveExecutor(task.id, id, name); }; onCancelExecutor = (id: number) => { const {task} = this.props; this.props.onCancelExecutor(task.id, id); }; onEditExecutor = (i...
{ this.props.onExpand(this.props.task.id); }
conditional_block
full_inspiration.py
#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SYSTRAN Software, Inc. All rights reserved. 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/licen...
def __repr__(self): properties = [] for p in self.__dict__: if p != 'systran_types' and p != 'attribute_map': properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) return '<{name} {props}>'.format(name=__name__, props=' '.join(proper...
""" Systran model :param dict systran_types: The key is attribute name and the value is attribute type. :param dict attribute_map: The key is attribute name and the value is json key in definition. """ self.systran_types = { 'id': 'str', 'location': 'Full...
identifier_body
full_inspiration.py
#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SYSTRAN Software, Inc. All rights reserved. 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/licen...
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
conditional_block
full_inspiration.py
#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SYSTRAN Software, Inc. All rights reserved. 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/licen...
(object): """ NOTE: This class is auto generated by the systran code generator program. Do not edit the class manually. """ def __init__(self): """ Systran model :param dict systran_types: The key is attribute name and the value is attribute type. :param dict attrib...
FullInspiration
identifier_name
full_inspiration.py
#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SYSTRAN Software, Inc. All rights reserved. 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/licen...
class FullInspiration(object): """ NOTE: This class is auto generated by the systran code generator program. Do not edit the class manually. """ def __init__(self): """ Systran model :param dict systran_types: The key is attribute name and the value is attribute type. ...
random_line_split
step6_file.rs
use std::rc::Rc; //use std::collections::HashMap; use fnv::FnvHashMap; use itertools::Itertools; #[macro_use] extern crate lazy_static; extern crate regex; extern crate itertools; extern crate fnv; extern crate rustyline; use rustyline::error::ReadlineError; use rustyline::Editor; #[macro_use] mod types; use types::...
fn rep(str: &str, env: &Env) -> Result<String,MalErr> { let ast = read(str)?; let exp = eval(ast, env.clone())?; Ok(print(&exp)) } fn main() { let mut args = std::env::args(); let arg1 = args.nth(1); // `()` can be used when no completer is required let mut rl = Editor::<()>::new(); if rl.load_histo...
{ ast.pr_str(true) }
identifier_body
step6_file.rs
use std::rc::Rc; //use std::collections::HashMap; use fnv::FnvHashMap; use itertools::Itertools; #[macro_use] extern crate lazy_static; extern crate regex; extern crate itertools; extern crate fnv; extern crate rustyline; use rustyline::error::ReadlineError; use rustyline::Editor; #[macro_use] mod types; use types::...
, _ => Ok(Nil) } }, Sym(ref a0sym) if a0sym == "fn*" => { let (a1, a2) = (l[1].clone(), l[2].clone()); Ok(MalFunc{eval: eval, ast: Rc::new(a2), env: env, params: Rc::new(a1), is_macro: false, meta: Rc::new(Nil)}) ...
{ ast = l[2].clone(); continue 'tco; }
conditional_block
step6_file.rs
use std::rc::Rc; //use std::collections::HashMap; use fnv::FnvHashMap; use itertools::Itertools; #[macro_use] extern crate lazy_static; extern crate regex; extern crate itertools; extern crate fnv; extern crate rustyline; use rustyline::error::ReadlineError; use rustyline::Editor; #[macro_use] mod types; use types::...
} } } }, _ => eval_ast(&ast, &env), }; break; } // end 'tco loop ret } // print fn print(ast: &MalVal) -> String { ast.pr_str(true) } fn rep(str: &str, env: &Env) -> Result<String,MalErr> { let ast = read(str)?; let exp = eval(ast, env.clone())?; Ok(print(&exp)) } f...
} }, _ => { error("expected a list") }
random_line_split
step6_file.rs
use std::rc::Rc; //use std::collections::HashMap; use fnv::FnvHashMap; use itertools::Itertools; #[macro_use] extern crate lazy_static; extern crate regex; extern crate itertools; extern crate fnv; extern crate rustyline; use rustyline::error::ReadlineError; use rustyline::Editor; #[macro_use] mod types; use types::...
(str: &str, env: &Env) -> Result<String,MalErr> { let ast = read(str)?; let exp = eval(ast, env.clone())?; Ok(print(&exp)) } fn main() { let mut args = std::env::args(); let arg1 = args.nth(1); // `()` can be used when no completer is required let mut rl = Editor::<()>::new(); if rl.load_history(".mal...
rep
identifier_name
mod.rs
//! Provides functions for maintaining database schema. //! //! A database migration always provides procedures to update the schema, as well as to revert //! itself. Diesel's migrations are versioned, and run in order. Diesel also takes care of tracking //! which migrations have already been run automatically. Your mi...
//! ## Example //! //! ```text //! # Directory Structure //! - 20151219180527_create_users //! - up.sql //! - down.sql //! - 20160107082941_create_posts //! - up.sql //! - down.sql //! ``` //! //! ```sql //! -- 20151219180527_create_users/up.sql //! CREATE TABLE users ( //! id SERIAL PRIMARY KEY, //! ...
//! Individual migrations should be a folder containing exactly two files, `up.sql` and `down.sql`. //! `up.sql` will be used to run the migration, while `down.sql` will be used for reverting it. The //! folder itself should have the structure `{version}_{migration_name}`. It is recommended that //! you use the timesta...
random_line_split
mod.rs
//! Provides functions for maintaining database schema. //! //! A database migration always provides procedures to update the schema, as well as to revert //! itself. Diesel's migrations are versioned, and run in order. Diesel also takes care of tracking //! which migrations have already been run automatically. Your mi...
() { let dir = TempDir::new("diesel").unwrap(); let temp_path = dir.path().canonicalize().unwrap(); let migrations_path = temp_path.join("migrations"); let child_path = temp_path.join("child"); fs::create_dir(&child_path).unwrap(); fs::create_dir(&migrations_path).unwrap...
migration_directory_checks_parents
identifier_name
mod.rs
//! Provides functions for maintaining database schema. //! //! A database migration always provides procedures to update the schema, as well as to revert //! itself. Diesel's migrations are versioned, and run in order. Diesel also takes care of tracking //! which migrations have already been run automatically. Your mi...
#[doc(hidden)] pub fn revert_migration_with_version(conn: &Connection, ver: &str) -> Result<(), RunMigrationsError> { migration_with_version(ver) .map_err(|e| e.into()) .and_then(|m| revert_migration(conn, m)) } #[doc(hidden)] pub fn run_migration_with_version(conn: &Connection, ver: &str) -> Res...
{ try!(create_schema_migrations_table_if_needed(conn)); let latest_migration_version = try!(latest_run_migration_version(conn)); revert_migration_with_version(conn, &latest_migration_version) .map(|_| latest_migration_version) }
identifier_body
makeseeds.py
#!/usr/bin/env python3 # Copyright (c) 2013-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Generate seeds.txt from Pieter's DNS seeder # import re import sys import dns.resolver import collect...
ips = filterbyasn(ips, MAX_SEEDS_PER_ASN, NSEEDS) print('%s Look up ASNs and limit results per ASN and per net' % (ip_stats(ips)), file=sys.stderr) # Sort the results by IP address (for deterministic output). ips.sort(key=lambda x: (x['net'], x['sortkey'])) for ip in ips: if ip['net'] == 'ip...
# Filter out hosts with multiple bitcoin ports, these are likely abusive ips = filtermultiport(ips) print('%s Filter out hosts with multiple bitcoin ports' % (ip_stats(ips)), file=sys.stderr) # Look up ASNs and limit results, both per ASN and globally.
random_line_split
makeseeds.py
#!/usr/bin/env python3 # Copyright (c) 2013-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Generate seeds.txt from Pieter's DNS seeder # import re import sys import dns.resolver import collect...
return '%6d %6d %6d' % (hist['ipv4'], hist['ipv6'], hist['onion']) def main(): lines = sys.stdin.readlines() ips = [parseline(line) for line in lines] print('\x1b[7m IPv4 IPv6 Onion Pass \x1b[0m', file=sys.stderr) print('%s Initial' % (ip_stats(i...
hist[ip['net']] += 1
conditional_block
makeseeds.py
#!/usr/bin/env python3 # Copyright (c) 2013-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Generate seeds.txt from Pieter's DNS seeder # import re import sys import dns.resolver import collect...
(net, ip): ''' Look up the asn for an IP (4 or 6) address by querying cymru.com, or None if it could not be found. ''' try: if net == 'ipv4': ipaddr = ip prefix = '.origin' else: # http://www.team-cymru.com/IP-ASN-mapping.html res ...
lookup_asn
identifier_name
makeseeds.py
#!/usr/bin/env python3 # Copyright (c) 2013-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Generate seeds.txt from Pieter's DNS seeder # import re import sys import dns.resolver import collect...
def filtermultiport(ips): '''Filter out hosts with more nodes per IP''' hist = collections.defaultdict(list) for ip in ips: hist[ip['sortkey']].append(ip) return [value[0] for (key,value) in list(hist.items()) if len(value)==1] def lookup_asn(net, ip): ''' Look up the asn for an IP (4...
'''deduplicate by address,port''' d = {} for ip in ips: d[ip['ip'],ip['port']] = ip return list(d.values())
identifier_body
base.py
try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] ...
(self, *children): self.add_children(children) return self def __repr__(self): attr_string = ''.join(' {}="{}"'.format(key, val) for key, val in self.attrs.items() if val) return '<{}{}>'.format(self.tag, attr_string) def add_children(self, children): if self.self_closi...
__call__
identifier_name
base.py
try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] ...
def __repr__(self): attr_string = ''.join(' {}="{}"'.format(key, val) for key, val in self.attrs.items() if val) return '<{}{}>'.format(self.tag, attr_string) def add_children(self, children): if self.self_closing and children: raise ValueError("Self-closing tags can't hav...
self.add_children(children) return self
identifier_body
base.py
try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] ...
# Some helpers for the `class` attribute if 'classes' in attrs: attrs['class'] = ' '.join(c for c in attrs.pop('classes') if c) elif 'class_' in attrs: attrs['class'] = attrs.pop('class_') self.children = [] self.add_children(children) def __call__...
self.attrs = attrs
conditional_block
base.py
try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] ...
else: self.children.append(child)
for child in children: if child is not None: if isinstance(child, list): self.add_children(child)
random_line_split