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 |
|---|---|---|---|---|
sort.ts | import { SortType, SortDirection, SortPropDir } from '../types';
import { getterForProp } from './column-prop-getters';
/**
* Gets the next sort direction
*/
export function nextSortDir(sortType: SortType, current: SortDirection): SortDirection | undefined {
if (sortType === SortType.single) {
if(current === So... | return 0;
}
/**
* creates a shallow copy of the `rows` input and returns the sorted copy. this function
* does not sort the `rows` argument in place
*/
export function sortRows(rows: any[], columns: any[], dirs: SortPropDir[]): any[] {
if(!rows) return [];
if(!dirs || !dirs.length || !columns) return [...row... | {
if (a === null || typeof a === 'undefined') a = 0;
if (b === null || typeof b === 'undefined') b = 0;
if (a instanceof Date && b instanceof Date) {
if (a < b) return -1;
if (a > b) return 1;
} else if ((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))) {
// Convert t... | identifier_body |
sort.ts | import { SortType, SortDirection, SortPropDir } from '../types';
import { getterForProp } from './column-prop-getters';
/**
* Gets the next sort direction
*/
export function nextSortDir(sortType: SortType, current: SortDirection): SortDirection | undefined {
if (sortType === SortType.single) {
if(current === So... | export function sortRows(rows: any[], columns: any[], dirs: SortPropDir[]): any[] {
if(!rows) return [];
if(!dirs || !dirs.length || !columns) return [...rows];
/**
* record the row ordering of results from prior sort operations (if applicable)
* this is necessary to guarantee stable sorting behavior
*... | random_line_split | |
edition-keywords-2018-2018.rs | // run-pass
#![allow(unused_assignments)]
// edition:2018
// aux-build:edition-kw-macro-2018.rs
#[macro_use]
extern crate edition_kw_macro_2018;
pub fn check_async() {
// let mut async = 1; // ERROR, reserved
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_as... | // OK
// one_async::async(); // ERROR, reserved
// one_async::r#async(); // ERROR, unresolved name
// two_async::async(); // ERROR, reserved
two_async::r#async(); // OK
}
mod one_async {
// produces_async! {} // ERROR, reserved
}
mod two_async {
produces_async_raw! {} // OK
}
fn main() {}
| {} | conditional_block |
edition-keywords-2018-2018.rs | // run-pass
#![allow(unused_assignments)]
// edition:2018
// aux-build:edition-kw-macro-2018.rs
#[macro_use]
extern crate edition_kw_macro_2018;
pub fn check_async() {
// let mut async = 1; // ERROR, reserved
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_as... | mod one_async {
// produces_async! {} // ERROR, reserved
}
mod two_async {
produces_async_raw! {} // OK
}
fn main() {} | }
| random_line_split |
edition-keywords-2018-2018.rs | // run-pass
#![allow(unused_assignments)]
// edition:2018
// aux-build:edition-kw-macro-2018.rs
#[macro_use]
extern crate edition_kw_macro_2018;
pub fn check_async() {
// let mut async = 1; // ERROR, reserved
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_as... | () {}
| main | identifier_name |
edition-keywords-2018-2018.rs | // run-pass
#![allow(unused_assignments)]
// edition:2018
// aux-build:edition-kw-macro-2018.rs
#[macro_use]
extern crate edition_kw_macro_2018;
pub fn check_async() {
// let mut async = 1; // ERROR, reserved
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_as... | {} | identifier_body | |
index.tsx | import * as React from "react";
import { Code, H1, Li, Link, List, P } from "../../src/components/article";
export const Article = () => (
<>
<P>
In JavaScript, most common way to get pseudo random values is from the <Code language="js">Math.random()</Code>{" "}
standard library function.
</P>
... | .
</Li>
<Li>
You probably should not do the range transformations by yourself as they can be{" "}
<Link href="https://gist.github.com/joepie91/7105003c3b26e65efcea63f3db82dfba">error prone</Link>. I would
recommend using some library for that.
</Li>
</List>
</>
); | </Link> | random_line_split |
query_binder.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be |
import {CompileTokenMetadata, tokenReference} from '../compile_metadata';
import * as o from '../output/output_ast';
import {CompileElement} from './compile_element';
import {CompileQuery} from './compile_query';
// Note: We can't do this when we create the CompileElements already,
// as we create embedded views be... | * found in the LICENSE file at https://angular.io/license
*/ | random_line_split |
query_binder.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CompileTokenMetadata, tokenReference} from '../compile_metadata';
import * as o from '../output/output_ast';... | (public query: CompileQuery, match: CompileTokenMetadata) {
this.read = query.meta.read || match;
}
}
| constructor | identifier_name |
query_binder.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CompileTokenMetadata, tokenReference} from '../compile_metadata';
import * as o from '../output/output_ast';... |
});
}
class _QueryWithRead {
public read: CompileTokenMetadata;
constructor(public query: CompileQuery, match: CompileTokenMetadata) {
this.read = query.meta.read || match;
}
}
| {
queryWithRead.query.addValue(value, ce.view);
} | conditional_block |
time.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/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::p... |
send_profile_data(category,
meta,
&profiler_chan,
start_time,
end_time,
start_energy,
end_energy);
val
}
pub fn send_profile_data(category: ProfilerCategory,
... | {
signpost::end(category as u32, &[0, 0, 0, (category as usize) >> 4]);
} | conditional_block |
time.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/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::p... | ScriptAttachLayout = 0x60,
ScriptConstellationMsg = 0x61,
ScriptDevtoolsMsg = 0x62,
ScriptDocumentEvent = 0x63,
ScriptDomEvent = 0x64,
ScriptEvaluate = 0x65,
ScriptEvent = 0x66,
ScriptFileRead = 0x67,
ScriptImageCacheMsg = 0x68,
ScriptInputEvent = 0x69,
ScriptNetworkEvent = 0... | ImageDecoding = 0x50,
ImageSaving = 0x51, | random_line_split |
time.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/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::p... | {
RootWindow,
IFrame,
}
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum TimerMetadataReflowType {
Incremental,
FirstReflow,
}
pub fn profile<T, F>(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan:... | TimerMetadataFrameType | identifier_name |
xorg.py | # -*- coding: utf-8 -*-
"""
pygments.lexers.xorg
~~~~~~~~~~~~~~~~~~~~
Lexers for Xorg configs.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, bygroups
from pygments.token import Comment, String,... | """Lexer for xorg.conf file."""
name = 'Xorg'
aliases = ['xorg.conf']
filenames = ['xorg.conf']
mimetypes = []
tokens = {
'root': [
(r'\s+', Text),
(r'#.*$', Comment),
(r'((?:Sub)?Section)(\s+)("\w+")',
bygroups(String.Escape, Text, String.E... | identifier_body | |
xorg.py | # -*- coding: utf-8 -*-
"""
pygments.lexers.xorg
~~~~~~~~~~~~~~~~~~~~
Lexers for Xorg configs.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, bygroups
from pygments.token import Comment, String,... | (RegexLexer):
"""Lexer for xorg.conf file."""
name = 'Xorg'
aliases = ['xorg.conf']
filenames = ['xorg.conf']
mimetypes = []
tokens = {
'root': [
(r'\s+', Text),
(r'#.*$', Comment),
(r'((?:Sub)?Section)(\s+)("\w+")',
bygroups(String.Esca... | XorgLexer | identifier_name |
xorg.py | # -*- coding: utf-8 -*-
"""
pygments.lexers.xorg
~~~~~~~~~~~~~~~~~~~~
Lexers for Xorg configs.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, bygroups
from pygments.token import Comment, String,... | name = 'Xorg'
aliases = ['xorg.conf']
filenames = ['xorg.conf']
mimetypes = []
tokens = {
'root': [
(r'\s+', Text),
(r'#.*$', Comment),
(r'((?:Sub)?Section)(\s+)("\w+")',
bygroups(String.Escape, Text, String.Escape)),
(r'(End(|Su... | random_line_split | |
test_query_cache.d.ts | /**
* @license
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applica... | {
persistence: Persistence;
cache: QueryCache;
constructor(persistence: Persistence, cache: QueryCache);
addQueryData(queryData: QueryData): Promise<void>;
updateQueryData(queryData: QueryData): Promise<void>;
getQueryCount(): Promise<number>;
removeQueryData(queryData: QueryData): P... | TestQueryCache | identifier_name |
test_query_cache.d.ts | /**
* @license
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applica... | allocateTargetId(): Promise<TargetId>;
addMatchingKeys(keys: DocumentKey[], targetId: TargetId): Promise<void>;
removeMatchingKeys(keys: DocumentKey[], targetId: TargetId): Promise<void>;
getMatchingKeysForTargetId(targetId: TargetId): Promise<DocumentKey[]>;
removeMatchingKeysForTargetId(target... | random_line_split | |
local-routing.js | 'use strict';
const psplit = require('../psplit');
/**
* Routes the mock API calls (from Lambda functions) into the AWS
* actions.
*
* @param {RouteMap} actionMap - the route entry from the api/route.js
* file, for a specific service name.
* @return {Object[]} list of { actionName, handler }.
*/
... | else {
callback(null, res[1]);
}
})
.catch(function(err) {
callback(err, null);
});
} catch (err) {
console.log(`[local route ${serviceName}] invoking ${route.Action} with params ${JSON.stringify(params)} generated: ${err.message}\n${err.stack}`... | {
// Error result
callback(new Error(res[3]));
} | conditional_block |
local-routing.js | 'use strict';
const psplit = require('../psplit');
/**
* Routes the mock API calls (from Lambda functions) into the AWS
* actions.
*
* @param {RouteMap} actionMap - the route entry from the api/route.js
* file, for a specific service name.
* @return {Object[]} list of { actionName, handler }.
*/
... | signature: '12341234', // TODO fix
signatureMethod: '', // TODO fix
signatureVersion: '', // TODO fix
timestamp: 10, // TODO fix
region: (!!awsConfig.region ? awsConfig.region : 'ZN-MOCK-1'),
isRest: (!route.Action),
};
}
| {
var awsConfig = p.awsConfig;
var serviceName = p.serviceName;
var url = p.url;
var route = p.route;
var params = p.params;
// FIXME
return {
baseUrl: 'http://localhost/' + url, // TODO fix
requestUrl: url, // TODO fix
serviceName: serviceName,
params: params,
restParams... | identifier_body |
local-routing.js | 'use strict';
const psplit = require('../psplit');
/**
* Routes the mock API calls (from Lambda functions) into the AWS
* actions.
*
* @param {RouteMap} actionMap - the route entry from the api/route.js
* file, for a specific service name.
* @return {Object[]} list of { actionName, handler }.
*/
... | (p) {
var awsConfig = p.awsConfig;
var serviceName = p.serviceName;
var url = p.url;
var route = p.route;
var params = p.params;
// FIXME
return {
baseUrl: 'http://localhost/' + url, // TODO fix
requestUrl: url, // TODO fix
serviceName: serviceName,
params: params,
restPa... | createAws | identifier_name |
local-routing.js | 'use strict';
const psplit = require('../psplit');
/**
* Routes the mock API calls (from Lambda functions) into the AWS
* actions.
*
* @param {RouteMap} actionMap - the route entry from the api/route.js
* file, for a specific service name.
* @return {Object[]} list of { actionName, handler }.
*/
... | return ret;
};
function createHandler(p) {
var serviceName = p.serviceName;
var url = p.url;
var route = p.route;
return function(awsConfig, params, callback) {
console.log(`[local route ${serviceName}] calling ${route.Action} with params ${JSON.stringify(params)}`);
try {
var aws = c... | });
}
| random_line_split |
index.js | var height = window.innerHeight;
// console.log(height);
var main = document.getElementById('main');
var btn = document.getElementById("btn");
main.style.height = height + 'px';
btn.style.top = (height-90) + 'px';
document.getElementById('usr_name').onkeydown = function(e) {
e = e || event;
if(e.keyCode === 13) {
b... | ow.location.href;
var splited = url.split('/');
var roomID = splited[splited.length - 1];
ajax({
url: "/login/"+roomID, //请求地址
type: "POST", //请求方式
data: {new_topic:true,username: name}, //请求参数
dataType: "json",
success: function (data) {
data=JSON.parse(data);
... | {
alert("请填写用户名哦!");
return false;
}
var url = wind | conditional_block |
index.js | var height = window.innerHeight;
// console.log(height);
var main = document.getElementById('main');
var btn = document.getElementById("btn");
main.style.height = height + 'px';
btn.style.top = (height-90) + 'px';
document.getElementById('usr_name').onkeydown = function(e) {
e = e || event;
if(e.keyCode === 13) {
b... | dataType: "json",
success: function (data) {
data=JSON.parse(data);
if(data.status==1){
//alert("登录成功");
window.location.href="/show";
}
else if(data.status==0){
alert("已经有人登录了哦");
}
// 此处放成功后执行的代码
},
fail: function (status) {
// 此处放失败后执行的代码
}
});
}); | data: {new_topic:true,username: name}, //请求参数 | random_line_split |
lib.rs | //! # Feature gates
//!
//! This crate declares the set of past and present unstable features in the compiler.
//! Feature gate checking itself is done in `rustc_ast_passes/src/feature_gate.rs`
//! at the moment.
//!
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a co... | use std::num::NonZeroU32;
#[derive(Clone, Copy)]
pub enum State {
Accepted,
Active { set: fn(&mut Features, Span) },
Removed { reason: Option<&'static str> },
Stabilized { reason: Option<&'static str> },
}
impl fmt::Debug for State {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
... | #[cfg(test)]
mod tests;
use rustc_span::{edition::Edition, symbol::Symbol, Span};
use std::fmt; | random_line_split |
lib.rs | //! # Feature gates
//!
//! This crate declares the set of past and present unstable features in the compiler.
//! Feature gate checking itself is done in `rustc_ast_passes/src/feature_gate.rs`
//! at the moment.
//!
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a co... | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
State::Accepted { .. } => write!(f, "accepted"),
State::Active { .. } => write!(f, "active"),
State::Removed { .. } => write!(f, "removed"),
State::Stabilized { .. } => write!(f, "stabilized"),
... | fmt | identifier_name |
lib.rs | //! # Feature gates
//!
//! This crate declares the set of past and present unstable features in the compiler.
//! Feature gate checking itself is done in `rustc_ast_passes/src/feature_gate.rs`
//! at the moment.
//!
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a co... |
pub fn is_nightly_build(&self) -> bool {
match *self {
UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
UnstableFeatures::Disallow => false,
}
}
}
fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> {
if let Some(info) = ACTIVE_FEATURES.iter... | {
// `true` if this is a feature-staged build, i.e., on the beta or stable channel.
let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
// Returns whether `krate` should be counted as unstable
let is_unstable_crate = |var: &str| {
krate.map... | identifier_body |
demo.py | #!/usr/bin/python3
import sys
import getpass
import helper
from argparse import ArgumentParser
if __name__ == "__main__":
parser = ArgumentParser(description="Simple file password based encryption/decryption tools. When run as pipe, use standard in/out.")
parser.add_argument("-a", "--action", choices=["encrypt... |
else:
passwd = args.password
# setup params
inF = sys.stdin.buffer if not sys.stdin.isatty() else args.INPUT
if not sys.stdin.isatty():
args.OUTPUT = args.INPUT
outF = sys.stdout.buffer if not sys.stdout.isatty() or args.OUTPUT == "" else args.OUTPUT
if inF == "":
prin... | print("Password mismatch...")
exit() | conditional_block |
demo.py | #!/usr/bin/python3
import sys
import getpass
import helper
from argparse import ArgumentParser
if __name__ == "__main__":
parser = ArgumentParser(description="Simple file password based encryption/decryption tools. When run as pipe, use standard in/out.")
parser.add_argument("-a", "--action", choices=["encrypt... | args.OUTPUT = args.INPUT
outF = sys.stdout.buffer if not sys.stdout.isatty() or args.OUTPUT == "" else args.OUTPUT
if inF == "":
print("No input source provided...")
exit()
_log_out = None if outF is sys.stdout.buffer else sys.stdout
op_type = helper.Type.with_password
if ... | inF = sys.stdin.buffer if not sys.stdin.isatty() else args.INPUT
if not sys.stdin.isatty(): | random_line_split |
loginEvent.py | import userHelper
import serverPackets
import exceptions
import glob
import consoleHelper
import bcolors
import locationHelper
import countryHelper
import time
import generalFunctions
import channelJoinEvent
def | (flaskRequest):
# Data to return
responseTokenString = "ayy"
responseData = bytes()
# The IP for your private network, to get the right location you should use your
# public IP (e.g http://ping.eu)
localIP = "172.20.7.107" # The ip you log in with
publicIP = "8.8.8.8" # google lul
# Get IP from flask request
... | handle | identifier_name |
loginEvent.py | import userHelper
import serverPackets
import exceptions
import glob
import consoleHelper
import bcolors
import locationHelper
import countryHelper
import time
import generalFunctions
import channelJoinEvent
def handle(flaskRequest):
# Data to return
responseTokenString = "ayy"
responseData = bytes()
# The IP for ... | # Delete old tokens for that user and generate a new one
glob.tokens.deleteOldTokens(userID)
responseToken = glob.tokens.addToken(userID)
responseTokenString = responseToken.token
# Get silence end
userSilenceEnd = max(0, userHelper.getSilenceEnd(userID)-int(time.time()))
# Get supporter/GMT
userRank ... | userHelper.Activate(userID)
# No login errors! | random_line_split |
loginEvent.py | import userHelper
import serverPackets
import exceptions
import glob
import consoleHelper
import bcolors
import locationHelper
import countryHelper
import time
import generalFunctions
import channelJoinEvent
def handle(flaskRequest):
# Data to return
| print("> Processing login request for {}...".format(loginData[0]))
try:
# If true, print error to console
err = False
# Try to get the ID from username
userID = userHelper.getID(str(loginData[0]))
if userID == False:
# Invalid username
raise exceptions.loginFailedException()
if userHelper.checkLog... | responseTokenString = "ayy"
responseData = bytes()
# The IP for your private network, to get the right location you should use your
# public IP (e.g http://ping.eu)
localIP = "172.20.7.107" # The ip you log in with
publicIP = "8.8.8.8" # google lul
# Get IP from flask request
requestIP = flaskRequest.headers.ge... | identifier_body |
loginEvent.py | import userHelper
import serverPackets
import exceptions
import glob
import consoleHelper
import bcolors
import locationHelper
import countryHelper
import time
import generalFunctions
import channelJoinEvent
def handle(flaskRequest):
# Data to return
responseTokenString = "ayy"
responseData = bytes()
# The IP for ... |
# Send all needed login packets
responseToken.enqueue(serverPackets.silenceEndTime(userSilenceEnd))
responseToken.enqueue(serverPackets.userID(userID))
responseToken.enqueue(serverPackets.protocolVersion())
responseToken.enqueue(serverPackets.userSupporterGMT(userSupporter, userGMT))
responseToken.enqueue... | if userGMT == False:
# We are not mod/admin, delete token, send notification and logout
glob.tokens.deleteToken(responseTokenString)
raise exceptions.banchoMaintenanceException()
else:
# We are mod/admin, send warning notification and continue
responseToken.enqueue(serverPackets.notification("Ban... | conditional_block |
test_RrScore.py | import alpenglow as prs
import alpenglow.Getter as rs
import alpenglow.evaluation
import pandas as pd
import math
import unittest
class | (unittest.TestCase):
def test_rrScore(self):
ranks = [102, 102, 102, 102, 3, 4, 102, 9, 102, 102, 102, 9, 102, 102, 102, 6, 102, 102, 102, 102, 102, 102, 102, 1, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 12, 102, 1, 102, 102, 102, 1, 102, 102, 102, 102, 65, 1, 12, ... | TestRrScore | identifier_name |
test_RrScore.py | import alpenglow as prs
import alpenglow.Getter as rs
import alpenglow.evaluation
import pandas as pd
import math
import unittest
class TestRrScore(unittest.TestCase):
def test_rrScore(self): | ranks = [102, 102, 102, 102, 3, 4, 102, 9, 102, 102, 102, 9, 102, 102, 102, 6, 102, 102, 102, 102, 102, 102, 102, 1, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 12, 102, 1, 102, 102, 102, 1, 102, 102, 102, 102, 65, 1, 12, 12, 10, 102, 102, 102, 102, 102]
facRanki... | random_line_split | |
test_RrScore.py | import alpenglow as prs
import alpenglow.Getter as rs
import alpenglow.evaluation
import pandas as pd
import math
import unittest
class TestRrScore(unittest.TestCase):
def test_rrScore(self):
| ranks = [102, 102, 102, 102, 3, 4, 102, 9, 102, 102, 102, 9, 102, 102, 102, 6, 102, 102, 102, 102, 102, 102, 102, 1, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 12, 102, 1, 102, 102, 102, 1, 102, 102, 102, 102, 65, 1, 12, 12, 10, 102, 102, 102, 102, 102]
facRankings = pd... | identifier_body | |
widgets.py | that it should be
updated more often because it is time sensitive.
'''
TIME_SENSITIVE = False
@abc.abstractmethod
def update(self, pbar):
'''Updates the widget.
pbar - a reference to the calling ProgressBar
'''
class WidgetHFill(Widget):
'''The base class for all v... | return '%s%s%s' % (left, marked.ljust(width, self.fill), right) | conditional_block | |
widgets.py | absolute_import, with_statement
import datetime
import math
import abc
class AbstractWidget(object):
__metaclass__ = abc.ABCMeta
def format_updatable(updatable, pbar):
if hasattr(updatable, 'update'):
return updatable.update(pbar)
else:
return updatable
class Widget(AbstractWidget):
... |
class AdaptiveETA(ETA):
'''Widget which attempts to estimate the time of arrival.
Uses a sampled average of the speed based on the 10 last updates.
Very convenient for resuming the progress halfway.
'''
TIME_SENSITIVE = True
def __init__(self, num_samples=10, **kwargs):
ETA.__init_... | 'Widget which attempts to estimate the time of arrival.'
TIME_SENSITIVE = True
def _eta(self, pbar):
elapsed = pbar.seconds_elapsed
return elapsed * pbar.maxval / pbar.currval - elapsed
def update(self, pbar):
'Updates the widget to show the ETA or total time when finished.'
... | identifier_body |
widgets.py | absolute_import, with_statement
import datetime
import math
import abc
class AbstractWidget(object):
__metaclass__ = abc.ABCMeta
def format_updatable(updatable, pbar):
if hasattr(updatable, 'update'):
return updatable.update(pbar)
else:
return updatable
class Widget(AbstractWidget):
... | (Timer):
'Displays a formatted label'
mapping = {
'elapsed': ('seconds_elapsed', Timer.format_time),
'finished': ('finished', None),
'last_update': ('last_update_time', None),
'max': ('maxval', None),
'seconds': ('seconds_elapsed', None),
'start': ('start_time',... | FormatLabel | identifier_name |
widgets.py | '''Default ProgressBar widgets'''
from __future__ import division, absolute_import, with_statement
import datetime
import math
import abc
class AbstractWidget(object):
__metaclass__ = abc.ABCMeta
def format_updatable(updatable, pbar):
if hasattr(updatable, 'update'):
return updatable.update(pbar)
... | # You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
| random_line_split | |
createMiddleware.js | 'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
import isFunction from 'lodash.isfunction';
import isObject from 'lodash.isobject';
import { save as action... |
return function (_ref) {
var dispatch = _ref.dispatch,
getState = _ref.getState;
return function (next) {
return function (action) {
var result = next(action);
if (!isValidAction(action)) {
return result;
... | {
warnAboutConfusingFiltering(actionBlacklist, actionWhitelist);
} | conditional_block |
createMiddleware.js | 'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
import isFunction from 'lodash.isfunction';
import isObject from 'lodash.isobject';
import { save as action... |
function isValidAction(action) {
var isFunc = isFunction(action);
var isObj = isObject(action);
var hasType = isObj && action.hasOwnProperty('type');
if (!isFunc && isObj && hasType) {
return true;
}
if (process.env.NODE_ENV !== 'production') {
if (isFunc) {
conso... | {
blacklist.filter(function (item) {
return whitelist.indexOf(item) !== -1;
}).forEach(function (item) {
console.warn( // eslint-disable-line no-console
'[redux-storage] Action ' + item + ' is on BOTH black- and whitelist.' + ' This is most likely a mistake!');
});
} | identifier_body |
createMiddleware.js | 'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
import isFunction from 'lodash.isfunction';
import isObject from 'lodash.isobject';
import { save as action... | (action) {
var isFunc = isFunction(action);
var isObj = isObject(action);
var hasType = isObj && action.hasOwnProperty('type');
if (!isFunc && isObj && hasType) {
return true;
}
if (process.env.NODE_ENV !== 'production') {
if (isFunc) {
console.warn( // eslint-disab... | isValidAction | identifier_name |
createMiddleware.js | 'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
import isFunction from 'lodash.isfunction';
import isObject from 'lodash.isobject';
import { save as action... | var isObj = isObject(action);
var hasType = isObj && action.hasOwnProperty('type');
if (!isFunc && isObj && hasType) {
return true;
}
if (process.env.NODE_ENV !== 'production') {
if (isFunc) {
console.warn( // eslint-disable-line no-console
'[redux-storage] ... | });
}
function isValidAction(action) {
var isFunc = isFunction(action); | random_line_split |
error-page.component.spec.ts | // Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... | beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ErrorPageComponent, MockTranslatePipe],
providers: [
{
provide: I18nLanguageCodeService,
useClass: MockI18nLanguageCodeService
},
{ provide: TranslateService, useClass: MockTranslateSer... | random_line_split | |
error-page.component.spec.ts | // Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... |
}
let component: ErrorPageComponent;
let fixture: ComponentFixture<ErrorPageComponent>;
describe('Error page', () => {
let pageTitle = null;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ErrorPageComponent, MockTranslatePipe],
providers: [
{
provide: ... | {
return this.codeChangeEventEmiiter;
} | identifier_body |
error-page.component.spec.ts | // Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... | {
languageCode = 'es';
use(newLanguageCode: string): string {
this.languageCode = newLanguageCode;
return this.languageCode;
}
}
class MockI18nLanguageCodeService {
codeChangeEventEmiiter = new EventEmitter<string>();
getCurrentI18nLanguageCode() {
return 'en';
}
get onI18nLanguageCodeChang... | MockTranslateService | identifier_name |
nexus_binary2multistate.py | #!/usr/bin/env python
import sys
from nexus import NexusReader, VERSION
from nexus.tools import multistatise, combine_nexuses
__author__ = 'Simon Greenhill <simon@simon.net.nz>'
__doc__ = """nexus_binary2multistate - python-nexus tools v%(version)s
Converts binary nexuses to a multistate nexus.
""" % {'version': VERS... | parser.print_help()
sys.exit()
if options.output is not None:
outfile = options.output
else:
outfile = 'multistate.nex'
nexuslist2 = []
for nfile in nexuslist:
n = NexusReader(nfile)
n = multistatise(n)
nexuslist2.append(n)
... | print(__doc__) | random_line_split |
nexus_binary2multistate.py | #!/usr/bin/env python
import sys
from nexus import NexusReader, VERSION
from nexus.tools import multistatise, combine_nexuses
__author__ = 'Simon Greenhill <simon@simon.net.nz>'
__doc__ = """nexus_binary2multistate - python-nexus tools v%(version)s
Converts binary nexuses to a multistate nexus.
""" % {'version': VERS... |
if options.output is not None:
outfile = options.output
else:
outfile = 'multistate.nex'
nexuslist2 = []
for nfile in nexuslist:
n = NexusReader(nfile)
n = multistatise(n)
nexuslist2.append(n)
out = combine_nexuses(nexuslist2)
... | print(__doc__)
parser.print_help()
sys.exit() | conditional_block |
const-bound.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 ... | {
/*foo(1);
foo("hi".to_string());
foo(vec![1, 2, 3]);
foo(F{field: 42});
foo((1, 2));
foo(@1);*/
foo(Box::new(1));
} | identifier_body | |
const-bound.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 ... | { field: isize }
pub fn main() {
/*foo(1);
foo("hi".to_string());
foo(vec![1, 2, 3]);
foo(F{field: 42});
foo((1, 2));
foo(@1);*/
foo(Box::new(1));
}
| F | identifier_name |
results.py | from collections import defaultdict
from django import template
from django.utils.safestring import mark_safe
from censusreporter.apps.census.utils import parse_table_id, generic_table_description, table_link
register = template.Library()
@register.filter
def format_subtables_for_results(table_ids):
parts = [... | elif parsed['puerto_rico']:
deferred_pr.append(table)
else:
parts.append(table_link(table, generic_table_description(table)))
for table in deferred_pr:
parts.append(table_link(table, generic_table_description(table)))
racial_label_tests = [
('B', 'Detail... | random_line_split | |
results.py | from collections import defaultdict
from django import template
from django.utils.safestring import mark_safe
from censusreporter.apps.census.utils import parse_table_id, generic_table_description, table_link
register = template.Library()
@register.filter
def format_subtables_for_results(table_ids):
parts = [... |
except Exception as e:
parts.append(e.message)
return mark_safe(', '.join(parts))
| contents = ' / '.join(iteration_parts)
iter_wrapper = """
<a class="toggler" data-id="{}">{}</a>
<span data-id="{}" class='racial-iteration'>{}</span>
""".format(group_table_id, label, group_table_id, contents)
parts.append(iter_wrapper) | conditional_block |
results.py | from collections import defaultdict
from django import template
from django.utils.safestring import mark_safe
from censusreporter.apps.census.utils import parse_table_id, generic_table_description, table_link
register = template.Library()
@register.filter
def format_subtables_for_results(table_ids):
| ('C', 'Simplified (by race)'),
('BPR', 'Detailed (by race) for Puerto Rico'),
('CPR', 'Simplified (by race) for Puerto Rico'),
]
for test, label in racial_label_tests:
try:
iteration_parts = []
for table_dict in deferred_racials[test]:
ite... | parts = []
deferred_racials = defaultdict(list)
deferred_pr = []
for table in table_ids:
parsed = parse_table_id(table)
if parsed['racial']:
key = parsed['table_type']
if parsed['puerto_rico']:
key += 'PR'
deferred_racials[key].append(parse... | identifier_body |
results.py | from collections import defaultdict
from django import template
from django.utils.safestring import mark_safe
from censusreporter.apps.census.utils import parse_table_id, generic_table_description, table_link
register = template.Library()
@register.filter
def | (table_ids):
parts = []
deferred_racials = defaultdict(list)
deferred_pr = []
for table in table_ids:
parsed = parse_table_id(table)
if parsed['racial']:
key = parsed['table_type']
if parsed['puerto_rico']:
key += 'PR'
deferred_racials... | format_subtables_for_results | identifier_name |
constants.js | the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specifi... | "dataLists": "data-lists",
"event": "events",
"control": "control",
"sensing": "sensing",
"operators": "operators",
"more": "more"
};
/**
* ENUM representing that an event is not in any delete areas.
* Null for backwards compatibility reasons.
* @const
*/
Blockly.DELETE_AREA_NONE = null;
/**
* ENUM r... | "pen": "pen",
"data": "data", | random_line_split |
data_download.py | # [START all]
import argparse
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.client import GoogleCredentials
def | (project_id):
# [START build_service]
# Grab the application's default credentials from the environment.
credentials = GoogleCredentials.get_application_default()
# Construct the service object for interacting with the BigQuery API.
bigquery_service = build('bigquery', 'v2', credentials=credentials)... | main | identifier_name |
data_download.py | # [START all]
import argparse
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.client import GoogleCredentials
def main(project_id):
# [START build_service]
# Grab the application's default credentials from the environment.
credentials = GoogleCredentials.get... | query_data = {
'query':
"""
SELECT a.name, a.Total, a.Female, a.Male,
GREATEST(a.Male, a.Female) as confidence
FROM
(SELECT name, SUM(number) as Total,
SUM(CASE
WHEN gender = "F"
THEN number
ELSE 0
END)/Total as Female,
SUM(CASE
WHEN gender = "M"
THEN number
ELSE 0
END)... | query_request = bigquery_service.jobs() | random_line_split |
data_download.py | # [START all]
import argparse
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.client import GoogleCredentials
def main(project_id):
# [START build_service]
# Grab the application's default credentials from the environment.
credentials = GoogleCredentials.get... |
# [END print_results]
except HttpError as err:
print('Error: {}'.format(err.content))
raise err
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('project_id'... | print >> fp, '\t'.join(field['v'] for field in row['f']) | conditional_block |
data_download.py | # [START all]
import argparse
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.client import GoogleCredentials
def main(project_id):
# [START build_service]
# Grab the application's default credentials from the environment.
| SUM(CASE
WHEN gender = "M"
THEN number
ELSE 0
END)/Total as Male,
FROM [fh-bigquery:popular_names.usa_1910_2013] GROUP BY name) as a ORDER BY confidence DESC;
"""
}
query_response = query_request.query(
projectId=project_id,
body=query_data).execute()
... | credentials = GoogleCredentials.get_application_default()
# Construct the service object for interacting with the BigQuery API.
bigquery_service = build('bigquery', 'v2', credentials=credentials)
# [END build_service]
try:
# [START run_query]
query_request = bigquery_service.jobs()
... | identifier_body |
test_gjslint.py | import os
import sys
import nose
from subprocess import CalledProcessError, check_output as run
from functools import partial
GJSLINT_COMMAND = 'gjslint'
GJSLINT_OPTIONS = ['--strict']
JS_BASE_FOLDER = os.path.join('skylines', 'public', 'js')
JS_FILES = [
'baro.js',
'fix-table.js',
'flight.js',
'gen... | nose.run() | if __name__ == "__main__":
sys.argv.append(__name__) | random_line_split |
test_gjslint.py | import os
import sys
import nose
from subprocess import CalledProcessError, check_output as run
from functools import partial
GJSLINT_COMMAND = 'gjslint'
GJSLINT_OPTIONS = ['--strict']
JS_BASE_FOLDER = os.path.join('skylines', 'public', 'js')
JS_FILES = [
'baro.js',
'fix-table.js',
'flight.js',
'gen... | sys.argv.append(__name__)
nose.run() | conditional_block | |
test_gjslint.py | import os
import sys
import nose
from subprocess import CalledProcessError, check_output as run
from functools import partial
GJSLINT_COMMAND = 'gjslint'
GJSLINT_OPTIONS = ['--strict']
JS_BASE_FOLDER = os.path.join('skylines', 'public', 'js')
JS_FILES = [
'baro.js',
'fix-table.js',
'flight.js',
'gen... | (filename):
path = os.path.join(JS_BASE_FOLDER, filename)
args = [GJSLINT_COMMAND]
args.extend(GJSLINT_OPTIONS)
args.append(path)
try:
run(args)
except CalledProcessError, e:
print e.output
raise AssertionError('gjslint has found errors.')
except OSError:
ra... | run_gjslint | identifier_name |
test_gjslint.py | import os
import sys
import nose
from subprocess import CalledProcessError, check_output as run
from functools import partial
GJSLINT_COMMAND = 'gjslint'
GJSLINT_OPTIONS = ['--strict']
JS_BASE_FOLDER = os.path.join('skylines', 'public', 'js')
JS_FILES = [
'baro.js',
'fix-table.js',
'flight.js',
'gen... |
def run_gjslint(filename):
path = os.path.join(JS_BASE_FOLDER, filename)
args = [GJSLINT_COMMAND]
args.extend(GJSLINT_OPTIONS)
args.append(path)
try:
run(args)
except CalledProcessError, e:
print e.output
raise AssertionError('gjslint has found errors.')
except O... | for filename in JS_FILES:
f = partial(run_gjslint, filename)
f.description = 'gjslint {}'.format(filename)
yield f | identifier_body |
utils.ts | import { Atem } from "atem-connection";
import { AudioMixOption } from "atem-connection/dist/enums";
import { MULTI_VIEWER_INPUT } from "../server";
/**
* Apply initial state to the ATEM mixer.
*
* @param atem - ATEM mixer instance.
*/
export const applyInitialConfiguration = async (atem: Atem) => {
const afv = ... | await atem.setAudioMixerInputProps(3, { mixOption: afv });
await atem.setAudioMixerInputProps(4, { mixOption: afv });
} catch (e) {
console.log("got exception while setting audio mixer input props");
console.log(e);
}
await atem.setAuxSource(MULTI_VIEWER_INPUT, 2);
}; | random_line_split | |
internet.py | # coding=utf-8
from __future__ import unicode_literals
from ..internet import Provider as InternetProvider
class Provider(InternetProvider):
safe_email_tlds = ('com', 'net', 'fr', 'fr')
free_email_domains = (
'voila.fr', 'gmail.com', 'hotmail.fr', 'yahoo.fr', 'laposte.net', 'free.fr', 'sfr.fr', 'orange.fr... | mpany = self.generator.format('company')
company_elements = company.split(' ')
company = company_elements[0]
company = company.replace(" ", "")
return self._to_ascii(company).lower() |
co | identifier_name |
internet.py | # coding=utf-8
from __future__ import unicode_literals
from ..internet import Provider as InternetProvider
class Provider(InternetProvider):
safe_email_tlds = ('com', 'net', 'fr', 'fr')
free_email_domains = (
'voila.fr', 'gmail.com', 'hotmail.fr', 'yahoo.fr', 'laposte.net', 'free.fr', 'sfr.fr', 'orange.fr... | tring
def user_name(self):
pattern = self.random_element(self.user_name_formats)
return self._to_ascii(self.bothify(self.generator.parse(pattern))).lower()
def domain_word(self):
company = self.generator.format('company')
company_elements = company.split(' ')
company = ... | place(search, replace)
return s | conditional_block |
internet.py | from __future__ import unicode_literals
from ..internet import Provider as InternetProvider
class Provider(InternetProvider):
safe_email_tlds = ('com', 'net', 'fr', 'fr')
free_email_domains = (
'voila.fr', 'gmail.com', 'hotmail.fr', 'yahoo.fr', 'laposte.net', 'free.fr', 'sfr.fr', 'orange.fr', 'bouygtel.fr... | # coding=utf-8 | random_line_split | |
internet.py | # coding=utf-8
from __future__ import unicode_literals
from ..internet import Provider as InternetProvider
class Provider(InternetProvider):
| return self._to_ascii(self.bothify(self.generator.parse(pattern))).lower()
def domain_word(self):
company = self.generator.format('company')
company_elements = company.split(' ')
company = company_elements[0]
company = company.replace(" ", "")
return self._to_ascii(... | safe_email_tlds = ('com', 'net', 'fr', 'fr')
free_email_domains = (
'voila.fr', 'gmail.com', 'hotmail.fr', 'yahoo.fr', 'laposte.net', 'free.fr', 'sfr.fr', 'orange.fr', 'bouygtel.fr',
'club-internet.fr', 'dbmail.com', 'live.com', 'ifrance.com', 'noos.fr', 'tele2.fr', 'tiscali.fr', 'wanadoo.fr')
tlds = ('... | identifier_body |
attachSession.ts | /*
* This is an implementation of the Attach Session Driver Provider.
* It is responsible for setting up the account object, tearing
* it down, and setting up the driver correctly.
*/
import * as q from 'q';
import {Config} from '../config';
import {Logger} from '../logger';
import {DriverProvider} from './dri... |
/**
* Maintains the existing session and does not quit the driver.
*
* @public
*/
quitDriver(): q.Promise<webdriver.WebDriver> {
let defer = q.defer<webdriver.WebDriver>();
defer.resolve(null);
return defer.promise;
}
}
| {
var executor = executors.createExecutor(this.config_.seleniumAddress);
var newDriver = webdriver.WebDriver.attachToSession(
executor, this.config_.seleniumSessionId);
this.drivers_.push(newDriver);
return newDriver;
} | identifier_body |
attachSession.ts | /*
* This is an implementation of the Attach Session Driver Provider.
* It is responsible for setting up the account object, tearing
* it down, and setting up the driver correctly.
*/
import * as q from 'q';
import {Config} from '../config';
import {Logger} from '../logger';
import {DriverProvider} from './dri... | (): q.Promise<webdriver.WebDriver> {
let defer = q.defer<webdriver.WebDriver>();
defer.resolve(null);
return defer.promise;
}
}
| quitDriver | identifier_name |
attachSession.ts | /*
* This is an implementation of the Attach Session Driver Provider.
* It is responsible for setting up the account object, tearing
* it down, and setting up the driver correctly.
*/
import * as q from 'q';
import {Config} from '../config';
import {Logger} from '../logger';
import {DriverProvider} from './dri... | logger.info('Using the selenium server at ' + this.config_.seleniumAddress);
logger.info('Using session id - ' + this.config_.seleniumSessionId);
return q(undefined);
}
/**
* Getting a new driver by attaching an existing session.
*
* @public
* @return {WebDriver} webdriver instance
*/
... | random_line_split | |
htmlimageelement.rs | ThreadEventCategory::UpdateReplacedElement;
use script_thread::{CommonScriptMsg, Runnable, ScriptChan};
use std::sync::Arc;
use string_cache::Atom;
use url::Url;
use util::str::{DOMString, LengthOrPercentageOrAuto};
#[dom_struct]
pub struct HTMLImageElement {
htmlelement: HTMLElement,
url: DOMRefCell<Option<Ur... |
#[allow(unsafe_code)]
fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &atom!("width"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthO... | {
(*self.unsafe_get()).url.borrow_for_layout().clone()
} | identifier_body |
htmlimageelement.rs | = Some(img_url.clone());
let trusted_node = Trusted::new(self, window.networking_task_source());
let (responder_sender, responder_receiver) = ipc::channel().unwrap();
let script_chan = window.networking_task_source();
let wrapper = window.get_runnable_wr... | image_dimension_setter | identifier_name | |
htmlimageelement.rs | ThreadEventCategory::UpdateReplacedElement;
use script_thread::{CommonScriptMsg, Runnable, ScriptChan};
use std::sync::Arc;
use string_cache::Atom;
use url::Url;
use util::str::{DOMString, LengthOrPercentageOrAuto};
#[dom_struct]
pub struct HTMLImageElement {
htmlelement: HTMLElement,
url: DOMRefCell<Option<Ur... |
if let Some(h) = height {
image.SetHeight(h);
}
Ok(image)
}
}
pub trait LayoutHTMLImageElementHelpers {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>>;
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url>;
fn get_width(&self... | {
image.SetWidth(w);
} | conditional_block |
htmlimageelement.rs | ScriptThreadEventCategory::UpdateReplacedElement;
use script_thread::{CommonScriptMsg, Runnable, ScriptChan};
use std::sync::Arc;
use string_cache::Atom;
use url::Url;
use util::str::{DOMString, LengthOrPercentageOrAuto};
#[dom_struct]
pub struct HTMLImageElement {
htmlelement: HTMLElement,
url: DOMRefCell<Opt... | fn Height(&self) -> u32 {
let node = self.upcast::<Node>();
let rect = node.get_bounding_content_box();
rect.size.height.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn SetHeight(&self, value: u32) {
image_dimension_setter(self.upcast(), ato... | // https://html.spec.whatwg.org/multipage/#dom-img-height | random_line_split |
mock_network.py | from unittest.mock import Mock |
class MockNetwork(Network):
"""Mock implementation of the network interface for testing purposes."""
def __init__(self):
super().__init__()
self._session = Mock(requests.Session)
self._retries = []
def request(self, method, url, access_token, **kwargs):
"""Base class over... | import requests
from boxsdk.network.default_network import DefaultNetworkResponse
from boxsdk.network.network_interface import Network | random_line_split |
mock_network.py | from unittest.mock import Mock
import requests
from boxsdk.network.default_network import DefaultNetworkResponse
from boxsdk.network.network_interface import Network
class MockNetwork(Network):
"""Mock implementation of the network interface for testing purposes."""
def | (self):
super().__init__()
self._session = Mock(requests.Session)
self._retries = []
def request(self, method, url, access_token, **kwargs):
"""Base class override.
Make a mock network request using a mock requests.Session.
"""
return DefaultNetworkResponse(s... | __init__ | identifier_name |
mock_network.py | from unittest.mock import Mock
import requests
from boxsdk.network.default_network import DefaultNetworkResponse
from boxsdk.network.network_interface import Network
class MockNetwork(Network):
"""Mock implementation of the network interface for testing purposes."""
def __init__(self):
super().__init... | return self._session | identifier_body | |
bmu.py | #!/usr/bin/env python
import json
import numpy
import scipy.sparse as sp
from optparse import OptionParser
__author__ = "Gregory Ditzler"
__copyright__ = "Copyright 2014, EESI Laboratory (Drexel University)"
__credits__ = ["Gregory Ditzler"]
__license__ = "GPL"
__version__ = "0.1.0"
__maintainer__ = "Gregory Ditzler... |
def load_sparse(obj):
"""
load a biom file in sparse format
:obj - json dictionary from biom file
:data - dense data matrix
"""
n_feat,n_sample = obj["shape"]
data = numpy.zeros((n_feat, n_sample),order="F")
for val in obj["data"]:
data[val[0], val[1]] = val[2]
data = data.transpose()
return... | """
load a biom file in dense format
:obj - json dictionary from biom file
:data - dense data matrix
"""
n_feat,n_sample = obj["shape"]
data = np.array(obj["data"], order="F")
return data.transpose() | identifier_body |
bmu.py | #!/usr/bin/env python
import json
import numpy
import scipy.sparse as sp
from optparse import OptionParser
__author__ = "Gregory Ditzler"
__copyright__ = "Copyright 2014, EESI Laboratory (Drexel University)"
__credits__ = ["Gregory Ditzler"]
__license__ = "GPL"
__version__ = "0.1.0"
__maintainer__ = "Gregory Ditzler... |
data = data.transpose()
return data
def load_map(fname):
"""
load a map file. this function does not have any dependecies on qiime's
tools. the returned object is a dictionary of dictionaries. the dictionary
is indexed by the sample_ID and there is an added field for the the
available meta-data. each... | data[val[0], val[1]] = val[2] | conditional_block |
bmu.py | #!/usr/bin/env python
import json
import numpy
import scipy.sparse as sp
from optparse import OptionParser
__author__ = "Gregory Ditzler"
__copyright__ = "Copyright 2014, EESI Laboratory (Drexel University)"
__credits__ = ["Gregory Ditzler"]
__license__ = "GPL"
__version__ = "0.1.0"
__maintainer__ = "Gregory Ditzler... | (obj):
"""
load a biom file in sparse format
:obj - json dictionary from biom file
:data - dense data matrix
"""
n_feat,n_sample = obj["shape"]
data = numpy.zeros((n_feat, n_sample),order="F")
for val in obj["data"]:
data[val[0], val[1]] = val[2]
data = data.transpose()
return data
def load_m... | load_sparse | identifier_name |
bmu.py | #!/usr/bin/env python
import json
import numpy
import scipy.sparse as sp
from optparse import OptionParser
__author__ = "Gregory Ditzler"
__copyright__ = "Copyright 2014, EESI Laboratory (Drexel University)"
__credits__ = ["Gregory Ditzler"]
__license__ = "GPL" | __version__ = "0.1.0"
__maintainer__ = "Gregory Ditzler"
__email__ = "gregory.ditzler@gmail.com"
def load_biom(fname):
"""
load a biom file and return a dense matrix
:fname - string containing the path to the biom file
:data - numpy array containing the OTU matrix
:samples - list containing the sample IDs (... | random_line_split | |
affix.js | $(function () {
'use strict';
module('affix plugin')
test('should be defined on jquery object', function () {
ok($(document.body).affix, 'affix method is defined')
})
module('affix', {
setup: function () {
// Run all tests in noConflict mode -- it's the only way to ensure that the plugin work... | })
test('should trigger affixed event after affix', function () {
stop()
var templateHTML = '<div id="affixTarget">'
+ '<ul>'
+ '<li>Please affix</li>'
+ '<li>And unaffix</li>'
+ '</ul>'
+ '</div>'
+ '<div id="affixAfter" style="height: 20000px; display: blo... | ok(!$affix.hasClass('affix'), 'affix class was not added') | random_line_split |
activations.py | from __future__ import absolute_import
import six
import warnings
from . import backend as K
from .utils.generic_utils import deserialize_keras_object
from .engine import Layer
def softmax(x, axis=-1):
"""Softmax activation function.
# Arguments
x : Tensor.
axis: Integer, axis along which the... |
def softplus(x):
return K.softplus(x)
def softsign(x):
return K.softsign(x)
def relu(x, alpha=0., max_value=None):
return K.relu(x, alpha=alpha, max_value=max_value)
def tanh(x):
return K.tanh(x)
def sigmoid(x):
return K.sigmoid(x)
def hard_sigmoid(x):
return K.hard_sigmoid(x)
def... | """Scaled Exponential Linear Unit. (Klambauer et al., 2017)
# Arguments
x: A tensor or variable to compute the activation function for.
# References
- [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)
"""
alpha = 1.6732632423543772848170429916717
scale = 1.050700... | identifier_body |
activations.py | from __future__ import absolute_import
import six
import warnings
from . import backend as K
from .utils.generic_utils import deserialize_keras_object
from .engine import Layer
def softmax(x, axis=-1):
"""Softmax activation function.
# Arguments
x : Tensor.
axis: Integer, axis along which the... |
def selu(x):
"""Scaled Exponential Linear Unit. (Klambauer et al., 2017)
# Arguments
x: A tensor or variable to compute the activation function for.
# References
- [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)
"""
alpha = 1.6732632423543772848170429916717
... | return K.elu(x, alpha) | random_line_split |
activations.py | from __future__ import absolute_import
import six
import warnings
from . import backend as K
from .utils.generic_utils import deserialize_keras_object
from .engine import Layer
def softmax(x, axis=-1):
"""Softmax activation function.
# Arguments
x : Tensor.
axis: Integer, axis along which the... |
else:
raise ValueError('Cannot apply softmax to a tensor that is 1D')
def elu(x, alpha=1.0):
return K.elu(x, alpha)
def selu(x):
"""Scaled Exponential Linear Unit. (Klambauer et al., 2017)
# Arguments
x: A tensor or variable to compute the activation function for.
# References... | e = K.exp(x - K.max(x, axis=axis, keepdims=True))
s = K.sum(e, axis=axis, keepdims=True)
return e / s | conditional_block |
activations.py | from __future__ import absolute_import
import six
import warnings
from . import backend as K
from .utils.generic_utils import deserialize_keras_object
from .engine import Layer
def softmax(x, axis=-1):
"""Softmax activation function.
# Arguments
x : Tensor.
axis: Integer, axis along which the... | (activation):
return activation.__name__
def deserialize(name, custom_objects=None):
return deserialize_keras_object(name,
module_objects=globals(),
custom_objects=custom_objects,
printable_module_name=... | serialize | identifier_name |
gulpfile.js | var gulp = require('gulp');
var plumber = require('gulp-plumber');
var notify = require('gulp-notify');
var gutil = require('gulp-util');
var gulpsass = require('gulp-sass');
var cssnano = require('gulp-cssnano');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-s... | });
gulp.task('watch', function() {
gulp.watch('my_project/assets/sass/*.scss', ['sass']);
gulp.watch('my_project/assets/js/*.js', ['js']);
gulp.watch('my_project/assets/images/*', ['img']);
gulp.watch('my_project/**/*.php').on('change', browsersync.reload);
});
gulp.task('default', ['sass', 'js', 'im... |
gulp.task('browser-sync', function() {
browsersync.init({
proxy: 'localhost/project_setup/my_project'
}); | random_line_split |
gulpfile.js | var gulp = require('gulp');
var plumber = require('gulp-plumber');
var notify = require('gulp-notify');
var gutil = require('gulp-util');
var gulpsass = require('gulp-sass');
var cssnano = require('gulp-cssnano');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-s... |
console.error(report);
// Prevent the 'watch' task from stopping
this.emit('end');
};
gulp.task('sass', function() {
return gulp.src('my_project/assets/sass/i.scss')
.pipe(plumber({
errorHandler: reportError
}))
.pipe(sourcemaps.init())
.pipe(gulpsass())
.pip... | { report += chalk('FILE:') + ' ' + error.fileName + '\n'; } | conditional_block |
test_prettyprint.py | # -*- coding: utf-8 -*-
# This file is part of Gtfslib-python.
#
# Gtfslib-python 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... | csv.writerow([ 1 ])
csv.writerow([ None, 1.42 ])
csv.writerow([ None, 1./3., math.pi ])
output3 = out.getvalue().strip()
finally:
sys.stdout = saved_stdout
self.assertEqual("+------+-------+-------+\n"+
"|... | aved_stdout = sys.stdout
try:
out = six.StringIO()
sys.stdout = out
with PrettyCsv(None, fieldnames=[ 'col1', 'col2' ], maxwidth=5) as csv:
csv.writerow({ 'col1': 1, 'col2': 2 })
csv.writerow({ 'col2': 'foobarbaz', 'col1': 11 })
... | identifier_body |
test_prettyprint.py | # -*- coding: utf-8 -*-
# This file is part of Gtfslib-python.
#
# Gtfslib-python 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... | self):
# Capture standard output
saved_stdout = sys.stdout
try:
out = six.StringIO()
sys.stdout = out
with PrettyCsv(None, fieldnames=[ 'col1', 'col2' ], maxwidth=5) as csv:
csv.writerow({ 'col1': 1, 'col2': 2 })
csv.writerow({ ... | est_prettyprinter( | identifier_name |
test_prettyprint.py | # -*- coding: utf-8 -*-
# This file is part of Gtfslib-python.
#
# Gtfslib-python 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... | nittest.main()
| conditional_block | |
test_prettyprint.py | # -*- coding: utf-8 -*-
# This file is part of Gtfslib-python.
#
# Gtfslib-python is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with gtfslib-python. If not, see <http://www.gnu.org/licenses/>.
"""
@author: Laurent GRÉGOIRE <laurent.gregoire@mecat... | # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Gtfslib-python is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
574A_bear.py | #!/usr/bin/env python3
# 574A_bear.py - Codeforces.com/problemset/problem/574/A Bear program by Sergey 2015
import unittest
import sys
###############################################################################
# Bear Class
###############################################################################
class Be... | (unittest.TestCase):
def test_single_test(self):
""" Bear class testing """
# Constructor test
test = "5\n5 1 11 2 8"
d = Bear(test)
self.assertEqual(d.n, 5)
self.assertEqual(d.nums, [5, 1, 11, 2, 8])
# Sample test
self.assertEqual(Bear(test).calcul... | unitTests | identifier_name |
574A_bear.py | #!/usr/bin/env python3
# 574A_bear.py - Codeforces.com/problemset/problem/574/A Bear program by Sergey 2015
import unittest
import sys
###############################################################################
# Bear Class
###############################################################################
class Be... |
# Reading single elements
self.n = int(uinput())
# Reading a single line of multiple elements
self.nums = list(map(int, uinput().split()))
def calculate(self):
""" Main calcualtion function of the class """
lamak = self.nums[0]
srt = sorted(self.nums[1:])
... | return next(it) if it else sys.stdin.readline().rstrip() | random_line_split |
574A_bear.py | #!/usr/bin/env python3
# 574A_bear.py - Codeforces.com/problemset/problem/574/A Bear program by Sergey 2015
import unittest
import sys
###############################################################################
# Bear Class
###############################################################################
class Be... |
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
sys.stdout.write(Bear().calculate())
| """ Timelimit testing """
import random
import timeit
# Random inputs
test = str(nmax) + "\n"
test += "0 "
nums = [1000 for i in range(nmax-1)]
test += " ".join(map(str, nums)) + "\n"
# Run the test
start = timeit.default_timer()
d = Bear... | identifier_body |
574A_bear.py | #!/usr/bin/env python3
# 574A_bear.py - Codeforces.com/problemset/problem/574/A Bear program by Sergey 2015
import unittest
import sys
###############################################################################
# Bear Class
###############################################################################
class Be... | sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
sys.stdout.write(Bear().calculate()) | conditional_block | |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | """Xedit is a simple text editor for X."""
homepage = "https://cgit.freedesktop.org/xorg/app/xedit"
url = "https://www.x.org/archive/individual/app/xedit-1.2.2.tar.gz"
version('1.2.2', '9fb9d6f63b574e5a4937384fbe6579c1')
depends_on('libxaw')
depends_on('libxmu')
depends_on('libxt@1.0:')
... | identifier_body | |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | (AutotoolsPackage):
"""Xedit is a simple text editor for X."""
homepage = "https://cgit.freedesktop.org/xorg/app/xedit"
url = "https://www.x.org/archive/individual/app/xedit-1.2.2.tar.gz"
version('1.2.2', '9fb9d6f63b574e5a4937384fbe6579c1')
depends_on('libxaw')
depends_on('libxmu')
d... | Xedit | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.