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 |
|---|---|---|---|---|
order.service.ts | /* Importing core module */
import {Injectable} from 'angular2/core';
import {Response} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import {HttpClient} from './http-client.service';
/* Importing model */
import {OrderModel} from '../model/order.model';
i... | (private _config: Configuration, private _httpClient: HttpClient) {
this._actionUrl = _config.serverUrl + 'orders/';
this._isHeadersSet = false;
}
/**
* Make the following request to the server: [GET][/orders]: fetch all orders in the database
*/
getAllOrders() {
return ... | constructor | identifier_name |
api_events.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of GNUWiNetwork,
# Copyright (C) 2014 by
# Pablo Belzarena, Gabriel Gomez Sena, Victor Gonzalez Barbone,
# Facultad de Ingenieria, Universidad de la Republica, Uruguay.
#
# GNUWiNetwork is free software: you can redistribute it ... | (nickname, **kwargs):
'''Returns an event of the given event nickname.
@param nickname: a valid event nickname, i.e. one that is a key in dictionary of valid nicknames.
@param kwargs: a dictionary of variables depending on the type of event. Field C{ev_dc} is a dictionary of fields and values for the corre... | mkevent | identifier_name |
api_events.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of GNUWiNetwork,
# Copyright (C) 2014 by
# Pablo Belzarena, Gabriel Gomez Sena, Victor Gonzalez Barbone,
# Facultad de Ingenieria, Universidad de la Republica, Uruguay.
#
# GNUWiNetwork is free software: you can redistribute it ... | if kwargs.has_key('payload'):
payload = kwargs['payload']
else:
payload = ''
if evtimer.dc_nicknames.has_key(nickname):
ptype, psubtype, eventclass = evtimer.dc_nicknames[nickname]
return eventclass(nickname, ptype, psubtype, ev_dc)
elif evframes80211.dc_nicknames.has... | '''Returns an event of the given event nickname.
@param nickname: a valid event nickname, i.e. one that is a key in dictionary of valid nicknames.
@param kwargs: a dictionary of variables depending on the type of event. Field C{ev_dc} is a dictionary of fields and values for the corresponding event type; field... | identifier_body |
api_events.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of GNUWiNetwork,
# Copyright (C) 2014 by
# Pablo Belzarena, Gabriel Gomez Sena, Victor Gonzalez Barbone,
# Facultad de Ingenieria, Universidad de la Republica, Uruguay.
#
# GNUWiNetwork is free software: you can redistribute it ... |
import evtimer
import utils.framers.ieee80211.evframes80211 as evframes80211
import evrequest
#sys.path = sys.path + ['..']
def mkevent(nickname, **kwargs):
'''Returns an event of the given event nickname.
@param nickname: a valid event nickname, i.e. one that is a key in dictionary of valid nicknames.
... |
import sys
import types | random_line_split |
api_events.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of GNUWiNetwork,
# Copyright (C) 2014 by
# Pablo Belzarena, Gabriel Gomez Sena, Victor Gonzalez Barbone,
# Facultad de Ingenieria, Universidad de la Republica, Uruguay.
#
# GNUWiNetwork is free software: you can redistribute it ... |
else:
ev_dc['frame_length'] = 0
frmpkt = ''
if kwargs.has_key('payload'):
payload = kwargs['payload']
else:
payload = ''
if evtimer.dc_nicknames.has_key(nickname):
ptype, psubtype, eventclass = evtimer.dc_nicknames[nickname]
return eventclass(nickname, pt... | frmpkt = kwargs['frmpkt']
ev_dc['frame_length'] = len(frmpkt) | conditional_block |
main.rs | // Copyright (C) 2015 - Will Glozer. All rights reserved.
#![feature(convert, core, plugin, collections, ip, ip_addr, libc, duration)]
#![plugin(docopt_macros, regex_macros)]
#![allow(dead_code)]
mod cms;
mod kqueue;
mod pf;
mod posix;
mod tail;
#[macro_use]
mod log;
#[macro_use]
extern crate bitflags;
#[macro_use]... |
fn is_global(addr: IpAddr) -> bool {
match addr {
IpAddr::V4(addr) => addr.is_global(),
IpAddr::V6(addr) => addr.is_global(),
}
}
#[cfg(test)] extern crate tempdir;
#[cfg(test)] mod tests;
| {
let tm = try!(time::strptime(&line[..15], "%b %e %T"));
let (year, month) = match tm.tm_mon as u32 + 1 {
month if month > now.month() => (now.year() - 1, month),
month => (now.year(), month),
};
let day = tm.tm_mday as u32;
let hour = tm.tm_hour as ... | identifier_body |
main.rs | // Copyright (C) 2015 - Will Glozer. All rights reserved.
#![feature(convert, core, plugin, collections, ip, ip_addr, libc, duration)]
#![plugin(docopt_macros, regex_macros)]
#![allow(dead_code)]
mod cms;
mod kqueue;
mod pf;
mod posix;
mod tail;
#[macro_use]
mod log;
#[macro_use]
extern crate bitflags;
#[macro_use]... | <Z: TimeZone>(line: &str, now: DateTime<Z>) -> Result<DateTime<Z>, time::ParseError> {
let tm = try!(time::strptime(&line[..15], "%b %e %T"));
let (year, month) = match tm.tm_mon as u32 + 1 {
month if month > now.month() => (now.year() - 1, month),
month => (now.year(), ... | timestamp | identifier_name |
main.rs | // Copyright (C) 2015 - Will Glozer. All rights reserved.
#![feature(convert, core, plugin, collections, ip, ip_addr, libc, duration)]
#![plugin(docopt_macros, regex_macros)]
#![allow(dead_code)]
mod cms;
mod kqueue;
mod pf;
mod posix;
mod tail;
#[macro_use]
mod log;
#[macro_use]
extern crate bitflags;
#[macro_use]... |
}
}
}
}
}
}
}
static PATTERNS: [Regex; 3] = [
regex!(r"sshd\[\d+\]: Invalid user (\w+) from (?P<addr>.+)"),
regex!(r"sshd\[\d+\]: Failed (.+) for( invalid user)? (\w+) from (?P<addr>.+) port"),
regex!(r"sshd\[\d+\]: Receiv... | {
syslog!("Address added to table '{}': {}", self.table, addr);
} | conditional_block |
main.rs | // Copyright (C) 2015 - Will Glozer. All rights reserved.
#![feature(convert, core, plugin, collections, ip, ip_addr, libc, duration)]
#![plugin(docopt_macros, regex_macros)]
#![allow(dead_code)]
mod cms;
mod kqueue;
mod pf;
mod posix;
mod tail;
#[macro_use]
mod log;
#[macro_use]
extern crate bitflags;
#[macro_use]... | limit: u64,
period: Duration,
table: &'a str,
}
impl<'a> IronGate<'a> {
fn monitor(&self, path: &Path) -> Result<(), tail::Error> {
let pf = try!(Pf::new());
let mut tailer = try!(Tailer::new(path.as_os_str()));
let resolution = |d: &Duration| { d.num_seconds() };
let ... |
struct IronGate<'a> { | random_line_split |
element-helper.ts | import { SupportedLocators } from './locators';
export function findAll(locator: string, parent: HTMLElement | Document) {
const index = locator && locator.indexOf('=');
if (index) {
try {
const type = locator.substr(0, index);
const selector = locator.substr(index + 1).replace(/(.*)@[^/\\'"><\]\[]... | const backgroundColor = element.style.backgroundColor;
const transition = element.style.transition;
const restore1 = function () {
element.style.backgroundColor = backgroundColor;
element.removeEventListener('transitionend', restore1);
element.addEventListener('transitionend', restore2);
};
cons... | random_line_split | |
element-helper.ts | import { SupportedLocators } from './locators';
export function findAll(locator: string, parent: HTMLElement | Document) {
const index = locator && locator.indexOf('=');
if (index) {
try {
const type = locator.substr(0, index);
const selector = locator.substr(index + 1).replace(/(.*)@[^/\\'"><\]\[]... |
export function findLocators(target: HTMLElement, settings) {
const types = (settings.locators || '').split(/\s|,/);
return types.map((type) => {
if (type && SupportedLocators[type]) {
return SupportedLocators[type].create(target, settings);
} else {
console.info('unknown locator %s, must be o... | {
const list = findAll(locator, parent) || [];
return list[0];
} | identifier_body |
element-helper.ts | import { SupportedLocators } from './locators';
export function findAll(locator: string, parent: HTMLElement | Document) {
const index = locator && locator.indexOf('=');
if (index) {
try {
const type = locator.substr(0, index);
const selector = locator.substr(index + 1).replace(/(.*)@[^/\\'"><\]\[]... | (target: HTMLElement, settings) {
const types = (settings.locators || '').split(/\s|,/);
return types.map((type) => {
if (type && SupportedLocators[type]) {
return SupportedLocators[type].create(target, settings);
} else {
console.info('unknown locator %s, must be one of %s', type, Object.keys(S... | findLocators | identifier_name |
element-helper.ts | import { SupportedLocators } from './locators';
export function findAll(locator: string, parent: HTMLElement | Document) {
const index = locator && locator.indexOf('=');
if (index) {
try {
const type = locator.substr(0, index);
const selector = locator.substr(index + 1).replace(/(.*)@[^/\\'"><\]\[]... |
return undefined;
}).filter((value) => !!value);
}
export function highlight(element: HTMLElement, color?: string) {
// ignore if element is highlighted now
if (element.dataset._highlighted === '1') {
return;
}
element.dataset._highlighted = '1';
const backgroundColor = element.style.backgroundCo... | {
console.info('unknown locator %s, must be one of %s', type, Object.keys(SupportedLocators).join(','));
} | conditional_block |
CalendarCell.driver.ts | import {
BaseUniDriver,
baseUniDriverFactory,
} from 'wix-ui-test-utils/base-driver';
import { UniDriver } from 'wix-ui-test-utils/unidriver';
import { CALENDAR_DATA_KEYS } from './dataHooks';
import { Alignment } from './CalendarCell';
export interface CalendarCellDriver extends BaseUniDriver {
hasTimeType(time... | },
async hasCurrent() {
return (await base.attr(CALENDAR_DATA_KEYS.Current)) === 'true';
},
async hasRightAlignment(mockAlignment) {
return (await base.attr(CALENDAR_DATA_KEYS.Alignment)) === mockAlignment;
},
};
}; | },
async hasTimeType(timeType) {
return (await base.attr(CALENDAR_DATA_KEYS.TimeType)) === timeType; | random_line_split |
CalendarCell.driver.ts | import {
BaseUniDriver,
baseUniDriverFactory,
} from 'wix-ui-test-utils/base-driver';
import { UniDriver } from 'wix-ui-test-utils/unidriver';
import { CALENDAR_DATA_KEYS } from './dataHooks';
import { Alignment } from './CalendarCell';
export interface CalendarCellDriver extends BaseUniDriver {
hasTimeType(time... | () {
return (await base.attr(CALENDAR_DATA_KEYS.Stertchable)) === 'true';
},
async hasTimeType(timeType) {
return (await base.attr(CALENDAR_DATA_KEYS.TimeType)) === timeType;
},
async hasCurrent() {
return (await base.attr(CALENDAR_DATA_KEYS.Current)) === 'true';
},
async hasRi... | stretcheable | identifier_name |
CalendarCell.driver.ts | import {
BaseUniDriver,
baseUniDriverFactory,
} from 'wix-ui-test-utils/base-driver';
import { UniDriver } from 'wix-ui-test-utils/unidriver';
import { CALENDAR_DATA_KEYS } from './dataHooks';
import { Alignment } from './CalendarCell';
export interface CalendarCellDriver extends BaseUniDriver {
hasTimeType(time... | ,
async hasTimeType(timeType) {
return (await base.attr(CALENDAR_DATA_KEYS.TimeType)) === timeType;
},
async hasCurrent() {
return (await base.attr(CALENDAR_DATA_KEYS.Current)) === 'true';
},
async hasRightAlignment(mockAlignment) {
return (await base.attr(CALENDAR_DATA_KEYS.Alignm... | {
return (await base.attr(CALENDAR_DATA_KEYS.Stertchable)) === 'true';
} | identifier_body |
gyp_to_android.py | #!/usr/bin/python
# Copyright 2014 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Script for generating the Android framework's version of Skia from gyp
files.
"""
import android_framework_gyp
import os
import shutil
import sys
import tempfile
... | # so that it is a sibling of gyp/, so the relationships between gyp files and
# other files (e.g. platform_tools/android/gyp/dependencies.gypi, referenced
# by android_deps.gyp as a relative path) is unchanged.
# Use mkdtemp to find an unused folder name, but then delete it so copytree
# can be called with a ... | """
# Create a temporary folder to hold gyp and gypd files. Create it in SKIA_DIR | random_line_split |
gyp_to_android.py | #!/usr/bin/python
# Copyright 2014 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Script for generating the Android framework's version of Skia from gyp
files.
"""
import android_framework_gyp
import os
import shutil
import sys
import tempfile
... |
def generate_var_dict(target_dir, target_file, skia_arch_type, have_neon):
"""
Create a VarsDict for a particular arch type. Each paramater is passed
directly to android_framework_gyp.main().
@param target_dir Directory containing gyp files.
@param target_file Target gyp file.
@param skia_arch_type Target... | if f.endswith('gypd'):
os.remove(os.path.join(folder, f)) | conditional_block |
gyp_to_android.py | #!/usr/bin/python
# Copyright 2014 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Script for generating the Android framework's version of Skia from gyp
files.
"""
import android_framework_gyp
import os
import shutil
import sys
import tempfile
... | (target_dir, target_file, skia_arch_type, have_neon):
"""
Create a VarsDict for a particular arch type. Each paramater is passed
directly to android_framework_gyp.main().
@param target_dir Directory containing gyp files.
@param target_file Target gyp file.
@param skia_arch_type Target architecture.
@param... | generate_var_dict | identifier_name |
gyp_to_android.py | #!/usr/bin/python
# Copyright 2014 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Script for generating the Android framework's version of Skia from gyp
files.
"""
import android_framework_gyp
import os
import shutil
import sys
import tempfile
... |
# Generate a separate VarsDict for each architecture type. For each
# archtype:
# 1. call android_framework_gyp.main() to generate gypd files
# 2. call parse_gypd to read those gypd files into the VarsDict
# 3. delete the gypd files
#
# Once we have the VarsDict for each architecture type,... | """
Read gyp files and create Android.mk for the Android framework's
external/skia.
@param target_dir Directory in which to place 'Android.mk'. If None, the file
will be placed in skia's root directory.
"""
# Create a temporary folder to hold gyp and gypd files. Create it in SKIA_DIR
# s... | identifier_body |
cryptography.rs | pub use rust_sodium::crypto::box_::curve25519xsalsa20poly1305 as crypto_box;
pub use rust_sodium::crypto::hash::sha256;
pub use rust_sodium::crypto::scalarmult::curve25519 as scalarmult;
pub use self::crypto_box::{PrecomputedKey, PublicKey, SecretKey};
use auth_failure::AuthFailure;
/// Number of bytes in a password... |
/// Randomly generates a secret key and a corresponding public key.
///
/// THREAD SAFETY: `gen_keypair()` is thread-safe provided that you
/// have called `fcp_cryptoauth::init()` (or `rust_sodium::init()`)
/// once before using any other function from `fcp_cryptoauth` or
/// `rust_sodium`.
pub fn gen_keypair() -> (... | {
if packet_end.len() < crypto_box::MACBYTES {
return Err(AuthFailure::PacketTooShort(format!(
"Packet end: {}",
packet_end.len()
)));
}
match crypto_box::open_precomputed(packet_end, nonce, &shared_secret) {
Err(_) => Err(AuthFailure::CorruptedPacket(
... | identifier_body |
cryptography.rs | pub use rust_sodium::crypto::box_::curve25519xsalsa20poly1305 as crypto_box;
pub use rust_sodium::crypto::hash::sha256;
pub use rust_sodium::crypto::scalarmult::curve25519 as scalarmult;
pub use self::crypto_box::{PrecomputedKey, PublicKey, SecretKey};
use auth_failure::AuthFailure;
/// Number of bytes in a password... |
match crypto_box::open_precomputed(packet_end, nonce, &shared_secret) {
Err(_) => Err(AuthFailure::CorruptedPacket(
"Could not decrypt handshake packet end.".to_owned(),
)),
Ok(buf) => {
let mut pk = [0u8; crypto_box::PUBLICKEYBYTES];
pk.copy_from_slice(&... | {
return Err(AuthFailure::PacketTooShort(format!(
"Packet end: {}",
packet_end.len()
)));
} | conditional_block |
cryptography.rs | pub use rust_sodium::crypto::box_::curve25519xsalsa20poly1305 as crypto_box;
pub use rust_sodium::crypto::hash::sha256;
pub use rust_sodium::crypto::scalarmult::curve25519 as scalarmult;
pub use self::crypto_box::{PrecomputedKey, PublicKey, SecretKey};
use auth_failure::AuthFailure;
/// Number of bytes in a password... | return Err(AuthFailure::PacketTooShort(format!(
"Packet end: {}",
packet_end.len()
)));
}
match crypto_box::open_precomputed(packet_end, nonce, &shared_secret) {
Err(_) => Err(AuthFailure::CorruptedPacket(
"Could not decrypt handshake packet end.".to_o... | shared_secret: &PrecomputedKey,
nonce: &crypto_box::Nonce,
) -> Result<(PublicKey, Vec<u8>), AuthFailure> {
if packet_end.len() < crypto_box::MACBYTES { | random_line_split |
cryptography.rs | pub use rust_sodium::crypto::box_::curve25519xsalsa20poly1305 as crypto_box;
pub use rust_sodium::crypto::hash::sha256;
pub use rust_sodium::crypto::scalarmult::curve25519 as scalarmult;
pub use self::crypto_box::{PrecomputedKey, PublicKey, SecretKey};
use auth_failure::AuthFailure;
/// Number of bytes in a password... | (my_sk: &SecretKey, their_pk: &PublicKey) -> PrecomputedKey {
crypto_box::precompute(their_pk, my_sk)
}
/// unseals the concatenation of fields msg_auth_code, sender_encrypted_temp_pk, and
/// encrypted_data of a packet.
/// If authentication was successful, returns the sender's temp_pk and the
/// data, unencrypt... | shared_secret_from_keys | identifier_name |
tagme.py |
self.cmn_th = 0.02
self.k_th = 0.3
self.link_probs = {}
self.in_links = {}
self.rel_scores = {} # dictionary {men: {en: rel_score, ...}, ...}
self.disamb_ens = {}
def parse(self):
"""
Parses the query and returns all candidate mention-entity pairs.... |
def __get_coherence_score(self, men, en, dismab_ens):
"""
coherence_score = sum_e_i(rel(e_i, en)) / len(ens) - 1
:param en: entity
:param dismab_ens: {men: (dbp_uri, fb_id), ....}
"""
coh_score = 0
for m_i, e_i in dismab_ens.iteritems():
if m_i... | """
returns "and" occurrences of entities in the corpus.
:param en_uris: list of dbp_uris
"""
en_uris = tuple(sorted(set(en_uris)))
if en_uris in self.in_links:
return self.in_links[en_uris]
term_queries = []
for en_uri in en_uris:
term_q... | identifier_body |
tagme.py |
self.cmn_th = 0.02
self.k_th = 0.3
self.link_probs = {}
self.in_links = {}
self.rel_scores = {} # dictionary {men: {en: rel_score, ...}, ...}
self.disamb_ens = {}
def parse(self):
"""
Parses the query and returns all candidate mention-entity pairs.... |
conj = self.__get_in_links(en_uris)
if conj == 0:
return 0
numerator = math.log(max(ens_in_links)) - math.log(conj)
denominator = math.log(ANNOT_INDEX.num_docs()) - math.log(min(ens_in_links))
rel = 1 - (numerator / denominator)
if rel < 0:
return... | return 0 | conditional_block |
tagme.py |
self.cmn_th = 0.02
self.k_th = 0.3
self.link_probs = {}
self.in_links = {}
self.rel_scores = {} # dictionary {men: {en: rel_score, ...}, ...}
self.disamb_ens = {}
def parse(self):
"""
Parses the query and returns all candidate mention-entity pairs.... | (self, mention):
"""Returns top-k percent of the entities based on rel score."""
| __get_top_k | identifier_name |
tagme.py |
self.cmn_th = 0.02
self.k_th = 0.3
self.link_probs = {}
self.in_links = {}
self.rel_scores = {} # dictionary {men: {en: rel_score, ...}, ...}
self.disamb_ens = {}
def parse(self):
"""
Parses the query and returns all candidate mention-entity pairs.... |
:param dismab_ens: {men: en, ... }
:return: {men: (en, score), ...}
"""
linked_ens = {}
for men, en in dismab_ens.iteritems():
coh_score = self.__get_coherence_score(men, en, dismab_ens)
rho_score = (self.link_probs[men] + coh_score) / 2.0
if ... |
def prune(self, dismab_ens):
"""
Performs AVG pruning. | random_line_split |
las.rs | //! Sink points into a las file.
use std::io::{Write, Seek};
use std::path::Path;
use las;
use Result;
use error::Error;
use point::{Point, ScanDirection};
use sink::{FileSink, Sink};
impl<W: Write + Seek> Sink for las::writer::OpenWriter<W> {
fn sink(&mut self, point: &Point) -> Result<()> {
try!(self.... |
}
/// Simple wrapper around x, y, and z scale factors.
#[derive(Clone, Copy, Debug, RustcDecodable)]
pub struct ScaleFactors {
x: f64,
y: f64,
z: f64,
}
/// Simple wrapper around version pair.
#[derive(Clone, Copy, Debug, RustcDecodable)]
pub struct Version {
major: u8,
minor: u8,
}
#[cfg(test)]... | {
LasConfig {
auto_offsets: Some(true),
point_format: Some(1),
version: Some(Version { major: 1, minor: 2}),
scale_factors: None,
}
} | identifier_body |
las.rs | //! Sink points into a las file.
use std::io::{Write, Seek};
use std::path::Path;
use las;
use Result;
use error::Error;
use point::{Point, ScanDirection};
use sink::{FileSink, Sink};
impl<W: Write + Seek> Sink for las::writer::OpenWriter<W> {
fn sink(&mut self, point: &Point) -> Result<()> {
try!(self.... | let mut writer = try!(las::Writer::from_path(path));
if let Some(s) = config.scale_factors {
writer = writer.scale_factors(s.x, s.y, s.z);
}
if let Some(a) = config.auto_offsets {
writer = writer.auto_offsets(a);
}
if let Some(p) = config.point_for... | random_line_split | |
las.rs | //! Sink points into a las file.
use std::io::{Write, Seek};
use std::path::Path;
use las;
use Result;
use error::Error;
use point::{Point, ScanDirection};
use sink::{FileSink, Sink};
impl<W: Write + Seek> Sink for las::writer::OpenWriter<W> {
fn | (&mut self, point: &Point) -> Result<()> {
try!(self.write_point(&try!(from_point(point))));
Ok(())
}
fn close_sink(self: Box<Self>) -> Result<()> {
self.close().map_err(|e| Error::from(e)).map(|_| ())
}
}
fn from_point(point: &Point) -> Result<las::Point> {
Ok(las::Point {
... | sink | identifier_name |
isb_auth.py | #
# Copyright 2015-2019, Institute for Systems Biology
#
# 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 ... | from oauth2client.file import Storage
VERBOSE = False
# for native application - same as settings.INSTALLED_APP_CLIENT_ID
CLIENT_ID = '586186890913-atr969tu3lf7u574khjjplb45fgpq1bg.apps.googleusercontent.com'
# NOTE: this is NOT actually a 'secret' -- we're using the 'installed
# application' OAuth pattern here
CLIENT... | import os
from oauth2client.client import OAuth2WebServerFlow
from oauth2client import tools | random_line_split |
isb_auth.py | #
# Copyright 2015-2019, Institute for Systems Biology
#
# 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 ... |
credentials = storage.get()
if not credentials or credentials.invalid:
maybe_print('credentials missing/invalid, kicking off OAuth flow')
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, EMAIL_SCOPE)
flow.auth_uri = flow.auth_uri.rstrip('/') + '?approval_prompt=force'
creden... | storage = Storage(DEFAULT_STORAGE_FILE) | conditional_block |
isb_auth.py | #
# Copyright 2015-2019, Institute for Systems Biology
#
# 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 ... | (msg):
if VERBOSE:
print(msg)
def get_credentials(storage=None, oauth_flow_args=[]):
noweb = '--noauth_local_webserver'
if __name__ != '__main__' and noweb not in oauth_flow_args:
oauth_flow_args.append(noweb)
if storage is None:
storage = Storage(DEFAULT_STORAGE_FILE)
cred... | maybe_print | identifier_name |
isb_auth.py | #
# Copyright 2015-2019, Institute for Systems Biology
#
# 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 ... |
if __name__ == '__main__':
main() | parser = ArgumentParser()
parser.add_argument('--storage_file', '-s', default=DEFAULT_STORAGE_FILE, help='storage file to use for the credentials (default is {})'.format(DEFAULT_STORAGE_FILE))
parser.add_argument('--verbose', '-v', dest='verbose', action='store_true', help='display credentials storage location,... | identifier_body |
pybrctl.py | import subprocess
from distutils import spawn
brctlexe = spawn.find_executable("brctl")
ipexe = spawn.find_executable("ip")
class BridgeException(Exception):
pass
class Bridge(object):
def __init__(self, name):
""" Initialize a bridge object. """
self.name = name
def __str__(self):
... |
def _runshell(cmd, exception):
""" Run a shell command. if fails, raise a proper exception. """
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if p.wait() != 0:
raise BridgeException(exception)
return p
| """ Return a bridge object."""
for br in self.showall():
if br.name == name:
return br
raise BridgeException("Bridge does not exist.") | identifier_body |
pybrctl.py | import subprocess
from distutils import spawn
brctlexe = spawn.find_executable("brctl")
ipexe = spawn.find_executable("ip")
class BridgeException(Exception):
pass
class Bridge(object):
def __init__(self, name):
""" Initialize a bridge object. """
self.name = name
def __str__(self):
... | (self):
""" Return a list of mac addresses. """
raise NotImplementedError()
def showstp(self):
""" Return STP information. """
raise NotImplementedError()
class BridgeController(object):
def addbr(self, name):
""" Create a bridge and set the device up. """
... | showmacs | identifier_name |
pybrctl.py | import subprocess
from distutils import spawn
brctlexe = spawn.find_executable("brctl")
ipexe = spawn.find_executable("ip")
class BridgeException(Exception):
pass
class Bridge(object):
def __init__(self, name):
""" Initialize a bridge object. """
self.name = name
def __str__(self):
... |
def _runshell(cmd, exception):
""" Run a shell command. if fails, raise a proper exception. """
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if p.wait() != 0:
raise BridgeException(exception)
return p | raise BridgeException("Bridge does not exist.")
| random_line_split |
pybrctl.py | import subprocess
from distutils import spawn
brctlexe = spawn.find_executable("brctl")
ipexe = spawn.find_executable("ip")
class BridgeException(Exception):
pass
class Bridge(object):
def __init__(self, name):
""" Initialize a bridge object. """
self.name = name
def __str__(self):
... |
else: state = 'off'
_runshell([brctlexe, 'stp', self.name, state],
"Could not set stp on %s." % self.name)
def setageing(self, time):
""" Set bridge ageing time. """
_runshell([brctlexe, 'setageing', self.name, str(time)],
"Could not set ageing time in %s."... | state = 'on' | conditional_block |
ItemPicker.tsx | import React from 'react';
import { DimItem } from '../inventory/item-types';
import { ItemPickerState } from './item-picker';
import Sheet from '../dim-ui/Sheet';
import ConnectedInventoryItem from '../inventory/ConnectedInventoryItem';
import { connect, MapStateToProps } from 'react-redux';
import { RootState } from ... |
const mapDispatchToProps = {
setSetting
};
type DispatchProps = typeof mapDispatchToProps;
type Props = ProvidedProps & StoreProps & DispatchProps;
interface State {
query: string;
equip: boolean;
height?: number;
}
class ItemPicker extends React.Component<Props, State> {
state: State = {
query: '',
... | {
const filteredItemsSelector = createSelector(
storesSelector,
(_: RootState, ownProps: ProvidedProps) => ownProps.filterItems,
(stores, filterItems) =>
stores.flatMap((s) => (filterItems ? s.items.filter(filterItems) : s.items))
);
return (state, ownProps) => ({
allItems: filteredItemsSel... | identifier_body |
ItemPicker.tsx | import React from 'react';
import { DimItem } from '../inventory/item-types';
import { ItemPickerState } from './item-picker';
import Sheet from '../dim-ui/Sheet';
import ConnectedInventoryItem from '../inventory/ConnectedInventoryItem';
import { connect, MapStateToProps } from 'react-redux';
import { RootState } from ... |
}
componentDidUpdate() {
if (this.itemContainer.current && !this.state.height) {
this.setState({ height: this.itemContainer.current.clientHeight });
}
}
render() {
const {
allItems,
prompt,
searchConfig,
filters,
itemSortOrder,
hideStoreEquip,
sortB... | {
this.setState({ height: this.itemContainer.current.clientHeight });
} | conditional_block |
ItemPicker.tsx | import React from 'react';
import { DimItem } from '../inventory/item-types';
import { ItemPickerState } from './item-picker';
import Sheet from '../dim-ui/Sheet';
import ConnectedInventoryItem from '../inventory/ConnectedInventoryItem';
import { connect, MapStateToProps } from 'react-redux';
import { RootState } from ... | () {
if (this.itemContainer.current && !this.state.height) {
this.setState({ height: this.itemContainer.current.clientHeight });
}
}
render() {
const {
allItems,
prompt,
searchConfig,
filters,
itemSortOrder,
hideStoreEquip,
sortBy
} = this.props;
... | componentDidUpdate | identifier_name |
ItemPicker.tsx | import React from 'react';
import { DimItem } from '../inventory/item-types';
import { ItemPickerState } from './item-picker';
import Sheet from '../dim-ui/Sheet';
import ConnectedInventoryItem from '../inventory/ConnectedInventoryItem';
import { connect, MapStateToProps } from 'react-redux';
import { RootState } from ... | const filteredItemsSelector = createSelector(
storesSelector,
(_: RootState, ownProps: ProvidedProps) => ownProps.filterItems,
(stores, filterItems) =>
stores.flatMap((s) => (filterItems ? s.items.filter(filterItems) : s.items))
);
return (state, ownProps) => ({
allItems: filteredItemsSelec... |
function mapStateToProps(): MapStateToProps<StoreProps, ProvidedProps, RootState> { | random_line_split |
streamgraph.src.js | /**
* @license Highcharts JS v6.0.6 (2018-02-05)
* Streamgraph module
*
* (c) 2010-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function(factory) {
if (typeof module === 'object' && module.exports) | else {
factory(Highcharts);
}
}(function(Highcharts) {
(function(H) {
/**
* Streamgraph module
*
* (c) 2010-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
var seriesType = H.seriesType;
/**
* A stre... | {
module.exports = factory;
} | conditional_block |
streamgraph.src.js | /**
* @license Highcharts JS v6.0.6 (2018-02-05)
* Streamgraph module
*
* (c) 2010-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function(factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
factory(Highcharts);... | * @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
* @product highcharts highstock
* @apioption series.streamgraph.data
*/
}(Highcharts));
})); | * Arrays of point.name and y | random_line_split |
image.spec.tsx | import React from "react";
import { shallow } from "enzyme";
import ImageDisplay, {
PNGDisplay,
GIFDisplay,
JPEGDisplay
} from "../src/image";
const imageData = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
describe("ImageDisplay", () => {
it("creates an image based on data and mimetype", () =>... |
const img2 = component2.find("img");
expect(img2.prop("width")).toEqual("200");
expect(img2.prop("height")).toEqual("300");
});
});
describe("PNGDisplay", () => {
it("renders a single image base64 inline", () => {
const component = shallow(<PNGDisplay data={imageData} />);
expect(
compo... | random_line_split | |
frequency.rs | //! System and Hardware Clocks
/// Internal Oscillator
pub const HSI: u32 = 8_000_000;
/// External clock
pub const HSE: u32 = 8_000_000;
use stm32f103xx::{Rcc, Flash, rcc};
/// Board clock speeds
pub struct | {
/// System Clock
pub sysclk: u32,
/// AHB peripheral clock
pub hclk: u32,
/// Low speed bus
pub apb1: u32,
/// high speed bus
pub apb2: u32,
}
impl ClockSpeeds {
/// Get clock speeds
pub fn get(rcc: &Rcc) -> ClockSpeeds {
let sysclk = match rcc.cfgr.read().sws(){
... | ClockSpeeds | identifier_name |
frequency.rs | //! System and Hardware Clocks
/// Internal Oscillator
pub const HSI: u32 = 8_000_000;
/// External clock
pub const HSE: u32 = 8_000_000;
use stm32f103xx::{Rcc, Flash, rcc};
/// Board clock speeds
pub struct ClockSpeeds{
/// System Clock
pub sysclk: u32,
/// AHB peripheral clock
pub hclk: u32,
//... | rcc::cfgr::Ppre1R::Div16 => hclk / 16,
_ => hclk,
};
let apb2 = match rcc.cfgr.read().ppre2() {
rcc::cfgr::Ppre2R::Div2 => hclk / 2,
rcc::cfgr::Ppre2R::Div4 => hclk / 4,
rcc::cfgr::Ppre2R::Div8 => hclk / 8,
rcc::cfgr::Ppre2R::Div16... | random_line_split | |
frequency.rs | //! System and Hardware Clocks
/// Internal Oscillator
pub const HSI: u32 = 8_000_000;
/// External clock
pub const HSE: u32 = 8_000_000;
use stm32f103xx::{Rcc, Flash, rcc};
/// Board clock speeds
pub struct ClockSpeeds{
/// System Clock
pub sysclk: u32,
/// AHB peripheral clock
pub hclk: u32,
//... | rcc::cfgr::Ppre1R::Div2 => hclk / 2,
rcc::cfgr::Ppre1R::Div4 => hclk / 4,
rcc::cfgr::Ppre1R::Div8 => hclk / 8,
rcc::cfgr::Ppre1R::Div16 => hclk / 16,
_ => hclk,
};
let apb2 = match rcc.cfgr.read().ppre2() {
rcc::cfgr::Ppre2R::Div2 ... | {
let sysclk = match rcc.cfgr.read().sws(){
rcc::cfgr::SwsR::Hse => HSE,
rcc::cfgr::SwsR::Pll => Self::get_pll_speed(rcc),
_ => HSI,
};
let hclk = match rcc.cfgr.read().hpre() {
rcc::cfgr::HpreR::Div2 => sysclk / 2,
rcc::cfgr::HpreR::D... | identifier_body |
mod.rs | /*
* niepce - fwk/base/mod.rs
*
* Copyright (C) 2017-2021 Hubert Figuière
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any lat... |
use std::collections::BTreeSet;
#[macro_use]
pub mod debug;
pub mod date;
pub mod fractions;
pub mod propertybag;
pub mod propertyvalue;
pub mod rgbcolour;
pub type PropertyIndex = u32;
pub type PropertySet<T> = BTreeSet<T>;
pub use self::propertyvalue::PropertyValue; | random_line_split | |
test_wapi_metrics.py | import uuid
from unithelper import DBTestCase
from unithelper import mocker
from unithelper import requestor
from unithelper import hashable_dict
from bc import database
from bc import metrics
from bc_wapi import wapi_metrics
class Test(DBTestCase):
def test_metric_get(self):
"""Check getting metric with metri... | (self):
"""Check getting metrics with metricList"""
data = []
for i in range(2, 10):
d={
'id': str(uuid.uuid4()),
'type': str(uuid.uuid4())[:10],
'formula': metrics.constants.FORMULA_SPEED,
'aggregate': 0L,
}
with database.DBConnect() as db:
db.insert('metrics', d)... | test_metric_get_list | identifier_name |
test_wapi_metrics.py | import uuid
from unithelper import DBTestCase
from unithelper import mocker
from unithelper import requestor
from unithelper import hashable_dict
from bc import database
from bc import metrics
from bc_wapi import wapi_metrics
class Test(DBTestCase):
def test_metric_get(self):
"""Check getting metric with metri... |
ans = wapi_metrics.metricList('')
self.assertEquals(ans[0], (01 << 2))
self.assertEquals(ans[1]['status'], 'ok')
self.assertEquals(set(map(lambda x: hashable_dict(x), ans[1]['metrics'])),
set(map(lambda x: hashable_dict(x), data)))
with mocker([('bc.metrics.get_all', mocker.exception),
('bc_wapi.... | d={
'id': str(uuid.uuid4()),
'type': str(uuid.uuid4())[:10],
'formula': metrics.constants.FORMULA_SPEED,
'aggregate': 0L,
}
with database.DBConnect() as db:
db.insert('metrics', d)
data.append(d) | conditional_block |
test_wapi_metrics.py | import uuid
from unithelper import DBTestCase
from unithelper import mocker
from unithelper import requestor
from unithelper import hashable_dict
from bc import database
from bc import metrics
from bc_wapi import wapi_metrics
class Test(DBTestCase):
def test_metric_get(self):
"""Check getting metric with metri... | self.assertEquals(set(map(lambda x: hashable_dict(x), ans[1]['metrics'])),
set(map(lambda x: hashable_dict(x), data)))
with mocker([('bc.metrics.get_all', mocker.exception),
('bc_wapi.wapi_metrics.LOG.error', mocker.passs)]):
self.assertEquals(wapi_metrics.metricList({'id':''}),
requestor({'message... | """Check getting metrics with metricList"""
data = []
for i in range(2, 10):
d={
'id': str(uuid.uuid4()),
'type': str(uuid.uuid4())[:10],
'formula': metrics.constants.FORMULA_SPEED,
'aggregate': 0L,
}
with database.DBConnect() as db:
db.insert('metrics', d)
data.... | identifier_body |
test_wapi_metrics.py | import uuid
from unithelper import DBTestCase
from unithelper import mocker
from unithelper import requestor
from unithelper import hashable_dict
from bc import database
from bc import metrics
from bc_wapi import wapi_metrics
class Test(DBTestCase):
def test_metric_get(self):
"""Check getting metric with metri... | 'formula': metrics.constants.FORMULA_SPEED,
'aggregate': 0L,
}
with database.DBConnect() as db:
db.insert('metrics', d)
data.append(d)
ans = wapi_metrics.metricList('')
self.assertEquals(ans[0], (01 << 2))
self.assertEquals(ans[1]['status'], 'ok')
self.assertEquals(set(map(lambda x:... | random_line_split | |
test_io.py | import os
from numpy.testing import assert_array_equal, raises, run_module_suite
import numpy as np
import skimage.io as io
from skimage.io.manage_plugins import plugin_store
from skimage import data_dir
def test_stack_basic():
x = np.arange(12).reshape(3, 4)
io.push(x)
assert_array_equal(io.pop(), x)
... | run_module_suite() | conditional_block | |
test_io.py | import os
from numpy.testing import assert_array_equal, raises, run_module_suite
import numpy as np
import skimage.io as io
from skimage.io.manage_plugins import plugin_store
from skimage import data_dir
def test_stack_basic():
x = np.arange(12).reshape(3, 4)
io.push(x)
assert_array_equal(io.pop(), x)
... |
def test_imread_url():
# tweak data path so that file URI works on both unix and windows.
data_path = data_dir.lstrip(os.path.sep)
data_path = data_path.replace(os.path.sep, '/')
image_url = 'file:///{0}/camera.png'.format(data_path)
image = io.imread(image_url)
assert image.shape == (512, 51... | io.push([[1, 2, 3]]) | identifier_body |
test_io.py | import os
from numpy.testing import assert_array_equal, raises, run_module_suite
import numpy as np
import skimage.io as io
from skimage.io.manage_plugins import plugin_store
from skimage import data_dir
def | ():
x = np.arange(12).reshape(3, 4)
io.push(x)
assert_array_equal(io.pop(), x)
@raises(ValueError)
def test_stack_non_array():
io.push([[1, 2, 3]])
def test_imread_url():
# tweak data path so that file URI works on both unix and windows.
data_path = data_dir.lstrip(os.path.sep)
data_pat... | test_stack_basic | identifier_name |
select_model.py |
#Tables for component selection
Kappas = np.zeros([nc])
Rhos = np.zeros([nc])
varex = np.zeros([nc])
varex_norm = np.zeros([nc])
Z_maps = np.zeros([Nm,nc])
F_R2_maps = np.zeros([Nm,nc])
F_S0_maps = np.zeros([Nm,nc])
Z_clmaps = np.zeros([Nm,nc])
F_R2_clmaps = np.zeros([Nm,nc])
F_S0_clmaps = np.zeros([Nm,nc]... | """
LOW_PERC=25
HIGH_PERC=90
EXTEND_FACTOR=2
try:
if nt<100: EXTEND_FACTOR=3
except: pass
RESTRICT_FACTOR=2
if knobargs!='':
for knobarg in ''.join(knobargs).split(','): exec(knobarg)
"""
Do some tallies for no. of significant voxels
"""
countsigZ = Z_clmaps.sum(0)
countsigFS0 = F_S0_clmaps.sum(0)
c... | for key in seldict.keys(): exec("%s=seldict['%s']" % (key,key))
#List of components
midk = []
ign = []
nc = np.arange(len(Kappas))
ncl = np.arange(len(Kappas))
#If user has specified
try:
if options.manacc:
acc = sorted([int(vv) for vv in options.manacc.split(',')])
midk = []
rej = sorted(np.setdif... | identifier_body |
select_model.py | #Tables for component selection
Kappas = np.zeros([nc])
Rhos = np.zeros([nc])
varex = np.zeros([nc])
varex_norm = np.zeros([nc])
Z_maps = np.zeros([Nm,nc])
F_R2_maps = np.zeros([Nm,nc])
F_S0_maps = np.zeros([Nm,nc])
Z_clmaps = np.zeros([Nm,nc])
F_R2_clmaps = np.zeros([Nm,nc])
F_S0_clmaps = np.zeros([Nm,nc])
... | (seldict,debug=False,olevel=2,oversion=99,knobargs=''):
#import ipdb
#Dump dictionary into variable names
for key in seldict.keys(): exec("%s=seldict['%s']" % (key,key))
#List of components
midk = []
ign = []
nc = np.arange(len(Kappas))
ncl = np.arange(len(Kappas))
#If user has specified
try:
if option... | selcomps | identifier_name |
select_model.py | WTS','varex','Z_maps','Z_clmaps','F_R2_clmaps','F_S0_clmaps','Br_clmaps_R2','Br_clmaps_S0']
for vv in selvars:
with open('compsel.debug/%s.pkl.gz' % vv,'wb') as ofh:
print "Writing debug output: compsel.debug/%s.pkl.gz" % vv
ofh.write(zlib.compress(cP.dumps(eval(vv))))
ofh.close()
return seldict... | midkadd = np.union1d(midkadd,np.intersect1d(candartA,candartA[varex[candartA]>varex_ub*EXTEND_FACTOR]))
candartB = ncl[d_table_score>num_acc_guess*d_table_rank.shape[1]*HIGH_PERC/100.] | random_line_split | |
select_model.py | ptab[:,0],dtype=np.int)
mmix_new = mmix[:,nnc]
F_S0_maps = F_S0_maps[:,nnc]; F_R2_maps = F_R2_maps[:,nnc]; Z_maps = Z_maps[:,nnc]
WTS = WTS[:,nnc]; PSC=PSC[:,nnc]; tsoc_B=tsoc_B[:,nnc]; tsoc_Babs=tsoc_Babs[:,nnc]
comptab[:,0] = np.arange(comptab.shape[0])
else:
comptab = comptab_pre
mmix_new = mmix
#Full... | ncls = ncls[1:][(varex[ncls][1:]-varex[ncls][:-1])<varex_ub_p] #Step 2a | conditional_block | |
grid.filter.js | {
rule.field = $(ruleFieldSelect).val();
trpar = $(this).parents("tr:first");
for (i=0;i<that.p.columns.length;i++) {
if(that.p.columns[i].name === rule.field) {
cm = that.p.columns[i];
break;
}
}
if(!cm) {return;}
cm.searchoptions.id = $.jgrid.randId();
if(isIE && c... | {
for (index = 0; index < group.groups.length; index++) {
if (s.length > 1) {
s += " " + group.groupOp + " ";
}
try {
s += this.getStringForGroup(group.groups[index]);
} catch (eg) {alert(eg);}
}
} | conditional_block | |
grid.filter.js | if(this.p.showQuery) {
$(this).append("<table class='queryresult ui-widget ui-widget-content' style='display:block;max-width:440px;border:0px none;' dir='"+this.p.direction+"'><tbody><tr><td class='query'></td></tr></tbody></table>");
}
var getGrid = function () {
return $("#" + $.jgrid.jqID(p.id))[0] || nu... | random_line_split | ||
grid.filter.js | }
ruleFieldSelect.append( str );
// create operator container
var ruleOperatorTd = $("<td class='operators'></td>");
tr.append(ruleOperatorTd);
cm = p.columns[j];
// create it here so it can be referentiated in the onchange event
//var RD = that.createElement(rule, rule.data);
cm.searchoptions... | {
var s = "(", index;
if (group.groups !== undefined) {
for (index = 0; index < group.groups.length; index++) {
if (s.length > 1) {
if (group.groupOp === "OR") {
s += " || ";
}
else {
s += " && ";
}
}
s += getStringForGroup(group.groups[index])... | identifier_body | |
grid.filter.js | ].search === undefined) ? true: that.p.columns[i].search,
hidden = (that.p.columns[i].hidden === true),
ignoreHiding = (that.p.columns[i].searchoptions.searchhidden === true);
if ((ignoreHiding && searchable) || (searchable && !hidden)) {
selected = "";
if(rule.field === that.p.columns[i].name) {
... | getStringForGroup | identifier_name | |
runner.py | NOWN_TEST_RUNNERS = ('TestDataflowRunner',)
_RUNNER_MAP = {}
_RUNNER_MAP.update(_get_runner_map(_KNOWN_DIRECT_RUNNERS,
_DIRECT_RUNNER_PATH))
_RUNNER_MAP.update(_get_runner_map(_KNOWN_DATAFLOW_RUNNERS,
_DATAFLOW_RUNNER_PATH))
_RUNNER_MAP.update(_get_... | CANCELLED = 'CANCELLED' # explicitly cancelled (terminal state)
UPDATED = 'UPDATED' # replaced by another job (terminal state) | random_line_split | |
runner.py | 'PipelineResult']
def _get_runner_map(runner_names, module_path):
"""Create a map of runner name in lower case to full import path to the
runner class.
"""
return {runner_name.lower(): module_path + runner_name
for runner_name in runner_names}
_DIRECT_RUNNER_PATH = 'apache_beam.runners.direct.dir... |
raise NotImplementedError(
'Execution of [%s] not implemented in runner %s.' % (
transform_node.transform, self))
class PValueCache(object):
"""For internal use only; no backwards-compatibility guarantees.
Local cache for arbitrary information computed for PValue objects."""
def __ini... | m = getattr(self, 'run_%s' % cls.__name__, None)
if m:
return m(transform_node) | conditional_block |
runner.py | (runner_name.lower() + 'runner', runner_name))
if '.' in runner_name:
module, runner = runner_name.rsplit('.', 1)
try:
return getattr(__import__(module, {}, {}, [runner], -1), runner)()
except ImportError:
if runner_name in _KNOWN_DATAFLOW_RUNNERS:
raise ImportError(
'Goog... | metrics | identifier_name | |
runner.py | ', 'PipelineResult']
def _get_runner_map(runner_names, module_path):
"""Create a map of runner name in lower case to full import path to the
runner class.
"""
return {runner_name.lower(): module_path + runner_name
for runner_name in runner_names}
_DIRECT_RUNNER_PATH = 'apache_beam.runners.direct.d... |
pipeline.visit(RunVisitor(self))
def apply(self, transform, input):
"""Runner callback for a pipeline.apply call.
Args:
transform: the transform to apply.
input: transform's input (typically a PCollection).
A concrete implementation of the Runner class may want to do custom
pipeli... | def __init__(self, runner):
self.runner = runner
def visit_transform(self, transform_node):
try:
self.runner.run_transform(transform_node)
except:
logging.error('Error while visiting %s', transform_node.full_label)
raise | identifier_body |
karma.conf.js | // Karma configuration
// Generated on Fri Feb 26 2016 16:59:16 GMT+0900 (JST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/k... | // if true, Karma captures browsers, runs the tests and exits
singleRun: true,
browserNoActivityTimeout: 90000
})
} | browsers: ['Chrome'],
// Continuous Integration mode | random_line_split |
lib.rs | // =================================================================
//
// * WARNING *
//
// This file is generated!
//
// Changes made to this file will be overwritten. If changes are
// required to the generated code, the service_crategen project
// must be updated to g... | pub use generated::*; | pub use custom::*; | random_line_split |
decoder.rs | use std::io;
use std::io::Read;
use std::default::Default;
use byteorder::{ReadBytesExt, LittleEndian};
use image;
use image::ImageResult;
use image::ImageDecoder;
use color;
use super::vp8::Frame;
use super::vp8::VP8Decoder;
/// A Representation of a Webp Image format decoder.
pub struct WebpDecoder<R> {
r: ... | (&mut self) -> ImageResult<usize> {
try!(self.read_metadata());
Ok(self.frame.width as usize)
}
fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32> {
try!(self.read_metadata());
if self.decoded_rows > self.frame.height as u32 {
return Err(image::ImageEr... | row_len | identifier_name |
decoder.rs | use std::io;
use std::io::Read;
use std::default::Default;
use byteorder::{ReadBytesExt, LittleEndian};
use image;
use image::ImageResult;
use image::ImageDecoder;
use color;
use super::vp8::Frame;
use super::vp8::VP8Decoder;
/// A Representation of a Webp Image format decoder.
pub struct WebpDecoder<R> {
r: ... | let mut webp = Vec::with_capacity(4);
try!(self.r.by_ref().take(4).read_to_end(&mut webp));
if &*riff != b"RIFF" {
return Err(image::ImageError::FormatError("Invalid RIFF signature.".to_string()))
}
if &*webp != b"WEBP" {
return Err(image::ImageError::Fo... | let mut riff = Vec::with_capacity(4);
try!(self.r.by_ref().take(4).read_to_end(&mut riff));
let size = try!(self.r.read_u32::<LittleEndian>()); | random_line_split |
decoder.rs | use std::io;
use std::io::Read;
use std::default::Default;
use byteorder::{ReadBytesExt, LittleEndian};
use image;
use image::ImageResult;
use image::ImageDecoder;
use color;
use super::vp8::Frame;
use super::vp8::VP8Decoder;
/// A Representation of a Webp Image format decoder.
pub struct WebpDecoder<R> {
r: ... |
fn colortype(&mut self) -> ImageResult<color::ColorType> {
Ok(color::ColorType::Gray(8))
}
fn row_len(&mut self) -> ImageResult<usize> {
try!(self.read_metadata());
Ok(self.frame.width as usize)
}
fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32> {
... | {
try!(self.read_metadata());
Ok((self.frame.width as u32, self.frame.height as u32))
} | identifier_body |
decoder.rs | use std::io;
use std::io::Read;
use std::default::Default;
use byteorder::{ReadBytesExt, LittleEndian};
use image;
use image::ImageResult;
use image::ImageDecoder;
use color;
use super::vp8::Frame;
use super::vp8::VP8Decoder;
/// A Representation of a Webp Image format decoder.
pub struct WebpDecoder<R> {
r: ... |
Ok(())
}
}
impl<R: Read> ImageDecoder for WebpDecoder<R> {
fn dimensions(&mut self) -> ImageResult<(u32, u32)> {
try!(self.read_metadata());
Ok((self.frame.width as u32, self.frame.height as u32))
}
fn colortype(&mut self) -> ImageResult<color::ColorType> {
Ok(color:... | {
try!(self.read_riff_header());
try!(self.read_vp8_header());
try!(self.read_frame());
self.have_frame = true;
} | conditional_block |
utils.js | context, app) {
let ctx = {
isServer: !!context.isServer,
isClient: !!context.isClient,
isStatic: process.static,
isDev: true,
isHMR: context.isHMR || false,
app: app,
route: (context.to ? context.to : context.route),
payload: context.payload,
error: context.error,
base: '... | } | random_line_split | |
utils.js | Context) {
asyncData = this.$ssrContext.asyncData[Component.cid]
}
return { ...data, ...asyncData }
}
if (Component._Ctor && Component._Ctor.options) {
Component._Ctor.options.data = Component.options.data
}
}
export function sanitizeComponent (Component) {
if (!Component.options) {
Compo... |
if (ctx.isClient && window.__NUXT__) {
ctx.nuxtState = window.__NUXT__
}
return ctx
}
export function middlewareSeries (promises, context) {
if (!promises.length || context._redirected) {
return Promise.resolve()
}
return promisify(promises[0], context)
.then(() => {
return middlewareSeries(... | {
ctx.beforeNuxtRender = (fn) => context.beforeRenderFns.push(fn)
} | conditional_block |
utils.js | Context) {
asyncData = this.$ssrContext.asyncData[Component.cid]
}
return { ...data, ...asyncData }
}
if (Component._Ctor && Component._Ctor.options) {
Component._Ctor.options.data = Component.options.data
}
}
export function sanitizeComponent (Component) {
if (!Component.options) {
Compo... | (str) {
return encodeURI(str).replace(/[\/?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
/**
* Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
*
* @param {string}
* @return {string}
*/
function encodeAsterisk (str) {
return encodeURI(str).rep... | encodeURIComponentPretty | identifier_name |
utils.js | Context) {
asyncData = this.$ssrContext.asyncData[Component.cid]
}
return { ...data, ...asyncData }
}
if (Component._Ctor && Component._Ctor.options) {
Component._Ctor.options.data = Component.options.data
}
}
export function sanitizeComponent (Component) {
if (!Component.options) {
Compo... |
export function getMatchedComponentsInstances (route) {
return [].concat.apply([], route.matched.map(function (m) {
return Object.keys(m.instances).map(function (key) {
return m.instances[key]
})
}))
}
export function flatMapComponents (route, fn) {
return Array.prototype.concat.apply([], route.m... | {
return [].concat.apply([], route.matched.map(function (m) {
return Object.keys(m.components).map(function (key) {
return m.components[key]
})
}))
} | identifier_body |
subvertpy.py | vn_backend = (__version__ >= (0, 9, 1))
except ImportError:
# This try-except block is here for the sole purpose of avoiding
# exceptions with nose if subvertpy isn't installed when someone runs
# the testsuite.
has_svn_backend = False
from django.utils import six
from django.utils.datastructures impor... | (self):
"""Returns metadata about the repository:
* UUID
* Root URL
* URL
"""
try:
base = os.path.basename(self.repopath)
info = self.client.info(self.repopath, 'HEAD')[base]
except SubversionException as e:
raise SVNTool.norma... | repository_info | identifier_name |
subvertpy.py | vn_backend = (__version__ >= (0, 9, 1))
except ImportError:
# This try-except block is here for the sole purpose of avoiding
# exceptions with nose if subvertpy isn't installed when someone runs
# the testsuite.
has_svn_backend = False
from django.utils import six
from django.utils.datastructures impor... |
if username:
self.auth.set_parameter(B('svn:auth:username'), B(username))
if password:
self.auth.set_parameter(B('svn:auth:password'), B(password))
cfg = get_config(self.config_dir)
self.client = SVNClient(cfg, auth=self.auth)
def set_ssl_server_trust_pro... | super(Client, self).__init__(config_dir, repopath, username, password)
self.repopath = B(self.repopath)
self.config_dir = B(config_dir)
self._ssl_trust_prompt_cb = None
auth_providers = [
ra.get_simple_provider(),
ra.get_username_provider(),
]
i... | identifier_body |
subvertpy.py | _svn_backend = (__version__ >= (0, 9, 1))
except ImportError:
# This try-except block is here for the sole purpose of avoiding
# exceptions with nose if subvertpy isn't installed when someone runs
# the testsuite.
has_svn_backend = False
from django.utils import six
from django.utils.datastructures imp... | def __init__(self, config_dir, repopath, username=None, password=None):
super(Client, self).__init__(config_dir, repopath, username, password)
self.repopath = B(self.repopath)
self.config_dir = B(config_dir)
self._ssl_trust_prompt_cb = None
auth_providers = [
ra... | random_line_split | |
subvertpy.py | _svn_backend = (__version__ >= (0, 9, 1))
except ImportError:
# This try-except block is here for the sole purpose of avoiding
# exceptions with nose if subvertpy isn't installed when someone runs
# the testsuite.
has_svn_backend = False
from django.utils import six
from django.utils.datastructures imp... |
else:
depth = 0 # This will trigger recurse=False for SVN < 1.5.
# subvertpy asserts that svn_uri not ends with slash
norm_path = B(self.normalize_path(path)).rstrip('/')
dirents = self.client.list(norm_path, None, depth)
for name, dirent in six.iteritems(dirents... | depth = 2 # Immediate files in this path. Only in 1.5+. | conditional_block |
files.js | /*
* Copyright IBM Corp. 2017
*
* 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 agreed to in wr... |
fileExists: function (filePath) {
try {
return fs.statSync(filePath).isFile();
} catch (err) {
return false;
}
},
size: function (filePath) {
try {
var units = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
var size = fs.statSync(file... | var fs = require('fs');
var path = require('path');
module.exports = { | random_line_split |
index.ts | import * as http from "http";
export interface Data {
_id: string,
_rev?: string,
[x: string] : any
}
export interface QueryParams {
startkey?: string,
endkey?: string,
start_key?: string,
end_key?: string, | conflicts?: boolean,
descending?: boolean,
endkey_docid?: string,
end_key_doc_id?: string,
startkey_docid?: string,
start_key_doc_id?: string,
include_docs?: boolean,
inclusive_end?: boolean,
key?: string,
keys?: string[],
skip?: number,
stale?: string,
update_req?: boolean
}
export class Co... | limit?: number | random_line_split |
index.ts | import * as http from "http";
export interface Data {
_id: string,
_rev?: string,
[x: string] : any
}
export interface QueryParams {
startkey?: string,
endkey?: string,
start_key?: string,
end_key?: string,
limit?: number
conflicts?: boolean,
descending?: boolean,
endkey_docid?: string,
end_k... |
private buildRequestParams(data: QueryParams) {
let keys = Object.keys(data);
let hasQuote = ["startkey", "start_key", "endkey", "end_key"];
let args: string[] = [];
keys.forEach(key => {
if(key === "keys"){
let rows = data["keys"] || [];
let keysValue = '[' + rows.map(x => '"... | {
let params = {
url: [this.host, data._id].join("/"),
method: "DELETE",
headers: this.headers,
content: JSON.stringify(data)
}
return new Promise((resolve, reject) => {
http.request(params).then(response => {
if(response.statusCode === 200){
resolve(respon... | identifier_body |
index.ts | import * as http from "http";
export interface Data {
_id: string,
_rev?: string,
[x: string] : any
}
export interface QueryParams {
startkey?: string,
endkey?: string,
start_key?: string,
end_key?: string,
limit?: number
conflicts?: boolean,
descending?: boolean,
endkey_docid?: string,
end_k... | (data: QueryParams) {
let keys = Object.keys(data);
let hasQuote = ["startkey", "start_key", "endkey", "end_key"];
let args: string[] = [];
keys.forEach(key => {
if(key === "keys"){
let rows = data["keys"] || [];
let keysValue = '[' + rows.map(x => '"' + x + '"') + ']';
arg... | buildRequestParams | identifier_name |
index.ts | import * as http from "http";
export interface Data {
_id: string,
_rev?: string,
[x: string] : any
}
export interface QueryParams {
startkey?: string,
endkey?: string,
start_key?: string,
end_key?: string,
limit?: number
conflicts?: boolean,
descending?: boolean,
endkey_docid?: string,
end_k... | else{
reject(new Error(response.content));
}
}, err => reject(new Error(err)))
})
}
public put(data: Data) {
let params = {
url: [this.host, data._id].join("/"),
method: "PUT",
headers: this.headers,
content: JSON.stringify(data)
}
return new Pro... | {
resolve(response.content.toJSON());
} | conditional_block |
Gruntfile.js | module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
var debug = grunt.option('env') !== 'production';
grunt.config('env.' + grunt.option('env'), true);
grunt.config('clean', ['./client/build']);
grunt.config('browserify', {
options: {
debug: debug,
watch: true
},
... |
grunt.config('less', {
styles: {
src: './client/src/styles.less',
dest: './client/build/assets/styles.css',
options: {
dumpLineNumbers: debug ? 'all' : false,
sourceMap: debug,
outputSourceFiles: debug,
cleancss: !debug
}
}
});
grunt.config('concur... | random_line_split | |
test_searchdialogbase.py | '''Unittests for idlelib/SearchDialogBase.py
Coverage: 99%. The only thing not covered is inconsequential --
testing skipping of suite when self.needwrapbutton is false.
'''
import unittest
from test.support import requires
from tkinter import Tk, Toplevel, Frame, Label, BooleanVar, StringVar
from idlelib import Sear... | equal(int(egi['rowspan']), 1)
equal(int(egi['columnspan']), 1)
equal(self.dialog.row, 1)
def test_create_entries(self):
self.dialog.row = 0
self.engine.setpat('hello')
self.dialog.create_entries()
self.assertIn(self.dialog.ent.get(), 'hello')
def test_ma... | equal(int(egi['column']), 1) | random_line_split |
test_searchdialogbase.py | '''Unittests for idlelib/SearchDialogBase.py
Coverage: 99%. The only thing not covered is inconsequential --
testing skipping of suite when self.needwrapbutton is false.
'''
import unittest
from test.support import requires
from tkinter import Tk, Toplevel, Frame, Label, BooleanVar, StringVar
from idlelib import Sear... | (unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
@classmethod
def tearDownClass(cls):
cls.root.destroy()
del cls.root
def setUp(self):
self.engine = se.SearchEngine(self.root) # None also seems to work
self.dia... | SearchDialogBaseTest | identifier_name |
test_searchdialogbase.py | '''Unittests for idlelib/SearchDialogBase.py
Coverage: 99%. The only thing not covered is inconsequential --
testing skipping of suite when self.needwrapbutton is false.
'''
import unittest
from test.support import requires
from tkinter import Tk, Toplevel, Frame, Label, BooleanVar, StringVar
from idlelib import Sear... |
def tearDown(self):
self.dialog.close()
def test_open_and_close(self):
# open calls create_widgets, which needs default_command
self.dialog.default_command = None
# Since text parameter of .open is not used in base class,
# pass dummy 'text' instead of tk.Text().
... | self.engine = se.SearchEngine(self.root) # None also seems to work
self.dialog = sdb.SearchDialogBase(root=self.root, engine=self.engine) | identifier_body |
test_searchdialogbase.py | '''Unittests for idlelib/SearchDialogBase.py
Coverage: 99%. The only thing not covered is inconsequential --
testing skipping of suite when self.needwrapbutton is false.
'''
import unittest
from test.support import requires
from tkinter import Tk, Toplevel, Frame, Label, BooleanVar, StringVar
from idlelib import Sear... |
self.assertIn('close', closebuttoncommand)
if __name__ == '__main__':
unittest.main(verbosity=2, exit=2)
| closebuttoncommand = child['command'] | conditional_block |
DragCoordTest.ts | import { UnitTest } from '@ephox/bedrock-client';
import { Arr } from '@ephox/katamari';
import { SugarPosition } from '@ephox/sugar';
import { assert } from 'chai';
import * as fc from 'fast-check';
import * as DragCoord from 'ephox/alloy/api/data/DragCoord';
interface TestConversion {
mode: string;
nu: (x: numb... | }); | random_line_split | |
__init__.py | # -*- coding: utf-8 -*-
"""
UserBot module
Copyright 2015, Ismael R. Lugo G.
"""
import translate
reload(translate)
from sysb import commands
from translate import lang
from translate import _
commands.addHandler('translate', '(tr|translate)2 (?P<in>[^ ]+) (?P<out>[^ ]+) '
'(?P<text>.*)', {'sintax': 'tr2 <input... | commands.addHandler('translate', '(tr|translate) (?P<in>[^ ]+) (?P<out>[^ ]+) ('
'?P<text>.*)', {'sintax': 'tr <input> <output> <text>',
'example': 'tr en es Hello!',
'alias': ('traslate',),
'desc': _('Traduce un texto de un idioma a otro', lang)},
anyuser=True)(translate.translate2_2) | random_line_split | |
suggestions.py | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.core.db import db
from indico.util.string import format_repr
class SuggestedCategory(db.Mode... |
db.session.flush()
| new_suggestion = target_suggestions.get(suggestion.category) or cls(user=target,
category=suggestion.category,
score=0)
new_suggestion.score = max(n... | conditional_block |
suggestions.py | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.core.db import db
from indico.util.string import format_repr
class | (db.Model):
__tablename__ = 'suggested_categories'
__table_args__ = {'schema': 'users'}
user_id = db.Column(
db.Integer,
db.ForeignKey('users.users.id'),
primary_key=True,
index=True,
autoincrement=False
)
category_id = db.Column(
db.Integer,
... | SuggestedCategory | identifier_name |
suggestions.py | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.core.db import db
from indico.util.string import format_repr
class SuggestedCategory(db.Mode... |
@classmethod
def merge_users(cls, target, source):
"""Merge the suggestions for two users.
:param target: The target user of the merge.
:param source: The user that is being merged into `target`.
"""
target_suggestions = {x.category: x for x in target.suggested_categor... | return format_repr(self, 'user_id', 'category_id', 'score', is_ignored=False) | identifier_body |
suggestions.py | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.core.db import db
from indico.util.string import format_repr
class SuggestedCategory(db.Mode... | nullable=False,
default=False
)
score = db.Column(
db.Float,
nullable=False,
default=0
)
category = db.relationship(
'Category',
lazy=False,
backref=db.backref(
'suggestions',
lazy=True,
cascade='all, de... | is_ignored = db.Column(
db.Boolean, | random_line_split |
tictactoe.py | # Tic Tac Toe
# Tic Tac Toe
import random
def drawBoard(board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
p... |
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie!')
break
else:
turn = 'player'
if not playAgain():
break | drawBoard(theBoard)
print('The computer has beaten you! You lose.')
gameIsPlaying = False | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.