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 |
|---|---|---|---|---|
framerate.rs | //! Framerate control
use libc;
use libc::{c_void, size_t};
use std::mem;
use ::get_error;
use sys::gfx;
/// Structure holding the state and timing information of the framerate controller.
pub struct FPSManager {
raw: *mut gfx::framerate::FPSmanager,
}
impl FPSManager {
/// Create the framerate manager.
... |
/// Delay execution to maintain a constant framerate and calculate fps.
pub fn delay(&mut self) -> u32 {
unsafe { gfx::framerate::SDL_framerateDelay(self.raw) as u32 }
}
}
impl Drop for FPSManager {
fn drop(&mut self) {
unsafe { libc::free(self.raw as *mut c_void) }
}
}
| {
// will not get an error
unsafe { gfx::framerate::SDL_getFramecount(self.raw) as i32 }
} | identifier_body |
framerate.rs | //! Framerate control
use libc;
use libc::{c_void, size_t};
use std::mem;
use ::get_error;
use sys::gfx;
/// Structure holding the state and timing information of the framerate controller.
pub struct FPSManager {
raw: *mut gfx::framerate::FPSmanager, | unsafe {
let size = mem::size_of::<gfx::framerate::FPSmanager>() as size_t;
let raw = libc::malloc(size) as *mut gfx::framerate::FPSmanager;
gfx::framerate::SDL_initFramerate(raw);
FPSManager { raw: raw }
}
}
/// Set the framerate in Hz.
pub f... | }
impl FPSManager {
/// Create the framerate manager.
pub fn new() -> FPSManager { | random_line_split |
ssh.py | .
ref: https://github.com/paramiko/paramiko
This hook also lets you create ssh tunnel and serve as basis for SFTP file transfer
:param ssh_conn_id: :ref:`ssh connection id<howto/connection:ssh>` from airflow
Connections from where all the required parameters can be fetched like
username, pa... |
def __init__(
self,
ssh_conn_id: Optional[str] = None,
remote_host: Optional[str] = None,
username: Optional[str] = None,
password: Optional[str] = None,
key_file: Optional[str] = None,
port: Optional[int] = None,
timeout: int = 10,
keepalive_... | 'login': 'Username',
},
} | random_line_split |
ssh.py | .
ref: https://github.com/paramiko/paramiko
This hook also lets you create ssh tunnel and serve as basis for SFTP file transfer
:param ssh_conn_id: :ref:`ssh connection id<howto/connection:ssh>` from airflow
Connections from where all the required parameters can be fetched like
username, pa... |
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
if self.client is not None:
self.client.close()
self.client = None
def get_tunnel(
self, remote_port: int, remote_host: str = "localhost", local_port: Optional[int] = None
) -> SSHTunnelForwarder:
| warnings.warn(
'The contextmanager of SSHHook is deprecated.'
'Please use get_conn() as a contextmanager instead.'
'This method will be removed in Airflow 2.0',
category=DeprecationWarning,
)
return self | identifier_body |
ssh.py | .
ref: https://github.com/paramiko/paramiko
This hook also lets you create ssh tunnel and serve as basis for SFTP file transfer
:param ssh_conn_id: :ref:`ssh connection id<howto/connection:ssh>` from airflow
Connections from where all the required parameters can be fetched like
username, pa... |
self.no_host_key_check = no_host_key_check
if (
"allow_host_key_change" in extra_options
and str(extra_options["allow_host_key_change"]).lower() == 'true'
):
self.allow_host_key_change = True
... | raise ValueError("Must check host key when provided") | conditional_block |
ssh.py | .
ref: https://github.com/paramiko/paramiko
This hook also lets you create ssh tunnel and serve as basis for SFTP file transfer
:param ssh_conn_id: :ref:`ssh connection id<howto/connection:ssh>` from airflow
Connections from where all the required parameters can be fetched like
username, pa... | (self, exc_type, exc_val, exc_tb) -> None:
if self.client is not None:
self.client.close()
self.client = None
def get_tunnel(
self, remote_port: int, remote_host: str = "localhost", local_port: Optional[int] = None
) -> SSHTunnelForwarder:
| __exit__ | identifier_name |
test.ts | // This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test'; | import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
// Unfortunately there's no typing for the `__karma__` variable. Just ... | import 'zone.js/dist/jasmine-patch'; | random_line_split |
slidercc.core.js | _this.ready = true;
// console.log('Slider.init imagesLoaded',_this.$wrap.attr('id'));
_this.$wrap.trigger(_this.namespace+'-ready');
});
}
};
Slider.prototype.loadSlides = function(){
this.$slideList = $(this.$wrap).find(this.opts.slidesListSelector);
this.$slides = $(this.$wrap).find(this.opts.s... | random_line_split | ||
slidercc.core.js | slidercc')) |
this.init();
}
else {
this.$wrap.trigger(this.$wrap.data('slidercc').namespace+'-reset', opts);
}
};
Slider.prototype.modes = {};
Slider.prototype.init = function(){
var _this = this;
this.loadSlides();
if(this.testSlideLength()){
this.makeViewport();
this.$wrap.css('opacity', 0);
if(t... | {
if($.isEmptyObject(this.modes)) {
console.error('[CC Slider] No modules found.');
return false;
}
this.mode = this.modes[opts.mode || defaults.mode];
if(!this.mode) {
for(var firstMod in this.modes) {
break;
}
this.mode = this.modes[firstMod];
}
this.mode = new this.mode();... | conditional_block |
dummylayer.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2011-2012 Serge Noiraud
#
# 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; eithe... | GObject.type_register(DummyLayer) | random_line_split | |
dummylayer.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2011-2012 Serge Noiraud
#
# 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; eithe... | (GObject.GObject, osmgpsmap.MapLayer):
def __init__(self):
"""
Initialize the dummy layer
"""
GObject.GObject.__init__(self)
def do_draw(self, gpsmap, gdkdrawable):
"""
Draw the layer
"""
pass
def do_render(self, gpsmap):
"""
... | DummyLayer | identifier_name |
dummylayer.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2011-2012 Serge Noiraud
#
# 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; eithe... | The layer is busy
"""
return False
def do_button_press(self, gpsmap, gdkeventbutton):
"""
Someone press a button
"""
return False
GObject.type_register(DummyLayer)
| def __init__(self):
"""
Initialize the dummy layer
"""
GObject.GObject.__init__(self)
def do_draw(self, gpsmap, gdkdrawable):
"""
Draw the layer
"""
pass
def do_render(self, gpsmap):
"""
Render the layer
"""
pass
... | identifier_body |
browser_scanbox.py | # Copyright (C) 2015 Will Metcalf william.metcalf@gmail.com
#
# 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... | buf = self.get_argument(call, "Javascript")
else:
buf = self.get_argument(call, "Script")
if 'softwarelist.push(' in buf.lower() and 'indexof("-2147023083")' in buf.lower():
return True
elif 'var logger' in buf.lower() and 'document.onkeypress = ke... | filter_apinames = set(["JsEval", "COleScript_Compile", "COleScript_ParseScriptText"])
def on_call(self, call, process):
if call["api"] == "JsEval": | random_line_split |
browser_scanbox.py | # Copyright (C) 2015 Will Metcalf william.metcalf@gmail.com
#
# 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... | call["api"] == "JsEval":
buf = self.get_argument(call, "Javascript")
else:
buf = self.get_argument(call, "Script")
if 'softwarelist.push(' in buf.lower() and 'indexof("-2147023083")' in buf.lower():
return True
elif 'var logger' in buf.lower() and... | identifier_body | |
browser_scanbox.py | # Copyright (C) 2015 Will Metcalf william.metcalf@gmail.com
#
# 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... | elf, call, process):
if call["api"] == "JsEval":
buf = self.get_argument(call, "Javascript")
else:
buf = self.get_argument(call, "Script")
if 'softwarelist.push(' in buf.lower() and 'indexof("-2147023083")' in buf.lower():
return True
elif ... | _call(s | identifier_name |
browser_scanbox.py | # Copyright (C) 2015 Will Metcalf william.metcalf@gmail.com
#
# 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... | else:
buf = self.get_argument(call, "Script")
if 'softwarelist.push(' in buf.lower() and 'indexof("-2147023083")' in buf.lower():
return True
elif 'var logger' in buf.lower() and 'document.onkeypress = keypress;' in buf.lower() and 'setinterval(sendchar,' in bu... | f = self.get_argument(call, "Javascript")
| conditional_block |
noSwitchCaseFallThroughRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* 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... |
} else {
// case statement falling through a default
if (isFallingThrough && !isFallThroughAllowed(child)) {
const failureString = Rule.FAILURE_STRING_PART + "'default'";
this.addFailure(this.createFailure(switchClauses[i].getStart(), ... | {
if (!isFallThroughAllowed(switchClauses[i + 1])) {
this.addFailure(this.createFailure(
switchClauses[i + 1].getStart(),
"case".length,
`${Rule.FAILURE_STRING_PART}'case'`
... | conditional_block |
noSwitchCaseFallThroughRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* 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... | extends Lint.Rules.AbstractRule {
public static FAILURE_STRING_PART = "expected a 'break' before ";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new NoSwitchCaseFallThroughWalker(sourceFile, this.getOptions()));
}
}
export class NoSwitchCaseFallThrough... | Rule | identifier_name |
noSwitchCaseFallThroughRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* 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... | ));
}
}
} else {
// case statement falling through a default
if (isFallingThrough && !isFallThroughAllowed(child)) {
const failureString = Rule.FAILURE_STRING_PART + "'default'";
... | "case".length,
`${Rule.FAILURE_STRING_PART}'case'` | random_line_split |
async.js | /* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writ... | return hello;
}
async function runTest() {
debugger;
let result = await test();
console.log(result);
}
runTest(); | console.log(tmp); | random_line_split |
async.js | /* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writ... | () {
const hello = "world";
const tmp = await wait(1000);
console.log(tmp);
return hello;
}
async function runTest() {
debugger;
let result = await test();
console.log(result);
}
runTest();
| test | identifier_name |
async.js | /* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writ... |
runTest();
| {
debugger;
let result = await test();
console.log(result);
} | identifier_body |
modelsProgramsGetProgramByIdProgramViewModel.ts | /**
* Muscularity API
* The web API used by Muscularity web and mobile clients.
*
* OpenAPI spec version: v1
* Contact: support@muscularityapp.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.... | name?: string;
description?: string;
source?: string;
isPublic?: boolean;
createDate?: Date;
programDays?: Array<ModelsProgramsGetProgramByIdProgramDayViewModel>;
periodizationPhase?: ModelsProgramsGetProgramByIdPeriodizationPhaseViewModel;
} |
export interface ModelsProgramsGetProgramByIdProgramViewModel {
programId?: number; | random_line_split |
wps.py | Config.pl"))
# configure
# determine build type option to look for
self.comp_fam = self.toolchain.comp_family()
build_type_option = None
if LooseVersion(self.version) >= LooseVersion("3.4"):
knownbuildtypes = {
'smpar': 'serial',
... | make_module_extra | identifier_name | |
wps.py | get_software_version
from easybuild.tools.run import run_cmd, run_cmd_qa
class EB_WPS(EasyBlock):
"""Support for building/installing WPS."""
def __init__(self, *args, **kwargs):
"""Add extra config options specific to WPS."""
super(EB_WPS, self).__init__(*args, **kwargs)
self.build... |
def test_step(self):
"""Run WPS test (requires large dataset to be downloaded). """
wpsdir = None
def run_wps_cmd(cmdname, mpi_cmd=True):
"""Run a WPS command, and check for success."""
cmd = os.path.join(wpsdir, "%s.exe" % cmdname)
if mp... | """Build in install dir using compile script."""
cmd = "./%s" % self.compile_script
run_cmd(cmd, log_all=True, simple=True) | identifier_body |
wps.py | get_software_version
from easybuild.tools.run import run_cmd, run_cmd_qa
class EB_WPS(EasyBlock):
"""Support for building/installing WPS."""
def __init__(self, *args, **kwargs):
"""Add extra config options specific to WPS."""
super(EB_WPS, self).__init__(*args, **kwargs)
self.build... |
# check and fetch selected build type
bt = self.cfg['buildtype']
if not bt in knownbuildtypes.keys():
raise EasyBuildError("Unknown build type: '%s'. Supported build types: %s", bt, knownbuildtypes.keys())
# fetch option number based on build type option and selected buil... | knownbuildtypes = {
'smpar': 'serial',
'dmpar': 'DM parallel'
}
if self.comp_fam == toolchain.INTELCOMP: #@UndefinedVariable
build_type_option = "PC Linux x86_64, Intel compiler"
elif s... | conditional_block |
wps.py | , get_software_version
from easybuild.tools.run import run_cmd, run_cmd_qa
class EB_WPS(EasyBlock):
"""Support for building/installing WPS."""
def __init__(self, *args, **kwargs):
"""Add extra config options specific to WPS."""
super(EB_WPS, self).__init__(*args, **kwargs)
self.buil... | extra_vars = {
'buildtype': [None, "Specify the type of build (smpar: OpenMP, dmpar: MPI).", MANDATORY],
'runtest': [True, "Build and run WPS tests", CUSTOM],
'testdata': [testdata_urls, "URL to test data required to run WPS test", CUSTOM],
}
return EasyBlock.... | ] | random_line_split |
wwa_camera.ts |
import { WWAConsts, Position, Direction, speedList } from "./wwa_data";
import { Player } from "./wwa_parts_player";
export class Camera {
private _player: Player;
private _position: Position;
private _positionPrev: Position;
private _transitionStep: number;
private _isResetting: boolean;
/**... | n {
return this._positionPrev;
}
public resetPreviousPosition(): void {
this._positionPrev = null;
}
// throws OutOfWWAMapRangeError;
public move(dir: Direction): void {
var speed = speedList[this._player.getSpeedIndex()];
this._position = this._position.getNextFram... | (): Positio | identifier_name |
wwa_camera.ts |
import { WWAConsts, Position, Direction, speedList } from "./wwa_data";
import { Player } from "./wwa_parts_player";
export class Camera {
private _player: Player;
private _position: Position;
private _positionPrev: Position;
private _transitionStep: number;
private _isResetting: boolean;
/**... | n): void {
this._positionPrev = this._position;
this._position = position.getDefaultCameraPosition();
this._transitionStep = 0;
this._isResetting = true;
}
}
| === WWAConsts.V_PARTS_NUM_IN_WINDOW - 1;
}
public reset(position: Positio | conditional_block |
wwa_camera.ts | import { WWAConsts, Position, Direction, speedList } from "./wwa_data";
import { Player } from "./wwa_parts_player";
export class Camera {
private _player: Player;
private _position: Position;
private _positionPrev: Position;
private _transitionStep: number;
private _isResetting: boolean;
/**
... |
// throws OutOfWWAMapRangeError;
public move(dir: Direction): void {
var speed = speedList[this._player.getSpeedIndex()];
this._position = this._position.getNextFramePosition(
dir, speed * (WWAConsts.H_PARTS_NUM_IN_WINDOW - 1), speed * (WWAConsts.V_PARTS_NUM_IN_WINDOW - 1));
}
... | public resetPreviousPosition(): void {
this._positionPrev = null;
} | random_line_split |
wwa_camera.ts |
import { WWAConsts, Position, Direction, speedList } from "./wwa_data";
import { Player } from "./wwa_parts_player";
export class Camera {
private _player: Player;
private _position: Position;
private _positionPrev: Position;
private _transitionStep: number;
private _isResetting: boolean;
/**... | ed = speedList[this._player.getSpeedIndex()];
this._position = this._position.getNextFramePosition(
dir, speed * (WWAConsts.H_PARTS_NUM_IN_WINDOW - 1), speed * (WWAConsts.V_PARTS_NUM_IN_WINDOW - 1));
}
public getTransitionStepNum(): number {
return this._transitionStep;
}
p... | ve(dir: Direction): void {
var spe | identifier_body |
TwistFilter.ts | import { vertex } from '@tools/fragments';
import fragment from './twist.frag';
import { Filter } from '@pixi/core';
import { Point } from '@pixi/math';
interface TwistFilterOptions {
radius: number;
angle: number;
padding: number;
offset: Point;
}
/**
* This filter applies a twist effect making disp... |
set offset(value: Point)
{
this.uniforms.offset = value;
}
/**
* The radius of the twist.
*
* @member {number}
*/
get radius(): number
{
return this.uniforms.radius;
}
set radius(value: number)
{
this.uniforms.radius = value;
}
/... | {
return this.uniforms.offset;
} | identifier_body |
TwistFilter.ts | import { vertex } from '@tools/fragments';
import fragment from './twist.frag';
import { Filter } from '@pixi/core';
import { Point } from '@pixi/math';
interface TwistFilterOptions {
radius: number;
angle: number;
padding: number;
offset: Point;
}
/**
* This filter applies a twist effect making disp... | extends Filter
{
/** Default constructor options. */
public static readonly defaults: TwistFilterOptions = {
radius: 200,
angle: 4,
padding: 20,
offset: new Point(),
};
/**
* @param {object} [options] - Object object to use.
* @param {number} [options.radius=2... | TwistFilter | identifier_name |
TwistFilter.ts | import { vertex } from '@tools/fragments';
import fragment from './twist.frag';
import { Filter } from '@pixi/core';
import { Point } from '@pixi/math';
interface TwistFilterOptions {
radius: number;
angle: number;
padding: number;
offset: Point;
}
/**
* This filter applies a twist effect making disp... | export { TwistFilter };
export type { TwistFilterOptions }; | random_line_split | |
models.py | from __init__ import redis_db
from werkzeug.security import generate_password_hash, check_password_hash
from os import urandom
from base64 import b64encode
class User(object):
def __init__(self):
self.username = "" # required
self.password_hash = "" # required
self.phone_number = "" # req... |
@classmethod
def get_from_db(cls, username):
user_dict = redis_db.hmget(username, ["password_hash", "phone_number", "secret_key", "emergency_contact"])
fetched_user = User()
fetched_user.username = username
fetched_user.password_hash = user_dict[0]
fetched_user.phone_nu... | self.secret_key = b64encode(urandom(64)).decode("utf-8") | identifier_body |
models.py | from __init__ import redis_db
from werkzeug.security import generate_password_hash, check_password_hash
from os import urandom
from base64 import b64encode
class User(object):
def __init__(self):
self.username = "" # required
self.password_hash = "" # required
self.phone_number = "" # req... | if len(self.contacts):
redis_db.sadd(self.username + ":contacts", *self.contacts)
def deauthenticate(self):
self.secret_key = b64encode(urandom(64)).decode("utf-8")
@classmethod
def get_from_db(cls, username):
user_dict = redis_db.hmget(username, ["password_hash", "phon... | random_line_split | |
models.py | from __init__ import redis_db
from werkzeug.security import generate_password_hash, check_password_hash
from os import urandom
from base64 import b64encode
class User(object):
def __init__(self):
self.username = "" # required
self.password_hash = "" # required
self.phone_number = "" # req... | (self):
self.secret_key = b64encode(urandom(64)).decode("utf-8")
@classmethod
def get_from_db(cls, username):
user_dict = redis_db.hmget(username, ["password_hash", "phone_number", "secret_key", "emergency_contact"])
fetched_user = User()
fetched_user.username = username
... | deauthenticate | identifier_name |
models.py | from __init__ import redis_db
from werkzeug.security import generate_password_hash, check_password_hash
from os import urandom
from base64 import b64encode
class User(object):
def __init__(self):
self.username = "" # required
self.password_hash = "" # required
self.phone_number = "" # req... |
else:
fetched_user.contacts = redis_db.smembers(fetched_user.username + ":contacts")
return fetched_user
| return None | conditional_block |
study_hour.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime
import os
import psycopg2
import sys
con = None
f = None
try:
################ CHANGE THESE PARAMETERS ONLY ################
con = psycopg2.connect(database='switch', host='localhost', port='5432', user='deepakc_super', password='myPassword')
... | except psycopg2.DatabaseError, e:
if con:
con.rollback()
print 'Error %s' % e
sys.exit(1)
except IOError, e:
if con:
con.rollback()
print 'Error %s' % e
sys.exit(1)
finally:
if con:
con.close() | random_line_split | |
study_hour.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime
import os
import psycopg2
import sys
con = None
f = None
try:
################ CHANGE THESE PARAMETERS ONLY ################
con = psycopg2.connect(database='switch', host='localhost', port='5432', user='deepakc_super', password='myPassword')
... |
print 'Error %s' % e
sys.exit(1)
finally:
if con:
con.close()
| con.rollback() | conditional_block |
Sprite.ts | import { Coord } from "./Coord";
import { SpriteSheet } from "./SpriteSheet";
export class Sprite {
sheetPosition: Coord;
sheetSize: Coord;
spriteSheet: SpriteSheet;
constructor(
spriteSheet: SpriteSheet,
sheetPosition: Coord,
sheetSize: Coord,
) {
this.sheetPosition = sheetPosition;
this.sheetSize = s... | (context: CanvasRenderingContext2D, position: Coord, size: Coord) {
context.drawImage(
this.spriteSheet.image,
// Source xywh
this.sheetPosition.x *
this.spriteSheet.image.width /
this.spriteSheet.gridSize.x,
this.sheetPosition.y *
this.spriteSheet.image.height /
this.spriteSheet.gridSize... | draw | identifier_name |
Sprite.ts | import { Coord } from "./Coord";
import { SpriteSheet } from "./SpriteSheet";
export class Sprite {
sheetPosition: Coord;
sheetSize: Coord;
spriteSheet: SpriteSheet;
constructor(
spriteSheet: SpriteSheet,
sheetPosition: Coord,
sheetSize: Coord,
) {
this.sheetPosition = sheetPosition;
this.sheetSize = s... |
// Source xywh
this.sheetPosition.x *
this.spriteSheet.image.width /
this.spriteSheet.gridSize.x,
this.sheetPosition.y *
this.spriteSheet.image.height /
this.spriteSheet.gridSize.y,
this.spriteSheet.image.width / this.spriteSheet.gridSize.x,
this.spriteSheet.image.height / this.spriteShe... | context.drawImage(
this.spriteSheet.image, | random_line_split |
Footer.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
import React, {Component} from 'react';
import Link from 'gatsby-link';
import {Icon} from 'antd';
import '... |
}
| {
return (
<div className="Footer">
<a href="https://code.facebook.com/projects/" className="logoOSS">
<FacebookOSSLogo />
Facebook Open Source
</a>
<div className="SocialNetwork">
<a href="https://github.com/facebook/yoga">GitHub</a>
<a href="ht... | identifier_body |
Footer.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
* | */
import React, {Component} from 'react';
import Link from 'gatsby-link';
import {Icon} from 'antd';
import './Footer.css';
import FacebookOSSLogo from './FacebookOSSLogo';
export default class Footer extends Component<{}> {
render() {
return (
<div className="Footer">
<a href="https://code.face... | * This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format | random_line_split |
Footer.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
import React, {Component} from 'react';
import Link from 'gatsby-link';
import {Icon} from 'antd';
import '... | () {
return (
<div className="Footer">
<a href="https://code.facebook.com/projects/" className="logoOSS">
<FacebookOSSLogo />
Facebook Open Source
</a>
<div className="SocialNetwork">
<a href="https://github.com/facebook/yoga">GitHub</a>
<a href=... | render | identifier_name |
textformat.py | r'[\]^_`'
'𝗮𝗯𝗰𝗱𝗲𝗳𝗴𝗵𝗶𝗷𝗸𝗹𝗺𝗻𝗼𝗽𝗾𝗿𝘀𝘁𝘂𝘃𝘄𝘅𝘆𝘇'
'{|}~')
sanSerifItalic: str = (''' !"#$%&'()*+,-./'''
'𝟢𝟣𝟤𝟥𝟦𝟧𝟨𝟩𝟪𝟫'
':;<=>?@'
'𝘈𝘉𝘊𝘋𝘌𝘍𝘎𝘏𝘐𝘑𝘒𝘓𝘔𝘕𝘖𝘗𝘘𝘙𝘚𝘛𝘜𝘝𝘞𝘟𝘠𝘡'
... | = {
| identifier_name | |
textformat.py | ③④⑤⑥⑦⑧⑨'
':;<=>?@'
'ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ'
'[\\]^_`'
'ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ'
'{|}~')
smallcaps: str = (''' !"#$%&'()*+,-./'''
'0123456789'
':;<=>?@'
'ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴩQʀsᴛᴜᴠᴡxYᴢ... | ':;<=>?@'
'𝑨𝑩𝑪𝑫𝑬𝑭𝑮𝑯𝑰𝑱𝑲𝑳𝑴𝑵𝑶𝑷𝑸𝑹𝑺𝑻𝑼𝑽𝑾𝑿𝒀𝒁'
r'[\]^_`'
'𝒂𝒃𝒄𝒅𝒆𝒇𝒈𝒉𝒊𝒋𝒌𝒍𝒎𝒏𝒐𝒑𝒒𝒓𝒔𝒕𝒖𝒗𝒘𝒙𝒚𝒛'
'{|}~')
sanSerif: str = (''' !"#$%&'()*+,-./'''
'𝟢𝟣... | '𝟎𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗' | random_line_split |
textformat.py | %&'()*+,-./'''
'𝟬𝟭𝟮𝟯𝟰𝟱𝟲𝟳𝟴𝟵'
':;<=>?@'
'𝘼𝘽𝘾𝘿𝙀𝙁𝙂𝙃𝙄𝙅𝙆𝙇𝙈𝙉𝙊𝙋𝙌𝙍𝙎𝙏𝙐𝙑𝙒𝙓𝙔𝙕'
r'[\]^_`'
'𝙖𝙗𝙘𝙙𝙚𝙛𝙜𝙝𝙞𝙟𝙠𝙡𝙢𝙣𝙤𝙥𝙦𝙧𝙨𝙩𝙪𝙫𝙬𝙭𝙮𝙯'
... | identifier_body | ||
textformat.py | %&'()*+,-./'''
'𝟬𝟭𝟮𝟯𝟰𝟱𝟲𝟳𝟴𝟵'
':;<=>?@'
'𝘼𝘽𝘾𝘿𝙀𝙁𝙂𝙃𝙄𝙅𝙆𝙇𝙈𝙉𝙊𝙋𝙌𝙍𝙎𝙏𝙐𝙑𝙒𝙓𝙔𝙕'
r'[\]^_`'
'𝙖𝙗𝙘𝙙𝙚𝙛𝙜𝙝𝙞𝙟𝙠𝙡𝙢𝙣𝙤𝙥𝙦𝙧𝙨𝙩𝙪𝙫𝙬𝙭𝙮𝙯'
... | conditional_block | ||
index.js | import React, {PropTypes} from 'react';
export default class InfiniteScroll extends React.Component {
static propTypes = {
bufferPx: PropTypes.number,
callback: PropTypes.func,
autoFirstLoad: PropTypes.bool,
style: PropTypes.object
};
static defaultProps = {
bufferPx... | () {
if (!this.dom) {
return false;
}
this.dom.addEventListener('scroll', (e) => {
if (this.checkScrollBottom()) {
this.throttle(this.props.callback);
}
});
if (this.props.autoFirstLoad) {
this.props.callback();
... | componentDidMount | identifier_name |
index.js | import React, {PropTypes} from 'react';
export default class InfiniteScroll extends React.Component {
static propTypes = {
bufferPx: PropTypes.number, | };
static defaultProps = {
bufferPx: 40,
autoFirstLoad: false,
style: {}
};
constructor() {
super();
this.dom = null;
this.timer = null;
}
componentDidMount() {
if (!this.dom) {
return false;
}
this.dom.addEven... | callback: PropTypes.func,
autoFirstLoad: PropTypes.bool,
style: PropTypes.object | random_line_split |
index.js | import React, {PropTypes} from 'react';
export default class InfiniteScroll extends React.Component {
static propTypes = {
bufferPx: PropTypes.number,
callback: PropTypes.func,
autoFirstLoad: PropTypes.bool,
style: PropTypes.object
};
static defaultProps = {
bufferPx... |
});
if (this.props.autoFirstLoad) {
this.props.callback();
}
}
componentDidUpdate(prevProps) {
if (prevProps.children !== this.props.children) {
if (!this.checkBottom()) {
this.throttle(this.props.callback);
}
}
}
... | {
this.throttle(this.props.callback);
} | conditional_block |
index.js | import React, {PropTypes} from 'react';
export default class InfiniteScroll extends React.Component {
static propTypes = {
bufferPx: PropTypes.number,
callback: PropTypes.func,
autoFirstLoad: PropTypes.bool,
style: PropTypes.object
};
static defaultProps = {
bufferPx... |
checkScrollBottom() {
if (!this.dom) {
return false;
}
if (this.dom.scrollTop === 0) {
return true;
}
return this.dom.scrollTop + this.dom.clientHeight + this.props.bufferPx >= this.dom.scrollHeight;
}
checkBottom() {
if (!this.dom) ... | {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
if (typeof func === 'function') {
func();
}
}, time);
} | identifier_body |
ethkey.rs | bool,
arg_prefix: String,
arg_iterations: String,
arg_seed: String,
arg_secret: String,
arg_message: String,
arg_public: String,
arg_address: String,
arg_signature: String,
flag_secret: bool,
flag_public: bool,
flag_address: bool,
}
#[derive(Debug)]
enum Error {
Ethkey(EthkeyError),
FromHex(FromHexError)... | let expected =
"secret: 17d08f5fe8c77af811caa0c9a187e668ce3b74a99acc3f6d976f075fa8e0be55
public: 689268c0ff57a20cd299fa60d3fb374862aff565b20b5f1767906a99e6e09f3ff04ca2b2a5cd22f62941db103c0356df1a8ed20ce322cab2483db67685afd124
address: 26d1ec50b4e62c1d1a40d16e7cacc6a6580757d5".to_owned();
assert_eq!(execute(comman... | random_line_split | |
ethkey.rs | bool,
arg_prefix: String,
arg_iterations: String,
arg_seed: String,
arg_secret: String,
arg_message: String,
arg_public: String,
arg_address: String,
arg_signature: String,
flag_secret: bool,
flag_public: bool,
flag_address: bool,
}
#[derive(Debug)]
enum Error {
Ethkey(EthkeyError),
FromHex(FromHexError)... | () {
let command = vec!["ethkey", "info", "17d08f5fe8c77af811caa0c9a187e668ce3b74a99acc3f6d976f075fa8e0be55"]
.into_iter()
.map(Into::into)
.collect::<Vec<String>>();
let expected =
"secret: 17d08f5fe8c77af811caa0c9a187e668ce3b74a99acc3f6d976f075fa8e0be55
public: 689268c0ff57a20cd299fa60d3fb374862aff565... | info | identifier_name |
ethkey.rs | bool,
arg_prefix: String,
arg_iterations: String,
arg_seed: String,
arg_secret: String,
arg_message: String,
arg_public: String,
arg_address: String,
arg_signature: String,
flag_secret: bool,
flag_public: bool,
flag_address: bool,
}
#[derive(Debug)]
enum Error {
Ethkey(EthkeyError),
FromHex(FromHexError)... |
}
enum DisplayMode {
KeyPair,
Secret,
Public,
Address,
}
impl DisplayMode {
fn new(args: &Args) -> Self {
if args.flag_secret {
DisplayMode::Secret
} else if args.flag_public {
DisplayMode::Public
} else if args.flag_address {
DisplayMode::Address
} else {
DisplayMode::KeyPair
}
}
}
fn m... | {
match *self {
Error::Ethkey(ref e) => write!(f, "{}", e),
Error::FromHex(ref e) => write!(f, "{}", e),
Error::ParseInt(ref e) => write!(f, "{}", e),
}
} | identifier_body |
user.effect.ts | import { Injectable } from "@angular/core";
import { Actions, createEffect, ofType } from "@ngrx/effects";
import { EMPTY } from "rxjs";
import { catchError, map, switchMap } from "rxjs/operators";
import { getLogger } from "../../@core/logging";
import { PsaAuthService } from "../../@core/service/psa-auth.service";
i... | (
private readonly actions$: Actions,
private readonly authService: PsaAuthService,
) {
}
}
| constructor | identifier_name |
tornado_server.py | import os.path
import logging
_logger = logging.getLogger(__name__)
from operator import itemgetter
from tornado.web import Application, RequestHandler, StaticFileHandler
from tornado.ioloop import IOLoop
config = {
'DEBUG': True,
'PORT' : 5000
}
HANDLERS = []
ROOT_DIR = os.path.abspath(os.path.join(os.pa... |
class MainHandler(RequestHandler):
def get(self):
self.render("index.html")
def main():
global HANDLERS
HANDLERS += [(r'/(.+)', StaticFileHandler, {'path': ROOT_DIR}),
(r'/', MainHandler)]
app = Application(HANDLERS,
debug=config.get('DEBUG', False), st... | from GfxTablet import GfxTabletHandler
HANDLERS.append((r'/gfxtablet', GfxTabletHandler))
| random_line_split |
tornado_server.py | import os.path
import logging
_logger = logging.getLogger(__name__)
from operator import itemgetter
from tornado.web import Application, RequestHandler, StaticFileHandler
from tornado.ioloop import IOLoop
config = {
'DEBUG': True,
'PORT' : 5000
}
HANDLERS = []
ROOT_DIR = os.path.abspath(os.path.join(os.pa... | (RequestHandler):
def get(self):
self.render("index.html")
def main():
global HANDLERS
HANDLERS += [(r'/(.+)', StaticFileHandler, {'path': ROOT_DIR}),
(r'/', MainHandler)]
app = Application(HANDLERS,
debug=config.get('DEBUG', False), static_path=ROOT_DIR... | MainHandler | identifier_name |
tornado_server.py | import os.path
import logging
_logger = logging.getLogger(__name__)
from operator import itemgetter
from tornado.web import Application, RequestHandler, StaticFileHandler
from tornado.ioloop import IOLoop
config = {
'DEBUG': True,
'PORT' : 5000
}
HANDLERS = []
ROOT_DIR = os.path.abspath(os.path.join(os.pa... |
def main():
global HANDLERS
HANDLERS += [(r'/(.+)', StaticFileHandler, {'path': ROOT_DIR}),
(r'/', MainHandler)]
app = Application(HANDLERS,
debug=config.get('DEBUG', False), static_path=ROOT_DIR)
_logger.info("app.settings:\n%s" % '\n'.join(['%s: %s' % (k, st... | def get(self):
self.render("index.html") | identifier_body |
tornado_server.py | import os.path
import logging
_logger = logging.getLogger(__name__)
from operator import itemgetter
from tornado.web import Application, RequestHandler, StaticFileHandler
from tornado.ioloop import IOLoop
config = {
'DEBUG': True,
'PORT' : 5000
}
HANDLERS = []
ROOT_DIR = os.path.abspath(os.path.join(os.pa... |
class MainHandler(RequestHandler):
def get(self):
self.render("index.html")
def main():
global HANDLERS
HANDLERS += [(r'/(.+)', StaticFileHandler, {'path': ROOT_DIR}),
(r'/', MainHandler)]
app = Application(HANDLERS,
debug=config.get('DEBUG', False),... | import sys
sys.path.insert(0, GFXTABLET_DIR)
from GfxTablet import GfxTabletHandler
HANDLERS.append((r'/gfxtablet', GfxTabletHandler)) | conditional_block |
prompt.py | class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'Prompt',
# list of one or more authors for the module
... | """ % (appName, appName, appName, appName)
return script
| listApps = self.options['ListApps']['Value']
appName = self.options['AppName']['Value']
if listApps != "":
script = """
import os
apps = [ app.split('.app')[0] for app in os.listdir('/Applications/') if not app.split('.app')[0].startswith('.')]
choices = []
for x in xrange(len(apps)):
c... | identifier_body |
prompt.py | class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'Prompt',
# list of one or more authors for the module
... | (self):
listApps = self.options['ListApps']['Value']
appName = self.options['AppName']['Value']
if listApps != "":
script = """
import os
apps = [ app.split('.app')[0] for app in os.listdir('/Applications/') if not app.split('.app')[0].startswith('.')]
choices = []
for x in xrange(... | generate | identifier_name |
prompt.py | class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'Prompt',
# list of one or more authors for the module
... |
def generate(self):
listApps = self.options['ListApps']['Value']
appName = self.options['AppName']['Value']
if listApps != "":
script = """
import os
apps = [ app.split('.app')[0] for app in os.listdir('/Applications/') if not app.split('.app')[0].startswith('.')]
choices = [... | for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value | conditional_block |
prompt.py | class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'Prompt', | 'Author': ['@FuzzyNop', '@harmj0y'],
# more verbose multi-line description of the module
'Description': ('Launches a specified application with an prompt for credentials with osascript.'),
# True if the module needs to run in the background
'Background' : Fa... |
# list of one or more authors for the module | random_line_split |
jeanstest.py | 0.05*wavelength
lmax = 1.95*wavelength
ratiomin = 0.0
ratiomax = 2.0
numSimMax = 24
stable_lambdas = []
stable_periods = []
unstable_lambdas = []
unstable_periods = [] |
stable_wavelengths = np.arange(lmin, 0.999*wavelength, 0.001)
unstable_wavelengths = np.arange(1.001*wavelength, lmax, 0.001)
x_solution = np.arange(0.0, wavelength, 0.001*wavelength)
# Analytical solutions for stable and unstable modes (for function fitting)
#-----------------------------------------------------... | random_line_split | |
jeanstest.py | 0.05*wavelength
lmax = 1.95*wavelength
ratiomin = 0.0
ratiomax = 2.0
numSimMax = 24
stable_lambdas = []
stable_periods = []
unstable_lambdas = []
unstable_periods = []
stable_wavelengths = np.arange(lmin, 0.999*wavelength, 0.001)
unstable_wavelengths = np.arange(1.001*wavelength, lmax, 0.001)
x_solu... |
print 'LAMBDA_JEANS : ',lambda_jeans,tsim
sim = newsim('jeans_mfm.dat')
sim.SetParam('tend', tsim)
sim.SetParam('tsnapfirst', tsim)
sim.SetParam('temp0', temp0)
setupsim()
run()
# Get grav. data for simulaton for plotting
x_data = get_data("x", sim=sim_no)
vx_data = get_da... | tsim = 0.3*oscillation_period(lambda_jeans) | conditional_block |
jeanstest.py | 0.05*wavelength
lmax = 1.95*wavelength
ratiomin = 0.0
ratiomax = 2.0
numSimMax = 24
stable_lambdas = []
stable_periods = []
unstable_lambdas = []
unstable_periods = []
stable_wavelengths = np.arange(lmin, 0.999*wavelength, 0.001)
unstable_wavelengths = np.arange(1.001*wavelength, lmax, 0.001)
x_solu... | (lambda_jeans):
return np.sqrt(np.pi/rho0)*wavelength/np.sqrt(lambda_jeans*lambda_jeans - wavelength*wavelength)
def growth_timescale(lambda_jeans):
return np.sqrt(1/4.0/np.pi/rho0)*wavelength/np.sqrt(wavelength*wavelength - lambda_jeans*lambda_jeans)
# Quick sims to generate
periodic_sim = newsim('jeans.dat... | oscillation_period | identifier_name |
jeanstest.py | 0.05*wavelength
lmax = 1.95*wavelength
ratiomin = 0.0
ratiomax = 2.0
numSimMax = 24
stable_lambdas = []
stable_periods = []
unstable_lambdas = []
unstable_periods = []
stable_wavelengths = np.arange(lmin, 0.999*wavelength, 0.001)
unstable_wavelengths = np.arange(1.001*wavelength, lmax, 0.001)
x_solu... |
# Quick sims to generate
periodic_sim = newsim('jeans.dat')
periodic_sim.SetParam('tsnapfirst', 0.0)
periodic_sim.SetParam('temp0', 0.1)
periodic_sim.SetParam('amp', 0.15)
periodic_sim.SetParam('Nstepsmax',1)
setupsim()
run()
# Get grav. data for simulaton for plotting
x_data0 = get_data("x", sim=sim_no)
ax_data0... | return np.sqrt(1/4.0/np.pi/rho0)*wavelength/np.sqrt(wavelength*wavelength - lambda_jeans*lambda_jeans) | identifier_body |
vec-matching-autoslice.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = [1, 2, 3];
match x {
[2, _, _] => panic!(),
[1, a, b] => {
assert!([a, b] == [2, 3]);
}
[_, _, _] => panic!(),
}
let y = ([(1, true), (2, false)], 0.5f64);
match y {
([(1, a), (b, false)], _) => {
assert_eq!(a, true);
... | identifier_body | |
vec-matching-autoslice.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = [1, 2, 3];
match x {
[2, _, _] => panic!(),
[1, a, b] => {
assert!([a, b] == [2, 3]);
}
[_, _, _] => panic!(),
}
let y = ([(1, true), (2, false)], 0.5f64);
match y {
([(1, a), (b, false)], _) => {
assert_eq!(a, true);
... | main | identifier_name |
vec-matching-autoslice.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub fn main() {
let x = [1, 2, 3];
match x {
[2, _, _] => panic!(),
... | random_line_split | |
create_new_scheme_with_novel.py | #!/usr/bin/env python
import logging
logger = logging.getLogger()
import argparse
import collections
import sys
import os
from Bio import SeqIO |
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Adds novel alleles to an existing MLST scheme.")
parser.add_argument("-n", "--novel", type=str, help="FASTA with novel alleles.")
parser.add_argument("-o", "--output", type=str, help="Output folder for new scheme.")
parser.add_ar... | random_line_split | |
create_new_scheme_with_novel.py | #!/usr/bin/env python
import logging
logger = logging.getLogger()
import argparse
import collections
import sys
import os
from Bio import SeqIO
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Adds novel alleles to an existing MLST scheme.")
parser.add_argument("-n", "--novel", type=... |
# save:
SeqIO.write(record_list, os.path.join(param.output, os.path.basename(f)), "fasta")
logger.info("Done.")
| id_list = [int(s.id.split("_")[-1]) for s in record_list]
next_id = max(id_list) + 1
# append novels:
for record in novel[locus]:
record.id += "_%d" % next_id
record.name = record.description = ""
next_id += 1
record_lis... | conditional_block |
journey-search.component.ts | '],
viewProviders: [],
providers: [Device, LocationService]
})
/** @classdesc Manages journey search form.
* Expects to be embedded in containing component taking care of
* search execution and presentation of search results
*/
export class JourneySearchComponent {
// attributes
@Input() public date: any = null;... | { // use fallback (string parsing could be unreliable, but seems to work)
this.datetime = _parseDate(this.date) + 'T' + _parseTime(this.time) + 'Z'; // parse date and time entries
date = !isNaN(Date.parse(this.datetime)) ? new Date(this.datetime) : now; // cast to UTC Date, or default to now
} | conditional_block | |
journey-search.component.ts | {htmlTemplate} from './journey-search.component.html'; // include template in compiled bundle; external html may cause extra http request
//import htmlTemplate: string from './journey-search.component.html'; // no need for ts literal when ts compiler catches up
import {styles} from './journey-search.component.css';... |
/** Captures updates to component data when entries are made/deleted in from/to fields */
public onFromToChange(event: any) {
this[event.target.name] = event.detail.value;
this.valid = this.origin !== null && this.destination !== null;
}
/** Fetches from/to autocomplete suggestions in response to us... | {
if (event && event.srcElement.date && event.srcElement.date.constructor === Date) {
this.date = this._formatDate(event.srcElement.date);
}
} | identifier_body |
journey-search.component.ts | import {htmlTemplate} from './journey-search.component.html'; // include template in compiled bundle; external html may cause extra http request
//import htmlTemplate: string from './journey-search.component.html'; // no need for ts literal when ts compiler catches up
import {styles} from './journey-search.componen... | let hours: string = (time[time.length-4] !== undefined ? time[time.length-4] : '0' ) // tens of hours
+ (time[time.length-3] !== undefined ? time[time.length-3] : '0' ) // single hours
hours = isPM ? String(Number(hours) + 12) : hours; // adjust for pm
time = !time.length ? now.toTimeString().s... | function _parseTime(time: any): string {
let isPM: boolean = time.toLowerCase().indexOf('pm') > -1;
time = time.replace(/\D/g, '').split(''); // strip non-digits, get array of single characters | random_line_split |
journey-search.component.ts | {htmlTemplate} from './journey-search.component.html'; // include template in compiled bundle; external html may cause extra http request
//import htmlTemplate: string from './journey-search.component.html'; // no need for ts literal when ts compiler catches up
import {styles} from './journey-search.component.css';... | (event: any): void {
if (event && event.srcElement.date && event.srcElement.date.constructor === Date) {
this.date = this._formatDate(event.srcElement.date);
}
}
/** Captures updates to component data when entries are made/deleted in from/to fields */
public onFromToChange(event: any) {
this[ev... | onDateChange | identifier_name |
variables.py | import sublime
import collections
VAR_MAP_LEADER = 'mapleader'
VAR_MAP_LOCAL_LEADER = 'maplocalleader'
# well-known variables
_SPECIAL_STRINGS = {
'<leader>': VAR_MAP_LEADER,
'<localleader>': VAR_MAP_LOCAL_LEADER,
}
_DEFAULTS = {
VAR_MAP_LEADER: '\\',
VAR_MAP_LOCAL_LEADER: '\\'
}
_VARIABLES = {... | (self, instance, owner):
self.view = instance.view
self.settings = instance.settings
return self
def get(self, name):
return get(name)
def set(self, name, value):
return set_(name, value)
| __get__ | identifier_name |
variables.py | import sublime
import collections
VAR_MAP_LEADER = 'mapleader'
VAR_MAP_LOCAL_LEADER = 'maplocalleader'
# well-known variables
_SPECIAL_STRINGS = {
'<leader>': VAR_MAP_LEADER,
'<localleader>': VAR_MAP_LOCAL_LEADER,
}
_DEFAULTS = {
VAR_MAP_LEADER: '\\',
VAR_MAP_LOCAL_LEADER: '\\'
}
_VARIABLES = {... |
if seq.lower().startswith('<localleader>'):
var = '<localleader>'
local_leader = _VARIABLES.get('maplocalleader',
_DEFAULTS.get('maplocalleader'))
try:
return leader + seq[len(var_name):]
except TypeError:
return seq
def is_key_name(name):
... | var_name = '<leader>'
leader = _VARIABLES.get('mapleader', _DEFAULTS.get('mapleader')) | conditional_block |
variables.py | import sublime
import collections
VAR_MAP_LEADER = 'mapleader'
VAR_MAP_LOCAL_LEADER = 'maplocalleader'
# well-known variables
_SPECIAL_STRINGS = {
'<leader>': VAR_MAP_LEADER,
'<localleader>': VAR_MAP_LOCAL_LEADER,
}
_DEFAULTS = {
VAR_MAP_LEADER: '\\',
VAR_MAP_LOCAL_LEADER: '\\'
}
_VARIABLES = {... | '''Stores variables during the current Sublime Text session.
Meant to be used as a descriptor with `State`.
'''
def __get__(self, instance, owner):
self.view = instance.view
self.settings = instance.settings
return self
def get(self, name):
return get(name)
def set... | identifier_body | |
variables.py | import sublime
import collections
VAR_MAP_LEADER = 'mapleader'
VAR_MAP_LOCAL_LEADER = 'maplocalleader'
# well-known variables
_SPECIAL_STRINGS = {
'<leader>': VAR_MAP_LEADER,
'<localleader>': VAR_MAP_LOCAL_LEADER,
}
_DEFAULTS = {
VAR_MAP_LEADER: '\\',
VAR_MAP_LOCAL_LEADER: '\\'
}
_VARIABLES = {... | _DEFAULTS.get('maplocalleader'))
try:
return leader + seq[len(var_name):]
except TypeError:
return seq
def is_key_name(name):
return name.lower() in _SPECIAL_STRINGS
def get(name):
name = name.lower()
name = _SPECIAL_STRINGS.get(name, name)
return... | local_leader = _VARIABLES.get('maplocalleader', | random_line_split |
addLocking.js | (function (root, factory) { // UMD from https://github.com/umdjs/umd/blob/master/returnExports.js
"use strict";
if (typeof exports === 'object') {
module.exports = factory();
} else {
define(factory);
}
}(this, function () {
"use strict";
// Author: Matthew Forrester <matt_at_keyboardwritescode.com>
// Copyr... | * **@return {Boolean}** False if the lock was not present, True otherwise.
*/
classFunc.prototype._unlockFor = function(lockType) {
this._ensureLockingData();
if (!(this._locked & lockType)) {
return false;
}
this._locked = this._locked ^ (maxLockingValue & lockType);
};
/**
* ### classFunc.isLo... | random_line_split | |
addLocking.js | (function (root, factory) { // UMD from https://github.com/umdjs/umd/blob/master/returnExports.js
"use strict";
if (typeof exports === 'object') | else {
define(factory);
}
}(this, function () {
"use strict";
// Author: Matthew Forrester <matt_at_keyboardwritescode.com>
// Copyright: Matthew Forrester
// License: MIT/BSD-style
/**
* # addLocking()
*
* Adds internal locking to an existing pseudo-classical Javascript class
*
* ## Example
*
* ```java... | {
module.exports = factory();
} | conditional_block |
find.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cookiecutter.find
-----------------
Functions for finding Cookiecutter templates and other components.
"""
import logging
import os
from .exceptions import NonTemplatedInputDirException
def | (repo_dir):
"""
Determines which child directory of `repo_dir` is the project template.
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logging.debug('Searching {0} for the project template.'.format(repo_dir))
repo_d... | find_template | identifier_name |
find.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cookiecutter.find
-----------------
Functions for finding Cookiecutter templates and other components.
"""
import logging
import os
from .exceptions import NonTemplatedInputDirException
def find_template(repo_dir):
| 'The project template appears to be {0}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
| """
Determines which child directory of `repo_dir` is the project template.
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logging.debug('Searching {0} for the project template.'.format(repo_dir))
repo_dir_contents = os... | identifier_body |
find.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cookiecutter.find
-----------------
Functions for finding Cookiecutter templates and other components.
"""
import logging
import os
from .exceptions import NonTemplatedInputDirException
def find_template(repo_dir):
"""
Determines which child directory of `... |
if project_template:
project_template = os.path.join(repo_dir, project_template)
logging.debug(
'The project template appears to be {0}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
| if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break | conditional_block |
find.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cookiecutter.find
-----------------
Functions for finding Cookiecutter templates and other components.
"""
import logging
import os
from .exceptions import NonTemplatedInputDirException
def find_template(repo_dir):
"""
Determines which child directory of `... |
logging.debug('Searching {0} for the project template.'.format(repo_dir))
repo_dir_contents = os.listdir(repo_dir)
project_template = None
for item in repo_dir_contents:
if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break
if ... | :param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
""" | random_line_split |
schema.js | import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import organSiteCategories from './organSiteCategories';
import riskEstimateSchema from './riskEstimateSchema';
import { isNumericishString } from '/imports/api/validators';
export default {
organSiteCategory: {
label: 'Organ site',
typ... | stratum: {
label: 'Stratum (if relevant)',
type: String,
optional: true,
popoverText: 'e.g.: men only, women only',
typeaheadMethod: 'searchStratum',
},
trendTest: {
label: 'Trend p-value',
type: String,
optional: true,
custom: isNumeri... | typeaheadMethod: 'searchEffectUnits',
}, | random_line_split |
init.js | return map.containsKey(name);
},
__delete__ : function (name) {
return map.remove(name);
},
__put__ : function(name, value) {
map.put(name, value);
},
__getIds__ : function() {
return map.keySet().toArray();
},
toString: function() {
return map.toString();
}
});
}
/**
* C... | random_line_split | ||
init.js | example,
* scriptObj[index] syntax can be used to access values in the List instance.
* 'length' field gives size of the List. <br>
*
* Example:
* <pre>
* <code>
* var x = new java.util.ArrayList(4);
* x.add('Java');
* x.add('JavaScript');
* x.add('SQL');
* x.add('XML');
*
* var y = jlis... | (dir) {
var dir = pathToFile(dir);
println(dir.mkdir()? "created" : "can not create dir");
}
/**
* Creates the directory named by given pathname, including
* any necessary but nonexistent parent directories.
*
* @param dir input path name
*/
function mkdirs(dir) {
var dir = pathToFile(dir);
println(dir.mkdir... | mkdir | identifier_name |
init.js | ()) {
curDir = target;
} else {
println(target + " is not a directory");
}
}
/**
* Converts path to java.io.File taking care of shell present working dir
*
* @param pathname file path to be converted
* @private
*/
function pathToFile(pathname) {
var tmp = pathname;
if (!(tmp instanceof File)) {
tmp = ne... | {
return builder.newDocument();
} | conditional_block | |
init.js | example,
* scriptObj[index] syntax can be used to access values in the List instance.
* 'length' field gives size of the List. <br>
*
* Example:
* <pre>
* <code>
* var x = new java.util.ArrayList(4);
* x.add('Java');
* x.add('JavaScript');
* x.add('SQL');
* x.add('XML');
*
* var y = jlis... | } else {
while ((line=obj.readLine()) != null) {
println(line);
}
}
}
/**
* Returns directory part of a filename
*
* @param pathname input path name
* @return directory part of the given file name
*/
function dirname(pathname) {
var dirName = ".";
// Normalize '/' to local file separator before work.
... | {
if (obj instanceof File && obj.isDirectory()) {
ls(obj);
return;
}
var inp = null;
if (!(obj instanceof Reader)) {
inp = inStream(obj);
obj = new BufferedReader(new InputStreamReader(inp));
}
var line;
if (pattern) {
var count = 1;
while ((line=obj.readLine()) != null) {
if (line.match(pattern... | identifier_body |
util.js |
// If the object has children, add a slash.
var newPoss = {};
for (var item in possibilities) {
var keys = Object.keys(possibilities[item]);
keys = keys.filter(function (key) {
return String(key).slice(0, 2) !== '__';
});
if (keys.length > 0) {
newPoss[item + '/'] =... | {
var results = {};
for (var item in objs) {
if (objs[item].__class === type) {
results[item] = objs[item];
}
}
return Object.keys(results);
} | identifier_body | |
util.js | for (var i = 0; i < cats.length; ++i) {
data[cats[i]] = filter(newPoss, cats[i]);
matches = matches.concat(data[cats[i]]);
}
// Data.remainer takes care of any items that don't
// have a `__class` attribute in the index.
data.remainder = all.filter(function (item) {
return matches.in... | var maxHeight = process.stdout.rows - 4;
maxHeight = maxHeight > 24 ? 24 : maxHeight;
// Match pad all other blocks with white-space
// lines at the bottom to match the length of
// the longest block. In other words, make the
// blocks... blocks.
combined = combined.map(function (lines) {
... | random_line_split | |
util.js | for (var i = 0; i < cats.length; ++i) {
data[cats[i]] = filter(newPoss, cats[i]);
matches = matches.concat(data[cats[i]]);
}
// Data.remainer takes care of any items that don't
// have a `__class` attribute in the index.
data.remainder = all.filter(function (item) {
return matches.in... | () {
var lineWidth = strip(line).length;
longestLine = lineWidth > longestLine ? lineWidth : longestLine;
lines += line + '\n';
line = '';
ctr = 1;
}
for (var i = 0; i < arr.length; ++i) {
var _item = self.pad(arr[i], width) + ' ';
_item = color ? cha... | endLine | identifier_name |
util.js |
}
return Object.keys(results);
}
// If the object has children, add a slash.
var newPoss = {};
for (var item in possibilities) {
var keys = Object.keys(possibilities[item]);
keys = keys.filter(function (key) {
return String(key).slice(0, 2) !== '__';
});
if ... | {
results[item] = objs[item];
} | conditional_block | |
bucket-settings.js | /**
*
* Bucket Settings Component
* @parent ToolSettings
* @author Robert P.
*
*/
import React from 'react';
import BaseComponent from '../../../base-component/base-component';
import {branch} from 'baobab-react/higher-order';
import ColorPicker from 'react-color';
import * as actions from '../../actions';
con... | this._bind('_handleChange');
}
_handleChange(color) {
let color2 = '#' + color.hex;
this.props.actions.updateColor(color2);
}
render() {
const props = this.props;
return (
<aside>
<p className="settingsTitle">Bucket settings</p>
<div className="settings settings--short">
<ColorPicker
... | constructor(props) {
super(props);
| random_line_split |
bucket-settings.js | /**
*
* Bucket Settings Component
* @parent ToolSettings
* @author Robert P.
*
*/
import React from 'react';
import BaseComponent from '../../../base-component/base-component';
import {branch} from 'baobab-react/higher-order';
import ColorPicker from 'react-color';
import * as actions from '../../actions';
con... | (color) {
let color2 = '#' + color.hex;
this.props.actions.updateColor(color2);
}
render() {
const props = this.props;
return (
<aside>
<p className="settingsTitle">Bucket settings</p>
<div className="settings settings--short">
<ColorPicker
color = {props.color}
onChange = {this.... | _handleChange | identifier_name |
bucket-settings.js | /**
*
* Bucket Settings Component
* @parent ToolSettings
* @author Robert P.
*
*/
import React from 'react';
import BaseComponent from '../../../base-component/base-component';
import {branch} from 'baobab-react/higher-order';
import ColorPicker from 'react-color';
import * as actions from '../../actions';
con... |
}
export default branch(BucketSettings, {
cursors: {
color: ['color']
},
actions: {
updateColor: actions.updateColor
}
}); | {
const props = this.props;
return (
<aside>
<p className="settingsTitle">Bucket settings</p>
<div className="settings settings--short">
<ColorPicker
color = {props.color}
onChange = {this._handleChange}
type="chrome"
/>
</div>
</aside>
);
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.