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 |
|---|---|---|---|---|
check_key_import.py | '''Manual check (not a discoverable unit test) for the key import,
to identify problems with gnupg, gpg, gpg1, gpg2 and so on'''
import os
import shutil
from gnupg import GPG
def setup_keyring(keyring_name):
|
CRYPTO = setup_keyring("keyringtest")
if CRYPTO:
print("Ready", CRYPTO)
KEY_LIST = CRYPTO.list_keys(False)
NUM_KEYS = len(KEY_LIST) if KEY_LIST else 0
print("Number of public keys:", NUM_KEYS)
if NUM_KEYS < 1:
print("ERROR: Number of keys should be 1, not", NUM_KEYS)
KEY_LIST = CRYPTO.list_keys(True)
NUM_KEYS... | '''Setup the keyring'''
keyring_path = os.path.join("test", "outputdata", keyring_name)
# Delete the entire keyring
shutil.rmtree(keyring_path, ignore_errors=True)
os.makedirs(keyring_path)
gpg = GPG(gnupghome=keyring_path, gpgbinary="gpg")
for key_name in ["key1_private", "key1_public"]:
... | identifier_body |
check_key_import.py | '''Manual check (not a discoverable unit test) for the key import,
to identify problems with gnupg, gpg, gpg1, gpg2 and so on'''
import os
import shutil
from gnupg import GPG
def | (keyring_name):
'''Setup the keyring'''
keyring_path = os.path.join("test", "outputdata", keyring_name)
# Delete the entire keyring
shutil.rmtree(keyring_path, ignore_errors=True)
os.makedirs(keyring_path)
gpg = GPG(gnupghome=keyring_path, gpgbinary="gpg")
for key_name in ["key1_private", "k... | setup_keyring | identifier_name |
check_key_import.py | '''Manual check (not a discoverable unit test) for the key import,
to identify problems with gnupg, gpg, gpg1, gpg2 and so on'''
import os
import shutil
from gnupg import GPG
def setup_keyring(keyring_name):
'''Setup the keyring'''
keyring_path = os.path.join("test", "outputdata", keyring_name)
# Delet... | print("Number of private keys:", NUM_KEYS)
if NUM_KEYS < 1:
print("ERROR: Number of keys should be 1, not", NUM_KEYS) | NUM_KEYS = len(KEY_LIST) if KEY_LIST else 0 | random_line_split |
gated-quote.rs | // Copyright 2015 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 ecx = &ParseSess;
let x = quote_tokens!(ecx, 3); //~ ERROR macro undefined: 'quote_tokens!'
let x = quote_expr!(ecx, 3); //~ ERROR macro undefined: 'quote_expr!'
let x = quote_ty!(ecx, 3); //~ ERROR macro undefined: 'quote_ty!'
let x = quote_method!(ecx, 3); //~ ERROR macro undef... | identifier_body | |
gated-quote.rs | // Copyright 2015 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 ... | <'a>(&'a self) -> &'a parse::ParseSess { loop { } }
fn call_site(&self) -> Span { loop { } }
fn ident_of(&self, st: &str) -> ast::Ident { loop { } }
fn name_of(&self, st: &str) -> ast::Name { loop { } }
}
pub fn main() {
let ecx = &ParseSess;
let x = quote_tokens!(ecx, 3); //~ ERROR macro undefin... | parse_sess | identifier_name |
gated-quote.rs | // Copyright 2015 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 ... |
use syntax::ast;
use syntax::codemap::Span;
use syntax::parse;
struct ParseSess;
impl ParseSess {
fn cfg(&self) -> ast::CrateConfig { loop { } }
fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess { loop { } }
fn call_site(&self) -> Span { loop { } }
fn ident_of(&self, st: &str) -> ast::Ident { loop ... | #![allow(dead_code, unused_imports, unused_variables)]
#[macro_use]
extern crate syntax; | random_line_split |
lib.rs | // Copyright 2017 James Duley
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... | without_name
}
fn extract_tied_operands(
pos_and_tts: (usize, Vec<TokenTree>),
) -> (Vec<TokenTree>, Option<Vec<TokenTree>>) {
{
let constraint = get_string_literal(pos_and_tts.1.first().expect("error: empty operand"));
if constraint.starts_with("+") {
let lvalue = pos_and_tts.... | {
let name_and_remaining = match *tts.first().expect("error: empty operand") {
TokenTree::Delimited(ref d) => {
assert!(d.delim == DelimToken::Bracket, "error: bad operand");
let name = if d.tts.len() == 1usize {
match d.tts[0] {
TokenTree::Token(T... | identifier_body |
lib.rs | // Copyright 2017 James Duley
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... | use syn::{parse_token_trees, Token, TokenTree, Lit, DelimToken, StrStyle};
#[proc_macro]
pub fn gcc_asm(token_stream: TokenStream) -> TokenStream {
let tokens = token_stream.to_string();
let token_trees = parse_token_trees(&tokens).unwrap();
let mut parts = split_on_token(token_trees.as_slice(), &Token::Co... | #[macro_use]
extern crate quote;
use proc_macro::TokenStream;
use std::str::FromStr; | random_line_split |
lib.rs | // Copyright 2017 James Duley
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... | (token_stream: TokenStream) -> TokenStream {
let tokens = token_stream.to_string();
let token_trees = parse_token_trees(&tokens).unwrap();
let mut parts = split_on_token(token_trees.as_slice(), &Token::Colon);
let template = parts
.next()
.expect("error: template missing")
.iter... | gcc_asm | identifier_name |
scan.rs | #![feature(core, unboxed_closures)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::Scan;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item... |
None => { assert!(false); }
}
}
assert_eq!(scan.next(), None::<B>);
}
}
| { assert_eq!(v, n * (n + 1) / 2); } | conditional_block |
scan.rs | #![feature(core, unboxed_closures)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::Scan;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item... | (&mut self, (st, item): Args) -> Self::Output {
*st += item;
Some::<B>(*st)
}
}
#[test]
fn scan_test1() {
let a: A<T> = A { begin: 0, end: 10 };
let st: St = 0;
let f: F = F;
let mut scan: Scan<A<T>, B, F> = a.scan::<St, B, F>(st, f);
for n in 0..10 {
let x: Option<B> = scan.next();
... | call_mut | identifier_name |
scan.rs | #![feature(core, unboxed_closures)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::Scan;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item... | Some::<B>(*st)
}
}
#[test]
fn scan_test1() {
let a: A<T> = A { begin: 0, end: 10 };
let st: St = 0;
let f: F = F;
let mut scan: Scan<A<T>, B, F> = a.scan::<St, B, F>(st, f);
for n in 0..10 {
let x: Option<B> = scan.next();
match x {
Some(v) => { assert_eq!(v, n * (n + 1) / 2); }
... | random_line_split | |
index.stories.tsx | /*
import * as React from 'react'
import * as Kb from '../../../common-adapters'
import * as Sb from '../../../stories/storybook'
import * as RPCChatTypes from '../../../constants/types/rpc-chat-gen' |
import CommandStatus from '.'
const errorProps = {
actions: [],
displayText: 'Failed to send message.',
displayType: RPCChatTypes.UICommandStatusDisplayTyp.error,
onCancel: Sb.action('onCancel'),
}
const warningProps = {
...errorProps,
displayType: RPCChatTypes.UICommandStatusDisplayTyp.warning,
}
const... | random_line_split | |
acquire_pessimistic_lock.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::kvrpcpb::{ExtraOp, LockInfo};
use txn_types::{Key, OldValues, TimeStamp, TxnExtra};
use crate::storage::kv::WriteData;
use crate::storage::lock_manager::{LockManager, WaitTimeout};
use crate::storage::mvcc::{
Error as MvccError, Error... |
}
context.statistics.add(&reader.take_statistics());
// no conflict
let (pr, to_be_write, rows, ctx, lock_info) = if res.is_ok() {
let pr = ProcessResult::PessimisticLockRes { res };
let extra = TxnExtra {
old_values: self.old_values,
... | {
txn.concurrency_manager.update_max_ts(self.for_update_ts);
} | conditional_block |
acquire_pessimistic_lock.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::kvrpcpb::{ExtraOp, LockInfo};
use txn_types::{Key, OldValues, TimeStamp, TxnExtra};
use crate::storage::kv::WriteData;
use crate::storage::lock_manager::{LockManager, WaitTimeout};
use crate::storage::mvcc::{
Error as MvccError, Error... |
fn write_bytes(&self) -> usize {
self.keys
.iter()
.map(|(key, _)| key.as_encoded().len())
.sum()
}
gen_lock!(keys: multiple(|x| &x.0));
}
fn extract_lock_info_from_result<T>(res: &StorageResult<T>) -> &LockInfo {
match res {
Err(StorageError(box St... | command_method!(can_be_pipelined, bool, true); | random_line_split |
acquire_pessimistic_lock.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::kvrpcpb::{ExtraOp, LockInfo};
use txn_types::{Key, OldValues, TimeStamp, TxnExtra};
use crate::storage::kv::WriteData;
use crate::storage::lock_manager::{LockManager, WaitTimeout};
use crate::storage::mvcc::{
Error as MvccError, Error... | (&self) -> usize {
self.keys
.iter()
.map(|(key, _)| key.as_encoded().len())
.sum()
}
gen_lock!(keys: multiple(|x| &x.0));
}
fn extract_lock_info_from_result<T>(res: &StorageResult<T>) -> &LockInfo {
match res {
Err(StorageError(box StorageErrorInner::Tx... | write_bytes | identifier_name |
acquire_pessimistic_lock.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::kvrpcpb::{ExtraOp, LockInfo};
use txn_types::{Key, OldValues, TimeStamp, TxnExtra};
use crate::storage::kv::WriteData;
use crate::storage::lock_manager::{LockManager, WaitTimeout};
use crate::storage::mvcc::{
Error as MvccError, Error... |
gen_lock!(keys: multiple(|x| &x.0));
}
fn extract_lock_info_from_result<T>(res: &StorageResult<T>) -> &LockInfo {
match res {
Err(StorageError(box StorageErrorInner::Txn(Error(box ErrorInner::Mvcc(MvccError(
box MvccErrorInner::KeyIsLocked(info),
)))))) => info,
_ => panic... | {
self.keys
.iter()
.map(|(key, _)| key.as_encoded().len())
.sum()
} | identifier_body |
preset.js | var winston = require('winston');
var fs = require('fs');
var presets = {};
function | (player, values, callback) {
var value = decodeURIComponent(values[0]);
if (value.startsWith('{'))
var preset = JSON.parse(value);
else
var preset = presets[value];
if (preset) {
winston.info("Preset found: ", preset);
player.discovery.applyPreset(preset, function (err, result) {
if (err)... | presetsAction | identifier_name |
preset.js | var winston = require('winston');
var fs = require('fs');
var presets = {};
function presetsAction(player, values, callback) {
var value = decodeURIComponent(values[0]);
if (value.startsWith('{'))
var preset = JSON.parse(value);
else
var preset = presets[value];
if (preset) {
winston.info("Preset ... | } else {
winston.info("Playing ", preset);
}
});
} else {
winston.error("No preset found...");
var simplePresets = [];
for (var key in presets) {
if (presets.hasOwnProperty(key)) {
simplePresets.push(key);
}
}
callback(simplePresets);
}
}
function initPr... | random_line_split | |
preset.js | var winston = require('winston');
var fs = require('fs');
var presets = {};
function presetsAction(player, values, callback) {
var value = decodeURIComponent(values[0]);
if (value.startsWith('{'))
var preset = JSON.parse(value);
else
var preset = presets[value];
if (preset) {
winston.info("Preset ... |
module.exports = function (api) {
initPresets(api);
} | {
var presetsFilename = __dirname + '/../../presets.json';
fs.exists(presetsFilename, function (exists) {
if (exists) {
presets = require(presetsFilename);
winston.info('loaded presets', presets);
} else {
winston.info('no preset file, ignoring...');
}
api.registerAction('preset', ... | identifier_body |
preset.js | var winston = require('winston');
var fs = require('fs');
var presets = {};
function presetsAction(player, values, callback) {
var value = decodeURIComponent(values[0]);
if (value.startsWith('{'))
var preset = JSON.parse(value);
else
var preset = presets[value];
if (preset) {
winston.info("Preset ... |
}
callback(simplePresets);
}
}
function initPresets(api) {
var presetsFilename = __dirname + '/../../presets.json';
fs.exists(presetsFilename, function (exists) {
if (exists) {
presets = require(presetsFilename);
winston.info('loaded presets', presets);
} else {
winston.info('n... | {
simplePresets.push(key);
} | conditional_block |
Key.js | === undefined) {
throw new TypeError('Could not copy the bytes held by a buffer source as the buffer was undefined.');
}
offset = O.byteOffset; // [[ByteOffset]] (will also throw as desired if detached)
length = O.byteLength; // [[ByteLength]] (will also throw as desired if detached... | {
let lowerMatch = range.lower === undefined;
let upperMatch = range.upper === undefined;
const encodedKey = encode(key, true);
const lower = checkCached ? range.__lowerCached : encode(range.lower, true);
const upper = checkCached ? range.__upperCached : encode(range.upper, true);
if (range.low... | identifier_body | |
Key.js | negate(exponent);
mantissa = flipBase32(mantissa);
return -pow32(mantissa, exponent);
case 'bigNegative':
exponent = flipBase32(exponent);
mantissa = flipBase32(mantissa);
return -pow32(mantissa, exponent);
default:... |
return flipped;
}
/**
* Base-32 power function.
* RESEARCH: This function does not precisely decode floats because it performs
* floating point arithmetic to recover values. But can the original values be
* recovered exactly?
* Someone may have already figured out a good way to store JavaScript floats as
* ... | {
flipped += (31 - parseInt(encoded[i], 32)).toString(32);
} | conditional_block |
Key.js | keys.push(fullKeys ? key : key.value);
}
} catch (err) {
if (!multiEntry) {
throw err;
}
}
}
return {type, value: keys};
} case 'date': {
if (!Number.isNaN(input.getTime())) {
return full... | // array, date, number, string, binary (should already have detected "invalid")
return types[getKeyType(key)].encode(key, inArray);
} | random_line_split | |
Key.js | negate(exponent);
mantissa = flipBase32(mantissa);
return -pow32(mantissa, exponent);
case 'bigNegative':
exponent = flipBase32(exponent);
mantissa = flipBase32(mantissa);
return -pow32(mantissa, exponent);
default:... | (s) {
return '-' + s;
}
/**
* Returns the string "number", "date", "string", "binary", or "array"
*/
function getKeyType (key) {
if (Array.isArray(key)) return 'array';
if (util.isDate(key)) return 'date';
if (util.isBinary(key)) return 'binary';
const keyType = typeof key;
return ['string',... | negate | identifier_name |
lib.rs | //! pokereval-rs currently contains a single way of evaluating poker hands (5,6 or 7 cards)
//! to a HandRank, which is a number from 0 to 7461 inclusive, the higher the better the hand.
//! Inside the modules, there are more efficient methods that don't need to convert cards
//! to internal representations first.
ext... | (cards: &[&Card; 6]) -> HandRank {
let c1 = card_to_deck_number(cards[0]);
let c2 = card_to_deck_number(cards[1]);
let c3 = card_to_deck_number(cards[2]);
let c4 = card_to_deck_number(cards[3]);
let c5 = card_to_deck_number(cards[4]);
let c6 = card_to_deck_number(cards[5]);
let converted_ca... | eval_6cards | identifier_name |
lib.rs | //! pokereval-rs currently contains a single way of evaluating poker hands (5,6 or 7 cards)
//! to a HandRank, which is a number from 0 to 7461 inclusive, the higher the better the hand.
//! Inside the modules, there are more efficient methods that don't need to convert cards
//! to internal representations first.
ext... | pub mod original;
//mod perfect;
pub mod utils;
use cards::card::{Card};
use holdem::{HandRank};
use utils::{card_to_deck_number};
/// Evalate a hand consisting of 5 cards. The cards are grouped in an array.
/// This is quite inefficient, due to the arrays that need to be created. But convenient.
pub fn eval_5cards(c... | random_line_split | |
lib.rs | //! pokereval-rs currently contains a single way of evaluating poker hands (5,6 or 7 cards)
//! to a HandRank, which is a number from 0 to 7461 inclusive, the higher the better the hand.
//! Inside the modules, there are more efficient methods that don't need to convert cards
//! to internal representations first.
ext... |
/// Evalate a hand consisting of 7 cards. The cards are grouped in an array.
/// This is quite inefficient, due to the arrays that need to be created. But convenient.
pub fn eval_7cards(cards: &[&Card; 7]) -> HandRank {
let c1 = card_to_deck_number(cards[0]);
let c2 = card_to_deck_number(cards[1]);
let c3... | {
let c1 = card_to_deck_number(cards[0]);
let c2 = card_to_deck_number(cards[1]);
let c3 = card_to_deck_number(cards[2]);
let c4 = card_to_deck_number(cards[3]);
let c5 = card_to_deck_number(cards[4]);
let c6 = card_to_deck_number(cards[5]);
let converted_cards = [&c1, &c2, &c3, &c4, &c5, &... | identifier_body |
object.ts | /**
* Copyright 2019 OpenCensus Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or ... | * limitations under the License.
*/
import {
Exporter,
ExporterBuffer,
ExporterConfig,
Span,
} from '@opencensus/core';
import { logger, Logger } from '@opencensus/core';
/** Object Exporter manager class */
export class ObjectTraceExporter implements Exporter {
buffer: ExporterBuffer;
logger: Logger;
... | * See the License for the specific language governing permissions and | random_line_split |
object.ts | /**
* Copyright 2019 OpenCensus Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or ... |
/**
* Is called whenever a span is ended.
* @param span the ended span
*/
onEndSpan(span: Span) {
this.endedSpans.push(span);
this.buffer.addToBuffer(span);
}
/**
* Send the spans to memory store.
* @param spans The list of spans to transmit to memory.
*/
publish(spans: Span[]): P... | {
this.startedSpans.push(span);
} | identifier_body |
object.ts | /**
* Copyright 2019 OpenCensus Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or ... | () {
this.startedSpans = [];
this.endedSpans = [];
this.publishedSpans = [];
}
}
| reset | identifier_name |
conanfile.py | from conans import ConanFile, AutoToolsBuildEnvironment, tools
import os
class LibHaruConn(ConanFile):
name = "libharu"
version = "2.3.0"
license = "ZLIB https://github.com/libharu/libharu/blob/master/LICENCE"
url = "https://github.com/trigger-happy/conan-packages"
description = "C library for gene... |
def package(self):
self.copy("lib/*", dst="lib", keep_path=False)
self.copy("include/*", dst=".", keep_path=True)
def package_info(self):
self.cpp_info.libs = ["hpdf"]
| env_build = AutoToolsBuildEnvironment(self)
install_prefix=os.getcwd()
with tools.chdir("libharu-RELEASE_2_3_0"):
with tools.environment_append(env_build.vars):
self.run("touch include/config.h.in")
self.run("aclocal")
self.run("libtoolize")
... | identifier_body |
conanfile.py | from conans import ConanFile, AutoToolsBuildEnvironment, tools
import os
class LibHaruConn(ConanFile):
name = "libharu"
version = "2.3.0"
license = "ZLIB https://github.com/libharu/libharu/blob/master/LICENCE"
url = "https://github.com/trigger-happy/conan-packages"
description = "C library for gene... | (self):
self.copy("lib/*", dst="lib", keep_path=False)
self.copy("include/*", dst=".", keep_path=True)
def package_info(self):
self.cpp_info.libs = ["hpdf"]
| package | identifier_name |
conanfile.py | from conans import ConanFile, AutoToolsBuildEnvironment, tools
import os
class LibHaruConn(ConanFile):
name = "libharu"
version = "2.3.0"
license = "ZLIB https://github.com/libharu/libharu/blob/master/LICENCE"
url = "https://github.com/trigger-happy/conan-packages"
description = "C library for gene... | pkgLink = 'https://github.com/libharu/libharu/archive/RELEASE_2_3_0.tar.gz'
self.run("curl -JOL " + pkgLink)
self.run("tar xf libharu-RELEASE_2_3_0.tar.gz")
def build(self):
env_build = AutoToolsBuildEnvironment(self)
install_prefix=os.getcwd()
with tools.chdir("libh... | random_line_split | |
views.py | import os
from tornado import gen
import tornado.web
class DocsHandler(tornado.web.RequestHandler):
@gen.coroutine
def get(self):
version = "{}://{}/docs/version/v1.yml".format(
self.request.protocol, self.request.host)
self.render("swagger/index.html", version=version)
class H... |
class CachingFrontendHandler(tornado.web.StaticFileHandler):
"""If a file exists in the root folder, serve it, otherwise serve index.html
"""
@gen.coroutine
def get(self, path, include_body=True):
absolute_path = self.get_absolute_path(self.root, path)
is_file = os.path.isfile(absol... | yield super().get('index.html', include_body) | identifier_body |
views.py | import os
from tornado import gen
import tornado.web
class DocsHandler(tornado.web.RequestHandler):
@gen.coroutine
def get(self):
version = "{}://{}/docs/version/v1.yml".format(
self.request.protocol, self.request.host)
self.render("swagger/index.html", version=version)
class H... | (tornado.web.StaticFileHandler):
"""If a file exists in the root folder, serve it, otherwise serve index.html
"""
@gen.coroutine
def get(self, path, include_body=True):
absolute_path = self.get_absolute_path(self.root, path)
is_file = os.path.isfile(absolute_path)
if is_file:
... | CachingFrontendHandler | identifier_name |
views.py | import os
from tornado import gen
import tornado.web
class DocsHandler(tornado.web.RequestHandler):
@gen.coroutine
def get(self):
version = "{}://{}/docs/version/v1.yml".format(
self.request.protocol, self.request.host)
self.render("swagger/index.html", version=version)
class H... |
else:
yield super().get('index.html', include_body)
| yield super().get(path, include_body) | conditional_block |
views.py | import os
from tornado import gen
import tornado.web
class DocsHandler(tornado.web.RequestHandler):
@gen.coroutine
def get(self):
version = "{}://{}/docs/version/v1.yml".format(
self.request.protocol, self.request.host)
self.render("swagger/index.html", version=version) |
class HomeHandler(tornado.web.StaticFileHandler):
@gen.coroutine
def get(self, path, include_body=True):
yield super().get('index.html', include_body)
class CachingFrontendHandler(tornado.web.StaticFileHandler):
"""If a file exists in the root folder, serve it, otherwise serve index.html
"... | random_line_split | |
create_time_characteristics.py |
"""
#####################################
## create_time_characteristics.py
#####################################
- Open a CSV file of 30min daily load profiles using TKinter file dialog box (for example "load_file.csv")
- Read CSV file and build list of loads
- Loop through list of loads and create time characte... |
else:
root = tk.Tk()
root.withdraw()
file_name_ = filedialog.askopenfilename(title='Select a CSV file to open',filetypes=[('Comma Separated Value file', '*.csv')])
# Handler for cancel button
if not file_name_:
print_str('Script execution cancelled...')
exit()
# Read in lines from ... | file_name_ = str(sys.argv[1]) | conditional_block |
create_time_characteristics.py |
"""
#####################################
## create_time_characteristics.py
#####################################
- Open a CSV file of 30min daily load profiles using TKinter file dialog box (for example "load_file.csv")
- Read CSV file and build list of loads
- Loop through list of loads and create time characte... |
# Get PowerFactory application
app = pf.GetApplication()
app.ClearOutputWindow()
# Operational library folder
oplib = app.GetProjectFolder('oplib')
# Characteristics folder
opchar = oplib.GetContents('Characteristics')[0][0]
# Select csv file
if len(sys.argv)>1:
file_name_ = str(sys.argv[1])
else:
root = tk... | self.name = input[0]
self.P = [float(i)/1000 for i in input[1:49]] # Convert loads from kW to MW | identifier_body |
create_time_characteristics.py | """
#####################################
## create_time_characteristics.py |
Format of CSV file:
- Column 1: Name of load
- Column 2-49: Load demand (in kW) for each half hour interval from 0:00 to 23:30
"""
import tkinter as tk
from tkinter import filedialog
import sys
import csv
import powerfactory as pf
# Load object class definition
class csv_load():
def __init__ (self, input):
... | #####################################
- Open a CSV file of 30min daily load profiles using TKinter file dialog box (for example "load_file.csv")
- Read CSV file and build list of loads
- Loop through list of loads and create time characteristics | random_line_split |
create_time_characteristics.py |
"""
#####################################
## create_time_characteristics.py
#####################################
- Open a CSV file of 30min daily load profiles using TKinter file dialog box (for example "load_file.csv")
- Read CSV file and build list of loads
- Loop through list of loads and create time characte... | (self, input):
self.name = input[0]
self.P = [float(i)/1000 for i in input[1:49]] # Convert loads from kW to MW
# Get PowerFactory application
app = pf.GetApplication()
app.ClearOutputWindow()
# Operational library folder
oplib = app.GetProjectFolder('oplib')
# Characteristics folder
opchar = oplib... | __init__ | identifier_name |
housing_test.py | # -*- coding: utf-8 -*-
# Copyright(C) 2018 Phyks
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... |
return results
def check_single_housing_all(self, housing,
type, house_types, advert_type):
for field in self.FIELDS_ALL_SINGLE_HOUSING:
self.assertNotEmpty(housing, field)
if 'type' in self.FIELDS_ALL_SINGLE_HOUSING:
if (
... | self.assertRegexpMatches(photo.url, r'^http(s?)://') | conditional_block |
housing_test.py | # -*- coding: utf-8 -*-
# Copyright(C) 2018 Phyks
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | # Fields to be checked for values at least once for all items when querying
# individually
FIELDS_ANY_SINGLE_HOUSING = [
"photos"
]
# Some backends cannot distinguish between rent and furnished rent for
# single housing post. Set this to True if this is the case.
DO_NOT_DISTINGUISH_F... | """
Testing class to standardize the housing modules tests.
"""
# Fields to be checked for values across all items in housings list
FIELDS_ALL_HOUSINGS_LIST = [
"id", "type", "advert_type", "house_type", "url", "title", "area",
"cost", "currency", "utilities", "date", "location", "statio... | identifier_body |
housing_test.py | # -*- coding: utf-8 -*-
# Copyright(C) 2018 Phyks
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | counter[field] += 1
for photo in housing.photos:
self.assertRegexpMatches(photo.url, r'^http(s?)://')
return counter
def check_against_query(self, query):
# Check housing listing results
results = self.check_housing_lists(query)
# Check mandatory... | for field in self.FIELDS_ANY_SINGLE_HOUSING:
if not empty(getattr(housing, field)): | random_line_split |
housing_test.py | # -*- coding: utf-8 -*-
# Copyright(C) 2018 Phyks
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | (self, query):
# Check housing listing results
results = self.check_housing_lists(query)
# Check mandatory fields in all housings
housing = self.backend.get_housing(results[0].id)
self.backend.fillobj(housing, 'phone') # Fetch phone
self.check_single_housing_all(
... | check_against_query | identifier_name |
setup.py | #!/bin/env python
import os
from distutils.core import setup
name = 'django_sphinx_db'
version = '0.1'
release = '3' |
setup(
name = name,
version = versrel,
description = 'Django database backend for SphinxQL.',
long_description = long_description,
author = 'Ben Timby',
author_email = 'btimby@gmail.com',
maintainer = 'Ben Timby',
maintainer_email = 'btimby@gmail.com',
url = 'http://github.com/smart... | versrel = version + '-' + release
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
download_url = 'https://github.com/downloads/smartfile/django-sphinx-db' \
'/' + name + '-' + versrel + '.tar.gz'
long_description = open(readme).read() | random_line_split |
domain.py | """
Domain middleware: enables multi-tenancy in a single process
"""
from anaf.core.domains import setup_domain, setup_domain_database
from anaf.core.db import DatabaseNotFound
from anaf.core.conf import settings
from django.http import HttpResponseRedirect
from django.db.utils import DatabaseError
from django.core.url... | if isinstance(exception, DatabaseNotFound):
evergreen_url = getattr(
settings, 'EVERGREEN_BASE_URL', 'http://tree.io/')
return HttpResponseRedirect(evergreen_url) | identifier_body | |
domain.py | """
Domain middleware: enables multi-tenancy in a single process
"""
from anaf.core.domains import setup_domain, setup_domain_database
from anaf.core.db import DatabaseNotFound
from anaf.core.conf import settings
from django.http import HttpResponseRedirect
from django.db.utils import DatabaseError
from django.core.url... | (object):
"""Handles multiple domains within the same Django process"""
def process_request(self, request):
"""Identify the current domain and database, set up appropriate variables in the pandora box"""
domain = request.get_host().split('.')[0]
try:
setup_domain(domain)
... | DomainMiddleware | identifier_name |
domain.py | """
Domain middleware: enables multi-tenancy in a single process
"""
from anaf.core.domains import setup_domain, setup_domain_database
from anaf.core.db import DatabaseNotFound
from anaf.core.conf import settings
from django.http import HttpResponseRedirect
from django.db.utils import DatabaseError
from django.core.url... | box['request'] = request
def process_exception(self, request, exception):
if isinstance(exception, DatabaseNotFound):
evergreen_url = getattr(
settings, 'EVERGREEN_BASE_URL', 'http://tree.io/')
return HttpResponseRedirect(evergreen_url) | from anaf.core.models import ConfigSetting
setup_domain_database(router.db_for_read(ConfigSetting))
return HttpResponseRedirect(reverse('database_setup')) | random_line_split |
domain.py | """
Domain middleware: enables multi-tenancy in a single process
"""
from anaf.core.domains import setup_domain, setup_domain_database
from anaf.core.db import DatabaseNotFound
from anaf.core.conf import settings
from django.http import HttpResponseRedirect
from django.db.utils import DatabaseError
from django.core.url... | evergreen_url = getattr(
settings, 'EVERGREEN_BASE_URL', 'http://tree.io/')
return HttpResponseRedirect(evergreen_url) | conditional_block | |
landmarks.py | # Copyright (c) 2016 Matthew Earl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distr... |
def draw_convex_hull(im, points, color):
points = cv2.convexHull(points)
cv2.fillConvexPoly(im, points, color=color)
def get_face_mask(shape, landmarks):
im = numpy.zeros(shape[:2], dtype=numpy.float64)
draw_convex_hull(im,
landmarks,
color=1)
return i... | def __init__(self, predictor_path):
self.detector = dlib.get_frontal_face_detector()
self.predictor = dlib.shape_predictor(str(predictor_path))
def get(self, im):
rects = self.detector(im, 1)
if len(rects) > 1:
raise TooManyFaces
if len(rects) == 0:
... | identifier_body |
landmarks.py | # Copyright (c) 2016 Matthew Earl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distr... | 'LandmarkFinder',
'NoFaces',
'TooManyFaces',
)
import cv2
import dlib
import numpy
class TooManyFaces(Exception):
pass
class NoFaces(Exception):
pass
class LandmarkFinder(object):
def __init__(self, predictor_path):
self.detector = dlib.get_frontal_face_detector()
self.pr... | __all__ = (
'get_face_mask', | random_line_split |
landmarks.py | # Copyright (c) 2016 Matthew Earl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distr... | (im, points, color):
points = cv2.convexHull(points)
cv2.fillConvexPoly(im, points, color=color)
def get_face_mask(shape, landmarks):
im = numpy.zeros(shape[:2], dtype=numpy.float64)
draw_convex_hull(im,
landmarks,
color=1)
return im
| draw_convex_hull | identifier_name |
landmarks.py | # Copyright (c) 2016 Matthew Earl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distr... |
return numpy.matrix([[p.x, p.y]
for p in self.predictor(im, rects[0]).parts()])
def draw_convex_hull(im, points, color):
points = cv2.convexHull(points)
cv2.fillConvexPoly(im, points, color=color)
def get_face_mask(shape, landmarks):
im = numpy.zeros(shape[:2], ... | raise NoFaces | conditional_block |
main.js | /* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* ... | fire = fire && namespace[func];
fire = fire && typeof namespace[func][funcname] === 'function';
if (fire) {
namespace[func][funcname](args);
}
},
loadEvents: function() {
// Fire common init JS
UTIL.fire('common');
// Fire page-specific init JS, and then final... | funcname = (funcname === undefined) ? 'init' : funcname;
fire = func !== ''; | random_line_split |
main.js | /* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* ... |
},
loadEvents: function() {
// Fire common init JS
UTIL.fire('common');
// Fire page-specific init JS, and then finalize JS
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
UTIL.fire(classnm);
UTIL.fire(classnm, 'finalize');
}... | {
namespace[func][funcname](args);
} | conditional_block |
regex_route_param_spec.ts | import {
describe,
it,
iit,
ddescribe,
expect,
inject,
beforeEach,
} from '@angular/core/testing/testing_internal';
import {GeneratedUrl} from '../../../src/rules/route_paths/route_path';
import {RegexRoutePath} from '../../../src/rules/route_paths/regex_route_path';
import {parser, Url} from '../../../s... | (params) {
return new GeneratedUrl(`/a/${params['a']}/b/${params['b']}`, {});
}
var rec = new RegexRoutePath('/a/(.+)/b/(.+)$', serializer);
var params = {a: 'one', b: 'two'};
var url = rec.generateUrl(params);
expect(url.urlPath).toEqual('/a/one/b/two');
});
});
}
| serializer | identifier_name |
regex_route_param_spec.ts | import {
describe,
it,
iit,
ddescribe,
expect,
inject,
beforeEach,
} from '@angular/core/testing/testing_internal';
import {GeneratedUrl} from '../../../src/rules/route_paths/route_path';
import {RegexRoutePath} from '../../../src/rules/route_paths/regex_route_path';
import {parser, Url} from '../../../s... |
var rec = new RegexRoutePath('/a/(.+)/b/(.+)$', serializer);
var params = {a: 'one', b: 'two'};
var url = rec.generateUrl(params);
expect(url.urlPath).toEqual('/a/one/b/two');
});
});
}
| {
return new GeneratedUrl(`/a/${params['a']}/b/${params['b']}`, {});
} | identifier_body |
regex_route_param_spec.ts | import {
describe,
it,
iit,
ddescribe,
expect,
inject,
beforeEach,
} from '@angular/core/testing/testing_internal';
import {GeneratedUrl} from '../../../src/rules/route_paths/route_path';
import {RegexRoutePath} from '../../../src/rules/route_paths/regex_route_path';
import {parser, Url} from '../../../s... | });
} | random_line_split | |
status_updater.py | Replied", "communication_sent"],
["Open", "communication_received"]
],
"Job Applicant": [
["Replied", "communication_sent"],
["Open", "communication_received"]
],
"Lead": [
["Replied", "communication_sent"],
["Converted", "has_customer"],
["Opportunity", "has_opportunity"],
["Open", "communication_rec... | (DocListController):
"""
Updates the status of the calling records
Delivery Note: Update Delivered Qty, Update Percent and Validate over delivery
Sales Invoice: Update Billed Amt, Update Percent and Validate over billing
Installation Note: Update Installed Qty, Update Percent Qty and Validate over installation... | StatusUpdater | identifier_name |
status_updater.py | Quotation": [
["Draft", None],
["Submitted", "eval:self.doc.docstatus==1"],
["Lost", "eval:self.doc.status=='Lost'"],
["Ordered", "has_sales_order"],
["Replied", "communication_sent"],
["Cancelled", "eval:self.doc.docstatus==2"],
["Open", "communication_received"],
],
"Sales Order": [
["Draft", None],... | global_tolerance = flt(webnotes.conn.get_value('Global Defaults', None,
'tolerance')) | random_line_split | |
status_updater.py | 1"],
["Lost", "eval:self.doc.status=='Lost'"],
["Ordered", "has_sales_order"],
["Replied", "communication_sent"],
["Cancelled", "eval:self.doc.docstatus==2"],
["Open", "communication_received"],
],
"Sales Order": [
["Draft", None],
["Submitted", "eval:self.doc.docstatus==1"],
["Stopped", "eval:self.do... | """
Returns the tolerance for the item, if not set, returns global tolerance
"""
if item_tolerance.get(item_code):
return item_tolerance[item_code], item_tolerance, global_tolerance
tolerance = flt(webnotes.conn.get_value('Item',item_code,'tolerance') or 0)
if not tolerance:
if global_tolerance == None:
... | identifier_body | |
status_updater.py | Replied", "communication_sent"],
["Open", "communication_received"]
],
"Job Applicant": [
["Replied", "communication_sent"],
["Open", "communication_received"]
],
"Lead": [
["Replied", "communication_sent"],
["Converted", "has_customer"],
["Opportunity", "has_opportunity"],
["Open", "communication_rec... |
elif s[1].startswith("eval:"):
if eval(s[1][5:]):
self.doc.status = s[0]
break
elif getattr(self, s[1])():
self.doc.status = s[0]
break
if update:
webnotes.conn.set_value(self.doc.doctype, self.doc.name, "status", self.doc.status)
def on_communication(self):
self.commu... | self.doc.status = s[0]
break | conditional_block |
startup.py | #!/usr/bin/env python
# gRefer is a Bibliographic Management System that uses Google Docs
# as shared storage.
#
# Copyright (C) 2011 NigelB
#
# 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 Soft... | ():
import os
from gRefer.config_constants import dir_name, bibfiler_log_file
from gRefer.log import NotifyHandler
import logging
import logging.handlers
logger = logging.getLogger(name="Notifier")
if not os.path.exists(dir_name):
os.makedirs(dir_name)
fh = logging.handlers.Time... | start_notifier | identifier_name |
startup.py | #!/usr/bin/env python
# gRefer is a Bibliographic Management System that uses Google Docs
# as shared storage.
#
# Copyright (C) 2011 NigelB
#
# 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 Soft... |
from gRefer.filer.systray import run_systray
run_systray() | logger.root.setLevel(log.TRACE) | random_line_split |
startup.py | #!/usr/bin/env python
# gRefer is a Bibliographic Management System that uses Google Docs
# as shared storage.
#
# Copyright (C) 2011 NigelB
#
# 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 Soft... |
fh = logging.handlers.TimedRotatingFileHandler(
os.path.join(dir_name,bibfiler_log_file),
when="midnight",
backupCount="7"
)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.root.addHandler(NotifyHandler(... | os.makedirs(dir_name) | conditional_block |
startup.py | #!/usr/bin/env python
# gRefer is a Bibliographic Management System that uses Google Docs
# as shared storage.
#
# Copyright (C) 2011 NigelB
#
# 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 Soft... | logger.root.setLevel(log.TRACE)
from gRefer.filer.systray import run_systray
run_systray() | import os
from gRefer.config_constants import dir_name, bibfiler_log_file
from gRefer.log import NotifyHandler
import logging
import logging.handlers
logger = logging.getLogger(name="Notifier")
if not os.path.exists(dir_name):
os.makedirs(dir_name)
fh = logging.handlers.TimedRotatin... | identifier_body |
photobooth.py | 2,1555
# if you run into resource issues, try smaller, like 1920x1152.
# or increase memory http://picamera.readthedocs.io/en/release-1.12/fov.html#hardware-limits
high_res_w = 1190 # width of high res image, if taken
high_res_h = 790 # height of high res image, if taken
#############################
### Variables t... | ():
logging.critical('Ended abruptly')
pygame.quit()
GPIO.cleanup()
atexit.register(cleanup)
# A function to handle keyboard/mouse/device input events
def input(events):
for event in events: # Hit the ESC key to quit the slideshow.
if (event.type == QUIT or
(event.type == ... | cleanup | identifier_name |
photobooth.py | 2,1555
# if you run into resource issues, try smaller, like 1920x1152.
# or increase memory http://picamera.readthedocs.io/en/release-1.12/fov.html#hardware-limits
high_res_w = 1190 # width of high res image, if taken
high_res_h = 790 # height of high res image, if taken
#############################
### Variables t... | def clear_screen():
screen.fill((0, 0, 0))
pygame.display.flip()
# display a group of images
def display_pics(jpg_group):
for i in range(0, replay_cycles): # show pics a few times
for i in range(1, total_pics + 1): # show each pic
show_image(config.file_path + jpg_group + "-0" + str(... | # display a blank screen | random_line_split |
photobooth.py | 2,1555
# if you run into resource issues, try smaller, like 1920x1152.
# or increase memory http://picamera.readthedocs.io/en/release-1.12/fov.html#hardware-limits
high_res_w = 1190 # width of high res image, if taken
high_res_h = 790 # height of high res image, if taken
#############################
### Variables t... |
# delete files in folder
def clear_pics(channel):
files = glob.glob(config.file_path + '*')
for f in files:
os.remove(f)
# light the lights in series to show completed
logging.warning("Deleted previous pics")
for x in range(0, 3): # blink light
GPIO.output(led_pin, True)
... | for event in events: # Hit the ESC key to quit the slideshow.
if (event.type == QUIT or
(event.type == KEYDOWN and event.key == K_ESCAPE)):
pygame.quit() | identifier_body |
photobooth.py | 0x1152.
# or increase memory http://picamera.readthedocs.io/en/release-1.12/fov.html#hardware-limits
high_res_w = 1190 # width of high res image, if taken
high_res_h = 790 # height of high res image, if taken
#############################
### Variables that Change ###
#############################
# Do not change th... | logging.debug("capture_continuous")
camera.start_preview(
resolution=(high_res_w, high_res_h)) # start preview at low res but the right ratio
time.sleep(2) # warm up camera
try: # take the photos
for i, filename in enumerate(camera.capture_continuous(config.file_path ... | conditional_block | |
test.py | # Create the data.
from numpy import pi, sin, cos, mgrid
dphi, dtheta = pi/250.0, pi/250.0
[phi,theta] = mgrid[0:pi+dphi*1.5:dphi,0:2*pi+dtheta*1.5:dtheta]
m0 = 4; m1 = 3; m2 = 2; m3 = 3; m4 = 6; m5 = 2; m6 = 6; m7 = 4;
r = sin(m0*phi)**m1 + cos(m2*phi)**m3 + sin(m4*theta)**m5 + cos(m6*theta)**m7
x = r*sin(phi)*cos(the... | mlab.show() | random_line_split | |
symbols.js | /*=========================================================================================
File Name: symbols.js
Description: Flot symbols chart
----------------------------------------------------------------------------------------
Item Name: Stack - Responsive Admin Theme
Version: 1.1
Author... | // ------------------------------
$(window).on("load", function(){
function generate(offset, amplitude) {
var res = [];
var start = 0, end = 10;
for (var i = 0; i <= 50; ++i) {
var x = start + i / 50 * (end - start);
res.push([x, amplitude * Math.sin(x + offset)]);... | Author URL: http://www.themeforest.net/user/pixinvent
==========================================================================================*/
// Symbols chart | random_line_split |
symbols.js | /*=========================================================================================
File Name: symbols.js
Description: Flot symbols chart
----------------------------------------------------------------------------------------
Item Name: Stack - Responsive Admin Theme
Version: 1.1
Author... |
return res;
}
var data = [
{ data: generate(2, 1.8), points: { symbol: "circle" } },
{ data: generate(3, 1.5), points: { symbol: "square" } },
{ data: generate(4, 0.9), points: { symbol: "diamond" } },
{ data: generate(6, 1.4), points: { symbol: "triangle" } },
... | {
var x = start + i / 50 * (end - start);
res.push([x, amplitude * Math.sin(x + offset)]);
} | conditional_block |
symbols.js | /*=========================================================================================
File Name: symbols.js
Description: Flot symbols chart
----------------------------------------------------------------------------------------
Item Name: Stack - Responsive Admin Theme
Version: 1.1
Author... | (offset, amplitude) {
var res = [];
var start = 0, end = 10;
for (var i = 0; i <= 50; ++i) {
var x = start + i / 50 * (end - start);
res.push([x, amplitude * Math.sin(x + offset)]);
}
return res;
}
var data = [
{ data: generate(2, 1.8),... | generate | identifier_name |
symbols.js | /*=========================================================================================
File Name: symbols.js
Description: Flot symbols chart
----------------------------------------------------------------------------------------
Item Name: Stack - Responsive Admin Theme
Version: 1.1
Author... |
var data = [
{ data: generate(2, 1.8), points: { symbol: "circle" } },
{ data: generate(3, 1.5), points: { symbol: "square" } },
{ data: generate(4, 0.9), points: { symbol: "diamond" } },
{ data: generate(6, 1.4), points: { symbol: "triangle" } },
{ data: generate(7, 1.1), ... | {
var res = [];
var start = 0, end = 10;
for (var i = 0; i <= 50; ++i) {
var x = start + i / 50 * (end - start);
res.push([x, amplitude * Math.sin(x + offset)]);
}
return res;
} | identifier_body |
Main.ts | );
this.viewModel.items(Parser.parseTable($('.autolisting-table')));
ko.applyBindings(this.viewModel, $('.wrapper')[0]);
this.init();
this.viewModel.pathItems(Parser.parsePath($('.autolisting-path')));
this.viewModel.selectedIndex(0);
}
private init()
{
this.viewModel.selectedIndex.subscribe((newVal... | clearInterval(this.searchTimeout);
this.viewModel.search('');
this.viewModel.commandIndex = 0;
this.viewModel.searchMode(this.viewModel.searchMode() == 'search' ? 'filter' : 'search');
event.preventDefault();
}
// Shift + /, ?
else if (event.keyCode == 191 && event.shiftKey)
{
if (... | // Ctrl + Shift + F
else if (event.keyCode == 70 && event.ctrlKey && event.shiftKey)
{ | random_line_split |
Main.ts | ().indexOf(this.viewModel.selectedItem()));
}
this.viewModel.previousFilteredItemsLength = newValue.length;
});
this.viewModel.pathItems.subscribe((newValue) =>
{
if (this.viewModel.pathItems().length < this.viewModel.previousPathItems().length)
{
var recentFolder = this.viewModel.previousPathIt... | openNewPath | identifier_name | |
Main.ts | );
this.viewModel.items(Parser.parseTable($('.autolisting-table')));
ko.applyBindings(this.viewModel, $('.wrapper')[0]);
this.init();
this.viewModel.pathItems(Parser.parsePath($('.autolisting-path')));
this.viewModel.selectedIndex(0);
}
private init()
{
this.viewModel.selectedIndex.subscribe((newVal... |
});
$('.listing').on('click', 'li a', (event) =>
{
if (event.ctrlKey)
{
return;
}
event.preventDefault();
var data = ko.dataFor(<HTMLElement>event.currentTarget);
this.gotoPath(data);
});
if (!isMobile)// && this.viewModel.searchMode() == 'filter')
{
$('#search').on('blur', (ev... | {
//this.viewModel.commandQueue.push(String.fromCharCode(event.which).toLowerCase());
//console.log(this.viewModel.commandQueue.join(''));
} | conditional_block |
14-03.js | <div id="wrapper">
<div data-tabname="one">Tab one</div>
<div data-tabname="two">Tab two</div>
<div data-tabname="three">Tab three</div>
</div>
<script>
function asTabs(node) {
//1.Gathering all decent children (no whitespaces etc) and not displaying them
function decentChildren(node) |
var children = decentChildren(node);
function hideEm(nodes) {
nodes.forEach(function(node) {
node.style.display = "none";
});
}
hideEm(children);
//2.Act (what to do, after button is clicked)
function act(event) {
children.forEach(function(child) {
... | {
var arr = [];
for (var i = 0; i < node.childNodes.length; i++) {
if (node.childNodes[i].nodeType === 1) {
arr = arr.concat(node.childNodes[i]);
}
}
return arr;
} | identifier_body |
14-03.js | <div id="wrapper">
<div data-tabname="one">Tab one</div>
<div data-tabname="two">Tab two</div>
<div data-tabname="three">Tab three</div>
</div>
<script>
function asTabs(node) {
//1.Gathering all decent children (no whitespaces etc) and not displaying them
function decentChildren(node) {
var arr = ... | (event) {
children.forEach(function(child) {
if (event.target.getAttribute("data-num") == children.indexOf(child)) {
child.style.display = "block";
} else {
child.style.display = "none";
}
});
}
//3. Creating buttons
function buttons(tags){
... | act | identifier_name |
14-03.js | <div id="wrapper">
<div data-tabname="one">Tab one</div>
<div data-tabname="two">Tab two</div>
<div data-tabname="three">Tab three</div>
</div>
<script>
function asTabs(node) {
//1.Gathering all decent children (no whitespaces etc) and not displaying them
function decentChildren(node) {
var arr = ... | if (event.target.getAttribute("data-num") == children.indexOf(child)) {
child.style.display = "block";
} else {
child.style.display = "none";
}
});
}
//3. Creating buttons
function buttons(tags){
var arr = [];
for (var i = 0; i < tags.length... |
//2.Act (what to do, after button is clicked)
function act(event) {
children.forEach(function(child) { | random_line_split |
14-03.js | <div id="wrapper">
<div data-tabname="one">Tab one</div>
<div data-tabname="two">Tab two</div>
<div data-tabname="three">Tab three</div>
</div>
<script>
function asTabs(node) {
//1.Gathering all decent children (no whitespaces etc) and not displaying them
function decentChildren(node) {
var arr = ... |
});
}
//3. Creating buttons
function buttons(tags){
var arr = [];
for (var i = 0; i < tags.length; i++) {
arr[i] = document.createElement("BUTTON");
arr[i].textContent = tags[i].getAttribute("data-tabname");
arr[i].setAttribute("data-num", i);
arr[i].a... | {
child.style.display = "none";
} | conditional_block |
trace_test.py | # Copyright 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import tempfile
import unittest
from .log import *
from .parsed_trace_events import *
class TraceTest(unittest.TestCase):
def __init__(self, *args):
... |
if self._file:
self._file.close()
| trace_disable() | conditional_block |
trace_test.py | # Copyright 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import tempfile
import unittest
from .log import *
from .parsed_trace_events import *
class TraceTest(unittest.TestCase):
def __init__(self, *args):
... |
def tearDown(self):
if trace_is_enabled():
trace_disable()
if self._file:
self._file.close()
| return self._file.name | identifier_body |
trace_test.py | # Copyright 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import tempfile
import unittest
from .log import * | """
Infrastructure for running tests of the tracing system.
Does not actually run any tests. Look at subclasses for those.
"""
unittest.TestCase.__init__(self, *args)
self._file = None
def go(self, cb):
"""
Enables tracing, runs the provided callback, and if successful, returns a
... | from .parsed_trace_events import *
class TraceTest(unittest.TestCase):
def __init__(self, *args): | random_line_split |
trace_test.py | # Copyright 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import tempfile
import unittest
from .log import *
from .parsed_trace_events import *
class | (unittest.TestCase):
def __init__(self, *args):
"""
Infrastructure for running tests of the tracing system.
Does not actually run any tests. Look at subclasses for those.
"""
unittest.TestCase.__init__(self, *args)
self._file = None
def go(self, cb):
"""
Enables tracing, runs the p... | TraceTest | identifier_name |
addon.py | import xbmcaddon
import xbmcgui
import subprocess,os
def EstoEsUnaFun( str ):
xbmcgui.Dialog().ok("ESO ES","AHHHH",str)
return
addon = xbmcaddon.Addon()
addonname = addon.getAddonInfo('name')
line1 = "Hello World!"
line2 = "We can write anything we want here"
line3 = "Using Python"
my_setting = a... |
dia=xbmcgui.Dialog();
dia.addControl(xbmcgui.ControlLabel(x=190, y=25, width=500, height=25, label="Hoooolaa"))
dia.ok(addonname, line1, line2, line3 + my_setting)
#xbmcgui.Window().show() | addon.setSetting('my_setting', 'false')
os.system("echo caca>>/home/rafa400/caca.txt") | random_line_split |
addon.py | import xbmcaddon
import xbmcgui
import subprocess,os
def Es | str ):
xbmcgui.Dialog().ok("ESO ES","AHHHH",str)
return
addon = xbmcaddon.Addon()
addonname = addon.getAddonInfo('name')
line1 = "Hello World!"
line2 = "We can write anything we want here"
line3 = "Using Python"
my_setting = addon.getSetting('my_setting') # returns the string 'true' or 'false'
addon... | toEsUnaFun( | identifier_name |
addon.py | import xbmcaddon
import xbmcgui
import subprocess,os
def EstoEsUnaFun( str ):
xb | addon = xbmcaddon.Addon()
addonname = addon.getAddonInfo('name')
line1 = "Hello World!"
line2 = "We can write anything we want here"
line3 = "Using Python"
my_setting = addon.getSetting('my_setting') # returns the string 'true' or 'false'
addon.setSetting('my_setting', 'false')
os.system("echo caca>>/home... | mcgui.Dialog().ok("ESO ES","AHHHH",str)
return
| identifier_body |
pretrain.py | 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 specific lan... | batch_train_data,
optimizer_config)
if it % hparams.print_every == 0:
(batch_context_x,
batch_context_y,
batch_target_x,
batch_target_y,
batch_unseen_targets) = get_splits(valid_dataset,
num_context,
... | points_perm=True)
nll, mse, local_z_kl, global_z_kl = step(
model, | random_line_split |
pretrain.py | 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 specific lan... |
else:
r[3] = r_big
one_hot_vector = np.zeros((5))
random_action = np.random.randint(num_actions)
one_hot_vector[random_action] = 1
actions.append(one_hot_vector)
rewards.append(r[random_action])
rewards = np.expand_dims(np.array(rewards), -1)
context_action_pairs = np.hstack(... | r[2] = r_big | conditional_block |
pretrain.py | 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 specific languag... | (data_hparams,
model_hparams,
training_hparams):
"""Executes the training pipeline for SNPs."""
all_context_action_pairs, all_rewards = procure_dataset(
data_hparams,
num_wheels=100,
seed=0)
train_dataset = (all_context_action_pairs, all_rewards)
all_context_action_pairs, ... | train | identifier_name |
pretrain.py | 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 specific lan... | # Sample uniform contexts in unit ball.
while len(data) < num_datapoints:
raw_data = np.random.uniform(-1, 1, (int(num_datapoints / 3), context_dim))
for i in range(raw_data.shape[0]):
if np.linalg.norm(raw_data[i, :]) <= 1:
data.append(raw_data[i, :])
contexts = np.stack(data)[:num_datapo... | """Samples from Wheel bandit game (see Riquelme et al. (2018)).
Args:
num_datapoints: Number (n) of (context, action, reward) triplets to sample.
num_actions: (a) Number of actions.
context_dim: (c) Number of dimensions in the context.
delta: Exploration parameter: high reward in one region if norm a... | identifier_body |
LiveWatchStartStreamModel.ts | "use strict";
import ApiModel from '../ApiModel';
import Stream from '../../../Stream/Stream'
import StreamManager from '../../../Stream/StreamManager';
class LiveWatchStartStreamModel extends ApiModel {
private createStream: (channel: string, sid: string, tunerId: number, videoId: number) => Stream;
constru... |
try {
let streamId = StreamManager.getInstance().startStream(this.createStream(channel, sid, tunerId, videoId));
this.results = { streamId: streamId };
} catch(e) {
this.errors = 500;
}
this.eventsNotify();
}
}
export default LiveWatchStartStre... | {
this.errors = 415;
this.eventsNotify();
return;
} | conditional_block |
LiveWatchStartStreamModel.ts | "use strict";
import ApiModel from '../ApiModel';
import Stream from '../../../Stream/Stream'
import StreamManager from '../../../Stream/StreamManager';
class LiveWatchStartStreamModel extends ApiModel {
private createStream: (channel: string, sid: string, tunerId: number, videoId: number) => Stream;
constru... |
public execute(): void {
let channel = this.option["channel"];
let sid = this.option["sid"];
let tunerId = this.option["tunerId"];
let videoId = this.option["videoId"];
if( this.checkNull(channel) || this.checkNull(sid) || this.checkNull(tunerId) || this.checkNull(videoId)... | {
super();
this.createStream = _createStream;
} | identifier_body |
LiveWatchStartStreamModel.ts | "use strict";
import ApiModel from '../ApiModel';
import Stream from '../../../Stream/Stream'
import StreamManager from '../../../Stream/StreamManager';
class LiveWatchStartStreamModel extends ApiModel {
private createStream: (channel: string, sid: string, tunerId: number, videoId: number) => Stream;
constru... | try {
let streamId = StreamManager.getInstance().startStream(this.createStream(channel, sid, tunerId, videoId));
this.results = { streamId: streamId };
} catch(e) {
this.errors = 500;
}
this.eventsNotify();
}
}
export default LiveWatchStartStream... | }
| random_line_split |
LiveWatchStartStreamModel.ts | "use strict";
import ApiModel from '../ApiModel';
import Stream from '../../../Stream/Stream'
import StreamManager from '../../../Stream/StreamManager';
class LiveWatchStartStreamModel extends ApiModel {
private createStream: (channel: string, sid: string, tunerId: number, videoId: number) => Stream;
| (_createStream: (channel: string, sid: string, tunerId: number, videoId: number) => Stream) {
super();
this.createStream = _createStream;
}
public execute(): void {
let channel = this.option["channel"];
let sid = this.option["sid"];
let tunerId = this.option["tunerId"];
... | constructor | identifier_name |
fontbox.py | import typecat.font2img as f2i
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class FontBox(Gtk.FlowBoxChild):
def set_text(self, arg1):
if type(arg1) is str:
self.text = arg1
if type(arg1) is int:
self.font_size = arg1
try:
... | self.add(self.frame)
| Gtk.FlowBoxChild.__init__(self)
self.frame = Gtk.Frame()
self.set_border_width(5)
self.font = font
self.font_size = int(size[0]/9)
self.font.set_size(self.font_size)
self.text = text
self.size = size
self.title = self.font.name if len(self.font.name) < 3... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.