file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
interval.rs | //! Support for creating futures that represent intervals.
//!
//! This module contains the `Interval` type which is a stream that will
//! resolve at a fixed intervals in future
use std::io;
use std::time::{Duration, Instant};
use futures::{Poll, Async};
use futures::stream::{Stream};
use reactor::{Remote, Handle};... | else {
self.token.update_timeout(&self.handle);
Ok(Async::NotReady)
}
}
}
impl Drop for Interval {
fn drop(&mut self) {
self.token.cancel_timeout(&self.handle);
}
}
/// Converts Duration object to raw nanoseconds if possible
///
/// This is useful to divide interva... | {
self.next = next_interval(self.next, now, self.interval);
self.token.reset_timeout(self.next, &self.handle);
Ok(Async::Ready(Some(())))
} | conditional_block |
interval.rs | //! Support for creating futures that represent intervals.
//!
//! This module contains the `Interval` type which is a stream that will
//! resolve at a fixed intervals in future
use std::io;
use std::time::{Duration, Instant};
use futures::{Poll, Async};
use futures::stream::{Stream};
use reactor::{Remote, Handle};... | /// otherwise indicated to fire at.
pub struct Interval {
token: TimeoutToken,
next: Instant,
interval: Duration,
handle: Remote,
}
impl Interval {
/// Creates a new interval which will fire at `dur` time into the future,
/// and will repeat every `dur` interval after
///
/// This funct... | /// they will likely fire some granularity after the exact instant that they're | random_line_split |
location.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::LocationBinding;
use dom::bindings::js::{JSRef, Temporary};
use dom::binding... | else {
"?".to_string().append(query.as_slice())
}
}
}
impl Reflectable for Location {
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
}
| {
query
} | conditional_block |
location.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::LocationBinding;
use dom::bindings::js::{JSRef, Temporary};
use dom::binding... | (&self) -> DOMString {
let query = query_to_str(&self.page.get_url().query);
if query.as_slice() == "" {
query
} else {
"?".to_string().append(query.as_slice())
}
}
}
impl Reflectable for Location {
fn reflector<'a>(&'a self) -> &'a Reflector {
&s... | Search | identifier_name |
location.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::LocationBinding;
use dom::bindings::js::{JSRef, Temporary};
use dom::binding... |
pub fn new(window: &JSRef<Window>, page: Rc<Page>) -> Temporary<Location> {
reflect_dom_object(box Location::new_inherited(page),
window,
LocationBinding::Wrap)
}
}
pub trait LocationMethods {
fn Href(&self) -> DOMString;
fn Search(&self) -... | Location {
reflector_: Reflector::new(),
page: page
}
} | random_line_split |
location.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::LocationBinding;
use dom::bindings::js::{JSRef, Temporary};
use dom::binding... |
fn Search(&self) -> DOMString {
let query = query_to_str(&self.page.get_url().query);
if query.as_slice() == "" {
query
} else {
"?".to_string().append(query.as_slice())
}
}
}
impl Reflectable for Location {
fn reflector<'a>(&'a self) -> &'a Reflect... | {
self.page.get_url().to_str()
} | identifier_body |
main.rs | extern crate chrono;
#[macro_use]
extern crate derive_builder;
extern crate fern;
extern crate inflector;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate rand;
extern crate rayon;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate anyhow;
extern crate clap;
exter... | {
fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{}[{}][{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
record.target(),
record.level(),
message
))
... | identifier_body | |
main.rs | extern crate chrono;
#[macro_use]
extern crate derive_builder;
extern crate fern;
extern crate inflector;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate rand;
extern crate rayon;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate anyhow;
extern crate clap;
exter... | }
/// This doc string acts as a help message when the user runs '--help'
/// as do all doc strings on fields
#[derive(Clap)]
#[clap(version = "1.0", author = "Viktor H. <viktor.holmgren@gmail.com>")]
#[clap(setting = AppSettings::ColoredHelp)]
struct Opts {
/// A level of verbosity, and can be used multiple times
... | simulator.new_game();
}
}
// TODO: Implement the rest of the program. | random_line_split |
main.rs | extern crate chrono;
#[macro_use]
extern crate derive_builder;
extern crate fern;
extern crate inflector;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate rand;
extern crate rayon;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate anyhow;
extern crate clap;
exter... | {
#[clap(version = "1.3", author = "Viktor H. <viktor.holmgren@gmail.com>")]
NewGame(NewGame),
//TODO: Add additional subcommands; serve (for server) etc.
}
/// Subcommand for generating a new world.
#[derive(Clap)]
struct NewGame {
#[clap(short, long, default_value = "genconfig.toml")]
config_pat... | SubCommand | identifier_name |
main.rs | extern crate serenity;
use serenity::prelude::*;
use serenity::model::*;
use std::env;
// Serenity implements transparent sharding in a way that you do not need to
// manually handle separate processes or connections manually.
//
// Transparent sharding is useful for a shared cache. Instead of having caches
// with d... | (&self, ctx: Context, msg: Message) {
if msg.content == "!ping" {
// The current shard needs to be unlocked so it can be read from, as
// multiple threads may otherwise attempt to read from or mutate it
// concurrently.
{
let shard = ctx.shard.lock(... | on_message | identifier_name |
main.rs | extern crate serenity;
use serenity::prelude::*;
use serenity::model::*;
use std::env;
// Serenity implements transparent sharding in a way that you do not need to
// manually handle separate processes or connections manually.
//
// Transparent sharding is useful for a shared cache. Instead of having caches
// with d... |
}
fn main() {
// Configure the client with your Discord bot token in the environment.
let token = env::var("DISCORD_TOKEN")
.expect("Expected a token in the environment");
let mut client = Client::new(&token, Handler);
// The total number of shards to use. The "current shard number" of a
... | {
println!("{} is connected!", ready.user.name);
} | identifier_body |
main.rs | extern crate serenity;
use serenity::prelude::*;
use serenity::model::*;
use std::env;
// Serenity implements transparent sharding in a way that you do not need to
// manually handle separate processes or connections manually.
//
// Transparent sharding is useful for a shared cache. Instead of having caches
// with d... |
}
| {
println!("Client error: {:?}", why);
} | conditional_block |
main.rs | extern crate serenity;
use serenity::prelude::*;
use serenity::model::*;
use std::env;
// Serenity implements transparent sharding in a way that you do not need to
// manually handle separate processes or connections manually.
//
// Transparent sharding is useful for a shared cache. Instead of having caches
// with d... | if msg.content == "!ping" {
// The current shard needs to be unlocked so it can be read from, as
// multiple threads may otherwise attempt to read from or mutate it
// concurrently.
{
let shard = ctx.shard.lock();
let shard_info = sh... | fn on_message(&self, ctx: Context, msg: Message) { | random_line_split |
std-smallintmap.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
~[~"", ~"100000", ~"100"]
} else if args.len() <= 1u {
~[~"", ~"10000", ~"50"]
} else {
args
};
let max = from_str::<uint>(args[1]).unwrap();
let rep = from_str::<uint>(args[2]).unwrap();
... | main | identifier_name |
std-smallintmap.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
~[~"", ~"100000", ~"100"]
} else if args.len() <= 1u {
~[~"", ~"10000", ~"50"]
} else {
args
};
let max = from_str::<uint>(args[1]).unwrap();
let rep = from_str::<uint>(args[2]).un... | {
for i in range(min, max) {
assert_eq!(*map.get(&i), i + 22u);
}
} | identifier_body |
std-smallintmap.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ;
let max = from_str::<uint>(args[1]).unwrap();
let rep = from_str::<uint>(args[2]).unwrap();
let mut checkf = 0.0;
let mut appendf = 0.0;
for _ in range(0u, rep) {
let mut map = SmallIntMap::new();
let start = extra::time::precise_time_s();
append_sequential(0u, max, &mut ... | {
args
} | conditional_block |
std-smallintmap.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | append_sequential(0u, max, &mut map);
let mid = extra::time::precise_time_s();
check_sequential(0u, max, &map);
let end = extra::time::precise_time_s();
checkf += (end - mid) as f64;
appendf += (mid - start) as f64;
}
let maxf = max as f64;
println!("insert... | let mut appendf = 0.0;
for _ in range(0u, rep) {
let mut map = SmallIntMap::new();
let start = extra::time::precise_time_s(); | random_line_split |
SerialChart.d.ts | /**
* Serial chart module.
*/
/**
* ============================================================================
* IMPORTS
* ============================================================================
* @hidden
*/
import { Chart, IChartProperties, IChartDataFields, IChartAdapters, IChartEvents, ChartDa... | /**
* ============================================================================
* DATA ITEM
* ============================================================================
* @hidden
*/
/**
* Defines a [[DataItem]] for [[SerialChart]].
*
* @see {@link DataItem}
*/
export declare class SerialChartDa... | import { Container } from "../../core/Container";
import { Series } from "../series/Series";
import { ColorSet } from "../../core/utils/ColorSet";
import { PatternSet } from "../../core/utils/PatternSet";
| random_line_split |
SerialChart.d.ts | /**
* Serial chart module.
*/
/**
* ============================================================================
* IMPORTS
* ============================================================================
* @hidden
*/
import { Chart, IChartProperties, IChartDataFields, IChartAdapters, IChartEvents, ChartDa... | extends ChartDataItem {
/**
* Defines a type of [[Component]] this data item is used for.
*/
_component: SerialChart;
/**
* Constructor
*/
constructor();
}
/**
* ============================================================================
* REQUISITES
* =============... | SerialChartDataItem | identifier_name |
wallet.rs | use indy::IndyError;
use indy::wallet;
use indy::future::Future;
pub const DEFAULT_WALLET_CREDENTIALS: &'static str = r#"{"key":"8dvfYSt5d1taSd6yJdpjq4emkwsPDDLYxkNFysFD2cZY", "key_derivation_method":"RAW"}"#;
pub fn create_wallet(config: &str) -> Result<(), IndyError> {
wallet::create_wallet(config, DEFAULT_WALL... | {
wallet::close_wallet(wallet_handle).wait()
} | identifier_body | |
wallet.rs | use indy::IndyError;
use indy::wallet; |
pub const DEFAULT_WALLET_CREDENTIALS: &'static str = r#"{"key":"8dvfYSt5d1taSd6yJdpjq4emkwsPDDLYxkNFysFD2cZY", "key_derivation_method":"RAW"}"#;
pub fn create_wallet(config: &str) -> Result<(), IndyError> {
wallet::create_wallet(config, DEFAULT_WALLET_CREDENTIALS).wait()
}
pub fn open_wallet(config: &str) -> Res... | use indy::future::Future; | random_line_split |
wallet.rs | use indy::IndyError;
use indy::wallet;
use indy::future::Future;
pub const DEFAULT_WALLET_CREDENTIALS: &'static str = r#"{"key":"8dvfYSt5d1taSd6yJdpjq4emkwsPDDLYxkNFysFD2cZY", "key_derivation_method":"RAW"}"#;
pub fn create_wallet(config: &str) -> Result<(), IndyError> {
wallet::create_wallet(config, DEFAULT_WALL... | () -> Result<i32, IndyError> {
let wallet_name = format!("default-wallet-name-{}", super::sequence::get_next_id());
let config = format!(r#"{{"id":"{}"}}"#, wallet_name);
create_wallet(&config)?;
open_wallet(&config)
}
pub fn close_wallet(wallet_handle: i32) -> Result<(), IndyError> {
wallet::clos... | create_and_open_wallet | identifier_name |
solver.js | // Copyright (c) 2015 by rapidhere, RANTTU. INC. All Rights Reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later vers... | var dy = [0, 1, -1, 0, 0];
// a util: create a 2-d array, and fill with zero
rapidGameSolver.new2dArray = function(h, w) {
var ret = new Array(h);
var i;
for(i = 0;i < h;i ++)
ret[i] = rapidGameSolver.new1dArray(w);
return ret;
};
// create a 1-d array
// and fill with zero
rapidGameSolver.n... | var dx = [0, 0, 0, 1, -1]; | random_line_split |
solver.js | // Copyright (c) 2015 by rapidhere, RANTTU. INC. All Rights Reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later vers... | $div.attr('data-clicked', clicked ^ 1);
};
// game solve entry
rapidGameSolver.solveGame = function(game) {
// solve the game with Gaussian Elimination
// get board and width, height
var bd = game.gb.board;
var h = bd.length;
var w = bd[0].length;
if(game.solved)
return ;
// m... | $div.html('');
}
| conditional_block |
host.ts | import {
Injectable,
ApplicationRef,
ComponentFactoryResolver,
Injector,
Component,
EmbeddedViewRef,
ComponentDecorator
} from '@angular/core';
import { ComponentType } from './models';
import { ComponentInstance } from './component-instance';
@Injectable()
export class ComponentHost<C> {
private compF... | (component: ComponentType<C>, props = {}) {
this.component = component;
this.componentProps = props;
}
attach(): ComponentHost<C> {
this.compFac = this.compFacResolver.resolveComponentFactory(this.component);
this.compRef = this.compFac.create(this.injector);
this.compIns = this.compRef.instanc... | configure | identifier_name |
host.ts | import {
Injectable,
ApplicationRef,
ComponentFactoryResolver,
Injector,
Component,
EmbeddedViewRef,
ComponentDecorator
} from '@angular/core';
import { ComponentType } from './models';
import { ComponentInstance } from './component-instance';
@Injectable()
export class ComponentHost<C> {
private compF... |
detach() {
this.appRef.detachView(this.compRef.hostView);
this.compRef.destroy();
}
componentView(): HTMLElement {
return (this.compRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
}
}
| {
return this.compIns;
} | identifier_body |
host.ts | import {
Injectable,
ApplicationRef,
ComponentFactoryResolver,
Injector,
Component,
EmbeddedViewRef,
ComponentDecorator
} from '@angular/core'; | @Injectable()
export class ComponentHost<C> {
private compFac;
private compRef;
private component;
private componentProps;
compIns: ComponentInstance<C>;
constructor(
private appRef: ApplicationRef,
private compFacResolver: ComponentFactoryResolver,
private injector: Injector
) {}
configure... | import { ComponentType } from './models';
import { ComponentInstance } from './component-instance';
| random_line_split |
architecture.rs | /*
* Panopticon - A libre disassembler
* Copyright (C) 2015, 2017 Panopticon authors
*
* 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 opti... | (&self) -> usize {
match self {
&Mode::Real => 32,
&Mode::Protected => 16,
&Mode::Long => 16,
}
}
pub fn bits(&self) -> usize {
match self {
&Mode::Real => 16,
&Mode::Protected => 32,
&Mode::Long => 64,
}
... | alt_bits | identifier_name |
architecture.rs | /*
* Panopticon - A libre disassembler
* Copyright (C) 2015, 2017 Panopticon authors
*
* 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 opti... |
let ret = crate::disassembler::read(*cfg, &buf, p).and_then(
|(len, mne, mut jmp)| {
Ok(
Match::<Amd64> {
tokens: buf[0..len as usize].to_vec(),
mnemonics: vec![mne],
jumps: jmp.drain(..).map... | }
debug!("disass @ {:#x}: {:?}", p, buf); | random_line_split |
sonnet_predict_bed.py | #!/usr/bin/env python
# Copyright 2017 Calico LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
#################################################################
# setup model
seqnn_model = tf.saved_model.load(model_file).model
# query num model targets
seq_length = seqnn_model.predict_on_batch.input_signature[0].shape[1]
null_1hot = np.zeros((1,seq_length,4))
null_preds = seqnn_model.predict_o... | targets_df = pd.read_table(options.targets_file, index_col=0)
target_slice = targets_df.index | conditional_block |
sonnet_predict_bed.py | #!/usr/bin/env python
# Copyright 2017 Calico LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
################################################################################
# __main__
################################################################################
if __name__ == '__main__':
main()
| """ Write a signal track to a BigWig file over the region
specified by seqs_coords.
Args
signal: Sequences x Length signal array
seq_coords: (chr,start,end)
bw_file: BigWig filename
genome_file: Chromosome lengths file
seq_crop: Sequence length cropped from each side ... | identifier_body |
sonnet_predict_bed.py | #!/usr/bin/env python
# Copyright 2017 Calico LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
#################################################################
# predict scores, write output
# define sequence generator
def seqs_gen():
for seq_dna in model_seqs_dna:
yield dna_io.dna_1hot(seq_dna)
# initialize predictions stream
preds_stream = stream.PredStreamSonnet(seqnn_model, seqs_gen... | out_h5.create_dataset('chrom', data=site_seqs_chr)
out_h5.create_dataset('start', data=site_seqs_start)
out_h5.create_dataset('end', data=site_seqs_end)
| random_line_split |
sonnet_predict_bed.py | #!/usr/bin/env python
# Copyright 2017 Calico LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | ():
for seq_dna in model_seqs_dna:
yield dna_io.dna_1hot(seq_dna)
# initialize predictions stream
preds_stream = stream.PredStreamSonnet(seqnn_model, seqs_gen(),
rc=options.rc, shifts=options.shifts, species=options.species)
for si in range(num_seqs):
preds_seq = preds_stream[si]
# slice ... | seqs_gen | identifier_name |
process_test.py | #!/usr/bin/env python
import logging
import os
import signal
import sys
from tornado.httpclient import HTTPClient, HTTPError
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.netutil import bind_sockets
from tornado.process import fork_processes, task_id
from tornado.simple_httpc... | (RequestHandler):
def get(self):
if self.get_argument("exit", None):
# must use os._exit instead of sys.exit so unittest's
# exception handler doesn't catch it
os._exit(int(self.get_argument("exit")))
if self.get_arg... | ProcessHandler | identifier_name |
process_test.py | #!/usr/bin/env python
import logging
import os
import signal
import sys
from tornado.httpclient import HTTPClient, HTTPError
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.netutil import bind_sockets
from tornado.process import fork_processes, task_id
from tornado.simple_httpc... |
return Application([("/", ProcessHandler)])
def tearDown(self):
if task_id() is not None:
# We're in a child process, and probably got to this point
# via an uncaught exception. If we return now, both
# processes will continue with the rest of the test suite.
... | def get(self):
if self.get_argument("exit", None):
# must use os._exit instead of sys.exit so unittest's
# exception handler doesn't catch it
os._exit(int(self.get_argument("exit")))
if self.get_argument("signal", None):
... | identifier_body |
process_test.py | #!/usr/bin/env python
import logging
import os
import signal
import sys
from tornado.httpclient import HTTPClient, HTTPError
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.netutil import bind_sockets
from tornado.process import fork_processes, task_id
from tornado.simple_httpc... |
# Always use SimpleAsyncHTTPClient here; the curl
# version appears to get confused sometimes if the
# connection gets closed before it's had a chance to
# switch from writing mode to reading mode.
client = HTTPClient(SimpleAsyncHTTPClient... | sock.close() | conditional_block |
process_test.py | #!/usr/bin/env python
import logging
import os
import signal
import sys
from tornado.httpclient import HTTPClient, HTTPError
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.netutil import bind_sockets
from tornado.process import fork_processes, task_id
from tornado.simple_httpc... | os._exit(1)
super(ProcessTest, self).tearDown()
def test_multi_process(self):
self.assertFalse(IOLoop.initialized())
port = get_unused_port()
def get_url(path):
return "http://127.0.0.1:%d%s" % (port, path)
sockets = bind_sockets(port, "127.0.0.1")
... | # Exit now so the parent process will restart the child
# (since we don't have a clean way to signal failure to
# the parent that won't restart)
logging.error("aborting child process from tearDown")
logging.shutdown() | random_line_split |
style.ts | // Copyright (c) Jonathan Frederic, see the LICENSE file for more info.
import utils = require('../utils/utils');
import generics = require('../utils/generics');
import styles = require('./init');
/**
* Style
*/
export class Style extends utils.PosterClass {
public comment: string;
public string: string;
... |
// Read each attribute of the style.
for (var key in style) {
if (style.hasOwnProperty(key)) {
this[key] = style[key];
}
}
return true;
} catch (e) {
console.error('Error loading style'... | {
style = styles.styles[style].style;
} | conditional_block |
style.ts | // Copyright (c) Jonathan Frederic, see the LICENSE file for more info.
import utils = require('../utils/utils');
import generics = require('../utils/generics');
import styles = require('./init');
/**
* Style
*/
export class Style extends utils.PosterClass {
public comment: string;
public string: string;
... | (name: string, default_value?: any): any {
name = name.replace(/-/g, '_');
return this[name] !== undefined ? this[name] : default_value;
}
/**
* Load a rendering style
* @param style - name of the built-in style
* or style dictionary itself.
* @return success
... | get | identifier_name |
style.ts | // Copyright (c) Jonathan Frederic, see the LICENSE file for more info.
import utils = require('../utils/utils');
import generics = require('../utils/generics');
import styles = require('./init');
/**
* Style
*/
export class Style extends utils.PosterClass {
public comment: string;
public string: string;
... | 'gutter_text',
'gutter_shadow'
]);
// Load the default style.
this.load('peacock');
}
/**
* Get the value of a property of this instance.
*/
get(name: string, default_value?: any): any {
name = name.replace(/-/g, '_');
return this[n... |
'text',
'background',
'gutter', | random_line_split |
style.ts | // Copyright (c) Jonathan Frederic, see the LICENSE file for more info.
import utils = require('../utils/utils');
import generics = require('../utils/generics');
import styles = require('./init');
/**
* Style
*/
export class Style extends utils.PosterClass {
public comment: string;
public string: string;
... |
/**
* Get the value of a property of this instance.
*/
get(name: string, default_value?: any): any {
name = name.replace(/-/g, '_');
return this[name] !== undefined ? this[name] : default_value;
}
/**
* Load a rendering style
* @param style - name of the built-in... | {
super([
'comment',
'string',
'class_name',
'keyword',
'boolean',
'function',
'operator',
'number',
'ignore',
'punctuation',
'cursor',
'cursor_width',
'cu... | identifier_body |
uievent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::UIEventBin... | can_bubble: bool,
cancelable: bool,
view: Option<JSRef<Window>>,
detail: i32) -> Temporary<UIEvent> {
let ev = UIEvent::new_uninitialized(window).root();
ev.deref().InitUIEvent(type_, can_bubble, cancelable, view, detail);
Temporary::fr... |
pub fn new(window: JSRef<Window>,
type_: DOMString, | random_line_split |
uievent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::UIEventBin... | {
pub event: Event,
view: Cell<Option<JS<Window>>>,
detail: Traceable<Cell<i32>>
}
impl UIEventDerived for Event {
fn is_uievent(&self) -> bool {
self.type_id == UIEventTypeId
}
}
impl UIEvent {
pub fn new_inherited(type_id: EventTypeId) -> UIEvent {
UIEvent {
even... | UIEvent | identifier_name |
uievent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::UIEventBin... |
pub fn new_uninitialized(window: JSRef<Window>) -> Temporary<UIEvent> {
reflect_dom_object(box UIEvent::new_inherited(UIEventTypeId),
&Window(window),
UIEventBinding::Wrap)
}
pub fn new(window: JSRef<Window>,
type_: DOMString,
... | {
UIEvent {
event: Event::new_inherited(type_id),
view: Cell::new(None),
detail: Traceable::new(Cell::new(0)),
}
} | identifier_body |
activityAdd.component.ts | import { Component } from '@angular/core';
import { User } from '../user/user.entity'
import { Answer } from '../topics/answer.entity'
import { Router, ActivatedRoute } from '@angular/router';
import { LoginService } from "../login/login.service";
import { Activity } from './activity.entity'
import { ActivityService } ... | () {
this.formData.content = this.contentN;
this.formData.nameactivity = this.nameActivityN;
this.formData.activityType = this.activityTypeN;
this.activityService.addActivity(this.formData).subscribe(
response =>
this.router.navigate(['/activity'])
);
... | addNewActivity | identifier_name |
activityAdd.component.ts | import { Component } from '@angular/core';
import { User } from '../user/user.entity'
import { Answer } from '../topics/answer.entity'
import { Router, ActivatedRoute } from '@angular/router';
import { LoginService } from "../login/login.service";
import { Activity } from './activity.entity'
import { ActivityService } ... | this.formData.content = this.contentN;
this.formData.nameactivity = this.nameActivityN;
this.formData.activityType = this.activityTypeN;
this.activityService.addActivity(this.formData).subscribe(
response =>
this.router.navigate(['/activity'])
);
... | addNewActivity() { | random_line_split |
activityAdd.component.ts | import { Component } from '@angular/core';
import { User } from '../user/user.entity'
import { Answer } from '../topics/answer.entity'
import { Router, ActivatedRoute } from '@angular/router';
import { LoginService } from "../login/login.service";
import { Activity } from './activity.entity'
import { ActivityService } ... |
}
| {
this.formData.content = this.contentN;
this.formData.nameactivity = this.nameActivityN;
this.formData.activityType = this.activityTypeN;
this.activityService.addActivity(this.formData).subscribe(
response =>
this.router.navigate(['/activity'])
);
... | identifier_body |
customize_form.py | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# MIT License. See license.txt
from __future__ import unicode_literals
"""
Customize Form is a Single DocType used to mask the Property Setter
Thus providing a better UI from user perspective
"""
import webnotes
from webnotes.utils import cstr
class DocType:
... |
def set(self, args):
"""
Set a list of attributes of a doc to a value
or to attribute values of a doc passed
args can contain:
* list --> list of attributes to set
* doc_to_set --> defaults to self.doc
* value --> to set all attributes to one value eg. None
* doc --> copy attributes fr... | """
Clear fields in the doc
"""
# Clear table before adding new doctype's fields
self.doclist = self.doc.clear_table(self.doclist, 'fields')
self.set({ 'list': self.doctype_properties, 'value': None }) | identifier_body |
customize_form.py | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# MIT License. See license.txt
from __future__ import unicode_literals
"""
Customize Form is a Single DocType used to mask the Property Setter
Thus providing a better UI from user perspective
"""
import webnotes
from webnotes.utils import cstr
class DocType:
... | ( \
new_d.fields.get(prop) in [None, ''] \
and dt_d.fields.get(prop) in [None, ''] \
)):
delete = 1
break
value = new_d.fields.get(prop)
if prop in self.property_restrictions:
allow_change = False
for restrict_list in self.property_restrictions.get(prop):
if value i... | ( \
new_d.fields.get(prop) in [None, 0] \
and dt_d.fields.get(prop) in [None, 0] \
) or \ | random_line_split |
customize_form.py | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# MIT License. See license.txt
from __future__ import unicode_literals
"""
Customize Form is a Single DocType used to mask the Property Setter
Thus providing a better UI from user perspective
"""
import webnotes
from webnotes.utils import cstr
class DocType:
... |
break
elif ref_d.doctype == 'DocType' and new_d.doctype == 'Customize Form':
for prop in self.doctype_properties:
d = self.prepare_to_set(prop, new_d, ref_d, dt_dl)
if d: diff_list.append(d)
break
return diff_list
def get_defaults(self):
"""
Get fieldtype and default valu... | diff_list.append(d) | conditional_block |
customize_form.py | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# MIT License. See license.txt
from __future__ import unicode_literals
"""
Customize Form is a Single DocType used to mask the Property Setter
Thus providing a better UI from user perspective
"""
import webnotes
from webnotes.utils import cstr
class DocType:
... | (self):
"""
Clear fields in the doc
"""
# Clear table before adding new doctype's fields
self.doclist = self.doc.clear_table(self.doclist, 'fields')
self.set({ 'list': self.doctype_properties, 'value': None })
def set(self, args):
"""
Set a list of attributes of a doc to a value
or to attribu... | clear | identifier_name |
n.js | /*************************************************************
*
* MathJax/jax/output/HTML-CSS/entities/n.js
*
* Copyright (c) 2010-2014 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may ob... | 'notinvc': '\u22F6',
'notni': '\u220C',
'notniva': '\u220C',
'notnivb': '\u22FE',
'notnivc': '\u22FD',
'npar': '\u2226',
'nparallel': '\u2226',
'nparsl': '\u2AFD\u20E5',
'npart': '\u2202\u0338',
'npolint': '\u2A14',
'npr': '\u2280',
'nprcue': '\u22E0',
'npre': '\u2AAF... | random_line_split | |
common.py | """Utilities for multiprocess tests running."""
# pylint: disable=invalid-name,super-init-not-called
from __future__ import absolute_import
import os
import psutil
from rotest.common import core_log
PROCESS_TERMINATION_TIMEOUT = 10
class | (Exception):
"""Used to wrapping exceptions so they could be passed via queues.
Queue pickles every object it is requires to pass, and since Traceback
objects cannot be pickled and therfore cannot be transfered using queue,
there is a need to pass the traceback in another way.
This class is designe... | WrappedException | identifier_name |
common.py | """Utilities for multiprocess tests running."""
# pylint: disable=invalid-name,super-init-not-called
from __future__ import absolute_import
import os
import psutil
from rotest.common import core_log
PROCESS_TERMINATION_TIMEOUT = 10
class WrappedException(Exception):
"""Used to wrapping exceptions so they coul... | """Kill a process and all its subprocesses.
Note:
Kill the process and all its sub processes recursively.
If the given process is the current process - Kills the sub process
before the given process. Otherwise - Kills the given process before
its sub processes
Args:
pro... | identifier_body | |
common.py | """Utilities for multiprocess tests running."""
# pylint: disable=invalid-name,super-init-not-called
from __future__ import absolute_import
import os
import psutil
from rotest.common import core_log
PROCESS_TERMINATION_TIMEOUT = 10
class WrappedException(Exception):
"""Used to wrapping exceptions so they coul... |
if test_item.IS_COMPLEX:
sub_test = max([sub_test for sub_test in test_item
if sub_test.identifier <= item_id],
key=lambda test: test.identifier)
return get_item_by_id(sub_test, item_id)
def kill_process(process):
"""Kill a single process.
... | return test_item | conditional_block |
common.py | """Utilities for multiprocess tests running."""
# pylint: disable=invalid-name,super-init-not-called
from __future__ import absolute_import
import os
import psutil
from rotest.common import core_log
PROCESS_TERMINATION_TIMEOUT = 10
class WrappedException(Exception):
"""Used to wrapping exceptions so they coul... | Goes over the test item's sub tests recursively and returns
the one that matches the requested identifier.
The search algorithm assumes that the identifiers assignment was the
default one (use of default indexer), which identifies the tests in a DFS
recursion.
The algorithm continues the search ... |
def get_item_by_id(test_item, item_id):
"""Return the requested test item by its identifier.
| random_line_split |
mixin.js | this.selector = new(tree.Selector)(elements);
this.arguments = args;
this.index = index;
};
tree.mixin.Call.prototype = {
eval: function (env) {
var mixins, rules = [], match = false;
for (var i = 0; i < env.frames.length; i++) {
if ((mixins = env.frames[i].find(this.selecto... | (function (tree) {
tree.mixin = {};
tree.mixin.Call = function (elements, args, index) { | random_line_split | |
mixin.js | (function (tree) {
tree.mixin = {};
tree.mixin.Call = function (elements, args, index) {
this.selector = new(tree.Selector)(elements);
this.arguments = args;
this.index = index;
};
tree.mixin.Call.prototype = {
eval: function (env) {
var mixins, rules = [], match = false;
for (var i = ... |
}
return new(tree.Ruleset)(null, this.rules.slice(0)).eval({
frames: [this, frame].concat(this.frames, env.frames)
});
},
match: function (args, env) {
var argsLength = (args && args.length) || 0, len;
if (argsLength < this.required) { return false }
... | {
if (val = (args && args[i]) || this.params[i].value) {
frame.rules.unshift(new(tree.Rule)(this.params[i].name, val.eval(env)));
} else {
throw { message: "wrong number of arguments for " + this.name +
' (' + args.lengt... | conditional_block |
skyTile.py | #!/usr/bin/python
#
# Fabien Chereau fchereau@eso.org
#
import gzip
import os
def writePolys(pl, f):
"""Write a list of polygons pl into the file f.
The result is under the form [[[ra1, de1],[ra2, de2],[ra3, de3],[ra4, de4]], [[ra1, de1],[ra2, de2],[ra3, de3]]]"""
f.write('[')
for idx, poly in enumer... |
class SkyImageTile:
"""Contains all the properties needed to describe a multiresolution image tile"""
def __init__(self):
self.subTiles = []
self.imageCredits = StructCredits()
self.serverCredits = StructCredits()
self.imageInfo = StructCredits()
self.imageUrl = None
... | def __init__(self):
self.short = None
self.full = None
self.infoUrl = None
return
def outJSON(self, f, levTab):
if self.short != None:
f.write(levTab + '\t\t"short": "' + self.short + '",\n')
if self.full != None:
f.write(levTab + '\t\t"full":... | identifier_body |
skyTile.py | #!/usr/bin/python
#
# Fabien Chereau fchereau@eso.org
#
import gzip
import os
def writePolys(pl, f):
"""Write a list of polygons pl into the file f.
The result is under the form [[[ra1, de1],[ra2, de2],[ra3, de3],[ra4, de4]], [[ra1, de1],[ra2, de2],[ra3, de3]]]"""
f.write('[')
for idx, poly in enumer... | with open(fName) as ff:
fout = gzip.GzipFile(fName + ".gz", 'w')
fout.write(ff.read())
fout.close()
os.remove(fName)
def __subOutJSON(self, prefix, qCompress, maxLevelPerFile, f, curLev, outDir):
"""Write the tile in the file f"""
... | # Actually write the file with maxLevelPerFile level
with open(fName, 'w') as f:
self.__subOutJSON(prefix, qCompress, maxLevelPerFile, f, 0, outDir)
if (qCompress): | random_line_split |
skyTile.py | #!/usr/bin/python
#
# Fabien Chereau fchereau@eso.org
#
import gzip
import os
def writePolys(pl, f):
"""Write a list of polygons pl into the file f.
The result is under the form [[[ra1, de1],[ra2, de2],[ra3, de3],[ra4, de4]], [[ra1, de1],[ra2, de2],[ra3, de3]]]"""
f.write('[')
for idx, poly in enumer... |
if self.imageUrl:
f.write(levTab + '\t"imageUrl": "' + self.imageUrl + '",\n')
f.write(levTab + '\t"worldCoords": ')
writePolys(self.skyConvexPolygons, f)
f.write(',\n')
f.write(levTab + '\t"textureCoords": ')
writePolys(self.textureCoords, f)
f.write... | f.write(levTab + '\t"serverCredits": {\n')
self.serverCredits.outJSON(f, levTab)
f.write(levTab + '\t},\n') | conditional_block |
skyTile.py | #!/usr/bin/python
#
# Fabien Chereau fchereau@eso.org
#
import gzip
import os
def writePolys(pl, f):
"""Write a list of polygons pl into the file f.
The result is under the form [[[ra1, de1],[ra2, de2],[ra3, de3],[ra4, de4]], [[ra1, de1],[ra2, de2],[ra3, de3]]]"""
f.write('[')
for idx, poly in enumer... | (self):
self.subTiles = []
self.imageCredits = StructCredits()
self.serverCredits = StructCredits()
self.imageInfo = StructCredits()
self.imageUrl = None
self.alphaBlend = None
self.maxBrightness = None
return
def outputJSON(self, prefix='', qCompress... | __init__ | identifier_name |
click_report.test.js | import * as chai from 'chai';
const expect = chai.expect;
const chaiAsPromised = require('chai-as-promised');
import * as sinon from 'sinon';
import * as sinonAsPromised from 'sinon-as-promised';
import { ClickReport } from '../src/models/click_report';
chai.use(chaiAsPromised);
describe('ClickReport', () => {
cons... | });
describe('#get', () => {
it('calls the DynamoDB get method with correct params', (done) => {
ClickReport.get(campaignId, clickReportRangeKey).then(() => {
const args = ClickReport._client.lastCall.args;
expect(args[0]).to.equal('get');
expect(args[1]).to.have.deep.property(`Ke... | const clickReportRangeKey = 'timestamp';
before(() => {
sinon.stub(ClickReport, '_client').resolves(true);
tNameStub = sinon.stub(ClickReport, 'tableName', { get: () => tableName}); | random_line_split |
server.js | /**
* Module dependencies
*/
var Server = require('annex-ws-node').Server;
var http = require('http');
var stack = require('connect-stack');
var pns = require('pack-n-stack');
module.exports = function createServer(opts) {
var server = http.createServer();
server.stack = [];
server.handle = stack(server.stac... | server.stack.push(fn);
return server;
};
var routes = server.routes = {};
var hasPushedRouter = false;
server.register =
server.fn = function(modName, fnName, cb) {
var mod = routes[modName] = routes[modName] || {};
var fn = mod[fnName] = mod[fnName] || [];
fn.push(cb);
server.emit('... | fn.handle = fn; | random_line_split |
server.js | /**
* Module dependencies
*/
var Server = require('annex-ws-node').Server;
var http = require('http');
var stack = require('connect-stack');
var pns = require('pack-n-stack');
module.exports = function createServer(opts) {
var server = http.createServer();
server.stack = [];
server.handle = stack(server.stac... |
var wss = new Server({server: server, marshal: opts.marshal});
wss.listen(function(req, res) {
// TODO do a domain here
server.handle(req, res, function(err) {
if (!res._sent) {
err ? res.error(err.message) : res.error(req.module + ':' + req.method + ' not implemented');
if (err) co... | {
var mod = routes[req.module];
if (!mod) return next();
var fn = mod[req.method];
if (!fn) return next();
// TODO support next('route')
fn[0](req, res, next);
} | identifier_body |
server.js | /**
* Module dependencies
*/
var Server = require('annex-ws-node').Server;
var http = require('http');
var stack = require('connect-stack');
var pns = require('pack-n-stack');
module.exports = function createServer(opts) {
var server = http.createServer();
server.stack = [];
server.handle = stack(server.stac... | (req, res, next) {
var mod = routes[req.module];
if (!mod) return next();
var fn = mod[req.method];
if (!fn) return next();
// TODO support next('route')
fn[0](req, res, next);
}
var wss = new Server({server: server, marshal: opts.marshal});
wss.listen(function(req, res) {
// TODO do... | router | identifier_name |
index.js | var engine = require('../');
var express = require('express');
var path = require('path');
var app = express();
app.engine('dot', engine.__express);
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'dot');
app.get('/', function(req, res) {
res.render('index', { fromServer: 'Hello from serv... | res.render('helper/index', { fromServer: 'Hello from server', });
});
var server = app.listen(2015, function() {
console.log('Run the example at http://locahost:%d', server.address().port);
}); | // helper as a method
engine.helper.myHelperMethod = function(param) {
return 'Hello from server method helper (parameter: ' + param + ', server model: ' + this.model.fromServer + ')';
}
| random_line_split |
user.service.ts | import { Injectable, Inject } from '@angular/core';
import { User } from './user.model';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { IdType } from '../shared/shared-types';
import { BACKEND_SERVICE } from '../core/core.module';
import { BackendService } from '../core/backend.servic... | return this.backend.findAll(User);
}
findById(id: IdType): Observable<User | undefined> {
return this.backend.findById(User, id);
}
findByEmail(email: string): Observable<User | undefined> {
return this.backend.findAll(User).pipe(
map( users => users.find(user => user.email === email) )
... |
findAll(): Observable<User[]> { | random_line_split |
user.service.ts | import { Injectable, Inject } from '@angular/core';
import { User } from './user.model';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { IdType } from '../shared/shared-types';
import { BACKEND_SERVICE } from '../core/core.module';
import { BackendService } from '../core/backend.servic... | (@Inject(BACKEND_SERVICE) private backend: BackendService) { }
findAll(): Observable<User[]> {
return this.backend.findAll(User);
}
findById(id: IdType): Observable<User | undefined> {
return this.backend.findById(User, id);
}
findByEmail(email: string): Observable<User | undefined> {
return th... | constructor | identifier_name |
user.service.ts | import { Injectable, Inject } from '@angular/core';
import { User } from './user.model';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { IdType } from '../shared/shared-types';
import { BACKEND_SERVICE } from '../core/core.module';
import { BackendService } from '../core/backend.servic... |
findByEmail(email: string): Observable<User | undefined> {
return this.backend.findAll(User).pipe(
map( users => users.find(user => user.email === email) )
);
}
create(entity: User): Observable<User | undefined> {
return this.backend.add(User, entity);
}
update(entity: User): Observable<... | {
return this.backend.findById(User, id);
} | identifier_body |
regions-steal-closure.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let cl_box = {
let mut i = 3i;
box_it(box || i += 1) //~ ERROR cannot infer
};
cl_box.cl.call_mut(());
} |
fn box_it<'r>(x: Box<FnMut() + 'r>) -> closure_box<'r> {
closure_box {cl: x}
} | random_line_split |
regions-steal-closure.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a> {
cl: Box<FnMut() + 'a>,
}
fn box_it<'r>(x: Box<FnMut() + 'r>) -> closure_box<'r> {
closure_box {cl: x}
}
fn main() {
let cl_box = {
let mut i = 3i;
box_it(box || i += 1) //~ ERROR cannot infer
};
cl_box.cl.call_mut(());
}
| closure_box | identifier_name |
regions-steal-closure.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let cl_box = {
let mut i = 3i;
box_it(box || i += 1) //~ ERROR cannot infer
};
cl_box.cl.call_mut(());
} | identifier_body | |
options.rs | // The MIT License (MIT)
// Copyright (c) 2015 Y. T. Chung <zonyitoo@gmail.com>
// 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 righ... | () -> Options {
Options {
stack_size: rt::min_stack(),
name: None,
}
}
pub fn stack_size(mut self, size: usize) -> Options {
self.stack_size = size;
self
}
pub fn name(mut self, name: Option<String>) -> Options {
self.name = name;
... | new | identifier_name |
options.rs | // The MIT License (MIT)
// Copyright (c) 2015 Y. T. Chung <zonyitoo@gmail.com>
// 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 righ... | pub name: Option<String>,
}
impl Options {
pub fn new() -> Options {
Options {
stack_size: rt::min_stack(),
name: None,
}
}
pub fn stack_size(mut self, size: usize) -> Options {
self.stack_size = size;
self
}
pub fn name(mut self, name: ... | /// Coroutine options
pub struct Options {
pub stack_size: usize, | random_line_split |
test_utf8.py | import unittest
from pystan import stanc, StanModel
from pystan._compat import PY2
class | (unittest.TestCase):
desired = sorted({"status", "model_cppname", "cppcode", "model_name", "model_code", "include_paths"})
def test_utf8(self):
model_code = 'parameters {real y;} model {y ~ normal(0,1);}'
result = stanc(model_code=model_code)
self.assertEqual(sorted(result.keys()), sel... | TestUTF8 | identifier_name |
test_utf8.py | import unittest
| class TestUTF8(unittest.TestCase):
desired = sorted({"status", "model_cppname", "cppcode", "model_name", "model_code", "include_paths"})
def test_utf8(self):
model_code = 'parameters {real y;} model {y ~ normal(0,1);}'
result = stanc(model_code=model_code)
self.assertEqual(sorted(resul... | from pystan import stanc, StanModel
from pystan._compat import PY2
| random_line_split |
test_utf8.py | import unittest
from pystan import stanc, StanModel
from pystan._compat import PY2
class TestUTF8(unittest.TestCase):
desired = sorted({"status", "model_cppname", "cppcode", "model_name", "model_code", "include_paths"})
def test_utf8(self):
model_code = 'parameters {real y;} model {y ~ normal(0,1);}... | st_utf8_inprogramcode(self):
model_code = u'parameters {real ö;\n} model {ö ~ normal(0,1);}'
assertRaisesRegex = self.assertRaisesRegexp if PY2 else self.assertRaisesRegex
with assertRaisesRegex(ValueError, 'Failed to parse Stan model .*'):
stanc(model_code=model_code)
| l_code = u'parameters {real y;\n /*äöéü\näöéü*/\n} model {y ~ normal(0,1);}'
result = stanc(model_code=model_code)
self.assertEqual(sorted(result.keys()), self.desired)
self.assertTrue(result['cppcode'].startswith("// Code generated by Stan "))
self.assertEqual(result['status'], 0)
... | identifier_body |
setup.py | #!/usr/bin/python3
#from __future__ import print_function
from setuptools import setup, Extension
import sys
import os
import psutil
# monkey-patch for parallel compilation
def parallelCCompile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=No... | ():
platform = sys.platform
extensionsList = []
sources = ['src/Genome.cpp',
'src/Innovation.cpp',
'src/NeuralNetwork.cpp',
'src/Parameters.cpp',
'src/PhenotypeBehavior.cpp',
'src/Population.cpp',
'src/Random.cpp',
... | getExtensions | identifier_name |
setup.py | #!/usr/bin/python3
#from __future__ import print_function
from setuptools import setup, Extension
import sys
import os
import psutil
# monkey-patch for parallel compilation
def parallelCCompile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=No... |
if platform == 'darwin':
extra += ['-stdlib=libc++',
'-std=c++11',]
else:
extra += ['-std=gnu++11']
is_windows = 'win' in platform and platform != 'darwin'
if is_windows:
extra.append('/EHsc')
else:
extra.append('-w')
prefix = os.getenv('PREFIX')
... | random_line_split | |
setup.py | #!/usr/bin/python3
#from __future__ import print_function
from setuptools import setup, Extension
import sys
import os
import psutil
# monkey-patch for parallel compilation
def parallelCCompile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=No... |
elif build_sys == 'boost':
is_python_2 = sys.version_info[0] < 3
sources.insert(0, 'src/PythonBindings.cpp')
if is_windows:
if is_python_2:
raise RuntimeError("Python prior to version 3 is not supported on Windows due to limits of VC++ compiler version")
... | from Cython.Build import cythonize
sources.insert(0, '_MultiNEAT.pyx')
extra.append('-O3')
extensionsList.extend(cythonize([Extension('MultiNEAT._MultiNEAT',
sources,
extra_compile_args=extra)],... | conditional_block |
setup.py | #!/usr/bin/python3
#from __future__ import print_function
from setuptools import setup, Extension
import sys
import os
import psutil
# monkey-patch for parallel compilation
def parallelCCompile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=No... |
setup(name='multineat',
version='0.5', # Update version in conda/meta.yaml as well
packages=['MultiNEAT'],
ext_modules=getExtensions())
| platform = sys.platform
extensionsList = []
sources = ['src/Genome.cpp',
'src/Innovation.cpp',
'src/NeuralNetwork.cpp',
'src/Parameters.cpp',
'src/PhenotypeBehavior.cpp',
'src/Population.cpp',
'src/Random.cpp',
... | identifier_body |
app.module.ts | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { MapComponent } from './map/map.component';
import { Ng2MapModule} from 'ng2-map';
import {SearchComponent} from './search/search.component';
import {FormsModule,... | { }
| AppModule | identifier_name |
app.module.ts | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { MapComponent } from './map/map.component';
import { Ng2MapModule} from 'ng2-map';
import {SearchComponent} from './search/search.component';
import {FormsModule,... | HttpModule,
JsonpModule,
CommonModule
],
declarations: [
AppComponent,
MapComponent,
SearchComponent
],
providers: [SearchAPIService],
bootstrap: [ AppComponent ]
})
export class AppModule { } | ReactiveFormsModule, | random_line_split |
accessor-test.js | import HasManyHelper from './has-many-helper';
import {module, test} from 'qunit';
module('Integration | ORM | hasMany #accessor');
/*
#association behavior works regardless of the state of the parent
*/
HasManyHelper.forEachScenario((scenario) => {
test(`the references of a ${scenario.title} are correct`, funct... | });
});
}); | } | random_line_split |
accessor-test.js | import HasManyHelper from './has-many-helper';
import {module, test} from 'qunit';
module('Integration | ORM | hasMany #accessor');
/*
#association behavior works regardless of the state of the parent
*/
HasManyHelper.forEachScenario((scenario) => {
test(`the references of a ${scenario.title} are correct`, funct... |
});
});
});
| {
assert.ok(parent[idsAccessor].indexOf(child.id) > -1, 'each saved child id is in parent.childrenIds array');
} | conditional_block |
cursor.js | /**
* Baobab Cursors
* ===============
*
* Cursors created by selecting some data within a Baobab tree.
*/
import Emitter from 'emmett';
import {Monkey} from './monkey';
import type from './type';
import {
Archive,
arrayFrom,
before, | getIn,
makeError,
shallowClone,
solveUpdate
} from './helpers';
/**
* Traversal helper function for dynamic cursors. Will throw a legible error
* if traversal is not possible.
*
* @param {string} method - The method name, to create a correct error msg.
* @param {array} solvedPath - The cursor's solv... | coercePath,
deepClone, | random_line_split |
cursor.js | /**
* Baobab Cursors
* ===============
*
* Cursors created by selecting some data within a Baobab tree.
*/
import Emitter from 'emmett';
import {Monkey} from './monkey';
import type from './type';
import {
Archive,
arrayFrom,
before,
coercePath,
deepClone,
getIn,
makeError,
shallowClone,
solveUpd... |
/**
* Method returning the left sibling node of the cursor if this one is
* pointing at a list. Returns `null` if this cursor is already leftmost.
*
* @return {Baobab} - The left sibling cursor.
*/
left() {
checkPossibilityOfDynamicTraversal('left', this.solvedPath);
const last = +this.sol... | {
checkPossibilityOfDynamicTraversal('down', this.solvedPath);
if (!(this._get().data instanceof Array))
throw Error('Baobab.Cursor.down: cannot go down on a non-list type.');
return this.tree.select(this.solvedPath.concat(0));
} | identifier_body |
cursor.js | /**
* Baobab Cursors
* ===============
*
* Cursors created by selecting some data within a Baobab tree.
*/
import Emitter from 'emmett';
import {Monkey} from './monkey';
import type from './type';
import {
Archive,
arrayFrom,
before,
coercePath,
deepClone,
getIn,
makeError,
shallowClone,
solveUpd... | (path) {
path = coercePath(path);
if (arguments.length > 1)
path = arrayFrom(arguments);
if (!type.path(path))
throw makeError('Baobab.Cursor.getters: invalid path.', {path});
if (!this.solvedPath)
return undefined;
const fullPath = this.solvedPath.concat(path);
const data... | serialize | identifier_name |
map_clone.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_trait_method;
use clippy_utils::remove_blocks;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::{is_copy, is_type_diagnostic_item};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_... | applicability,
);
}
} | random_line_split | |
map_clone.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_trait_method;
use clippy_utils::remove_blocks;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::{is_copy, is_type_diagnostic_item};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_... | (cx: &LateContext<'_>, replace: Span, root: Span, copied: bool) {
let mut applicability = Applicability::MachineApplicable;
if copied {
span_lint_and_sugg(
cx,
MAP_CLONE,
replace,
"you are using an explicit closure for copying elements",
"consi... | lint | identifier_name |
map_clone.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_trait_method;
use clippy_utils::remove_blocks;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::{is_copy, is_type_diagnostic_item};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_... |
}
| {
span_lint_and_sugg(
cx,
MAP_CLONE,
replace,
"you are using an explicit closure for cloning elements",
"consider calling the dedicated `cloned` method",
format!(
"{}.cloned()",
snippet_with_applicability(cx,... | conditional_block |
map_clone.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_trait_method;
use clippy_utils::remove_blocks;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::{is_copy, is_type_diagnostic_item};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_... | {
let mut applicability = Applicability::MachineApplicable;
if copied {
span_lint_and_sugg(
cx,
MAP_CLONE,
replace,
"you are using an explicit closure for copying elements",
"consider calling the dedicated `copied` method",
format!(... | identifier_body | |
gamma.rs | // Copyright 2013 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 ... | /// See `Gamma` for sampling from a Gamma distribution with general
/// shape parameters.
struct GammaSmallShape {
inv_shape: f64,
large_shape: GammaLargeShape
}
/// Gamma distribution where the shape parameter is larger than 1.
///
/// See `Gamma` for sampling from a Gamma distribution with general
/// shape ... | random_line_split | |
gamma.rs | // Copyright 2013 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 gamma = Gamma::new(10., 1.0);
let mut rng = ::test::weak_rng();
b.iter(|| {
for _ in 0..::RAND_BENCH_N {
gamma.ind_sample(&mut rng);
}
});
b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N;
}
#[bench]
fn bench_gamma_s... | e_shape(b: &mut Bencher | identifier_name |
gamma.rs | // Copyright 2013 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 ... | l Sample<f64> for GammaSmallShape {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
}
impl Sample<f64> for GammaLargeShape {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
}
impl IndependentSample<f64> for Gamma {
fn ind_sample<R: Rng>(&self, rng: &mut R... | .ind_sample(rng) }
}
imp | identifier_body |
get_state_events_for_empty_key.rs | //! [GET /_matrix/client/r0/rooms/{roomId}/state/{eventType}](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-rooms-roomid-state-eventtype)
use ruma_api::ruma_api;
use ruma_events::EventType;
use ruma_identifiers::RoomId;
use serde_json::value::RawValue as RawJsonValue;
ruma_api! {
metadata... | response {
/// The content of the state event.
///
/// To create a `Box<RawJsonValue>`, use `serde_json::value::to_raw_value`.
#[ruma_api(body)]
pub content: Box<RawJsonValue>,
}
error: crate::Error
} | #[ruma_api(path)]
pub event_type: EventType,
}
| random_line_split |
key_value_table_demo.py | import json
import pprint
from a2qt import QtWidgets
from a2widget.key_value_table import KeyValueTable
from a2widget.a2text_field import A2CodeField
_DEMO_DATA = {
'Name': 'Some Body',
'Surname': 'Body',
'Street. Nr': 'Thingstreet 8',
'Street': 'Thingstreet',
'Nr': '8',
'PLZ': '12354',
... |
def table_to_code(self):
data = self.key_value_table.get_data()
self.text_field.setText(json.dumps(data, indent=2))
def code_to_table(self):
data = json.loads(self.text_field.text())
self.key_value_table.set_silent(data)
def get_data(self):
data = self.key_value_t... | super(Demo, self).__init__()
w = QtWidgets.QWidget(self)
self.setCentralWidget(w)
lyt = QtWidgets.QVBoxLayout(w)
self.key_value_table = KeyValueTable(self)
self.key_value_table.changed.connect(self.table_to_code)
lyt.addWidget(self.key_value_table)
btn = QtWidget... | identifier_body |
key_value_table_demo.py | import json
import pprint
from a2qt import QtWidgets
from a2widget.key_value_table import KeyValueTable
from a2widget.a2text_field import A2CodeField
_DEMO_DATA = {
'Name': 'Some Body',
'Surname': 'Body',
'Street. Nr': 'Thingstreet 8',
'Street': 'Thingstreet',
'Nr': '8',
'PLZ': '12354',
... | super(Demo, self).__init__()
w = QtWidgets.QWidget(self)
self.setCentralWidget(w)
lyt = QtWidgets.QVBoxLayout(w)
self.key_value_table = KeyValueTable(self)
self.key_value_table.changed.connect(self.table_to_code)
lyt.addWidget(self.key_value_table)
btn = ... | def __init__(self): | random_line_split |
key_value_table_demo.py | import json
import pprint
from a2qt import QtWidgets
from a2widget.key_value_table import KeyValueTable
from a2widget.a2text_field import A2CodeField
_DEMO_DATA = {
'Name': 'Some Body',
'Surname': 'Body',
'Street. Nr': 'Thingstreet 8',
'Street': 'Thingstreet',
'Nr': '8',
'PLZ': '12354',
... | (self):
data = self.key_value_table.get_data()
self.text_field.setText(json.dumps(data, indent=2))
def code_to_table(self):
data = json.loads(self.text_field.text())
self.key_value_table.set_silent(data)
def get_data(self):
data = self.key_value_table.get_data()
... | table_to_code | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.