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
user.js
'use strict'; const User = require('../../models/admin/user'), Role = require('../../models/admin/role'), page = require('../../util/page'), _ = require('lodash'); module.exports = class UserController { /** * Display a list of users. */ static index(req, res) { page(User, req).then(data => { res.rende...
/** * Save a user. */ static save(req, res) { let data = _.pick(req.body, _.concat(User.keys, 'password')); User.save(data, req.params.id).then( result => { req.flash('success', 'Saved successfully!'); res.redirect('/admin/users'); }, err =>{ _.pull(data, 'password'); req.flash('err...
{ let id = req.params.id, view = 'admin/user/form', roles = {'admin': 'Admin'}; Role.where({}).then(cursor => { cursor.project({'name': 1}).forEach(role => { roles[role._id] = role.name; }, err => { if (id) { User.find(id).then(user => { res.render(view, {doc: user.data, roles}); ...
identifier_body
filters.py
# -*- coding: utf-8; -*- import sys import os.path import fnmatch from ano.utils import FileMap, SpaceList class GlobFile(object): def __init__(self, filename, dirname): self.filename = filename self.dirname = dirname @property def path(self): return os.path.join(self.dirname, s...
@filter def colorize(s, color): if not sys.stdout.isatty(): return s ccodes = { 'cyan': '96', 'purple': '95', 'blue': '94', 'green': '92', 'yellow': '93', 'red': '91', } return ''.join([ '\033[', ccodes[color], 'm',...
return FileMap(( source_dir, GlobFile(libname(basename(source_dir)), pjoin(target_dir, basename(source_dir)))) for source_dir in source_dirs)
identifier_body
filters.py
# -*- coding: utf-8; -*- import sys import os.path import fnmatch from ano.utils import FileMap, SpaceList class GlobFile(object): def __init__(self, filename, dirname): self.filename = filename self.dirname = dirname @property def path(self): return os.path.join(self.dirname, s...
(self): return '<%s + %s>' % (self.dirname, self.filename) def __str__(self): return self.filename def filter(f): f.filter = True return f @filter def glob(dirname, *patterns, **kwargs): recursive = kwargs.get('recursive', True) subdir = kwargs.get('subdir', '') result = Sp...
__repr__
identifier_name
filters.py
# -*- coding: utf-8; -*- import sys import os.path import fnmatch from ano.utils import FileMap, SpaceList class GlobFile(object): def __init__(self, filename, dirname): self.filename = filename self.dirname = dirname @property def path(self): return os.path.join(self.dirname, s...
return result @filter def pjoin(base, *parts): return os.path.join(str(base), *map(str, parts)) def oxname(filepath, basename_fmt): head, basename = os.path.split(str(filepath)) return os.path.join(head, basename_fmt % basename) def xname(filepath, basename_fmt): head, tail = os.path.split(st...
result.append(GlobFile(os.path.join(subdir, entry), dirname))
conditional_block
filters.py
# -*- coding: utf-8; -*- import sys import os.path
from ano.utils import FileMap, SpaceList class GlobFile(object): def __init__(self, filename, dirname): self.filename = filename self.dirname = dirname @property def path(self): return os.path.join(self.dirname, self.filename) def __repr__(self): return '<%s + %s>' % ...
import fnmatch
random_line_split
0001_0_8_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
], ), migrations.AlterUniqueTogether( name='label', unique_together=set([('content_type', 'object_id', 'key')]), ), ]
initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ] replaces = [ ('core', '0001_initial'), ('core', '0002_v0_7_migrations'), ] operations = [ migrations.CreateModel( name='Label', fields=[ ('i...
identifier_body
0001_0_8_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ] replaces = [ ('core', '0001_initial'), ('core...
unique_together=set([('content_type', 'object_id', 'key')]), ), ]
migrations.AlterUniqueTogether( name='label',
random_line_split
0001_0_8_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class
(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ] replaces = [ ('core', '0001_initial'), ('core', '0002_v0_7_migrations'), ] operations = [ migrations.CreateModel( name='Label', ...
Migration
identifier_name
directconnect.rs
#![cfg(feature = "directconnect")] extern crate rusoto; use rusoto::directconnect::{DirectConnectClient, DescribeConnectionsRequest, DescribeConnectionsError}; use rusoto::{DefaultCredentialsProvider, Region}; use rusoto::default_tls_client; #[test] fn should_describe_connections() { let credentials = DefaultCre...
#[test] fn should_describe_locations() { let credentials = DefaultCredentialsProvider::new().unwrap(); let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1); client.describe_locations().unwrap(); } #[test] fn should_describe_virtual_gateways() { let crede...
{ let credentials = DefaultCredentialsProvider::new().unwrap(); let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1); let request = DescribeConnectionsRequest { connection_id: Some("invalid".to_string()) }; match client.describe_connections(&re...
identifier_body
directconnect.rs
#![cfg(feature = "directconnect")] extern crate rusoto; use rusoto::directconnect::{DirectConnectClient, DescribeConnectionsRequest, DescribeConnectionsError}; use rusoto::{DefaultCredentialsProvider, Region}; use rusoto::default_tls_client; #[test] fn should_describe_connections() { let credentials = DefaultCre...
() { let credentials = DefaultCredentialsProvider::new().unwrap(); let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1); client.describe_virtual_gateways().unwrap(); }
should_describe_virtual_gateways
identifier_name
directconnect.rs
#![cfg(feature = "directconnect")] extern crate rusoto; use rusoto::directconnect::{DirectConnectClient, DescribeConnectionsRequest, DescribeConnectionsError}; use rusoto::{DefaultCredentialsProvider, Region}; use rusoto::default_tls_client; #[test] fn should_describe_connections() { let credentials = DefaultCre...
let credentials = DefaultCredentialsProvider::new().unwrap(); let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1); let request = DescribeConnectionsRequest { connection_id: Some("invalid".to_string()) }; match client.describe_connections(&requ...
#[test] fn should_fail_gracefully() {
random_line_split
get-export-documents.ts
import { Document, Relations, Name, ObjectUtils, ON_RESOURCE_ID, ResourceId, RESOURCE_DOT_IDENTIFIER, toResourceId } from 'idai-field-core'; import { Either, subtract, to } from 'tsfun'; import { ImageRelationsManager } from '../../model/image-relations-manager'; import { RelationsManager } from '../../model/relations-...
{ delete document['_attachments']; delete document[Document._REV]; delete document['_id']; delete document[Document.CREATED]; delete document[Document.MODIFIED]; delete document.resource.relations[Relations.Type.HASINSTANCE]; delete document.resource.relations[Relations.Hierarchy.RECORDEDIN...
identifier_body
get-export-documents.ts
import { Document, Relations, Name, ObjectUtils, ON_RESOURCE_ID, ResourceId, RESOURCE_DOT_IDENTIFIER, toResourceId } from 'idai-field-core'; import { Either, subtract, to } from 'tsfun'; import { ImageRelationsManager } from '../../model/image-relations-manager'; import { RelationsManager } from '../../model/relations-...
imageRelationsManager: ImageRelationsManager, catalogId: ResourceId, project: Name) : Promise<Either<string[] /* msgWithParams */, [Array<Document>, Array<ResourceId>]>> { const catalogAnd...
export async function getExportDocuments(relationsManager: RelationsManager,
random_line_split
get-export-documents.ts
import { Document, Relations, Name, ObjectUtils, ON_RESOURCE_ID, ResourceId, RESOURCE_DOT_IDENTIFIER, toResourceId } from 'idai-field-core'; import { Either, subtract, to } from 'tsfun'; import { ImageRelationsManager } from '../../model/image-relations-manager'; import { RelationsManager } from '../../model/relations-...
const relatedImages = cleanImageDocuments(linkedImages); return [ undefined, [ catalogAndTypes .concat(relatedImages) .map(cleanDocument) .map(document => { document.project = project; return do...
{ const diff = subtract(ON_RESOURCE_ID, exclusivelyLinkedImages)(linkedImages); const diffImageIds = diff.map(to(RESOURCE_DOT_IDENTIFIER)); return [ [ERROR_NOT_ALL_IMAGES_EXCLUSIVELY_LINKED, diffImageIds.join(',')], undefined ]; }
conditional_block
get-export-documents.ts
import { Document, Relations, Name, ObjectUtils, ON_RESOURCE_ID, ResourceId, RESOURCE_DOT_IDENTIFIER, toResourceId } from 'idai-field-core'; import { Either, subtract, to } from 'tsfun'; import { ImageRelationsManager } from '../../model/image-relations-manager'; import { RelationsManager } from '../../model/relations-...
(images: Array<Document>) { const relatedImageDocuments = []; for (let image of images) { image.resource.relations = { depicts: image.resource.relations[Relations.Image.DEPICTS] // we know it depicts only catalog exclusive resources } as any; relatedImageDocuments.push(image...
cleanImageDocuments
identifier_name
tagstore.py
#!/usr/bin/env python import re, logging, copy from threading import Lock class Tagger(object): def __init__(self, hosts_attr="fields.hosts", hosts_sep=":", tag_file="tags_jobs.safe"): self.tags_by_host = {} self.hosts_sep = str(hosts_sep) self.hosts_attr = str(hosts_attr) self.ta...
hostlist = re.split(self.hosts_sep, hosts.strip("'").strip("\"")) tags = measurement.get_all_tags() if self.hosts_attr in tags: del tags[self.hosts_attr] self.lock.acquire() for h in hostlist: if h in self.tags_by_host: logging.in...
logging.error("Measurement does not have the attribute with host list %s" % self.hosts_attr) return False
conditional_block
tagstore.py
#!/usr/bin/env python import re, logging, copy from threading import Lock class Tagger(object): def __init__(self, hosts_attr="fields.hosts", hosts_sep=":", tag_file="tags_jobs.safe"): self.tags_by_host = {} self.hosts_sep = str(hosts_sep) self.hosts_attr = str(hosts_attr) self.ta...
(self, measurement): hosts = measurement.get_attr(self.hosts_attr) if not hosts: logging.error("Measurement does not have the attribute with host list %s" % self.hosts_attr) return False hostlist = re.split(self.hosts_sep, hosts.strip("'").strip("\"")) self.lock....
delete
identifier_name
tagstore.py
#!/usr/bin/env python import re, logging, copy from threading import Lock class Tagger(object): def __init__(self, hosts_attr="fields.hosts", hosts_sep=":", tag_file="tags_jobs.safe"): self.tags_by_host = {} self.hosts_sep = str(hosts_sep) self.hosts_attr = str(hosts_attr) self.ta...
def store(self): f = open(self.tag_file, "w") f.write(json.dumps(self.tags_by_host, sort_keys=True, indent=4, separators=(',', ': '))) f.close() def restore(self): f = open(self.tag_file, "r") self.lock.acquire() self.tags_by_host = json.loads(f.read()) se...
def host_active(self, host): return host in self.tags_by_host
random_line_split
tagstore.py
#!/usr/bin/env python import re, logging, copy from threading import Lock class Tagger(object): def __init__(self, hosts_attr="fields.hosts", hosts_sep=":", tag_file="tags_jobs.safe"): self.tags_by_host = {} self.hosts_sep = str(hosts_sep) self.hosts_attr = str(hosts_attr) self.ta...
def get_all_tags(self): return self.tags_by_host def get_all_active_hosts(self): return sorted(self.tags_by_host.keys()) def host_active(self, host): return host in self.tags_by_host def store(self): f = open(self.tag_file, "w") f.write(json.dumps(self.tags_by_ho...
if host not in self.tags_by_host: return {} return copy.deepcopy(self.tags_by_host[host])
identifier_body
authorization_interceptor.js
/** * @license Copyright (c) 2012, Viet Trinh All Rights Reserved. * Available via MIT license. */ /** * An authorizeation interceptor used to determine if the user can access the given resource. */ define([ 'framework/controller/interceptor/i_interceptor', 'framework/core/utils/clazz', 'framework/core/def...
// Assumes this function doesn't fail. return Deferred.resolvedPromise(requestContext); }; // @override AuthorizationInterceptor.prototype.after = function(requestContext) { return Deferred.resolvedPromise(requestContext); }; return AuthorizationInterceptor; });
{ requestContext.setStatusCode(403); requestContext.setErrorMessage('Unauthorized Access! You are not allowed to access the given resource.'); return Deferred.rejectedPromise(requestContext); }
conditional_block
authorization_interceptor.js
/**
*/ /** * An authorizeation interceptor used to determine if the user can access the given resource. */ define([ 'framework/controller/interceptor/i_interceptor', 'framework/core/utils/clazz', 'framework/core/deferred/deferred' ], function(IInterceptor, ClazzUtils, Deferred) { var AuthorizationInterc...
* @license Copyright (c) 2012, Viet Trinh All Rights Reserved. * Available via MIT license.
random_line_split
logger.ts
import { Common } from './common'; export class Logger { private static levels: { [key: string]: number; } = { trace: 0, info: 1, warn: 2, error: 3 }; public name: string; private level: number | boolean; public constructor(name: string, level: string); public constructor(name: stri...
}
{ return Common.find(Logger.levels, (_level, key) => key === name); }
identifier_body
logger.ts
import { Common } from './common'; export class Logger { private static levels: { [key: string]: number; } = { trace: 0, info: 1, warn: 2, error: 3 }; public name: string; private level: number | boolean; public constructor(name: string, level: string); public constructor(name: stri...
(level: string): boolean { if (this.level === false) return false; return this.level === true || this.level <= this.toLevel(level); } public toLevel(name: string): number { return Common.find(Logger.levels, (_level, key) => key === name); } }
enabled
identifier_name
logger.ts
import { Common } from './common'; export class Logger { private static levels: { [key: string]: number; } = { trace: 0, info: 1, warn: 2, error: 3 }; public name: string; private level: number | boolean; public constructor(name: string, level: string); public constructor(name: stri...
if (this.enabled(level)) { console.log(`${level}: ${message}`, ...optionalParams); } } public enabled(level: string): boolean { if (this.level === false) return false; return this.level === true || this.level <= this.toLevel(level); } public toLevel(name: string): number { return Co...
private log(level: string, message: string, ...optionalParams: any[]) {
random_line_split
logger.ts
import { Common } from './common'; export class Logger { private static levels: { [key: string]: number; } = { trace: 0, info: 1, warn: 2, error: 3 }; public name: string; private level: number | boolean; public constructor(name: string, level: string); public constructor(name: stri...
} public enabled(level: string): boolean { if (this.level === false) return false; return this.level === true || this.level <= this.toLevel(level); } public toLevel(name: string): number { return Common.find(Logger.levels, (_level, key) => key === name); } }
{ console.log(`${level}: ${message}`, ...optionalParams); }
conditional_block
thread.rs
use crate::ffi::CStr; use crate::io; use crate::num::NonZeroUsize; use crate::os::windows::io::{AsRawHandle, FromRawHandle}; use crate::ptr; use crate::sys::c; use crate::sys::handle::Handle; use crate::sys::stack_overflow; use crate::time::Duration; use libc::c_void; use super::to_u16s; pub const DEFAULT_MIN_STACK_...
(main: *mut c_void) -> c::DWORD { unsafe { // Next, set up our stack overflow handler which may get triggered if we run // out of stack. let _handler = stack_overflow::Handler::new(); // Finally, let's run some code. Box::from_r...
thread_start
identifier_name
thread.rs
use crate::ffi::CStr; use crate::io; use crate::num::NonZeroUsize; use crate::os::windows::io::{AsRawHandle, FromRawHandle}; use crate::ptr; use crate::sys::c; use crate::sys::handle::Handle; use crate::sys::stack_overflow; use crate::time::Duration; use libc::c_void; use super::to_u16s; pub const DEFAULT_MIN_STACK_...
} } pub fn yield_now() { // This function will return 0 if there are no other threads to execute, // but this also means that the yield was useless so this isn't really a // case that needs to be worried about. unsafe { c::SwitchToThread(); } } ...
let rc = unsafe { c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE) }; if rc == c::WAIT_FAILED { panic!("failed to join on thread: {}", io::Error::last_os_error());
random_line_split
thread.rs
use crate::ffi::CStr; use crate::io; use crate::num::NonZeroUsize; use crate::os::windows::io::{AsRawHandle, FromRawHandle}; use crate::ptr; use crate::sys::c; use crate::sys::handle::Handle; use crate::sys::stack_overflow; use crate::time::Duration; use libc::c_void; use super::to_u16s; pub const DEFAULT_MIN_STACK_...
} pub fn yield_now() { // This function will return 0 if there are no other threads to execute, // but this also means that the yield was useless so this isn't really a // case that needs to be worried about. unsafe { c::SwitchToThread(); } } pub fn...
{ panic!("failed to join on thread: {}", io::Error::last_os_error()); }
conditional_block
thread.rs
use crate::ffi::CStr; use crate::io; use crate::num::NonZeroUsize; use crate::os::windows::io::{AsRawHandle, FromRawHandle}; use crate::ptr; use crate::sys::c; use crate::sys::handle::Handle; use crate::sys::stack_overflow; use crate::time::Duration; use libc::c_void; use super::to_u16s; pub const DEFAULT_MIN_STACK_...
pub fn sleep(dur: Duration) { unsafe { c::Sleep(super::dur2timeout(dur)) } } pub fn handle(&self) -> &Handle { &self.handle } pub fn into_handle(self) -> Handle { self.handle } } pub fn available_parallelism() -> io::Result<NonZeroUsize> { let res = unsafe { ...
{ // This function will return 0 if there are no other threads to execute, // but this also means that the yield was useless so this isn't really a // case that needs to be worried about. unsafe { c::SwitchToThread(); } }
identifier_body
htmlobjectelement.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 http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLObjectElementB...
(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLObjectElement> { let element = HTMLObjectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLObjectElementBinding::Wrap) } } trait ProcessDataUR...
new
identifier_name
htmlobjectelement.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 http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLObjectElementB...
} trait ProcessDataURL { fn process_data_url(&self); } impl<'a> ProcessDataURL for &'a HTMLObjectElement { // Makes the local `data` member match the status of the `data` attribute and starts /// prefetching the image. This method must be called after `data` is changed. fn process_data_url(&self) { ...
{ let element = HTMLObjectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLObjectElementBinding::Wrap) }
identifier_body
htmlobjectelement.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 http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLObjectElementB...
, _ => {}, } } } impl FormControl for HTMLObjectElement {}
{ if let AttributeMutation::Set(_) = mutation { self.process_data_url(); } }
conditional_block
all_1.js
fdevice_5fmem_5fmanager_2eh',['barelog_device_mem_manager.h',['../barelog__device__mem__manager_8h.html',1,'']]], ['barelog_5fdevice_5fmem_5fmanager_5ft',['barelog_device_mem_manager_t',['../structbarelog__device__mem__manager__t.html',1,'']]], ['barelog_5ferr',['BARELOG_ERR',['../barelog__internal_8h.html#ae86020d...
['barelog_5fevent_5fper_5fcore_5fshr_5fmem_5fmax',['BARELOG_EVENT_PER_CORE_SHR_MEM_MAX',['../barelog__internal_8h.html#a75ca1f6b4314062cd744575f81c95d14',1,'barelog_internal.h']]], ['barelog_5fevent_5fshared_5fmem_5fmax',['BARELOG_EVENT_SHARED_MEM_MAX',['../barelog__config_8h.html#a3678960a8851bdd48135dff9c5213e7a'...
['barelog_5fevent_5finitializer',['BARELOG_EVENT_INITIALIZER',['../barelog__event_8h.html#a2da2edea64e53dd86c4d7480987b260c',1,'barelog_event.c']]], ['barelog_5fevent_5fmax_5fsize',['BARELOG_EVENT_MAX_SIZE',['../barelog__config_8h.html#adbd7a03a709aa4ad63455907ff05b98a',1,'barelog_config.h']]], ['barelog_5fevent_...
random_line_split
foos-game-stats.js
var foosUtilLib = require('/lib/foos-util'); var foosRetrievalLib = require('/lib/foos-retrieval');
game.gen = game.gen || {}; game.gen.score = { winners: 0, losers: 0 }; var winnerResults = foosUtilLib.toArray(game.data.winners); winnerResults.forEach(function (playerResult) { game.gen.score.winners += playerResult.score; if (playerResult.against) { ga...
var foosUrlLib = require('/lib/foos-url'); exports.generateGameBasicStats = function (game) {
random_line_split
foos-game-stats.js
var foosUtilLib = require('/lib/foos-util'); var foosRetrievalLib = require('/lib/foos-retrieval'); var foosUrlLib = require('/lib/foos-url'); exports.generateGameBasicStats = function (game) { game.gen = game.gen || {}; game.gen.score = { winners: 0, losers: 0 }; var winnerResults = f...
foosUtilLib.toArray(game.data.winners).forEach(doGenerateGameStats); foosUtilLib.toArray(game.data.losers).forEach(doGenerateGameStats); }; exports.generateGameComments = function (game) { game.gen = game.gen || {}; game.gen.comments = foosRetrievalLib.getChildrenByParentKey(game._id); game.gen...
{ var playerContent = foosRetrievalLib.getContentByKey(playerResult.playerId); playerResult.gen = {}; playerResult.gen.name = playerContent.displayName; foosUrlLib.generatePictureUrl(playerContent); foosUrlLib.generatePageUrl(playerContent); playerResult.gen.pictureUrl =...
identifier_body
foos-game-stats.js
var foosUtilLib = require('/lib/foos-util'); var foosRetrievalLib = require('/lib/foos-retrieval'); var foosUrlLib = require('/lib/foos-url'); exports.generateGameBasicStats = function (game) { game.gen = game.gen || {}; game.gen.score = { winners: 0, losers: 0 }; var winnerResults = f...
}); }; exports.generateGameStats = function (game) { exports.generateGameBasicStats(game); function doGenerateGameStats(playerResult) { var playerContent = foosRetrievalLib.getContentByKey(playerResult.playerId); playerResult.gen = {}; playerResult.gen.name = playerContent.displa...
{ game.gen.score.winners += playerResult.against; }
conditional_block
foos-game-stats.js
var foosUtilLib = require('/lib/foos-util'); var foosRetrievalLib = require('/lib/foos-retrieval'); var foosUrlLib = require('/lib/foos-url'); exports.generateGameBasicStats = function (game) { game.gen = game.gen || {}; game.gen.score = { winners: 0, losers: 0 }; var winnerResults = f...
(playerResult) { var playerContent = foosRetrievalLib.getContentByKey(playerResult.playerId); playerResult.gen = {}; playerResult.gen.name = playerContent.displayName; foosUrlLib.generatePictureUrl(playerContent); foosUrlLib.generatePageUrl(playerContent); playerResult.g...
doGenerateGameStats
identifier_name
piv_inner.py
as plt import hotwire as hw ### PIV INNER PLOTS AND ANALYSIS ######## ######################################### def
(date, num_tests, utau, legend1): ################################################ # PURPOSE # 1. Inner Normalize # 2. PLOT # uplus vs yplus # urmsplus vs yplus # uvprimeplus vs yplus ################################################## ##note- vel and axis are flipped to properlly calc d...
piv_inner
identifier_name
piv_inner.py
as plt import hotwire as hw ### PIV INNER PLOTS AND ANALYSIS ######## ######################################### def piv_inner(date, num_tests, utau, legend1): ################################################ # PURPOSE # 1. Inner Normalize # 2. PLOT # uplus vs yplus # urmsplus vs yplus # ...
uvprime[j] = np.array(pd.read_hdf(name, 'uvprime_profile_avg'))[:-3] x[j] = np.array(pd.read_hdf(name, 'xaxis'))[:-3] y[j] = np.array(pd.read_hdf(name, 'yaxis'))[:-3] #conf[j] = pd.read_hdf(name, 'confidence')[:-3] #air_prop = hw.air_prop(23) ####Vincenti data### name = '../outside_data/FPF_Vincenti_Data.h5'...
umean = dict() vmean = dict() urms = dict() vrms = dict() uvprime = dict() x = dict() y = dict() conf = dict() uplus = dict() yplus = dict() urmsplus = dict() vrmsplus = dict() uvprimeplus = dict() #read in variables for j in range(0, num_tests): name = 'data/PIV_' + date + '_' +str(j) +'.h5' umean[j]...
identifier_body
piv_inner.py
as plt import hotwire as hw ### PIV INNER PLOTS AND ANALYSIS ######## ######################################### def piv_inner(date, num_tests, utau, legend1): ################################################ # PURPOSE # 1. Inner Normalize # 2. PLOT # uplus vs yplus # urmsplus vs yplus # ...
#plt.fill_between(yplus, urmsplus[:,0], urmsplus[:,0] + np.array(conf['urmsplus']), color='r', alpha=.5) #plt.fill_between(yplus, urmsplus[:,0], urmsplus[:,0] - np.array(conf['urmsplus']), color='r', alpha=.5) plt.legend(legend2, loc=2, fontsize=10) plt.ylabel('$v_{rms}^+$', fontsize=20) plt.xlabel('$y^+$', fonts...
plt.semilogx(yplus[j], vrmsplus[j], marker_v[j])
conditional_block
piv_inner.py
.pyplot as plt import hotwire as hw ### PIV INNER PLOTS AND ANALYSIS ######## ######################################### def piv_inner(date, num_tests, utau, legend1): ################################################ # PURPOSE # 1. Inner Normalize # 2. PLOT # uplus vs yplus # urmsplus vs yplus ...
#plt.fill_between(yplus, urmsplus[:,0], urmsplus[:,0] - np.array(conf['urmsplus']), color='r', alpha=.5) plt.legend(legend2, loc=2, fontsize=10) plt.ylabel('$v_{rms}^+$', fontsize=20) plt.xlabel('$y^+$', fontsize=20) plt.grid(True) #plt.axis([.001, 30000, 0, 35]) plt.show() ##UVprimeplus Yplus legend2 = [r'$...
for j in range(0, num_tests): plt.semilogx(yplus[j], vrmsplus[j], marker_v[j]) #plt.fill_between(yplus, urmsplus[:,0], urmsplus[:,0] + np.array(conf['urmsplus']), color='r', alpha=.5)
random_line_split
simple.rs
use std::env; use std::io; use std::io::{Error, Write}; use std::path::Path; use std::sync::Arc; use log::error; use petgraph::Graph; use tempdir::TempDir; use crate::clang::compiler::ClangCompiler; use crate::cluster::client::RemoteCompiler; use crate::compiler::*; use crate::config::Config; use crate::vs::compiler:...
pub fn simple_compile<C, F>(exec: &str, factory: F) -> i32 where C: Compiler, F: FnOnce(&Config) -> Result<C, Error>, { let config = match Config::new() { Ok(v) => v, Err(e) => { error!("FATAL ERROR: Can't load configuration {}", e); return 501; } }; ...
{ TempDir::new("octobuild").map(Arc::new) }
identifier_body
simple.rs
use std::env; use std::io; use std::io::{Error, Write}; use std::path::Path; use std::sync::Arc; use log::error; use petgraph::Graph; use tempdir::TempDir; use crate::clang::compiler::ClangCompiler; use crate::cluster::client::RemoteCompiler; use crate::compiler::*; use crate::config::Config; use crate::vs::compiler:...
<C>( config: &Config, state: &SharedState, exec: &str, compiler: C, ) -> Result<Option<i32>, Error> where C: Compiler, { let args: Vec<String> = env::args().collect(); let command_info = CommandInfo::simple(Path::new(exec)); let remote = RemoteCompiler::new(&config.coordinator, compiler)...
compile
identifier_name
simple.rs
use std::env; use std::io; use std::io::{Error, Write}; use std::path::Path; use std::sync::Arc; use log::error; use petgraph::Graph; use tempdir::TempDir; use crate::clang::compiler::ClangCompiler; use crate::cluster::client::RemoteCompiler; use crate::compiler::*; use crate::config::Config; use crate::vs::compiler:...
let args: Vec<String> = env::args().collect(); let command_info = CommandInfo::simple(Path::new(exec)); let remote = RemoteCompiler::new(&config.coordinator, compiler); let actions = BuildAction::create_tasks(&remote, command_info, &args[1..], exec); let mut build_graph: BuildGraph = Graph::new(); ...
C: Compiler, {
random_line_split
144_update_calendar_index.py
"""Update Calendar index. Revision ID: 1c73ca99c03b Revises: 1d7a72222b7c Create Date: 2015-02-26 00:50:52.322510 """ # revision identifiers, used by Alembic. revision = '1c73ca99c03b' down_revision = '1d7a72222b7c' from alembic import op def upgrade(): op.drop_constraint('calendar_ibfk_1', 'calendar', type_=...
op.drop_constraint('calendar_ibfk_1', 'calendar', type_='foreignkey') op.drop_constraint('uuid', 'calendar', type_='unique') op.create_index('uuid', 'calendar', ['namespace_id', 'provider_name', 'name'], unique=True) op.create_foreign_key('calendar_ibfk_1', 'cal...
identifier_body
144_update_calendar_index.py
"""Update Calendar index. Revision ID: 1c73ca99c03b Revises: 1d7a72222b7c Create Date: 2015-02-26 00:50:52.322510 """
# revision identifiers, used by Alembic. revision = '1c73ca99c03b' down_revision = '1d7a72222b7c' from alembic import op def upgrade(): op.drop_constraint('calendar_ibfk_1', 'calendar', type_='foreignkey') op.drop_constraint('uuid', 'calendar', type_='unique') op.create_index('uuid', 'calendar', ...
random_line_split
144_update_calendar_index.py
"""Update Calendar index. Revision ID: 1c73ca99c03b Revises: 1d7a72222b7c Create Date: 2015-02-26 00:50:52.322510 """ # revision identifiers, used by Alembic. revision = '1c73ca99c03b' down_revision = '1d7a72222b7c' from alembic import op def upgrade(): op.drop_constraint('calendar_ibfk_1', 'calendar', type_=...
(): op.drop_constraint('calendar_ibfk_1', 'calendar', type_='foreignkey') op.drop_constraint('uuid', 'calendar', type_='unique') op.create_index('uuid', 'calendar', ['namespace_id', 'provider_name', 'name'], unique=True) op.create_foreign_key('calendar_ibfk_1', ...
downgrade
identifier_name
commonjs.js
var client = require('braintree-web/client'); var validatedHostedFields = require('braintree-validation'); client.create({ authorization: 'sandbox_g42y39zw_348pk9cgf3bgyw2b' }, function (err, clientInstance) { if (err)
validatedHostedFields.create({ client: clientInstance, styles: { 'input': { 'font-size': '14px', 'font-family': 'helvetica, tahoma, calibri, sans-serif', 'color': '#3a3a3a' }, ':focus': { 'color': 'black' }, '.error': { 'color': 'red' }, '.valid': { 'color': 'green' ...
{ console.error(err); return; }
conditional_block
commonjs.js
var client = require('braintree-web/client'); var validatedHostedFields = require('braintree-validation'); client.create({ authorization: 'sandbox_g42y39zw_348pk9cgf3bgyw2b' }, function (err, clientInstance) { if (err) { console.error(err); return;
'input': { 'font-size': '14px', 'font-family': 'helvetica, tahoma, calibri, sans-serif', 'color': '#3a3a3a' }, ':focus': { 'color': 'black' }, '.error': { 'color': 'red' }, '.valid': { 'color': 'green' } }, fields: { number: { selector: '#card-number', plac...
} validatedHostedFields.create({ client: clientInstance, styles: {
random_line_split
nodemap.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::ops::Range; use std::path::Path; use anyhow::Result; use indexedlog::{ log::{self, IndexOutput, Log}, DefaultOpenOptions, }...
} let second = second.pop().unwrap(); Ok((Node::from_slice(&first)?, Node::from_slice(&second)?)) } Err(e) => Err(e.into()), } }); Ok(Box::new(iter)) } } #[cfg(test)] mod tests { use super:...
{ let iter = self.log.iter().map(move |entry| { match entry { Ok(data) => { let mut first = self.log.index_func(0, &data)?; if first.len() != 1 { return Err(NodeMapError(format!( "invalid inde...
identifier_body
nodemap.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::ops::Range; use std::path::Path; use anyhow::Result; use indexedlog::{ log::{self, IndexOutput, Log}, DefaultOpenOptions, }...
let second = second.pop().unwrap(); Ok((Node::from_slice(&first)?, Node::from_slice(&second)?)) } Err(e) => Err(e.into()), } }); Ok(Box::new(iter)) } } #[cfg(test)] mod tests { use super::*; use quickcheck...
{ return Err(NodeMapError(format!( "invalid index 2 keys in {:?}", self.log.dir )) .into()); }
conditional_block
nodemap.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::ops::Range;
log::{self, IndexOutput, Log}, DefaultOpenOptions, }; use thiserror::Error; use types::errors::KeyError; use types::node::Node; #[derive(Debug, Error)] #[error("Node Map Error: {0:?}")] struct NodeMapError(String); impl From<NodeMapError> for KeyError { fn from(err: NodeMapError) -> Self { KeyErro...
use std::path::Path; use anyhow::Result; use indexedlog::{
random_line_split
nodemap.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::ops::Range; use std::path::Path; use anyhow::Result; use indexedlog::{ log::{self, IndexOutput, Log}, DefaultOpenOptions, }...
{ log: Log, } impl DefaultOpenOptions<log::OpenOptions> for NodeMap { fn default_open_options() -> log::OpenOptions { let first_index = |_data: &[u8]| vec![IndexOutput::Reference(0..20)]; let second_index = |_data: &[u8]| vec![IndexOutput::Reference(20..40)]; log::OpenOptions::new() ...
NodeMap
identifier_name
cycle_strip.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 ~ 2012 Deepin, Inc. # 2011 ~ 2012 Wang Yong # # Author: Wang Yong <lazycat.manatee@gmail.com> # Maintainer: Wang Yong <lazycat.manatee@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the...
gobject.type_register(CycleStrip)
cr = widget.window.cairo_create() rect = widget.allocation background_pixbuf = self.background_dpixbuf.get_pixbuf() self.cache_pixbuf.scale( background_pixbuf, rect.width, rect.height) draw_pixbuf( cr, self.cache_pixbuf.get_c...
identifier_body
cycle_strip.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 ~ 2012 Deepin, Inc. # 2011 ~ 2012 Wang Yong # # Author: Wang Yong <lazycat.manatee@gmail.com> # Maintainer: Wang Yong <lazycat.manatee@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the...
(gtk.HBox): ''' CycleStrip class. This widget use for cycle drawing background, but use CachePixbuf to accelerate render. @undocumented: expose_cycle_strip ''' def __init__(self, background_dpixbuf): ''' Initialize CycleStrip class. @param background_dpixbuf: DynamicP...
CycleStrip
identifier_name
cycle_strip.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 ~ 2012 Deepin, Inc. # 2011 ~ 2012 Wang Yong # # Author: Wang Yong <lazycat.manatee@gmail.com> # Maintainer: Wang Yong <lazycat.manatee@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the...
class CycleStrip(gtk.HBox): ''' CycleStrip class. This widget use for cycle drawing background, but use CachePixbuf to accelerate render. @undocumented: expose_cycle_strip ''' def __init__(self, background_dpixbuf): ''' Initialize CycleStrip class. @param background_...
from cache_pixbuf import CachePixbuf from draw import draw_pixbuf
random_line_split
config.py
#!/usr/bin/env python # 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. # # This program is distributed in the hope that ...
(cp): """Makes sure boolean opts are parsed""" from collections import OrderedDict options = OrderedDict() #options = cp._sections['base'] for section in cp.sections(): options.update( (cp._sections[section]) ) for o in options: for section in cp.sections(): try: ...
get_options
identifier_name
config.py
#!/usr/bin/env python # 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. # # This program is distributed in the hope that ...
return cp def parse_config(conffile=None): """Parse a configparser file""" f = open(conffile,'r') cp = configparser.ConfigParser() try: cp.read(conffile) except Exception as e: print ('failed to read config file! check format') print ('Error returned:', e) retu...
if k in opts: cp.set(s, k, kwargs[k])
conditional_block
config.py
#!/usr/bin/env python # 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. # # This program is distributed in the hope that ...
def create_config_parser_from_dict(data, sections, **kwargs): """Helper method to create a ConfigParser from a dict and/or keywords""" cp = configparser.ConfigParser() for s in sections: cp.add_section(s) if not data.has_key(s): continue for i in data[s]: n...
"""Write a default config file""" if not os.path.exists(conffile): cp = create_config_parser_from_dict(defaults, ['base','novel','aligner','de']) cp.write(open(conffile,'w')) print ('wrote config file %s' %conffile) return conffile
identifier_body
config.py
#!/usr/bin/env python # 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. # # This program is distributed in the hope that ...
('de_plot','point')] } def write_default_config(conffile='default.conf', defaults={}): """Write a default config file""" if not os.path.exists(conffile): cp = create_config_parser_from_dict(defaults, ['base','novel','aligner','de']) cp.write(open(conffil...
('conditions',''),('logfc_cutoff',1.5),
random_line_split
ActivityListComponent.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/empty'; import 'rxjs/add/operator/switchMap'; import { isNullOrUndefined } from 'util'; import { Activity } from 'app/activity/A...
() { this.firstResult -= this.MAX_RESULTS; if (this.firstResult < 0) { this.firstResult = 0; return } this.getActivities() } }
prevPage
identifier_name
ActivityListComponent.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/empty'; import 'rxjs/add/operator/switchMap'; import { isNullOrUndefined } from 'util'; import { Activity } from 'app/activity/A...
else { return this.activityService.getById(+params['id']) } }) .subscribe((activity: Activity) => { this.selectedActivity = activity; }) } isActivityNotSelected(): boolean { return isNullOrUndefined(this.selectedActivity); } setActivity(activity: Activity) { this.router.navigate(['activ...
{ return Observable.empty() }
conditional_block
ActivityListComponent.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/empty'; import 'rxjs/add/operator/switchMap'; import { isNullOrUndefined } from 'util'; import { Activity } from 'app/activity/A...
nextPage() { this.firstResult += this.MAX_RESULTS; this.getActivities() } prevPage() { this.firstResult -= this.MAX_RESULTS; if (this.firstResult < 0) { this.firstResult = 0; return } this.getActivities() } }
{ this.activityService .getAll(this.firstResult, this.MAX_RESULTS) .subscribe((activities: Array<Activity>) => { this.activities = activities; }); }
identifier_body
ActivityListComponent.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/empty'; import 'rxjs/add/operator/switchMap'; import { isNullOrUndefined } from 'util'; import { Activity } from 'app/activity/A...
private route: ActivatedRoute) { } ngOnInit(): void { this.getActivities() this.route.params .switchMap((params: Params) => { if (isNullOrUndefined(params['id'])) { return Observable.empty() } else { return this.activityService.getById(+params['id']) } }) .subscribe((activity:...
constructor(private activityService: ActivityService, private router: Router,
random_line_split
domparser.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 http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::DOMParserBinding; use dom::bindings::utils::{CacheableWrapper, WrapperCache}; use dom:...
(&mut self) -> &mut WrapperCache { unsafe { cast::transmute(&self.wrapper) } } fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject { let mut unused = false; DOMParserBinding::Wrap(cx, scope, self, &mut unused) } } impl BindingObject for DOMParser { f...
get_wrappercache
identifier_name
domparser.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 http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::DOMParserBinding; use dom::bindings::utils::{CacheableWrapper, WrapperCache}; use dom:...
else { unsafe { *vp = RUST_OBJECT_TO_JSVAL(obj) }; return 1; } } }
{ return 0; }
conditional_block
domparser.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 http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::DOMParserBinding; use dom::bindings::utils::{CacheableWrapper, WrapperCache}; use dom:...
let obj = self.wrap_object_shared(cx, scope); if obj.is_null() { return 0; } else { unsafe { *vp = RUST_OBJECT_TO_JSVAL(obj) }; return 1; } } }
fail!(~"nyi") } fn wrap_shared(@mut self, cx: *JSContext, scope: *JSObject, vp: *mut JSVal) -> i32 {
random_line_split
domparser.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 http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::DOMParserBinding; use dom::bindings::utils::{CacheableWrapper, WrapperCache}; use dom:...
}
{ let obj = self.wrap_object_shared(cx, scope); if obj.is_null() { return 0; } else { unsafe { *vp = RUST_OBJECT_TO_JSVAL(obj) }; return 1; } }
identifier_body
base.py
from abc import ABC, abstractmethod from typing import Dict, List, Optional, Tuple from limits.storage.registry import StorageRegistry from limits.util import LazyDependency class
(LazyDependency, metaclass=StorageRegistry): """ Base class to extend when implementing an async storage backend. .. warning:: This is a beta feature .. versionadded:: 2.1 """ STORAGE_SCHEME: Optional[List[str]] """The storage schemes to register against this implementation""" def __i...
Storage
identifier_name
base.py
from abc import ABC, abstractmethod from typing import Dict, List, Optional, Tuple from limits.storage.registry import StorageRegistry from limits.util import LazyDependency class Storage(LazyDependency, metaclass=StorageRegistry): """ Base class to extend when implementing an async storage backend. .. ...
""" resets the rate limit key :param key: the key to clear rate limits for """ raise NotImplementedError class MovingWindowSupport(ABC): """ Abstract base for storages that intend to support the moving window strategy .. warning:: This is a beta feature .....
@abstractmethod async def clear(self, key: str) -> int:
random_line_split
base.py
from abc import ABC, abstractmethod from typing import Dict, List, Optional, Tuple from limits.storage.registry import StorageRegistry from limits.util import LazyDependency class Storage(LazyDependency, metaclass=StorageRegistry): """ Base class to extend when implementing an async storage backend. .. ...
""" returns the starting point and the number of entries in the moving window :param key: rate limit key :param expiry: expiry of entry :return: (start of window, number of acquired entries) """ raise NotImplementedError
""" Abstract base for storages that intend to support the moving window strategy .. warning:: This is a beta feature .. versionadded:: 2.1 """ async def acquire_entry( self, key: str, limit: int, expiry: int, amount: int = 1 ) -> bool: """ :param key: rate limit key...
identifier_body
index.d.ts
// Type definitions for Angular Wizard 0.6.1 // Project: https://github.com/mgonto/angular-wizard // Definitions by: Marko Jurisic <https://github.com/mjurisic>, Ronald Wildenberg <https://github.com/rwwilden> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export namespace mgoAngularWizard { interface WizardHandler { wizard(name?: string): Wizard; addWizard(name: string, wizard: Wizard): void; removeWizard(name: string): void; } interface Wizard { next(nextHandler?: () => boolean): void; previous(): void; cancel: () => v...
// TypeScript Version: 2.1 import * as angular from 'angular'; declare module 'angular' {
random_line_split
index.ts
/* MIT License Copyright (c) 2022 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...
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 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 SOFTWARE. */ export * from './Aside'
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
random_line_split
BoxOfficeMojo_Scraping_Code.py
: merged = dict(dictData) merged.update(countriesData) dictData = merged with open(filePath, "a") as outfile: json.dump(dictData, outfile, ensure_ascii=False) def write_header(filePath): # Write a header text_file = open(filePath, "ab") for header in Keys: text...
(link, arrData): url = "http://www.boxofficemojo.com"+ link page = urlopen(url) soup = BeautifulSoup(page, "lxml") # Assume that domestic info is from USA arrData['Countryclicktoviewweekendbreakdown']= "USA" #print(main_tbl) tables = soup.find_all('table', attrs={'border': '0' , 'cells...
get_total_lifetime_grosses
identifier_name
BoxOfficeMojo_Scraping_Code.py
: merged = dict(dictData) merged.update(countriesData) dictData = merged with open(filePath, "a") as outfile: json.dump(dictData, outfile, ensure_ascii=False) def write_header(filePath): # Write a header text_file = open(filePath, "ab") for header in Keys: text...
DS_tr_content = DS_tr.td.findNext('td') if DS_tr_content: arrData["Opening Weekend"] = DS_tr_content.text.strip() arrData["OpeningWknd"] = DS_tr_content.text.strip() ...
if(box.text == "Total Lifetime Grosses"): div_content= box.findNext('div') trs = div_content.find_all('tr') for tr in trs: tds = tr.find_all('td') if len(tds) == 3: if tds[0].text.strip() == "Domestic:": ...
conditional_block
BoxOfficeMojo_Scraping_Code.py
, "a") as outfile: json.dump(dictData, outfile, ensure_ascii=False) def write_header(filePath): # Write a header text_file = open(filePath, "ab") for header in Keys: text_file.write((header + u"|").encode('utf-8')) text_file.write("\n".encode('utf-8')) text_file.close() def save_t...
arrData['Runtime'] = Runtime
random_line_split
BoxOfficeMojo_Scraping_Code.py
def save_to_json(filePath, dictData, countriesData=None): dictData = remove_special_chars(dictData) countriesData = remove_special_chars(countriesData) if countriesData: merged = dict(dictData) merged.update(countriesData) dictData = merged with open(filePath, "a") a...
newDict= {} for key in dictData: new_key= re.sub(r'\W+', '', key) newDict[new_key] = dictData[key] return newDict
identifier_body
conf.py
# -*- coding: utf-8 -*- # # GromacsWrapper documentation build configuration file, created by # sphinx-quickstart on Tue Jun 23 19:38:56 2009. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't ...
# Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class ...
random_line_split
AjaxErrorModal.tsx
import * as React from 'react'; import { Modal } from 'react-bootstrap'; export interface IAjaxErrorModalProps { show: boolean; onHide: () => void; title?: string; troubleshooting?: string[]; } export default class AjaxErrorModal extends React.Component< IAjaxErrorModalProps, {} > { privat...
() { return ( <Modal show={this.props.show} onHide={this.props.onHide}> <Modal.Header closeButton> <Modal.Title> {typeof this.props.title === 'undefined' ? this.defaultTitle : this.pro...
render
identifier_name
AjaxErrorModal.tsx
import * as React from 'react'; import { Modal } from 'react-bootstrap'; export interface IAjaxErrorModalProps { show: boolean; onHide: () => void; title?: string; troubleshooting?: string[]; } export default class AjaxErrorModal extends React.Component< IAjaxErrorModalProps, {} > { privat...
</Modal.Title> </Modal.Header> <Modal.Body> <p>Troubleshooting:</p> <ul> {( this.props.troubleshooting || this.defaultTroubleshooting ...
{typeof this.props.title === 'undefined' ? this.defaultTitle : this.props.title}
random_line_split
issue-2895.rs
// Copyright 2012 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 ...
{ assert_eq!(mem::size_of::<Cat>(), 4 as uint); assert_eq!(mem::size_of::<Kitty>(), 8 as uint); }
identifier_body
issue-2895.rs
// Copyright 2012 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 ...
(&mut self) {} } #[cfg(target_arch = "x86_64")] pub fn main() { assert_eq!(mem::size_of::<Cat>(), 8 as uint); assert_eq!(mem::size_of::<Kitty>(), 16 as uint); } #[cfg(any(target_arch = "x86", target_arch = "arm"))] pub fn main() { assert_eq!(mem::size_of::<Cat>(), 4 as uint); assert_eq!(mem::size_of::...
drop
identifier_name
issue-2895.rs
// Copyright 2012 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 ...
impl Drop for Kitty { fn drop(&mut self) {} } #[cfg(target_arch = "x86_64")] pub fn main() { assert_eq!(mem::size_of::<Cat>(), 8 as uint); assert_eq!(mem::size_of::<Kitty>(), 16 as uint); } #[cfg(any(target_arch = "x86", target_arch = "arm"))] pub fn main() { assert_eq!(mem::size_of::<Cat>(), 4 as ui...
struct Kitty { x: int, }
random_line_split
dashboard.py
# -*- coding: utf-8 -*- """ proxy.py ~~~~~~~~ ⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on Network monitoring, controls & Application development, testing, debugging. :copyright: (c) 2013-present by Abhinav Singh and contributors. :license: BSD, see LICENSE...
from ..http.parser import HttpParser from ..http.server import HttpWebServerBasePlugin, httpProtocolTypes from ..http.responses import permanentRedirectResponse logger = logging.getLogger(__name__) class ProxyDashboard(HttpWebServerBasePlugin): """Proxy Dashboard.""" # Redirects to /dashboard/ REDIREC...
random_line_split
dashboard.py
# -*- coding: utf-8 -*- """ proxy.py ~~~~~~~~ ⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on Network monitoring, controls & Application development, testing, debugging. :copyright: (c) 2013-present by Abhinav Singh and contributors. :license: BSD, see LICENSE...
def handle_request(self, request: HttpParser) -> None: if request.path == b'/dashboard/': self.client.queue( self.serve_static_file( os.path.join( self.flags.static_server_dir, 'dashboard', 'proxy.html', ...
xy Dashboard.""" # Redirects to /dashboard/ REDIRECT_ROUTES = [ (httpProtocolTypes.HTTP, r'/dashboard$'), (httpProtocolTypes.HTTPS, r'/dashboard$'), (httpProtocolTypes.HTTP, r'/dashboard/proxy.html$'), (httpProtocolTypes.HTTPS, r'/dashboard/proxy.html$'), ] # Index html...
identifier_body
dashboard.py
# -*- coding: utf-8 -*- """ proxy.py ~~~~~~~~ ⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on Network monitoring, controls & Application development, testing, debugging. :copyright: (c) 2013-present by Abhinav Singh and contributors. :license: BSD, see LICENSE...
lient.queue(permanentRedirectResponse(b'/dashboard/'))
conditional_block
dashboard.py
# -*- coding: utf-8 -*- """ proxy.py ~~~~~~~~ ⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on Network monitoring, controls & Application development, testing, debugging. :copyright: (c) 2013-present by Abhinav Singh and contributors. :license: BSD, see LICENSE...
-> List[Tuple[int, str]]: return ProxyDashboard.REDIRECT_ROUTES + \ ProxyDashboard.INDEX_ROUTES def handle_request(self, request: HttpParser) -> None: if request.path == b'/dashboard/': self.client.queue( self.serve_static_file( os.path.j...
(self)
identifier_name
array.ts
import {PathSegment} from '@sanity/types/src' import {findIndex} from 'lodash' import applyPatch from './applyPatch' import insert from './arrayInsert' const hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty) function move(arr: any[], from: number, to: any) { const nextValue = arr.s...
else if (patch.type === 'move') { if (!patch.value || !hasOwn(patch.value, 'from') || !hasOwn(patch.value, 'to')) { // eslint-disable-line max-depth throw new Error( `Invalid value of 'move' patch. Expected a value with "from" and "to" indexes, instead got: ${JSON.stringify( ...
{ return undefined }
conditional_block
array.ts
import {PathSegment} from '@sanity/types/src' import {findIndex} from 'lodash' import applyPatch from './applyPatch' import insert from './arrayInsert' const hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty) function move(arr: any[], from: number, to: any) { const nextValue = arr.s...
} const index = findIndex(array, pathSegment) return index === -1 ? false : index } export default function apply( value: any, patch: {type: any; path: any; value: any; position: any; items: any} ) { const nextValue = value.slice() // make a copy for internal mutation if (patch.path.length === 0) { ...
function findTargetIndex(array: any[], pathSegment: PathSegment) { if (typeof pathSegment === 'number') { return pathSegment
random_line_split
array.ts
import {PathSegment} from '@sanity/types/src' import {findIndex} from 'lodash' import applyPatch from './applyPatch' import insert from './arrayInsert' const hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty) function move(arr: any[], from: number, to: any) { const nextValue = arr.s...
export default function apply( value: any, patch: {type: any; path: any; value: any; position: any; items: any} ) { const nextValue = value.slice() // make a copy for internal mutation if (patch.path.length === 0) { // its directed to me if (patch.type === 'setIfMissing') { if (!Array.isArray(p...
{ if (typeof pathSegment === 'number') { return pathSegment } const index = findIndex(array, pathSegment) return index === -1 ? false : index }
identifier_body
array.ts
import {PathSegment} from '@sanity/types/src' import {findIndex} from 'lodash' import applyPatch from './applyPatch' import insert from './arrayInsert' const hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty) function move(arr: any[], from: number, to: any) { const nextValue = arr.s...
(array: any[], pathSegment: PathSegment) { if (typeof pathSegment === 'number') { return pathSegment } const index = findIndex(array, pathSegment) return index === -1 ? false : index } export default function apply( value: any, patch: {type: any; path: any; value: any; position: any; items: any} ) { ...
findTargetIndex
identifier_name
keywords.rs
use nom::branch::alt; use nom::bytes::complete::{tag, tag_no_case}; use nom::combinator::peek; use nom::sequence::terminated; use nom::IResult; use crate::parsers::parser::elements::eof; fn keyword_follow_char(input: &str) -> IResult<&str, &str>
pub fn sql_keyword(input: &str) -> IResult<&str, &str> { alt(( terminated(tag_no_case("SELECT"), keyword_follow_char), terminated(tag_no_case("FROM"), keyword_follow_char), terminated(tag_no_case("WHERE"), keyword_follow_char), terminated(tag_no_case("ORDER"), keyword_follow_char),...
{ peek(alt(( tag(" "), tag("\n"), tag(";"), tag("("), tag(")"), tag("\t"), tag(","), tag("="), eof, )))(input) }
identifier_body
keywords.rs
use nom::branch::alt; use nom::bytes::complete::{tag, tag_no_case}; use nom::combinator::peek; use nom::sequence::terminated; use nom::IResult; use crate::parsers::parser::elements::eof; fn
(input: &str) -> IResult<&str, &str> { peek(alt(( tag(" "), tag("\n"), tag(";"), tag("("), tag(")"), tag("\t"), tag(","), tag("="), eof, )))(input) } pub fn sql_keyword(input: &str) -> IResult<&str, &str> { alt(( terminated(tag...
keyword_follow_char
identifier_name
keywords.rs
use nom::branch::alt; use nom::bytes::complete::{tag, tag_no_case}; use nom::combinator::peek; use nom::sequence::terminated; use nom::IResult; use crate::parsers::parser::elements::eof; fn keyword_follow_char(input: &str) -> IResult<&str, &str> { peek(alt(( tag(" "), tag("\n"), tag(";"...
terminated(tag_no_case("ORDER"), keyword_follow_char), terminated(tag_no_case("BY"), keyword_follow_char), terminated(tag_no_case("ASC"), keyword_follow_char), terminated(tag_no_case("DESC"), keyword_follow_char), terminated(tag_no_case("LIMIT"), keyword_follow_char), ter...
terminated(tag_no_case("SELECT"), keyword_follow_char), terminated(tag_no_case("FROM"), keyword_follow_char), terminated(tag_no_case("WHERE"), keyword_follow_char),
random_line_split
t_LogUniformFactory_std.py
#! /usr/bin/env python from openturns import * TESTPREAMBLE() RandomGenerator().SetSeed(0) try : distribution = LogUniform(1.0, 2.5) size = 10000 sample = distribution.getSample(size) factory = LogUniformFactory covariance = CovarianceMatrix estimatedDistribution = factory.build(sample) p...
except : import sys print "t_LogUniformFactory_std.py", sys.exc_type, sys.exc_value
random_line_split
number_pipe.ts
import { isNumber, isPresent, isBlank, StringWrapper, NumberWrapper, RegExpWrapper, BaseException, CONST, FunctionWrapper } from 'angular2/src/core/facade/lang'; import {NumberFormatter, NumberFormatStyle} from 'angular2/src/core/facade/intl'; import {Injectable} from 'angular2/di'; import {ListWrappe...
symbolDisplay); } }
random_line_split
number_pipe.ts
import { isNumber, isPresent, isBlank, StringWrapper, NumberWrapper, RegExpWrapper, BaseException, CONST, FunctionWrapper } from 'angular2/src/core/facade/lang'; import {NumberFormatter, NumberFormatStyle} from 'angular2/src/core/facade/intl'; import {Injectable} from 'angular2/di'; import {ListWrappe...
extends NumberPipe implements PipeTransform { transform(value: any, args: any[]): string { var digits: string = ListWrapper.first(args); return NumberPipe._format(value, NumberFormatStyle.PERCENT, digits); } } /** * WARNING: this pipe uses the Internationalization API. * Therefore it is only reliable in...
PercentPipe
identifier_name
number_pipe.ts
import { isNumber, isPresent, isBlank, StringWrapper, NumberWrapper, RegExpWrapper, BaseException, CONST, FunctionWrapper } from 'angular2/src/core/facade/lang'; import {NumberFormatter, NumberFormatStyle} from 'angular2/src/core/facade/intl'; import {Injectable} from 'angular2/di'; import {ListWrappe...
if (isPresent(parts[1])) { // min integer digits minInt = NumberWrapper.parseIntAutoRadix(parts[1]); } if (isPresent(parts[3])) { // min fraction digits minFraction = NumberWrapper.parseIntAutoRadix(parts[3]); } if (isPresent(parts[5])) { // max fraction digits ...
{ throw new BaseException(`${digits} is not a valid digit info for number pipes`); }
conditional_block
dining_philosophers.rs
// http://rosettacode.org/wiki/Dining_philosophers //! A Rust implementation of a solution for the Dining Philosophers Problem. We prevent a deadlock //! by using Dijkstra's solution of making a single diner "left-handed." That is, all diners except //! one pick up the chopstick "to their left" and then the chopstick ...
() { let table = Arc::new(Table { forks: vec![ Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), ], }); let philosophers = vec![ Philosopher::new("Baruch Spinoza", 0, 1), Philosopher::new("Gilles Deleuze", 1, ...
main
identifier_name
dining_philosophers.rs
// http://rosettacode.org/wiki/Dining_philosophers //! A Rust implementation of a solution for the Dining Philosophers Problem. We prevent a deadlock //! by using Dijkstra's solution of making a single diner "left-handed." That is, all diners except //! one pick up the chopstick "to their left" and then the chopstick ...
} struct Table { forks: Vec<Mutex<()>>, } fn main() { let table = Arc::new(Table { forks: vec![ Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), ], }); let philosophers = vec![ Philosopher::new("Baruch Spinoza...
{ let _left = table.forks[self.left].lock().unwrap(); let _right = table.forks[self.right].lock().unwrap(); println!("{} is eating.", self.name); thread::sleep(Duration::from_secs(1)); println!("{} is done eating.", self.name); }
identifier_body