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
window.js
/** * A debounce method that has a sliding window, there's a minimum and maximum wait time **/ module.exports = function (cb, min, max, settings) { var ctx, args, next, limit, timeout; if (!settings) { settings = {}; } function
() { limit = null; cb.apply(settings.context || ctx, args); } function run() { var now = Date.now(); if (now >= limit || now >= next) { fire(); } else { timeout = setTimeout(run, Math.min(limit, next) - now); } } let fn = function windowed() { var now = Date.now(); ctx = this; args = arg...
fire
identifier_name
window.js
/** * A debounce method that has a sliding window, there's a minimum and maximum wait time **/ module.exports = function (cb, min, max, settings) { var ctx, args, next, limit, timeout; if (!settings) { settings = {}; } function fire()
function run() { var now = Date.now(); if (now >= limit || now >= next) { fire(); } else { timeout = setTimeout(run, Math.min(limit, next) - now); } } let fn = function windowed() { var now = Date.now(); ctx = this; args = arguments; next = now + min; if (!limit) { limit = now + max;...
{ limit = null; cb.apply(settings.context || ctx, args); }
identifier_body
window.js
/** * A debounce method that has a sliding window, there's a minimum and maximum wait time **/ module.exports = function (cb, min, max, settings) { var ctx, args, next, limit, timeout; if (!settings)
function fire() { limit = null; cb.apply(settings.context || ctx, args); } function run() { var now = Date.now(); if (now >= limit || now >= next) { fire(); } else { timeout = setTimeout(run, Math.min(limit, next) - now); } } let fn = function windowed() { var now = Date.now(); ctx = th...
{ settings = {}; }
conditional_block
models.py
from django.db import models from django.contrib.auth.models import User import MySQLdb # Create your models here. class Comentario(models.Model): """Comentario""" contenido = models.TextField(help_text='Escribe un comentario') fecha_coment = models.DateField(auto_now=True)
nom_estado = models.CharField(max_length=50) def __unicode__(self): return nom_estado class Categoria(models.Model): """Categoria""" nombre = models.CharField(max_length=50) descripcion = models.TextField(help_text='Escribe una descripcion de la categoria') class Entrada(models.Model): """Entrada""" autor =...
def __unicode__(self): return self.contenido class Estado(models.Model): """Estado"""
random_line_split
models.py
from django.db import models from django.contrib.auth.models import User import MySQLdb # Create your models here. class Comentario(models.Model): """Comentario""" contenido = models.TextField(help_text='Escribe un comentario') fecha_coment = models.DateField(auto_now=True) def __unicode__(self): return self.c...
(models.Model): """Categoria""" nombre = models.CharField(max_length=50) descripcion = models.TextField(help_text='Escribe una descripcion de la categoria') class Entrada(models.Model): """Entrada""" autor = models.ForeignKey(User) comentario = models.ForeignKey(Comentario) estado = models.ForeignKey(Estado) ...
Categoria
identifier_name
models.py
from django.db import models from django.contrib.auth.models import User import MySQLdb # Create your models here. class Comentario(models.Model): """Comentario""" contenido = models.TextField(help_text='Escribe un comentario') fecha_coment = models.DateField(auto_now=True) def __unicode__(self): return self.c...
class Agregador(models.Model): """agreador""" entrada = models.ForeignKey(Entrada) categoria = models.ManyToManyField(Categoria)
"""Entrada""" autor = models.ForeignKey(User) comentario = models.ForeignKey(Comentario) estado = models.ForeignKey(Estado) titulo = models.CharField(max_length=100) contenido = models.TextField(help_text='Redacta el contenido') fecha_pub = models.DateField(auto_now=True) def __unicode__(self): return self.t...
identifier_body
captcha.tsx
import * as React from 'react'; import ReCaptcha from 'react-google-recaptcha'; import styled from 'styled-components'; const CenteredReCaptcha = styled(ReCaptcha)` display: flex; justify-content: center; align-items: center; margin-bottom: 12px;
export interface CaptchaWidgetProps { onChange: (captchaResponse: string | null) => void; value?: boolean; } export class CaptchaWidget extends React.Component<CaptchaWidgetProps> { public static displayName = 'Captcha'; public recaptchaRef: React.RefObject<any>; constructor(props: CaptchaWidgetProps) { supe...
`;
random_line_split
captcha.tsx
import * as React from 'react'; import ReCaptcha from 'react-google-recaptcha'; import styled from 'styled-components'; const CenteredReCaptcha = styled(ReCaptcha)` display: flex; justify-content: center; align-items: center; margin-bottom: 12px; `; export interface CaptchaWidgetProps { onChange: (captchaRespons...
return ( <CenteredReCaptcha ref={this.recaptchaRef} onChange={this.onChange} sitekey={captchaKey} /> ); } }
{ return null; }
conditional_block
captcha.tsx
import * as React from 'react'; import ReCaptcha from 'react-google-recaptcha'; import styled from 'styled-components'; const CenteredReCaptcha = styled(ReCaptcha)` display: flex; justify-content: center; align-items: center; margin-bottom: 12px; `; export interface CaptchaWidgetProps { onChange: (captchaRespons...
public componentDidCatch(error: Error) { console.error(error, 'The reCaptcha api key is invalid.'); } public onChange = () => { const recaptchaValue = this.recaptchaRef.current.getValue(); this.props.onChange(recaptchaValue); }; public render() { // @ts-ignore Don't render and require recaptcha when th...
{ // Reset the captcha component if the form was submitted, since a captcha value can only be used once (and it will error if used again). The caller is obliged to empty the captcha value on submit if (prevProps.value !== this.props.value && !Boolean(this.props.value)) { this.recaptchaRef.current.reset(); } }
identifier_body
captcha.tsx
import * as React from 'react'; import ReCaptcha from 'react-google-recaptcha'; import styled from 'styled-components'; const CenteredReCaptcha = styled(ReCaptcha)` display: flex; justify-content: center; align-items: center; margin-bottom: 12px; `; export interface CaptchaWidgetProps { onChange: (captchaRespons...
(props: CaptchaWidgetProps) { super(props); this.recaptchaRef = React.createRef(); } public componentDidMount() { // @ts-ignore If there is no recaptcha key, just set a dummy value so forms that require it will be filled-in. if (!window.RECAPTCHA_V2_API_KEY) { this.props.onChange('dummy'); } } public...
constructor
identifier_name
topojson_plugin_test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import os from nose.tools import assert_almost_equal, eq_ import mapnik from .utilities import execution_path, run_all def setup(): # All of the paths used are relative, if we run the tests # from another ...
up() exit(run_all(eval(x) for x in dir() if x.startswith("test_")))
conditional_block
topojson_plugin_test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import os from nose.tools import assert_almost_equal, eq_ import mapnik from .utilities import execution_path, run_all def setup(): # All of the paths used are relative, if we run the tests # from another ...
kwargs): ds = mapnik.Datasource( type='topojson', file='../data/topojson/escaped.topojson') eq_(len(ds.fields()), 11) # TODO - this sorting is messed up eq_(ds.fields(), ['name', 'int', 'description', 'spaces', 'double', 'boolean', 'NOM_F...
t_that_nonexistant_query_field_throws(**
identifier_name
topojson_plugin_test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import os from nose.tools import assert_almost_equal, eq_ import mapnik from .utilities import execution_path, run_all def setup(): # All of the paths used are relative, if we run the tests # from another ...
eq_(f['NOM_FR'], u'Québec') ds = mapnik.Datasource( type='topojson', file='../data/topojson/escaped.topojson') f = list(ds.all_features())[0] eq_(len(ds.fields()), 11) desc = ds.describe() eq_(desc['geometry_type'], mapnik.DataGeometryType.Point)...
eq_(f['double'], 1.1) eq_(f['boolean'], True) eq_(f['NOM_FR'], u'Qu\xe9bec')
random_line_split
topojson_plugin_test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import os from nose.tools import assert_almost_equal, eq_ import mapnik from .utilities import execution_path, run_all def setup(): # All of the paths used are relative, if we run the tests # from another ...
# @raises(RuntimeError) def test_that_nonexistant_query_field_throws(**kwargs): ds = mapnik.Datasource( type='topojson', file='../data/topojson/escaped.topojson') eq_(len(ds.fields()), 11) # TODO - this sorting is messed up eq_(ds.fields(), ['name', 'int',...
= mapnik.Datasource( type='topojson', inline=open( '../data/topojson/escaped.topojson', 'r').read()) f = list(ds.all_features())[0] eq_(len(ds.fields()), 11) desc = ds.describe() eq_(desc['geometry_type'], mapnik.DataGeometryType....
identifier_body
CorrelationIdManager.d.ts
import Config = require("./Config"); declare class CorrelationIdManager {
static w3cEnabled: boolean; private static pendingLookups; private static completedLookups; private static requestIdMaxLength; private static currentRootId; static queryCorrelationId(config: Config, callback: (correlationId: string) => void): void; static cancelCorrelationIdQuery(config: Con...
private static TAG; static correlationIdPrefix: string;
random_line_split
CorrelationIdManager.d.ts
import Config = require("./Config"); declare class
{ private static TAG; static correlationIdPrefix: string; static w3cEnabled: boolean; private static pendingLookups; private static completedLookups; private static requestIdMaxLength; private static currentRootId; static queryCorrelationId(config: Config, callback: (correlationId: stri...
CorrelationIdManager
identifier_name
patch-log-service.ts
/** Regular expression that matches TypeScript mixin names inside of the project. */ const mixinNameRegex = /_\w+Base/; /** * Function that patches Dgeni's instantiated log service. The patch will hide warnings about * unresolved TypeScript symbols for the mixin base classes. * * ``` * warn: Unresolved TypeScr...
(log: any) { const warnFn = log.warn; log.warn = function(message: string) { if (message.includes('Unresolved TypeScript symbol') && mixinNameRegex.test(message)) { return; } warnFn.apply(this, [message]); }; }
patchLogService
identifier_name
patch-log-service.ts
/** Regular expression that matches TypeScript mixin names inside of the project. */ const mixinNameRegex = /_\w+Base/; /** * Function that patches Dgeni's instantiated log service. The patch will hide warnings about * unresolved TypeScript symbols for the mixin base classes. * * ``` * warn: Unresolved TypeScr...
warnFn.apply(this, [message]); }; }
{ return; }
conditional_block
patch-log-service.ts
/** Regular expression that matches TypeScript mixin names inside of the project. */ const mixinNameRegex = /_\w+Base/; /** * Function that patches Dgeni's instantiated log service. The patch will hide warnings about * unresolved TypeScript symbols for the mixin base classes. * * ``` * warn: Unresolved TypeScr...
{ const warnFn = log.warn; log.warn = function(message: string) { if (message.includes('Unresolved TypeScript symbol') && mixinNameRegex.test(message)) { return; } warnFn.apply(this, [message]); }; }
identifier_body
patch-log-service.ts
/** Regular expression that matches TypeScript mixin names inside of the project. */ const mixinNameRegex = /_\w+Base/; /** * Function that patches Dgeni's instantiated log service. The patch will hide warnings about * unresolved TypeScript symbols for the mixin base classes. * * ``` * warn: Unresolved TypeScr...
} warnFn.apply(this, [message]); }; }
random_line_split
player.rs
use std::collections::LinkedList; use application::gps_location::GpsLocation; #[derive(Hash, Clone, Eq, PartialEq, Debug)] pub struct Player { name: String, icon_path: String, target: Option<Box<Player>>, targeting_players: LinkedList<Box<Player>>, location: GpsLocation, score: i32, } impl Pl...
}
{ return &self.name; }
identifier_body
player.rs
use std::collections::LinkedList; use application::gps_location::GpsLocation; #[derive(Hash, Clone, Eq, PartialEq, Debug)] pub struct Player { name: String, icon_path: String, target: Option<Box<Player>>, targeting_players: LinkedList<Box<Player>>, location: GpsLocation, score: i32, } impl Pla...
}; return player; } pub fn increment_score(&mut self) { self.score += 1; } pub fn get_score(&self) -> i32 { return self.score; } pub fn get_name(&self) -> &String { return &self.name; } }
random_line_split
player.rs
use std::collections::LinkedList; use application::gps_location::GpsLocation; #[derive(Hash, Clone, Eq, PartialEq, Debug)] pub struct Player { name: String, icon_path: String, target: Option<Box<Player>>, targeting_players: LinkedList<Box<Player>>, location: GpsLocation, score: i32, } impl Pl...
(&self) -> i32 { return self.score; } pub fn get_name(&self) -> &String { return &self.name; } }
get_score
identifier_name
jquery-chosen-sortable.js
/* * Author: Yves Van Broekhoven & Simon Menke * Created at: 2012-07-05 * * Requirements: * - jQuery * - jQuery UI * - Chosen * * Version: 1.0.0 */ (function($) { $.fn.chosenOrder = function() { var $this = this.filter('.chzn-sortable[multiple]').first(), $chosen = $this.siblings('.chzn-conta...
}); // Initialize jQuery UI Sortable $chosen.find('.chzn-choices').sortable({ 'placeholder' : 'ui-state-highlight', 'items' : 'li:not(.search-field)', //'update' : _update, 'tolerance' : 'pointer' }); // Intercept form submit & order the chos...
{ event.stopPropagation(); }
conditional_block
jquery-chosen-sortable.js
/* * Author: Yves Van Broekhoven & Simon Menke * Created at: 2012-07-05 * * Requirements: * - jQuery * - jQuery UI * - Chosen * * Version: 1.0.0 */ (function($) { $.fn.chosenOrder = function() { var $this = this.filter('.chzn-sortable[multiple]').first(), $chosen = $this.siblings('.chzn-conta...
var $select = $(this); var $chosen = $select.siblings('.chzn-container'); // On mousedown of choice element, // we don't want to display the dropdown list $chosen.find('.chzn-choices').bind('mousedown', function(event){ if ($(event.target).is('span')) { event.stopPropaga...
*/ $.fn.chosenSortable = function(){ var $this = this.filter('.chzn-sortable[multiple]'); $this.each(function(){
random_line_split
updater.py
#!/usr/bin/python from src.sqllist import get_sql _UPDATER_EXTRAS = { 'runningcatalog': ['runcatid'], 'runningcatalog_fluxes': ['runcat_id', 'band', 'stokes'], } def _refactor_update(sql):
sqlwhere = sqlwhere.replace('%s.%s' % (table, field), 'x.%s' % field) update_field = [] for sqlf in sqlupd_list: field, update_stmt = sqlf.split('=') update_field.append('%s = (select %s from %s x, %s %s %s)' % ( field, update_stmt.replace(table, 'x'), ...
""" Special refactoring for MonetDB update..from imitation. """ def _get_extra_conditions(tabname): return ' '.join(map(lambda x: 'and {0}.{1} = x.{1}'.format(tabname, x), _UPDATER_EXTRAS[tabname])) sqlupdate, sqlfrom = sql.strip().split('from', 1) table, sqlupd_l...
identifier_body
updater.py
#!/usr/bin/python from src.sqllist import get_sql _UPDATER_EXTRAS = { 'runningcatalog': ['runcatid'], 'runningcatalog_fluxes': ['runcat_id', 'band', 'stokes'], } def _refactor_update(sql): """ Special refactoring for MonetDB update..from imitation. """ def _get_extra_conditions(tabname): ...
conn.execute(sql)
conditional_block
updater.py
#!/usr/bin/python from src.sqllist import get_sql _UPDATER_EXTRAS = { 'runningcatalog': ['runcatid'], 'runningcatalog_fluxes': ['runcat_id', 'band', 'stokes'], } def _refactor_update(sql): """ Special refactoring for MonetDB update..from imitation. """ def _get_extra_conditions(tabname): ...
sqlupd_list = sqlupd_list.split(',') table = table.split()[1] if sqlfrom.endswith(';'): sqlfrom = sqlfrom[:-1] sqlfrom_split = sqlfrom.split('where', 1) if len(sqlfrom_split) > 1: [sqlfrom2, sqlwhere] = sqlfrom_split sqlwhere = 'where %s' % sqlwhere else: sqlfrom2...
table, sqlupd_list = sqlupdate.split('set')
random_line_split
updater.py
#!/usr/bin/python from src.sqllist import get_sql _UPDATER_EXTRAS = { 'runningcatalog': ['runcatid'], 'runningcatalog_fluxes': ['runcat_id', 'band', 'stokes'], } def
(sql): """ Special refactoring for MonetDB update..from imitation. """ def _get_extra_conditions(tabname): return ' '.join(map(lambda x: 'and {0}.{1} = x.{1}'.format(tabname, x), _UPDATER_EXTRAS[tabname])) sqlupdate, sqlfrom = sql.strip().split('from', 1) tabl...
_refactor_update
identifier_name
index.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const common_1 = require("../common"); const ENDPT = 'achievementicons'; /** * Achievement icons resource */ class AchievementIconsResource { /** * Construct the achievement icons resource * @param context The context to make r...
/** * Delete previously uploaded achievement icon by filename. * @param iconFileName icon file name (generated by BadgeUp when the icon was uploaded, not the original file name) * @param userOpts option overrides for this request * @returns A promise that resolves to the deleted achievement ico...
{ return this.context.http.makeRequest({ method: 'GET', url: `/v2/apps/${this.context.applicationId}/${ENDPT}` }, userOpts); }
identifier_body
index.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const common_1 = require("../common"); const ENDPT = 'achievementicons'; /** * Achievement icons resource */ class AchievementIconsResource { /** * Construct the achievement icons resource * @param context The context to make r...
(context) { this.context = context; this.common = new common_1.Common(context, ENDPT); } /** * Get a list of all preloaded achievement icons * @param {object} userOpts option overrides for this request * @returns {Promise<object[]>} A promise that resolves to an array of achieveme...
constructor
identifier_name
index.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const common_1 = require("../common"); const ENDPT = 'achievementicons'; /** * Achievement icons resource */
class AchievementIconsResource { /** * Construct the achievement icons resource * @param context The context to make requests as */ constructor(context) { this.context = context; this.common = new common_1.Common(context, ENDPT); } /** * Get a list of all preloaded ac...
random_line_split
log.js
'use strict'; var crayon = require('@ccheever/crayon'); function log() { var prefix = crayon.gray('[') + crayon.gray('exp') + crayon.gray(']'); var args = [prefix].concat(Array.prototype.slice.call(arguments, 0)); console.error.apply(console, args); } log.error = function error() { var prefix = crayon.red('[...
return crayon.yellow(x); })); console.warn.apply(console, args); }; log.gray = function () { var prefix = '[exp]'; var args = [prefix].concat(Array.prototype.slice.call(arguments, 0)); crayon.gray.error.apply(crayon, args); }; log.crayon = crayon; module.exports = log; //# sourceMappingURL=sourcemaps/l...
log.warn = function warn() { var prefix = crayon.yellow('[') + crayon.gray('exp') + crayon.yellow(']'); var args = [prefix].concat(Array.prototype.slice.call(arguments, 0).map(function (x) {
random_line_split
log.js
'use strict'; var crayon = require('@ccheever/crayon'); function
() { var prefix = crayon.gray('[') + crayon.gray('exp') + crayon.gray(']'); var args = [prefix].concat(Array.prototype.slice.call(arguments, 0)); console.error.apply(console, args); } log.error = function error() { var prefix = crayon.red('[') + crayon.gray('exp') + crayon.red(']') + crayon.red.bold(' Error:')...
log
identifier_name
log.js
'use strict'; var crayon = require('@ccheever/crayon'); function log()
log.error = function error() { var prefix = crayon.red('[') + crayon.gray('exp') + crayon.red(']') + crayon.red.bold(' Error:'); var args = [prefix].concat(Array.prototype.slice.call(arguments, 0).map(function (x) { return crayon.red(x); })); console.error.apply(console, args); }; log.warn = function war...
{ var prefix = crayon.gray('[') + crayon.gray('exp') + crayon.gray(']'); var args = [prefix].concat(Array.prototype.slice.call(arguments, 0)); console.error.apply(console, args); }
identifier_body
small_vector.rs
// Copyright 2013-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-MI...
() -> SmallVector<T> { SmallVector { repr: Zero } } pub fn one(v: T) -> SmallVector<T> { SmallVector { repr: One(v) } } pub fn many(vs: Vec<T>) -> SmallVector<T> { SmallVector { repr: Many(vs) } } pub fn as_slice<'a>(&'a self) -> &'a [T] { match self.repr { ...
zero
identifier_name
small_vector.rs
// Copyright 2013-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-MI...
pub fn push(&mut self, v: T) { match self.repr { Zero => self.repr = One(v), One(..) => { let one = mem::replace(&mut self.repr, Zero); match one { One(v1) => mem::replace(&mut self.repr, Many(vec!(v1, v))), _ ...
{ match self.repr { Zero => { let result: &[T] = &[]; result } One(ref v) => slice::ref_slice(v), Many(ref vs) => vs.as_slice() } }
identifier_body
small_vector.rs
// Copyright 2013-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-MI...
impl<T> Extend<T> for SmallVector<T> { fn extend<I: Iterator<T>>(&mut self, mut iter: I) { for val in iter { self.push(val); } } } impl<T> SmallVector<T> { pub fn zero() -> SmallVector<T> { SmallVector { repr: Zero } } pub fn one(v: T) -> SmallVector<T> { ...
v.extend(iter); v } }
random_line_split
PatchInputFiles.ts
import { HTMLInputElement, File, Window, document, Event } from '@ephox/dom-globals'; import { Cell, Option } from '@ephox/katamari'; import { Step, GeneralSteps, Chain } from '@ephox/agar'; import { createFileList } from './FileList'; interface Props {
const inputPrototypeState = Cell(Option.none<Props>()); const createChangeEvent = (win: Window): Event => { const event: any = document.createEvent('CustomEvent'); event.initCustomEvent('change', true, true, null); event.view = win; event.ctrlKey = false; event.altKey = false; event.shiftKey = false; e...
files: PropertyDescriptor; click: () => void; }
random_line_split
pfs.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
export function readdir(path: string): TPromise<string[]> { return nfcall(extfs.readdir, path); } export function exists(path: string): TPromise<boolean> { return new Promise(c => fs.exists(path, c)); } export function chmod(path: string, mode: number): TPromise<boolean> { return nfcall(fs.chmod, path, mode); } ...
{ return path === dirname(path); }
identifier_body
pfs.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return TPromise.wrapError<boolean>(err); }); if (isRoot(path)) { return TPromise.as(true); } return mkdir().then(null, (err: NodeJS.ErrnoException) => { if (err.code === 'ENOENT') { return mkdirp(dirname(path), mode).then(mkdir); } return TPromise.wrapError<boolean>(err); }); } export function...
{ return nfcall(fs.stat, path) .then((stat: fs.Stats) => stat.isDirectory ? null : Promise.wrapError(new Error(`'${ path }' exists and is not a directory.`))); }
conditional_block
pfs.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(path: string): TPromise<void> { return stat(path).then(stat => { if (stat.isDirectory()) { return readdir(path) .then(children => TPromise.join(children.map(child => rimraf(join(path, child))))) .then(() => rmdir(path)); } else { return unlink(path); } }, (err: NodeJS.ErrnoException) => { if (e...
rimraf
identifier_name
pfs.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
}); }); } function dirExistsWithResult<T>(path: string, successResult: T): TPromise<T> { return dirExists(path).then((exists) => { return exists ? successResult : null; }); } /** * `path` exists and is a directory */ export function dirExists(path: string): TPromise<boolean> { return stat(path).then(stat => s...
return removeNull(subdirs);
random_line_split
magic-eight-ball.component.spec.ts
import {TestBed, async} from '@angular/core/testing'; import {MagicEightBallComponent} from './magic-eight-ball.component'; import {MagicEightBallService} from import {MagicEightBallService} from '../magic-eight-ball.service'; import {By} from '@angular/platform-browser'; describe('Component: MagicEightBall', () => ...
it('should begin with no text', async(() => { fixture.detectChanges(); expect(getHeaderEl().textContent).toEqual(''); })); it('should show text after click', async(() => { fixture.debugElement.query(By.css('button')) .triggerEventHandler('click', null); fixture.detectChanges(); expect(g...
fixture = undefined; });
random_line_split
query.rs
ated() .map(|(k, v)| (GenVariantPrinter(k), OneLinePrinter(v))), ), ) .field("storage_conflicts", &self.storage_conflicts) .finish() } } #[derive(Debug, TyEncodable, TyDecodable, HashStable)] pub struct BorrowCheckResult<'tcx> { /// Al...
{ self.mir_const_qualif_const_arg((def.did, param_did)) }
conditional_block
query.rs
afetyViolationDetails, } #[derive(Clone, TyEncodable, TyDecodable, HashStable, Debug)] pub struct UnsafetyCheckResult { /// Violations that are propagated *upwards* from this function. pub violations: Lrc<[UnsafetyViolation]>, /// `unsafe` blocks in this function, along with whether they are used. This is ...
#[derive(TyEncodable, TyDecodable, HashStable)] pub enum ConstraintCategory {
random_line_split
query.rs
aque_types: VecMap<OpaqueTypeKey<'tcx>, Ty<'tcx>>, pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>, pub used_mut_upvars: SmallVec<[Field; 8]>, } /// The result of the `mir_const_qualif` query. /// /// Each field (except `error_occured`) corresponds to an implementer of the `Qualif` trait in /...
{ if let Some((did, param_did)) = def.as_const_arg() { self.promoted_mir_of_const_arg((did, param_did)) } else { self.promoted_mir(def.did) } }
identifier_body
query.rs
are not controlled by the Rust type system: invalid data, \ aliasing violations or data races will cause undefined behavior", ), DerefOfRawPointer => ( "dereference of raw pointer", "raw pointers may be null, dangling or unaligned; they can viola...
<T>(T); impl<T: Debug> Debug for OneLinePrinter<T> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{:?}", self.0) } } fmt.debug_struct("GeneratorLayout") .field("field_tys", &MapPrinter::new(self.field_tys.iter_enum...
OneLinePrinter
identifier_name
mem.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! Memory operations. pub use lrs_core::mem::{ uninit, cast, zeroed, copy_as, forget, unsafe_forget, drop, copy...
#[cfg(not(freestanding))] pub use lrs_mem::flags::{MemLockFlags}; #[cfg(not(freestanding))] pub mod advice { pub use lrs_mem::adv::{ Normal, Random, Sequential, WillNeed, DontNeed, Remove, DontFork, DoFork, HwPoison, SoftOffline, Mergeable, Unmergeable, HugePage, NoHugePage, DontDump, DoDu...
pub use lrs_mem::{ advise, protect, lock, unlock, lock_all, unlock_all, Availability, availability, };
random_line_split
mongo.js
'use strict'; var q = require('q'), MongoClient = require('mongodb').MongoClient, ObjectID = require('mongodb').ObjectID, logger = require('./logger'); module.exports = { buildConfig: buildConfig, testConnection: testConnection, createSampleData: createSampleData }; function buildConfig(url){...
} return deferred.promise; } function importData(host, col, obj){ var deferred = q.defer(); MongoClient.connect(host, function(err, db) { if (err) logger.error(err.message); db.collection(col, function(err, collection){ if (err) logger.error(err.message); col...
{ return function(){ var def = q.defer(); importData(config.db.host, colName, obj).then( function(){ def.resolve(); } ); return def.promise; }; }
identifier_body
mongo.js
'use strict'; var q = require('q'), MongoClient = require('mongodb').MongoClient, ObjectID = require('mongodb').ObjectID, logger = require('./logger'); module.exports = { buildConfig: buildConfig, testConnection: testConnection, createSampleData: createSampleData }; function buildConfig(url){...
function(err){ logger.error(''); logger.error(err.message); deferred.reject(err); } ); function save(colName){ var deferred = q.defer(), items = require('../../sampledata/basic/' + colName)(ObjectID), instances = []; i...
function(){ deferred.resolve(config) },
random_line_split
mongo.js
'use strict'; var q = require('q'), MongoClient = require('mongodb').MongoClient, ObjectID = require('mongodb').ObjectID, logger = require('./logger'); module.exports = { buildConfig: buildConfig, testConnection: testConnection, createSampleData: createSampleData }; function buildConfig(url){...
(host, col, obj){ var deferred = q.defer(); MongoClient.connect(host, function(err, db) { if (err) logger.error(err.message); db.collection(col, function(err, collection){ if (err) logger.error(err.message); collection.insert(obj, function(err){ if (err) ...
importData
identifier_name
test.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 ...
(&mut self) { unsafe { llvm::LLVMDisposeExecutionEngine(self.ee) }; } } /// Returns last error from LLVM wrapper code. fn llvm_error() -> String { String::from_utf8_lossy( unsafe { CStr::from_ptr(llvm::LLVMRustGetLastError()).to_bytes() }) .into_owned() } fn build_exec_options(sysroot:...
drop
identifier_name
test.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 ...
} } } impl Drop for ExecutionEngine { fn drop(&mut self) { unsafe { llvm::LLVMDisposeExecutionEngine(self.ee) }; } } /// Returns last error from LLVM wrapper code. fn llvm_error() -> String { String::from_utf8_lossy( unsafe { CStr::from_ptr(llvm::LLVMRustGetLastError()).to_byt...
{ panic!("Failed to load crate {:?}: {}", path.display(), llvm_error()); }
conditional_block
test.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 ...
/// Compiles input up to phase 4, translation to LLVM. /// /// Returns the LLVM `ModuleRef` and a series of paths to dynamic libraries /// for crates used in the given input. fn compile_program(input: &str, sysroot: PathBuf) -> Option<(llvm::ModuleRef, Vec<PathBuf>)> { let input = Input::Str(in...
{ let mut opts = basic_options(); // librustc derives sysroot from the executable name. // Since we are not rustc, we must specify it. opts.maybe_sysroot = Some(sysroot); // Prefer faster build time opts.optimize = config::No; // Don't require a `main` function opts.crate_types = vec!...
identifier_body
test.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 ...
for &m in &self.modules { let gv = unsafe { llvm::LLVMGetNamedGlobal(m, s.as_ptr()) }; if !gv.is_null() { let gp = unsafe { llvm::LLVMGetPointerToGlobal(self.ee, gv) }; assert!(!gp.is_null()); return Some(gp); } } ...
/// Returns a raw pointer to the named global item. pub fn get_global(&mut self, name: &str) -> Option<*const ()> { let s = CString::new(name.as_bytes()).unwrap();
random_line_split
_internal.py
# The MIT License # # Copyright (c) 2015 the bpython authors. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, mo...
def __call__(self, *args, **kwargs): if self._repl.reevaluating: with NopPydocPager(): return super(_Helper, self).__call__(*args, **kwargs) else: return super(_Helper, self).__call__(*args, **kwargs) # vim: sw=4 ts=4 sts=4 ai et
if not py3 and isinstance(output, str): output = output.decode(getpreferredencoding()) self._repl.pager(output)
identifier_body
_internal.py
# The MIT License # # Copyright (c) 2015 the bpython authors. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, mo...
else: return super(_Helper, self).__call__(*args, **kwargs) # vim: sw=4 ts=4 sts=4 ai et
with NopPydocPager(): return super(_Helper, self).__call__(*args, **kwargs)
conditional_block
_internal.py
# The MIT License # # Copyright (c) 2015 the bpython authors. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, mo...
(self, *args, **kwargs): if self._repl.reevaluating: with NopPydocPager(): return super(_Helper, self).__call__(*args, **kwargs) else: return super(_Helper, self).__call__(*args, **kwargs) # vim: sw=4 ts=4 sts=4 ai et
__call__
identifier_name
_internal.py
# The MIT License # # Copyright (c) 2015 the bpython authors. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, mo...
class _Helper(bpython._internal._Helper): def __init__(self, repl=None): self._repl = repl pydoc.pager = self.pager super(_Helper, self).__init__() def pager(self, output): if not py3 and isinstance(output, str): output = output.decode(getpreferredencoding()) ...
return None
random_line_split
conf.py
# -*- coding: utf-8 -*- # # SRL 5 documentation build configuration file, created by # sphinx-quickstart on Sat Oct 16 15:51:55 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All c...
latex_documents = [ ('index', 'SRL5.tex', u'SRL 5 Documentation', u'SRL Developers', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #late...
# Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]).
random_line_split
game-char-info.spec.tsx
import React from 'react'; import { shallow } from 'enzyme'; import chaiEnzyme from 'chai-enzyme'; import chai, { expect } from 'chai'; import GameCharInfo from '../../../client/jsx/game-char-info'; const RG = require('../../../client/src/battles'); chai.use(chaiEnzyme()); // Props with non-default values passes to...
});
random_line_split
chess.py
# -*- coding: utf-8 -*- import struct class GGZChessFeedback: def onSeat(self, seatNum, version): pass def
(self, whiteType, whiteName, blackType, blackName): pass def onClockRequest(self): pass def onClock(self, mode, seconds): pass def onStart(self): pass def onMove(self, move): pass class Chess: CLOCK_NONE = 0 CLOCK_CLI...
onPlayers
identifier_name
chess.py
# -*- coding: utf-8 -*- import struct class GGZChessFeedback: def onSeat(self, seatNum, version): pass def onPlayers(self, whiteType, whiteName, blackType, blackName): pass def onClockRequest(self): pass def onClock(self, mode, sec...
def decodeStart(self): # [5] self.decodeMethod = None self.feedback.onStart() def decodeMove(self): # [07][move(8)] # or [07][move(8)][seconds] (move, _) = self.getGGZString(self.command[1:]) if move is None: return self.d...
(value,) = struct.unpack("!xI", self.command) mode = value >> 24 seconds = value & 0x00FFFFFF self.feedback.onClock(mode, seconds) self.decodeMethod = None
conditional_block
chess.py
# -*- coding: utf-8 -*- import struct class GGZChessFeedback: def onSeat(self, seatNum, version): pass def onPlayers(self, whiteType, whiteName, blackType, blackName): pass def onClockRequest(self): pass def onClock(self, mode, sec...
def decodeClock(self): # [4][mode][seconds] if len(self.command) == 5: (value,) = struct.unpack("!xI", self.command) mode = value >> 24 seconds = value & 0x00FFFFFF self.feedback.onClock(mode, seconds) self.decodeMethod = None ...
self.decodeMethod = None self.feedback.onClockRequest()
identifier_body
chess.py
# -*- coding: utf-8 -*- import struct class GGZChessFeedback: def onSeat(self, seatNum, version): pass def onPlayers(self, whiteType, whiteName, blackType, blackName): pass def onClockRequest(self): pass def onClock(self, mode, sec...
string = buffer[4:length + 4] # Strip C null characters while string.endswith('\x00'): string = string[:-1] return (string, length + 4) def decodeSeat(self): # seat [01][num][version] if len(self.command) == 3: self....
return (None, 0)
random_line_split
utils.py
from flask import request, abort, jsonify, render_template from flask.ext.sqlalchemy import BaseQuery import math class PaginatedQuery(object): def __init__(self, query_or_model, paginate_by, page_var='page', check_bounds=False): self.paginate_by = paginate_by self.page_var = page...
(self): curr_page = request.args.get(self.page_var) if curr_page and curr_page.isdigit(): return max(1, int(curr_page)) return 1 def get_page_count(self): return int(math.ceil(float(self.query.count()) / self.paginate_by)) def get_object_list(self): if self....
get_page
identifier_name
utils.py
from flask import request, abort, jsonify, render_template
from flask.ext.sqlalchemy import BaseQuery import math class PaginatedQuery(object): def __init__(self, query_or_model, paginate_by, page_var='page', check_bounds=False): self.paginate_by = paginate_by self.page_var = page_var self.check_bounds = check_bounds if i...
random_line_split
utils.py
from flask import request, abort, jsonify, render_template from flask.ext.sqlalchemy import BaseQuery import math class PaginatedQuery(object): def __init__(self, query_or_model, paginate_by, page_var='page', check_bounds=False): self.paginate_by = paginate_by self.page_var = page...
else: self.model = query_or_model self.query = self.model.all() def get_page(self): curr_page = request.args.get(self.page_var) if curr_page and curr_page.isdigit(): return max(1, int(curr_page)) return 1 def get_page_count(self): re...
self.query = query_or_model
conditional_block
utils.py
from flask import request, abort, jsonify, render_template from flask.ext.sqlalchemy import BaseQuery import math class PaginatedQuery(object): def __init__(self, query_or_model, paginate_by, page_var='page', check_bounds=False): self.paginate_by = paginate_by self.page_var = page...
q = query.filter(criteria) if q.first(): return q.first() else: abort(404)
identifier_body
joystick_controller.py
import sdl2 from mgl2d.input.game_controller import GameController class JoystickController(GameController): _DEBUG_CONTROLLER = False AXIS_DEAD_ZONE = 4000 AXIS_MIN_VALUE = -32768 AXIS_MAX_VALUE = 32767 def __init__(self): super().__init__() self._sdl_controller = None s...
(self, axis_index): axis_value = sdl2.SDL_GameControllerGetAxis(self._sdl_controller, axis_index) # Sticks have a dead zone if axis_index != self.AXIS_TRIGGER_LEFT and axis_index != self.AXIS_TRIGGER_RIGHT: if abs(axis_value) < self.AXIS_DEAD_ZONE: return 0 ...
get_axis
identifier_name
joystick_controller.py
import sdl2 from mgl2d.input.game_controller import GameController class JoystickController(GameController):
for btn_index in range(0, self.MAX_BUTTONS): self._button_down[btn_index] = 0 self._button_pressed[btn_index] = 0 self._button_released[btn_index] = 0 if self._sdl_joystick_id != -1: self._connected = True def close(self): sdl2.SDL_GameContr...
_DEBUG_CONTROLLER = False AXIS_DEAD_ZONE = 4000 AXIS_MIN_VALUE = -32768 AXIS_MAX_VALUE = 32767 def __init__(self): super().__init__() self._sdl_controller = None self._sdl_joystick = None self._sdl_joystick_id = None def open(self, device_index): self._sdl_c...
identifier_body
joystick_controller.py
import sdl2 from mgl2d.input.game_controller import GameController class JoystickController(GameController): _DEBUG_CONTROLLER = False AXIS_DEAD_ZONE = 4000 AXIS_MIN_VALUE = -32768 AXIS_MAX_VALUE = 32767 def __init__(self): super().__init__() self._sdl_controller = None s...
self._button_down[btn_index] = is_down def get_axis(self, axis_index): axis_value = sdl2.SDL_GameControllerGetAxis(self._sdl_controller, axis_index) # Sticks have a dead zone if axis_index != self.AXIS_TRIGGER_LEFT and axis_index != self.AXIS_TRIGGER_RIGHT: if abs...
self._button_pressed[btn_index] = True
conditional_block
joystick_controller.py
import sdl2 from mgl2d.input.game_controller import GameController class JoystickController(GameController): _DEBUG_CONTROLLER = False AXIS_DEAD_ZONE = 4000 AXIS_MIN_VALUE = -32768 AXIS_MAX_VALUE = 32767 def __init__(self): super().__init__() self._sdl_controller = None s...
if axis_index != self.AXIS_TRIGGER_LEFT and axis_index != self.AXIS_TRIGGER_RIGHT: if abs(axis_value) < self.AXIS_DEAD_ZONE: return 0 # Return scaled value return axis_value / self.AXIS_MAX_VALUE if axis_value > 0 else -axis_value / self.AXIS_MIN_VALUE def get_a...
axis_value = sdl2.SDL_GameControllerGetAxis(self._sdl_controller, axis_index) # Sticks have a dead zone
random_line_split
analysis.py
#!usr/bin/env python # -*- coding: utf-8! -*- from collections import Counter, OrderedDict import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy.cluster.hierarchy import ward, dendrogram from sklearn.decomposition import PCA from sklearn.metrics.pairwise import euclidean_distances from s...
(self): return '%s(%r)' % (self.__class__.__name__, OrderedDict(self)) def __reduce__(self): return self.__class__, (OrderedDict(self),) def pca_cluster(slice_matrix, slice_names, feature_names, prefix='en', nb_clusters=3): """ Run pca on matrix and visualize samples in...
__repr__
identifier_name
analysis.py
#!usr/bin/env python # -*- coding: utf-8! -*- from collections import Counter, OrderedDict import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy.cluster.hierarchy import ward, dendrogram from sklearn.decomposition import PCA from sklearn.metrics.pairwise import euclidean_distances from s...
plt.rcParams['font.family'] = 'arial' plt.rcParams['font.size'] = 8 plt.clf() plt.figure(figsize=(10,20)) sample_names, breakpoints_cnts = zip(*sample_cnts.items()) pos = [i for i, n in enumerate(sample_names)][::-1] # reverse for legibility plt.yticks(pos, [n[:3].replace('_', '') if n.en...
print('===============\niteration:', nb+1) # sample a subset of the features in our matrix: rnd_indices = np.random.randint(low=0, high=corpus_matrix.shape[1], size=nb_mfw_sampled) sampled_matrix = corpus_matrix[:,rnd_indices] # get which breaks are selected and adjust the cnts: ...
conditional_block
analysis.py
#!usr/bin/env python # -*- coding: utf-8! -*- from collections import Counter, OrderedDict import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy.cluster.hierarchy import ward, dendrogram from sklearn.decomposition import PCA from sklearn.metrics.pairwise import euclidean_distances from s...
def pca_cluster(slice_matrix, slice_names, feature_names, prefix='en', nb_clusters=3): """ Run pca on matrix and visualize samples in 1st PCs, with word loadings projected on top. The colouring of the samples is provided by running a cluster analysis on the samples in these first dime...
'Counter that remembers the order elements are first encountered' def __repr__(self): return '%s(%r)' % (self.__class__.__name__, OrderedDict(self)) def __reduce__(self): return self.__class__, (OrderedDict(self),)
identifier_body
analysis.py
#!usr/bin/env python # -*- coding: utf-8! -*- from collections import Counter, OrderedDict import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy.cluster.hierarchy import ward, dendrogram from sklearn.decomposition import PCA from sklearn.metrics.pairwise import euclidean_distances from s...
clustering = AgglomerativeClustering(linkage='ward', affinity='euclidean', n_clusters=nb_clusters) clustering.fit(pca_matrix) # add slice names: for x, y, name, cluster_label in zip(x1, x2, slice_names, clustering.labels_): ax1.text(x, y, name.split('_')[0][:3], ha='center', va="center", ...
# clustering on top (for colouring):
random_line_split
circle_urls.py
#!/usr/bin/env python ''' circle_urls.py will rename all url files to not have extension .html ''' import sys import os from glob import glob site_dir = os.path.abspath(sys.argv[1]) print("Using site directory %s" %(site_dir)) files = glob("%s/*.html" %(site_dir)) # For each file, we need to replace all links to h...
with open(html_file,'r') as filey: content = filey.read() for search_name in search_names: content = content.replace('%s"' %(search_name),'%s.html"' %(search_name)) content = content.replace('/images/logo/logo.png','https://sci-f.github.io/apps/assets/img/logo/logo.png') with open(html_file,...
conditional_block
circle_urls.py
#!/usr/bin/env python
circle_urls.py will rename all url files to not have extension .html ''' import sys import os from glob import glob site_dir = os.path.abspath(sys.argv[1]) print("Using site directory %s" %(site_dir)) files = glob("%s/*.html" %(site_dir)) # For each file, we need to replace all links to have correct .html extension...
'''
random_line_split
lib.rs
extern crate fringe; extern crate tokio_core; #[macro_use(task_local)] extern crate futures; use futures::Async; use std::cell::{RefCell, UnsafeCell}; /// Convenient macro to suspend and retry async operation /// just as it was blocking operation #[macro_export] macro_rules! poll { ($e:expr) => {{ let re...
<'a>(y : &'a Yield) -> YielderRefStore { YielderRefStore ( UnsafeCell::new(std::mem::transmute(y)) ) } } unsafe impl Send for YielderRefStore {} // Wrapper over `fringe::Yielder` to make put it in `task_local` trait Yield { fn suspend(&self); } impl<I : Send, O : Send, E : Send> ...
new
identifier_name
lib.rs
extern crate fringe; extern crate tokio_core; #[macro_use(task_local)] extern crate futures; use futures::Async; use std::cell::{RefCell, UnsafeCell}; /// Convenient macro to suspend and retry async operation /// just as it was blocking operation #[macro_export] macro_rules! poll { ($e:expr) => {{ let re...
/// Block current fiber. It will be resumed and thus this function will return, /// when the event loop decides it might be ready. This includes: previously /// blocked IO becoming unblocked etc. pub fn yield_now() { let y = unsafe { yielder_tl_pop() }; y.suspend(); unsafe { yielder_tl_push(y) } } /// Bl...
///
random_line_split
lib.rs
extern crate fringe; extern crate tokio_core; #[macro_use(task_local)] extern crate futures; use futures::Async; use std::cell::{RefCell, UnsafeCell}; /// Convenient macro to suspend and retry async operation /// just as it was blocking operation #[macro_export] macro_rules! poll { ($e:expr) => {{ let re...
/// Block current fiber to wait for result of another future pub fn await<F: futures::Future>(mut f: F) -> Result<F::Item, F::Error> { loop { match f.poll() { Ok(Async::NotReady) => yield_now(), Ok(Async::Ready(val)) => return Ok(val), Err(e) => return Err(e), }...
{ let y = unsafe { yielder_tl_pop() }; y.suspend(); unsafe { yielder_tl_push(y) } }
identifier_body
lib.rs
// Copyright 2016 Alexander Reece // // 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...
try!(writeln!(writer, "}}")); Ok(()) } } impl<'a> Class<'a> { pub fn name(&self) -> &str { &self.name } pub fn fields(&self) -> &[ClassField<'a>] { &self.fields } pub fn index(&self) -> &str { &self.index } pub fn methods(&self) -> &[ClassMeth...
try!(writeln!(writer, "response_codes: {},", codegen::format_to_map(response_codes.into_iter()))); try!(writeln!(writer, "version: {},", self.version().format_rust()));
random_line_split
lib.rs
// Copyright 2016 Alexander Reece // // 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...
<W>(&self, name: &str, writer: &mut W) -> io::Result<()> where W: io::Write { let (ungrouped, frame_types, response_codes) = { let (mut ungrouped, mut frame_types, mut response_codes) = (vec![], vec![], vec![]); #[allow(match_same_arms)] for constant in self.const...
write_generated
identifier_name
enemy.rs
pub enum ExecuteState { Term, Update(ExecuteBoxFn), Delay(GameTime, ExecuteBoxFn), WaitForAll(ExecuteBoxFn) } macro_rules! AdditionalArgsBoxed { ($f: expr => $($a: expr),*) => {Box::new(|a, b, c| $f(a, b, c $(, $a)*))}; (mv $f: expr => $($a: expr),*) => {Box::new(move |a, b, c| $f(a, b, c $(, $a)*))} }...
{ /* extern mgr: &mut EnemySquads; extern args: &GameUpdateArgs; loop { mgr.spawn_squad(spawn_group::strategies::RandomFall(0.1, 10)); yield WaitForAllSquads; yield Delay(2.5); } */ fn eternal_loop(mgr: &mut EnemySquads, _: &mut GameUpdateArgs) -> ManagerExecuteState { mgr.spawn_s...
identifier_body
enemy.rs
(Vector3::new(0.0, 0.0, 0.0)).quaternion()); store_quaternion(&mut uref.rotq[1], UnitQuaternion::new(Vector3::new(0.0, 0.0, 0.0)).quaternion()); *iref_rez = [3.0, 0.0, 0.0, 0.0]; // let (frsender, uref_th) = unsafe { (fr_sender.clone(), CharacterLocationUnsafePtr(std::mem::transmute(uref))) }; Enemy::Entity ...
(None, Some(newpos)) } }, _ => (None, None) }; if let Some(gb) = gb_index { *self = Enemy::Garbage(gb); } np } pub fn is_garbage(&self) -> bool { match self { &Enemy::Garbage(_) => true, _ => false } } } /// Enemy Spawn Group pub mod spawn_group { use super::{GameTime, GameUpdateArg...
{ *next = n; }
conditional_block
enemy.rs
0, 0.0, 0.0)).quaternion()); store_quaternion(&mut uref.rotq[1], UnitQuaternion::new(Vector3::new(0.0, 0.0, 0.0)).quaternion()); *iref_rez = [3.0, 0.0, 0.0, 0.0]; // let (frsender, uref_th) = unsafe { (fr_sender.clone(), CharacterLocationUnsafePtr(std::mem::transmute(uref))) }; Enemy::Entity { block_index...
{ self.0 = 0.0;
random_line_split
enemy.rs
.5).normalize() * (-260.0 * *living_secs + 13.0).to_radians()).quaternion()); rezonator_iref[0] = rezonator_left as f32; rezonator_iref[1] -= 130.0f32.to_radians() * update_args.delta_time; rezonator_iref[2] += 220.0f32.to_radians() * update_args.delta_time; *living_secs += update_args.delta_time; ...
spawn_squad
identifier_name
hello.rs
extern crate timely_communication; fn main() { // configure for two threads, just one process. let config = timely_communication::Configuration::Process(2); // initailizes communication, spawns workers let guards = timely_communication::initialize(config, |mut allocator| { println!("worker {} ...
}
{ println!("error in computation"); }
conditional_block
hello.rs
extern crate timely_communication; fn
() { // configure for two threads, just one process. let config = timely_communication::Configuration::Process(2); // initailizes communication, spawns workers let guards = timely_communication::initialize(config, |mut allocator| { println!("worker {} started", allocator.index()); // a...
main
identifier_name
hello.rs
extern crate timely_communication; fn main()
println!("worker {}: received: <{}>", allocator.index(), message); expecting -= 1; } } allocator.index() }); // computation runs until guards are joined or dropped. if let Ok(guards) = guards { for guard in guards.join() { pri...
{ // configure for two threads, just one process. let config = timely_communication::Configuration::Process(2); // initailizes communication, spawns workers let guards = timely_communication::initialize(config, |mut allocator| { println!("worker {} started", allocator.index()); // allo...
identifier_body
hello.rs
extern crate timely_communication; fn main() { // configure for two threads, just one process. let config = timely_communication::Configuration::Process(2); // initailizes communication, spawns workers let guards = timely_communication::initialize(config, |mut allocator| { println!("worker {} ...
// we have to count down ourselves. let mut expecting = 2; while expecting > 0 { if let Some(message) = receiver.recv() { println!("worker {}: received: <{}>", allocator.index(), message); expecting -= 1; } } allocator.inde...
// send typed data along each channel senders[0].send(format!("hello, {}", 0)); senders[1].send(format!("hello, {}", 1)); // no support for termination notification,
random_line_split
declFileWithExtendsClauseThatHasItsContainerNameConflict.js
//// [declFileWithExtendsClauseThatHasItsContainerNameConflict.ts] declare module A.B.C { class B { } } module A.B { export class EventManager { id: number; } } module A.B.C { export class ContextMenu extends EventManager { name: string; } } //// [declFileWithExtendsClaus...
() { _super.apply(this, arguments); } return ContextMenu; })(B.EventManager); C.ContextMenu = ContextMenu; })(C = B.C || (B.C = {})); })(B = A.B || (A.B = {})); })(A || (A = {})); //// [declFileWithExtendsClauseThatHasI...
ContextMenu
identifier_name
declFileWithExtendsClauseThatHasItsContainerNameConflict.js
//// [declFileWithExtendsClauseThatHasItsContainerNameConflict.ts] declare module A.B.C { class B { } } module A.B {
} } module A.B.C { export class ContextMenu extends EventManager { name: string; } } //// [declFileWithExtendsClauseThatHasItsContainerNameConflict.js] var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { ...
export class EventManager { id: number;
random_line_split
dlp_v2_generated_dlp_service_list_stored_info_types_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
# Make the request page_result = client.list_stored_info_types(request=request) # Handle the response for response in page_result: print(response) # [END dlp_v2_generated_DlpService_ListStoredInfoTypes_sync]
request = dlp_v2.ListStoredInfoTypesRequest( parent="parent_value", )
random_line_split
dlp_v2_generated_dlp_service_list_stored_info_types_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
# [END dlp_v2_generated_DlpService_ListStoredInfoTypes_sync]
client = dlp_v2.DlpServiceClient() # Initialize request argument(s) request = dlp_v2.ListStoredInfoTypesRequest( parent="parent_value", ) # Make the request page_result = client.list_stored_info_types(request=request) # Handle the response for response in page_result: prin...
identifier_body
dlp_v2_generated_dlp_service_list_stored_info_types_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
(): # Create a client client = dlp_v2.DlpServiceClient() # Initialize request argument(s) request = dlp_v2.ListStoredInfoTypesRequest( parent="parent_value", ) # Make the request page_result = client.list_stored_info_types(request=request) # Handle the response for respons...
sample_list_stored_info_types
identifier_name
dlp_v2_generated_dlp_service_list_stored_info_types_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
# [END dlp_v2_generated_DlpService_ListStoredInfoTypes_sync]
print(response)
conditional_block
test_url_middleware.py
# # 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 writing, software # distributed under...
# Copyright 2012 OpenStack Foundation
random_line_split