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 |
|---|---|---|---|---|
index.tsx | Item(
items: ClipboardItem[],
): Promise<undefined | Blob> {
for (const item of items) {
const type = item.types.find((type) => type.startsWith('image/'));
if (type) return item.getType(type);
}
}
interface Props {
onFile?: (file: File) => void;
showSnack?: SnackBarElement['showSnackbar'];
}
interfac... |
private onFileChange = (event: Event): void => {
const fileInput = event.target as HTMLInputElement;
const file = fileInput.files && fileInput.files[0];
if (!file) return;
this.fileInput!.value = '';
this.props.onFile!(file);
};
private onOpenClick = () => {
this.fileInput!.click();
}... | {
window.removeEventListener(
'beforeinstallprompt',
this.onBeforeInstallPromptEvent,
);
window.removeEventListener('appinstalled', this.onAppInstalled);
} | identifier_body |
generator-yielding-or-returning-itself.rs | // Copyright 2016 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 ... |
pub fn want_cyclic_generator_yield<T>(_: T)
where T: Generator<Yield = T, Return = ()>
{
}
fn supply_cyclic_generator_yield() {
want_cyclic_generator_yield(|| {
//~^ ERROR type mismatch
if false { yield None.unwrap(); }
None.unwrap()
})
}
fn main() { }
| {
want_cyclic_generator_return(|| {
//~^ ERROR type mismatch
if false { yield None.unwrap(); }
None.unwrap()
})
} | identifier_body |
generator-yielding-or-returning-itself.rs | // Copyright 2016 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 ... | <T>(_: T)
where T: Generator<Yield = T, Return = ()>
{
}
fn supply_cyclic_generator_yield() {
want_cyclic_generator_yield(|| {
//~^ ERROR type mismatch
if false { yield None.unwrap(); }
None.unwrap()
})
}
fn main() { }
| want_cyclic_generator_yield | identifier_name |
generator-yielding-or-returning-itself.rs | // Copyright 2016 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 ... |
fn supply_cyclic_generator_yield() {
want_cyclic_generator_yield(|| {
//~^ ERROR type mismatch
if false { yield None.unwrap(); }
None.unwrap()
})
}
fn main() { } | where T: Generator<Yield = T, Return = ()>
{
} | random_line_split |
generator-yielding-or-returning-itself.rs | // Copyright 2016 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 ... |
None.unwrap()
})
}
pub fn want_cyclic_generator_yield<T>(_: T)
where T: Generator<Yield = T, Return = ()>
{
}
fn supply_cyclic_generator_yield() {
want_cyclic_generator_yield(|| {
//~^ ERROR type mismatch
if false { yield None.unwrap(); }
None.unwrap()
})
}
fn main() ... | { yield None.unwrap(); } | conditional_block |
LibraryFormContents.js | import React from 'react';
import PropTypes from 'prop-types';
import FormField from '../../components/FormField';
import TextHelp from '../../components/TextHelp';
import DomainIdField from '../../components/DomainIdField';
import PodcastEdit from './PodcastEdit';
const LibraryFormContents = (props) => {
const { cl... | </fieldset>
{podcast}
</div>
);
};
LibraryFormContents.propTypes = {
className: PropTypes.string,
errors: PropTypes.object,
formState: PropTypes.object.isRequired,
session: PropTypes.object.isRequired,
};
LibraryFormContents.defaultProps = {
className: undefined,
errors: {},
};
export d... | random_line_split | |
LibraryFormContents.js |
import React from 'react';
import PropTypes from 'prop-types';
import FormField from '../../components/FormField';
import TextHelp from '../../components/TextHelp';
import DomainIdField from '../../components/DomainIdField';
import PodcastEdit from './PodcastEdit';
const LibraryFormContents = (props) => {
const { c... |
return (
<div className={className}>
<fieldset className="form__fields">
<FormField label="Name" error={errors.name}>
<input name="name"
value={library.name || ''}
onChange={formState.change('name')} />
</FormField>
<FormField name="text" label="De... | {
const url = `${window.location.origin}/${library.path || library.id}.rss`;
podcast = [
<p key="loc" className="form__text secondary">
Published at: {url}<br />
<a href={`https://validator.w3.org/feed/check.cgi?url=${encodeURIComponent(url)}`}>
Test
</a> <a href="https:/... | conditional_block |
BaseTexture.js | /**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
PIXI.BaseTextureCache = {};
PIXI.BaseTextureCacheIdGenerator = 0;
/**
* A texture stores the information that represents an image. All textures have a base texture.
*
* @class BaseTexture
* @uses EventTarget
* @constructor
* @param source {String} ... | */
this.source = source;
this._UID = PIXI._UID++;
/**
* Controls if RGB channels should be pre-multiplied by Alpha (WebGL only)
*
* @property premultipliedAlpha
* @type Boolean
* @default true
*/
this.premultipliedAlpha = true;
// used for webGL
/**
*... | /**
* The image source that is used to create the texture.
*
* @property source
* @type Image | random_line_split |
BaseTexture.js | /**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
PIXI.BaseTextureCache = {};
PIXI.BaseTextureCacheIdGenerator = 0;
/**
* A texture stores the information that represents an image. All textures have a base texture.
*
* @class BaseTexture
* @uses EventTarget
* @constructor
* @param source {String} ... |
this.source = null;
this.unloadFromGPU();
};
/**
* Changes the source image of the texture
*
* @method updateSourceImage
* @param newSrc {String} the path of the image
*/
PIXI.BaseTexture.prototype.updateSourceImage = function(newSrc)
{
this.hasLoaded = false;
this.source.src = null;
this.so... | {
delete PIXI.BaseTextureCache[this.source._pixiId];
} | conditional_block |
test.py | from __future__ import print_function
import sqlite3
import time
from datetime import datetime
def adapt_datetime(ts):
return int(time.mktime(ts.timetuple()))
sqlite3.register_adapter(datetime, adapt_datetime)
def pp(cursor, data=None, rowlens=0):
d = cursor.description
if not d:
return "#### NO ... | print (pp (c))
print ()
return conn
test()
| conn = sqlite3.connect(':memory:')
c = conn.cursor()
create_tables(c)
create_feeds(c)
create_items(c)
# c.execute('SELECT * FROM feeds')
# print ()
# print (pp (c))
# c.execute('SELECT * FROM items')
# print ()
# print (pp (c))
c.execute("""
SELECT item_ti... | identifier_body |
test.py | from __future__ import print_function
import sqlite3
import time
from datetime import datetime
def adapt_datetime(ts):
return int(time.mktime(ts.timetuple()))
sqlite3.register_adapter(datetime, adapt_datetime)
def pp(cursor, data=None, rowlens=0):
d = cursor.description
if not d:
return "#### NO ... | lengths = []
rules = []
if not data:
data = cursor.fetchall()
for dd in d: # iterate over description
l = dd[1]
if not l:
l = 12 # or default arg ...
l = max(l, len(dd[0])) # handle long names
names.append(dd[0])
lengths.append(l... | random_line_split | |
test.py | from __future__ import print_function
import sqlite3
import time
from datetime import datetime
def adapt_datetime(ts):
return int(time.mktime(ts.timetuple()))
sqlite3.register_adapter(datetime, adapt_datetime)
def pp(cursor, data=None, rowlens=0):
d = cursor.description
if not d:
|
names = []
lengths = []
rules = []
if not data:
data = cursor.fetchall()
for dd in d: # iterate over description
l = dd[1]
if not l:
l = 12 # or default arg ...
l = max(l, len(dd[0])) # handle long names
names.append(dd[0])
... | return "#### NO RESULTS ###" | conditional_block |
test.py | from __future__ import print_function
import sqlite3
import time
from datetime import datetime
def adapt_datetime(ts):
return int(time.mktime(ts.timetuple()))
sqlite3.register_adapter(datetime, adapt_datetime)
def pp(cursor, data=None, rowlens=0):
d = cursor.description
if not d:
return "#### NO ... | (c):
c.execute('''
CREATE TABLE items (
item_title TEXT,
item_content TEXT,
item_posted INTEGER,
item_updated INTEGER,
item_is_read INTEGER DEFAULT 0,
item_mute ... | create_tables | identifier_name |
platform_browser.ts | /**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
encode(text: string, encoding: string): Uint8Array {
if (encoding !== 'utf-8' && encoding !== 'utf8') {
throw new Error(
`Browser's encoder only supports utf-8, but got ${encoding}`);
}
if (this.textEncoder == null) {
this.textEncoder = new TextEncoder();
}
return this.text... | {
return performance.now();
} | identifier_body |
platform_browser.ts | /**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | (path: string, init?: RequestInit): Promise<Response> {
return fetch(path, init);
}
now(): number {
return performance.now();
}
encode(text: string, encoding: string): Uint8Array {
if (encoding !== 'utf-8' && encoding !== 'utf8') {
throw new Error(
`Browser's encoder only supports ... | fetch | identifier_name |
platform_browser.ts | /**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | if (encoding !== 'utf-8' && encoding !== 'utf8') {
throw new Error(
`Browser's encoder only supports utf-8, but got ${encoding}`);
}
if (this.textEncoder == null) {
this.textEncoder = new TextEncoder();
}
return this.textEncoder.encode(text);
}
decode(bytes: Uint8Array, enc... | }
encode(text: string, encoding: string): Uint8Array { | random_line_split |
platform_browser.ts | /**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
return this.textEncoder.encode(text);
}
decode(bytes: Uint8Array, encoding: string): string {
return new TextDecoder(encoding).decode(bytes);
}
}
if (env().get('IS_BROWSER')) {
env().setPlatform('browser', new PlatformBrowser());
}
| {
this.textEncoder = new TextEncoder();
} | conditional_block |
thepiratebay.py | # Author: Mr_Orange <mr_orange@hotmail.it>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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 Lic... |
continue
item = title, download_url, size, seeders, leechers
if mode is not 'RSS':
logging.debug("Found result: %s " % title)
items[mode].append(item)
# For each search mode sort all the items by ... | logging.debug(
"Found result %s but that doesn't seem like a trusted result so I'm ignoring it" % title) | conditional_block |
thepiratebay.py | # Author: Mr_Orange <mr_orange@hotmail.it>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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 Lic... |
"""
205 = SD, 208 = HD, 200 = All Videos
https://thepiratebay.gd/s/?q=Game of Thrones&type=search&orderby=7&page=0&category=200
"""
self.search_params = {
'q': '',
'type': 'search',
'orderby': 7,
'page': 0,
'category': ... | generic.TorrentProvider.__init__(self, "ThePirateBay")
self.supportsBacklog = True
self.public = True
self.ratio = None
self.confirmed = True
self.minseed = None
self.minleech = None
self.cache = ThePirateBayCache(self)
self.urls = {
'base_... | identifier_body |
thepiratebay.py | # Author: Mr_Orange <mr_orange@hotmail.it>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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 Lic... | (self, size):
size, modifier = size.split(' ')
size = float(size)
if modifier in 'KiB':
size = size * 1024
elif modifier in 'MiB':
size = size * 1024 ** 2
elif modifier in 'GiB':
size = size * 1024 ** 3
elif modifier in 'TiB':
... | _convertSize | identifier_name |
thepiratebay.py | # Author: Mr_Orange <mr_orange@hotmail.it>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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 Lic... | """
205 = SD, 208 = HD, 200 = All Videos
https://thepiratebay.gd/s/?q=Game of Thrones&type=search&orderby=7&page=0&category=200
"""
self.search_params = {
'q': '',
'type': 'search',
'orderby': 7,
'page': 0,
'category': 2... | }
self.url = self.urls[b'base_url']
self.headers.update({'User-Agent': USER_AGENT})
| random_line_split |
combinations.py | _v2 import adam as adam_v2
from tensorflow.contrib.optimizer_v2 import gradient_descent as gradient_descent_v2
from tensorflow.python.distribute import distribution_strategy_context
from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from tensorflow.python.training import adagrad
fro... | return self._required_gpus | identifier_body | |
combinations.py | _v2 import adagrad as adagrad_v2
from tensorflow.contrib.optimizer_v2 import adam as adam_v2
from tensorflow.contrib.optimizer_v2 import gradient_descent as gradient_descent_v2
from tensorflow.python.distribute import distribution_strategy_context
from tensorflow.python.eager import context
from tensorflow.python.frame... |
return combined_results
class NamedObject(object):
"""A class that translates an object into a good test name."""
def __init__(self, name, obj):
self._name = name
self._obj = obj
def __getattr__(self, name):
return getattr(self._obj, name)
def __call__(self, *args, **kwargs):
return self... | if set(a.keys()).intersection(set(b.keys())):
raise ValueError("Keys need to not overlap: {} vs {}".format(
a.keys(), b.keys()))
combined_results.append(OrderedDict(list(a.items()) + list(b.items()))) | conditional_block |
combinations.py | .optimizer_v2 import adagrad as adagrad_v2
from tensorflow.contrib.optimizer_v2 import adam as adam_v2
from tensorflow.contrib.optimizer_v2 import gradient_descent as gradient_descent_v2
from tensorflow.python.distribute import distribution_strategy_context
from tensorflow.python.eager import context
from tensorflow.py... | Args:
**kwargs: keyword arguments of form `option=[possibilities, ...]`
or `option=the_only_possibility`.
Returns:
a list of dictionaries for each combination. Keys in the dictionaries are
the keyword argument names. Each key has one value - one of the
corresponding keyword argument value... | Two sets of returned combinations can be concatenated using +. Their product
can be computed using `times()`.
| random_line_split |
combinations.py | rad_v2
from tensorflow.contrib.optimizer_v2 import adam as adam_v2
from tensorflow.contrib.optimizer_v2 import gradient_descent as gradient_descent_v2
from tensorflow.python.distribute import distribution_strategy_context
from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from tenso... | required_gpus | identifier_name | |
errors.rs | use next_swc::{
disallow_re_export_all_in_page::disallow_re_export_all_in_page, next_dynamic::next_dynamic,
};
use std::path::PathBuf;
use swc_common::FileName;
use swc_ecma_transforms_testing::test_fixture_allowing_error;
use swc_ecmascript::parser::{EsConfig, Syntax};
use testing::fixture;
fn syntax() -> Syntax ... | })
}
#[fixture("tests/errors/re-export-all-in-page/**/input.js")]
fn re_export_all_in_page(input: PathBuf) {
let output = input.parent().unwrap().join("output.js");
test_fixture_allowing_error(
syntax(),
&|_tr| disallow_re_export_all_in_page(true),
&input,
&output,
);
}
... | ..Default::default() | random_line_split |
errors.rs | use next_swc::{
disallow_re_export_all_in_page::disallow_re_export_all_in_page, next_dynamic::next_dynamic,
};
use std::path::PathBuf;
use swc_common::FileName;
use swc_ecma_transforms_testing::test_fixture_allowing_error;
use swc_ecmascript::parser::{EsConfig, Syntax};
use testing::fixture;
fn syntax() -> Syntax |
#[fixture("tests/errors/re-export-all-in-page/**/input.js")]
fn re_export_all_in_page(input: PathBuf) {
let output = input.parent().unwrap().join("output.js");
test_fixture_allowing_error(
syntax(),
&|_tr| disallow_re_export_all_in_page(true),
&input,
&output,
);
}
#[fixtu... | {
Syntax::Es(EsConfig {
jsx: true,
..Default::default()
})
} | identifier_body |
errors.rs | use next_swc::{
disallow_re_export_all_in_page::disallow_re_export_all_in_page, next_dynamic::next_dynamic,
};
use std::path::PathBuf;
use swc_common::FileName;
use swc_ecma_transforms_testing::test_fixture_allowing_error;
use swc_ecmascript::parser::{EsConfig, Syntax};
use testing::fixture;
fn | () -> Syntax {
Syntax::Es(EsConfig {
jsx: true,
..Default::default()
})
}
#[fixture("tests/errors/re-export-all-in-page/**/input.js")]
fn re_export_all_in_page(input: PathBuf) {
let output = input.parent().unwrap().join("output.js");
test_fixture_allowing_error(
syntax(),
... | syntax | identifier_name |
ng2-tabs.component.ts | import { Component, ContentChildren, AfterContentInit, Output, EventEmitter } from '@angular/core'
import { Ng2TabComponent } from './ng2-tab.component'
interface SelectTabModel {
tab?: Ng2TabComponent
metaData?: any
selectMethod?: string // 'clickedTab'
activatorId?: string
}
@Component({
selector: 'ng2-ta... |
public selectTab (options: SelectTabModel) {
let foundTab
let selectMethod
// The tab itself
if (options.tab) {
this.unselectAllTabs()
options.tab.active = true
// Select by activator ID
} else if (options.activatorId) {
selectMethod = 'activatorId'
foundTab = this.... | {
const activeTabs = this.coTabCmps.filter(tab => tab.active)
if (activeTabs.length === 0) {
this.selectTab({
tab: this.coTabCmps.first,
selectMethod: 'initFirstTab'
})
}
} | identifier_body |
ng2-tabs.component.ts | import { Component, ContentChildren, AfterContentInit, Output, EventEmitter } from '@angular/core'
import { Ng2TabComponent } from './ng2-tab.component'
interface SelectTabModel {
tab?: Ng2TabComponent
metaData?: any
selectMethod?: string // 'clickedTab'
activatorId?: string
}
@Component({
selector: 'ng2-ta... | else if (options.activatorId) {
selectMethod = 'activatorId'
foundTab = this.coTabCmps.toArray().find(tab => tab.activatorId === options.activatorId)
if (!foundTab) {
console.error(`No tab with activatorId: "${options.activatorId}" found`)
} else {
this.unselectAllTabs()
... | {
this.unselectAllTabs()
options.tab.active = true
// Select by activator ID
} | conditional_block |
ng2-tabs.component.ts | import { Component, ContentChildren, AfterContentInit, Output, EventEmitter } from '@angular/core'
import { Ng2TabComponent } from './ng2-tab.component'
interface SelectTabModel {
tab?: Ng2TabComponent
metaData?: any
selectMethod?: string // 'clickedTab'
activatorId?: string
}
@Component({
selector: 'ng2-ta... | selectMethod: options.selectMethod || selectMethod,
activatorId: options.activatorId
} as SelectTabModel)
return false
}
private unselectAllTabs () {
this.coTabCmps.toArray().forEach(tab => tab.active = false)
}
} | metaData: options.metaData, | random_line_split |
ng2-tabs.component.ts | import { Component, ContentChildren, AfterContentInit, Output, EventEmitter } from '@angular/core'
import { Ng2TabComponent } from './ng2-tab.component'
interface SelectTabModel {
tab?: Ng2TabComponent
metaData?: any
selectMethod?: string // 'clickedTab'
activatorId?: string
}
@Component({
selector: 'ng2-ta... | (options: SelectTabModel) {
let foundTab
let selectMethod
// The tab itself
if (options.tab) {
this.unselectAllTabs()
options.tab.active = true
// Select by activator ID
} else if (options.activatorId) {
selectMethod = 'activatorId'
foundTab = this.coTabCmps.toArray().... | selectTab | identifier_name |
iconListInfo.js | // JSON Object of all of the icons and their tags
export default {
apple : {
name : 'apple',
color: '#be0000',
image : 'apple67.svg',
tags: ['apple', 'fruit', 'food'],
categories: ['food', 'supermarket']
},
bread : {
name : 'bread',
color: '#c26b24',
image : 'bread14.svg',
tag... | categories: ['gift', 'shopping', 'supermarket']
}
}; | name : 'giftbox',
color: '#f32393',
image : 'giftbox56.svg',
tags: ['giftbox', 'gift', 'present'], | random_line_split |
nightwatch.py | .__QuotesEod = db.Table('Quotes.EOD')
self.__Securities = db.Table('Securities')
self.__Orders = db.Table('Orders')
s3 = boto3.resource('s3')
debug = os.environ['DEBUG_FOLDER']
self.__debug = s3.Object(debug, 'vix_roll.txt')
logging.basicConfig(format='%(asctime)s - %(lev... | ':s': symbol,
':m': maturity,
':p': productType,
':b': broker,
':o': order,
':t': trade,
':str': strategy
},
ReturnValues="UPDATED_NEW")
ex... | random_line_split | |
nightwatch.py | QuotesEod = db.Table('Quotes.EOD')
self.__Securities = db.Table('Securities')
self.__Orders = db.Table('Orders')
s3 = boto3.resource('s3')
debug = os.environ['DEBUG_FOLDER']
self.__debug = s3.Object(debug, 'vix_roll.txt')
logging.basicConfig(format='%(asctime)s - %(leveln... | ():
async with IGClient(params, self.Logger) as client:
auth = await client.Login()
self.Logger.info('Auth: %s' % auth)
lastMonth = datetime.date.today() - datetime.timedelta(days=30)
activities = await client.GetActivities(lastMonth.strftime(... | read | identifier_name |
nightwatch.py |
class CapsuleParams(object):
def __init__(self):
self.Region = ''
self.Instance = ''
self.Email = ''
self.Iam = ''
self.User = ''
self.Password = ''
self.Smtp = ''
class CapsuleController(object):
def __init__(self, params):
self.secDef = cont... | def __init__(self):
pass
@staticmethod
def reliable(func):
def _decorator(self, *args, **kwargs):
tries = 0
result = func(self, *args, **kwargs)
if result is None:
while result is None and tries < 10:
tries += 1
... | identifier_body | |
nightwatch.py | '#str': 'Strategy'
},
ExpressionAttributeValues={
':st': 'FILLED',
':s': symbol,
':m': maturity,
':p': productType,
':b': broker,
':o': order,
':t'... | main() | conditional_block | |
wheelevent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods;
use crate::dom::bindings::code... |
// https://w3c.github.io/uievents/#widl-WheelEvent-deltaZ
fn DeltaZ(&self) -> Finite<f64> {
self.delta_z.get()
}
// https://w3c.github.io/uievents/#widl-WheelEvent-deltaMode
fn DeltaMode(&self) -> u32 {
self.delta_mode.get()
}
// https://w3c.github.io/uievents/#widl-Wheel... | {
self.delta_y.get()
} | identifier_body |
wheelevent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods;
use crate::dom::bindings::code... |
self.upcast::<MouseEvent>().InitMouseEvent(
type_arg,
can_bubble_arg,
cancelable_arg,
view_arg,
detail_arg,
self.mouseevent.ScreenX(),
self.mouseevent.ScreenY(),
self.mouseevent.ClientX(),
self.mouseeve... | {
return;
} | conditional_block |
wheelevent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods;
use crate::dom::bindings::code... | self.delta_y.set(delta_y_arg);
self.delta_z.set(delta_z_arg);
self.delta_mode.set(delta_mode_arg);
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.mouseevent.IsTrusted()
}
} | self.delta_x.set(delta_x_arg); | random_line_split |
wheelevent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods;
use crate::dom::bindings::code... | (&self) -> u32 {
self.delta_mode.get()
}
// https://w3c.github.io/uievents/#widl-WheelEvent-initWheelEvent
fn InitWheelEvent(
&self,
type_arg: DOMString,
can_bubble_arg: bool,
cancelable_arg: bool,
view_arg: Option<&Window>,
detail_arg: i32,
d... | DeltaMode | identifier_name |
solid-gauge.src.js | * (c) 2010-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
var pInt = H.pInt,
pick = H.pick,
each = H.each,
isNumber = H.isNumber,
wrap = H.wrap,
Renderer = H.Renderer,
colorAxisMethods;
... |
break;
}
}
} else {
if (this.isLog) {
value = this.val2lin(value);
}
pos = 1 - ((this.max - value) / (this.max - this.min));
... | {
point.dataClass = i;
} | conditional_block |
solid-gauge.src.js | if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
factory(Highcharts);
}
}(function(Highcharts) {
(function(H) {
/**
* Solid angular gauge module
*
* (c) 2010-2017 Torstein Honsi
*
* License: www.hi... | (function(factory) { | random_line_split | |
dumpPHOTO.py | #!/usr/bin/python3
import sys
from gi.repository import GExiv2
phototags = {
'Exif.Photo.ExposureTime': "Belichtung:\t",
'Exif.Photo.FNumber': "Blende:\t\tF",
# 'Exif.Photo.ExposureProgram',
'Exif.Photo.ISOSpeedRatings': "ISO:\t\t", | # 'Exif.Photo.ExifVersion',
# 'Exif.Photo.DateTimeOriginal',
# 'Exif.Photo.DateTimeDigitized',
# 'Exif.Photo.ComponentsConfiguration',
# 'Exif.Photo.CompressedBitsPerPixel',
# 'Exif.Photo.ExposureBiasValue',
# 'Exif.Photo.MaxApertureValue',
# 'Exif.Photo.MeteringMode',
# 'Exif.Photo.... | # 'Exif.Photo.SensitivityType', | random_line_split |
dumpPHOTO.py | #!/usr/bin/python3
import sys
from gi.repository import GExiv2
phototags = {
'Exif.Photo.ExposureTime': "Belichtung:\t",
'Exif.Photo.FNumber': "Blende:\t\tF",
# 'Exif.Photo.ExposureProgram',
'Exif.Photo.ISOSpeedRatings': "ISO:\t\t",
# 'Exif.Photo.SensitivityType',
# 'Exif.Photo.ExifVersion',
... | metadata = GExiv2.Metadata(sys.argv[i])
print("file: {}".format(sys.argv[i]))
for key in phototags:
try:
print("{}: {}".format(phototags[key], metadata[key]))
except KeyError:
continue | conditional_block | |
conf.py | directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
import time
# If extensions (or modules to document with autodoc) ... | # not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generate... | random_line_split | |
jquery.bgiframe.unminified.js | /*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Version 3.0.0
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
... | (n) {
return n && n.constructor === Number ? n + 'px' : n;
}
}));
| prop | identifier_name |
jquery.bgiframe.unminified.js | /*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Version 3.0.0
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
... |
});
};
// old alias
$.fn.bgIframe = $.fn.bgiframe;
function prop(n) {
return n && n.constructor === Number ? n + 'px' : n;
}
}));
| {
$this.prepend($el);
} | conditional_block |
jquery.bgiframe.unminified.js | /*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Version 3.0.0
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
... | var $iframe = $('<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
'style="display:block;position:absolute;z-index:-1;"/>');
return this.each(function() {
var $this = $(this);
if ( s.conditional(this) === false ) { return; }
... | var condition = s.conditional;
s.conditional = function() { return condition; };
}
| random_line_split |
jquery.bgiframe.unminified.js | /*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Version 3.0.0
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
... |
}));
| {
return n && n.constructor === Number ? n + 'px' : n;
} | identifier_body |
tf_record_dataset_serialization_test.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
def _build_iterator_graph(self,
num_epochs,
batch_size=1,
compression_type=None,
buffer_size=None):
filenames = self._createFiles()
if compression_type == "ZLIB":
zlib_files = []
for i,... | random_line_split | |
tf_record_dataset_serialization_test.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
filenames = zlib_files
elif compression_type == "GZIP":
gzip_files = []
for i, fn in enumerate(self.test_filenames):
with open(fn, "rb") as f:
gzfn = os.path.join(self.get_temp_dir(), "tfrecord_%s.gz" % i)
with gzip.GzipFile(gzfn, "wb") as gzf:
gzf.write(f... | with open(fn, "rb") as f:
cdata = zlib.compress(f.read())
zfn = os.path.join(self.get_temp_dir(), "tfrecord_%s.z" % i)
with open(zfn, "wb") as f:
f.write(cdata)
zlib_files.append(zfn) | conditional_block |
tf_record_dataset_serialization_test.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | with open(fn, "rb") as f:
gzfn = os.path.join(self.get_temp_dir(), "tfrecord_%s.gz" % i)
with gzip.GzipFile(gzfn, "wb") as gzf:
gzf.write(f.read())
gzip_files.append(gzfn)
filenames = gzip_files
return core_readers.TFRecordDataset(
filenames, compress... | def _build_iterator_graph(self,
num_epochs,
batch_size=1,
compression_type=None,
buffer_size=None):
filenames = self._createFiles()
if compression_type == "ZLIB":
zlib_files = []
for i, fn... | identifier_body |
tf_record_dataset_serialization_test.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (self):
num_epochs = 5
batch_size = num_epochs
num_outputs = num_epochs * self._num_files * self._num_records // batch_size
# pylint: disable=g-long-lambda
self.run_core_tests(
lambda: self._build_iterator_graph(num_epochs, batch_size,
buffer_size=0... | testTFRecordWithoutBufferCore | identifier_name |
actions.js | import { fetchContacts, deleteContactById } from './utils/api'
export const ADD_CONTACT = 'ADD_CONTACT'
export const LOAD_CONTACTS = 'LOAD_CONTACTS'
export const CONTACTS_WERE_LOADED = 'CONTACTS_WERE_LOADED'
export const DELETE_CONTACT = 'DELETE_CONTACT'
export const CONTACT_WAS_DELETED = 'CONTACT_WAS_DELETED'
export ... |
})
}
| {
// ...and another when we finish!
dispatch({ type: CONTACT_WAS_DELETED, contactId })
} | conditional_block |
actions.js | import { fetchContacts, deleteContactById } from './utils/api'
export const ADD_CONTACT = 'ADD_CONTACT'
export const LOAD_CONTACTS = 'LOAD_CONTACTS'
export const CONTACTS_WERE_LOADED = 'CONTACTS_WERE_LOADED'
export const DELETE_CONTACT = 'DELETE_CONTACT'
export const CONTACT_WAS_DELETED = 'CONTACT_WAS_DELETED'
export ... | } | random_line_split | |
_wizard.js | var f = require('fs');
var _ = require('underscore');
var r = {};
var cr = require('../config.json').resources;
var k = require('../config.json').plugins;
var b = require('../config.json').APIVARS.PLUGINS;
var n = __dirname.replace('/autoform', b.DIR);
var w = ['tokens', 'settings'];
var s = ['actions', 'login', 'recov... |
}
};
var init = function() {
for(var i in k){
if(k.hasOwnProperty(i)){
var e = k[i];
var g = '/' + e;
var a = require(n + g + b.CONFIG);
j(a.resources);
}
}
};
init();
j(r);
var generator = function (cb) {
var t;
var x;
var v;
var u = _.union(Object.keys(r), Object.key... | {
if(!props[p].exclude){
r[p] = props[p];
}
} | conditional_block |
_wizard.js | var f = require('fs');
var _ = require('underscore');
var r = {};
var cr = require('../config.json').resources;
var k = require('../config.json').plugins;
var b = require('../config.json').APIVARS.PLUGINS;
var n = __dirname.replace('/autoform', b.DIR);
var w = ['tokens', 'settings'];
var s = ['actions', 'login', 'recov... | };
module.exports = generator; | random_line_split | |
app.routing.ts | import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './dashboard.component';
import { HeroesComponent } from './heroes.component';
import { HeroDetailComponent } from './hero-detail.component';
import { EditorComponent} from './editor.component';
import { AccordionDemoComponent} ... | path: 'accordion',
component: AccordionDemoComponent
}
];
export const routing = RouterModule.forRoot(appRoutes);
export const routedComponents = [DashboardComponent, HeroesComponent, HeroDetailComponent, EditorComponent, AccordionDemoComponent]; | component: EditorComponent
},
{ | random_line_split |
unboxed-closure-sugar-region.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 ... |
fn test<'a,'b>() {
// Parens are equivalent to omitting default in angle.
eq::< Foo<(isize,),()>, Foo(isize) >();
// Here we specify 'static explicitly in angle-bracket version.
// Parenthesized winds up getting inferred.
eq::< Foo<'static, (isize,),()>, Fo... | { } | identifier_body |
unboxed-closure-sugar-region.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 ... | () { }
| main | identifier_name |
unboxed-closure-sugar-region.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 ... |
fn test<'a,'b>() {
// Parens are equivalent to omitting default in angle.
eq::< Foo<(isize,),()>, Foo(isize) >();
// Here we specify 'static explicitly in angle-bracket version.
// Parenthesized winds up getting inferred.
eq::< Foo<'static, (isize,),()>, Foo... | fn same_type<A,B:Eq<A>>(a: A, b: B) { } | random_line_split |
gen_riscv.py | #!/usr/bin/env python
import os
def create_asm(instruction):
if instruction.startswith("main:"):
if "ja" in instruction:
instruction = "." + instruction
#print instruction
out = open("temp.asm", "wb")
out.write(" " + instruction + "\n")
out.close()
# --------------------------------- fold her... | fp1.close
os.remove("a.out")
os.remove("riscv_gnu.hex")
fp.close()
out.close()
os.remove("temp.asm")
| instruction = instruction.strip()
if instruction.startswith(";"): continue
print instruction
create_asm(instruction)
os.system("riscv64-unknown-elf-as temp.asm")
os.system("riscv64-unknown-elf-objcopy -F ihex a.out riscv_gnu.hex")
#os.system("as-new temp.asm")
#os.system("objcopy -F ihex a.out riscv_gnu.... | conditional_block |
gen_riscv.py | #!/usr/bin/env python
import os
def | (instruction):
if instruction.startswith("main:"):
if "ja" in instruction:
instruction = "." + instruction
#print instruction
out = open("temp.asm", "wb")
out.write(" " + instruction + "\n")
out.close()
# --------------------------------- fold here -------------------------------
fp = open("ri... | create_asm | identifier_name |
gen_riscv.py | #!/usr/bin/env python
import os
def create_asm(instruction):
|
# --------------------------------- fold here -------------------------------
fp = open("riscv_template.txt", "rb")
out = open("riscv.txt", "wb")
for instruction in fp:
instruction = instruction.strip()
if instruction.startswith(";"): continue
print instruction
create_asm(instruction)
os.system("riscv64-... | if instruction.startswith("main:"):
if "ja" in instruction:
instruction = "." + instruction
#print instruction
out = open("temp.asm", "wb")
out.write(" " + instruction + "\n")
out.close() | identifier_body |
gen_riscv.py | #!/usr/bin/env python
import os
def create_asm(instruction):
if instruction.startswith("main:"):
if "ja" in instruction:
instruction = "." + instruction
#print instruction
| out.write(" " + instruction + "\n")
out.close()
# --------------------------------- fold here -------------------------------
fp = open("riscv_template.txt", "rb")
out = open("riscv.txt", "wb")
for instruction in fp:
instruction = instruction.strip()
if instruction.startswith(";"): continue
print instruct... | out = open("temp.asm", "wb") | random_line_split |
test_distributed.py | from runtests.mpi import MPITest
from nbodykit import set_options, GlobalCache, use_distributed, use_mpi
from numpy.testing import assert_array_equal
from nbodykit.lab import UniformCatalog
def setup():
from distributed import LocalCluster, Client
cluster = LocalCluster(n_workers=1, threads_per_worker=1, proce... | (comm):
import pickle
cat = UniformCatalog(1e-3, 512, comm=comm)
ss = pickle.dumps(cat)
cat2 = pickle.loads(ss)
assert_array_equal(cat['Position'], cat2['Position'])
@MPITest([1])
def test_save(comm):
cat = UniformCatalog(1e-3, 512, comm=comm)
import tempfile
import shutil
tm... | test_pickle | identifier_name |
test_distributed.py | from runtests.mpi import MPITest
from nbodykit import set_options, GlobalCache, use_distributed, use_mpi
from numpy.testing import assert_array_equal
from nbodykit.lab import UniformCatalog
def setup():
from distributed import LocalCluster, Client
cluster = LocalCluster(n_workers=1, threads_per_worker=1, proce... | cat = UniformCatalog(1e-3, 512, comm=comm)
import tempfile
import shutil
tmpfile = tempfile.mkdtemp()
cat.save(tmpfile, dataset='data')
shutil.rmtree(tmpfile) | identifier_body | |
test_distributed.py | from runtests.mpi import MPITest
from nbodykit import set_options, GlobalCache, use_distributed, use_mpi |
def setup():
from distributed import LocalCluster, Client
cluster = LocalCluster(n_workers=1, threads_per_worker=1, processes=False)
use_distributed(Client(cluster))
def teardown():
from mpi4py import MPI
use_mpi(MPI.COMM_WORLD)
@MPITest([1])
def test_pickle(comm):
import pickle
cat = Uni... | from numpy.testing import assert_array_equal
from nbodykit.lab import UniformCatalog | random_line_split |
group_by.rs | <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distributed except according to those terms.
*/
use std::cell::RefCell;
use std::cmp::mi... | state.last_group = Some(g.clone());
// Construct the sub-iterator and yield it.
Some((
g.clone(),
Group {
state: self.state.clone(),
group_value: g,
first_value: Some(e),
}
))
}
fn size_hint(&se... |
// Remember this group. | random_line_split |
group_by.rs | <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distributed except according to those terms.
*/
use std::cell::RefCell;
use std::cmp::mi... | assert_eq!(g, 1);
assert_eq!(ii.next(), Some(3));
assert_eq!(ii.next(), Some(5));
assert_eq!(ii.next(), None);
let (g, mut ii) = oi.next().unwrap();
assert_eq!(g, 0);
assert_eq!(ii.next(), Some(4));
assert_eq!(ii.next(), Some(6));
assert_eq!(ii.ne... | {
let v = vec![0usize, 1, 2, 3, 5, 4, 6, 8, 7];
let mut oi = v.into_iter().group_by(|&e| e & 1);
let (g, mut ii) = oi.next().unwrap();
assert_eq!(g, 0);
assert_eq!(ii.next(), Some(0));
assert_eq!(ii.next(), None);
let (g, mut ii) = oi.next().unwrap();
... | identifier_body |
group_by.rs | <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distributed except according to those terms.
*/
use std::cell::RefCell;
use std::cmp::mi... | t, GroupFn, E, G> {
state: Rc<RefCell<GroupByShared<It, GroupFn, E, G>>>,
}
pub struct GroupByShared<It, GroupFn, E, G> {
iter: It,
group: GroupFn,
last_group: Option<G>,
push_back: Option<(G, E)>,
}
impl<It, GroupFn, E, G> Iterator for GroupBy<It, GroupFn, E, G> where GroupFn: FnMut(&E) -> G, It... | oupBy<I | identifier_name |
condvar.rs | use crate::sys::condvar as imp;
use crate::sys::mutex as mutex_imp;
use crate::sys_common::mutex::MovableMutex;
use crate::time::Duration;
mod check;
type CondvarCheck = <mutex_imp::MovableMutex as check::CondvarCheck>::Check;
/// An OS-based condition variable.
pub struct Condvar {
inner: imp::MovableCondvar,
... | (&self) {
unsafe { self.inner.notify_one() };
}
/// Awakens all current waiters on this condition variable.
#[inline]
pub fn notify_all(&self) {
unsafe { self.inner.notify_all() };
}
/// Waits for a signal on the specified mutex.
///
/// Behavior is undefined if the mut... | notify_one | identifier_name |
condvar.rs | use crate::sys::condvar as imp;
use crate::sys::mutex as mutex_imp;
use crate::sys_common::mutex::MovableMutex;
use crate::time::Duration;
mod check;
type CondvarCheck = <mutex_imp::MovableMutex as check::CondvarCheck>::Check;
/// An OS-based condition variable.
pub struct Condvar {
inner: imp::MovableCondvar,
... | pub fn notify_all(&self) {
unsafe { self.inner.notify_all() };
}
/// Waits for a signal on the specified mutex.
///
/// Behavior is undefined if the mutex is not locked by the current thread.
///
/// May panic if used with more than one mutex.
#[inline]
pub unsafe fn wait(&s... | #[inline] | random_line_split |
condvar.rs | use crate::sys::condvar as imp;
use crate::sys::mutex as mutex_imp;
use crate::sys_common::mutex::MovableMutex;
use crate::time::Duration;
mod check;
type CondvarCheck = <mutex_imp::MovableMutex as check::CondvarCheck>::Check;
/// An OS-based condition variable.
pub struct Condvar {
inner: imp::MovableCondvar,
... |
/// Waits for a signal on the specified mutex with a timeout duration
/// specified by `dur` (a relative time into the future).
///
/// Behavior is undefined if the mutex is not locked by the current thread.
///
/// May panic if used with more than one mutex.
#[inline]
pub unsafe fn wa... | {
self.check.verify(mutex);
self.inner.wait(mutex.raw())
} | identifier_body |
split_check.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::path::Path;
use std::sync::mpsc::{self, sync_channel};
use std::sync::Arc;
use std::time::Duration;
use engine_rocks::raw::DB;
use engine_rocks::Compat;
use raftstore::coprocessor::{
config::{Config, SplitCheckConfigManager},
Coproces... | (cfg: TiKvConfig, engine: Arc<DB>) -> (ConfigController, LazyWorker<Task>) {
let (router, _) = sync_channel(1);
let runner = Runner::new(
engine.c().clone(),
router.clone(),
CoprocessorHost::new(router),
cfg.coprocessor.clone(),
);
let share_worker = Worker::new("split-ch... | setup | identifier_name |
split_check.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::path::Path;
use std::sync::mpsc::{self, sync_channel};
use std::sync::Arc;
use std::time::Duration;
use engine_rocks::raw::DB;
use engine_rocks::Compat;
use raftstore::coprocessor::{
config::{Config, SplitCheckConfigManager},
Coproces... | "true".to_owned(),
);
m.insert("coprocessor.batch_split_limit".to_owned(), "123".to_owned());
m.insert(
"coprocessor.region_split_keys".to_owned(),
"12345".to_owned(),
);
m
};
cfg_controller.update(change).unwrap();
// config shoul... | {
let (mut cfg, _dir) = TiKvConfig::with_tmp().unwrap();
cfg.validate().unwrap();
let engine = tmp_engine(&cfg.storage.data_dir);
let (cfg_controller, mut worker) = setup(cfg.clone(), engine);
let scheduler = worker.scheduler();
let cop_config = cfg.coprocessor.clone();
// update of other m... | identifier_body |
split_check.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::path::Path;
use std::sync::mpsc::{self, sync_channel};
use std::sync::Arc;
use std::time::Duration;
use engine_rocks::raw::DB;
use engine_rocks::Compat;
use raftstore::coprocessor::{
config::{Config, SplitCheckConfigManager},
Coproces... | validate(&scheduler, move |cfg: &Config| {
assert_eq!(cfg, &cop_config);
});
worker.stop();
} | }; | random_line_split |
cap-order.module.ts | import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { RouterModule } from '@angular/router';
import { TheBuybackSharedModule } from '../../shared';
import {
CapOrderService,
CapOrderPopupService,
CapOrderComponent,
CapOrderDetailComponent,
CapOrderDialogComponent,
CapOrderP... | {}
| TheBuybackCapOrderModule | identifier_name |
cap-order.module.ts | import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { RouterModule } from '@angular/router';
| import {
CapOrderService,
CapOrderPopupService,
CapOrderComponent,
CapOrderDetailComponent,
CapOrderDialogComponent,
CapOrderPopupComponent,
CapOrderDeletePopupComponent,
CapOrderDeleteDialogComponent,
capOrderRoute,
capOrderPopupRoute,
CapOrderResolvePagingParams,
} from './... | import { TheBuybackSharedModule } from '../../shared'; | random_line_split |
stats.py | # Copyright 2008-2014 Nokia Solutions and Networks
#
# 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 l... |
def __cmp__(self, other):
return cmp(self._norm_name, other._norm_name)
def __nonzero__(self):
return not self.failed
def visit(self, visitor):
visitor.visit_stat(self)
class TotalStat(Stat):
"""Stores statistic values for a test run."""
#: Always string `total`
typ... | self.elapsed += test.elapsedtime | identifier_body |
stats.py | # Copyright 2008-2014 Nokia Solutions and Networks
#
# 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 l... |
def _update_elapsed(self, test):
self.elapsed += test.elapsedtime
def __cmp__(self, other):
return cmp(self._norm_name, other._norm_name)
def __nonzero__(self):
return not self.failed
def visit(self, visitor):
visitor.visit_stat(self)
class TotalStat(Stat):
"""... | self.failed += 1 | conditional_block |
stats.py | # Copyright 2008-2014 Nokia Solutions and Networks
#
# 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 l... | self.failed += other.failed
class TagStat(Stat):
"""Stores statistic values for a single tag."""
#: Always string `tag`.
type = 'tag'
def __init__(self, name, doc='', links=None, critical=False,
non_critical=False, combined=''):
Stat.__init__(self, name)
#: Do... | def add_stat(self, other):
self.passed += other.passed | random_line_split |
stats.py | # Copyright 2008-2014 Nokia Solutions and Networks
#
# 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 l... | (self, test):
self.elapsed += test.elapsedtime
def __cmp__(self, other):
return cmp(self._norm_name, other._norm_name)
def __nonzero__(self):
return not self.failed
def visit(self, visitor):
visitor.visit_stat(self)
class TotalStat(Stat):
"""Stores statistic values f... | _update_elapsed | identifier_name |
row.number.column.js | import {ColumnView} from '../scene/view';
import {ColumnModel} from './column.model';
import {TemplatePath} from '../template';
TemplatePath.register('row-number-cell', (template, column) => {
return {
model: template.for,
resource: column.key
};
});
export class RowNumberColumnModel extends ColumnModel {
cons... | (model) {
return model ? RowNumberColumn.assign(model) : new RowNumberColumnModel();
}
} | model | identifier_name |
row.number.column.js | import {ColumnView} from '../scene/view';
import {ColumnModel} from './column.model';
import {TemplatePath} from '../template';
TemplatePath.register('row-number-cell', (template, column) => {
return {
model: template.for,
resource: column.key
};
});
export class RowNumberColumnModel extends ColumnModel {
cons... |
static model(model) {
return model ? RowNumberColumn.assign(model) : new RowNumberColumnModel();
}
} | {
super(model);
} | identifier_body |
row.number.column.js | import {ColumnView} from '../scene/view'; | TemplatePath.register('row-number-cell', (template, column) => {
return {
model: template.for,
resource: column.key
};
});
export class RowNumberColumnModel extends ColumnModel {
constructor() {
super('row-number');
this.pin = 'left';
this.key = '$row.number';
this.title = 'No.';
this.canEdit = false... | import {ColumnModel} from './column.model';
import {TemplatePath} from '../template';
| random_line_split |
errors.py | # Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | (Error):
pass
class UserSetupError(Error):
pass
class ThreadException(Error):
pass
class CalledProcessException(Error):
pass
class Benchmarks(object):
"""Errors raised by individual benchmark."""
class PrepareException(Error):
pass
class MissingObjectCredentialException(Error):
... | IpParsingError | identifier_name |
errors.py | # Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | pass
class RetryableDeletionError(Error):
pass | random_line_split | |
errors.py | # Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
raise TypeError('The argument of FromDebugInfo should be an instance '
'of dictionary.')
@staticmethod
def FormatDebugInfo(info, error_message):
"""A function to return a string in human readable format.
Args:
info: A dictionary containing debug information (su... | info = VirtualMachine.VirtualMachineError.FormatDebugInfo(
info, error_message)
return cls(info) | conditional_block |
errors.py | # Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
class RestConnectionError(Error):
pass
class IpParsingError(Error):
pass
class UserSetupError(Error):
pass
class ThreadException(Error):
pass
class CalledProcessException(Error):
pass
class Benchmarks(object):
"""Errors raised by individual benchmark."""
class PrepareException... | """An error raised when VM is running but not SSHable."""
pass | identifier_body |
StatisticsSpec.js | (function() {
'use strict';
describe('statistics', function() {
var $scope, element;
beforeEach(module('weddinvApp'));
beforeEach(inject(function($injector) {
$scope = $injector.get('$rootScope').$new();
var $compile = $injector.get('$compile'),
template = "<stat... | });
it('should show up total number of pending invitations', function() {
expect(paragraphs.eq(4).text()).toMatch(/Total of pending invitations: 1/);
});
});
});
}()); | expect(paragraphs.eq(3).text()).toMatch(/Total of rejected invitations: 1/); | random_line_split |
StatisticsSpec.js | (function() {
'use strict';
describe('statistics', function() {
var $scope, element;
beforeEach(module('weddinvApp'));
beforeEach(inject(function($injector) {
$scope = $injector.get('$rootScope').$new();
var $compile = $injector.get('$compile'),
template = "<stat... | ;
$scope.invitations[0].isPending.andReturn(true);
$scope.invitations[1].isRejected.andReturn(true);
$scope.invitations[2].isAccepted.andReturn(true);
$scope.$digest();
paragraphs = element.find('p');
});
it('should show up total number of people assisting the event'... | {
$scope.invitations.push(jasmine.createSpyObj('invitation', [
'isAccepted',
'isRejected',
'isPending'
]));
} | conditional_block |
seq2seq_model.py | max_gradient_norm,
batch_size,
learning_rate,
learning_rate_decay_factor,
use_lstm=True,
num_samples=512,
forward_only=False,
dtype=tf.float32):
"""Create the model.
Args:
source_vocab_... | """Sequence-to-sequence model with attention and for multiple buckets.
This class implements a multi-layer recurrent neural network as encoder,
and an attention-based decoder. This is the same as the model described in
this paper: http://arxiv.org/abs/1412.7449 - please look there for details,
or into the seq2... | identifier_body | |
seq2seq_model.py | GRU cells in addition to LSTM cells, and
sampled softmax to handle large output vocabulary size. A single-layer
version of this model, but with bi-directional encoder, was presented in
http://arxiv.org/abs/1409.0473
and sampled softmax is described in Section 3 of the following paper.
http://arxiv.org/ab... | average perplexity, and the outputs.
Raises:
ValueError: if length of encoder_inputs, decoder_inputs, or
target_weights disagrees with bucket size for the specified bucket_id.
"""
# Check if the sizes match.
encoder_size, decoder_size = self.buckets[bucket_id]
if len(encoder_inp... | Returns:
A triple consisting of gradient norm (or None if we did not do backward), | random_line_split |
seq2seq_model.py | set, we do not construct the backward pass in the model.
dtype: the data type to use to store internal variables.
"""
self.source_vocab_size = source_vocab_size
self.target_vocab_size = target_vocab_size
self.buckets = buckets
self.batch_size = batch_size
self.learning_rate = tf.Variable(... | encoder_input, decoder_input = random.choice(data[bucket_id])
# Encoder inputs are padded and then reversed.
encoder_pad = [data_utils.PAD_ID] * (encoder_size - len(encoder_input))
encoder_inputs.append(list(reversed(encoder_input + encoder_pad)))
# Decoder inputs get an extra "GO" symbol, and... | conditional_block | |
seq2seq_model.py | U cells in addition to LSTM cells, and
sampled softmax to handle large output vocabulary size. A single-layer
version of this model, but with bi-directional encoder, was presented in
http://arxiv.org/abs/1409.0473
and sampled softmax is described in Section 3 of the following paper.
http://arxiv.org/abs/1... | (self, session, encoder_inputs, decoder_inputs, target_weights,
bucket_id, forward_only):
"""Run a step of the model feeding the given inputs.
Args:
session: tensorflow session to use.
encoder_inputs: list of numpy int vectors to feed as encoder inputs.
decoder_inputs: list of nump... | step | identifier_name |
html_variable_assignment_visitor.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/// <amd-module name="@angular/core/schematics/migrations/template-var-assignment/angular/html_variable_assignment_vi... | extends NullVisitor {
variableAssignments: TemplateVariableAssignment[];
private currentVariables;
private expressionAstVisitor;
visitElement(element: Element): void;
visitTemplate(template: Template): void;
visitBoundEvent(node: BoundEvent): void;
}
| HtmlVariableAssignmentVisitor | identifier_name |
html_variable_assignment_visitor.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/// <amd-module name="@angular/core/schematics/migrations/template-var-assignment/angular/html_variable_assignment_vi... | * expressions that write to local template variables within bound events.
*/
export declare class HtmlVariableAssignmentVisitor extends NullVisitor {
variableAssignments: TemplateVariableAssignment[];
private currentVariables;
private expressionAstVisitor;
visitElement(element: Element): void;
vis... | * HTML AST visitor that traverses the Render3 HTML AST in order to find all | random_line_split |
conf.py | cache
from google.appengine.ext import db
from google.appengine.api import validation
from google.appengine.api import yaml_object
except:
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext import validation
from google.appengine.ext import yaml_object
... | (self):
self.regex = validation.Regex(PARAMETER_NAME_REGEX)
def Validate(self, value, key):
"""Check that all parameter names are valid.
This is used as a validator when parsing conf.yaml.
Args:
value: the value to check.
key: A description of the context for which this value is being
... | __init__ | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.