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 |
|---|---|---|---|---|
exceptions.js | import { ListWrapper } from 'angular2/src/facade/collection';
import { stringify, isBlank } from 'angular2/src/facade/lang';
import { BaseException, WrappedException } from 'angular2/src/facade/exceptions';
function findFirstClosedCycle(keys) {
var res = [];
for (var i = 0; i < keys.length; ++i) {
if (L... |
return "Cannot resolve all parameters for " + stringify(typeOrFunc) + "(" +
signature.join(', ') + "). " + 'Make sure they all have valid type or annotations.';
}
}
/**
* Thrown when getting an object by index.
*
* ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview)... | {
var parameter = params[i];
if (isBlank(parameter) || parameter.length == 0) {
signature.push('?');
}
else {
signature.push(parameter.map(stringify).join(' '));
}
} | conditional_block |
main.rs | /*
License stuff
----------------------------------------------------------
Copyright 2013 Joris Rehm
Licensed under the Apache License, Version 2.0.
Licensed under The MIT License.
See joined files "LICENSE-APACHE" and "LICENSE-MIT".
----------------------------------------------------------
*/
... | 'event : loop {
match sdl::event::poll_event() {
sdl::event::QuitEvent => break 'main,
sdl::event::NoEvent => break 'event,
sdl::event::KeyEvent(k, _, _, _)
if k == sdl::event::EscapeKey
=> break 'main,
... |
'main : loop { | random_line_split |
main.rs | /*
License stuff
----------------------------------------------------------
Copyright 2013 Joris Rehm
Licensed under the Apache License, Version 2.0.
Licensed under The MIT License.
See joined files "LICENSE-APACHE" and "LICENSE-MIT".
----------------------------------------------------------
*/
... |
/* ----------------------------------------------------------- */
// TODO define an integration function and refactor
// compute_velocity and compute_position.
// TODO it's not really usefull to record acceleration
/* ----------------------------------------------------------- */
fn init_system() -> ~Manager... | {
let mut mng = Manager::new();
let e1 = mng.new_entity();
assert!( e1 == 0 );
let e2 = mng.new_entity();
assert!( e2 == 1 );
} | identifier_body |
main.rs | /*
License stuff
----------------------------------------------------------
Copyright 2013 Joris Rehm
Licensed under the Apache License, Version 2.0.
Licensed under The MIT License.
See joined files "LICENSE-APACHE" and "LICENSE-MIT".
----------------------------------------------------------
*/
... | () -> ~Manager {
println("use RUST_LOG=3 to see log");
let mut mng = Manager::new();
let zero = Vec(0., 0., 0.);
//
for i in range(0,10) {
let entity2 = mng.new_entity();
mng.table_position.set(entity2, Vec::rand_around_origin(5., 25.) );
mng.table_velocity.set(entity2, Vec::rand_around_origin(0.2... | init_system | identifier_name |
gulpfile.js | var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify');
var rename = require('gulp-rename');
var sh = require('shelljs');
var minify = require('gulp-minify');
var argv = re... | })
gulp.task('concat-src', function() {
return gulp.src(paths.js)
.pipe(concat('app-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
});
gulp.task('concat-lib', function() {
return gulp.src(paths.lib)
.pipe(concat('lib-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
});
gulp.task('minify', ['concat']... |
gulp.task('concat-all', ['minify'],function(){
return gulp.src(['./www/dist/lib-bundle-min.js','./www/dist/app-bundle-min.js'])
.pipe(concat('bundle-min.js'))
.pipe(gulp.dest('./www/dist/')); | random_line_split |
gulpfile.js | var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify');
var rename = require('gulp-rename');
var sh = require('shelljs');
var minify = require('gulp-minify');
var argv = re... |
done();
});
gulp.task('concat-and-minify', ['concat','minify']);
gulp.task('default', ['concat-and-minify']);
| {
console.log(
' ' + gutil.colors.red('Git is not installed.'),
'\n Git, the version control system, is required to download Ionic.',
'\n Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
'\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') +... | conditional_block |
lib.rs | // =================================================================
//
// * WARNING *
//
// This file is generated!
//
// Changes made to this file will be overwritten. If changes are
// required to the generated code, the service_crategen project
// must be updated to g... | extern crate serde_derive;
extern crate serde_json;
mod generated;
mod custom;
pub use generated::*;
pub use custom::*; | random_line_split | |
disallow_id_as_alias.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::WithLocation;
use errors::try2;
use graphql_ir::{
LinkedField, Program, ScalarField, ValidationError, ValidationMes... | }
}
}
impl<'s> Validator for DisallowIdAsAlias<'s> {
const NAME: &'static str = "DisallowIdAsAlias";
const VALIDATE_ARGUMENTS: bool = false;
const VALIDATE_DIRECTIVES: bool = false;
fn validate_linked_field(&mut self, field: &LinkedField) -> Result<(), Vec<ValidationError>> {
if le... | Self {
program,
id_key: "id".intern(), | random_line_split |
disallow_id_as_alias.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::WithLocation;
use errors::try2;
use graphql_ir::{
LinkedField, Program, ScalarField, ValidationError, ValidationMes... | else {
Ok(())
}
}
| {
Err(vec![ValidationError::new(
ValidationMessage::DisallowIdAsAliasError(),
vec![alias.location],
)])
} | conditional_block |
disallow_id_as_alias.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::WithLocation;
use errors::try2;
use graphql_ir::{
LinkedField, Program, ScalarField, ValidationError, ValidationMes... | {
if alias.item == id_key && schema.field(field).name != id_key {
Err(vec![ValidationError::new(
ValidationMessage::DisallowIdAsAliasError(),
vec![alias.location],
)])
} else {
Ok(())
}
} | identifier_body | |
disallow_id_as_alias.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::WithLocation;
use errors::try2;
use graphql_ir::{
LinkedField, Program, ScalarField, ValidationError, ValidationMes... | <'s>(program: &'s Program<'s>) -> Vec<ValidationError> {
let mut validator = DisallowIdAsAlias::new(program);
match validator.validate_program(program) {
Err(e) => e,
Ok(_) => Default::default(),
}
}
struct DisallowIdAsAlias<'s> {
program: &'s Program<'s>,
id_key: StringKey,
}
impl... | disallow_id_as_alias | identifier_name |
backend.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import string
from urlparse import urlparse, parse_qs
from mopidy import backend
from mopidy.models import SearchResult, Track, Album, Artist
import pykka
import pafy
import requests
import unicodedata
from mopidy_youtube import logger
yt_api_e... |
def resolve_playlist(url):
logger.info("Resolving Youtube for playlist '%s'", url)
query = {
'part': 'snippet',
'maxResults': 50,
'playlistId': url,
'fields': 'items/snippet/resourceId',
'key': yt_key
}
pl = requests.get(yt_api_endpoint+'playlistItem', params=q... | query = {
'part': 'id',
'maxResults': 15,
'type': 'video',
'q': q,
'key': yt_key
}
pl = requests.get(yt_api_endpoint+'search', params=query)
playlist = []
for yt_id in pl.json().get('items'):
try:
track = resolve_url(yt_id.get('id').get('videoI... | identifier_body |
backend.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import string
from urlparse import urlparse, parse_qs
from mopidy import backend
from mopidy.models import SearchResult, Track, Album, Artist
import pykka
import pafy
import requests
import unicodedata
from mopidy_youtube import logger
yt_api_e... | comment=video.videoid,
length=video.length*1000,
album=Album(
name='Youtube',
images=[video.bigthumb, video.bigthumbhd]
),
uri=uri
)
return track
def search_youtube(q):
query = {
'part': 'id',
'... | random_line_split | |
backend.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import string
from urlparse import urlparse, parse_qs
from mopidy import backend
from mopidy.models import SearchResult, Track, Album, Artist
import pykka
import pafy
import requests
import unicodedata
from mopidy_youtube import logger
yt_api_e... | (uri):
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
safe_uri = unicodedata.normalize(
'NFKD',
unicode(uri)
).encode('ASCII', 'ignore')
return re.sub(
'\s+',
' ',
''.join(c for c in safe_uri if c in valid_chars)
).strip()
def resolve_url... | safe_url | identifier_name |
backend.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import string
from urlparse import urlparse, parse_qs
from mopidy import backend
from mopidy.models import SearchResult, Track, Album, Artist
import pykka
import pafy
import requests
import unicodedata
from mopidy_youtube import logger
yt_api_e... |
logger.debug('%s - %s %s %s' % (
video.title, uri.bitrate, uri.mediatype, uri.extension))
uri = uri.url
if not uri:
return
if '-' in video.title:
title = video.title.split('-')
track = Track(
name=title[1].strip(),
comment=video.video... | uri = video.getbest() | conditional_block |
tinyurl.py | from ..base import BaseShortener
from ..exceptions import ShorteningErrorException
class Shortener(BaseShortener):
"""
TinyURL.com shortener implementation
Example:
>>> import pyshorteners
>>> s = pyshorteners.Shortener()
>>> s.tinyurl.short('http://www.google.com')
'http... |
raise ShorteningErrorException(response.content)
| return response.text.strip() | conditional_block |
tinyurl.py | from ..base import BaseShortener
from ..exceptions import ShorteningErrorException
class | (BaseShortener):
"""
TinyURL.com shortener implementation
Example:
>>> import pyshorteners
>>> s = pyshorteners.Shortener()
>>> s.tinyurl.short('http://www.google.com')
'http://tinyurl.com/TEST'
>>> s.tinyurl.expand('http://tinyurl.com/test')
'http://www.goo... | Shortener | identifier_name |
tinyurl.py | from ..base import BaseShortener
from ..exceptions import ShorteningErrorException
class Shortener(BaseShortener):
"""
TinyURL.com shortener implementation
Example:
>>> import pyshorteners
>>> s = pyshorteners.Shortener()
>>> s.tinyurl.short('http://www.google.com')
'http... | return response.text.strip()
raise ShorteningErrorException(response.content) | random_line_split | |
tinyurl.py | from ..base import BaseShortener
from ..exceptions import ShorteningErrorException
class Shortener(BaseShortener):
"""
TinyURL.com shortener implementation
Example:
>>> import pyshorteners
>>> s = pyshorteners.Shortener()
>>> s.tinyurl.short('http://www.google.com')
'http... | """Short implementation for TinyURL.com
Args:
url: the URL you want to shorten
Returns:
A string containing the shortened URL
Raises:
ShorteningErrorException: If the API returns an error as response
"""
url = self.clean_url(url)
res... | identifier_body | |
HorizontalRule.js | dojo.provide("dijit.form.HorizontalRule");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.declare("dijit.form.HorizontalRule", [dijit._Widget, dijit._Templated],
{
// summary:
// Hash marks for `dijit.form.HorizontalSlider`
templateString: '<div class="dijitRuleContainer dijitRuleContainer... | else{
var i;
var interval = 100 / (this.count-1);
if(!this._isHorizontal || this.isLeftToRight()){
innerHTML = this._genHTML(0, 0);
for(i=1; i < this.count-1; i++){
innerHTML += this._genHTML(interval*i, i);
}
innerHTML += this._genHTML(100, this.count-1);
}else{
innerHTML = this._g... | {
innerHTML = this._genHTML(50, 0);
} | conditional_block |
HorizontalRule.js | dojo.provide("dijit.form.HorizontalRule");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.declare("dijit.form.HorizontalRule", [dijit._Widget, dijit._Templated],
{
// summary:
// Hash marks for `dijit.form.HorizontalSlider`
templateString: '<div class="dijitRuleContainer dijitRuleContainer... |
postCreate: function(){
var innerHTML;
if(this.count==1){
innerHTML = this._genHTML(50, 0);
}else{
var i;
var interval = 100 / (this.count-1);
if(!this._isHorizontal || this.isLeftToRight()){
innerHTML = this._genHTML(0, 0);
for(i=1; i < this.count-1; i++){
innerHTML += this._genHTML(in... | random_line_split | |
borrowck-loan-in-overloaded-op.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = foo(~3);
let _y = x + {x}; // the `{x}` forces a move to occur
//~^ ERROR cannot move out of `x`
}
| main | identifier_name |
borrowck-loan-in-overloaded-op.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
fn main() {
let x = foo(~3);
let _y = x + {x}; // the `{x}` forces a move to occur
//~^ ERROR cannot move out of `x`
}
| {
let foo(~i) = *self;
let foo(~j) = *f;
foo(~(i + j))
} | identifier_body |
borrowck-loan-in-overloaded-op.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
impl Add<foo, foo> for foo {
fn add(&self, f: &foo) -> foo {
let foo(~i) = *self;
let foo(~j) = *f;
foo(~(i + j))
}
}
fn main() {
let x = foo(~3);
let _y = x + {x}; // the `{x}` forces a move to occur
//~^ ERROR cannot move out of `x`
} |
struct foo(~uint); | random_line_split |
templates.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Handlebars = require("handlebars");
var fs_1... | __extends(TemplateStack, _super);
function TemplateStack() {
return _super.call(this, Template, /\.hbs$/) || this;
}
return TemplateStack;
}(stack_1.ResourceStack));
exports.TemplateStack = TemplateStack;
var PartialStack = (function (_super) {
__extends(PartialStack, _super);
function P... | var TemplateStack = (function (_super) { | random_line_split |
templates.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function | () { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Handlebars = require("handlebars");
var fs_1 = require("../../../utils/fs");
var stack_1 = require("./stack");
var Template = (function (_super) {
__extends(Template, _super);
function T... | __ | identifier_name |
templates.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Handlebars = require("handlebars");
var fs_1... |
this.registeredNames = [];
return true;
};
return PartialStack;
}(TemplateStack));
exports.PartialStack = PartialStack;
//# sourceMappingURL=templates.js.map | {
var name = _a[_i];
Handlebars.unregisterPartial(name);
} | conditional_block |
templates.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Handlebars = require("handlebars");
var fs_1... |
PartialStack.prototype.activate = function () {
if (!_super.prototype.activate.call(this))
return false;
var resources = this.getAllResources();
for (var name in resources) {
if (this.registeredNames.indexOf(name) !== -1)
continue;
this.re... | {
var _this = _super.apply(this, arguments) || this;
_this.registeredNames = [];
return _this;
} | identifier_body |
main.rs | extern crate rand;
use std::fmt;
use std::{thread, time};
use std::process;
use rand::{thread_rng, Rng};
trait State : fmt::Display {
fn do_clock(&self, hour: u32) -> Box<State>;
fn do_use(&self, context: Box<&Context>);
fn do_alarm(&self, context: Box<&Context>);
fn do_phone(&self, context: Box<&Cont... | fn click_exit(&self) {
process::exit(0);
}
}
impl Context for SafeFrame {
fn set_clock(&mut self, hour: u32) {
println!("現在時刻は{0: >02}:00", hour);
let state = self.state.do_clock(hour);
if &self.state != &state {
self.change_state(state);
}
}... | random_line_split | |
main.rs | extern crate rand;
use std::fmt;
use std::{thread, time};
use std::process;
use rand::{thread_rng, Rng};
trait State : fmt::Display {
fn do_clock(&self, hour: u32) -> Box<State>;
fn do_use(&self, context: Box<&Context>);
fn do_alarm(&self, context: Box<&Context>);
fn do_phone(&self, context: Box<&Cont... | new("State Sample".to_string(), Box::new(NightState::new()));
let mut rng = thread_rng();
println!("------------");
println!("{}", frame.title);
println!("------------\n");
loop {
for hour in 0..24 {
frame.set_clock(hour);
match rng.gen_range(0, 3) ... | n main() {
let mut frame = SafeFrame:: | identifier_body |
main.rs | extern crate rand;
use std::fmt;
use std::{thread, time};
use std::process;
use rand::{thread_rng, Rng};
trait State : fmt::Display {
fn do_clock(&self, hour: u32) -> Box<State>;
fn do_use(&self, context: Box<&Context>);
fn do_alarm(&self, context: Box<&Context>);
fn do_phone(&self, context: Box<&Cont... | 9 <= hour && hour < 17 {
Box::new(DayState::new())
} else {
Box::new(NightState::new())
}
}
fn do_use(&self, context: Box<&Context>) {
context.call_security_center("非常:夜間の金庫使用!".to_string());
}
fn do_alarm(&self, context: Box<&Context>) {
context... | if | identifier_name |
dynamic_tests.rs | use crate::cell::RefCell;
use crate::collections::HashMap;
use crate::thread_local;
#[test]
fn smoke() {
fn square(i: i32) -> i32 {
i * i
}
thread_local!(static FOO: i32 = square(3));
FOO.with(|f| {
assert_eq!(*f, 9);
});
}
#[test]
fn hashmap() |
#[test]
fn refcell_vec() {
thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3]));
FOO.with(|vec| {
assert_eq!(vec.borrow().len(), 3);
vec.borrow_mut().push(4);
assert_eq!(vec.borrow()[3], 4);
});
}
| {
fn map() -> RefCell<HashMap<i32, i32>> {
let mut m = HashMap::new();
m.insert(1, 2);
RefCell::new(m)
}
thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map());
FOO.with(|map| {
assert_eq!(map.borrow()[&1], 2);
});
} | identifier_body |
dynamic_tests.rs | use crate::cell::RefCell;
use crate::collections::HashMap;
use crate::thread_local;
#[test]
fn smoke() {
fn square(i: i32) -> i32 {
i * i
}
thread_local!(static FOO: i32 = square(3));
FOO.with(|f| {
assert_eq!(*f, 9);
});
}
#[test]
fn hashmap() {
fn map() -> RefCell<HashMap<i3... |
FOO.with(|map| {
assert_eq!(map.borrow()[&1], 2);
});
}
#[test]
fn refcell_vec() {
thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3]));
FOO.with(|vec| {
assert_eq!(vec.borrow().len(), 3);
vec.borrow_mut().push(4);
assert_eq!(vec.borrow()[3], 4);
... | }
thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map()); | random_line_split |
dynamic_tests.rs | use crate::cell::RefCell;
use crate::collections::HashMap;
use crate::thread_local;
#[test]
fn smoke() {
fn | (i: i32) -> i32 {
i * i
}
thread_local!(static FOO: i32 = square(3));
FOO.with(|f| {
assert_eq!(*f, 9);
});
}
#[test]
fn hashmap() {
fn map() -> RefCell<HashMap<i32, i32>> {
let mut m = HashMap::new();
m.insert(1, 2);
RefCell::new(m)
}
thread_local!(... | square | identifier_name |
register.js | const AuthUtil = require('../thulib/auth')
const User = require('../models/user')
const updateCourseInfo = require('./update_course_info')
const updateCurriculumInfo = require('./update_curriculum_info')
const updateScheduleInfo = require('./update_schedule_info')
const taskScheduler = require('./task_scheduler')
cons... | const existed = !!user
if (!existed) {
const info = await AuthUtil.getUserInfo(username, password)
user = new User({
username: username,
password: password,
info: info
})
await user.save()
taskScheduler.add(updateCourseInfo, user, 3600000)
taskSched... | const authResult = await AuthUtil.auth(username, password)
if (authResult) {
let user = await User.findOne({username: username}) | random_line_split |
env.js | /*
* Meccano IOT WebConsole
*
*
* 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 program is distributed in the h... | port: process.env.MYSQL_PORT
}
},
servicemaneger: {
url: process.env.SERVICEMANAGER_URL
}
}; | pool: {
maxConnections: process.env.MYSQL_OPTIONS_POOL_MAXCONNECTIONS,
minConnections: process.env.MYSQL_OPTIONS_POOL_MINCONNECTIONS
},
host: process.env.MYSQL_HOST, | random_line_split |
test_hb.py | from __future__ import division, print_function, absolute_import
from io import StringIO
import tempfile
import numpy as np
from numpy.testing import assert_equal, \
assert_array_almost_equal_nulp
from scipy.sparse import coo_matrix, csc_matrix, rand
from scipy.io import hb_read, hb_write
SIMPLE = """\
No Ti... |
class TestHBReadWrite(object):
def check_save_load(self, value):
with tempfile.NamedTemporaryFile(mode='w+t') as file:
hb_write(file, value)
file.file.seek(0)
value_loaded = hb_read(file)
assert_csc_almost_equal(value, value_loaded)
def test_simple(self):... | m = hb_read(StringIO(SIMPLE))
assert_csc_almost_equal(m, SIMPLE_MATRIX) | identifier_body |
test_hb.py | from __future__ import division, print_function, absolute_import
from io import StringIO
import tempfile
import numpy as np
from numpy.testing import assert_equal, \
assert_array_almost_equal_nulp
from scipy.sparse import coo_matrix, csc_matrix, rand
from scipy.io import hb_read, hb_write
SIMPLE = """\
No Ti... | matrix = random_matrix.asformat(matrix_format, copy=False)
self.check_save_load(matrix) | conditional_block | |
test_hb.py | from __future__ import division, print_function, absolute_import
from io import StringIO
import tempfile
import numpy as np
from numpy.testing import assert_equal, \
assert_array_almost_equal_nulp
from scipy.sparse import coo_matrix, csc_matrix, rand
from scipy.io import hb_read, hb_write
SIMPLE = """\
No Ti... | 3 3 3 3 3 3 3 4 4 4 6 6 6 6 6 6 6 6 6 6 6 8 9 9 9 9
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 11
37 71 89 18 30 45 70 19 25 52
2.971243799687726e-01 3.662366682877375e-01 4.786962174699534e-01
6.490068647991184e-01 6.617490424831662e-02 8.870370343191623e-01
4.1964785... | (26I3) (26I3) (3E23.15)
1 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 | random_line_split |
test_hb.py | from __future__ import division, print_function, absolute_import
from io import StringIO
import tempfile
import numpy as np
from numpy.testing import assert_equal, \
assert_array_almost_equal_nulp
from scipy.sparse import coo_matrix, csc_matrix, rand
from scipy.io import hb_read, hb_write
SIMPLE = """\
No Ti... | (self):
m = hb_read(StringIO(SIMPLE))
assert_csc_almost_equal(m, SIMPLE_MATRIX)
class TestHBReadWrite(object):
def check_save_load(self, value):
with tempfile.NamedTemporaryFile(mode='w+t') as file:
hb_write(file, value)
file.file.seek(0)
value_loaded =... | test_simple | identifier_name |
drop-container.js | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { useState, useCallback, useEffect } from 'react';
import classnames from 'classnames';
import { settings } from 'carbon-compon... |
// file type validation
if (fileToUpload.invalidFileType) {
const updatedFile = {
...fileToUpload,
status: 'edit',
iconDescription: 'Delete file',
invalid: true,
errorSubject: 'Invalid file type',
errorBody: `"${fileToUpload.name}" does not have a valid fi... | {
const updatedFile = {
...fileToUpload,
status: 'edit',
iconDescription: 'Delete file',
invalid: true,
errorSubject: 'File size exceeds limit',
errorBody: '500kb max file size. Select a new file and try again.',
};
setFiles((files) =>
files.map(... | conditional_block |
drop-container.js | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { useState, useCallback, useEffect } from 'react';
import classnames from 'classnames';
import { settings } from 'carbon-compon... | name: file.name,
filesize: file.size,
status: 'uploading',
iconDescription: 'Uploading',
invalidFileType: file.invalidFileType,
}));
// eslint-disable-next-line react/prop-types
if (props.multiple) {
setFiles([...files, ...newFiles]);
newFiles.fo... | evt.stopPropagation();
const newFiles = addedFiles.map((file) => ({
uuid: uid(), | random_line_split |
toNumber.test.ts | import * as test from 'tape';
import { toNumber } from '../../src/to';
test('toNumber:numbers', (t) => {
t.equal(toNumber(0), 0);
t.equal(toNumber(-0), 0);
t.equal(toNumber(1), 1);
t.equal(toNumber(-1), -1); | });
test('toNumber:strings', (t) => {
t.equal(toNumber(''), 0);
t.equal(toNumber('0'), 0);
t.equal(toNumber('-0'), 0);
t.equal(toNumber('1'), 1);
t.equal(toNumber('-1'), -1);
t.equal(toNumber('1.5'), 1.5);
t.equal(toNumber('-1.5'), -1.5);
t.end();
});
test('toNumber:Infinity', (t) => {
t.equal(toNumber(Infin... | t.equal(toNumber(1), 1);
t.equal(toNumber(1.5), 1.5);
t.equal(toNumber(-1.5), -1.5);
t.end(); | random_line_split |
SacrificedSouls.js | import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import SPELLS from 'common/SPELLS';
import { formatThousands } from 'common/format';
import STATISTIC_CATEG... |
debug && this.log('Paired damage event', event, 'with queued cast', JSON.parse(JSON.stringify(this._queue[castIndex])));
const bonusDamage = calculateEffectiveDamage(event, this._queue[castIndex].bonus);
this._queue.splice(castIndex, 1);
if (event.ability.guid === SPELLS.SHADOW_BOLT_DEMO.id) {
th... | {
debug && this.error('Encountered damage event with no cast associated. Queue', JSON.parse(JSON.stringify(this._queue)), 'event', event);
return;
} | conditional_block |
SacrificedSouls.js | import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import SPELLS from 'common/SPELLS';
import { formatThousands } from 'common/format';
import STATISTIC_CATEG... | extends Analyzer {
get totalBonusDamage() {
return this._shadowBoltDamage + this._demonboltDamage;
}
static dependencies = {
demoPets: DemoPets,
};
_shadowBoltDamage = 0;
_demonboltDamage = 0;
_queue = [];
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.has... | SacrificedSouls | identifier_name |
SacrificedSouls.js | import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import SPELLS from 'common/SPELLS';
import { formatThousands } from 'common/format';
import STATISTIC_CATEG... | </>
)}
</>
)}
>
<BoringSpellValueText spell={SPELLS.SACRIFICED_SOULS_TALENT}>
<ItemDamageDone amount={this.totalBonusDamage} />
</BoringSpellValueText>
</Statistic>
);
}
}
export default SacrificedSouls; | {hasPS && (
<>
<br /><br />* Since you have Power Siphon talent, it's highly likely that it messes up getting current pets at certain time because sometimes
the number of Imps we sacrifice in code doesn't agree with what happens in logs. Therefore, this value is... | random_line_split |
SacrificedSouls.js | import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import SPELLS from 'common/SPELLS';
import { formatThousands } from 'common/format';
import STATISTIC_CATEG... |
static dependencies = {
demoPets: DemoPets,
};
_shadowBoltDamage = 0;
_demonboltDamage = 0;
_queue = [];
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.SACRIFICED_SOULS_TALENT.id);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell([S... | {
return this._shadowBoltDamage + this._demonboltDamage;
} | identifier_body |
nav.js | var _0x89fd = ["maps", "fn", "extend", "length", "ul", "children", "<span class='indicator'>+</span>", "append", "each", "li", "find", ".venus-menu", "<li class='showhide'><span class='title'>Menu</span><span class='icon'><em></em><em></em><em></em><em></em></span></li>", "prepend", "resize", "unbind", "li, a", "hide",... | if ($(_0x89fd[45])[_0x89fd[44]](_0x89fd[43])) {
$(_0x89fd[45])[_0x89fd[37]](300);
_0x2091x3 = 1;
} else {
$(_0x89fd[19])[_0x89fd[38]](300);
$(_0x89fd[42])[_0x89fd[41]](0);
_0x2091x3 = 0;
};
});
};
function _0x2091x8() {
$(_0x89fd[45])[_0x89fd[41]](0);
$(_0x89fd[42])[_0x89fd[17]](0)... | };
function _0x2091x7() {
$(_0x89fd[42])[_0x89fd[41]](0);
$(_0x89fd[42])[_0x89fd[27]](_0x89fd[32], function() { | random_line_split |
nav.js | var _0x89fd = ["maps", "fn", "extend", "length", "ul", "children", "<span class='indicator'>+</span>", "append", "each", "li", "find", ".venus-menu", "<li class='showhide'><span class='title'>Menu</span><span class='icon'><em></em><em></em><em></em><em></em></span></li>", "prepend", "resize", "unbind", "li, a", "hide",... | ;
function _0x2091x6() {
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[21]](_0x89fd[23]);
$(_0x89fd[40])[_0x89fd[8]](function() {
if ($(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[3]] > 0) {
$(this)[_0x89fd[5]](_0x89fd[39])[_0x89fd[27]](_0x89fd[32], function() {
if ($(this)[_0x89fd[35]](_0x89fd[4])[_0x89f... | {
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[21]](_0x89fd[20]);
$(_0x89fd[31])[_0x89fd[27]](_0x89fd[28], function() {
$(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[26]](true, true)[_0x89fd[30]](_0x2091x2[_0x89fd[24]])[_0x89fd[29]](_0x89fd[23]);
})[_0x89fd[27]](_0x89fd[22], function() {
$(this)[_0x89fd[5]](_0... | identifier_body |
nav.js | var _0x89fd = ["maps", "fn", "extend", "length", "ul", "children", "<span class='indicator'>+</span>", "append", "each", "li", "find", ".venus-menu", "<li class='showhide'><span class='title'>Menu</span><span class='icon'><em></em><em></em><em></em><em></em></span></li>", "prepend", "resize", "unbind", "li, a", "hide",... | ;
});
};
function _0x2091x8() {
$(_0x89fd[45])[_0x89fd[41]](0);
$(_0x89fd[42])[_0x89fd[17]](0);
};
};
$(document).ready(function(){
$().maps();
}); | {
$(_0x89fd[19])[_0x89fd[38]](300);
$(_0x89fd[42])[_0x89fd[41]](0);
_0x2091x3 = 0;
} | conditional_block |
nav.js | var _0x89fd = ["maps", "fn", "extend", "length", "ul", "children", "<span class='indicator'>+</span>", "append", "each", "li", "find", ".venus-menu", "<li class='showhide'><span class='title'>Menu</span><span class='icon'><em></em><em></em><em></em><em></em></span></li>", "prepend", "resize", "unbind", "li, a", "hide",... | () {
$(_0x89fd[45])[_0x89fd[41]](0);
$(_0x89fd[42])[_0x89fd[17]](0);
};
};
$(document).ready(function(){
$().maps();
}); | _0x2091x8 | identifier_name |
copyfiles.ts | /// <reference path="../../definitions/vsts-task-lib.d.ts" />
import path = require('path');
import os = require('os');
import tl = require('vsts-task-lib/task');
function getCommonLocalPath(files: string[]): string {
if (!files || files.length === 0) {
return "";
}
else if (files.length === 1) {
... | (item: string, parent: string): boolean {
item = path.normalize(item);
parent = path.normalize(parent);
return item.substring(0, parent.length) == parent
&& (item.length == parent.length || (parent.length > 0 && parent[parent.length - 1] === path.sep) || (item[parent.length] === path.sep));
}
funct... | isSubItem | identifier_name |
copyfiles.ts | /// <reference path="../../definitions/vsts-task-lib.d.ts" />
import path = require('path');
import os = require('os');
import tl = require('vsts-task-lib/task');
function getCommonLocalPath(files: string[]): string {
if (!files || files.length === 0) {
return "";
}
else if (files.length === 1) {
... |
function getFolderDepth(fullPath: string): number {
if (!fullPath) {
return 0;
}
var current = path.normalize(fullPath);
var parentPath = path.dirname(current);
var count = 0;
while (parentPath !== current) {
++count;
current = parentPath;
parentPath = path.dir... | {
item = path.normalize(item);
parent = path.normalize(parent);
return item.substring(0, parent.length) == parent
&& (item.length == parent.length || (parent.length > 0 && parent[parent.length - 1] === path.sep) || (item[parent.length] === path.sep));
} | identifier_body |
copyfiles.ts | /// <reference path="../../definitions/vsts-task-lib.d.ts" />
import path = require('path');
import os = require('os');
import tl = require('vsts-task-lib/task');
function getCommonLocalPath(files: string[]): string {
if (!files || files.length === 0) {
return "";
}
else if (files.length === 1) {
... | for (var i: number = 0; i < includeContents.length; i++) {
var pattern = includeContents[i];
tl.debug('Include matching ' + pattern);
// let minimatch do the actual filtering
var matches: string[] = tl.match(allFiles, pattern, matchOptions);
tl.debug('In... | random_line_split | |
copyfiles.ts | /// <reference path="../../definitions/vsts-task-lib.d.ts" />
import path = require('path');
import os = require('os');
import tl = require('vsts-task-lib/task');
function getCommonLocalPath(files: string[]): string {
if (!files || files.length === 0) {
return "";
}
else if (files.length === 1) {
... |
return root;
}
}
function _getCommonLocalPath(path1: string, path2: string): string {
var path1Depth = getFolderDepth(path1);
var path2Depth = getFolderDepth(path2);
var shortPath: string;
var longPath: string;
if (path1Depth >= path2Depth) {
shortPath = path2;
longPa... | {
root = _getCommonLocalPath(root, files[index]);
if (!root) {
break;
}
} | conditional_block |
prefs.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 basedir::default_config_dir;
use embedder_traits::resources::{self, Resource};
use num_cpus;
use opts;
use rus... |
}
pub fn default_prefs() -> Preferences {
let prefs = Preferences(Arc::new(RwLock::new(HashMap::new())));
prefs.set(
"layout.threads",
PrefValue::Number(max(num_cpus::get() * 3 / 4, 1) as f64),
);
prefs
}
pub fn read_prefs(txt: &str) -> Result<HashMap<String, Pref>, ()> {
let json... | {
self.value().to_json()
} | identifier_body |
prefs.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 basedir::default_config_dir;
use embedder_traits::resources::{self, Resource};
use num_cpus;
use opts;
use rus... | (&self) -> bool {
self.get("dom.webgl2.enabled").as_boolean().unwrap_or(false)
}
}
| is_webgl2_enabled | identifier_name |
prefs.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 basedir::default_config_dir;
use embedder_traits::resources::{self, Resource};
use num_cpus;
use opts;
use rus... | WithDefault(Arc<PrefValue>, Option<Arc<PrefValue>>),
}
impl Pref {
pub fn new(value: PrefValue) -> Pref {
Pref::NoDefault(Arc::new(value))
}
fn new_default(value: PrefValue) -> Pref {
Pref::WithDefault(Arc::new(value), None)
}
fn from_json(data: Json) -> Result<Pref, ()> {
... | }
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum Pref {
NoDefault(Arc<PrefValue>), | random_line_split |
main.js | (function(){
// Back to Top - by CodyHouse.co
var backTop = document.getElementsByClassName('js-cd-top')[0],
offset = 300, // browser window scroll (in pixels) after which the "back to top" link is shown
offsetOpacity = 1200, //browser window scroll (in pixels) after which the "back to top" link opacity is red... | () {
var windowTop = window.scrollY || document.documentElement.scrollTop;
( windowTop > offset ) ? Util.addClass(backTop, 'cd-top--is-visible') : Util.removeClass(backTop, 'cd-top--is-visible cd-top--fade-out');
( windowTop > offsetOpacity ) && Util.addClass(backTop, 'cd-top--fade-out');
scrolling = false;
}
... | checkBackToTop | identifier_name |
main.js | (function(){
// Back to Top - by CodyHouse.co
var backTop = document.getElementsByClassName('js-cd-top')[0],
offset = 300, // browser window scroll (in pixels) after which the "back to top" link is shown
offsetOpacity = 1200, //browser window scroll (in pixels) after which the "back to top" link opacity is red... |
if( backTop ) {
//update back to top visibility on scrolling
window.addEventListener("scroll", function(event) {
if( !scrolling ) {
scrolling = true;
(!window.requestAnimationFrame) ? setTimeout(checkBackToTop, 250) : window.requestAnimationFrame(checkBackToTop);
}
});
//smooth scroll to top
... | scrollDuration = 700,
scrolling = false; | random_line_split |
main.js | (function(){
// Back to Top - by CodyHouse.co
var backTop = document.getElementsByClassName('js-cd-top')[0],
offset = 300, // browser window scroll (in pixels) after which the "back to top" link is shown
offsetOpacity = 1200, //browser window scroll (in pixels) after which the "back to top" link opacity is red... |
})(); | {
var windowTop = window.scrollY || document.documentElement.scrollTop;
( windowTop > offset ) ? Util.addClass(backTop, 'cd-top--is-visible') : Util.removeClass(backTop, 'cd-top--is-visible cd-top--fade-out');
( windowTop > offsetOpacity ) && Util.addClass(backTop, 'cd-top--fade-out');
scrolling = false;
} | identifier_body |
main.js | (function(){
// Back to Top - by CodyHouse.co
var backTop = document.getElementsByClassName('js-cd-top')[0],
offset = 300, // browser window scroll (in pixels) after which the "back to top" link is shown
offsetOpacity = 1200, //browser window scroll (in pixels) after which the "back to top" link opacity is red... |
});
//smooth scroll to top
backTop.addEventListener('click', function(event) {
event.preventDefault();
(!window.requestAnimationFrame) ? window.scrollTo(0, 0) : Util.scrollTo(0, scrollDuration);
});
}
function checkBackToTop() {
var windowTop = window.scrollY || document.documentElement.scrollTop;
... | {
scrolling = true;
(!window.requestAnimationFrame) ? setTimeout(checkBackToTop, 250) : window.requestAnimationFrame(checkBackToTop);
} | conditional_block |
_nlp_common.py | 4
special_symbols = {
"<unk>": 0,
"<s>": 1,
"</s>": 2,
"<cls>": 3,
"<sep>": 4,
"<pad>": 5,
"<mask>": 6,
"<eod>": 7,
"<eop>": 8,
}
UNK_ID = special_symbols["<unk>"]
CLS_ID = special_symbols["<cls>"]
SEP_ID = special_symbols["<sep>"]
MASK_ID = special_symbols["<mask>"]
EOD_ID = specia... |
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
output_tokens.append("[UNK]")
else:
output_tokens.extend(sub_tokens)
r... | substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in self.vocab:
cur_substr = substr
break
end -= 1 | conditional_block |
_nlp_common.py | :
tokenizer = WordPieceTokenizer(vocab_file, lower_case)
elif sentence_piece_model_file:
tokenizer = SentencePieceTokenizer(sentence_piece_model_file, lower_case)
if tokenizer is None:
raise ValueError('tokenization parameters is not found, please provide: \n'
'for WordPiece... | if not sample:
pieces = self.encoder.EncodeAsPieces(text)
else:
pieces = self.encoder.SampleEncodeAsPieces(text, 64, 0.1)
new_pieces = []
for piece in pieces:
if len(piece) > 1 and piece[-1] == ',' and piece[-2].isdigit():
cur_pieces = self.enc... | identifier_body | |
_nlp_common.py | 4
special_symbols = {
"<unk>": 0,
"<s>": 1,
"</s>": 2,
"<cls>": 3,
"<sep>": 4,
"<pad>": 5,
"<mask>": 6,
"<eod>": 7,
"<eop>": 8,
}
UNK_ID = special_symbols["<unk>"]
CLS_ID = special_symbols["<cls>"]
SEP_ID = special_symbols["<sep>"]
MASK_ID = special_symbols["<mask>"]
EOD_ID = specia... | def get_tokenizer(lower_case, vocab_file=None, sentence_piece_model_file=None):
tokenizer = None
if vocab_file:
tokenizer = WordPieceTokenizer(vocab_file, lower_case)
elif sentence_piece_model_file:
tokenizer = SentencePieceTokenizer(sentence_piece_model_file, lower_case)
if tokenizer ... | SENTENCE_PIECE_PARAMETERS = ['sentence_piece_model_file']
| random_line_split |
_nlp_common.py | 4
special_symbols = {
"<unk>": 0,
"<s>": 1,
"</s>": 2,
"<cls>": 3,
"<sep>": 4,
"<pad>": 5,
"<mask>": 6,
"<eod>": 7,
"<eop>": 8,
}
UNK_ID = special_symbols["<unk>"]
CLS_ID = special_symbols["<cls>"]
SEP_ID = special_symbols["<sep>"]
MASK_ID = special_symbols["<mask>"]
EOD_ID = specia... | (tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is ver... | truncate_seq_pair | identifier_name |
AccordionTitle.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCal... |
/**
* A title sub-component for Accordion component
*/
var AccordionTitle = function (_Component) {
(0, _inherits3.default)(AccordionTitle, _Component);
function AccordionTitle() {
var _ref;
var _temp, _this, _ret;
(0, _classCallCheck3.default)(this, AccordionTitle);
for (var _len = argument... | { return obj && obj.__esModule ? obj : { default: obj }; } | identifier_body |
AccordionTitle.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCal... |
return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = AccordionTitle.__proto__ || Object.getPrototypeOf(AccordionTitle)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (e) {
var onClick = _this.props.onClick;
if (onClick) onClick(e, _thi... | {
args[_key] = arguments[_key];
} | conditional_block |
AccordionTitle.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCal... | (obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A title sub-component for Accordion component
*/
var AccordionTitle = function (_Component) {
(0, _inherits3.default)(AccordionTitle, _Component);
function AccordionTitle() {
var _ref;
var _temp, _this, _ret;
(0, _classCallChec... | _interopRequireDefault | identifier_name |
AccordionTitle.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCal... | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A title sub-component for Accordion component
*/
var AccordionTitle = function (_Component) {
(0, _inherits3.default)(AccordionTitle, _Component);
function AccordionTitle() {
var _ref;
var _temp, _this... | var _lib = require('../../lib');
| random_line_split |
preprocessor_tests.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
errors::*,
preprocessor::{build_transactions, extract_global_config, split_input},
};
fn parse_input(input: &str) -> Result<()> {
let config = extract_global_config("".lines(), false)?;
let (_, transactions... | () {
parse_input(r"
main() {}
//! new-transaction
//! new-transaction
main() {}
").unwrap_err();
}
#[rustfmt::skip]
#[test]
fn parse_input_empty_transaction_with_config() {
parse_input(r"
main() {}
//! new-transaction
//! sender: default
/... | parse_input_empty_transaction | identifier_name |
preprocessor_tests.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
errors::*,
preprocessor::{build_transactions, extract_global_config, split_input},
};
fn parse_input(input: &str) -> Result<()> {
let config = extract_global_config("".lines(), false)?;
let (_, transactions... |
#[test]
fn parse_input_no_transactions_with_config() {
parse_input("//! no-run: verifier").unwrap_err();
}
#[rustfmt::skip]
#[test]
fn parse_input_nothing_before_first_empty_transaction() {
parse_input(r"
//! new-transaction
main() {}
").unwrap();
}
#[rustfmt::skip]
#[test]
fn parse_inpu... | {
parse_input("").unwrap_err();
} | identifier_body |
preprocessor_tests.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
errors::*,
preprocessor::{build_transactions, extract_global_config, split_input},
};
| build_transactions(&config, &transactions)?;
Ok(())
}
#[test]
fn parse_input_no_transactions() {
parse_input("").unwrap_err();
}
#[test]
fn parse_input_no_transactions_with_config() {
parse_input("//! no-run: verifier").unwrap_err();
}
#[rustfmt::skip]
#[test]
fn parse_input_nothing_before_first_empt... | fn parse_input(input: &str) -> Result<()> {
let config = extract_global_config("".lines(), false)?;
let (_, transactions) = split_input(input.lines(), &config)?; | random_line_split |
boxes.rs | impl From<u32> for BoxType {
fn from(t: u32) -> BoxType {
use self::BoxType::*;
match t {
$($boxtype => $boxenum),*,
_ => UnknownBox(t),
}
}
}
impl Into<u32> for BoxType {
... | random_line_split | ||
boxes.rs | )]
pub struct FourCC {
pub value: String
}
impl From<u32> for FourCC {
fn from(number: u32) -> FourCC {
let mut box_chars = Vec::new();
for x in 0..4 {
let c = (number >> (x * 8) & 0x0000_00FF) as u8;
box_chars.push(c);
}
box_chars.reverse();
let... | (t: BoxType) -> FourCC {
let box_num: u32 = Into::into(t);
From::from(box_num)
}
}
impl<'a> From<&'a str> for FourCC {
fn from(v: &'a str) -> FourCC {
FourCC {
value: v.to_owned()
}
}
}
impl fmt::Debug for FourCC {
fn fmt(&self, f: &mut fmt::Formatter) -> fm... | from | identifier_name |
boxes.rs | )]
pub struct FourCC {
pub value: String
}
impl From<u32> for FourCC {
fn from(number: u32) -> FourCC |
}
impl From<BoxType> for FourCC {
fn from(t: BoxType) -> FourCC {
let box_num: u32 = Into::into(t);
From::from(box_num)
}
}
impl<'a> From<&'a str> for FourCC {
fn from(v: &'a str) -> FourCC {
FourCC {
value: v.to_owned()
}
}
}
impl fmt::Debug for FourCC {
... | {
let mut box_chars = Vec::new();
for x in 0..4 {
let c = (number >> (x * 8) & 0x0000_00FF) as u8;
box_chars.push(c);
}
box_chars.reverse();
let box_string = match String::from_utf8(box_chars) {
Ok(t) => t,
_ => String::from("null"... | identifier_body |
VideoWizard.py | = False
has_dvi = False
if boxtype in ('formuler3', 'enibox', 'mago', 'x2plus', 'sf3038', 'sf108', 'twinboxlcd', 'atemio6000', 'atemio6100', 'atemio6200', 'mbminiplus', 'vp7358ci', 'enibox', 'gbquad', 'gbquadplus', 'et5x00', 'et6000', 'et7000', 'et7500', 'et8500', 'classm', 'axodin', 'axodinc', 'genius', 'evo', 'galax... |
def modeSelectionMoved(self):
print "mode selection moved:", self.selection
self.modeSelect(self.selection)
def modeSelect(self, mode):
ratesList = self.listRates(mode)
print "ratesList:", ratesList
if self.port == "HDMI" and mode in ("720p", "1080i", "1080p"):
self.rate = "multi"
self.hw.setMode(p... | print "modeSelectionMade:", index
self.mode = index
self.modeSelect(index) | identifier_body |
VideoWizard.py | twinboxlcd', 'atemio6000', 'atemio6100', 'atemio6200', 'mbminiplus', 'vp7358ci', 'enibox', 'gbquad', 'gbquadplus', 'et5x00', 'et6000', 'et7000', 'et7500', 'et8500', 'classm', 'axodin', 'axodinc', 'genius', 'evo', 'galaxym6', 'geniuse3hd', 'evoe3hd', 'axase3', 'axase3c', 'starsatlx', 'mixosf7', 'mixoslumi', 'tmnano', 'a... | for rate in mode[1]:
if self.port == "DVI-PC":
print "rate:", rate
if rate == "640x480":
list.insert(0, (rate, rate))
continue
list.append((rate, rate)) | conditional_block | |
VideoWizard.py | ca = False
has_dvi = False
if boxtype in ('formuler3', 'enibox', 'mago', 'x2plus', 'sf3038', 'sf108', 'twinboxlcd', 'atemio6000', 'atemio6100', 'atemio6200', 'mbminiplus', 'vp7358ci', 'enibox', 'gbquad', 'gbquadplus', 'et5x00', 'et6000', 'et7000', 'et7500', 'et8500', 'classm', 'axodin', 'axodinc', 'genius', 'evo', 'gal... | if len(modeList) > 0:
ratesList = self.listRates(modeList[0][0])
self.hw.setMode(port = port, mode = modeList[0][0], rate = ratesList[0][0])
def listModes(self):
list = []
print "modes for port", self.port
for mode in self.hw.getModeList(self.port):
#if mode[0] != "PC":
list.append((mode[0], mode... | random_line_split | |
VideoWizard.py | = False
has_dvi = False
if boxtype in ('formuler3', 'enibox', 'mago', 'x2plus', 'sf3038', 'sf108', 'twinboxlcd', 'atemio6000', 'atemio6100', 'atemio6200', 'mbminiplus', 'vp7358ci', 'enibox', 'gbquad', 'gbquadplus', 'et5x00', 'et6000', 'et7000', 'et7500', 'et8500', 'classm', 'axodin', 'axodinc', 'genius', 'evo', 'galax... | (self):
self.parent.setLCDTextCallback(self.setText)
def setLCDPic(self, file):
self["pic"].instance.setPixmapFromFile(file)
class VideoWizard(WizardLanguage, Rc):
skin = """
<screen position="fill" title="Welcome..." flags="wfNoBorder" >
<panel name="WizardMarginsTemplate"/>
<panel name="WizardPictureL... | setLCDPicCallback | identifier_name |
Scene.ts | //missing
import {ISprite} from "browser/graphics/ISprite";
//convert-files
import {View} from "./View";
///<module="framework/ghost/events"/>
//convert-files
import {Sprite} from "./Sprite";
export class Scene extends Sprite
{
public static EVENT_CHANGE:string = "change";
public static EVENT_END: string = "end... |
public addView(view:View)
{
this.views.push(view);
this.viewsLength++;
view.on(View.EVENT_SIZE_CHANGE, this.viewChanged, this, view);
view.on(View.EVENT_CHANGE, this.viewChanged, this, view);
}
public play():void
{
if(this.state_running !== Scene.STATE_PLAY)
{
this.state_running = Scene... | {
super();
this.views = [];
this.viewsLength = 0;
this.state_running = Scene.STATE_STOP;
} | identifier_body |
Scene.ts | //missing
import {ISprite} from "browser/graphics/ISprite";
//convert-files
import {View} from "./View";
///<module="framework/ghost/events"/>
//convert-files
import {Sprite} from "./Sprite";
export class Scene extends Sprite
{
public static EVENT_CHANGE:string = "change";
public static EVENT_END: string = "end... |
}
}
| {
requestAnimationFrame(this.render.bind(this));
} | conditional_block |
Scene.ts | //missing
import {ISprite} from "browser/graphics/ISprite";
//convert-files
import {View} from "./View";
///<module="framework/ghost/events"/>
//convert-files
import {Sprite} from "./Sprite";
export class Scene extends Sprite
{
public static EVENT_CHANGE:string = "change";
public static EVENT_END: string = "end... | this.viewsLength = 0;
this.state_running = Scene.STATE_STOP;
}
public addView(view:View)
{
this.views.push(view);
this.viewsLength++;
view.on(View.EVENT_SIZE_CHANGE, this.viewChanged, this, view);
view.on(View.EVENT_CHANGE, this.viewChanged, this, view);
}
public play():void
{
if(this.s... | {
super();
this.views = []; | random_line_split |
Scene.ts | //missing
import {ISprite} from "browser/graphics/ISprite";
//convert-files
import {View} from "./View";
///<module="framework/ghost/events"/>
//convert-files
import {Sprite} from "./Sprite";
export class Scene extends Sprite
{
public static EVENT_CHANGE:string = "change";
public static EVENT_END: string = "end... | ():void
{
this.state_running = Scene.STATE_STOP;
}
protected render():void
{
for (var i: number = 0; i < this.viewsLength; i++)
{
this.views[i].draw(this);
}
if (this.state_running == Scene.STATE_PLAY)
{
requestAnimationFrame(this.render.bind(this));
}
}
}
| pause | identifier_name |
ListProvider.ts | import {Model} from '../../models/base/Model';
import {Subject} from 'rxjs/Subject';
import {BaseService} from '../BaseService';
import {ActivatedRoute, Router} from '@angular/router';
import {UserRights, UserService} from '../../services/UserService';
import {ListTableColumn} from './ListTableColumn';
import {Behavior... | blic init() {
this.items = new BehaviorSubject<T[]>([]);
this.route.queryParamMap.subscribe(params => {
const pageNumber = parseInt(params.get('page'), 10);
if (pageNumber >= 1) {
this.currentPage = pageNumber;
}
const sort = params.get('sort');
if (sort != null) {
... |
pu | identifier_body |
ListProvider.ts | import {Model} from '../../models/base/Model';
import {Subject} from 'rxjs/Subject';
import {BaseService} from '../BaseService';
import {ActivatedRoute, Router} from '@angular/router';
import {UserRights, UserService} from '../../services/UserService';
import {ListTableColumn} from './ListTableColumn';
import {Behavior... | eturn sortKey;
}
constructor(private service: BaseService<T>, private router: Router,
private route: ActivatedRoute, private _userService: UserService) {
}
public init() {
this.items = new BehaviorSubject<T[]>([]);
this.route.queryParamMap.subscribe(params => {
const pageNumber = p... | sortKey = '-' + sortKey;
}
r | conditional_block |
ListProvider.ts | import {Model} from '../../models/base/Model';
import {Subject} from 'rxjs/Subject';
import {BaseService} from '../BaseService';
import {ActivatedRoute, Router} from '@angular/router';
import {UserRights, UserService} from '../../services/UserService';
import {ListTableColumn} from './ListTableColumn';
import {Behavior... | te service: BaseService<T>, private router: Router,
private route: ActivatedRoute, private _userService: UserService) {
}
public init() {
this.items = new BehaviorSubject<T[]>([]);
this.route.queryParamMap.subscribe(params => {
const pageNumber = parseInt(params.get('page'), 10);
... | uctor(priva | identifier_name |
ListProvider.ts | import {Model} from '../../models/base/Model';
import {Subject} from 'rxjs/Subject';
import {BaseService} from '../BaseService';
import {ActivatedRoute, Router} from '@angular/router';
import {UserRights, UserService} from '../../services/UserService';
import {ListTableColumn} from './ListTableColumn'; |
export class ListProvider<T extends Model> {
public currentPage = 1;
public itemsPerPage = 10;
public totalItems = 0;
public dataLoaded = false;
public items: Subject<T[]>;
public cardTitle = '';
public cardIcon = '';
public columns: ListTableColumn<T>[];
public sortDirection = SortDirection;
publ... | import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {SortDirection} from '../SortDirection';
import {ListTableColumnActionType, ListTableColumnType} from './ListEnums'; | random_line_split |
generator.py | def is_tl(data):
return isinstance(data, tuple) or isinstance(data, list)
def get_depth(data):
'''
:type data: list or tuple
get the depth of nested list
'x' is 0
['x', 'y'] is 1
['x', ['y', 'z'] is 2
'''
if is_tl(data):
depths = []
for i in data:... |
if not is_tl(b):
b = [b]
result = []
for i in a:
for j in b:
result.append('%s%s' % (i, j))
return result
def _generate_d2(data):
return reduce(reduce_d2, data)
def _generate(data):
'''
recursively generate the list
'''
depth = get_depth(data)
if ... | a = [a] | conditional_block |
generator.py | def is_tl(data):
|
def get_depth(data):
'''
:type data: list or tuple
get the depth of nested list
'x' is 0
['x', 'y'] is 1
['x', ['y', 'z'] is 2
'''
if is_tl(data):
depths = []
for i in data:
depths.append(1+get_depth(i))
return max(depths)
els... | return isinstance(data, tuple) or isinstance(data, list) | identifier_body |
generator.py | def is_tl(data):
return isinstance(data, tuple) or isinstance(data, list)
def get_depth(data):
'''
:type data: list or tuple
get the depth of nested list
'x' is 0
['x', 'y'] is 1
['x', ['y', 'z'] is 2
'''
if is_tl(data):
depths = []
for i in data:... |
def reduce_d2(a, b):
'''
generate all combination from a, b
'''
if not is_tl(a):
a = [a]
if not is_tl(b):
b = [b]
result = []
for i in a:
for j in b:
result.append('%s%s' % (i, j))
return result
def _generate_d2(data):
return reduce(reduce_d2, d... | else:
return 0
| random_line_split |
generator.py | def is_tl(data):
return isinstance(data, tuple) or isinstance(data, list)
def get_depth(data):
'''
:type data: list or tuple
get the depth of nested list
'x' is 0
['x', 'y'] is 1
['x', ['y', 'z'] is 2
'''
if is_tl(data):
depths = []
for i in data:... | (a, b):
'''
generate all combination from a, b
'''
if not is_tl(a):
a = [a]
if not is_tl(b):
b = [b]
result = []
for i in a:
for j in b:
result.append('%s%s' % (i, j))
return result
def _generate_d2(data):
return reduce(reduce_d2, data)
def _ge... | reduce_d2 | identifier_name |
index.tsx | import * as React from 'react';
import { Route, Switch } from 'react-router-dom';
import Header from '../Header/index';
import Home from '../Home/index';
import Login from '../Login/index';
import SignUp from '../SignUp/index';
import Dashboard from '../Dashboard/index';
import Settings from '../Settings/index';
import... | extends React.PureComponent<any, any> {
constructor(props: any, context: any) {
super(props, context);
}
render() {
const { auth, component: Component, ...rest } = this.props;
return (
<Route {...rest} render={props => {
if (!auth || !!localStorage.getItem('token')) {
return ... | PrivateRoute | identifier_name |
index.tsx | import * as React from 'react';
import { Route, Switch } from 'react-router-dom';
import Header from '../Header/index';
import Home from '../Home/index';
import Login from '../Login/index';
import SignUp from '../SignUp/index';
import Dashboard from '../Dashboard/index';
import Settings from '../Settings/index';
import... | main: () => <Encounter title="Encounter"/>,
},
{
protectedPath: false,
header: () => <Header title="Page not found"/>,
main: () => <NotFoundPage title="Page not found"/>,
},
];
class PrivateRoute extends React.PureComponent<any, any> {
constructor(props: any, context: any) {
super(props, co... | path: '/encounter',
protectedPath: true,
header: () => <Header title="Encounter"/>, | random_line_split |
index.tsx | import * as React from 'react';
import { Route, Switch } from 'react-router-dom';
import Header from '../Header/index';
import Home from '../Home/index';
import Login from '../Login/index';
import SignUp from '../SignUp/index';
import Dashboard from '../Dashboard/index';
import Settings from '../Settings/index';
import... |
render() {
const { auth, component: Component, ...rest } = this.props;
return (
<Route {...rest} render={props => {
if (!auth || !!localStorage.getItem('token')) {
return <Component {...props}/>;
} else {
const Redirect = require('react-router').Redirect;
... | {
super(props, context);
} | identifier_body |
main.ng.rs | //! Multivariate linear regression using gradient descent
//!
//! Model:
//!
//! ```
//! y = x * theta + e
//!
//! y Dependent variable (scalar)
//! x Independent variables (1-by-n matrix)
//! theta Parameters to estimate (n-by-1 matrix)
//! e Error (scalar)
//! ```
//!
//! Cost fu... | (path: &Path) -> io::Result<Transposed<Mat<f64>>> {
let mut lines = Lines::from(BufReader::new(try!(File::open(path))));
let mut v = vec![];
let ncols = {
let mut ncols = 0;
for number in try!(lines.next().unwrap()).split_whitespace() {
ncols += 1;
... | load | identifier_name |
main.ng.rs | //! Multivariate linear regression using gradient descent
//!
//! Model:
//!
//! ```
//! y = x * theta + e
//!
//! y Dependent variable (scalar)
//! x Independent variables (1-by-n matrix)
//! theta Parameters to estimate (n-by-1 matrix)
//! e Error (scalar)
//! ```
//!
//! Cost fu... |
last_J = J;
}
max_niters
}
/// Loads data from a TSV file
fn load<P>(path: P) -> io::Result<Transposed<Mat<f64>>> where P: AsRef<Path> {
fn load(path: &Path) -> io::Result<Transposed<Mat<f64>>> {
let mut lines = Lines::from(BufReader::new(try!(File::open(path))));
let mut v = ve... | {
return i
} | conditional_block |
main.ng.rs | //! Multivariate linear regression using gradient descent
//!
//! Model:
//!
//! ```
//! y = x * theta + e
//!
//! y Dependent variable (scalar)
//! x Independent variables (1-by-n matrix)
//! theta Parameters to estimate (n-by-1 matrix)
//! e Error (scalar)
//! ```
//!
//! Cost fu... |
let mut X = Mat::ones((m, n + 1));
X[.., 1..] = data[.., 1..];
let y = data.col(0);
let (mu, sigma) = timeit!("Normalization", {
normalize(&mut X[.., 1..])
});
println!("mean: {:?}", mu);
println!("std deviation: {:?}\n", sigma);
let ref mut theta = ColVec::zeros(n + 1);
... | {
env_logger::init().unwrap();
// Some dummy operation to force the initialization of OpenBLAS' runtime (~90 ms) here rather
// than during the measurements below
(&mat![1., 2.; 3., 4.].inv() * &mat![1., 2.; 3., 4.]).eval();
let data = timeit!("Loading data", {
load("mpg.tsv").unwrap()
... | identifier_body |
main.ng.rs | //! Multivariate linear regression using gradient descent
//!
//! Model:
//!
//! ```
//! y = x * theta + e
//!
//! y Dependent variable (scalar)
//! x Independent variables (1-by-n matrix)
//! theta Parameters to estimate (n-by-1 matrix)
//! e Error (scalar)
//! ```
//!
//! Cost fu... |
*col -= mean;
*col /= sd;
}
(mu, sigma)
}
/// Performs the gradient descent algorithm to find the value of `theta` that minimizes the cost
/// function.
///
/// X (m, n)
/// y (m, 1)
/// theta (n, 1)
/// alpha scalar Step size
/// max_niters integer Maximum... |
mu.push(mean);
sigma.push(sd); | random_line_split |
CheckboxSelectionModel.js | /*!
* js-file-browser
* Copyright(c) 2011 Biotechnology Computing Facility, University of Arizona. See included LICENSE.txt file.
*
* With components from: Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/*!
* Ext JS Library 3.3.1
* Copyrigh... |
},
// private
onMouseDown : function(e, t){
if(e.button === 0 && t.className == 'x-grid3-row-checker'){ // Only fire if left-click
e.stopEvent();
var row = e.getTarget('.x-grid3-row');
if(row){
var index = row.rowIndex;
if(this.is... | {
return Ext.grid.Column.prototype.processEvent.apply(this, arguments);
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.