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
__init__.py
from __future__ import print_function from sqlalchemy import create_engine from sqlalchemy.pool import NullPool import sqlalchemy import sys # This value must be incremented after schema changes on replicated tables! SCHEMA_VERSION = 1 engine = None def init_db_engine(connect_str): global engine engine = cre...
(sql_file_path): with open(sql_file_path) as sql: connection = engine.connect() connection.connection.set_isolation_level(0) lines = sql.read().splitlines() try: for line in lines: # TODO: Not a great way of removing comments. The alternative is to catch ...
run_sql_script_without_transaction
identifier_name
__init__.py
from __future__ import print_function from sqlalchemy import create_engine from sqlalchemy.pool import NullPool import sqlalchemy import sys # This value must be incremented after schema changes on replicated tables! SCHEMA_VERSION = 1 engine = None def init_db_engine(connect_str): global engine engine = cre...
except sqlalchemy.exc.ProgrammingError as e: print("Error: {}".format(e)) return False finally: connection.connection.set_isolation_level(1) connection.close() return True
if line and not line.startswith("--"): connection.execute(line)
conditional_block
__init__.py
from __future__ import print_function from sqlalchemy import create_engine from sqlalchemy.pool import NullPool import sqlalchemy import sys # This value must be incremented after schema changes on replicated tables! SCHEMA_VERSION = 1
engine = None def init_db_engine(connect_str): global engine engine = create_engine(connect_str, poolclass=NullPool) def run_sql_script(sql_file_path): with open(sql_file_path) as sql: connection = engine.connect() connection.execute(sql.read()) connection.close() def run_sql_scri...
random_line_split
__init__.py
from __future__ import print_function from sqlalchemy import create_engine from sqlalchemy.pool import NullPool import sqlalchemy import sys # This value must be incremented after schema changes on replicated tables! SCHEMA_VERSION = 1 engine = None def init_db_engine(connect_str):
def run_sql_script(sql_file_path): with open(sql_file_path) as sql: connection = engine.connect() connection.execute(sql.read()) connection.close() def run_sql_script_without_transaction(sql_file_path): with open(sql_file_path) as sql: connection = engine.connect() con...
global engine engine = create_engine(connect_str, poolclass=NullPool)
identifier_body
tests.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import mock import six import time from exam import fixture, patcher from sentry.quotas.redis import ( is_rate_limited, RedisQuota, ) from sentry.testutils import TestCase from sentry.utils.redis import clusters def
(): now = int(time.time()) cluster = clusters.get('default') client = cluster.get_local_client(six.next(iter(cluster.hosts))) # The item should not be rate limited by either key. assert list(map(bool, is_rate_limited(client, ('foo', 'bar'), (1, now + 60, 2, now + 120)))) == \ [False, False...
test_is_rate_limited_script
identifier_name
tests.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import mock import six import time from exam import fixture, patcher from sentry.quotas.redis import ( is_rate_limited, RedisQuota, ) from sentry.testutils import TestCase from sentry.utils.redis import clusters def test_is_rate_limited_script...
@mock.patch('sentry.quotas.redis.is_rate_limited', return_value=(False, False)) def test_is_not_limited_without_rejections(self, is_rate_limited): self.get_organization_quota.return_value = (100, 60) self.get_project_quota.return_value = (200, 60) assert not self.quota.is_rate_limited(s...
result = self.quota.is_rate_limited(self.project) assert not is_rate_limited.called assert not result.is_limited
random_line_split
tests.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import mock import six import time from exam import fixture, patcher from sentry.quotas.redis import ( is_rate_limited, RedisQuota, ) from sentry.testutils import TestCase from sentry.utils.redis import clusters def test_is_rate_limited_script...
@mock.patch('sentry.quotas.redis.is_rate_limited', return_value=(False, False)) def test_is_not_limited_without_rejections(self, is_rate_limited): self.get_organization_quota.return_value = (100, 60) self.get_project_quota.return_value = (200, 60) assert not self.quota.is_rate_limited(...
result = self.quota.is_rate_limited(self.project) assert not is_rate_limited.called assert not result.is_limited
identifier_body
main.component.js
import React, { Component } from 'react' import { connect } from 'react-redux' import {Link} from 'react-router-dom' import Images from '../widget/images' import Button from '../widget/button' import Icon from '../widget/icon' import { setInactiveLoading, setActiveLoading } from '../../action/LoadingAction' import { se...
else { this.setState({classDiv : 'great animated fadeOut'}) } } action(url) { this.context.router.history.push(url) } render() { return ( <div className={this.state.classDiv}> <Images src='coffee-vector.png' class='logo inline float-...
{ setTimeout(() => { this.setState({classDiv : 'great animated fadeIn'}) }, 500) }
conditional_block
main.component.js
import React, { Component } from 'react' import { connect } from 'react-redux' import {Link} from 'react-router-dom' import Images from '../widget/images' import Button from '../widget/button' import Icon from '../widget/icon' import { setInactiveLoading, setActiveLoading } from '../../action/LoadingAction' import { se...
componentWillReceiveProps(next) { if(next.loading == false) { setTimeout(() => { this.setState({classDiv : 'great animated fadeIn'}) }, 500) } else { this.setState({classDiv : 'great animated fadeOut'}) } } action(url) { ...
{ this.props.active() }
identifier_body
main.component.js
import React, { Component } from 'react' import { connect } from 'react-redux' import {Link} from 'react-router-dom' import Images from '../widget/images' import Button from '../widget/button' import Icon from '../widget/icon' import { setInactiveLoading, setActiveLoading } from '../../action/LoadingAction' import { se...
this.props.inactive() }, 1000) this.props.setActive(0) } componentDidMount() { document.title = 'Main Pages' document.body.removeAttribute("style"); let style = this.props.menu[0].style for(let a in style) { document.body.style[a] = styl...
} } componentWillMount() { setTimeout(() => {
random_line_split
main.component.js
import React, { Component } from 'react' import { connect } from 'react-redux' import {Link} from 'react-router-dom' import Images from '../widget/images' import Button from '../widget/button' import Icon from '../widget/icon' import { setInactiveLoading, setActiveLoading } from '../../action/LoadingAction' import { se...
extends Component { static contextTypes = { router: React.PropTypes.object.isRequired }; constructor(props, context) { super(props, context) this.state = { classDiv : `great ${this.props.loading ? ' animated fadeOut' : ' animated fadeIn' }` } } componen...
MainComponent
identifier_name
typeck-default-trait-impl-cross-crate-coherence.rs
// Copyright 2015 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 ...
struct C; struct D<T>(T); impl DefaultedTrait for Box<C> { } //~ ERROR E0321 impl DefaultedTrait for lib::Something<C> { } //~ ERROR E0117 impl DefaultedTrait for D<C> { } // OK fn main() { }
impl !DefaultedTrait for (B,) { } //~ ERROR E0117
random_line_split
typeck-default-trait-impl-cross-crate-coherence.rs
// Copyright 2015 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 ...
; struct D<T>(T); impl DefaultedTrait for Box<C> { } //~ ERROR E0321 impl DefaultedTrait for lib::Something<C> { } //~ ERROR E0117 impl DefaultedTrait for D<C> { } // OK fn main() { }
C
identifier_name
merge-stream.ts
import { PassThrough } from 'stream'; function mergeStream(...args: any): any { let sources: any = []; const output: any = new PassThrough({ objectMode: true }); output.setMaxListeners(0); function remove(source: any): void { sources = sources.filter((it: any) => { return it !== source; }); ...
sources.push(source); source.once('end', remove.bind(null, source)); source.once('error', output.emit.bind(output, 'error')); source.pipe(output, { end: false }); return this; } function isEmpty(): boolean { return sources.length == 0; } output.add = add; output.isEmpty = isEmpty; ...
{ source.forEach(add); return this; }
conditional_block
merge-stream.ts
import { PassThrough } from 'stream'; function mergeStream(...args: any): any { let sources: any = []; const output: any = new PassThrough({ objectMode: true }); output.setMaxListeners(0); function remove(source: any): void { sources = sources.filter((it: any) => { return it !== source; }); ...
output.on('unpipe', remove); [...args].slice().forEach(add); return output; } export default mergeStream;
return sources.length == 0; } output.add = add; output.isEmpty = isEmpty;
random_line_split
merge-stream.ts
import { PassThrough } from 'stream'; function mergeStream(...args: any): any { let sources: any = []; const output: any = new PassThrough({ objectMode: true }); output.setMaxListeners(0); function remove(source: any): void
function add(this: any, source: any): any { if (Array.isArray(source)) { source.forEach(add); return this; } sources.push(source); source.once('end', remove.bind(null, source)); source.once('error', output.emit.bind(output, 'error')); source.pipe(output, { end: false }); ret...
{ sources = sources.filter((it: any) => { return it !== source; }); if (!sources.length && output.readable) { output.end(); } }
identifier_body
merge-stream.ts
import { PassThrough } from 'stream'; function mergeStream(...args: any): any { let sources: any = []; const output: any = new PassThrough({ objectMode: true }); output.setMaxListeners(0); function remove(source: any): void { sources = sources.filter((it: any) => { return it !== source; }); ...
(): boolean { return sources.length == 0; } output.add = add; output.isEmpty = isEmpty; output.on('unpipe', remove); [...args].slice().forEach(add); return output; } export default mergeStream;
isEmpty
identifier_name
task-list.ts
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { FirebaseListObservable } from 'angularfire2/database'; import { ITask } from '../models/task'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, selector: 'task-list', styles: [ require('./t...
{ @Input() filter: string; @Input() tasks: FirebaseListObservable<ITask[]>; @Output() remove = new EventEmitter(false); @Output() update = new EventEmitter(false); }
TaskListComponent
identifier_name
task-list.ts
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { FirebaseListObservable } from 'angularfire2/database'; import { ITask } from '../models/task'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, selector: 'task-list', styles: [ require('./t...
<div class="task-list"> <task-item *ngFor="let task of tasks | async" [task]="task" (remove)="remove.emit(task)" (update)="update.emit({task: task, changes: $event})"></task-item> </div> ` }) export class TaskListComponent { @Input() filter: string; @Input() tasks: F...
<li><a [class.active]="filter === 'true'" [routerLink]="['/tasks', {completed: true}]">Completed</a></li> </ul>
random_line_split
lineDecorations.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
: 0 ); // If the position would end up in the middle of a high-low surrogate pair, we move it to before the pair if (startColumn > 1) { const charCodeBefore = lineContent.charCodeAt(startColumn - 2); if (strings.isHighSurrogate(charCodeBefore)) { startColumn--; } } if (endColumn ...
{ if (lineDecorations.length === 0) { return []; } let result: DecorationSegment[] = []; const stack = new Stack(); let nextStartOffset = 0; for (let i = 0, len = lineDecorations.length; i < len; i++) { const d = lineDecorations[i]; let startColumn = d.startColumn; let endColumn = d.endColumn...
identifier_body
lineDecorations.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(lineDecorations: InlineDecoration[], lineNumber: number, minLineColumn: number, maxLineColumn: number): LineDecoration[] { if (lineDecorations.length === 0) { return []; } let result: LineDecoration[] = [], resultLen = 0; for (let i = 0, len = lineDecorations.length; i < len; i++) { const d = lineDecor...
filter
identifier_name
lineDecorations.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return result; } private static _typeCompare(a: InlineDecorationType, b: InlineDecorationType): number { const ORDER = [2, 0, 1, 3]; return ORDER[a] - ORDER[b]; } public static compare(a: LineDecoration, b: LineDecoration): number { if (a.startColumn !== b.startColumn) { return a.startColumn - b.star...
{ const d = lineDecorations[i]; const range = d.range; if (range.endLineNumber < lineNumber || range.startLineNumber > lineNumber) { // Ignore decorations that sit outside this line continue; } if (range.isEmpty() && (d.type === InlineDecorationType.Regular || d.type === InlineDecorationType.Re...
conditional_block
lineDecorations.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} public static compare(a: LineDecoration, b: LineDecoration): number { if (a.startColumn !== b.startColumn) { return a.startColumn - b.startColumn; } if (a.endColumn !== b.endColumn) { return a.endColumn - b.endColumn; } const typeCmp = LineDecoration._typeCompare(a.type, b.type); if (typeCmp !=...
private static _typeCompare(a: InlineDecorationType, b: InlineDecorationType): number { const ORDER = [2, 0, 1, 3]; return ORDER[a] - ORDER[b];
random_line_split
form-group.test.ts
import { async, inject, } from '@angular/core/testing'; import {Component} from '@angular/core'; import {By} from '@angular/platform-browser'; import {RioFormGroup} from './form-group'; import {TestBed} from '@angular/core/testing/test_bed'; import {RioFormModule} from './form.module'; describe('Component: Navigat...
fixture.whenStable().then(() => { fixture.autoDetectChanges(); let query = fixture.debugElement .query(By.directive(RioFormGroup)); expect(query).toBeTruthy(); expect(query.componentInstance).toBeTruthy(); }); }))); }); @Component({ selector: 'test', template: ` <rio-...
it('should create the component', async(inject([], () => {
random_line_split
form-group.test.ts
import { async, inject, } from '@angular/core/testing'; import {Component} from '@angular/core'; import {By} from '@angular/platform-browser'; import {RioFormGroup} from './form-group'; import {TestBed} from '@angular/core/testing/test_bed'; import {RioFormModule} from './form.module'; describe('Component: Navigat...
{ }
RioFormGroupTestController
identifier_name
Row.tsx
import React from 'react'; import { toJunction } from 'brookjs'; import { Observable } from 'kefir'; import { i18n, link } from '../../../helpers'; import { jobDispatchClick } from '../../../actions'; import { Job } from './types'; type Props = Job & { onClick: (slug: string) => void }; const Row: React.FC<Props> = (...
<button className="button button-primary" data-testid={`dispatch-job-${slug}`} onClick={() => onClick(slug)} > {i18n('jobs.dispatch')} </button> </td> </tr> ); const events = { onClick: (evt$: Observable<string, never>) => evt$.map(jobDispatchClick).debounc...
<td>
random_line_split
get_profile.rs
//! [GET /_matrix/client/r0/profile/{userId}](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-profile-userid) use ruma_api::ruma_api; use ruma_identifiers::UserId; ruma_api! { metadata { description: "Get all profile information of an user.", method: GET, name: "get_...
request { /// The user whose profile will be retrieved. #[ruma_api(path)] pub user_id: UserId, } response { /// The user's avatar URL, if set. #[serde(skip_serializing_if = "Option::is_none")] pub avatar_url: Option<String>, /// The user's display na...
rate_limited: false, requires_authentication: false, }
random_line_split
4623531fa2b_record_information_about_how_a_game_.py
"""Record information about how a game finished. Revision ID: 4623531fa2b Revises: 9aec2a74d9 Create Date: 2016-04-16 12:27:45.788322 """ # revision identifiers, used by Alembic. revision = '4623531fa2b' down_revision = '9aec2a74d9' from alembic import op import sqlalchemy as sa import app.go as go # A kind of hyb...
(): connection = op.get_bind() with op.batch_alter_table('games', schema=None) as batch_op: batch_op.add_column(sa.Column('finished', sa.BOOLEAN(), server_default=sa.text("'0'"), autoincrement=False, nullable=True)) for game in connection.execute(gamehelper.select()): finished = game.result ...
downgrade
identifier_name
4623531fa2b_record_information_about_how_a_game_.py
"""Record information about how a game finished. Revision ID: 4623531fa2b Revises: 9aec2a74d9 Create Date: 2016-04-16 12:27:45.788322 """ # revision identifiers, used by Alembic. revision = '4623531fa2b' down_revision = '9aec2a74d9' from alembic import op import sqlalchemy as sa import app.go as go # A kind of hyb...
with op.batch_alter_table('games', schema=None) as batch_op: batch_op.drop_column('finished') ### end Alembic commands ### def downgrade(): connection = op.get_bind() with op.batch_alter_table('games', schema=None) as batch_op: batch_op.add_column(sa.Column('finished', sa.BOOLEAN(), ...
result = go.get_game_result(game.sgf).value connection.execute( gamehelper.update().where( gamehelper.c.id == game.id ).values(result=result) )
conditional_block
4623531fa2b_record_information_about_how_a_game_.py
"""Record information about how a game finished. Revision ID: 4623531fa2b Revises: 9aec2a74d9 Create Date: 2016-04-16 12:27:45.788322 """ # revision identifiers, used by Alembic. revision = '4623531fa2b' down_revision = '9aec2a74d9' from alembic import op import sqlalchemy as sa import app.go as go # A kind of hyb...
gamehelper.update().where( gamehelper.c.id == game.id ).values(finished=finished)) with op.batch_alter_table('games', schema=None) as batch_op: batch_op.drop_column('result') ### end Alembic commands ###
random_line_split
4623531fa2b_record_information_about_how_a_game_.py
"""Record information about how a game finished. Revision ID: 4623531fa2b Revises: 9aec2a74d9 Create Date: 2016-04-16 12:27:45.788322 """ # revision identifiers, used by Alembic. revision = '4623531fa2b' down_revision = '9aec2a74d9' from alembic import op import sqlalchemy as sa import app.go as go # A kind of hyb...
connection = op.get_bind() with op.batch_alter_table('games', schema=None) as batch_op: batch_op.add_column(sa.Column('finished', sa.BOOLEAN(), server_default=sa.text("'0'"), autoincrement=False, nullable=True)) for game in connection.execute(gamehelper.select()): finished = game.result != "" ...
identifier_body
main.rs
macro_rules! timeit { ($func:expr) => ({ let t1 = std::time::Instant::now(); println!("{:?}", $func); let t2 = std::time::Instant::now().duration_since(t1); println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00); }) } fn main() { fn
(n: usize) -> bool { let primes: Vec<usize> = vec![1, 2, 3, 5, 7]; match n < 1 || n % 2 == 0 || n % 3 == 0 || primes.iter().filter(|&x| *x == n).collect::<Vec<_>>().len() > 0 { true => return false, false => { let mut i = 5; loop { ...
is_prime
identifier_name
main.rs
macro_rules! timeit { ($func:expr) => ({ let t1 = std::time::Instant::now(); println!("{:?}", $func); let t2 = std::time::Instant::now().duration_since(t1); println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00); }) } fn main() { fn is_prime(n: usize...
timeit!(get_prime(10001)) }
{ (12..) .filter(|&x| is_prime(x)) .take(n - 5) .max() .unwrap() }
identifier_body
main.rs
macro_rules! timeit { ($func:expr) => ({ let t1 = std::time::Instant::now(); println!("{:?}", $func); let t2 = std::time::Instant::now().duration_since(t1);
fn main() { fn is_prime(n: usize) -> bool { let primes: Vec<usize> = vec![1, 2, 3, 5, 7]; match n < 1 || n % 2 == 0 || n % 3 == 0 || primes.iter().filter(|&x| *x == n).collect::<Vec<_>>().len() > 0 { true => return false, false => { let mut i =...
println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00); }) }
random_line_split
main.rs
macro_rules! timeit { ($func:expr) => ({ let t1 = std::time::Instant::now(); println!("{:?}", $func); let t2 = std::time::Instant::now().duration_since(t1); println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00); }) } fn main() { fn is_prime(n: usize...
else { if n % i == 0 || n % (i + 2) == 0 { return false; } } i = i + 6; } } } true } fn get_prime(n: usize) -> usize { (12..) .fil...
{ break; }
conditional_block
viewer.index.ts
import * as path from 'path' import Mocha from 'mocha' import glob from 'glob' export function run(): Promise<void> { // Create the mocha test const mocha = new Mocha({ ui: 'tdd', color: true, timeout: 0 }) const testsRoot = path.resolve(__dirname, '.') return new Promise((...
reject(new Error(`${failures} tests failed.`)) } else { resolve() } }) } catch (e) { console.error(e) reject(e) } }) }) }
// Run the mocha test mocha.run(failures => { if (failures > 0) {
random_line_split
viewer.index.ts
import * as path from 'path' import Mocha from 'mocha' import glob from 'glob' export function run(): Promise<void> { // Create the mocha test const mocha = new Mocha({ ui: 'tdd', color: true, timeout: 0 }) const testsRoot = path.resolve(__dirname, '.') return new Promise((...
else { resolve() } }) } catch (e) { console.error(e) reject(e) } }) }) }
{ reject(new Error(`${failures} tests failed.`)) }
conditional_block
viewer.index.ts
import * as path from 'path' import Mocha from 'mocha' import glob from 'glob' export function run(): Promise<void>
mocha.run(failures => { if (failures > 0) { reject(new Error(`${failures} tests failed.`)) } else { resolve() } }) } catch (e) { console.error(e) ...
{ // Create the mocha test const mocha = new Mocha({ ui: 'tdd', color: true, timeout: 0 }) const testsRoot = path.resolve(__dirname, '.') return new Promise((resolve, reject) => { glob('**/viewer.test.js', { cwd: testsRoot }, (err, files) => { if (err) { ...
identifier_body
viewer.index.ts
import * as path from 'path' import Mocha from 'mocha' import glob from 'glob' export function
(): Promise<void> { // Create the mocha test const mocha = new Mocha({ ui: 'tdd', color: true, timeout: 0 }) const testsRoot = path.resolve(__dirname, '.') return new Promise((resolve, reject) => { glob('**/viewer.test.js', { cwd: testsRoot }, (err, files) => { ...
run
identifier_name
register.module.ts
import { CdkStepperModule } from '@angular/cdk/stepper' import { NgModule } from '@angular/core' import { SharedSignupModule } from '@app/+signup/shared/shared-signup.module' import { SharedInstanceModule } from '@app/shared/shared-instance' import { CustomStepperComponent } from './custom-stepper.component' import { R...
providers: [ ] }) export class RegisterModule { }
random_line_split
register.module.ts
import { CdkStepperModule } from '@angular/cdk/stepper' import { NgModule } from '@angular/core' import { SharedSignupModule } from '@app/+signup/shared/shared-signup.module' import { SharedInstanceModule } from '@app/shared/shared-instance' import { CustomStepperComponent } from './custom-stepper.component' import { R...
{ }
RegisterModule
identifier_name
scorers.py
''' Auxiliary code providing vector-valued scoring functions for convenient use in the parameter-free Ladder Mechanism. Original algorithm by Avrim Blum and Moritz Hardt Python implementation by Jamie Hall and Moritz Hardt MIT License '''
from functools import wraps import numpy as np def validate_input(metric): @wraps(metric) def wrapped(y, y_pred): _check_y_shapes(y, y_pred) return metric(y, y_pred) return wrapped @validate_input def squared_error(y, y_pred): return ((y - y_pred)**2) @validate_input def absolute_e...
from sklearn.utils import check_consistent_length
random_line_split
scorers.py
''' Auxiliary code providing vector-valued scoring functions for convenient use in the parameter-free Ladder Mechanism. Original algorithm by Avrim Blum and Moritz Hardt Python implementation by Jamie Hall and Moritz Hardt MIT License ''' from sklearn.utils import check_consistent_length from functools import wraps ...
raise ValueError("y_true and y_pred have different number of output " "({0}!={1})".format(y_true.shape[1], y_pred.shape[1]))
conditional_block
scorers.py
''' Auxiliary code providing vector-valued scoring functions for convenient use in the parameter-free Ladder Mechanism. Original algorithm by Avrim Blum and Moritz Hardt Python implementation by Jamie Hall and Moritz Hardt MIT License ''' from sklearn.utils import check_consistent_length from functools import wraps ...
(y_true, y_pred): ''' Check that two target vectors are compatible. This is based on sklearn's validation in sklearn.metrics.regression._check_reg_targets and sklearn.metrics.classification._check_targets. ''' check_consistent_length(y_true, y_pred) if y_true.ndim == 1: y_true = y_true....
_check_y_shapes
identifier_name
scorers.py
''' Auxiliary code providing vector-valued scoring functions for convenient use in the parameter-free Ladder Mechanism. Original algorithm by Avrim Blum and Moritz Hardt Python implementation by Jamie Hall and Moritz Hardt MIT License ''' from sklearn.utils import check_consistent_length from functools import wraps ...
''' Check that two target vectors are compatible. This is based on sklearn's validation in sklearn.metrics.regression._check_reg_targets and sklearn.metrics.classification._check_targets. ''' check_consistent_length(y_true, y_pred) if y_true.ndim == 1: y_true = y_true.reshape((-1, 1)) ...
identifier_body
slide-toggle.ts
haviors/disable-ripple'; // Increasing integer for generating unique ids for slide-toggle components. let nextUniqueId = 0; export const MD_SLIDE_TOGGLE_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MdSlideToggle), multi: true }; /** Change event object emitted by a MdSlideT...
} /** * Emits a change event on the `change` output. Also notifies the FormControl about the change. */ private _emitChangeEvent() { let event = new MdSlideToggleChange(); event.source = this; event.checked = this.checked; this.change.emit(event); this.onChange(this.checked); } _o...
{ this.onTouched(); // Fade out and clear the focus ripple if one is currently present. if (this._focusRipple) { this._focusRipple.fadeOut(); this._focusRipple = null; } }
conditional_block
slide-toggle.ts
haviors/disable-ripple'; // Increasing integer for generating unique ids for slide-toggle components. let nextUniqueId = 0; export const MD_SLIDE_TOGGLE_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MdSlideToggle), multi: true }; /** Change event object emitted by a MdSlideT...
/** * This function will called if the underlying input changed its value through user interaction. */ _onChangeEvent(event: Event) { // We always have to stop propagation on the change event. // Otherwise the change event, from the input element, will bubble up and // emit its event object to t...
{ this._focusOriginMonitor.stopMonitoring(this._inputElement.nativeElement); }
identifier_body
slide-toggle.ts
} from '@angular/core'; import {Platform} from '@angular/cdk/platform'; import {coerceBooleanProperty} from '@angular/cdk/coercion'; import { applyCssTransform, FocusOrigin, FocusOriginMonitor, HammerInput, MdRipple, RippleRef, } from '../core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angula...
random_line_split
slide-toggle.ts
-behaviors/disable-ripple'; // Increasing integer for generating unique ids for slide-toggle components. let nextUniqueId = 0; export const MD_SLIDE_TOGGLE_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MdSlideToggle), multi: true }; /** Change event object emitted by a MdSli...
(value) { this._required = coerceBooleanProperty(value); } /** Whether the slide-toggle element is checked or not */ @Input() get checked(): boolean { return this._checked; } set checked(value) { this._checked = !!value; this._changeDetectorRef.markForCheck(); } /** An event will be dispatched each...
required
identifier_name
parser.rs
use std::fs::File; use std::io::prelude::*; use png::errors::PNGError; use super::chunk::{Chunk, ChunkBuilder}; pub struct ChunkIterator<'a> { parser: &'a PNGParser<'a>, } impl<'a> Iterator for ChunkIterator<'a> { type Item = Chunk; fn next (&mut self) -> Option<Chunk> { self.parser.read_chunk(...
ChunkIterator { parser: self } } }
.and_then(|b| b.read_data(self.source)) .map(|b| b.as_chunk()) } pub fn iter_chunks(&'a self) -> ChunkIterator {
random_line_split
parser.rs
use std::fs::File; use std::io::prelude::*; use png::errors::PNGError; use super::chunk::{Chunk, ChunkBuilder}; pub struct ChunkIterator<'a> { parser: &'a PNGParser<'a>, } impl<'a> Iterator for ChunkIterator<'a> { type Item = Chunk; fn next (&mut self) -> Option<Chunk> { self.parser.read_chunk(...
else { Err(PNGError::InvalidHeader) } }) } pub fn read_chunk(&'a self) -> Result<Chunk, PNGError>{ ChunkBuilder::default() .read_header(self.source) .and_then(|b| b.read_data(self.source)) ...
{ Ok(()) }
conditional_block
parser.rs
use std::fs::File; use std::io::prelude::*; use png::errors::PNGError; use super::chunk::{Chunk, ChunkBuilder}; pub struct ChunkIterator<'a> { parser: &'a PNGParser<'a>, } impl<'a> Iterator for ChunkIterator<'a> { type Item = Chunk; fn next (&mut self) -> Option<Chunk> { self.parser.read_chunk(...
(&'a self) -> ChunkIterator { ChunkIterator { parser: self } } }
iter_chunks
identifier_name
main.py
#! /usr/bin/python # -*- coding: utf-8 -*- u""" Finite Horizon Optimal Control author Atsushi Sakai """ import numpy as np import scipy.linalg as la def
(A,B,Q,R,P,N,x0): u""" Calc Finite Horizon Optimal Input # TODO optimize in: see below min x'Px+sum(x'Qx+u'Ru) s.t xk+1=Axk+Bu out: uopt optimal input """ # print("CalcFiniteHorizonOptimalInput start") # data check if A.shape[1] is not x0.shape[0]: print("Data E...
CalcFiniteHorizonOptimalInput
identifier_name
main.py
#! /usr/bin/python # -*- coding: utf-8 -*- u""" Finite Horizon Optimal Control author Atsushi Sakai """ import numpy as np import scipy.linalg as la def CalcFiniteHorizonOptimalInput(A,B,Q,R,P,N,x0): u""" Calc Finite Horizon Optimal Input # TODO optimize in: see below min x'Px+sum(x'Qx+u'Ru...
print("R's shape:") print(R.shape) return None sx=np.eye(A.ndim) su=np.zeros((A.ndim,B.shape[1]*N)) #calc sx,su for i in range(N): #generate sx An=np.linalg.matrix_power(A, i+1) sx=np.r_[sx,An] #generate su tmp=None for ii in ran...
elif B.shape[1] is not R.shape[1]: print("Data Error: B's col == R's row") print("B shape:") print(B.shape)
random_line_split
main.py
#! /usr/bin/python # -*- coding: utf-8 -*- u""" Finite Horizon Optimal Control author Atsushi Sakai """ import numpy as np import scipy.linalg as la def CalcFiniteHorizonOptimalInput(A,B,Q,R,P,N,x0):
return None elif B.shape[1] is not R.shape[1]: print("Data Error: B's col == R's row") print("B shape:") print(B.shape) print("R's shape:") print(R.shape) return None sx=np.eye(A.ndim) su=np.zeros((A.ndim,B.shape[1]*N)) #calc sx,su for i in r...
u""" Calc Finite Horizon Optimal Input # TODO optimize in: see below min x'Px+sum(x'Qx+u'Ru) s.t xk+1=Axk+Bu out: uopt optimal input """ # print("CalcFiniteHorizonOptimalInput start") # data check if A.shape[1] is not x0.shape[0]: print("Data Error: A's col == x0's ...
identifier_body
main.py
#! /usr/bin/python # -*- coding: utf-8 -*- u""" Finite Horizon Optimal Control author Atsushi Sakai """ import numpy as np import scipy.linalg as la def CalcFiniteHorizonOptimalInput(A,B,Q,R,P,N,x0): u""" Calc Finite Horizon Optimal Input # TODO optimize in: see below min x'Px+sum(x'Qx+u'Ru...
else: tmp =np.c_[tmp,tm] su=np.r_[su,tmp] tm1=np.eye(N+1) tm1[N,N]=0 tm2=np.zeros((N+1,N+1)) tm2[N,N]=1 Qbar=np.kron(tm1,Q)+np.kron(tm2,P) Rbar=np.kron(np.eye(N),R) uopt=-(su.T*Qbar*su+Rbar).I*su.T*Qbar*sx*x0 # print(uBa) costBa=x0.T*(sx.T*Qba...
tmp=tm
conditional_block
ControlPropertyBinding.js
/*! * ${copyright} */ // Provides the JSON model implementation of a property binding sap.ui.define(['sap/ui/model/PropertyBinding'], function(PropertyBinding) { "use strict"; /** * @class * Property binding implementation for JSON format. * * @param {sap.ui.model.control.ControlModel} oModel * @param...
});
random_line_split
ControlPropertyBinding.js
/*! * ${copyright} */ // Provides the JSON model implementation of a property binding sap.ui.define(['sap/ui/model/PropertyBinding'], function(PropertyBinding) { "use strict"; /** * @class * Property binding implementation for JSON format. * * @param {sap.ui.model.control.ControlModel} oModel * @param...
}; return ControlPropertyBinding; });
{// optimize for not firing the events when unneeded this.oValue = oValue; this._fireChange(); }
conditional_block
run_pseudo_tasks_slurm.py
#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys import argparse import datetime import time import gettext from pseudo_cluster.task import Task_record from pseudo_cluster.tasks_list import Tasks_list from pseudo_cluster.extended_task import Extended_task_record from pseudo_cluster.actions_list impor...
ивает ID задачи из файла и первой строчки, которая была до этого прочитана в файле. файл не закрывает. """ try: tup=first_line.split(' ') except: return False if (tup[0] == "Submitted") and (tup[1] == "batch"): self.actual_task_id=int(tup[3]) return True retu...
" Выковыр
identifier_name
run_pseudo_tasks_slurm.py
#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys import argparse import datetime import time import gettext from pseudo_cluster.task import Task_record from pseudo_cluster.tasks_list import Tasks_list from pseudo_cluster.extended_task import Extended_task_record from pseudo_cluster.actions_list impor...
if i < last_task: continue task=tasks_list[i] if task.time_submit < begin_time: last_task=i if task.time_submit < end_time: if task.job_id not in extended_tasks: extended_task=Extended_task_record() ...
while last_task != num_tasks-1: end_time=begin_time+datetime.timedelta(minutes=args.interval*args.compress_times) begin_actions_time=datetime.datetime.utcnow() for i in xrange(0,num_tasks):
random_line_split
run_pseudo_tasks_slurm.py
#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys import argparse import datetime import time import gettext from pseudo_cluster.task import Task_record from pseudo_cluster.tasks_list import Tasks_list from pseudo_cluster.extended_task import Extended_task_record from pseudo_cluster.actions_list impor...
argv=sys.argv gettext.install('pseudo-cluster') parser= argparse.ArgumentParser( description=_(""" Данная программа осуществляет постановку задач в очередь Slurm. Список задач получается из файла статистики. При этом программа ставит задачу в очеред...
и первой строчки, которая была до этого прочитана в файле. файл не закрывает. """ try: tup=first_line.split(' ') except: return False if (tup[0] == "Submitted") and (tup[1] == "batch"): self.actual_task_id=int(tup[3]) return True return False def main(a...
identifier_body
run_pseudo_tasks_slurm.py
#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys import argparse import datetime import time import gettext from pseudo_cluster.task import Task_record from pseudo_cluster.tasks_list import Tasks_list from pseudo_cluster.extended_task import Extended_task_record from pseudo_cluster.actions_list impor...
ppend("--time=%d" % time_limit) # # Path to this script must be available # from environment variable PATH # s.append(self.path_to_task) s.append("-t") s.append(str(duration)) s.append("-s") s.append(self.task_state) return s def get_cancel_string(self): return [ "scance...
) if time_limit > 0: s.a
conditional_block
TaskStatusDSLSection.tsx
import { Trans } from "@lingui/macro"; import PropTypes from "prop-types"; import * as React from "react"; import DSLCombinerTypes from "#SRC/js/constants/DSLCombinerTypes"; import DSLExpression from "#SRC/js/structs/DSLExpression"; import DSLExpressionPart from "#SRC/js/structs/DSLExpressionPart"; import DSLFormWithE...
() {}, }; TasksStatusDSLSection.propTypes = { expression: PropTypes.instanceOf(DSLExpression).isRequired, onChange: PropTypes.func.isRequired, }; export default TasksStatusDSLSection;
onChange
identifier_name
TaskStatusDSLSection.tsx
import { Trans } from "@lingui/macro"; import PropTypes from "prop-types"; import * as React from "react"; import DSLCombinerTypes from "#SRC/js/constants/DSLCombinerTypes"; import DSLExpression from "#SRC/js/structs/DSLExpression"; import DSLExpressionPart from "#SRC/js/structs/DSLExpressionPart"; import DSLFormWithE...
type="checkbox" /> <Trans render="span">Killed</Trans> </FieldLabel> </FormGroup> </div> </div> </DSLFormWithExpressionUpdates> ); }; TasksStatusDSLSection.defaultProps = { expression: new DSLExpression(""), onChange() {}, }; Ta...
disabled={!enabled} name="is_killed"
random_line_split
TaskStatusDSLSection.tsx
import { Trans } from "@lingui/macro"; import PropTypes from "prop-types"; import * as React from "react"; import DSLCombinerTypes from "#SRC/js/constants/DSLCombinerTypes"; import DSLExpression from "#SRC/js/structs/DSLExpression"; import DSLExpressionPart from "#SRC/js/structs/DSLExpressionPart"; import DSLFormWithE...
, }; TasksStatusDSLSection.propTypes = { expression: PropTypes.instanceOf(DSLExpression).isRequired, onChange: PropTypes.func.isRequired, }; export default TasksStatusDSLSection;
{}
identifier_body
MobileWrapper.tsx
import * as React from 'react'; import { WrapperVariantContext } from './WrapperVariantContext'; import PickersModalDialog, { ExportedPickerModalProps } from '../PickersModalDialog'; import { PrivateWrapperProps, DateInputPropsLike } from './WrapperProps'; export interface MobileWrapperProps extends ExportedPickerModa...
(props: InternalMobileWrapperProps) { const { cancelText, children, clearable, clearText, DateInputProps, DialogProps, okText, onAccept, onClear, onDismiss, onSetToday, open, PureDateInputComponent, showTodayButton, todayText, ...other } = props; re...
MobileWrapper
identifier_name
MobileWrapper.tsx
import * as React from 'react'; import { WrapperVariantContext } from './WrapperVariantContext'; import PickersModalDialog, { ExportedPickerModalProps } from '../PickersModalDialog'; import { PrivateWrapperProps, DateInputPropsLike } from './WrapperProps'; export interface MobileWrapperProps extends ExportedPickerModa...
} = props; return ( <WrapperVariantContext.Provider value="mobile"> <PureDateInputComponent {...other} {...DateInputProps} /> <PickersModalDialog cancelText={cancelText} clearable={clearable} clearText={clearText} DialogProps={DialogProps} okText={okText} ...
random_line_split
MobileWrapper.tsx
import * as React from 'react'; import { WrapperVariantContext } from './WrapperVariantContext'; import PickersModalDialog, { ExportedPickerModalProps } from '../PickersModalDialog'; import { PrivateWrapperProps, DateInputPropsLike } from './WrapperProps'; export interface MobileWrapperProps extends ExportedPickerModa...
return ( <WrapperVariantContext.Provider value="mobile"> <PureDateInputComponent {...other} {...DateInputProps} /> <PickersModalDialog cancelText={cancelText} clearable={clearable} clearText={clearText} DialogProps={DialogProps} okText={okText} onAccept=...
{ const { cancelText, children, clearable, clearText, DateInputProps, DialogProps, okText, onAccept, onClear, onDismiss, onSetToday, open, PureDateInputComponent, showTodayButton, todayText, ...other } = props;
identifier_body
forms.input.record.js
// ----------- this.extendable = safeAssign(args.format.extendable, false); this.showID = safeAssign(args.format.showID, true); this.mode = safeAssign(args.format.mode, 'preview'); // Additional widgets // ------------------ this.toolbarWidget = $('<div class="toolbar"/>').appendTo(this.widget); this.elementsW...
openEditor : function() { // Input // ----- var input = this; // Create editor window // -------------------- var editor = new RecordElementEditor({ 'format' : input.format.format, 'value' : input.getValue() }); // Listen for closing ...
// Open editor // -----------
random_line_split
visualize_overlapping_sbs.py
start, i)) return res def parseMarkerList(marker_seq_list): res = list() for x in xrange(len(genomes)): mlist = list() queue = list() goss = marker_seq_list[x] for i in xrange(len(goss)): start = int(PAT_POS.match(goss[i][1]).group(1)) end = in...
gt = gMap[genomes[target]][GM_ACTV_GNS_KEY][gt_id[1]-1] tstart, tend = map(int, PAT_POS.match(gt).groups()[:2]) cti = gt in tgi ctj = gt in tgj OFFSET_T = OFFSET_TI if ctj: OFFSET_T = OFFSET_TJ if (csi and csj) or (cti and ctj): ...
conditional_block
visualize_overlapping_sbs.py
1 insort(queue, (chrx, end, start, i)) return res def
(marker_seq_list): res = list() for x in xrange(len(genomes)): mlist = list() queue = list() goss = marker_seq_list[x] for i in xrange(len(goss)): start = int(PAT_POS.match(goss[i][1]).group(1)) end = int(PAT_POS.match(goss[i][-2]).group(2)) ...
parseMarkerList
identifier_name
visualize_overlapping_sbs.py
for chrx, start, end, i in goss: # only iterate until an interval is found that ends before new interval start y = len(queue)-1 while y >= 0 and queue[y][0] == chrx and queue[y][1] >= start: j = queue[y][3] if queue[y][1] < end and queue[y][2] ...
random_line_split
visualize_overlapping_sbs.py
insort(queue, (chrx, end, start, i)) return res def parseMarkerList(marker_seq_list): res = list() for x in xrange(len(genomes)): mlist = list() queue = list() goss = marker_seq_list[x] for i in xrange(len(goss)): start = int(PAT_P...
res = dict() for x in xrange(len(mlists)): queue = list() goss = mlists[x] # # XXX this whole procedure can be significanlty sped up by sorting start # positions before hand and then using a pointer within this list. # for chrx, start, end, i in goss: ...
identifier_body
movescu.py
PatientStudyOnlyQueryRetrieveInformationModelMove, ) __version__ = "0.4.0" def _setup_argparser(): """Setup the command line arguments""" # Description parser = argparse.ArgumentParser( description=( "The movescu application implements a Service Class User (SCU) " "fo...
elif not bool(ns.file) and not bool(ns.keyword): parser.error("-f and/or -k must be specified") return ns def main(args=None): """Run the application.""" if args is not None: sys.argv = args args = _setup_argparser() if args.version: print(f"movescu.py v{__version__...
pass
conditional_block
movescu.py
PatientStudyOnlyQueryRetrieveInformationModelMove, ) __version__ = "0.4.0" def _setup_argparser(): """Setup the command line arguments""" # Description parser = argparse.ArgumentParser( description=( "The movescu application implements a Service Class User (SCU) " "fo...
# identifier.PatientName = '*' identifier = create_dataset(args, APP_LOGGER) except Exception as exc: APP_LOGGER.exception(exc) sys.exit(1) # Create application entity ae = AE() # Start the Store SCP (optional) scp = None if args.store: transfer_synt...
"""Run the application.""" if args is not None: sys.argv = args args = _setup_argparser() if args.version: print(f"movescu.py v{__version__}") sys.exit() APP_LOGGER = setup_logging(args, "movescu") APP_LOGGER.debug(f"movescu.py v{__version__}") APP_LOGGER.debug("") ...
identifier_body
movescu.py
PatientStudyOnlyQueryRetrieveInformationModelMove, ) __version__ = "0.4.0" def _setup_argparser(): """Setup the command line arguments""" # Description parser = argparse.ArgumentParser( description=( "The movescu application implements a Service Class User (SCU) " "for t...
(args=None): """Run the application.""" if args is not None: sys.argv = args args = _setup_argparser() if args.version: print(f"movescu.py v{__version__}") sys.exit() APP_LOGGER = setup_logging(args, "movescu") APP_LOGGER.debug(f"movescu.py v{__version__}") APP_LOG...
main
identifier_name
movescu.py
PatientStudyOnlyQueryRetrieveInformationModelMove, ) __version__ = "0.4.0" def _setup_argparser(): """Setup the command line arguments""" # Description parser = argparse.ArgumentParser( description=( "The movescu application implements a Service Class User (SCU) " "fo...
qr_group = parser.add_argument_group("Query Information Model Options") qr_model = qr_group.add_mutually_exclusive_group() qr_model.add_argument( "-P", "--patient", help="use patient root information model (default)", action="store_true", ) qr_model.add_argument( ...
default=DEFAULT_MAX_LENGTH, ) # Query information model choices
random_line_split
about.tsx
import * as React from 'react' import { Row } from '../lib/row' import { Button } from '../lib/button' import { Dialog, DialogError, DialogContent, DefaultDialogFooter, } from '../dialog' import { LinkButton } from '../lib/link-button' import { updateStore, IUpdateState, UpdateStatus } from '../lib/update-stor...
{versionText} ({this.props.applicationArchitecture}) </span>{' '} ({releaseNotesLink}) </p> <p className="no-padding"> <LinkButton onClick={this.props.onShowTermsAndConditions}> Terms and Conditions </LinkButton> <...
<span className="selectable-text">
random_line_split
index.js
/** * naive SDK * Kevin Lee 31 March 2017 * Major Start on 26 July 2017 * * "Too Simple, Sometimes Naive ... UI gonna be" * A react-NAtIVE component for simple User Interface development * * Install (Vector Icon): * npm install react-native-vector-icons --save * * Edit android/app/build.gradle: // beg...
, get Screen() { return require('./screen').default }, get Block() { return require('./block').default }, get Content() { return require('./block').default }, get Bar() { return require('./bar').default }, get Modal() { return require('./modal').default }, get DataBar() { r...
{ return require('./device').default }
identifier_body
index.js
/** * naive SDK * Kevin Lee 31 March 2017 * Major Start on 26 July 2017 * * "Too Simple, Sometimes Naive ... UI gonna be" * A react-NAtIVE component for simple User Interface development * * Install (Vector Icon): * npm install react-native-vector-icons --save * * Edit android/app/build.gradle: // beg...
() { return require('./block').default }, get Bar() { return require('./bar').default }, get Modal() { return require('./modal').default }, get DataBar() { return require('./databar').default }, get DataBlock() { return require('./datablock').default }, // Icon get Icon() { r...
Content
identifier_name
index.js
/** * naive SDK * Kevin Lee 31 March 2017 * Major Start on 26 July 2017 * * "Too Simple, Sometimes Naive ... UI gonna be" * A react-NAtIVE component for simple User Interface development * * Install (Vector Icon): * npm install react-native-vector-icons --save * * Edit android/app/build.gradle: // beg...
return require('./icon').default }, get IconList() { return require('./iconlist').default }, // Button family get Button() { return require('./button').default }, get ButtonList() { return require('./buttonlist').default }, get ButtonPanel() { return require('./buttonpanel').default ...
get Icon() {
random_line_split
utils.d.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ declare type GetPath = { hasEndProp?: boolean; lastTraversedObject: unknown; traversedPath: Arr...
export declare const sparseArrayEquality: (a: unknown, b: unknown) => boolean | undefined; export declare const partition: <T>(items: T[], predicate: (arg: T) => boolean) => [T[], T[]]; export declare const isError: (value: unknown) => boolean; export declare function emptyObject(obj: any): boolean; export declare cons...
export declare const getObjectSubset: (object: any, subset: any) => any; export declare const iterableEquality: (a: any, b: any, aStack?: any[], bStack?: any[]) => boolean | undefined; export declare const subsetEquality: (object: any, subset: any) => boolean | undefined; export declare const typeEquality: (a: any, b: ...
random_line_split
extension.ts
import * as vscode from 'vscode'; import {actionsList, ActionsList} from './extension/action'; import { CommandCallback, AbstractAction } from './extension/action/AbstractAction'; import config from './extension/action/helpers/Config'; import { manager } from './extension/Manager'; import structureProvider from './exte...
(context: vscode.ExtensionContext, name: keyof ActionsList) { const func = getCommandFunction(name); const command = vscode.commands.registerCommand(name as string, func); context.subscriptions.push(command); } function addTextEditorCommand(context: vscode.ExtensionContext, name: keyof ActionsList) { c...
addCommand
identifier_name
extension.ts
import * as vscode from 'vscode'; import {actionsList, ActionsList} from './extension/action'; import { CommandCallback, AbstractAction } from './extension/action/AbstractAction'; import config from './extension/action/helpers/Config'; import { manager } from './extension/Manager'; import structureProvider from './exte...
{ }
identifier_body
extension.ts
import * as vscode from 'vscode';
import {actionsList, ActionsList} from './extension/action'; import { CommandCallback, AbstractAction } from './extension/action/AbstractAction'; import config from './extension/action/helpers/Config'; import { manager } from './extension/Manager'; import structureProvider from './extension/StructureProvider'; import c...
random_line_split
simple_wsgi.py
# # Copyright 2014, 2015 Red Hat. All Rights Reserved. # # Author: Chris Dent <chdent@redhat.com> # # 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/LICEN...
headers = [ ('X-Gabbi-method', request_method), ('Content-Type', response_content_type), ('X-Gabbi-url', request_url), ] if request_method not in METHODS: headers.append( ('Allow', ', '.join(METHODS))) start_response(...
response_content_type = 'application/json'
conditional_block
simple_wsgi.py
# # Copyright 2014, 2015 Red Hat. All Rights Reserved. # # Author: Chris Dent <chdent@redhat.com> # # 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/LICEN...
return urlparse.urlunsplit((server_scheme, netloc, path, query, fragment))
netloc = server_name
random_line_split
simple_wsgi.py
# # Copyright 2014, 2015 Red Hat. All Rights Reserved. # # Author: Chris Dent <chdent@redhat.com> # # 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/LICEN...
if request_method not in METHODS: headers.append( ('Allow', ', '.join(METHODS))) start_response('405 Method Not Allowed', headers) return [] if request_method.startswith('P'): body = environ['wsgi.input'].read() if body: ...
request_method = environ['REQUEST_METHOD'].upper() query_data = urlparse.parse_qs(environ.get('QUERY_STRING', '')) request_url = environ.get('REQUEST_URI', environ.get('RAW_URI', 'unknown')) accept_header = environ.get('HTTP_ACCEPT') content_type_header ...
identifier_body
simple_wsgi.py
# # Copyright 2014, 2015 Red Hat. All Rights Reserved. # # Author: Chris Dent <chdent@redhat.com> # # 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/LICEN...
(self, environ, start_response): request_method = environ['REQUEST_METHOD'].upper() query_data = urlparse.parse_qs(environ.get('QUERY_STRING', '')) request_url = environ.get('REQUEST_URI', environ.get('RAW_URI', 'unknown')) accept_header = environ.get('H...
__call__
identifier_name
IRegistryItems.ts
import { ActionCreatorsMapObject } from "redux"; import { ICoreAction, IOscActionDef, OscArgSequence } from "./IActions"; import { IState, Tuple } from "./interfaces"; /** * A basic interface for registry items that * shouldn't be used directly. It should be extended by * other interfaces to be used in registries (...
unboundActionCreators: ActionCreatorsMapObject; onChange(changed: Tuple): boolean; unsubscribe(): void; } /** * A plugin instance */ export interface IPlugin extends IRegistryItem { readonly frequencyLookup: number[]; inputs: AudioNode[]; outputs: AudioNode[]; getMyState(): IState; [p...
actionCreators: ActionCreatorsMapObject;
random_line_split
grass.tsx
<?xml version="1.0" encoding="UTF-8"?> <tileset name="grass" tilewidth="32" tileheight="32"> <properties> <property name="Content" value="LPC/Terrain/grass"/> </properties> <image source="../../LPC/Terrain/grass.png" width="96" height="192"/> <terraintypes> <terrain name="Grass" tile="-1"/> </terraintypes> <t...
<tile id="12" terrain=",0,,"/> <tile id="13" terrain="0,0,,"/> <tile id="14" terrain="0,,,"/> </tileset>
</tile> <tile id="11" terrain="0,,0,"/>
random_line_split
ContactListItem.tsx
// Copyright 2018-2020 Signal Messenger, LLC // SPDX-License-Identifier: AGPL-3.0-only import React from 'react'; import classNames from 'classnames'; import { Avatar } from './Avatar'; import { Emojify } from './conversation/Emojify'; import { InContactsIcon } from './InContactsIcon'; import { LocalizerType } from ...
profileName, title, } = this.props; const displayName = isMe ? i18n('you') : title; const shouldShowIcon = Boolean(name); const showNumber = Boolean(isMe || name || profileName); const showVerified = !isMe && isVerified; return ( <button onClick={onClick} cla...
phoneNumber,
random_line_split
pipeline-data-transform-dense.py
# # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
(config="../../config.yaml", namespace=""): # obtain config if isinstance(config, str): config = load_job_config(config) parties = config.parties guest = parties.guest[0] host = parties.host[0] guest_train_data = {"name": "breast_hetero_guest", "namespace": f"experiment{namespace}"} ...
main
identifier_name
pipeline-data-transform-dense.py
# # Copyright 2019 The FATE Authors. All Rights Reserved. #
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # 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 governi...
# 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 #
random_line_split
pipeline-data-transform-dense.py
# # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
parser = argparse.ArgumentParser("PIPELINE DEMO") parser.add_argument("-config", type=str, help="config file") args = parser.parse_args() if args.config is not None: main(args.config) else: main()
conditional_block
pipeline-data-transform-dense.py
# # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
pipeline.add_component(data_transform_0, data=Data(data=reader_0.output.data)) pipeline.compile() pipeline.fit() if __name__ == "__main__": parser = argparse.ArgumentParser("PIPELINE DEMO") parser.add_argument("-config", type=str, help="config file") args = parser.pa...
if isinstance(config, str): config = load_job_config(config) parties = config.parties guest = parties.guest[0] host = parties.host[0] guest_train_data = {"name": "breast_hetero_guest", "namespace": f"experiment{namespace}"} host_train_data = {"name": "breast_hetero_host", "namespace": f"exp...
identifier_body
sao-paulo.service.ts
export class SaoPauloService { private readonly TAMANHO_IE_DOZE_DIGITOS = 12; private readonly TAMANHO_IE_TREZE_DIGITOS = 13; /** * Regra de validação aplicada: http://www.sintegra.gov.br/Cad_Estados/cad_SP.html * * @param inscricaoEstadual Número referente a inscrição estadual */ validar(inscrica...
rivate validarInscricoesCom12Digitos(ie: string) { const posicaoPrimeiroDigito = 8; const posicaoSegundoDigito = 11; const pesosPrimeiroDigito = [1, 3, 4, 5, 6, 7, 8, 10]; const pesosSegundoDigito = [3, 2, 10, 9, 8, 7, 6, 5, 4, 3, 2]; const primeiroDigito = ie.charAt(posicaoPrimeiroDigito); con...
// https://jex.im/regulex/#!embed=false&flags=&re=%5C.%7C%5C%2F%7C%5C-%7C%5Cs const ieSemMascara = inscricaoEstadual.replace(/\.|\/|\-|\s/g, ''); if (ieSemMascara.length === this.TAMANHO_IE_DOZE_DIGITOS) { return this.validarInscricoesCom12Digitos(ieSemMascara); } else if (ieSemMascara.length === th...
identifier_body
sao-paulo.service.ts
export class SaoPauloService { private readonly TAMANHO_IE_DOZE_DIGITOS = 12; private readonly TAMANHO_IE_TREZE_DIGITOS = 13; /** * Regra de validação aplicada: http://www.sintegra.gov.br/Cad_Estados/cad_SP.html * * @param inscricaoEstadual Número referente a inscrição estadual */ validar(inscrica...
private validarInscricoesCom13Digitos(ie: string) { const posicaoDigito = 9; const pesosDigito = [1, 3, 4, 5, 6, 7, 8, 10]; const digito = ie.charAt(posicaoDigito); const digitoCalculado = this.calcularDigitoVerificador(ie.substring(1, posicaoDigito), pesosDigito); return digito === digitoCalcu...
random_line_split
sao-paulo.service.ts
export class SaoPauloService { private readonly TAMANHO_IE_DOZE_DIGITOS = 12; private readonly TAMANHO_IE_TREZE_DIGITOS = 13; /** * Regra de validação aplicada: http://www.sintegra.gov.br/Cad_Estados/cad_SP.html * * @param inscricaoEstadual Número referente a inscrição estadual */ validar(inscrica...
string) { const posicaoDigito = 9; const pesosDigito = [1, 3, 4, 5, 6, 7, 8, 10]; const digito = ie.charAt(posicaoDigito); const digitoCalculado = this.calcularDigitoVerificador(ie.substring(1, posicaoDigito), pesosDigito); return digito === digitoCalculado; } private calcularDigitoVerificado...
arInscricoesCom13Digitos(ie:
identifier_name
sao-paulo.service.ts
export class SaoPauloService { private readonly TAMANHO_IE_DOZE_DIGITOS = 12; private readonly TAMANHO_IE_TREZE_DIGITOS = 13; /** * Regra de validação aplicada: http://www.sintegra.gov.br/Cad_Estados/cad_SP.html * * @param inscricaoEstadual Número referente a inscrição estadual */ validar(inscrica...
return false; } private validarInscricoesCom12Digitos(ie: string) { const posicaoPrimeiroDigito = 8; const posicaoSegundoDigito = 11; const pesosPrimeiroDigito = [1, 3, 4, 5, 6, 7, 8, 10]; const pesosSegundoDigito = [3, 2, 10, 9, 8, 7, 6, 5, 4, 3, 2]; const primeiroDigito = ie.charAt(posicaoP...
return /^P/.test(ieSemMascara) && this.validarInscricoesCom13Digitos(ieSemMascara); }
conditional_block