file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
main.rs | extern crate piston;
extern crate graphics;
extern crate piston_window;
extern crate time;
extern crate rand;
extern crate ai_behavior;
extern crate cgmath;
extern crate opengl_graphics;
mod app;
mod entitymanager;
mod entity;
mod system;
mod player;
mod config;
mod person;
mod personspawner;
mod graphics_context;
us... | .unwrap_or_else(|e| { panic!("Failed to build PistonWindow: {}", e) });
window.set_ups(60);
let mut background_textures :Vec<String> = Vec::new();
background_textures.push(String::from("assets/img/ground/placeholder_01.jpg"));
background_textures.push(String::from("assets/img/ground/placeholder... | .exit_on_esc(true)
.opengl(opengl)
.build() | random_line_split |
main.rs | extern crate piston;
extern crate graphics;
extern crate piston_window;
extern crate time;
extern crate rand;
extern crate ai_behavior;
extern crate cgmath;
extern crate opengl_graphics;
mod app;
mod entitymanager;
mod entity;
mod system;
mod player;
mod config;
mod person;
mod personspawner;
mod graphics_context;
us... | () {
let mut rng = rand::thread_rng();
let seed: [u32;4] = [rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>()];
let opengl = OpenGL::V3_2;
let mut window: PistonWindow = WindowSettings::new("GGJ2016", [800, 600])
.exit_on_esc(true)
.opengl(opengl)
.build()
... | main | identifier_name |
main.rs | extern crate piston;
extern crate graphics;
extern crate piston_window;
extern crate time;
extern crate rand;
extern crate ai_behavior;
extern crate cgmath;
extern crate opengl_graphics;
mod app;
mod entitymanager;
mod entity;
mod system;
mod player;
mod config;
mod person;
mod personspawner;
mod graphics_context;
us... | {
let mut rng = rand::thread_rng();
let seed: [u32;4] = [rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>()];
let opengl = OpenGL::V3_2;
let mut window: PistonWindow = WindowSettings::new("GGJ2016", [800, 600])
.exit_on_esc(true)
.opengl(opengl)
.build()
... | identifier_body | |
main.rs | extern crate piston;
extern crate graphics;
extern crate piston_window;
extern crate time;
extern crate rand;
extern crate ai_behavior;
extern crate cgmath;
extern crate opengl_graphics;
mod app;
mod entitymanager;
mod entity;
mod system;
mod player;
mod config;
mod person;
mod personspawner;
mod graphics_context;
us... |
if let Some(args) = e.release_args() {
app.key_release(args);
}
if let Some(args) = e.update_args() {
app.update(args);
}
ctx.update_translation(app.get_player().get_position().x as u32, app.get_player().get_position().y as u32);
if let Some(a... | {
app.key_press(args);
} | conditional_block |
index.js | "use strict";
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createElement = _interopRequireDefault(require("../createElement"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _usePlatformMethods = _interopRe... |
if (onValueChange) {
onValueChange(value, selectedIndex);
}
} // $FlowFixMe
var supportedProps = _objectSpread({
children: children,
disabled: enabled === false ? true : undefined,
onChange: handleChange,
style: [styles.initial, style],
testID: testID,
value: selectedValue
... | random_line_split | |
index.js | "use strict";
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createElement = _interopRequireDefault(require("../createElement"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _usePlatformMethods = _interopRe... | (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPr... | _objectSpread | identifier_name |
index.js | "use strict";
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createElement = _interopRequireDefault(require("../createElement"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _usePlatformMethods = _interopRe... | else { obj[key] = value; } return obj; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = s... | { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } | conditional_block |
index.js | "use strict";
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createElement = _interopRequireDefault(require("../createElement"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _usePlatformMethods = _interopRe... |
var supportedProps = _objectSpread({
children: children,
disabled: enabled === false ? true : undefined,
onChange: handleChange,
style: [styles.initial, style],
testID: testID,
value: selectedValue
}, other);
var platformMethodsRef = (0, _usePlatformMethods.default)(supportedProps);
... | {
var _e$target = e.target,
selectedIndex = _e$target.selectedIndex,
value = _e$target.value;
if (onValueChange) {
onValueChange(value, selectedIndex);
}
} // $FlowFixMe | identifier_body |
mergeProcedureVirtual.py | # Serial Photo Merge
# Copyright (C) 2017 Simone Riva mail: simone.rva {at} gmail {dot} com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#(at your optio... | (self, rif):
self._read_img_factory = rif
if self.images_iterator:
self.images_iterator.read_image_factory = rif
read_image_factory = property(
get_read_image_factory, set_read_image_factory)
def execute(self):
NotImplementedError(
" %s : is virutal and ... | set_read_image_factory | identifier_name |
mergeProcedureVirtual.py | # Serial Photo Merge
# Copyright (C) 2017 Simone Riva mail: simone.rva {at} gmail {dot} com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#(at your optio... |
class MergeProcedureVirtual(object):
def __init__(self):
self._img_list = None
self._resimg = None
self._refimage = None
self._images_iterator = None
self._read_img_factory = ReadImageFarctory()
def set_images_iterator(self, img_itr):
self._images_iterator = ... | if color_bits == 8:
return np.uint8
elif color_bits == 16:
return np.uint16 | identifier_body |
mergeProcedureVirtual.py | # Serial Photo Merge
# Copyright (C) 2017 Simone Riva mail: simone.rva {at} gmail {dot} com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#(at your optio... |
def get_resulting_image(self):
return self._resimg
def set_resulting_image(self, resarr):
self._resimg = resarr
resulting_image = property(get_resulting_image, set_resulting_image) | def execute(self):
NotImplementedError(
" %s : is virutal and must be overridden." % sys._getframe().f_code.co_name) | random_line_split |
mergeProcedureVirtual.py | # Serial Photo Merge
# Copyright (C) 2017 Simone Riva mail: simone.rva {at} gmail {dot} com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#(at your optio... |
class MergeProcedureVirtual(object):
def __init__(self):
self._img_list = None
self._resimg = None
self._refimage = None
self._images_iterator = None
self._read_img_factory = ReadImageFarctory()
def set_images_iterator(self, img_itr):
self._images_iterator = ... | return np.uint16 | conditional_block |
ziptuple.rs | use super::size_hint;
/// See [`multizip`](../fn.multizip.html) for more information.
#[derive(Clone)]
pub struct Zip<T> {
t: T, | #[deprecated(note = "Renamed to multizip")]
pub fn new<U>(t: U) -> Zip<T>
where Zip<T>: From<U>,
Zip<T>: Iterator,
{
multizip(t)
}
}
/// An iterator that generalizes *.zip()* and allows running multiple iterators in lockstep.
///
/// The iterator `Zip<(I, J, ..., M)>` is f... | }
impl<T> Zip<T> {
/// Deprecated: renamed to multizip | random_line_split |
ziptuple.rs | use super::size_hint;
/// See [`multizip`](../fn.multizip.html) for more information.
#[derive(Clone)]
pub struct Zip<T> {
t: T,
}
impl<T> Zip<T> {
/// Deprecated: renamed to multizip
#[deprecated(note = "Renamed to multizip")]
pub fn new<U>(t: U) -> Zip<T>
where Zip<T>: From<U>,
... |
}
/// An iterator that generalizes *.zip()* and allows running multiple iterators in lockstep.
///
/// The iterator `Zip<(I, J, ..., M)>` is formed from a tuple of iterators (or values that
/// implement `IntoIterator`) and yields elements
/// until any of the subiterators yields `None`.
///
/// The iterator element ... | {
multizip(t)
} | identifier_body |
ziptuple.rs | use super::size_hint;
/// See [`multizip`](../fn.multizip.html) for more information.
#[derive(Clone)]
pub struct Zip<T> {
t: T,
}
impl<T> Zip<T> {
/// Deprecated: renamed to multizip
#[deprecated(note = "Renamed to multizip")]
pub fn | <U>(t: U) -> Zip<T>
where Zip<T>: From<U>,
Zip<T>: Iterator,
{
multizip(t)
}
}
/// An iterator that generalizes *.zip()* and allows running multiple iterators in lockstep.
///
/// The iterator `Zip<(I, J, ..., M)>` is formed from a tuple of iterators (or values that
/// implement ... | new | identifier_name |
stix-text-array.component.ts | import { Component, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'stix-text-array',
templateUrl: './stix-text-array.component.html'
})
export class StixTextArrayComponent {
@Input() public model: any;
@Input() public propertyName: any;
public ... | (index: number, obj: any): any {
return index;
}
public makePlaceholder(prop: string) {
let retVal = prop.replace(/e?s$/, '');
retVal = retVal.replace(/\b([a-z])(\w+)/g, (_, g1, g2) => {
let word = g1.concat(g2);
if (word === 'and' || word === 'or' || word === 't... | trackByIndex | identifier_name |
stix-text-array.component.ts | import { Component, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'stix-text-array',
templateUrl: './stix-text-array.component.html'
})
export class StixTextArrayComponent {
@Input() public model: any;
@Input() public propertyName: any;
public ... |
return g1.toUpperCase() + g2;
});
return retVal;
}
}
| {
return word;
} | conditional_block |
stix-text-array.component.ts | import { Component, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'stix-text-array',
templateUrl: './stix-text-array.component.html'
})
export class StixTextArrayComponent {
@Input() public model: any;
@Input() public propertyName: any;
public ... |
}
| {
let retVal = prop.replace(/e?s$/, '');
retVal = retVal.replace(/\b([a-z])(\w+)/g, (_, g1, g2) => {
let word = g1.concat(g2);
if (word === 'and' || word === 'or' || word === 'the') {
return word;
}
return g1.toUpperCase() + g2;
});... | identifier_body |
stix-text-array.component.ts | import { Component, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'stix-text-array',
templateUrl: './stix-text-array.component.html'
})
export class StixTextArrayComponent {
@Input() public model: any;
@Input() public propertyName: any;
public ... | return retVal;
}
} | if (word === 'and' || word === 'or' || word === 'the') {
return word;
}
return g1.toUpperCase() + g2;
}); | random_line_split |
step4.py | # 14.
print_log('\n14. Issuer (Trust Anchor) is creating a Credential Offer for Prover\n')
cred_offer_json = await anoncreds.issuer_create_credential_offer(issuer_wallet_handle,
cred_def_id)
print_log('Credential Offer: ')
... | # 20.
print_log('\n20. Deleting pool ledger config\n')
await pool.delete_pool_ledger_config(pool_name) | random_line_split | |
totaleq.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
let trait_def = TraitDef {
cx: cx, span: span,
path: Path::new(~["std", "cmp", "TotalEq"]),
additional_bounds: ~[],
generics: LifetimeBounds::empty(),
methods: ~[
MethodDef {
name: "equals",
generics: LifetimeBounds::empty(),
... | {
cs_and(|cx, span, _, _| cx.expr_bool(span, false),
cx, span, substr)
} | identifier_body |
totaleq.rs | // Copyright 2013 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 ... | (cx: &ExtCtxt,
span: Span,
mitem: @MetaItem,
in_items: ~[@Item]) -> ~[@Item] {
fn cs_equals(cx: &ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
cs_and(|cx, span, _, _| cx.expr_bool(span, false),
... | expand_deriving_totaleq | identifier_name |
totaleq.rs | // Copyright 2013 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 ... | }
]
};
trait_def.expand(mitem, in_items)
} | random_line_split | |
ramsAndSheeps.js | $(document).ready(function () {
$('#userData').hide();
$('#topScores').show();
// enchanced method addEventListener
function addEventListener(selector, eventType, listener) {
$(selector).on(eventType, listener);
}
function trigerClick($button) {
$button.click();
}
va... | var ramsAndSheepsHighScores = JSON.parse(localStorage.getItem('ramsAndSheepsHighScores')) || [];
function addScore(name, guesses) {
var user = {
name: name,
score: guesses
}
ramsAndSheepsHighScores.push(user);
var sortedH... | checkNumber: checkNumber
}
})();
var HighScores = (function () { | random_line_split |
ramsAndSheeps.js | $(document).ready(function () {
$('#userData').hide();
$('#topScores').show();
// enchanced method addEventListener
function addEventListener(selector, eventType, listener) {
$(selector).on(eventType, listener);
}
function trigerClick($button) {
$button.click();
}
va... | uessNumber, rams, sheeps) {
var ul = $('#guesses ul');
var li = $('<li>');
if (rams < 4) {
li.text(guesses + ': (' + guessNumber.join('') + ') You have ' + rams + ' rams and ' + sheeps + ' sheeps!');
ul.prepend(li);
}
else {
... | nageResult(g | identifier_name |
ramsAndSheeps.js | $(document).ready(function () {
$('#userData').hide();
$('#topScores').show();
// enchanced method addEventListener
function addEventListener(selector, eventType, listener) {
$(selector).on(eventType, listener);
}
function trigerClick($button) {
$button.click();
}
va... | function getUserInput(value) {
value = validateNumber(value);
guessNumber = String(parseInt(value)).split('');
}
function validateNumber(number) {
number = number.trim();
if (number.length != 4) {
throw new Error("The number must b... | var newNumber = [];
guesses = 0;
newNumber[0] = Math.round(Math.random() * 8 + 1); // first digit must be bigger than 0
newNumber[1] = Math.round(Math.random() * 9);
newNumber[2] = Math.round(Math.random() * 9);
newNumber[3] = Math.round(Math.rando... | identifier_body |
ramsAndSheeps.js | $(document).ready(function () {
$('#userData').hide();
$('#topScores').show();
// enchanced method addEventListener
function addEventListener(selector, eventType, listener) {
$(selector).on(eventType, listener);
}
function trigerClick($button) {
$button.click();
}
va... | number = String(parseInt(number));
if (isNaN(number) || (number < 1000 || number > 10000)) {
throw new Error("This is not a 4 digit number!");
}
return number;
}
function checkNumber() {
var rams = 0;
var sheeps = 0... | throw new Error("The number must be 4 digits long!");
}
| conditional_block |
unittest_utils.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 applicab... |
else:
raise AssertionError('Unsupported type: %s' % type(values[0]))
add(values)
return example.SerializeToString()
| add = feature.int64_list.value.extend | conditional_block |
unittest_utils.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 applicab... |
def create_serialized_example(name_to_values):
"""Creates a tf.Example proto using a dictionary.
It automatically detects type of values and define a corresponding feature.
Args:
name_to_values: A dictionary.
Returns:
tf.Example proto.
"""
example = tf.train.Example()
for name, values in nam... | """Creates an image with random values.
Args:
image_format: An image format (PNG or JPEG).
shape: A tuple with image shape (including channels).
Returns:
A tuple (<numpy ndarray>, <a string with encoded image>)
"""
image = np.random.randint(low=0, high=255, size=shape, dtype='uint8')
io = String... | identifier_body |
unittest_utils.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 applicab... | Returns:
tf.Example proto.
"""
example = tf.train.Example()
for name, values in name_to_values.items():
feature = example.features.feature[name]
if isinstance(values[0], str):
add = feature.bytes_list.value.extend
elif isinstance(values[0], float):
add = feature.float32_list.value.ex... | name_to_values: A dictionary.
| random_line_split |
unittest_utils.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 applicab... | (image_format, shape):
"""Creates an image with random values.
Args:
image_format: An image format (PNG or JPEG).
shape: A tuple with image shape (including channels).
Returns:
A tuple (<numpy ndarray>, <a string with encoded image>)
"""
image = np.random.randint(low=0, high=255, size=shape, dty... | create_random_image | identifier_name |
migration-0003.ts | import {DesktopCryptoFacade} from "../../DesktopCryptoFacade"
import type {Config} from "../ConfigCommon"
import {downcast} from "@tutao/tutanota-utils"
import type {DesktopKeyStoreFacade} from "../../KeyStoreFacadeImpl"
import {log} from "../../DesktopLog"
async function | (oldConfig: Config, crypto: DesktopCryptoFacade, keyStoreFacade: DesktopKeyStoreFacade): Promise<void> {
Object.assign(oldConfig, {
desktopConfigVersion: 3,
})
if (oldConfig.pushIdentifier) {
try {
const deviceKey = await keyStoreFacade.getDeviceKey()
Object.assign(oldConfig, {
sseInfo: crypto.aesEncr... | migrate | identifier_name |
migration-0003.ts | import {DesktopCryptoFacade} from "../../DesktopCryptoFacade"
import type {Config} from "../ConfigCommon"
import {downcast} from "@tutao/tutanota-utils"
import type {DesktopKeyStoreFacade} from "../../KeyStoreFacadeImpl"
import {log} from "../../DesktopLog"
async function migrate(oldConfig: Config, crypto: DesktopCryp... |
}
export const migrateClient = migrate
export const migrateAdmin = migrate | {
try {
const deviceKey = await keyStoreFacade.getDeviceKey()
Object.assign(oldConfig, {
sseInfo: crypto.aesEncryptObject(deviceKey, downcast(oldConfig.pushIdentifier)),
})
} catch (e) {
// cannot read device key, just remove sseInfo from old config
log.warn("migration003: could not read device k... | conditional_block |
migration-0003.ts | import {DesktopCryptoFacade} from "../../DesktopCryptoFacade"
import type {Config} from "../ConfigCommon"
import {downcast} from "@tutao/tutanota-utils"
import type {DesktopKeyStoreFacade} from "../../KeyStoreFacadeImpl"
import {log} from "../../DesktopLog"
async function migrate(oldConfig: Config, crypto: DesktopCryp... |
export const migrateClient = migrate
export const migrateAdmin = migrate | {
Object.assign(oldConfig, {
desktopConfigVersion: 3,
})
if (oldConfig.pushIdentifier) {
try {
const deviceKey = await keyStoreFacade.getDeviceKey()
Object.assign(oldConfig, {
sseInfo: crypto.aesEncryptObject(deviceKey, downcast(oldConfig.pushIdentifier)),
})
} catch (e) {
// cannot read devic... | identifier_body |
migration-0003.ts | import {DesktopCryptoFacade} from "../../DesktopCryptoFacade"
import type {Config} from "../ConfigCommon"
import {downcast} from "@tutao/tutanota-utils"
import type {DesktopKeyStoreFacade} from "../../KeyStoreFacadeImpl"
import {log} from "../../DesktopLog"
async function migrate(oldConfig: Config, crypto: DesktopCryp... | })
if (oldConfig.pushIdentifier) {
try {
const deviceKey = await keyStoreFacade.getDeviceKey()
Object.assign(oldConfig, {
sseInfo: crypto.aesEncryptObject(deviceKey, downcast(oldConfig.pushIdentifier)),
})
} catch (e) {
// cannot read device key, just remove sseInfo from old config
log.warn("m... | random_line_split | |
__init__.py | """
support for presenting detailed information in failing assertions.
"""
import py
import sys
import pytest
from _pytest.monkeypatch import monkeypatch
from _pytest.assertion import util
def pytest_addoption(parser):
group = parser.getgroup("debugconfig")
group.addoption('--assert', action="store", dest="ass... | (self, config, mode):
self.mode = mode
self.trace = config.trace.root.get("assertion")
def pytest_configure(config):
mode = config.getvalue("assertmode")
if config.getvalue("noassert") or config.getvalue("nomagic"):
mode = "plain"
if mode == "rewrite":
try:
impor... | __init__ | identifier_name |
__init__.py | """
support for presenting detailed information in failing assertions.
"""
import py
import sys
import pytest
from _pytest.monkeypatch import monkeypatch
from _pytest.assertion import util
def pytest_addoption(parser):
group = parser.getgroup("debugconfig")
group.addoption('--assert', action="store", dest="ass... |
util._reprcompare = callbinrepr
def pytest_runtest_teardown(item):
util._reprcompare = None
def pytest_sessionfinish(session):
hook = session.config._assertstate.hook
if hook is not None:
hook.session = None
def _load_modules(mode):
"""Lazily import assertion related code."""
global ... | res = '\n~'.join(new_expl)
if item.config.getvalue("assertmode") == "rewrite":
# The result will be fed back a python % formatting
# operation, which will fail if there are extraneous
# '%'s in the string. Escape them here.
... | conditional_block |
__init__.py | """
support for presenting detailed information in failing assertions.
"""
import py
import sys
import pytest
from _pytest.monkeypatch import monkeypatch
from _pytest.assertion import util
def pytest_addoption(parser):
group = parser.getgroup("debugconfig")
group.addoption('--assert', action="store", dest="ass... |
def _load_modules(mode):
"""Lazily import assertion related code."""
global rewrite, reinterpret
from _pytest.assertion import reinterpret
if mode == "rewrite":
from _pytest.assertion import rewrite
def warn_about_missing_assertion(mode):
try:
assert False
except AssertionErro... | hook = session.config._assertstate.hook
if hook is not None:
hook.session = None | identifier_body |
__init__.py | """
support for presenting detailed information in failing assertions.
"""
import py
import sys
import pytest
from _pytest.monkeypatch import monkeypatch
from _pytest.assertion import util
def pytest_addoption(parser):
group = parser.getgroup("debugconfig")
group.addoption('--assert', action="store", dest="ass... | help="""control assertion debugging tools.
'plain' performs no assertion debugging.
'reinterp' reinterprets assert statements after they failed to provide assertion expression information.
'rewrite' (the default) rewrites assert statements in test modules on import
to provide assert expression infor... | default="rewrite", metavar="MODE", | random_line_split |
lxc-patch.py | # Yum plugin to re-patch container rootfs after a yum update is done
#
# Copyright (C) 2012 Oracle
#
# Authors:
# Dwight Engen <dwight.engen@oracle.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fou... |
if patch_required:
conduit.info(2, "lxc-patch: patching container...")
os.spawnlp(os.P_WAIT, "lxc-patch", "lxc-patch", "--patch", "/")
| if fnmatch(pkg, tsmem.po.name):
patch_required = True | conditional_block |
lxc-patch.py | # Yum plugin to re-patch container rootfs after a yum update is done
#
# Copyright (C) 2012 Oracle
#
# Authors:
# Dwight Engen <dwight.engen@oracle.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fou... |
tmp = confpkgs.split(",")
for confpkg in tmp:
pkgs.append(confpkg.strip())
conduit.info(2, "lxc-patch: checking if updated pkgs need patching...")
ts = conduit.getTsInfo()
for tsmem in ts.getMembers():
for pkg in pkgs:
if fnmatch(pkg, tsmem.po.name):
pat... | if not confpkgs:
return | random_line_split |
lxc-patch.py | # Yum plugin to re-patch container rootfs after a yum update is done
#
# Copyright (C) 2012 Oracle
#
# Authors:
# Dwight Engen <dwight.engen@oracle.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fou... | pkgs = []
patch_required = False
# If we aren't root, we can't have updated anything
if os.geteuid():
return
# See what packages have files that were patched
confpkgs = conduit.confString('main', 'packages')
if not confpkgs:
return
tmp = confpkgs.split(",")
for confpkg... | identifier_body | |
lxc-patch.py | # Yum plugin to re-patch container rootfs after a yum update is done
#
# Copyright (C) 2012 Oracle
#
# Authors:
# Dwight Engen <dwight.engen@oracle.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fou... | (conduit):
pkgs = []
patch_required = False
# If we aren't root, we can't have updated anything
if os.geteuid():
return
# See what packages have files that were patched
confpkgs = conduit.confString('main', 'packages')
if not confpkgs:
return
tmp = confpkgs.split(",")
... | posttrans_hook | identifier_name |
xls.py | # Rekall Memory Forensics
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Authors:
# Michael Cohen <scudette@google.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 ... |
def RenderHeader(self, worksheet, column):
cell = worksheet.cell(
row=worksheet.current_row, column=worksheet.current_column)
cell.value = column.name
cell.style = HEADER_STYLE
# Advance the pointer by 1 cell.
worksheet.current_column += 1
def RenderCell(... | return self.ForTarget(item, "TextRenderer")(
session=self.session, renderer=self.renderer.delegate_text_renderer) | identifier_body |
xls.py | # Rekall Memory Forensics
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Authors:
# Michael Cohen <scudette@google.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 ... | from openpyxl.styles import fills
from rekall import utils
from rekall.ui import renderer
from rekall.ui import text
# pylint: disable=unexpected-keyword-arg,no-value-for-parameter
# pylint: disable=redefined-outer-name
HEADER_STYLE = styles.Style(font=styles.Font(bold=True))
SECTION_STYLE = styles.Style(
fill=s... |
from openpyxl import styles
from openpyxl.styles import colors | random_line_split |
xls.py | # Rekall Memory Forensics
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Authors:
# Michael Cohen <scudette@google.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 ... | (text.TextColumn):
def __init__(self, type=None, table=None, renderer=None, session=None,
**options):
super(XLSColumn, self).__init__(table=table, renderer=renderer,
session=session, **options)
if type:
self.object_renderer = sel... | XLSColumn | identifier_name |
xls.py | # Rekall Memory Forensics
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Authors:
# Michael Cohen <scudette@google.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 ... |
def table_header(self, *args, **options):
super(XLSRenderer, self).table_header(*args, **options)
self.table.render_header()
# Following here are object specific renderers.
class XLSEProcessRenderer(XLSObjectRenderer):
"""Expands an EPROCESS into three columns (address, name and PID)."""
... | worksheet.current_row += 1
worksheet.current_column = 1 | conditional_block |
utils.py |
def copy_files(src, target_node, parent=None, name=None):
| """Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node to copy files to
:param Folder parent: The parent of to attach the clone of src to, if applicable
"""
assert not parent or not parent.is_file, 'Parent must be a folder'... | identifier_body | |
utils.py | def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node to copy files to
:param Folder parent: The parent of to attach the clone of src to, if applicable
"""
asse... | for child in src.children:
copy_files(child, target_node, parent=cloned)
return cloned | record.metadata = src.records.get(schema__name=record.schema.name).metadata
record.save()
if not src.is_file: | random_line_split |
utils.py |
def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node to copy files to
:param Folder parent: The parent of to attach the clone of src to, if applicable
"""
ass... |
# copy over file metadata records
if cloned.provider == 'osfstorage':
for record in cloned.records.all():
record.metadata = src.records.get(schema__name=record.schema.name).metadata
record.save()
if not src.is_file:
for child in src.children:
... | cloned.versions.add(*src.versions.all()) | conditional_block |
utils.py |
def | (src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node to copy files to
:param Folder parent: The parent of to attach the clone of src to, if applicable
"""
assert not parent ... | copy_files | identifier_name |
DateRangePickerDay.test.tsx | import * as React from 'react';
import { describeConformanceV5 } from 'test/utils';
import DateRangePickerDay, {
dateRangePickerDayClasses as classes,
} from '@material-ui/lab/DateRangePickerDay';
import { adapterToUse, wrapPickerMount, createPickerRender } from '../internal/pickers/test-utils';
describe('<DateRange... | // TODO: Fix DateRangePickerDays is not spreading props on root
'themeDefaultProps',
'themeVariants',
],
}),
);
}); | 'componentsProp',
'reactTestRenderer',
'propsSpread',
'refForwarding', | random_line_split |
rpc_misc.py | #!/usr/bin/env python3
# Copyright (c) 2019-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test RPC misc output."""
import xml.etree.ElementTree as ET
from test_framework.test_framework import ... | self.log.info("test echoipc (testing spawned process in multiprocess build)")
assert_equal(node.echoipc("hello"), "hello")
self.log.info("test getindexinfo")
# Without any indices running the RPC returns an empty object
assert_equal(node.getindexinfo(), {})
# Restart th... | logging_help = self.nodes[0].help('logging')
assert f"valid logging categories are: {categories}" in logging_help
| random_line_split |
rpc_misc.py | #!/usr/bin/env python3
# Copyright (c) 2019-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test RPC misc output."""
import xml.etree.ElementTree as ET
from test_framework.test_framework import ... |
if __name__ == '__main__':
RpcMiscTest().main()
| node = self.nodes[0]
self.log.info("test CHECK_NONFATAL")
assert_raises_rpc_error(
-1,
'Internal bug detected: \'request.params[9].get_str() != "trigger_internal_bug"\'',
lambda: node.echo(arg9='trigger_internal_bug'),
)
self.log.info("test getmemory... | identifier_body |
rpc_misc.py | #!/usr/bin/env python3
# Copyright (c) 2019-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test RPC misc output."""
import xml.etree.ElementTree as ET
from test_framework.test_framework import ... | (SyscoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.supports_cli = False
def run_test(self):
node = self.nodes[0]
self.log.info("test CHECK_NONFATAL")
assert_raises_rpc_error(
-1,
'Internal bug detected: \'request.params[9]... | RpcMiscTest | identifier_name |
rpc_misc.py | #!/usr/bin/env python3
# Copyright (c) 2019-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test RPC misc output."""
import xml.etree.ElementTree as ET
from test_framework.test_framework import ... |
# Specifying an unknown index name returns an empty result
assert_equal(node.getindexinfo("foo"), {})
if __name__ == '__main__':
RpcMiscTest().main()
| assert_equal(node.getindexinfo(i), {i: values}) | conditional_block |
category-metadata.component.ts | import {MenuItem} from 'primeng/api';
import {ISubscription} from 'rxjs/Subscription';
import {SuggestionsProviderData} from '@kaltura-ng/kaltura-primeng-ui';
import {Subject} from 'rxjs';
import {Component, ElementRef, Inject, OnInit, QueryList, ViewChild, ViewChildren} from '@angular/core';
import {JumpToSection} fro... | (public _widgetService: CategoryMetadataWidget,
private _pageScrollService: PageScrollService,
@Inject(DOCUMENT) private document: any) {
}
ngOnInit() {
this._widgetService.attachForm();
}
_searchTags(event): void {
this._tagsProvider.next({ suggestions: [], isLoading: true });
if (this... | constructor | identifier_name |
category-metadata.component.ts | import {MenuItem} from 'primeng/api';
import {ISubscription} from 'rxjs/Subscription';
import {SuggestionsProviderData} from '@kaltura-ng/kaltura-primeng-ui';
import {Subject} from 'rxjs';
import {Component, ElementRef, Inject, OnInit, QueryList, ViewChild, ViewChildren} from '@angular/core';
import {JumpToSection} fro... |
this._searchTagsSubscription = this._widgetService.searchTags(event.query).subscribe(data => {
const suggestions = [];
const categoryTags = this._widgetService.metadataForm.value.tags || [];
(data || []).forEach(suggestedTag => {
const isSelectable = !categoryTags.find(tag => {
... | {
// abort previous request
this._searchTagsSubscription.unsubscribe();
this._searchTagsSubscription = null;
} | conditional_block |
category-metadata.component.ts | import {MenuItem} from 'primeng/api';
import {ISubscription} from 'rxjs/Subscription';
import {SuggestionsProviderData} from '@kaltura-ng/kaltura-primeng-ui';
import {Subject} from 'rxjs';
import {Component, ElementRef, Inject, OnInit, QueryList, ViewChild, ViewChildren} from '@angular/core';
import {JumpToSection} fro... |
}
| {
let pageScrollInstance: PageScrollInstance = PageScrollInstance.newInstance({
document: this.document,
scrollTarget: element,
pageScrollOffset: 105
});
this._pageScrollService.start(pageScrollInstance);
} | identifier_body |
category-metadata.component.ts | import {MenuItem} from 'primeng/api';
import {ISubscription} from 'rxjs/Subscription';
import {SuggestionsProviderData} from '@kaltura-ng/kaltura-primeng-ui';
import {Subject} from 'rxjs';
import {Component, ElementRef, Inject, OnInit, QueryList, ViewChild, ViewChildren} from '@angular/core';
import {JumpToSection} fro... | private _popupStateChangeSubscribe: ISubscription;
public _jumpToMenu: MenuItem[] = [];
@ViewChildren(JumpToSection) private _jumpToSectionQuery: QueryList<JumpToSection> = null;
@ViewChild('metadataContainer', { static: true })
public _container: ElementRef;
constructor(public _widgetService: CategoryMe... |
public _tagsProvider = new Subject<SuggestionsProviderData>();
private _searchTagsSubscription: ISubscription; | random_line_split |
sprites.rs |
use sdl2::rect::Rect;
use sdl2::video::Window;
use sdl2::render::{Texture, Canvas};
pub struct Sprite<'a> {
rect: Rect,
pub size: Rect,
texture: &'a Texture,
}
impl<'a> Sprite<'a> {
pub fn | (&self, x: i32, y: i32, canvas: &mut Canvas<Window>) {
let pos_rect = Rect::new(x, y, self.size.width(), self.size.height());
match canvas.copy(&self.texture, Some(self.rect), Some(pos_rect)) {
Err(e) => println!("canvas copy error: {}", e),
_ => {}
}
}
}
pub struct ... | draw | identifier_name |
sprites.rs |
use sdl2::rect::Rect;
use sdl2::video::Window;
use sdl2::render::{Texture, Canvas};
pub struct Sprite<'a> {
rect: Rect,
pub size: Rect,
texture: &'a Texture,
}
impl<'a> Sprite<'a> {
pub fn draw(&self, x: i32, y: i32, canvas: &mut Canvas<Window>) {
let pos_rect = Rect::new(x, y, self.size.widt... |
}
}
}
pub struct SpriteSheet {
pub sprite_width: u32,
pub sprite_height: u32,
padding: u32,
pub texture: Texture,
}
impl SpriteSheet {
pub fn new(texture: Texture, sprite_width: u32, sprite_height: u32, padding: u32) -> Self {
SpriteSheet {
sprite_width,
... | {} | conditional_block |
sprites.rs | use sdl2::rect::Rect;
use sdl2::video::Window;
use sdl2::render::{Texture, Canvas};
pub struct Sprite<'a> {
rect: Rect,
pub size: Rect,
texture: &'a Texture,
}
impl<'a> Sprite<'a> {
pub fn draw(&self, x: i32, y: i32, canvas: &mut Canvas<Window>) {
let pos_rect = Rect::new(x, y, self.size.width... | }
// Creates a sprite object
pub fn get_sprite(&self, index: usize) -> Sprite {
let texture_query = self.texture.query();
let sheet_width = texture_query.width;
let columns = sheet_width / (self.sprite_width + self.padding);
let sheet_x = index as u32 % columns;
le... | sprite_height,
padding,
texture: texture,
} | random_line_split |
sprites.rs |
use sdl2::rect::Rect;
use sdl2::video::Window;
use sdl2::render::{Texture, Canvas};
pub struct Sprite<'a> {
rect: Rect,
pub size: Rect,
texture: &'a Texture,
}
impl<'a> Sprite<'a> {
pub fn draw(&self, x: i32, y: i32, canvas: &mut Canvas<Window>) |
}
pub struct SpriteSheet {
pub sprite_width: u32,
pub sprite_height: u32,
padding: u32,
pub texture: Texture,
}
impl SpriteSheet {
pub fn new(texture: Texture, sprite_width: u32, sprite_height: u32, padding: u32) -> Self {
SpriteSheet {
sprite_width,
sprite_height,... | {
let pos_rect = Rect::new(x, y, self.size.width(), self.size.height());
match canvas.copy(&self.texture, Some(self.rect), Some(pos_rect)) {
Err(e) => println!("canvas copy error: {}", e),
_ => {}
}
} | identifier_body |
motion.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/. */
//! Generic types for CSS Motion Path.
use crate::values::specified::SVGPathData;
/// The <size> in ray() funct... | {
ClosestSide,
ClosestCorner,
FarthestSide,
FarthestCorner,
Sides,
}
/// The `ray()` function, `ray( [ <angle> && <size> && contain? ] )`
///
/// https://drafts.fxtf.org/motion-1/#valdef-offsetpath-ray
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
P... | RaySize | identifier_name |
motion.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/. */
//! Generic types for CSS Motion Path.
use crate::values::specified::SVGPathData;
/// The <size> in ray() funct... | ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C)]
pub struct RayFunction<Angle> {
/// The bearing angle with `0deg` pointing up and positive angles
/// representing clockwise rotation.
pub angle: Angle,
/// Decide the path length used when `offset-distan... | MallocSizeOf,
PartialEq,
SpecifiedValueInfo, | random_line_split |
config-store.es5.js | /**
@license
* @pnp/config-store v1.1.3 - pnp - provides a way to manage configuration within your application
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2018 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https:github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issu... | */
CachingConfigurationProvider.prototype.getConfiguration = function () {
var _this = this;
// Cache not available, pass control to the wrapped provider
if ((!this.store) || (!this.store.enabled)) {
return this.wrappedProvider.getConfiguration();
}
re... | * Loads the configuration values either from the cache or from the wrapped provider
*
* @return {Promise<TypedHash<string>>} Promise of loaded configuration values
| random_line_split |
config-store.es5.js | /**
@license
* @pnp/config-store v1.1.3 - pnp - provides a way to manage configuration within your application
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2018 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https:github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issu... | (web, listTitle, keyFieldName, valueFieldName) {
if (listTitle === void 0) { listTitle = "config"; }
if (keyFieldName === void 0) { keyFieldName = "Title"; }
if (valueFieldName === void 0) { valueFieldName = "Value"; }
this.web = web;
this.listTitle = listTitle;
thi... | SPListConfigurationProvider | identifier_name |
config-store.es5.js | /**
@license
* @pnp/config-store v1.1.3 - pnp - provides a way to manage configuration within your application
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2018 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https:github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issu... |
return NoCacheAvailableException;
}(Error));
/**
* A caching provider which can wrap other non-caching providers
*
*/
var CachingConfigurationProvider = /** @class */ (function () {
/**
* Creates a new caching configuration provider
* @constructor
* @param {IConfigurationProvider} ... | {
if (msg === void 0) { msg = "Cannot create a caching configuration provider since cache is not available."; }
var _this = _super.call(this, msg) || this;
_this.name = "NoCacheAvailableException";
Logger.log({ data: {}, level: 3 /* Error */, message: "[" + _this.name + "]::" + _this... | identifier_body |
config-store.es5.js | /**
@license
* @pnp/config-store v1.1.3 - pnp - provides a way to manage configuration within your application
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2018 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https:github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issu... |
return JSON.parse(o);
};
return Settings;
}());
var NoCacheAvailableException = /** @class */ (function (_super) {
__extends(NoCacheAvailableException, _super);
function NoCacheAvailableException(msg) {
if (msg === void 0) { msg = "Cannot create a caching configuration provider ... | {
return o;
} | conditional_block |
message-generator.js | 'use strict';
const async = require('async');
const _ = require('underscore');
const config = require('../config.json').MessageGenerator;
let mixedConfig = _.defaults(config, {
sendInterval: 500,
deliveryTimeoutTime: 2000,
sendNextMessageOnDelivery: false
});
module.exports = class MessageGenerator {
... | }
return nodeList[this.currentNode];
}
startSendMessages(callback) {
this.scope.publisher.get('currentCounter', (error, counter) => {
if(error) {
this.cnt = 0
}
if(!counter) {
this.cnt = 0;
}
... | this.currentNode = 0;
}
if(nodeList[this.currentNode] === scope.nodeName) {
return this.getNextNode(); | random_line_split |
message-generator.js | 'use strict';
const async = require('async');
const _ = require('underscore');
const config = require('../config.json').MessageGenerator;
let mixedConfig = _.defaults(config, {
sendInterval: 500,
deliveryTimeoutTime: 2000,
sendNextMessageOnDelivery: false
});
module.exports = class MessageGenerator {
... |
}
| {
this.scope.publisher.get('currentCounter', (error, counter) => {
if(error) {
this.cnt = 0
}
if(!counter) {
this.cnt = 0;
}
this.messageEmitter.subscribe([`${this.scope.nodeName}:recieved`], () => {
if... | identifier_body |
message-generator.js | 'use strict';
const async = require('async');
const _ = require('underscore');
const config = require('../config.json').MessageGenerator;
let mixedConfig = _.defaults(config, {
sendInterval: 500,
deliveryTimeoutTime: 2000,
sendNextMessageOnDelivery: false
});
module.exports = class MessageGenerator {
... | (callback) {
this.scope.publisher.get('currentCounter', (error, counter) => {
if(error) {
this.cnt = 0
}
if(!counter) {
this.cnt = 0;
}
this.messageEmitter.subscribe([`${this.scope.nodeName}:recieved`], () => {
... | startSendMessages | identifier_name |
message-generator.js | 'use strict';
const async = require('async');
const _ = require('underscore');
const config = require('../config.json').MessageGenerator;
let mixedConfig = _.defaults(config, {
sendInterval: 500,
deliveryTimeoutTime: 2000,
sendNextMessageOnDelivery: false
});
module.exports = class MessageGenerator {
... |
if(!counter) {
this.cnt = 0;
}
this.messageEmitter.subscribe([`${this.scope.nodeName}:recieved`], () => {
if(this.sendNextMessageOnDelivery) {
async.forever(this.sendMessage.bind(this));
} else {
... | {
this.cnt = 0
} | conditional_block |
read_exact.rs | use crate::io::AsyncRead;
use futures_core::future::Future;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use std::io;
use std::mem;
use std::pin::Pin;
/// Future for the [`read_exact`](super::AsyncReadExt::read_exact) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or... | return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into()));
}
}
Poll::Ready(Ok(()))
}
} | {
let (_, rest) = mem::replace(&mut this.buf, &mut []).split_at_mut(n);
this.buf = rest;
}
if n == 0 { | random_line_split |
read_exact.rs | use crate::io::AsyncRead;
use futures_core::future::Future;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use std::io;
use std::mem;
use std::pin::Pin;
/// Future for the [`read_exact`](super::AsyncReadExt::read_exact) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or... |
}
Poll::Ready(Ok(()))
}
}
| {
return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into()));
} | conditional_block |
read_exact.rs | use crate::io::AsyncRead;
use futures_core::future::Future;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use std::io;
use std::mem;
use std::pin::Pin;
/// Future for the [`read_exact`](super::AsyncReadExt::read_exact) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or... | (mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
while !this.buf.is_empty() {
let n = ready!(Pin::new(&mut this.reader).poll_read(cx, this.buf))?;
{
let (_, rest) = mem::replace(&mut this.buf, &mut []).split_at_mut(n)... | poll | identifier_name |
read_exact.rs | use crate::io::AsyncRead;
use futures_core::future::Future;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use std::io;
use std::mem;
use std::pin::Pin;
/// Future for the [`read_exact`](super::AsyncReadExt::read_exact) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or... |
}
| {
let this = &mut *self;
while !this.buf.is_empty() {
let n = ready!(Pin::new(&mut this.reader).poll_read(cx, this.buf))?;
{
let (_, rest) = mem::replace(&mut this.buf, &mut []).split_at_mut(n);
this.buf = rest;
}
if n == 0 ... | identifier_body |
case207.py | #
# Copyright (C) 2004 SIPfoundry Inc.
# Licensed by SIPfoundry under the GPL license.
#
# Copyright (C) 2004 SIP Forum
# Licensed to SIPfoundry under a Contributor Agreement.
#
#
# This file is part of SIP Forum User Agent Basic Test Suite which
# belongs to the SIP Forum Test Framework.
#
# SIP Forum User Agent Basic... | (TestCase):
def config(self):
self.name = "Case 207"
self.description = "Content length larger than message"
self.isClient = True
self.transport = "UDP"
def run(self):
self.neh = NEH.NetworkEventHandler(self.transport)
inv = self.createRequest("INVITE")
cl = inv.getParsedHeaderValue("Content-Length"... | case207 | identifier_name |
case207.py | #
# Copyright (C) 2004 SIPfoundry Inc.
# Licensed by SIPfoundry under the GPL license.
#
# Copyright (C) 2004 SIP Forum
# Licensed to SIPfoundry under a Contributor Agreement.
#
#
# This file is part of SIP Forum User Agent Basic Test Suite which
# belongs to the SIP Forum Test Framework.
#
# SIP Forum User Agent Basic... |
else:
self.addResult(TestCase.TC_FAILED, "INVITE accepted, not rejected with 400")
can = self.createRequest("CANCEL", trans=message.transaction)
message.transaction.canceled = True
self.writeMessageToNetwork(self.neh, can)
canrepl = self.readReplyFromNetwork(self.neh)
if canrepl is None:
self.a... | self.addResult(TestCase.TC_FAILED, "INVITE rejected, but not with 400") | conditional_block |
case207.py | #
# Copyright (C) 2004 SIPfoundry Inc.
# Licensed by SIPfoundry under the GPL license.
#
# Copyright (C) 2004 SIP Forum
# Licensed to SIPfoundry under a Contributor Agreement.
#
#
# This file is part of SIP Forum User Agent Basic Test Suite which
# belongs to the SIP Forum Test Framework.
#
# SIP Forum User Agent Basic... |
def onDefaultCode(self, message):
if message.code > self.code:
self.code = message.code
if message.code >= 200:
if message.getParsedHeaderValue("CSeq").method == "INVITE":
Log.logDebug("case207: sending ACK for >= 200 reply", 3)
ack = self.createRequest("ACK", trans=message.transaction)
self.wr... | self.neh = NEH.NetworkEventHandler(self.transport)
inv = self.createRequest("INVITE")
cl = inv.getParsedHeaderValue("Content-Length")
cl.length = 9999
inv.setHeaderValue("Content-Length", cl.create())
self.writeMessageToNetwork(self.neh, inv)
self.code = 0
while (self.code <= 200):
repl = self.readRe... | identifier_body |
case207.py | #
# Copyright (C) 2004 SIP Forum
# Licensed to SIPfoundry under a Contributor Agreement.
#
#
# This file is part of SIP Forum User Agent Basic Test Suite which
# belongs to the SIP Forum Test Framework.
#
# SIP Forum User Agent Basic Test Suite is free software; you can
# redistribute it and/or modify it under the ter... | #
# Copyright (C) 2004 SIPfoundry Inc.
# Licensed by SIPfoundry under the GPL license. | random_line_split | |
TeamEntity.test.ts | /*
* Wire
* Copyright (C) 2019 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This progr... | * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
... | random_line_split | |
crawler.py | #!/usr/bin/env python
#encoding:utf-8
import os
import sys
import requests
import MySQLdb
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
if len(sys.argv) != 4:
print 'Invalid parameters!'
exit(1) | start_point = (int(sys.argv[2]), int(sys.argv[3]))
immediate_download = False
base_url = 'http://www.3che.com'
session = requests.Session()
username = ''
password = ''
record = {
'category': '',
'detail_category': '',
'post_url': '',
'filename': '',
'url': ''
}
sql_cnt = 0
connection = None
cur... |
print '=' * 60
print 'start:', sys.argv
aim_category_id = int(sys.argv[1]) | random_line_split |
crawler.py | #!/usr/bin/env python
#encoding:utf-8
import os
import sys
import requests
import MySQLdb
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
if len(sys.argv) != 4:
print 'Invalid parameters!'
exit(1)
print '=' * 60
print 'start:', sys.argv
aim_category_id = int(sys.argv[1])
start_point = (int(sys.ar... | n()
# Extract categories from home page.
soup = get_soup(base_url, SoupStrainer(id='nv'))
category_lis = soup.find('div', id='nv').ul.find_all('li')
categories = map(lambda x: (x.a.text, x.a['href']), category_lis)
categories = filter(lambda x: x[1] != '/', categories)
crawl_category(categorie... | conditional_block | |
crawler.py | #!/usr/bin/env python
#encoding:utf-8
import os
import sys
import requests
import MySQLdb
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
if len(sys.argv) != 4:
print 'Invalid parameters!'
exit(1)
print '=' * 60
print 'start:', sys.argv
aim_category_id = int(sys.argv[1])
start_point = (int(sys.ar... |
def crawl_file(url, filename):
try:
soup = get_soup(url, SoupStrainer(id='attachpayform'))
attach_form = soup.find('form', id='attachpayform')
link = attach_form.table.find_all('a')[-1]
except Exception as e:
print 'Error! file url:', url
else:
download_file(link['h... | print 'Downloading:', filename, '=>', url
record['url'] = url
record['filename'] = filename
if immediate_download:
with open(filename, 'w') as fp:
res = requests.get(url)
fp.write(res.content)
fp.close()
else:
record_to_mysql() | identifier_body |
crawler.py | #!/usr/bin/env python
#encoding:utf-8
import os
import sys
import requests
import MySQLdb
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
if len(sys.argv) != 4:
print 'Invalid parameters!'
exit(1)
print '=' * 60
print 'start:', sys.argv
aim_category_id = int(sys.argv[1])
start_point = (int(sys.ar... | (url, parse_only=None):
text = session.get(url).text
return BeautifulSoup(text, 'lxml', parse_only=parse_only)
def download_file(url, filename):
print 'Downloading:', filename, '=>', url
record['url'] = url
record['filename'] = filename
if immediate_download:
with open(filename, 'w') as... | get_soup | identifier_name |
extra_tags.py | import time
import os
import posixpath
import datetime
import math
import re
import logging
from django import template
from django.utils.encoding import smart_unicode
from django.utils.safestring import mark_safe
from forum.models import Question, Answer, QuestionRevision, AnswerRevision, NodeRevision
from django.util... |
@register.tag(name='var')
def do_var(parser, token):
tokens = token.split_contents()[1:]
if not len(tokens) or not re.match('^\w+$', tokens[0]):
raise template.TemplateSyntaxError("Expected variable name")
if len(tokens) == 1:
nodelist = parser.parse(('endvar',))
parser.delete_f... | source = self.block.render(context)
context[self.name] = source.strip()
return '' | identifier_body |
extra_tags.py | import time
import os
import posixpath
import datetime
import math
import re
import logging
from django import template
from django.utils.encoding import smart_unicode
from django.utils.safestring import mark_safe
from forum.models import Question, Answer, QuestionRevision, AnswerRevision, NodeRevision
from django.util... | (self, name, block):
self.name = name
self.block = block
def render(self, context):
source = self.block.render(context)
context[self.name] = source.strip()
return ''
@register.tag(name='var')
def do_var(parser, token):
tokens = token.split_contents()[1:]
if not le... | __init__ | identifier_name |
extra_tags.py | import time
import os
import posixpath
import datetime
import math
import re
import logging
from django import template
from django.utils.encoding import smart_unicode
from django.utils.safestring import mark_safe
from forum.models import Question, Answer, QuestionRevision, AnswerRevision, NodeRevision
from django.util... |
self.content = sep
def render(self, context):
return self.content
class BlockMediaUrlNode(template.Node):
def __init__(self, nodelist):
self.items = nodelist
def render(self, context):
prefix = settings.APP_URL + 'm/'
url = ''
if self.items:
ur... | raise template.TemplateSyntaxError('separator in joinitems tag must be quoted') | conditional_block |
extra_tags.py | import time
import os
import posixpath
import datetime
import math
import re
import logging
from django import template
from django.utils.encoding import smart_unicode
from django.utils.safestring import mark_safe
from forum.models import Question, Answer, QuestionRevision, AnswerRevision, NodeRevision
from django.util... | raise template.TemplateSyntaxError("Expected variable name")
if len(tokens) == 1:
nodelist = parser.parse(('endvar',))
parser.delete_first_token()
return BlockVarNode(tokens[0], nodelist)
elif len(tokens) == 3:
return SimpleVarNode(tokens[0], tokens[2])
raise templa... | if not len(tokens) or not re.match('^\w+$', tokens[0]): | random_line_split |
logical_spec.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
*/
import {LogicalFileSystem, LogicalProjectPath} from '../src/logical';
import {AbsoluteFsPath} from '../src/types';
... | (file: string): AbsoluteFsPath {
return AbsoluteFsPath.from(file);
}
| abs | identifier_name |
logical_spec.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
*/
import {LogicalFileSystem, LogicalProjectPath} from '../src/logical';
import {AbsoluteFsPath} from '../src/types';
... |
it('should determine logical paths in a multi-root file system', () => {
const fs = new LogicalFileSystem([abs('/test/foo'), abs('/test/bar')]);
expect(fs.logicalPathOfFile(abs('/test/foo/foo.ts'))).toEqual('/foo' as LogicalProjectPath);
expect(fs.logicalPathOfFile(abs('/test/bar/bar.ts'))).toEqu... | .toEqual('/bar/bar' as LogicalProjectPath);
expect(fs.logicalPathOfFile(abs('/not-test/bar.ts'))).toBeNull();
}); | random_line_split |
logical_spec.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
*/
import {LogicalFileSystem, LogicalProjectPath} from '../src/logical';
import {AbsoluteFsPath} from '../src/types';
... | {
return AbsoluteFsPath.from(file);
} | identifier_body | |
tournament.py | # coding: utf-8
# license: GPLv3
from enemies import *
from hero import *
def annoying_input_int(message =''):
answer = None
while answer == None:
try:
answer = int(input(message))
except ValueError:
print('Вы ввели недопустимые символы')
return answer
def game_tou... | dragon_number = 3
dragon_list = generate_dragon_list(dragon_number)
assert(len(dragon_list) == 3)
print('У Вас на пути', dragon_number, 'драконов!')
game_tournament(hero, dragon_list)
except EOFError:
print('Поток ввода закончился. Извините, принимать ответы более нево... | identifier_body | |
tournament.py | # coding: utf-8
# license: GPLv3
from enemies import *
from hero import *
def annoying_input_int(message =''):
answer = None
while answer == None:
try:
answer = int(input(message))
except ValueError: | print('Вы ввели недопустимые символы')
return answer
def game_tournament(hero, dragon_list):
for dragon in dragon_list:
print('Вышел', dragon._color, 'дракон!')
while dragon.is_alive() and hero.is_alive():
print('Вопрос:', dragon.question())
answer = annoyin... | random_line_split | |
tournament.py | # coding: utf-8
# license: GPLv3
from enemies import *
from hero import *
def annoying_input_int(message =''):
answer = None
while answer == None:
try:
answer = int(input(message))
except ValueError:
print('Вы ввели недопустимые символы')
return answer
def game_tou... | с драконами!')
print('Представьтесь, пожалуйста: ', end = '')
hero = Hero(input())
dragon_number = 3
dragon_list = generate_dragon_list(dragon_number)
assert(len(dragon_list) == 3)
print('У Вас на пути', dragon_number, 'драконов!')
game_tournament(hero, dragon_li... | print('К сожалению, Вы проиграли...')
def start_game():
try:
print('Добро пожаловать в арифметико-ролевую игру | conditional_block |
tournament.py | # coding: utf-8
# license: GPLv3
from enemies import *
from hero import *
def annoying_input_int(message =''):
answer = None
while answer == None:
try:
answer = int(input(message))
except ValueError:
print('Вы ввели недопустимые символы')
return answer
def game_tou... | or dragon in dragon_list:
print('Вышел', dragon._color, 'дракон!')
while dragon.is_alive() and hero.is_alive():
print('Вопрос:', dragon.question())
answer = annoying_input_int('Ответ:')
if dragon.check_answer(answer):
hero.attack(dragon)
... | on_list):
f | identifier_name |
MCEImageBrowserDialog.js | class InsertImageDialog extends ConfirmMessageDialog {
| *
* @type {MessageDialog}
*/
this.parent = null;
this.icon_enabled = false;
this.itemClass = "MCEImagesBean";
}
setImageID(imageID) {
this.imageID = imageID;
}
setParent(dialog) {
this.parent = dialog;
}
setContents(contents... | constructor() {
super();
this.contents = "";
/** | random_line_split |
MCEImageBrowserDialog.js | class InsertImageDialog extends ConfirmMessageDialog {
constructor() {
super();
this.contents = "";
/**
*
* @type {MessageDialog}
*/
this.parent = null;
this.icon_enabled = false;
this.itemClass = "MCEImagesBean";
}
setImageID(i... |
loadImages(imageID) {
this.req.setFunction("find");
this.req.removeParameter("imageID");
if (imageID > 0) {
this.req.setParameter("imageID", imageID);
} else {
this.modal_pane.popup.find(".ImageStorage .Collection").first().empty();
}
this... | {
for (var a = 0; a < result.result_count; a++) {
var image = result.objects[a];
var imageID = image.imageID;
//load the image into the view
this.loadImages(imageID);
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.