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 |
|---|---|---|---|---|
parser2.py | # parser2.py
# parses sentences from the CSV files
# J. Hassler Thurston
# RocHack Hackathon December 7, 2013
# Modified December 11, 2013
import nltk
from random import choice
cfg_file = 'upenn_grammar.cfg'
tbank_productions = []
nonterminals = []
rightside = [] | def get_initial_rules():
global tbank_productions, nonterminals
# from http://stackoverflow.com/questions/7056996/how-do-i-get-a-set-of-grammar-rules-from-penn-treebank-using-python-nltk
tbank_productions = [production for sent in nltk.corpus.treebank.parsed_sents() for production in sent.productions()]
nonterminal... | random_line_split | |
parser2.py | # parser2.py
# parses sentences from the CSV files
# J. Hassler Thurston
# RocHack Hackathon December 7, 2013
# Modified December 11, 2013
import nltk
from random import choice
cfg_file = 'upenn_grammar.cfg'
tbank_productions = []
nonterminals = []
rightside = []
def | ():
global tbank_productions, nonterminals
# from http://stackoverflow.com/questions/7056996/how-do-i-get-a-set-of-grammar-rules-from-penn-treebank-using-python-nltk
tbank_productions = [production for sent in nltk.corpus.treebank.parsed_sents() for production in sent.productions()]
nonterminals = [production.lhs()... | get_initial_rules | identifier_name |
square.ts | import { Component, Output, Input, EventEmitter, OnInit } from '@angular/core';
import { sqStates, sqColor, Coord, Square } from '../knight/coord';
import { Observable } from 'rxjs/Observable';
@Component({
moduleId: module.id.toString(),
selector: 'square',
templateUrl: 'square.component.html', |
export class Square2 implements OnInit {
protected sqInfo: Square;
@Input() sqcolor: sqColor;
@Input() x: number;
@Input() y: number;
@Input() colors: Array<string>;
@Output() instanceSq: EventEmitter<Square> = new EventEmitter<Square>();
@Output() clickedSq: EventEmitter<Square>=new Even... | styleUrls: ['tictac.css']
}) | random_line_split |
square.ts | import { Component, Output, Input, EventEmitter, OnInit } from '@angular/core';
import { sqStates, sqColor, Coord, Square } from '../knight/coord';
import { Observable } from 'rxjs/Observable';
@Component({
moduleId: module.id.toString(),
selector: 'square',
templateUrl: 'square.component.html',
styleU... | (): string {
let val: string = "";
if (this.sqInfo.currState == sqStates.Start)
val = "X";
else if (this.sqInfo.currState == sqStates.End)
val = "O";
return val;
}
getColor(): string{
return this.sqInfo.getColor();
}
set currState(newsta... | getValue | identifier_name |
square.ts | import { Component, Output, Input, EventEmitter, OnInit } from '@angular/core';
import { sqStates, sqColor, Coord, Square } from '../knight/coord';
import { Observable } from 'rxjs/Observable';
@Component({
moduleId: module.id.toString(),
selector: 'square',
templateUrl: 'square.component.html',
styleU... |
getClassfromSq(sq: Square): string {
let classname = "col-md-1 square " + this.getColor();
//console.log(classname);
return classname;
}
}
| { return this.sqInfo.alg_not; } | identifier_body |
cssmediarule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSMediaRuleBinding;
use dom::bindings... | self) -> DOMString {
let guard = self.cssconditionrule.shared_lock().read();
self.mediarule.read_with(&guard).to_css_string(&guard).into()
}
}
impl CSSMediaRuleMethods for CSSMediaRule {
// https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media
fn Media(&self) -> Root<MediaList> {
... | t_css(& | identifier_name |
cssmediarule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSMediaRuleBinding;
use dom::bindings... |
impl CSSMediaRuleMethods for CSSMediaRule {
// https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media
fn Media(&self) -> Root<MediaList> {
self.medialist()
}
}
| let guard = self.cssconditionrule.shared_lock().read();
self.mediarule.read_with(&guard).to_css_string(&guard).into()
}
} | identifier_body |
cssmediarule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
use cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSMediaRuleBinding;
use dom::bindings::codegen::Bindings::CSSMediaRuleBinding::CSSMediaRuleMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods;
use dom::bindings::js::{MutNullableJS, Root};
use dom::bind... | random_line_split | |
ranges_iter.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use super::range::Range;
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum IterStatus {
/// All ranges are consumed.
Drained,
/// Last range is drained or this iteration is a fresh start so that caller should scan
/// on a new range.
... | (&mut self) {
self.in_range = false;
}
}
#[cfg(test)]
mod tests {
use super::super::range::IntervalRange;
use super::*;
use std::sync::atomic;
static RANGE_INDEX: atomic::AtomicU64 = atomic::AtomicU64::new(1);
fn new_range() -> Range {
use byteorder::{BigEndian, WriteBytesExt... | notify_drained | identifier_name |
ranges_iter.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use super::range::Range;
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum IterStatus {
/// All ranges are consumed.
Drained,
/// Last range is drained or this iteration is a fresh start so that caller should scan
/// on a new range.
... | } | random_line_split | |
ranges_iter.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use super::range::Range;
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum IterStatus {
/// All ranges are consumed.
Drained,
/// Last range is drained or this iteration is a fresh start so that caller should scan
/// on a new range.
... |
/// Continues iterating.
#[inline]
pub fn next(&mut self) -> IterStatus {
if self.in_range {
return IterStatus::Continue;
}
match self.iter.next() {
None => IterStatus::Drained,
Some(range) => {
self.in_range = true;
... | {
Self {
in_range: false,
iter: user_key_ranges.into_iter(),
}
} | identifier_body |
ranges_iter.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use super::range::Range;
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum IterStatus {
/// All ranges are consumed.
Drained,
/// Last range is drained or this iteration is a fresh start so that caller should scan
/// on a new range.
... |
match self.iter.next() {
None => IterStatus::Drained,
Some(range) => {
self.in_range = true;
IterStatus::NewRange(range)
}
}
}
/// Notifies that current range is drained.
#[inline]
pub fn notify_drained(&mut self) {
... | {
return IterStatus::Continue;
} | conditional_block |
compare.js | 'use strict';
const path = require('path');
const fs = require('fs');
const glob = require('glob');
const fm = require('front-matter');
const test = require('tape');
const dedent = require('dedent-js');
// Splits a string, normalizing line endings and filtering empty lines
const split =
str => str.replace(/\r\n|\r... | (pattern, options) {
const {
prefix='',
depth: objectPrintDepth=30,
exclude,
errorProps=['message', 'line', 'column'],
transform,
ext: { data: dExt='js', comparator: cExt='json' }={},
} = options;
if ([dExt, cExt].some(ext => typeof ext !== 'string')) {
throw new Error('compare: Inval... | compare | identifier_name |
compare.js | 'use strict';
const path = require('path');
const fs = require('fs');
const glob = require('glob');
const fm = require('front-matter');
const test = require('tape');
const dedent = require('dedent-js');
// Splits a string, normalizing line endings and filtering empty lines
const split =
str => str.replace(/\r\n|\r... | expected,
(hasMultiple ? `#${index} ` : '') + header.description
);
}
});
t.end();
};
}
else {
const message =
`Unknown modifier "${modifiers}" from filename ${dataFile}`;
throw new Error(message);
}
// tap... | {
fn = t => {
comparatorWrapper.forEach((comparator, index) => {
const transformArgs = {
comparator,
data: dataWrapper[index],
dataFile,
comparatorFile,
header,
};
try {
transform.data(transformArgs);
... | conditional_block |
compare.js | 'use strict';
const path = require('path');
const fs = require('fs');
const glob = require('glob');
const fm = require('front-matter');
const test = require('tape');
const dedent = require('dedent-js');
// Splits a string, normalizing line endings and filtering empty lines
const split =
str => str.replace(/\r\n|\r... | .filter(file => regext.test(file));
let stop = false;
files.forEach(file => {
const dir = path.dirname(file);
const ext = path.extname(file);
const basename = path.basename(file, ext);
const [base, ...modifiers] = path.basename(file, ext).split(/\./);
const comparatorFile = `${dir}/${bas... | {
const {
prefix='',
depth: objectPrintDepth=30,
exclude,
errorProps=['message', 'line', 'column'],
transform,
ext: { data: dExt='js', comparator: cExt='json' }={},
} = options;
if ([dExt, cExt].some(ext => typeof ext !== 'string')) {
throw new Error('compare: Invalid extentions');
... | identifier_body |
compare.js | 'use strict';
const path = require('path');
const fs = require('fs');
const glob = require('glob');
const fm = require('front-matter');
const test = require('tape');
const dedent = require('dedent-js');
// Splits a string, normalizing line endings and filtering empty lines
const split =
str => str.replace(/\r\n|\r... | try {
comparatorWrapper.forEach((comparator, index) => {
const transformArgs = {
comparator,
data: dataWrapper[index],
dataFile,
comparatorFile,
header,
};
const actual = transform.data(transformA... | fn = t => {
// Map through the comparators since it declares the standard | random_line_split |
dmd.py | # Copyright (c) 2014 - 2016 townhallpinball.org
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, p... |
def replace(self, previous, current, transition=None):
trans = "using {}".format(transition) if transition else ""
log.debug("{} replaces {} {}".format(current, previous, trans))
if previous in self.stack:
self.stack[self.stack.index(previous)] = current
elif previous i... | self.override = renderer
self.override.render_start()
log.debug("interrupting with {}".format(renderer)) | identifier_body |
dmd.py | # Copyright (c) 2014 - 2016 townhallpinball.org
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, p... | log.debug("{} replaces {} {}".format(current, previous, trans))
if previous in self.stack:
self.stack[self.stack.index(previous)] = current
elif previous in self.queue:
self.queue[self.queue.index(previous)] = current
else:
transition = None
... |
def replace(self, previous, current, transition=None):
trans = "using {}".format(transition) if transition else "" | random_line_split |
dmd.py | # Copyright (c) 2014 - 2016 townhallpinball.org
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, p... | (self):
if self.renderer:
self.renderer.on_render_stop()
if self.previous_renderer:
self.previous_renderer.on_render_stop()
self.renderer = None
self.previous_renderer = None
self.stack[:] = []
self.clear()
self.transition = None
def a... | reset | identifier_name |
dmd.py | # Copyright (c) 2014 - 2016 townhallpinball.org
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, p... |
if self.previous_renderer in self.stack:
self.previous_renderer.render_suspend()
elif self.previous_renderer:
self.previous_renderer.render_stop()
if self.renderer:
self.renderer.render_stop()
self.previous_renderer = self.renderer
if n... | renderer = None | conditional_block |
GeofenceProxy.js | module.exports = {
initialize: function (success, fail, args, env) {
GeofenceComponent.GeofenceTrigger.register();
success && success();
},
addOrUpdate: function (success, fail, args, env) {
args.forEach(function (geo) {
var geoN = new GeofenceComponent.GeoNotification(... | },
removeAll: function (success, fail, args, env) {
GeofenceComponent.GeoNotificationManager.removeAll();
success && success();
}
};
require("cordova/exec/proxy").add("GeofencePlugin", module.exports); | success && success(); | random_line_split |
logging.rs | extern crate cql_ffi;
use std::slice;
use cql_ffi::*;
unsafe fn print_error(future: &mut CassFuture) {
let message = future.error_message();
let message = slice::from_raw_parts(&message.data, message.length as usize);
println!("Error: {:?}", message);
}
unsafe fn | () -> *mut CassCluster {
let cluster = CassCluster::new();
cluster.set_contact_points(str2ref("127.0.0.1,127.0.0.2,127.0.0.3"));
cluster
}
unsafe fn connect_session(session: &mut CassSession, cluster: &mut CassCluster) -> CassError {
let future: CassFuture = &mut session.connect(cluster);
future.wa... | create_cluster | identifier_name |
logging.rs | extern crate cql_ffi;
use std::slice;
use cql_ffi::*;
unsafe fn print_error(future: &mut CassFuture) {
let message = future.error_message();
let message = slice::from_raw_parts(&message.data, message.length as usize);
println!("Error: {:?}", message);
}
unsafe fn create_cluster() -> *mut CassCluster {
... |
close_future = cass_session_close(session);
cass_future_wait(close_future);
cass_future_free(close_future);
cass_cluster_free(cluster);
cass_session_free(session);
/* This *MUST* be the last driver call */
cass_log_cleanup();
fclose(log_file);
return 0;
}
| {
cass_cluster_free(cluster);
cass_session_free(session);
return -1;
} | conditional_block |
logging.rs | extern crate cql_ffi;
use std::slice;
use cql_ffi::*;
unsafe fn print_error(future: &mut CassFuture) {
let message = future.error_message();
let message = slice::from_raw_parts(&message.data, message.length as usize);
println!("Error: {:?}", message);
}
unsafe fn create_cluster() -> *mut CassCluster {
... |
//~ fn on_log(message:&CassLogMessage, data:data) {
//~ println!("{}",
//~ message.time_ms / 1000,
//~ message->time_ms % 1000,
//~ cass_log_level_string(message.severity),
//~ message.file, message.line, message.function,
//~ message.message);
//~ }
fn main() {
//~ C... | {
let future: CassFuture = &mut session.connect(cluster);
future.wait();
future
} | identifier_body |
logging.rs | extern crate cql_ffi;
use std::slice;
use cql_ffi::*;
unsafe fn print_error(future: &mut CassFuture) {
let message = future.error_message();
let message = slice::from_raw_parts(&message.data, message.length as usize);
println!("Error: {:?}", message);
}
unsafe fn create_cluster() -> *mut CassCluster {
... | if (connect_session(session, cluster) != CASS_OK) {
cass_cluster_free(cluster);
cass_session_free(session);
return -1;
}
close_future = cass_session_close(session);
cass_future_wait(close_future);
cass_future_free(close_future);
cass_cluster_free(cluster);
cass_sessio... | /* Log configuration *MUST* be done before any other driver call */
cass_log_set_level(CASS_LOG_INFO);
cass_log_set_callback(on_log, log_file);
cluster = create_cluster();
session = cass_session_new(); | random_line_split |
test_guess.py | from tgbot import plugintest
from plugin_examples.guess import GuessPlugin
class GuessPluginTest(plugintest.PluginTestCase):
def setUp(self):
self.plugin = GuessPlugin()
self.bot = self.fake_bot('', plugins=[self.plugin])
def test_play(self):
self.receive_message('/guess_start')
... |
def test_stop_on_group(self):
chat = {
'id': -1,
'type': 'group',
'title': 'Test'
}
self.receive_message('/guess_start', chat=chat)
self.assertReplied("I'm going to think of a number between 0 and 9 and you have to guess it! What's your guess?")
... | self.receive_message('/guess_start')
self.assertReplied("I'm going to think of a number between 0 and 9 and you have to guess it! What's your guess?")
self.assertIsNotNone(self.plugin.read_data(1))
self.receive_message('/guess_stop')
self.assertReplied('Ok :(')
self.assertIsNone... | identifier_body |
test_guess.py | from tgbot import plugintest
from plugin_examples.guess import GuessPlugin
class GuessPluginTest(plugintest.PluginTestCase):
def setUp(self):
self.plugin = GuessPlugin()
self.bot = self.fake_bot('', plugins=[self.plugin])
def | (self):
self.receive_message('/guess_start')
self.assertReplied("I'm going to think of a number between 0 and 9 and you have to guess it! What's your guess?")
number = self.plugin.read_data(1)
self.assertIsNotNone(number)
self.assertGreaterEqual(number, 0)
self.assertLes... | test_play | identifier_name |
test_guess.py | from tgbot import plugintest
from plugin_examples.guess import GuessPlugin
class GuessPluginTest(plugintest.PluginTestCase):
def setUp(self):
self.plugin = GuessPlugin()
self.bot = self.fake_bot('', plugins=[self.plugin])
def test_play(self):
self.receive_message('/guess_start')
... |
self.receive_message('gief error')
self.assertReplied('Invalid guess!')
self.receive_message('5')
self.assertReplied('Congratz, you nailed it John')
def test_stop(self):
self.receive_message('/guess_start')
self.assertReplied("I'm going to think of a number between... | self.receive_message('6')
self.assertReplied("I'm thinking lower...") | random_line_split |
access_log.py | """Model for an access log."""
import functools
import logging
import numpy as np
from django.conf import settings
from django.db import models
from django.utils import timezone
logger = logging.getLogger(__name__)
class AccessLogMixin(models.Model):
"""Base class which logs access of information."""
# The ... | prev_time = log.timestamp
yield (period.end - prev_time).total_seconds()
# Calculate max, sum, count for time durations.
(m, s, c) = functools.reduce(
lambda r, d: (max(r[0], d), r[1] + d, r[2] + 1),
time_between_logs(time_periods, time_period... | prev_time = period.start
for log in time_period_logs[ix]:
yield (log.timestamp - prev_time).total_seconds() | random_line_split |
access_log.py | """Model for an access log."""
import functools
import logging
import numpy as np
from django.conf import settings
from django.db import models
from django.utils import timezone
logger = logging.getLogger(__name__)
class AccessLogMixin(models.Model):
"""Base class which logs access of information."""
# The ... |
def __init__(self, *args, **kwargs):
super(AccessLogMixin, self).__init__(*args, **kwargs)
if self.timestamp is None:
self.timestamp = timezone.now()
@classmethod
def by_user(cls, user, start_time=None, end_time=None):
"""Gets the time-sorted list of access log for the... | abstract = True
index_together = (('user', 'timestamp'), ) | identifier_body |
access_log.py | """Model for an access log."""
import functools
import logging
import numpy as np
from django.conf import settings
from django.db import models
from django.utils import timezone
logger = logging.getLogger(__name__)
class AccessLogMixin(models.Model):
"""Base class which logs access of information."""
# The ... |
@classmethod
def by_user(cls, user, start_time=None, end_time=None):
"""Gets the time-sorted list of access log for the given user.
Args:
user: The user to get the access log for.
start_time: Optional. Inclusive start time.
end_time: Optional. Exclusive end... | self.timestamp = timezone.now() | conditional_block |
access_log.py | """Model for an access log."""
import functools
import logging
import numpy as np
from django.conf import settings
from django.db import models
from django.utils import timezone
logger = logging.getLogger(__name__)
class AccessLogMixin(models.Model):
"""Base class which logs access of information."""
# The ... | (cls, user, start_time=None, end_time=None):
"""Gets the time-sorted list of access log for the given user.
Args:
user: The user to get the access log for.
start_time: Optional. Inclusive start time.
end_time: Optional. Exclusive end time.
Returns:
... | by_user | identifier_name |
__init__.py | # To install another language:
# - update default_bridges below
# - update languages.cson in seamless/compiler
from ...highlevel.Environment import ContextEnvironment, Environment
from . import r
_default_bridges = {
"r": {
"code": r.bridge_r,
"params": r.default_bridge_parameters,
"envir... |
env.set_py_bridge(lang, b["code"])
params = b.get("params")
if params is not None:
env.set_py_bridge_parameters(lang, params)
if "environment" in b:
e = b["environment"]
bridge_env = Environment()
if "conda" in e:
bridge_en... | env._py_bridges = {} | conditional_block |
__init__.py | # To install another language:
# - update default_bridges below
# - update languages.cson in seamless/compiler
from ...highlevel.Environment import ContextEnvironment, Environment
from . import r
_default_bridges = {
"r": {
"code": r.bridge_r, | "params": r.default_bridge_parameters,
"environment": {
"which": ["R", "Rscript"],
"conda": """
dependencies:
- rpy2
""",
}
}
}
def load_py_bridges(env: ContextEnvironment):
for lang in _default_bridges:
b =... | random_line_split | |
__init__.py | # To install another language:
# - update default_bridges below
# - update languages.cson in seamless/compiler
from ...highlevel.Environment import ContextEnvironment, Environment
from . import r
_default_bridges = {
"r": {
"code": r.bridge_r,
"params": r.default_bridge_parameters,
"envir... | for lang in _default_bridges:
b = _default_bridges[lang]
if env._py_bridges is None:
env._py_bridges = {}
env.set_py_bridge(lang, b["code"])
params = b.get("params")
if params is not None:
env.set_py_bridge_parameters(lang, params)
if "environment"... | identifier_body | |
__init__.py | # To install another language:
# - update default_bridges below
# - update languages.cson in seamless/compiler
from ...highlevel.Environment import ContextEnvironment, Environment
from . import r
_default_bridges = {
"r": {
"code": r.bridge_r,
"params": r.default_bridge_parameters,
"envir... | (env: ContextEnvironment):
for lang in _default_bridges:
b = _default_bridges[lang]
if env._py_bridges is None:
env._py_bridges = {}
env.set_py_bridge(lang, b["code"])
params = b.get("params")
if params is not None:
env.set_py_bridge_parameters(lang, p... | load_py_bridges | identifier_name |
mmdd.py | # -*- coding: utf-8 -*-
from dp_tornado.engine.controller import Controller
class MmddController(Controller):
def get(self):
| assert(self.render_string('tests/view/ui_methods/mmdd.html', {'args': args_ts_cc}) == '01/02')
| self.model.tests.helper_test.datetime.switch_timezone('Asia/Seoul')
ts = 1451671445
ms = ts * 1000
dt = self.helper.datetime.convert(timestamp=ts)
args_dt = {'datetime': dt}
args_ms = {'timestamp': ms, 'ms': True}
args_ts = {'timestamp': ts}
args_dt_cc = {'date... | identifier_body |
mmdd.py | # -*- coding: utf-8 -*-
from dp_tornado.engine.controller import Controller
class MmddController(Controller):
def | (self):
self.model.tests.helper_test.datetime.switch_timezone('Asia/Seoul')
ts = 1451671445
ms = ts * 1000
dt = self.helper.datetime.convert(timestamp=ts)
args_dt = {'datetime': dt}
args_ms = {'timestamp': ms, 'ms': True}
args_ts = {'timestamp': ts}
arg... | get | identifier_name |
mmdd.py | # -*- coding: utf-8 -*-
from dp_tornado.engine.controller import Controller
class MmddController(Controller):
def get(self):
self.model.tests.helper_test.datetime.switch_timezone('Asia/Seoul')
ts = 1451671445
ms = ts * 1000
dt = self.helper.datetime.convert(timestamp=ts)
... | assert(self.render_string('tests/view/ui_methods/mmdd.html', {'args': args_dt}) == '01.02')
assert(self.render_string('tests/view/ui_methods/mmdd.html', {'args': args_ms}) == '01.02')
assert(self.render_string('tests/view/ui_methods/mmdd.html', {'args': args_ts}) == '01.02')
assert(self... | random_line_split | |
addon.rs | // Copyright (c) 2014 by SiegeLord
//
// All rights reserved. Distributed under ZLib. For full terms see the file LICENSE.
#![allow(non_upper_case_globals)]
use std::cell::RefCell;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
use allegro::Core;
use allegro_font_sys::*;
static mut initialized: bool = f... |
else
{
al_init_font_addon();
initialized = true;
spawned_on_this_thread.with(|x| *x.borrow_mut() = true);
Ok(FontAddon{ core_mutex: core.get_core_mutex(), no_send_marker: PhantomData })
}
}
}
pub fn get_version() -> i32
{
unsafe
{
al_get_allegro_font_version() as i32
}
}
pub ... | {
if spawned_on_this_thread.with(|x| *x.borrow())
{
Err("The font addon has already been created in this task.".to_string())
}
else
{
spawned_on_this_thread.with(|x| *x.borrow_mut() = true);
Ok(FontAddon{ core_mutex: core.get_core_mutex(), no_send_marker: PhantomData })
}
} | conditional_block |
addon.rs | // Copyright (c) 2014 by SiegeLord
//
// All rights reserved. Distributed under ZLib. For full terms see the file LICENSE.
#![allow(non_upper_case_globals)]
use std::cell::RefCell;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
use allegro::Core;
use allegro_font_sys::*;
static mut initialized: bool = f... | } | random_line_split | |
addon.rs | // Copyright (c) 2014 by SiegeLord
//
// All rights reserved. Distributed under ZLib. For full terms see the file LICENSE.
#![allow(non_upper_case_globals)]
use std::cell::RefCell;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
use allegro::Core;
use allegro_font_sys::*;
static mut initialized: bool = f... |
{
core_mutex: Arc<Mutex<()>>,
no_send_marker: PhantomData<*mut u8>,
}
impl FontAddon
{
pub fn init(core: &Core) -> Result<FontAddon, String>
{
let mutex = core.get_core_mutex();
let _guard = mutex.lock();
unsafe
{
if initialized
{
if spawned_on_this_thread.with(|x| *x.borrow())
{
Err("T... | FontAddon | identifier_name |
addon.rs | // Copyright (c) 2014 by SiegeLord
//
// All rights reserved. Distributed under ZLib. For full terms see the file LICENSE.
#![allow(non_upper_case_globals)]
use std::cell::RefCell;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
use allegro::Core;
use allegro_font_sys::*;
static mut initialized: bool = f... | initialized = true;
spawned_on_this_thread.with(|x| *x.borrow_mut() = true);
Ok(FontAddon{ core_mutex: core.get_core_mutex(), no_send_marker: PhantomData })
}
}
}
pub fn get_version() -> i32
{
unsafe
{
al_get_allegro_font_version() as i32
}
}
pub fn get_core_mutex(&self) -> Arc<Mutex<(... | {
let mutex = core.get_core_mutex();
let _guard = mutex.lock();
unsafe
{
if initialized
{
if spawned_on_this_thread.with(|x| *x.borrow())
{
Err("The font addon has already been created in this task.".to_string())
}
else
{
spawned_on_this_thread.with(|x| *x.borrow_mut() = true... | identifier_body |
benchmark.ndarray.js | /**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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... | ( len ) {
var x;
var i;
x = new Float32Array( len );
for ( i = 0; i < x.length; i++ ) {
x[ i ] = ( randu()*10.0 ) - 20.0;
}
return benchmark;
function benchmark( b ) {
var v;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = ssumors( x.length, x, 1, 0 );
if ( isnan( v ) ) {
b.fail... | createBenchmark | identifier_name |
benchmark.ndarray.js | /**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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 benchmark;
function benchmark( b ) {
var v;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = ssumors( x.length, x, 1, 0 );
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'bench... | var i;
x = new Float32Array( len );
for ( i = 0; i < x.length; i++ ) {
x[ i ] = ( randu()*10.0 ) - 20.0; | random_line_split |
benchmark.ndarray.js | /**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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... |
}
b.toc();
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= ma... | {
b.fail( 'should not return NaN' );
} | conditional_block |
benchmark.ndarray.js | /**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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... |
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+':ndarray:len='+len, f );
}
}
main();
| {
var v;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = ssumors( x.length, x, 1, 0 );
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
} | identifier_body |
backtrace.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 ... | val == 2
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use sys_common;
macro_rules! t { ($a:expr, $b:expr) => ({
let mut m = Vec::new();
sys_common::backtrace::demangle(&mut m, $a).unwrap();
assert_eq!(String::from_utf8(m).unwrap(), $b);
}) }
#[test]
fn demangle() ... | None => 1,
};
ENABLED.store(val, Ordering::SeqCst); | random_line_split |
backtrace.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 ... |
#[cfg(test)]
mod tests {
use prelude::v1::*;
use sys_common;
macro_rules! t { ($a:expr, $b:expr) => ({
let mut m = Vec::new();
sys_common::backtrace::demangle(&mut m, $a).unwrap();
assert_eq!(String::from_utf8(m).unwrap(), $b);
}) }
#[test]
fn demangle() {
t!("... | {
static ENABLED: atomic::AtomicIsize = atomic::AtomicIsize::new(0);
match ENABLED.load(Ordering::SeqCst) {
1 => return false,
2 => return true,
_ => {}
}
let val = match env::var_os("RUST_BACKTRACE") {
Some(..) => 2,
None => 1,
};
ENABLED.store(val, Orde... | identifier_body |
backtrace.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 ... | () {
t!("_ZN13test$u20$test4foobE", "test test::foob");
t!("_ZN12test$BP$test4foobE", "test*test::foob");
}
#[test]
fn demangle_windows() {
t!("ZN4testE", "test");
t!("ZN13test$u20$test4foobE", "test test::foob");
t!("ZN12test$RF$test4foobE", "test&test::foob");
... | demangle_many_dollars | identifier_name |
feature_cltv.py | 015-2020 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 BIP65 (CHECKLOCKTIMEVERIFY).
Test that the CHECKLOCKTIMEVERIFY soft-fork activates at (regtest) block height
1351.
"""
from test_framewo... | wallet.generate(10)
self.nodes[0].generate(CLTV_HEIGHT - 2 - 10)
self.log.info("Test that invalid-according-to-CLTV transactions can still appear in a block")
# create one invalid tx per CLTV failure reason (5 in total) and collect them
invalid_cltv_txs = []
for i in ra... | random_line_split | |
feature_cltv.py | 015-2020 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 BIP65 (CHECKLOCKTIMEVERIFY).
Test that the CHECKLOCKTIMEVERIFY soft-fork activates at (regtest) block height
1351.
"""
from test_framewo... |
tx.vin[0].scriptSig = CScript(prepend_scriptsig + list(CScript(tx.vin[0].scriptSig)))
tx.rehash()
def cltv_invalidate(tx, failure_reason):
# Modify the signature in vin 0 and nSequence/nLockTime of the tx to fail CLTV
#
# According to BIP65, OP_CHECKLOCKTIMEVERIFY can fail due the following reas... | tx.vin[0].nSequence = nsequence
tx.nLockTime = nlocktime | conditional_block |
feature_cltv.py | 015-2020 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 BIP65 (CHECKLOCKTIMEVERIFY).
Test that the CHECKLOCKTIMEVERIFY soft-fork activates at (regtest) block height
1351.
"""
from test_framewo... | (BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.extra_args = [[
'-whitelist=noban@127.0.0.1',
'-par=1', # Use only one script thread to get the exact reject reason for testing
'-acceptnonstdtxn=1', # cltv_invalidate is nonstandard
... | BIP65Test | identifier_name |
feature_cltv.py | 015-2020 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 BIP65 (CHECKLOCKTIMEVERIFY).
Test that the CHECKLOCKTIMEVERIFY soft-fork activates at (regtest) block height
1351.
"""
from test_framewo... |
class BIP65Test(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.extra_args = [[
'-whitelist=noban@127.0.0.1',
'-par=1', # Use only one script thread to get the exact reject reason for testing
'-acceptnonstdtxn=1', # cltv_invalidate i... | scheme = [[CScriptNum(height), OP_CHECKLOCKTIMEVERIFY, OP_DROP], 0, height]
cltv_modify_tx(tx, prepend_scriptsig=scheme[0], nsequence=scheme[1], nlocktime=scheme[2]) | identifier_body |
day_04.rs | use std::rc::Rc;
type Link<T> = Option<Rc<Node<T>>>;
struct Node<T> {
item: T,
next: Link<T>
}
impl <T> Node<T> {
fn new(item: T, next: Link<T>) -> Link<T> {
Some(Rc::new(Node { item, next }))
}
}
pub struct List<T> {
head: Link<T>
}
impl<T> List<T> {
pub fn head(&self) -> Option<&T... |
}
pub struct ListIter<'l, T> {
node: Option<&'l Node<T>>
}
impl<'l, T> Iterator for ListIter<'l, T> {
type Item = &'l T;
fn next(&mut self) -> Option<Self::Item> {
self.node.take().map(|node| {
self.node = node.next.as_ref().map(|node| &**node);
&node.item
})
... | {
ListIter { node: self.head.as_ref().map(|node| &**node)}
} | identifier_body |
day_04.rs | use std::rc::Rc;
type Link<T> = Option<Rc<Node<T>>>;
struct Node<T> {
item: T,
next: Link<T>
}
impl <T> Node<T> {
fn new(item: T, next: Link<T>) -> Link<T> {
Some(Rc::new(Node { item, next }))
}
}
pub struct List<T> {
head: Link<T>
}
impl<T> List<T> {
pub fn head(&self) -> Option<&T... | }
#[test]
fn append_single_item() {
let mut list = List::default();
list = list.append(1);
assert_eq!(list.head(), Some(&1));
}
#[test]
fn append_many_items() {
let list = List::default().append(1).append(2).append(3);
assert_eq!(list.head(), Some(&3)... | fn empty_list_head() {
let list: List<i32> = List::default();
assert_eq!(list.head(), None); | random_line_split |
day_04.rs | use std::rc::Rc;
type Link<T> = Option<Rc<Node<T>>>;
struct Node<T> {
item: T,
next: Link<T>
}
impl <T> Node<T> {
fn new(item: T, next: Link<T>) -> Link<T> {
Some(Rc::new(Node { item, next }))
}
}
pub struct List<T> {
head: Link<T>
}
impl<T> List<T> {
pub fn head(&self) -> Option<&T... | else {
break;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_list_head() {
let list: List<i32> = List::default();
assert_eq!(list.head(), None);
}
#[test]
fn append_single_item() {
let mut list = List::default(... | {
link = node.next.take();
} | conditional_block |
day_04.rs | use std::rc::Rc;
type Link<T> = Option<Rc<Node<T>>>;
struct Node<T> {
item: T,
next: Link<T>
}
impl <T> Node<T> {
fn new(item: T, next: Link<T>) -> Link<T> {
Some(Rc::new(Node { item, next }))
}
}
pub struct List<T> {
head: Link<T>
}
impl<T> List<T> {
pub fn head(&self) -> Option<&T... | (&mut self) {
let mut link = self.head.take();
while let Some(node) = link {
if let Ok(mut node) = Rc::try_unwrap(node) {
link = node.next.take();
} else {
break;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[t... | drop | identifier_name |
lastfm.py | # This file is part of Headphones.
#
# Headphones 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.
#
# Headphones is distributed i... | kwargs.setdefault("lang", 'fr')
kwargs.setdefault("format", "json")
# Send request
logger.debug("Calling Last.FM method: %s", method)
logger.debug("Last.FM call parameters: %s", kwargs)
data = request.request_json(ENTRY_POINT, timeout=TIMEOUT, params=kwargs, lock=lastfm_lock)
# Parse resp... | """
# Prepare request
kwargs["method"] = method
kwargs.setdefault("api_key", API_KEY) | random_line_split |
lastfm.py | # This file is part of Headphones.
#
# Headphones 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.
#
# Headphones is distributed i... | (tag, limit=50):
myDB = db.DBConnection()
results = myDB.select("SELECT ArtistID from artists")
logger.info("Fetching top artists from Last.FM for tag: %s", tag)
data = request_lastfm("tag.gettopartists", limit=limit, tag=tag)
if data and "topartists" in data:
artistlist = []
artis... | getTagTopArtists | identifier_name |
lastfm.py | # This file is part of Headphones.
#
# Headphones 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.
#
# Headphones is distributed i... |
# Add new artists to tag cloud
logger.debug("Fetched %d artists from Last.FM", len(artistlist))
count = defaultdict(int)
for artist, mbid in artistlist:
count[artist, mbid] += 1
items = count.items()
top_list = sorted(items, key=lambda x: x[1], reverse=True)[:25]
random.shuffle(... | artists = data["similarartists"]["artist"]
for artist in artists:
try:
artist_mbid = artist["mbid"]
artist_name = artist["name"]
except TypeError:
continue
if not any(artist_mbid in x for x in resul... | conditional_block |
lastfm.py | # This file is part of Headphones.
#
# Headphones 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.
#
# Headphones is distributed i... | # Parse response and check for errors.
if not data:
logger.error("Error calling Last.FM method: %s", method)
return
if "error" in data:
logger.error("Last.FM returned an error: %s", data["message"])
return
return data
def getSimilar():
myDB = db.DBConnection()
... | """
Call a Last.FM API method. Automatically sets the method and API key. Method
will return the result if no error occured.
By default, this method will request the JSON format, since it is more
lightweight than XML.
"""
# Prepare request
kwargs["method"] = method
kwargs.setdefault("a... | identifier_body |
admin_list.py | _headers(cl):
"""
Generate the list column headers.
"""
ordering_field_columns = cl.get_ordering_field_columns()
for i, field_name in enumerate(cl.list_display):
text, attr = label_for_field(
field_name, cl.model,
model_admin=cl.model_admin,
return_attr=Tr... | sult_list_tag(p | identifier_name | |
admin_list.py | _SIDE, page_num + 1),
]
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range += [
*range(page_num + 1, page_num + ON_EACH_SIDE + 1), DOT,
... | else:
empty_value_display = getattr(attr, 'empty_value_display', empty_value_display)
if f is None or f.auto_created:
if field_name == 'action_checkbox':
row_classes = ['action-checkbox']
boolean = getattr(attr, 'boolean', False)
... | "
Generate the actual list of data.
"""
def link_in_col(is_first, field_name, cl):
if cl.list_display_links is None:
return False
if is_first and not cl.list_display_links:
return True
return field_name in cl.list_display_links
first = True
pk = cl.l... | identifier_body |
admin_list.py | ON_ENDS - 1):
page_range += [
*range(page_num + 1, page_num + ON_EACH_SIDE + 1), DOT,
*range(paginator.num_pages - ON_ENDS, paginator.num_pages)
]
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
n... | yield ResultList(form, items_for_result(cl, res, form))
else: | random_line_split | |
admin_list.py | ,
"sortable": True,
"sorted": is_sorted,
"ascending": order_type == "asc",
"sort_priority": sort_priority,
"url_primary": cl.get_query_string({ORDER_VAR: '.'.join(o_list_primary)}),
"url_remove": cl.get_query_string({ORDER_VAR: '.'.join(o_list_remo... | ars = getattr(cl.queryset, 'dates')(field_name, 'year')
return {
'show': True,
'back': None,
'choices': [{
'link': link({year_field: str(year.year)}),
'title': str(year.year),
} for year in years]
... | conditional_block | |
issue-20616-2.rs | // We need all these 9 issue-20616-N.rs files
// because we can only catch one parsing error at a time
type Type_1_<'a, T> = &'a T;
//type Type_1<'a T> = &'a T; // error: expected `,` or `>` after lifetime name, found `T`
type Type_2 = Type_1_<'static ()>; //~ error: expected one of `,`, `:`, `=`, or `>`, found ... |
//type Type_5<'a> = Type_1_<'a, (),,>; // error: expected type, found `,`
//type Type_6 = Type_5_<'a,,>; // error: expected type, found `,`
//type Type_7 = Box<(),,>; // error: expected type, found `,`
//type Type_8<'a,,> = &'a (); // error: expected ident, found `,`
//type Type_9<T,,> = Box<T>; // error: expe... |
type Type_5_<'a> = Type_1_<'a, ()>;
| random_line_split |
error_detector.ts | /*
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import {Diagnostic, ts, SyntaxKind} from 'ts-morph';
import {NodeDiagnostic} from '@/src/types';
/** Base class for filtering diagn... | Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
test-1.py | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... | testSuite.addTest( moduleTestSuite )
for i in range( 0, args["repeat"].value ) :
testRunner = unittest.TextTestRunner( verbosity=2 )
testResult = testRunner.run( testSuite )
if not testResult.wasSuccessful() :
return 1
return 0
IECore.registerRunTimeTyped( test )
| import unittest
testSuite = unittest.TestSuite()
if args["testCases"] :
for name in args["testCases"] :
testCase = unittest.defaultTestLoader.loadTestsFromName( name )
testSuite.addTest( testCase )
else :
import GafferTest
import GafferUITest
import GafferSceneTest
import GafferImageTes... | identifier_body |
test-1.py | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... |
return 0
IECore.registerRunTimeTyped( test )
| testRunner = unittest.TextTestRunner( verbosity=2 )
testResult = testRunner.run( testSuite )
if not testResult.wasSuccessful() :
return 1 | conditional_block |
test-1.py | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... | ( self ) :
Gaffer.Application.__init__(
self,
"""
Runs the unit tests for all of Gaffer's python
modules and libraries. These are run automatically
as part of Gaffer's build and review process, but it
is useful to run them manually when developing for
Gaffer or troubleshooting an installation.
... | __init__ | identifier_name |
test-1.py | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... | )
def _run( self, args ) :
import unittest
testSuite = unittest.TestSuite()
if args["testCases"] :
for name in args["testCases"] :
testCase = unittest.defaultTestLoader.loadTestsFromName( name )
testSuite.addTest( testCase )
else :
import GafferTest
import GafferUITest
import Gaffer... | } | random_line_split |
iword_embedding.py | """
Contains basic interface (abstract base class) for word embeddings.
"""
import os
from abc import ABCMeta, abstractmethod
class IWordEmbedding(object):
"""
Abstract base class for word embeddings
"""
__metaclass__ = ABCMeta
def __init__(self, path, vector_length):
self.model = None
... |
def get_embedding_model_path(self):
""" :return: absolute path to folder containing saved word embedding model """
return os.path.join(os.path.dirname(__file__), '../../../models/word_embeddings', self.path)
@staticmethod
def data_file_to_sentences(data_file_path):
"""
Co... | print("Loading pre-trained word embedding from {0}...".format(self.path))
self._build()
self.already_built = True
print("Pre-trained word embedding from {0} loaded!".format(self.path)) | conditional_block |
iword_embedding.py | """
Contains basic interface (abstract base class) for word embeddings.
"""
import os
from abc import ABCMeta, abstractmethod
class IWordEmbedding(object):
"""
Abstract base class for word embeddings
"""
__metaclass__ = ABCMeta
def __init__(self, path, vector_length):
self.model = None
... | (data_file_path):
"""
Converts a processed data file to generator of lists of words
:param data_file_path: path to data file
:return: iterator yielding sentences as lists of words
"""
with open(data_file_path, 'r') as f:
for line in f:
sentence... | data_file_to_sentences | identifier_name |
iword_embedding.py | """
Contains basic interface (abstract base class) for word embeddings.
"""
import os
from abc import ABCMeta, abstractmethod
class IWordEmbedding(object):
"""
Abstract base class for word embeddings
"""
__metaclass__ = ABCMeta
def __init__(self, path, vector_length):
self.model = None
... |
@abstractmethod
def __getitem__(self, word):
raise NotImplementedError
def build(self):
""" Loads word embedding from its file """
if not self.already_built:
print("Loading pre-trained word embedding from {0}...".format(self.path))
self._build()
... | raise NotImplementedError | identifier_body |
iword_embedding.py | """
Contains basic interface (abstract base class) for word embeddings.
"""
import os
from abc import ABCMeta, abstractmethod
class IWordEmbedding(object):
""" | def __init__(self, path, vector_length):
self.model = None
self.path = path
self.vector_length = vector_length
self.already_built = False
@abstractmethod
def _build(self):
raise NotImplementedError
@abstractmethod
def __getitem__(self, word):
raise N... | Abstract base class for word embeddings
"""
__metaclass__ = ABCMeta
| random_line_split |
unicode.rs | #[warn(clippy::invisible_characters)]
fn zero() {
print!("Here >< is a ZWS, and another");
print!("This\u{200B}is\u{200B}fine");
print!("Here >< is a SHY, and another");
print!("This\u{ad}is\u{ad}fine");
print!("Here >< is a WJ, and another");
print!("This\u{2060}is\u{2060}fine");
}
#[war... |
zero();
uni();
canon();
}
| ("Üben!");
print!("\u{DC}ben!"); // this is ok
}
fn main() { | identifier_body |
unicode.rs | #[warn(clippy::invisible_characters)]
fn zero() { | print!("Here >< is a ZWS, and another");
print!("This\u{200B}is\u{200B}fine");
print!("Here >< is a SHY, and another");
print!("This\u{ad}is\u{ad}fine");
print!("Here >< is a WJ, and another");
print!("This\u{2060}is\u{2060}fine");
}
#[warn(clippy::unicode_not_nfc)]
fn canon() {
print... | random_line_split | |
unicode.rs | #[warn(clippy::invisible_characters)]
fn zero() {
print!("Here >< is a ZWS, and another");
print!("This\u{200B}is\u{200B}fine");
print!("Here >< is a SHY, and another");
print!("This\u{ad}is\u{ad}fine");
print!("Here >< is a WJ, and another");
print!("This\u{2060}is\u{2060}fine");
}
#[war... | ();
uni();
canon();
}
| zero | identifier_name |
lc754-reach-a-number.py | # coding=utf-8
import unittest
"""754. Reach a Number
https://leetcode.com/problems/reach-a-number/description/
You are standing at position `0` on an infinite number line. There is a goal
at position `target`.
On each move, you can either go left or right. During the _n_ -th move
(starting from 1), you take _n_ ste... | unittest.main() | conditional_block | |
lc754-reach-a-number.py | # coding=utf-8
import unittest
"""754. Reach a Number
https://leetcode.com/problems/reach-a-number/description/
You are standing at position `0` on an infinite number line. There is a goal
at position `target`.
On each move, you can either go left or right. During the _n_ -th move
(starting from 1), you take _n_ ste... |
**Note:**
* `target` will be a non-zero integer in the range `[-10^9, 10^9]`.
Similar Questions:
"""
class Solution(object):
def reachNumber(self, target):
"""
:type target: int
:rtype: int
"""
def test(self):
pass
if __name__ == "__main__"... | random_line_split | |
lc754-reach-a-number.py | # coding=utf-8
import unittest
"""754. Reach a Number
https://leetcode.com/problems/reach-a-number/description/
You are standing at position `0` on an infinite number line. There is a goal
at position `target`.
On each move, you can either go left or right. During the _n_ -th move
(starting from 1), you take _n_ ste... |
def test(self):
pass
if __name__ == "__main__":
unittest.main()
| """
:type target: int
:rtype: int
""" | identifier_body |
lc754-reach-a-number.py | # coding=utf-8
import unittest
"""754. Reach a Number
https://leetcode.com/problems/reach-a-number/description/
You are standing at position `0` on an infinite number line. There is a goal
at position `target`.
On each move, you can either go left or right. During the _n_ -th move
(starting from 1), you take _n_ ste... | (object):
def reachNumber(self, target):
"""
:type target: int
:rtype: int
"""
def test(self):
pass
if __name__ == "__main__":
unittest.main()
| Solution | identifier_name |
test_basic.py | #_PYTHON_INSERT_SAO_COPYRIGHT_HERE_(2007)_
#_PYTHON_INSERT_GPL_LICENSE_HERE_
from numpy import arange
import sherpa.models.basic as basic
from sherpa.utils import SherpaFloat, SherpaTestCase
from sherpa.models.model import ArithmeticModel
def userfunc(pars, x, *args, **kwargs):
return x
class test_basic(SherpaTes... | m.calc = userfunc
self.assertEqual(type(m).__name__.lower(), m.name)
count += 1
try:
if m.name.count('2d'):
pt_out = m(x, x)
int_out = m(x, x, x, x)
else:
if m.name in ('log... | def test_create_and_evaluate(self):
x = arange(1.0, 5.0)
count = 0
for cls in dir(basic):
clsobj = getattr(basic, cls)
if ((not isinstance(clsobj, type)) or
(not issubclass(clsobj, ArithmeticModel)) or
(clsobj is ArithmeticModel)):
... | identifier_body |
test_basic.py | #_PYTHON_INSERT_SAO_COPYRIGHT_HERE_(2007)_
#_PYTHON_INSERT_GPL_LICENSE_HERE_
from numpy import arange
import sherpa.models.basic as basic
from sherpa.utils import SherpaFloat, SherpaTestCase
from sherpa.models.model import ArithmeticModel
def userfunc(pars, x, *args, **kwargs):
return x
class test_basic(SherpaTes... |
pt_out = m(xx)
int_out = m(xx, xx)
except ValueError:
self.fail("evaluation of model '%s' failed" % cls)
for out in (pt_out, int_out):
self.assert_(out.dtype.type is SherpaFloat)
self.assertEqual(out.shape... | xx = x | conditional_block |
test_basic.py | #_PYTHON_INSERT_SAO_COPYRIGHT_HERE_(2007)_
#_PYTHON_INSERT_GPL_LICENSE_HERE_
from numpy import arange
import sherpa.models.basic as basic
from sherpa.utils import SherpaFloat, SherpaTestCase
from sherpa.models.model import ArithmeticModel
def userfunc(pars, x, *args, **kwargs):
return x
class test_basic(SherpaTes... |
self.assertEqual(count, 31) | random_line_split | |
test_basic.py | #_PYTHON_INSERT_SAO_COPYRIGHT_HERE_(2007)_
#_PYTHON_INSERT_GPL_LICENSE_HERE_
from numpy import arange
import sherpa.models.basic as basic
from sherpa.utils import SherpaFloat, SherpaTestCase
from sherpa.models.model import ArithmeticModel
def | (pars, x, *args, **kwargs):
return x
class test_basic(SherpaTestCase):
def test_create_and_evaluate(self):
x = arange(1.0, 5.0)
count = 0
for cls in dir(basic):
clsobj = getattr(basic, cls)
if ((not isinstance(clsobj, type)) or
(not issubclass(... | userfunc | identifier_name |
login.service.ts | import { Injectable, Inject } from "@angular/core";
import { Headers, Http, Response, RequestOptions, URLSearchParams } from "@angular/http";
import { Observable } from "rxjs";
import { Customer } from "../_model/customer";
import { AppConfig, APP_CONFIG } from "../app.config";
@Injectable()
export class LoginService ... | () {
return this.http.post(`${this.url}/logout`, null, { withCredentials: true })
.toPromise()
.then(() => localStorage.removeItem('currentUser'));
}
// keepSessionAlive() {
// let url = `${this.url}/user/${this.username}`;
// this.http.get(url, { withCredentials... | logout | identifier_name |
login.service.ts | import { Injectable, Inject } from "@angular/core";
import { Headers, Http, Response, RequestOptions, URLSearchParams } from "@angular/http";
import { Observable } from "rxjs";
import { Customer } from "../_model/customer";
import { AppConfig, APP_CONFIG } from "../app.config";
@Injectable()
export class LoginService ... |
login(username: string, password: string) {
let headers = new Headers();
let encoded = btoa(`${username}:${password}`);
headers.append("Authorization", "Basic " + encoded);
headers.append("X-Requested-With", "XMLHttpRequest");
let params = new URLSearchParams();
pa... | {
this.sessionTimeout = config.sessionTimeout;
this.url = config.apiEndpoint;
} | identifier_body |
login.service.ts | import { Injectable, Inject } from "@angular/core";
import { Headers, Http, Response, RequestOptions, URLSearchParams } from "@angular/http"; | @Injectable()
export class LoginService {
private url: string;
private sessionTimeout: number;
private username: string;
constructor(private http: Http, @Inject(APP_CONFIG) config: AppConfig) {
this.sessionTimeout = config.sessionTimeout;
this.url = config.apiEndpoint;
}
login... | import { Observable } from "rxjs";
import { Customer } from "../_model/customer";
import { AppConfig, APP_CONFIG } from "../app.config";
| random_line_split |
login.service.ts | import { Injectable, Inject } from "@angular/core";
import { Headers, Http, Response, RequestOptions, URLSearchParams } from "@angular/http";
import { Observable } from "rxjs";
import { Customer } from "../_model/customer";
import { AppConfig, APP_CONFIG } from "../app.config";
@Injectable()
export class LoginService ... |
});
}
register(username: string, password: string, email: string): Promise<Response> {
let customer = new Customer();
customer.firstName = username;
customer.password = password;
customer.email = email;
return this.http.post(`${this.url}/users`, customer)
... | {
this.username = principal.name;
localStorage.setItem('currentUser', JSON.stringify(principal));
} | conditional_block |
snippets.rs | use crate::ast::with_error_checking_parse;
use crate::core::{Match, Session};
use crate::typeinf::get_function_declaration;
use rustc_ast::ast::AssocItemKind;
use rustc_parse::parser::ForceCollect;
/// Returns completion snippets usable by some editors
///
/// Generates a snippet string given a `Match`. The provided ... | }
})
.collect(),
});
}
}
debug!("Unable to parse method declaration. |{}|", source);
None
})
}
///Returns completion snippets usable by some e... | {
if let AssocItemKind::Fn(ref fn_kind) = method.kind {
let decl = &fn_kind.sig.decl;
return Some(MethodInfo {
// ident.as_str calls Ident.name.as_str
name: method.ident.name.to_string(),
args... | conditional_block |
snippets.rs | use crate::ast::with_error_checking_parse;
use crate::core::{Match, Session};
use crate::typeinf::get_function_declaration;
use rustc_ast::ast::AssocItemKind;
use rustc_parse::parser::ForceCollect;
/// Returns completion snippets usable by some editors
///
/// Generates a snippet string given a `Match`. The provided ... | Ok(name) => name,
_ => "".into(),
};
match source_map.span_to_snippet(arg.ty.span) {
Ok(ref type_name) if !type_name.is_empty() => {
... | .inputs
.iter()
.map(|arg| {
let source_map = &p.sess.source_map();
let var_name = match source_map.span_to_snippet(arg.pat.span) { | random_line_split |
snippets.rs | use crate::ast::with_error_checking_parse;
use crate::core::{Match, Session};
use crate::typeinf::get_function_declaration;
use rustc_ast::ast::AssocItemKind;
use rustc_parse::parser::ForceCollect;
/// Returns completion snippets usable by some editors
///
/// Generates a snippet string given a `Match`. The provided ... | };
match source_map.span_to_snippet(arg.ty.span) {
Ok(ref type_name) if !type_name.is_empty() => {
format!("{}: {}", var_name, type_name)
}
... | {
let trim: &[_] = &['\n', '\r', '{', ' '];
let decorated = format!("{} {{}}()", source.trim_end_matches(trim));
trace!("MethodInfo::from_source_str: {:?}", decorated);
with_error_checking_parse(decorated, |p| {
if let Ok(Some(Some(method))) = p.parse_impl_item(ForceCollect:... | identifier_body |
snippets.rs | use crate::ast::with_error_checking_parse;
use crate::core::{Match, Session};
use crate::typeinf::get_function_declaration;
use rustc_ast::ast::AssocItemKind;
use rustc_parse::parser::ForceCollect;
/// Returns completion snippets usable by some editors
///
/// Generates a snippet string given a `Match`. The provided ... | () {
let info = MethodInfo::from_source_str("pub fn new() -> Vec<T>").unwrap();
assert_eq!(info.name, "new");
assert_eq!(info.args.len(), 0);
assert_eq!(info.snippet(), "new()");
let info = MethodInfo::from_source_str("pub fn reserve(&mut self, additional: usize)").unwrap();
assert_eq!(info.nam... | method_info_test | identifier_name |
0063_populate_uuid_values.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-09-05 09:13
from __future__ import unicode_literals
import uuid
from django.core.exceptions import FieldDoesNotExist
from django.db import migrations
def set_uuid_field(apps, schema_editor):
"""
Set a random uuid value to all existing rows in all mod... |
class Migration(migrations.Migration):
dependencies = [
('base', '0062_add_uuid_field'),
]
operations = [
migrations.RunPython(set_uuid_field, elidable=True, reverse_code=migrations.RunPython.noop),
] | model_class.objects.filter(pk=pk).update(uuid=uuid.uuid4())
except FieldDoesNotExist:
break | random_line_split |
0063_populate_uuid_values.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-09-05 09:13
from __future__ import unicode_literals
import uuid
from django.core.exceptions import FieldDoesNotExist
from django.db import migrations
def | (apps, schema_editor):
"""
Set a random uuid value to all existing rows in all models containing an 'uuid' attribute in database.
"""
base = apps.get_app_config('base')
for model_class in base.get_models():
ids = model_class.objects.values_list('id', flat=True)
if ids:
fo... | set_uuid_field | identifier_name |
0063_populate_uuid_values.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-09-05 09:13
from __future__ import unicode_literals
import uuid
from django.core.exceptions import FieldDoesNotExist
from django.db import migrations
def set_uuid_field(apps, schema_editor):
"""
Set a random uuid value to all existing rows in all mod... | dependencies = [
('base', '0062_add_uuid_field'),
]
operations = [
migrations.RunPython(set_uuid_field, elidable=True, reverse_code=migrations.RunPython.noop),
] | identifier_body | |
0063_populate_uuid_values.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-09-05 09:13
from __future__ import unicode_literals
import uuid
from django.core.exceptions import FieldDoesNotExist
from django.db import migrations
def set_uuid_field(apps, schema_editor):
"""
Set a random uuid value to all existing rows in all mod... |
class Migration(migrations.Migration):
dependencies = [
('base', '0062_add_uuid_field'),
]
operations = [
migrations.RunPython(set_uuid_field, elidable=True, reverse_code=migrations.RunPython.noop),
]
| for pk in ids:
try:
model_class.objects.filter(pk=pk).update(uuid=uuid.uuid4())
except FieldDoesNotExist:
break | conditional_block |
ResourceTreeModel_test.ts | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as SDK from '../../../../../front_end/core/sdk/sdk.js';
import * as Protocol from '../../../../../front_end/generated/protocol.js'; |
describeWithMockConnection('ResourceTreeModel', () => {
let target: SDK.Target.Target;
let resourceTreeModel: SDK.ResourceTreeModel.ResourceTreeModel|null;
let networkManager: SDK.NetworkManager.NetworkManager|null;
beforeEach(() => {
target = createTarget();
resourceTreeModel = target.model(SDK.Resou... | import {createTarget} from '../../helpers/EnvironmentHelpers.js';
import {describeWithMockConnection, dispatchEvent} from '../../helpers/MockConnection.js';
const {assert} = chai; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.