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
MockFilesystem.test.ts
import {IFilesystem} from './Filesystem'; export type Node = Directory | string; export type Directory = {[name: string]: Node}; export class MockFilesystem implements IFilesystem { files: Directory = {}; constructor(files?: Directory) { this.files = files || {}; } private get(path: string, ...
let ret: string[] | undefined; let node: Node = this.files; const names = path.substr(1).split('/'); for (let i = 0; i < names.length - 1; i ++) { let nextNode: Node | string; if (names[i] in node) { nextNode = node[names[i]]; if (t...
random_line_split
MockFilesystem.test.ts
import {IFilesystem} from './Filesystem'; export type Node = Directory | string; export type Directory = {[name: string]: Node}; export class MockFilesystem implements IFilesystem { files: Directory = {}; constructor(files?: Directory) { this.files = files || {}; } private get(path: string, ...
}
{ const [dir, name] = this.get(path); if (typeof dir == 'undefined' || !(name in dir)) return Promise.reject(new Error('no such node')); delete dir[name]; return Promise.resolve(); }
identifier_body
MockFilesystem.test.ts
import {IFilesystem} from './Filesystem'; export type Node = Directory | string; export type Directory = {[name: string]: Node}; export class MockFilesystem implements IFilesystem { files: Directory = {}; constructor(files?: Directory) { this.files = files || {}; } private get(path: string, ...
(path: string, data: string) { const [dir, name] = this.get(path, true); if (typeof dir == 'undefined') return Promise.reject(new Error('cannot make parents')); dir[name] = data; return Promise.resolve(); } moveFolder(oldPath: string, newPath: string) { const...
write
identifier_name
mod.rs
/************************************************************************ * * * Copyright 2015 Urban Hafner, Thomas Poinsot, Igor Polyakov * * * * This file is part of ...
-> i64 { self.byo_time_left } pub fn main_time_left(&self) -> i64 { self.main_time_left } fn set_main_time(&mut self, time: i64) { self.main_time_left = time; } fn set_byo_time(&mut self, time: i64) { self.byo_time = time; self.byo_time_left = time; ...
_left(&self)
identifier_name
mod.rs
/************************************************************************ * * * Copyright 2015 Urban Hafner, Thomas Poinsot, Igor Polyakov * * * * This file is part of ...
b fn reset(&mut self) { // Do nothing } pub fn byo_stones_left(&self) -> i32 { self.byo_stones_left } pub fn byo_time_left(&self) -> i64 { self.byo_time_left } pub fn main_time_left(&self) -> i64 { self.main_time_left } fn set_main_time(&mut self, time...
self.adjust_time(); } pu
identifier_body
mod.rs
/************************************************************************ * * * Copyright 2015 Urban Hafner, Thomas Poinsot, Igor Polyakov * * * * This file is part of ...
byo_stones_left: 0, byo_time: 0, byo_time_left: 0, config: config, current_budget: Duration::milliseconds(0), main_time_left: 0, time_stamp: PreciseTime::now(), } } pub fn setup(&mut self, main_in_s: i64, byo_in_s: i64...
byo_stones: 0,
random_line_split
mod.rs
/************************************************************************ * * * Copyright 2015 Urban Hafner, Thomas Poinsot, Igor Polyakov * * * * This file is part of ...
elapsed > self.current_budget } } pub fn stop(&mut self) { self.adjust_time(); } pub fn reset(&mut self) { // Do nothing } pub fn byo_stones_left(&self) -> i32 { self.byo_stones_left } pub fn byo_time_left(&self) -> i64 { self.byo_t...
self.config.log(format!("Search stopped early. Fastplay rule triggered.")); true } else {
conditional_block
settings.py
""" Django settings for mysite2 project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # B...
ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myauthen', ] MIDDLEWARE_CLASSES = [ 'django.middleware.se...
random_line_split
dependency.rs
struct Dependency { inner: Rc<Inner>, } /// The data underlying a Dependency. #[derive(PartialEq, Clone, Debug)] struct Inner { name: String, source_id: SourceId, req: VersionReq, specified_req: bool, kind: Kind, only_match_name: bool, optional: bool, default_features: bool, f...
(&mut self, id: SourceId) -> &mut Dependency { Rc::make_mut(&mut self.inner).source_id = id; self } /// Set the version requirement for this dependency pub fn set_version_req(&mut self, req: VersionReq) -> &mut Dependency { Rc::make_mut(&mut self.inner).req = req; self }...
set_source_id
identifier_name
dependency.rs
struct Dependency { inner: Rc<Inner>, } /// The data underlying a Dependency. #[derive(PartialEq, Clone, Debug)] struct Inner { name: String, source_id: SourceId, req: VersionReq, specified_req: bool, kind: Kind, only_match_name: bool, optional: bool, default_features: bool, f...
} }, Ok(v) => Ok(v), } } impl ser::Serialize for Kind { fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, { match *self { Kind::Normal => None, Kind::Development => Some("dev"), Kind::Build => So...
} e => Err(e.into()),
random_line_split
result.ts
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; interface Option { option: string; value: any; } interface Question { question: string; options: Option[]; } interface ResultType { questions: Question[]; result: number[]; } @IonicPage() @Com...
og(question + '###########################################'); console.log(this.dados.questions[question - 1]); console.log(this.dados.questions[question - 1].options); console.log(this.dados.questions[question - 1].options[this.dados.result[question - 1]]); console.log(this.dados.result) return...
identifier_body
result.ts
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; interface Option { option: string; value: any; } interface Question { question: string; options: Option[]; } interface ResultType { questions: Question[]; result: number[]; } @IonicPage() @Com...
// Perguntas 8, 9 – Outros fatores – OF const OF = this.getQuestionValue(8) + this.getQuestionValue(9); return 2 * FD + 4 * FP + 2 * HC + 2 * OF; } private getQuestionValue(question: number) { console.log(question + '###########################################'); console.log(this.dados...
const HC = this.getQuestionValue(7);
random_line_split
result.ts
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; interface Option { option: string; value: any; } interface Question { question: string; options: Option[]; } interface ResultType { questions: Question[]; result: number[]; } @IonicPage() @Com...
() { // Perguntas 1,2 – Fatores distais const FD = this.getQuestionValue(1) + this.getQuestionValue(2); // Perguntas 2, 3, 4, 5, 6 – Fatores proximais – FP const FP = this.getQuestionValue(2) + this.getQuestionValue(3) + this.getQuestionValue(4) + this.getQuestionValue(5) ...
calculateResult
identifier_name
RenderSystem.ts
module asteroids.systems { import Position = asteroids.components.Position; import Display = asteroids.components.Display; import Mapper = artemis.annotations.Mapper; import ImmutableBag = artemis.utils.ImmutableBag; import GameConfig = asteroids.GameConfig; import EntitySystem = artemis.EntitySystem; i...
public processEach(e:Entity) { var position = this.pm.get(e); var display = this.dm.get(e); var sprite = display.sprite; sprite.x = position.position.x; sprite.y = position.position.y; sprite.rotation = position.rotation; sprite.draw(this.graphic); } } }
{ this.graphic.clearRect(0, 0, this.config.width, this.config.height); for (var i=0, k=entities.size(); i<k; i++) { this.processEach(entities.get(i)); } /** * DOUBLE_BUFFERING? * copy to the off screen canvas */ if (DOUBLE_BUFFERING) { this.screen.cle...
identifier_body
RenderSystem.ts
module asteroids.systems { import Position = asteroids.components.Position;
import EntitySystem = artemis.EntitySystem; import ComponentMapper = artemis.ComponentMapper; import Aspect = artemis.Aspect; import Entity = artemis.Entity; const DOUBLE_BUFFERING = (location.search === '?b=2'); console.log('Using DOUBLE_BUFFERING', DOUBLE_BUFFERING); export class RenderSystem extend...
import Display = asteroids.components.Display; import Mapper = artemis.annotations.Mapper; import ImmutableBag = artemis.utils.ImmutableBag; import GameConfig = asteroids.GameConfig;
random_line_split
RenderSystem.ts
module asteroids.systems { import Position = asteroids.components.Position; import Display = asteroids.components.Display; import Mapper = artemis.annotations.Mapper; import ImmutableBag = artemis.utils.ImmutableBag; import GameConfig = asteroids.GameConfig; import EntitySystem = artemis.EntitySystem; i...
} public processEach(e:Entity) { var position = this.pm.get(e); var display = this.dm.get(e); var sprite = display.sprite; sprite.x = position.position.x; sprite.y = position.position.y; sprite.rotation = position.rotation; sprite.draw(this.graphic); } } }
{ this.screen.clearRect(0, 0, this.config.width, this.config.height); this.screen.drawImage(this.canvas, 0, 0); }
conditional_block
RenderSystem.ts
module asteroids.systems { import Position = asteroids.components.Position; import Display = asteroids.components.Display; import Mapper = artemis.annotations.Mapper; import ImmutableBag = artemis.utils.ImmutableBag; import GameConfig = asteroids.GameConfig; import EntitySystem = artemis.EntitySystem; i...
extends EntitySystem { @Mapper(Position) pm:ComponentMapper<Position>; @Mapper(Display) dm:ComponentMapper<Display>; private graphic:CanvasRenderingContext2D; private screen:CanvasRenderingContext2D; private canvas:HTMLCanvasElement; private config:GameConfig; /** * @constructor ...
RenderSystem
identifier_name
text_utils.py
(bbs, t): """ Translate the bounding-boxes in by t_x,t_y. BB : 2x4xn T : 2-long np.array """ return bbs + t[:,None,None] def crop_safe(arr, rect, bbs=[], pad=0): """ ARR : arr to crop RECT: (x,y,w,h) : area to crop to BBS : nx4 xywh format bounding-boxes PAD : percentage to...
move_bb
identifier_name
text_utils.py
# get the union of characters for cropping: r0 = pygame.Rect(bbs[0]) rect_union = r0.unionall(bbs) # get the words: words = ' '.join(text.split()) # crop the surface to fit the text: bbs = np.array(bbs) surf_arr, bbs = crop_safe(pygame.surfarray.pixels...
x = 0 # carriage-return y += line_spacing # line-feed for ch in l: # render each character if ch.isspace(): # just shift x += space.width else: # render the character ch_bounds = font.render_to(surf, (x,...
conditional_block
text_utils.py
%.2f, max: %.2f)"%(f_h_px, self.min_font_h,max_font_h) # convert from pixel-height to font-point-size: f_h = self.font_state.get_font_size(font, f_h_px) # update for the loop max_font_h = f_h_px i += 1 font.size = f_h # set the font-size ...
char_ex = ['i','I','o','O','0','-'] chs = [ch in char_ex for ch in l] return not np.all(chs)
random_line_split
text_utils.py
' '.join(text.split()) # crop the surface to fit the text: bbs = np.array(bbs) surf_arr, bbs = crop_safe(pygame.surfarray.pixels_alpha(surf), rect_union, bbs, pad=5) surf_arr = surf_arr.swapaxes(0,1) #self.visualize_bb(surf_arr,bbs) return surf_arr, words, bbs def ...
# update the bounding-boxes: bbs[i] = move_bb(bbs[i],loc[::-1]) # blit the text onto the canvas w,h = text_arrs[i].shape out_arr[loc[0]:loc[0]+w,loc[1]:loc[1]+h] += text_arrs[i] return out_arr, locs, bbs, order def robust_HW(self,mask): ...
areas = [-np.prod(ta.shape) for ta in text_arrs] order = np.argsort(areas) locs = [None for i in range(len(text_arrs))] out_arr = np.zeros_like(back_arr) for i in order: ba = np.clip(back_arr.copy().astype(np.float), 0, 255) ta = np.clip(text_arrs[i]....
identifier_body
v1beta1.js
"use strict"; /** * Copyright 2015 Google 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/licenses/LICENSE-2.0 * * Unless req...
options || (options = {}); const rootUrl = options.rootUrl || 'https://datastore.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/v1beta1/projects/{projectId}:export').replace(/([^:]\/)\/+/g, '$1'), ...
{ callback = options; options = {}; }
conditional_block
v1beta1.js
"use strict"; /** * Copyright 2015 Google 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/licenses/LICENSE-2.0 * * Unless req...
(options) { const self = this; self._options = options || {}; self.projects = { /** * datastore.projects.export * * @desc Exports a copy of all or a subset of entities from Google Cloud Datastore to another storage system, such as Google Cloud Storage. Recent updates to en...
Datastore
identifier_name
v1beta1.js
"use strict"; /** * Copyright 2015 Google 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/licenses/LICENSE-2.0 * * Unless req...
if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://datastore.googleapis.com/'; const parameters = { options: Object.ass...
{ const self = this; self._options = options || {}; self.projects = { /** * datastore.projects.export * * @desc Exports a copy of all or a subset of entities from Google Cloud Datastore to another storage system, such as Google Cloud Storage. Recent updates to entities may...
identifier_body
v1beta1.js
"use strict"; /** * Copyright 2015 Google 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/licenses/LICENSE-2.0 * * Unless req...
* * @alias datastore.projects.export * @memberOf! datastore(v1beta1) * * @param {object} params Parameters for request * @param {string} params.projectId Project ID against which to make the request. * @param {datastore(v1beta1).GoogleDatastoreAdminV1beta1E...
* @desc Exports a copy of all or a subset of entities from Google Cloud Datastore to another storage system, such as Google Cloud Storage. Recent updates to entities may not be reflected in the export. The export occurs in the background and its progress can be monitored and managed via the Operation resource ...
random_line_split
S11.13.2_A4.6_T2.8.js
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.13.2_A4.6_T2.8; * @section: 11.13.2, 11.7.1; * @assertion: The production x <<= y is the same as x = x << y; * @description: Type(x) is different from Type(y)...
$ERROR('#1: x = true; x <<= undefined; x === 1. Actual: ' + (x)); } //CHECK#2 x = undefined; x <<= true; if (x !== 0) { $ERROR('#2: x = undefined; x <<= true; x === 0. Actual: ' + (x)); } //CHECK#3 x = new Boolean(true); x <<= undefined; if (x !== 1) { $ERROR('#3: x = new Boolean(true); x <<= unde...
if (x !== 1) {
random_line_split
S11.13.2_A4.6_T2.8.js
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.13.2_A4.6_T2.8; * @section: 11.13.2, 11.7.1; * @assertion: The production x <<= y is the same as x = x << y; * @description: Type(x) is different from Type(y)...
//CHECK#4 x = undefined; x <<= new Boolean(true); if (x !== 0) { $ERROR('#4: x = undefined; x <<= new Boolean(true); x === 0. Actual: ' + (x)); }
{ $ERROR('#3: x = new Boolean(true); x <<= undefined; x === 1. Actual: ' + (x)); }
conditional_block
nyc.py
import bikeshares import pandas as pd import numpy as np def convert_rider_gender(x): if x == 0: return np.nan if x == 1: return "M" if x == 2: return "F" raise Exception("Unrecognized gender variable: {0}".format(x)) def convert_rider_type(x): if x == "Subscriber": return "member" if x == "Cu...
def parse_stations(self, data_path): parsed = pd.read_csv(data_path, usecols=[ "start station id", "start station name", "start station latitude", "start station longitude" ]) mapped = pd.DataFrame({ "id": parsed["start station id"], "name": par...
parsed = pd.read_csv(data_path, usecols=["starttime", "stoptime", "tripduration", "start station id", "end station id", "bikeid", "usertype", "gender", "birth year" ], parse_dates=["starttime", "stoptime"]) mapped = pd.DataFrame({ "st...
identifier_body
nyc.py
import bikeshares import pandas as pd import numpy as np def convert_rider_gender(x): if x == 0: return np.nan if x == 1: return "M" if x == 2: return "F" raise Exception("Unrecognized gender variable: {0}".format(x)) def convert_rider_type(x): if x == "Subscriber": return "member" if x == "Cu...
(self, data_path): parsed = pd.read_csv(data_path, usecols=["starttime", "stoptime", "tripduration", "start station id", "end station id", "bikeid", "usertype", "gender", "birth year" ], parse_dates=["starttime", "stoptime"]) mapped = pd....
parse_trips
identifier_name
nyc.py
import bikeshares import pandas as pd import numpy as np def convert_rider_gender(x): if x == 0: return np.nan if x == 1: return "M" if x == 2: return "F"
if x == "Customer": return "non-member" raise Exception("Unrecognized rider type: {0}".format(x)) class CitiBike(bikeshares.program.BikeShareProgram): def parse_trips(self, data_path): parsed = pd.read_csv(data_path, usecols=["starttime", "stoptime", "tripduration", "sta...
raise Exception("Unrecognized gender variable: {0}".format(x)) def convert_rider_type(x): if x == "Subscriber": return "member"
random_line_split
nyc.py
import bikeshares import pandas as pd import numpy as np def convert_rider_gender(x): if x == 0: return np.nan if x == 1: return "M" if x == 2: return "F" raise Exception("Unrecognized gender variable: {0}".format(x)) def convert_rider_type(x): if x == "Subscriber": return "member" if x == "Cu...
raise Exception("Unrecognized rider type: {0}".format(x)) class CitiBike(bikeshares.program.BikeShareProgram): def parse_trips(self, data_path): parsed = pd.read_csv(data_path, usecols=["starttime", "stoptime", "tripduration", "start station id", "end station id", ...
return "non-member"
conditional_block
0002_projectcredentials_websitecredentials.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import creditpiggy.core.models class
(migrations.Migration): dependencies = [ ('core', '0014_auto_20150616_1247'), ('api', '0001_initial'), ] operations = [ migrations.CreateModel( name='ProjectCredentials', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, au...
Migration
identifier_name
0002_projectcredentials_websitecredentials.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals
from django.db import models, migrations import creditpiggy.core.models class Migration(migrations.Migration): dependencies = [ ('core', '0014_auto_20150616_1247'), ('api', '0001_initial'), ] operations = [ migrations.CreateModel( name='ProjectCredentials', ...
random_line_split
0002_projectcredentials_websitecredentials.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import creditpiggy.core.models class Migration(migrations.Migration):
('domains', models.TextField(default=b'[]')), ], ), ]
dependencies = [ ('core', '0014_auto_20150616_1247'), ('api', '0001_initial'), ] operations = [ migrations.CreateModel( name='ProjectCredentials', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=...
identifier_body
providers.js
module.exports = { us: [ '%s@email.uscc.net', '%s@message.alltel.com', '%s@message.ting.com', '%s@messaging.sprintpcs.com', '%s@mobile.celloneusa.com', '%s@msg.telus.com', '%s@paging.acswireless.com',
'%s@tmomail.net', '%s@txt.att.net', '%s@txt.windmobile.ca', '%s@vtext.com', '%s@text.republicwireless.com' //'%s@sms.edgewireless.com', // slow ], canada: [ '%s@blueskyfrog.com', '%s@bplmobile.com', '%s@cellularonewest.com', '%s@clearlydigital.com', '%s@comcastpcs.text...
'%s@pcs.rogers.com', '%s@qwestmp.com', '%s@sms.mycricket.com',
random_line_split
generator-config.ts
import { IGeneratorCallback, IGeneratorConfig, INormalizedOption, INormalizedOutputFile, ISettingsFlags, IStrictGeneratorConfig, NamingConvention } from "./interfaces"; import {Prop} from "../decorators"; import {Exception} from "../error/utils"; import {MakestuffErrors} from "../error/list"; export default cl...
}; } return normalizedConfig; } }
}; } if (typeof normalizedConfig.executeAfter !== "function") { normalizedConfig.executeAfter = function () {
random_line_split
generator-config.ts
import { IGeneratorCallback, IGeneratorConfig, INormalizedOption, INormalizedOutputFile, ISettingsFlags, IStrictGeneratorConfig, NamingConvention } from "./interfaces"; import {Prop} from "../decorators"; import {Exception} from "../error/utils"; import {MakestuffErrors} from "../error/list"; export default cl...
private normalizeConfig(config: IGeneratorConfig): IStrictGeneratorConfig { const normalizedConfig = {...config} as IStrictGeneratorConfig; normalizedConfig.description = config.description || ""; normalizedConfig.templatesRoot = config.templatesRoot || "./"; normalizedConfig.nami...
{ const validNamingValues = [ "camelCase", "pascalCase", "kebabCase", "trainCase", "snakeCase", "dotCase" ]; return validNamingValues.indexOf(convention) !== -1; }
identifier_body
generator-config.ts
import { IGeneratorCallback, IGeneratorConfig, INormalizedOption, INormalizedOutputFile, ISettingsFlags, IStrictGeneratorConfig, NamingConvention } from "./interfaces"; import {Prop} from "../decorators"; import {Exception} from "../error/utils"; import {MakestuffErrors} from "../error/list"; export default cl...
// Naming convention might be empty, it'll be initialized later by default value if (config.namingConvention !== void 0) { if (!this.checkNamingConvention(config.namingConvention)) { throw Exception( MakestuffErrors.invalidConfigValueError.id, ...
{ throw Exception( MakestuffErrors.invalidConfigValueError.id, "Name for generator is not specified" ); }
conditional_block
generator-config.ts
import { IGeneratorCallback, IGeneratorConfig, INormalizedOption, INormalizedOutputFile, ISettingsFlags, IStrictGeneratorConfig, NamingConvention } from "./interfaces"; import {Prop} from "../decorators"; import {Exception} from "../error/utils"; import {MakestuffErrors} from "../error/list"; export default cl...
(config: IGeneratorConfig): IStrictGeneratorConfig { const normalizedConfig = {...config} as IStrictGeneratorConfig; normalizedConfig.description = config.description || ""; normalizedConfig.templatesRoot = config.templatesRoot || "./"; normalizedConfig.namingConvention = config.namingC...
normalizeConfig
identifier_name
shared_memory.rs
//! TODO docs use std::ffi::CString; use std::slice; use types; pub struct Handle { shm_fd: ::detail::FileHandle, name: String, access_mode: types::AccessMode, } impl Handle { pub fn new(name: &str, create_mode: types::CreateMode, access_mode: types::AccessMode, ...
match Handle::remove(name) { Ok(_) => {}, Err(err) => assert!(false, "Can't remove file: {}", err), } } }
assert_eq!(data, &buffer[..data.len()]); }
random_line_split
shared_memory.rs
//! TODO docs use std::ffi::CString; use std::slice; use types; pub struct Handle { shm_fd: ::detail::FileHandle, name: String, access_mode: types::AccessMode, } impl Handle { pub fn new(name: &str, create_mode: types::CreateMode, access_mode: types::AccessMode, ...
(&self) -> &String { &self.name } pub fn access_mode(&self) -> types::AccessMode { self.access_mode.clone() } } impl Drop for Handle { fn drop(&mut self) { ::detail::close_handle(self.shm_fd) } } pub struct MappedRegion { _handle: Handle, ptr: *mut u8, size: u...
name
identifier_name
profileAppService.js
/******************************************************************************* * * Pentaho Data Profiling * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0...
() { this.profileId; this.lastViewedField; this.dataSourceUrl; this.dataSourceReference; this.statusMessages; this.operationError; this.treeViewService; this.profileManagementViewService; this.fieldOverviewViewService; this.metricConfigView...
ProfileAppService
identifier_name
profileAppService.js
/******************************************************************************* * * Pentaho Data Profiling * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0...
* ******************************************************************************/ define(["require", './services'], function (require, appServices) { appServices.factory('ProfileAppService', [ '$q', '$window', '$http', function ($q, $window, $http) { function ProfileAppService() { thi...
* distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.
random_line_split
profileAppService.js
/******************************************************************************* * * Pentaho Data Profiling * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0...
} ProfileAppService.prototype = { constructor: ProfileAppService, init: function (aTabularViewService, aTreeViewService, aProfileManagementViewService, aFieldOverviewViewService, aMetricConfigViewService, aDefaultMetricConfigViewService, aPro...
{ this.profileId; this.lastViewedField; this.dataSourceUrl; this.dataSourceReference; this.statusMessages; this.operationError; this.treeViewService; this.profileManagementViewService; this.fieldOverviewViewService; this.metricConfigViewSer...
identifier_body
profileAppService.js
/******************************************************************************* * * Pentaho Data Profiling * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0...
}, setLastViewedField: function (path) { profileAppService.lastViewedField = path; }, updateAvailableProfiles: function (profileTree) { profileAppService.profileManagementViewService.buildProfileManagementViewServiceTreeViewSchemas(profileTree); profileAppS...
{ profileAppService.dataSourceService.getCreate({ id: profileAppService.dataSourceReference.id, dataSourceProvider: profileAppService.dataSourceReference.dataSourceProvider }, function (createWrapper) { window.location.href = createWrapper.profileDataSou...
conditional_block
sequence-search-data.js
const dLog = console.debug; import EmberObject, { computed } from '@ember/object'; /** Allocate a unique id to each search / blast-result tab, for navigation. */ let searchId = 0; /** Data which backs each search instance initiated by sequence-search. * @param promise, seq, parent, searchType */ export default Em...
// maybe : this.set('startTime', startTime); this.set('timeId', startTime.toTimeString().split(' ')[0]); } , });
{ this._super(...arguments); /** an alternative is to use concat helper as in * components/panel/api-server-tab.hbs, but this seems simpler, * and avoids repeated calculation of a constant value. */ let id = searchId++, tabId = 'sequence-search-output-' + id; this.set('tabId', ta...
identifier_body
sequence-search-data.js
const dLog = console.debug; import EmberObject, { computed } from '@ember/object'; /** Allocate a unique id to each search / blast-result tab, for navigation. */ let searchId = 0; /** Data which backs each search instance initiated by sequence-search. * @param promise, seq, parent, searchType */ export default Em...
() { this._super(...arguments); /** an alternative is to use concat helper as in * components/panel/api-server-tab.hbs, but this seems simpler, * and avoids repeated calculation of a constant value. */ let id = searchId++, tabId = 'sequence-search-output-' + id; this.set('tabId',...
init
identifier_name
sequence-search-data.js
const dLog = console.debug; import EmberObject, { computed } from '@ember/object';
/** Allocate a unique id to each search / blast-result tab, for navigation. */ let searchId = 0; /** Data which backs each search instance initiated by sequence-search. * @param promise, seq, parent, searchType */ export default EmberObject.extend({ init() { this._super(...arguments); /** an alternative...
random_line_split
css_eb_tabmenu.ts
import {CONST as C} from "../css_const"; import {ICSSProperties} from "../css_types"; const TabMenuBase: ICSSProperties = { display: "flex", flexDirection: "column", fontFamily: "HelveticaNeue, Helvetica Neue, HelveticaNeueRoman, HelveticaNeue-Roman, Helvetica Neue Roman, TeXGyreHerosRegular, Helvetica, Tahoma, ...
}; const tabBase: ICSSProperties = { padding: "6px 5px 3px 5px", margin: "auto 5px 0px 5px", cursor: "pointer", }; const selectedTab: ICSSProperties = { borderBottom: `2px solid ${C.UnderlineColor}`, }; const tabWithTitleStyle: ICSSProperties = { display: "flex", alignItems: "center", justifyContent: "...
random_line_split
common.js
jQuery(function($) { getPreference(); $('#community-nav-collapse-toggle').on('click', function (e) { setPreference(); e.preventDefault(); if ($('#right-community-nav').hasClass('hide')) { expandMenu(); } else { collapseMenu(); } }); func...
$('.navbar .dropdown').hover(function() { $(this).find('.dropdown-menu').first().stop(true, true).delay().slideDown(); }, function() { $(this).find('.dropdown-menu').first().stop(true, true).delay().slideUp(); }); $('.navbar .dropdown > a').click(function(){ location.href = th...
{ $('#community-nav-collapse-toggle').addClass('active'); $('#community-nav-menu-icon').addClass('active'); $('#right-community-nav').addClass('span3').removeClass('hide'); $('#main').removeClass('span9').addClass('span6'); }
identifier_body
common.js
jQuery(function($) { getPreference(); $('#community-nav-collapse-toggle').on('click', function (e) { setPreference(); e.preventDefault(); if ($('#right-community-nav').hasClass('hide')) { expandMenu(); } else { collapseMenu(); } }); func...
} function setPreference () { var preference = ($('#right-community-nav').hasClass('hide') ? 'expanded' : 'collapsed'); createCookie('community_' + COMMUNITY_ID + '_nav_preference', preference, 365); } function collapseMenu() { $('#community-nav-collapse-toggle').removeClass('...
{ expandMenu(); }
conditional_block
common.js
jQuery(function($) { getPreference(); $('#community-nav-collapse-toggle').on('click', function (e) { setPreference(); e.preventDefault(); if ($('#right-community-nav').hasClass('hide')) { expandMenu(); } else { collapseMenu(); } }); func...
function setPreference () { var preference = ($('#right-community-nav').hasClass('hide') ? 'expanded' : 'collapsed'); createCookie('community_' + COMMUNITY_ID + '_nav_preference', preference, 365); } function collapseMenu() { $('#community-nav-collapse-toggle').removeClass('active')...
} else { expandMenu(); } }
random_line_split
common.js
jQuery(function($) { getPreference(); $('#community-nav-collapse-toggle').on('click', function (e) { setPreference(); e.preventDefault(); if ($('#right-community-nav').hasClass('hide')) { expandMenu(); } else { collapseMenu(); } }); func...
() { var preference = ($('#right-community-nav').hasClass('hide') ? 'expanded' : 'collapsed'); createCookie('community_' + COMMUNITY_ID + '_nav_preference', preference, 365); } function collapseMenu() { $('#community-nav-collapse-toggle').removeClass('active'); $('#main').remov...
setPreference
identifier_name
HeaderTransformer.ts
import isUndefined from 'lodash.isundefined'; import isFunction from 'lodash.isfunction'; import uniq from 'lodash.uniq'; import groupBy from 'lodash.groupby'; import { ParserOptions } from '../ParserOptions'; import { HeaderArray, HeaderTransformFunction, Row, RowArray, RowMap, RowValidationRes...
} this.processedFirstRow = true; return false; } if (!this.receivedHeaders && Array.isArray(row)) { if (this.headersTransform) { this.setHeaders(this.headersTransform(row)); } else if (this.shouldUseFirstRow) { t...
random_line_split
HeaderTransformer.ts
import isUndefined from 'lodash.isundefined'; import isFunction from 'lodash.isfunction'; import uniq from 'lodash.uniq'; import groupBy from 'lodash.groupby'; import { ParserOptions } from '../ParserOptions'; import { HeaderArray, HeaderTransformFunction, Row, RowArray, RowMap, RowValidationRes...
isValid: false, reason: `Column header mismatch expected: ${this.headersLength} columns got: ${row.length}`, }; } return { row: this.mapHeaders(row), isValid: true }; } private mapHeaders(row: RowArray<string>): O { const rowMap: RowMap = {};...
{ if (!this.headers) { return { row: (row as never) as O, isValid: true }; } const { parserOptions } = this; if (!parserOptions.discardUnmappedColumns && row.length > this.headersLength) { if (!parserOptions.strictColumnHandling) { throw new Error(...
identifier_body
HeaderTransformer.ts
import isUndefined from 'lodash.isundefined'; import isFunction from 'lodash.isfunction'; import uniq from 'lodash.uniq'; import groupBy from 'lodash.groupby'; import { ParserOptions } from '../ParserOptions'; import { HeaderArray, HeaderTransformFunction, Row, RowArray, RowMap, RowValidationRes...
this.processedFirstRow = true; return false; } if (!this.receivedHeaders && Array.isArray(row)) { if (this.headersTransform) { this.setHeaders(this.headersTransform(row)); } else if (this.shouldUseFirstRow) { this.setHeader...
{ throw new Error('Error renaming headers: new headers must be provided in an array'); }
conditional_block
HeaderTransformer.ts
import isUndefined from 'lodash.isundefined'; import isFunction from 'lodash.isfunction'; import uniq from 'lodash.uniq'; import groupBy from 'lodash.groupby'; import { ParserOptions } from '../ParserOptions'; import { HeaderArray, HeaderTransformFunction, Row, RowArray, RowMap, RowValidationRes...
(row: Row): boolean { const { parserOptions } = this; if (!this.headersTransform && parserOptions.renameHeaders && !this.processedFirstRow) { if (!this.receivedHeaders) { throw new Error('Error renaming headers: new headers must be provided in an array'); } ...
shouldMapRow
identifier_name
index.d.ts
// Type definitions for passport-google-oauth 1.0.3 // Project: https://github.com/jaredhanson/passport-google-oauth // Definitions by: James Roland Cabresos <https://github.com/staticfunction> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// <reference types="passport"...
interface VerifyFunction { (error: any, user?: any, msg?: VerifyOptions): void; } declare class OAuthStrategy implements passport.Strategy { constructor( options: IOAuthStrategyOption, verify: ( accessToken: string, refreshToken: string, profile: Profile, ...
random_line_split
index.d.ts
// Type definitions for passport-google-oauth 1.0.3 // Project: https://github.com/jaredhanson/passport-google-oauth // Definitions by: James Roland Cabresos <https://github.com/staticfunction> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// <reference types="passport"...
implements passport.Strategy { constructor( options: IOAuthStrategyOption, verify: ( accessToken: string, refreshToken: string, profile: Profile, done: VerifyFunction ) => void ); name: string; authenticate: (req: express.Request, ...
OAuthStrategy
identifier_name
paths.rs
// Copyright 2017 Thorben Kroeger. // Dual-licensed MIT and Apache 2.0 (see LICENSE files for details). use std::path::{Path, PathBuf}; pub struct CommonPrefix { pub prefix: PathBuf, pub suffix1: PathBuf, pub suffix2: PathBuf } pub fn common_prefix(path1: &Path, path2: &Path) -> CommonPrefix { let mu...
_ => { break; } } } let common_prefix = common_prefix.iter().map(|s| s.as_os_str()).collect::<PathBuf>(); let r1 = a.map(|s| s.as_os_str()).collect::<PathBuf>(); let r2 = b.map(|s| s.as_os_str()).collect::<PathBuf>(); CommonPrefix { prefix: common_prefix, suffix...
{ if e1 != e2 { break; } common_prefix.push(e1); a.next(); b.next(); continue; }
conditional_block
paths.rs
// Copyright 2017 Thorben Kroeger. // Dual-licensed MIT and Apache 2.0 (see LICENSE files for details). use std::path::{Path, PathBuf}; pub struct CommonPrefix { pub prefix: PathBuf, pub suffix1: PathBuf, pub suffix2: PathBuf } pub fn
(path1: &Path, path2: &Path) -> CommonPrefix { let mut a = path1.components().peekable(); let mut b = path2.components().peekable(); let mut common_prefix = vec![]; loop { match (a.peek(), b.peek()) { (Some(&e1), Some(&e2)) => { if e1 != e2 { ...
common_prefix
identifier_name
paths.rs
// Copyright 2017 Thorben Kroeger. // Dual-licensed MIT and Apache 2.0 (see LICENSE files for details). use std::path::{Path, PathBuf}; pub struct CommonPrefix { pub prefix: PathBuf, pub suffix1: PathBuf, pub suffix2: PathBuf } pub fn common_prefix(path1: &Path, path2: &Path) -> CommonPrefix { let mu...
if e1 != e2 { break; } common_prefix.push(e1); a.next(); b.next(); continue; } _ => { break; } } } let common_prefix = common_prefix.iter().map(|s| s.as_os_str()).co...
match (a.peek(), b.peek()) { (Some(&e1), Some(&e2)) => {
random_line_split
paths.rs
// Copyright 2017 Thorben Kroeger. // Dual-licensed MIT and Apache 2.0 (see LICENSE files for details). use std::path::{Path, PathBuf}; pub struct CommonPrefix { pub prefix: PathBuf, pub suffix1: PathBuf, pub suffix2: PathBuf } pub fn common_prefix(path1: &Path, path2: &Path) -> CommonPrefix
let r1 = a.map(|s| s.as_os_str()).collect::<PathBuf>(); let r2 = b.map(|s| s.as_os_str()).collect::<PathBuf>(); CommonPrefix { prefix: common_prefix, suffix1: r1, suffix2: r2 } }
{ let mut a = path1.components().peekable(); let mut b = path2.components().peekable(); let mut common_prefix = vec![]; loop { match (a.peek(), b.peek()) { (Some(&e1), Some(&e2)) => { if e1 != e2 { break; } comm...
identifier_body
main.py
#!/usr/bin/env python from . import dentist from .watchers import LogNotify, Notifier, Poller import logging import os import sys def parse(): from optparse import OptionParser parser = OptionParser() parser.add_option('-d', '--daemonize', dest='daemonize', action='store_true', defa...
poller = Poller() # Setup the log readers # Add the customized prefixes clr = dentist.CombinedLogReader clr.add_prefix(*options.prefixes) # Set the root of the home directories elr = dentist.ErrorLogReader elr.configure(homedir_root=options.parent_user_dir) notifier = Notifier() ...
dentist.LogReader.set_output_directory(options.output_dir)
conditional_block
main.py
#!/usr/bin/env python from . import dentist from .watchers import LogNotify, Notifier, Poller import logging import os import sys def parse():
def main(): options, args = parse() log_kwargs = { 'level': logging.INFO, 'format': '%(asctime)-15s %(levelname)-8s %(message)s', } if options.log_file is not None: log_kwargs['filename'] = options.log_file logging.basicConfig(**log_kwargs) access_logs = options.ac...
from optparse import OptionParser parser = OptionParser() parser.add_option('-d', '--daemonize', dest='daemonize', action='store_true', default=False) parser.add_option('-a', '--access_log', dest='access_logs', action='append', default=[]) parser.add_option('-...
identifier_body
main.py
#!/usr/bin/env python from . import dentist from .watchers import LogNotify, Notifier, Poller import logging import os import sys def parse(): from optparse import OptionParser parser = OptionParser() parser.add_option('-d', '--daemonize', dest='daemonize', action='store_true', defa...
return parser.parse_args() def main(): options, args = parse() log_kwargs = { 'level': logging.INFO, 'format': '%(asctime)-15s %(levelname)-8s %(message)s', } if options.log_file is not None: log_kwargs['filename'] = options.log_file logging.basicConfig(**log_kwargs)...
default=None) parser.add_option('-l', '--log_file', dest='log_file', metavar='PATH', default=None)
random_line_split
main.py
#!/usr/bin/env python from . import dentist from .watchers import LogNotify, Notifier, Poller import logging import os import sys def
(): from optparse import OptionParser parser = OptionParser() parser.add_option('-d', '--daemonize', dest='daemonize', action='store_true', default=False) parser.add_option('-a', '--access_log', dest='access_logs', action='append', default=[]) parser.add_o...
parse
identifier_name
p3.py
# $Id: p3.py,v 1.2 2003/11/18 19:04:03 phr Exp phr $ # Simple p3 encryption "algorithm": it's just SHA used as a stream # cipher in output feedback mode. # Author: Paul Rubin, Fort GNOX Cryptography, <phr-crypto at nightsong.com>. # Algorithmic advice from David Wagner, Richard Parker, Bryan # Olson, and Paul Crowley...
def _hmac(msg, key): if len(key)>64: key=sha.new(key).digest() ki = (translate(key,_itrans)+_ipad)[:64] # inner ko = (translate(key,_otrans)+_opad)[:64] # outer return sha.new(ko+sha.new(ki+msg).digest()).digest() # # benchmark and unit test # def _time_p3(n=1000,len=20): plain="a"*len ...
global _ipad, _opad, _itrans, _otrans _itrans = array('B',[0]*256) _otrans = array('B',[0]*256) for i in xrange(256): _itrans[i] = i ^ 0x36 _otrans[i] = i ^ 0x5c _itrans = _itrans.tostring() _otrans = _otrans.tostring() _ipad = '\x36'*64 _opad = '\x5c'*64
identifier_body
p3.py
# $Id: p3.py,v 1.2 2003/11/18 19:04:03 phr Exp phr $ # Simple p3 encryption "algorithm": it's just SHA used as a stream # cipher in output feedback mode. # Author: Paul Rubin, Fort GNOX Cryptography, <phr-crypto at nightsong.com>. # Algorithmic advice from David Wagner, Richard Parker, Bryan # Olson, and Paul Crowley...
(str): return sha.new(str).digest() _ivlen = 16 _maclen = 8 _state = _hash(`time()`) try: import os _pid = `os.getpid()` except ImportError, AttributeError: _pid = '' def _expand_key(key, clen): blocks = (clen+19)/20 xkey=[] seed=key for i in xrange(blocks): seed=sha.new(key+seed)...
_hash
identifier_name
p3.py
# $Id: p3.py,v 1.2 2003/11/18 19:04:03 phr Exp phr $ # Simple p3 encryption "algorithm": it's just SHA used as a stream # cipher in output feedback mode. # Author: Paul Rubin, Fort GNOX Cryptography, <phr-crypto at nightsong.com>. # Algorithmic advice from David Wagner, Richard Parker, Bryan # Olson, and Paul Crowley...
_state = H('update2'+_state+nonce) k_enc, k_auth = H('enc'+key+nonce), H('auth'+key+nonce) n=len(plain) # cipher size not counting IV stream = array('L', plain+'0000'[n&3:]) # pad to fill 32-bit words xkey = _expand_key(k_enc, n+4) for i in xrange(len(stream)): st...
# two separate Python instances at the same time), you might get # identical ciphertexts for the identical plaintexts, which would # be a security failure in some applications. Be careful. nlist = [`time()`, _pid, _state, `len(plain)`,plain, key] nonce = H(join(nlist,','))[:_ivlen]
random_line_split
p3.py
# $Id: p3.py,v 1.2 2003/11/18 19:04:03 phr Exp phr $ # Simple p3 encryption "algorithm": it's just SHA used as a stream # cipher in output feedback mode. # Author: Paul Rubin, Fort GNOX Cryptography, <phr-crypto at nightsong.com>. # Algorithmic advice from David Wagner, Richard Parker, Bryan # Olson, and Paul Crowley...
ct = nonce + stream.tostring()[:n] auth = _hmac(ct, k_auth) return ct + auth[:_maclen] def p3_decrypt(cipher,key): H = _hash n=len(cipher)-_ivlen-_maclen # length of ciphertext if n < 0: raise CryptError, "invalid ciphertext" nonce,stream,auth = \ cipher[:_ivlen], ciph...
stream[i] = stream[i] ^ xkey[i]
conditional_block
MessageProcessor.js
/** * Copyright (C) 2015 Austin Peterson * * 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 ...
*/ MessageProcessor.prototype.executeAllResponders = function(context) { var things = context.fullText.split(" "); var responses = 0; var runs = {}; for (var i = 0; i < things.length && responses < 3; i++) { // This loop runs through all handlers and attempts to execute them. this.handl...
/** * Execute all responders for a given context. * @param {Context} context The context to execute responders for.
random_line_split
MessageProcessor.js
/** * Copyright (C) 2015 Austin Peterson * * 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 ...
/** * Initialize this MessageProcessor. * @param {logger} logger The logger to use. * @param {Object} AKP48 The running instance of AKP48. */ MessageProcessor.prototype.initialize = function (logger, AKP48) { this.handlers = require('./MessageResponders')(logger, false); this.fullMsgHandlers = requir...
{ this.initialize(logger, AKP48); this.process(context); }
identifier_body
MessageProcessor.js
/** * Copyright (C) 2015 Austin Peterson * * 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 ...
(context, logger, AKP48) { this.initialize(logger, AKP48); this.process(context); } /** * Initialize this MessageProcessor. * @param {logger} logger The logger to use. * @param {Object} AKP48 The running instance of AKP48. */ MessageProcessor.prototype.initialize = function (logger, AKP48) { this....
MessageProcessor
identifier_name
MessageProcessor.js
/** * Copyright (C) 2015 Austin Peterson * * 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 ...
//if the handler's regex matches, execute handler. if (things[i].search(handler.regex) != -1 && (!handler.limit || runs[handler] < handler.limit)) { handler.execute(things[i], context); runs[handler]++; responses++; } retu...
{ runs[handler] = 0; }
conditional_block
mapper_data.py
from modelmapper.declarations import Mapper, Field from modelmapper.qt.fields import QLineEditAccessor class String(QLineEditAccessor):
class Integer(QLineEditAccessor): def get_value(self): return int(self.widget.text()) def set_value(self, value): self.widget.setText(int(value)) def get_child_x_mapper(x): return { '{}_link'.format(x): (x, 'val_{}'.format(x)) } def get_d_mapper(): return { 'e...
def get_value(self): return str(self.widget.text()) def set_value(self, value): self.widget.setText(str(value))
identifier_body
mapper_data.py
from modelmapper.declarations import Mapper, Field from modelmapper.qt.fields import QLineEditAccessor class String(QLineEditAccessor): def get_value(self): return str(self.widget.text()) def set_value(self, value): self.widget.setText(str(value)) class Integer(QLineEditAccessor): def...
(self): return int(self.widget.text()) def set_value(self, value): self.widget.setText(int(value)) def get_child_x_mapper(x): return { '{}_link'.format(x): (x, 'val_{}'.format(x)) } def get_d_mapper(): return { 'expediente_link': Mapper('c[0]', 'val_c[0]', get_child_x...
get_value
identifier_name
mapper_data.py
from modelmapper.declarations import Mapper, Field from modelmapper.qt.fields import QLineEditAccessor class String(QLineEditAccessor): def get_value(self): return str(self.widget.text())
self.widget.setText(str(value)) class Integer(QLineEditAccessor): def get_value(self): return int(self.widget.text()) def set_value(self, value): self.widget.setText(int(value)) def get_child_x_mapper(x): return { '{}_link'.format(x): (x, 'val_{}'.format(x)) } def ...
def set_value(self, value):
random_line_split
index.js
var Logger = require("./Logger.js"); var Level = require("./Level.js"); var PrintPattern = require("./PrintPattern.js"); module.exports = (function() { /* STATE VARIABLES */ // OUT configuration var OUT_INTERVAL = undefined; // 1sec var OUT_INTERVAL_TIMEOUT = 1000; // 1sec var OUT_SIZE = 1000; // logger object...
// using appender if (logger_appenders != undefined) { for (a in logger_appenders) { var appender = logger_appenders[a]; appender.write(record); } } } } } records.splice(0, OUT_SIZE); // clean interval identifier OUT_INTERVAL = undefined; // if still remain an...
} // getting appender list by logger var logger_appenders = level_appenders[logger_name];
random_line_split
index.js
var Logger = require("./Logger.js"); var Level = require("./Level.js"); var PrintPattern = require("./PrintPattern.js"); module.exports = (function() { /* STATE VARIABLES */ // OUT configuration var OUT_INTERVAL = undefined; // 1sec var OUT_INTERVAL_TIMEOUT = 1000; // 1sec var OUT_SIZE = 1000; // logger object...
// getting appender list by logger var logger_appenders = level_appenders[logger_name]; // using appender if (logger_appenders != undefined) { for (a in logger_appenders) { var appender = logger_appenders[a]; appender.write(record); } } } } } records.spli...
{ logger_name = logger_name + "." + logger_composition[lc]; }
conditional_block
trait-inheritance-num.rs
// xfail-fast // 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 // <...
<T:NumExt>(n: &T) -> bool { *n > NumCast::from(1).unwrap() } fn greater_than_one_float<T:FloatExt>(n: &T) -> bool { *n > NumCast::from(1).unwrap() } pub fn main() {}
greater_than_one
identifier_name
trait-inheritance-num.rs
// xfail-fast // 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 // <...
pub fn main() {}
{ *n > NumCast::from(1).unwrap() }
identifier_body
trait-inheritance-num.rs
// xfail-fast // 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 // <...
pub fn main() {}
random_line_split
post_command.py
# -*- encoding: utf-8 -*- ################################################################################ # TuiterPy - A Python Command Line Social Network Application # Copyright (C) 2016 Sergio Trujillo (sergiotrujillomartinez@gmail.com) # # This program is free software: you can redistribute it and/or mod...
(Command): def __init__(self, pattern, printer, add_post): super(PostCommand, self).__init__(pattern) self.printer = printer self.add_post = add_post def process(self): match = self.get_match() self.add_post.do_it(match.group(1), match.group(2)) return self.prin...
PostCommand
identifier_name
post_command.py
# -*- encoding: utf-8 -*- ################################################################################ # TuiterPy - A Python Command Line Social Network Application # Copyright (C) 2016 Sergio Trujillo (sergiotrujillomartinez@gmail.com) # # This program is free software: you can redistribute it and/or mod...
from command import Command class PostCommand(Command): def __init__(self, pattern, printer, add_post): super(PostCommand, self).__init__(pattern) self.printer = printer self.add_post = add_post def process(self): match = self.get_match() self.add_post.do_it(match.gro...
random_line_split
post_command.py
# -*- encoding: utf-8 -*- ################################################################################ # TuiterPy - A Python Command Line Social Network Application # Copyright (C) 2016 Sergio Trujillo (sergiotrujillomartinez@gmail.com) # # This program is free software: you can redistribute it and/or mod...
def __init__(self, pattern, printer, add_post): super(PostCommand, self).__init__(pattern) self.printer = printer self.add_post = add_post def process(self): match = self.get_match() self.add_post.do_it(match.group(1), match.group(2)) return self.printer
identifier_body
CharRec.py
#!/usr/bin/env python """CharRec.py: Runs a suite of ML algorithms on a character dataset""" import logging import numpy as np import pandas as pd from skimage import io, filters, exposure, morphology from sklearn import tree, ensemble, neighbors, neural_network, multiclass from sklearn.model_selection import cross...
log_and_print("Reading test data") labels_info_test = pd.read_csv("{0}/testLabels.csv".format(path)) x_test = read_data("test", labels_info_test, image_size, path) for algo in ["DT", "RF", "KNN", "MLP"]: log_and_print("Training the %s classifier" % algo) model = train(x_train, y_train, ...
y_train = list(map(ord, labels_info_train["Class"])) y_train = np.array(y_train) # Read testing data
random_line_split
CharRec.py
#!/usr/bin/env python """CharRec.py: Runs a suite of ML algorithms on a character dataset""" import logging import numpy as np import pandas as pd from skimage import io, filters, exposure, morphology from sklearn import tree, ensemble, neighbors, neural_network, multiclass from sklearn.model_selection import cross...
(): path = "C:/Dev/Data" image_size = 400 # 20 x 20 pixels # Read training data log_and_print("Reading training data") labels_info_train = pd.read_csv("{0}/trainLabels.csv".format(path)) x_train = read_data("train", labels_info_train, image_size, path) y_train = list(map(ord, labels_info_...
main
identifier_name
CharRec.py
#!/usr/bin/env python """CharRec.py: Runs a suite of ML algorithms on a character dataset""" import logging import numpy as np import pandas as pd from skimage import io, filters, exposure, morphology from sklearn import tree, ensemble, neighbors, neural_network, multiclass from sklearn.model_selection import cross...
main()
conditional_block
CharRec.py
#!/usr/bin/env python """CharRec.py: Runs a suite of ML algorithms on a character dataset""" import logging import numpy as np import pandas as pd from skimage import io, filters, exposure, morphology from sklearn import tree, ensemble, neighbors, neural_network, multiclass from sklearn.model_selection import cross...
def read_data(data_type, labels_info, image_size, path, preprocess=True): """ :param data_type: 'train' or 'test' data :param labels_info: List of file names with labels :param image_size: No. of image pixels :param path: Path where training or test data resides :param preprocess: a flag to e...
""" :param path: Image path :return: processed image """ image = io.imread(path, as_grey=True) image = exposure.adjust_sigmoid(image) image = filters.threshold_adaptive(image, 101) chull = np.count_nonzero(morphology.convex_hull_image(image)) if chull > 380: image = np.invert(ima...
identifier_body
__main__.py
import sys ## Make sure pyqtgraph is importable p = os.path.dirname(os.path.abspath(__file__)) p = os.path.join(p, '..', '..') sys.path.insert(0, p) from pyqtgraph.Qt import QtCore, QtGui from DockArea import * from Dock import * app = QtGui.QApplication([]) win = QtGui.QMainWindow() area = DockArea() win.setCentra...
for d in [d1, d2, d3, d4, d5]: w = QtGui.QWidget() l = QtGui.QVBoxLayout() w.setLayout(l) btns = [] for i in range(4): btns.append(QtGui.QPushButton("%s Button %d"%(d.name(), i))) l.addWidget(btns[-1]) d.w = (w, l, btns) d.addWidget(w) import pyqtgraph as pg p = pg.PlotWi...
d3.hideTitleBar() print "===build complete===="
random_line_split
__main__.py
import sys ## Make sure pyqtgraph is importable p = os.path.dirname(os.path.abspath(__file__)) p = os.path.join(p, '..', '..') sys.path.insert(0, p) from pyqtgraph.Qt import QtCore, QtGui from DockArea import * from Dock import * app = QtGui.QApplication([]) win = QtGui.QMainWindow() area = DockArea() win.setCentra...
import pyqtgraph as pg p = pg.PlotWidget() d6.addWidget(p) print "===widgets added===" #s = area.saveState() #print "\n\n-------restore----------\n\n" #area.restoreState(s) s = None def save(): global s s = area.saveState() def load(): global s area.restoreState(s) #d6.container().setCur...
w = QtGui.QWidget() l = QtGui.QVBoxLayout() w.setLayout(l) btns = [] for i in range(4): btns.append(QtGui.QPushButton("%s Button %d"%(d.name(), i))) l.addWidget(btns[-1]) d.w = (w, l, btns) d.addWidget(w)
conditional_block
__main__.py
import sys ## Make sure pyqtgraph is importable p = os.path.dirname(os.path.abspath(__file__)) p = os.path.join(p, '..', '..') sys.path.insert(0, p) from pyqtgraph.Qt import QtCore, QtGui from DockArea import * from Dock import * app = QtGui.QApplication([]) win = QtGui.QMainWindow() area = DockArea() win.setCentra...
def load(): global s area.restoreState(s) #d6.container().setCurrentIndex(0) #d2.label.setTabPos(40) #win2 = QtGui.QMainWindow() #area2 = DockArea() #win2.setCentralWidget(area2) #win2.resize(800,800) win.show() #win2.show()
global s s = area.saveState()
identifier_body
__main__.py
import sys ## Make sure pyqtgraph is importable p = os.path.dirname(os.path.abspath(__file__)) p = os.path.join(p, '..', '..') sys.path.insert(0, p) from pyqtgraph.Qt import QtCore, QtGui from DockArea import * from Dock import * app = QtGui.QApplication([]) win = QtGui.QMainWindow() area = DockArea() win.setCentra...
(): global s area.restoreState(s) #d6.container().setCurrentIndex(0) #d2.label.setTabPos(40) #win2 = QtGui.QMainWindow() #area2 = DockArea() #win2.setCentralWidget(area2) #win2.resize(800,800) win.show() #win2.show()
load
identifier_name
SampleApplicationWebPart.ts
import * as React from 'react'; import * as ReactDom from 'react-dom'; import { Version } from '@microsoft/sp-core-library'; import { IPropertyPaneConfiguration, PropertyPaneTextField } from '@microsoft/sp-property-pane'; import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base'; import * as stri...
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { groups: [ { groupFields: [ PropertyPaneTextField('endpoint', { label: strings.EndpointFieldLabel }) ...
{ return Version.parse('1.0'); }
identifier_body
SampleApplicationWebPart.ts
import * as React from 'react'; import * as ReactDom from 'react-dom'; import { Version } from '@microsoft/sp-core-library'; import { IPropertyPaneConfiguration, PropertyPaneTextField } from '@microsoft/sp-property-pane'; import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base'; import * as stri...
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { groups: [ { groupFields: [ PropertyPaneTextField('endpoint', { label: strings.EndpointFieldLabel }) ...
random_line_split
SampleApplicationWebPart.ts
import * as React from 'react'; import * as ReactDom from 'react-dom'; import { Version } from '@microsoft/sp-core-library'; import { IPropertyPaneConfiguration, PropertyPaneTextField } from '@microsoft/sp-property-pane'; import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base'; import * as stri...
(): void { ReactDom.unmountComponentAtNode(this.domElement); } protected get dataVersion(): Version { return Version.parse('1.0'); } protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { groups: [ { ...
onDispose
identifier_name
useragent.js
the browser engine at compile-time. * @type {boolean} * @private */ goog.userAgent.BROWSER_KNOWN_ = goog.userAgent.ASSUME_IE || goog.userAgent.ASSUME_EDGE || goog.userAgent.ASSUME_GECKO || goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_OPERA; /...
return goog.userAgent.WEBKIT && goog.labs.userAgent.util.matchUserAgent('Mobile'); }; /** * Whether the user agent is running on a mobile device. * * TODO(nnaze): Consider deprecating MOBILE when labs.userAgent * is promoted as the gecko/webkit logic is likely inaccurate. * * @type {boolean} */ go...
* @private */ goog.userAgent.isMobile_ = function() {
random_line_split
useragent.js
|| goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD; /** * Whether the user agent is running on a Macintosh operating system. * @type {boolean} */ goog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_MAC : goog.labs.userAgent.platform.isMacintosh(); /** * Whether th...
{ return undefined; }
conditional_block
audit.ts
import { Operator } from '../Operator'; import { Subscriber } from '../Subscriber'; import { Observable, SubscribableOrPromise } from '../Observable'; import { Subscription, TeardownLogic } from '../Subscription'; import { tryCatch } from '../util/tryCatch'; import { errorObject } from '../util/errorObject'; import { ...
* @extends {Ignored} */ class AuditSubscriber<T, R> extends OuterSubscriber<T, R> { private value: T; private hasValue: boolean = false; private throttled: Subscription; constructor(destination: Subscriber<T>, private durationSelector: (value: T) => SubscribableOrPromise<any>) { super(dest...
/** * We need this JSDoc comment for affecting ESDoc. * @ignore
random_line_split