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
where.rs
// Copyright 2014 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 ...
pub struct Alpha<A>(A) where A: MyTrait; // @has foo/trait.Bravo.html '//pre' "pub trait Bravo<B> where B: MyTrait" pub trait Bravo<B> where B: MyTrait { fn get(&self, B: B); } // @has foo/fn.charlie.html '//pre' "pub fn charlie<C>() where C: MyTrait" pub fn charlie<C>() where C: MyTrait {} pub struct Delta<D>(D); //...
#![crate_name = "foo"] pub trait MyTrait { fn dummy(&self) { } } // @has foo/struct.Alpha.html '//pre' "pub struct Alpha<A> where A: MyTrait"
random_line_split
where.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<A>(A) where A: MyTrait; // @has foo/trait.Bravo.html '//pre' "pub trait Bravo<B> where B: MyTrait" pub trait Bravo<B> where B: MyTrait { fn get(&self, B: B); } // @has foo/fn.charlie.html '//pre' "pub fn charlie<C>() where C: MyTrait" pub fn charlie<C>() where C: MyTrait {} pub struct Delta<D>(D); // @has foo/struct...
Alpha
identifier_name
sisr__smooth_8h.js
var sisr__smooth_8h = [ [ "SISRSmoother", "classSISRSmoother.html", "classSISRSmoother" ], [ "Mat", "sisr__smooth_8h.html#ae601f56a556993079f730483c574356f", null ], [ "Vec", "sisr__smooth_8h.html#a4c7df05c6f5e8a0d15ae14bcdbc07152", null ], [ "SISRResampStyle", "sisr__smooth_8h.html#a2486051fd2028dedca5...
[ "ess_multinomial", "sisr__smooth_8h.html#a2486051fd2028dedca520d3e0f8fd92fa9c6a482b0d50f2734e0da9f99d168098", null ] ] ] ];
[ "never", "sisr__smooth_8h.html#a2486051fd2028dedca520d3e0f8fd92fac7561db7a418dd39b2201dfe110ab4a4", null ], [ "ess_multinomial", "sisr__smooth_8h.html#a2486051fd2028dedca520d3e0f8fd92fa9c6a482b0d50f2734e0da9f99d168098", null ], [ "everytime_multinomial", "sisr__smooth_8h.html#a2486051fd2028dedca520d...
random_line_split
authorized.rs
use session::game::{Session, GameState}; use session::game::chunk::{self, Ref}; use protocol::messages::authorized::*; use std::io::Result; use server::SERVER; #[register_handlers] impl Session { pub fn handle_admin_quiet_command_message<'a>(&mut self, chunk: Ref<'a>, ...
chunk::teleport(chunk, ch, map_id, cell_id); } Ok(()) } }
{ let ch = match self.state { GameState::InContext(ref mut ch) => ch, _ => return Ok(()), }; if ch.movements.is_some() { return Ok(()); } let map_id: i32 = match msg.base.content.split(" ").last().map(|id| id.parse()) { Some(Ok(ma...
identifier_body
authorized.rs
use session::game::{Session, GameState}; use session::game::chunk::{self, Ref}; use protocol::messages::authorized::*; use std::io::Result; use server::SERVER; #[register_handlers] impl Session { pub fn
<'a>(&mut self, chunk: Ref<'a>, msg: AdminQuietCommandMessage) -> Result<()> { let ch = match self.state { GameState::InContext(ref mut ch) => ch, _ => return Ok(()), }; if ch.movements.is_some() { return Ok((...
handle_admin_quiet_command_message
identifier_name
authorized.rs
use session::game::{Session, GameState}; use session::game::chunk::{self, Ref}; use protocol::messages::authorized::*; use std::io::Result; use server::SERVER; #[register_handlers] impl Session { pub fn handle_admin_quiet_command_message<'a>(&mut self, chunk: Ref<'a>, ...
Ok(()) } }
{ chunk::teleport(chunk, ch, map_id, cell_id); }
conditional_block
authorized.rs
use session::game::{Session, GameState}; use session::game::chunk::{self, Ref}; use protocol::messages::authorized::*; use std::io::Result; use server::SERVER; #[register_handlers] impl Session { pub fn handle_admin_quiet_command_message<'a>(&mut self, chunk: Ref<'a>, ...
Ok(()) } }
}
random_line_split
lib.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/. */ // For simd (currently x86_64/aarch64) #![cfg_attr(any(target_os = "linux", target_os = "android", target_os = "wi...
pub mod paint_thread; // Platform-specific implementations. #[allow(unsafe_code)] mod platform; // Text pub mod text;
pub mod font_context; pub mod font_template;
random_line_split
TestNativeDivide.rs
/* * Copyright (C) 2016 The Android Open Source Project * * 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 app...
float __attribute__((kernel)) testNativeDivideFloatFloatFloat(float inLeftVector, unsigned int x) { float inRightVector = rsGetElementAt_float(gAllocInRightVector, x); return native_divide(inLeftVector, inRightVector); } float2 __attribute__((kernel)) testNativeDivideFloat2Float2Float2(float2 inLeftVector, un...
#pragma rs java_package_name(android.renderscript.cts) rs_allocation gAllocInRightVector;
random_line_split
test_aci-3.py
import pytest import psi4 from forte.solvers import solver_factory, HF, ActiveSpaceSolver, SpinAnalysis def test_aci_3():
'diag_algorithm': 'SPARSE', 'active_guess_size': 300, 'aci_screen_alg': 'BATCH_HASH', 'aci_nbatch': 2 } aci = ActiveSpaceSolver(hf, type='ACI', states=state, e_convergence=1.0e-11, r_convergence=1.0e-7, options=options) spin = SpinAnalysis(aci, options={'SPIN_TEST': True}) ...
"""Test FCI on H4/STO-3G. Reproduces the test aci-1""" ref_hf_energy = -2.0310813811962456 ref_aci_energy = -2.115455548674 ref_acipt2_energy = -2.116454734743 spin_val = 1.02027340 # setup job xyz = """ H -0.4 0.0 0.0 H 0.4 0.0 0.0 H 0.1 -0.3 1.0 H -0.1 0.5 1.0 """ ...
identifier_body
test_aci-3.py
import pytest import psi4 from forte.solvers import solver_factory, HF, ActiveSpaceSolver, SpinAnalysis def test_aci_3(): """Test FCI on H4/STO-3G. Reproduces the test aci-1""" ref_hf_energy = -2.0310813811962456 ref_aci_energy = -2.115455548674 ref_acipt2_energy = -2.116454734743 spin_val = 1.0...
H -0.4 0.0 0.0 H 0.4 0.0 0.0 H 0.1 -0.3 1.0 H -0.1 0.5 1.0 """ input = solver_factory(molecule=xyz, basis='cc-pVDZ') state = input.state(charge=0, multiplicity=1, sym='a') hf = HF(input, state=state, e_convergence=1.0e-12, d_convergence=1.0e-6) options = { 'sigma': 0.001...
random_line_split
test_aci-3.py
import pytest import psi4 from forte.solvers import solver_factory, HF, ActiveSpaceSolver, SpinAnalysis def
(): """Test FCI on H4/STO-3G. Reproduces the test aci-1""" ref_hf_energy = -2.0310813811962456 ref_aci_energy = -2.115455548674 ref_acipt2_energy = -2.116454734743 spin_val = 1.02027340 # setup job xyz = """ H -0.4 0.0 0.0 H 0.4 0.0 0.0 H 0.1 -0.3 1.0 H -0.1 0.5 1.0 ...
test_aci_3
identifier_name
test_aci-3.py
import pytest import psi4 from forte.solvers import solver_factory, HF, ActiveSpaceSolver, SpinAnalysis def test_aci_3(): """Test FCI on H4/STO-3G. Reproduces the test aci-1""" ref_hf_energy = -2.0310813811962456 ref_aci_energy = -2.115455548674 ref_acipt2_energy = -2.116454734743 spin_val = 1.0...
test_aci_3()
conditional_block
ClusterLauncher.py
import os import sys import time import subprocess import yaml import pathlib class ClusterLauncher: def __init__(self, config_yaml): self.Config = config_yaml def
(self): #read config with open(self.Config, 'r') as yf: config = yaml.safe_load(yf) #launch head node head = ClusterLauncher.LaunchUniCAVEWindow(config["build-path"], config["head-node"]) #wait a bit before launching child nodes if config["he...
Launch
identifier_name
ClusterLauncher.py
import os import sys import time import subprocess import yaml import pathlib class ClusterLauncher:
if config["child-wait"] is not None: time.sleep(config["child-wait"]) #poll head node process done = False while not done: if head.poll() is not None: done = True time.sleep(config["sleep-time"])...
def __init__(self, config_yaml): self.Config = config_yaml def Launch(self): #read config with open(self.Config, 'r') as yf: config = yaml.safe_load(yf) #launch head node head = ClusterLauncher.LaunchUniCAVEWindow(config["build-path"], config["head-node"...
identifier_body
ClusterLauncher.py
import os import sys import time import subprocess import yaml import pathlib class ClusterLauncher: def __init__(self, config_yaml): self.Config = config_yaml def Launch(self): #read config with open(self.Config, 'r') as yf: config = yaml.safe_load(yf) #launch...
#wait a bit between launching each child if config["child-wait"] is not None: time.sleep(config["child-wait"]) #poll head node process done = False while not done: if head.poll() is not None: don...
children = [] for child_node in config["child-nodes"]: children.append(ClusterLauncher.LaunchUniCAVEWindow(config["build-path"], child_node))
random_line_split
ClusterLauncher.py
import os import sys import time import subprocess import yaml import pathlib class ClusterLauncher: def __init__(self, config_yaml): self.Config = config_yaml def Launch(self): #read config with open(self.Config, 'r') as yf: config = yaml.safe_load(yf) #launch...
return subprocess.Popen(args) if __name__ == "__main__": ClusterLauncher(os.path.join(pathlib.Path(__file__).parent.absolute(), "config/input_test.yaml")).Launch()
args = args + ["overrideMachineName", machine_name]
conditional_block
celeba_formatting.py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def main(): """Main converter function.""" # Celeb A with open(FLAGS.partition_fn, "r") as infile: img_fn_list = infile.readlines() img_fn_list = [elem.strip().split() for elem in img_fn_lis...
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
identifier_body
celeba_formatting.py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
(): """Main converter function.""" # Celeb A with open(FLAGS.partition_fn, "r") as infile: img_fn_list = infile.readlines() img_fn_list = [elem.strip().split() for elem in img_fn_list] img_fn_list = [elem[0] for elem in img_fn_list if elem[1] == FLAGS.set] fn_root = FLAGS.fn_root num...
main
identifier_name
celeba_formatting.py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
main()
conditional_block
celeba_formatting.py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
for example_idx, img_fn in enumerate(img_fn_list): if example_idx % 1000 == 0: print example_idx, "/", num_examples image_raw = scipy.ndimage.imread(os.path.join(fn_root, img_fn)) rows = image_raw.shape[0] cols = image_raw.shape[1] depth = image_raw.shape[2] ...
file_out = "%s.tfrecords" % FLAGS.file_out writer = tf.python_io.TFRecordWriter(file_out)
random_line_split
config.py
# -*- coding: utf-8 -*- import os, argparse from flask import Flask parser = argparse.ArgumentParser() #настройка аргументов принимаемых с консоли parser.add_argument("--port", default='7000', type=int, help='Port to listen'), parser.add_argument("--hash-algo", default='sha1', type=str, help='Hashing algorithm to ...
1024 * 1024 #Максимальный размер загружаемых файлов (16 mb)
NTENT_LENGTH'] = 16 *
conditional_block
config.py
# -*- coding: utf-8 -*- import os, argparse from flask import Flask parser = argparse.ArgumentParser() #настройка аргументов принимаемых с консоли parser.add_argument("--port", default='7000', type=int, help='Port to listen'), parser.add_argument("--hash-algo", default='sha1', type=str, help='Hashing algorithm to ...
os.mkdir(content_dir) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = os.path.join(BASE_DIR, content_dir) app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 #Максимальный размер загружаемых файлов (16 mb)
BASE_DIR = os.path.abspath('.') if os.path.exists(os.path.join(BASE_DIR, content_dir)) == False: #если нету папки 'UPLOADS', в которой будут храниться все загрузки, создаем ее
random_line_split
pthread.rs
//! Low level threading primitives #[cfg(not(target_os = "redox"))] use crate::errno::Errno; #[cfg(not(target_os = "redox"))] use crate::Result; use libc::{self, pthread_t}; /// Identifies an individual thread. pub type Pthread = pthread_t; /// Obtain ID of the calling thread (see /// [`pthread_self(3)`](https://pub...
Errno::result(res).map(drop) } }
let sig = match signal.into() { Some(s) => s as libc::c_int, None => 0, }; let res = unsafe { libc::pthread_kill(thread, sig) };
random_line_split
pthread.rs
//! Low level threading primitives #[cfg(not(target_os = "redox"))] use crate::errno::Errno; #[cfg(not(target_os = "redox"))] use crate::Result; use libc::{self, pthread_t}; /// Identifies an individual thread. pub type Pthread = pthread_t; /// Obtain ID of the calling thread (see /// [`pthread_self(3)`](https://pub...
feature! { #![feature = "signal"] /// Send a signal to a thread (see [`pthread_kill(3)`]). /// /// If `signal` is `None`, `pthread_kill` will only preform error checking and /// won't send any signal. /// /// [`pthread_kill(3)`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html #[cfg(not(...
{ unsafe { libc::pthread_self() } }
identifier_body
pthread.rs
//! Low level threading primitives #[cfg(not(target_os = "redox"))] use crate::errno::Errno; #[cfg(not(target_os = "redox"))] use crate::Result; use libc::{self, pthread_t}; /// Identifies an individual thread. pub type Pthread = pthread_t; /// Obtain ID of the calling thread (see /// [`pthread_self(3)`](https://pub...
() -> Pthread { unsafe { libc::pthread_self() } } feature! { #![feature = "signal"] /// Send a signal to a thread (see [`pthread_kill(3)`]). /// /// If `signal` is `None`, `pthread_kill` will only preform error checking and /// won't send any signal. /// /// [`pthread_kill(3)`]: https://pubs.opengroup.org/onlinep...
pthread_self
identifier_name
fastq.rs
/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! FastQ reading and writing. //! //! # Example //! //! ``` //! use std::io; //! use bio::io::fastq; //! let reader = fastq::Reader::new(io::stdin()); //! ``` use std::convert::AsRef; use std::fmt; use std::fs...
try!(self.reader.read_line(&mut record.qual)); if record.qual.is_empty() { return Err(io::Error::new( io::ErrorKind::Other, "Incomplete record. Each FastQ record has to consist \ of 4 lines: header, sequence, separator ...
try!(self.reader.read_line(&mut record.seq)); try!(self.reader.read_line(&mut self.sep_line));
random_line_split
fastq.rs
/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! FastQ reading and writing. //! //! # Example //! //! ``` //! use std::io; //! use bio::io::fastq; //! let reader = fastq::Reader::new(io::stdin()); //! ``` use std::convert::AsRef; use std::fmt; use std::fs; use std...
if !self.qual.is_ascii() { return Err("Non-ascii character found in qualities."); } if self.seq().len() != self.qual().len() { return Err("Unequal length of sequence an qualities."); } Ok(()) } /// Return the id of the record. pub fn id(&self...
return Err("Non-ascii character found in sequence."); }
conditional_block
fastq.rs
/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! FastQ reading and writing. //! //! # Example //! //! ``` //! use std::io; //! use bio::io::fastq; //! let reader = fastq::Reader::new(io::stdin()); //! ``` use std::convert::AsRef; use std::fmt; use std::fs; use std...
} /// A FastQ record. #[derive(Debug, Clone, Default)] pub struct Record { id: String, desc: Option<String>, seq: String, qual: String, } impl Record { /// Create a new, empty FastQ record. pub fn new() -> Self { Record { id: String::new(), desc: None, ...
Records { reader: self } }
identifier_body
fastq.rs
/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! FastQ reading and writing. //! //! # Example //! //! ``` //! use std::io; //! use bio::io::fastq; //! let reader = fastq::Reader::new(io::stdin()); //! ``` use std::convert::AsRef; use std::fmt; use std::fs; use std...
) { let reader = Reader::new(FASTQ_FILE); let records: Vec<io::Result<Record>> = reader.records().collect(); assert!(records.len() == 1); for res in records { let record = res.ok().unwrap(); assert_eq!(record.check(), Ok(())); assert_eq!(record.id(), "...
est_reader(
identifier_name
index.ts
// Copyright 2020 Google 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 agreed to in ...
export {UserEventServiceClient} from './user_event_service_client';
export {CatalogServiceClient} from './catalog_service_client'; export {PredictionApiKeyRegistryClient} from './prediction_api_key_registry_client'; export {PredictionServiceClient} from './prediction_service_client';
random_line_split
serializers.py
from rest_framework import serializers from workers.models import (TaskConfig, Task, Job, TaskProducer) from grabbers.serializers import (MapperSerializer, SequenceSerializer) from grabbers.models impor...
class JobSerializer(serializers.ModelSerializer): ''' ''' class Meta: model=Job fields=('status','name') class TaskSerializer(serializers.ModelSerializer): ''' ''' config=TaskConfigDetailSerializer() job=JobSerializer() class Meta: model=Task fields=('...
''' ''' class Meta: model=TaskConfig fields=('url', 'name', 'sequence', 'driver', 'mapper','round_limit') extra_kwargs = { 'url': {'view_name': 'api:task_config-detail', 'lookup_field':'name'}, 'driver': {'view_name': 'api:driver-detail', 'lookup_field':'name'}, ...
identifier_body
serializers.py
from rest_framework import serializers from workers.models import (TaskConfig, Task, Job, TaskProducer) from grabbers.serializers import (MapperSerializer, SequenceSerializer) from grabbers.models impor...
fields=('name','driver','sequence','mapper','round_limit') def create(self, validated_data): ''' ''' name=validated_data['name'] try: task_config=TaskConfig.objects.get(name=name) print("[-] We already this guy in db") return task_config ...
class Meta: model=TaskConfig #no proxy by api yet - missing fields::proxy,network_cap
random_line_split
serializers.py
from rest_framework import serializers from workers.models import (TaskConfig, Task, Job, TaskProducer) from grabbers.serializers import (MapperSerializer, SequenceSerializer) from grabbers.models impor...
: model=Task fields=('target_url', 'config', 'status', 'job')
Meta
identifier_name
http_get.rs
extern crate clap; extern crate fibers; extern crate futures; extern crate miasht; use clap::{App, Arg}; use fibers::{Executor, InPlaceExecutor, Spawn}; use futures::{Future, IntoFuture}; use miasht::{Client, Method}; use miasht::builtin::{FutureExt, IoExt}; fn main()
Client::new() .connect(addr) .and_then(move |connection| connection.build_request(Method::Get, &path).finish()) .and_then(|req| req.read_response()) .and_then(|res| { res.into_body_reader() .into_future() .an...
{ let matches = App::new("http_get") .arg(Arg::with_name("HOST").index(1).required(true)) .arg(Arg::with_name("PATH").index(2).required(true)) .arg( Arg::with_name("PORT") .short("p") .takes_value(true) .default_value("80"), ...
identifier_body
http_get.rs
extern crate clap; extern crate fibers; extern crate futures; extern crate miasht; use clap::{App, Arg}; use fibers::{Executor, InPlaceExecutor, Spawn}; use futures::{Future, IntoFuture}; use miasht::{Client, Method}; use miasht::builtin::{FutureExt, IoExt}; fn main() { let matches = App::new("http_get") ...
); match executor.run_fiber(monitor).unwrap() { Ok(s) => println!("{}", s), Err(e) => println!("[ERROR] {:?}", e), } }
.into_future() .and_then(|r| r.read_all_str()) .map(|(_, body)| body) }),
random_line_split
http_get.rs
extern crate clap; extern crate fibers; extern crate futures; extern crate miasht; use clap::{App, Arg}; use fibers::{Executor, InPlaceExecutor, Spawn}; use futures::{Future, IntoFuture}; use miasht::{Client, Method}; use miasht::builtin::{FutureExt, IoExt}; fn
() { let matches = App::new("http_get") .arg(Arg::with_name("HOST").index(1).required(true)) .arg(Arg::with_name("PATH").index(2).required(true)) .arg( Arg::with_name("PORT") .short("p") .takes_value(true) .default_value("80"), ...
main
identifier_name
example.rs
extern crate int_range_check; use std::fmt::Display; use std::num::Int; use int_range_check::uncovered_and_overlapped; use int_range_check::IntRange; use int_range_check::IntRange::*; fn main() { example_driver("Example 1", vec![Bound(0i32, 5i32), From(3)]); example_driver("Example 2a", vec![To(5u8), From(2...
println!("{} uncovered ranges: {}", title, uncovered); println!("{} overlapping ranges: {}", title, overlapped); }
println!("{} input ranges: {}", title, ranges);
random_line_split
example.rs
extern crate int_range_check; use std::fmt::Display; use std::num::Int; use int_range_check::uncovered_and_overlapped; use int_range_check::IntRange; use int_range_check::IntRange::*; fn main() { example_driver("Example 1", vec![Bound(0i32, 5i32), From(3)]); example_driver("Example 2a", vec![To(5u8), From(...
<T: Display+Int>(title: &str, ranges: Vec<IntRange<T>>) { let (uncovered, overlapped) = uncovered_and_overlapped(&ranges); println!("{} input ranges: {}", title, ranges); println!("{} uncovered ranges: {}", title, uncovered); println!("{} overlapping ranges: {}", title, overlapped); }
example_driver
identifier_name
example.rs
extern crate int_range_check; use std::fmt::Display; use std::num::Int; use int_range_check::uncovered_and_overlapped; use int_range_check::IntRange; use int_range_check::IntRange::*; fn main()
fn example_driver<T: Display+Int>(title: &str, ranges: Vec<IntRange<T>>) { let (uncovered, overlapped) = uncovered_and_overlapped(&ranges); println!("{} input ranges: {}", title, ranges); println!("{} uncovered ranges: {}", title, uncovered); println!("{} overlapping ranges: {}", title, overla...
{ example_driver("Example 1", vec![Bound(0i32, 5i32), From(3)]); example_driver("Example 2a", vec![To(5u8), From(250)]); example_driver("Example 2b", vec![Bound(0u8, 5), Bound(250, 255)]); }
identifier_body
views.py
# -*- encoding: utf-8 -*- import hashlib import json import os import re import magic from perpetualfailure.db import session from pyramid.authentication import ( Authenticated, Everyone, ) from pyramid.httpexceptions import ( HTTPException, HTTPBadRequest, HTTPFound, HTTPNotFound, HTTPForb...
return {"gamemode": mode} @view_config( route_name='servers.gmod.acp.gamemode.edit', renderer="gmod/acp/gamemode.mako", permission=Authenticated, ) def acp_gamemode_edit(request): mode = session.query(m.LS_Gamemode).filter(m.LS_Gamemode.id==request.matchdict["id"]).first() if not request.per...
return r
conditional_block
views.py
# -*- encoding: utf-8 -*- import hashlib import json import os import re import magic from perpetualfailure.db import session from pyramid.authentication import ( Authenticated, Everyone, ) from pyramid.httpexceptions import ( HTTPException, HTTPBadRequest, HTTPFound, HTTPNotFound, HTTPForb...
(request): map = None if "map" in request.GET: map = request.GET["map"] gamemode = None if "gamemode" in request.GET: gamemode = request.GET["gamemode"] query = session.query(m.LS_Background) query = query.filter(m.LS_Background.gamemode.in_([gamemode, None])) query = query...
gmod_background
identifier_name
views.py
# -*- encoding: utf-8 -*- import hashlib import json import os import re import magic from perpetualfailure.db import session from pyramid.authentication import ( Authenticated, Everyone, ) from pyramid.httpexceptions import ( HTTPException, HTTPBadRequest, HTTPFound, HTTPNotFound, HTTPForb...
if query.count() < 1: query = session.query(m.LS_Background) query = query.filter(m.LS_Background.gamemode == gamemode) if query.count() < 1: query = session.query(m.LS_Background) bg = query.order_by(func.random()).first() retur...
map = None if "map" in request.GET: map = request.GET["map"] gamemode = None if "gamemode" in request.GET: gamemode = request.GET["gamemode"] query = session.query(m.LS_Background) query = query.filter(m.LS_Background.gamemode.in_([gamemode, None])) query = query.filter(m.LS_Ba...
identifier_body
views.py
# -*- encoding: utf-8 -*- import hashlib import json import os import re import magic from perpetualfailure.db import session from pyramid.authentication import ( Authenticated, Everyone, ) from pyramid.httpexceptions import ( HTTPException, HTTPBadRequest, HTTPFound, HTTPNotFound, HTTPForb...
if oldline == line and line.strip(): if not output: output.append("") output[-1] = (output[-1] + " " + line.strip()).strip() elif line.strip(): output.append(line.strip()) return output gamemode.title = request.para...
oldline = line if line.startswith("- "): line = line[2:] line = re.sub("^[0-9]+\. ", "", line)
random_line_split
Ghastly.js
import { Client } from 'discord.js'; import { isFunction, isRegExp, isString } from 'lodash/lang'; import CommandRegistry from '../command/CommandRegistry'; import Dispatcher from './dispatcher/Dispatcher'; import ServiceContainer from './services/ServiceContainer'; /** * @external {ClientOptions} https://discord.js....
extends Client { /** * Constructor. * @param {ClientOptions} options - The options for the client. * @param {PrefixType} options.prefix - The prefix for the client's dispatcher. * If a function is provided, it is given a received `Message` as an argument * and must return a `boolean` indicating if...
Ghastly
identifier_name
Ghastly.js
import { Client } from 'discord.js'; import { isFunction, isRegExp, isString } from 'lodash/lang'; import CommandRegistry from '../command/CommandRegistry'; import Dispatcher from './dispatcher/Dispatcher'; import ServiceContainer from './services/ServiceContainer'; /** * @external {ClientOptions} https://discord.js....
* @type {ServiceContainer} */ this.services = new ServiceContainer(); /** * The client's dispatcher. * @type {Dispatcher} * @private */ this.dispatcher = new Dispatcher({ client: this, prefix }); } }
random_line_split
Ghastly.js
import { Client } from 'discord.js'; import { isFunction, isRegExp, isString } from 'lodash/lang'; import CommandRegistry from '../command/CommandRegistry'; import Dispatcher from './dispatcher/Dispatcher'; import ServiceContainer from './services/ServiceContainer'; /** * @external {ClientOptions} https://discord.js....
super(rest); /** * The command registry for the client. * @type {CommandRegistry} */ this.commands = new CommandRegistry(); /** * The client's service container. * @type {ServiceContainer} */ this.services = new ServiceContainer(); /** * The client's dispa...
{ throw new TypeError('Expected prefix to be a string, RegExp or function.'); }
conditional_block
group_by.rs
use deuterium::*; #[test] fn select_group_by() { let jedi_table = TableDef::new("jedi"); let name = NamedField::<String>::field_of("name", &jedi_table); let side = NamedField::<bool>::field_of("side", &jedi_table); let force_level = NamedField::<i8>::field_of("force_level", &jedi_table); let quer...
() { let jedi_table = TableDef::new("jedi"); let name = NamedField::<String>::field_of("name", &jedi_table); let force_level = NamedField::<i8>::field_of("force_level", &jedi_table); let query = jedi_table.select_2(&name, &force_level.sum()).group_by(&[&name]); assert_sql!(query, "SELECT name, SUM...
select_with_agg
identifier_name
group_by.rs
use deuterium::*; #[test] fn select_group_by() { let jedi_table = TableDef::new("jedi"); let name = NamedField::<String>::field_of("name", &jedi_table); let side = NamedField::<bool>::field_of("side", &jedi_table); let force_level = NamedField::<i8>::field_of("force_level", &jedi_table); let quer...
{ let jedi_table = TableDef::new("jedi"); let name = NamedField::<String>::field_of("name", &jedi_table); let force_level = NamedField::<i8>::field_of("force_level", &jedi_table); let query = jedi_table.select_2(&name, &force_level.sum()).group_by(&[&name]); assert_sql!(query, "SELECT name, SUM(fo...
identifier_body
group_by.rs
use deuterium::*; #[test] fn select_group_by() { let jedi_table = TableDef::new("jedi"); let name = NamedField::<String>::field_of("name", &jedi_table); let side = NamedField::<bool>::field_of("side", &jedi_table); let force_level = NamedField::<i8>::field_of("force_level", &jedi_table); let quer...
} #[test] fn select_with_agg() { let jedi_table = TableDef::new("jedi"); let name = NamedField::<String>::field_of("name", &jedi_table); let force_level = NamedField::<i8>::field_of("force_level", &jedi_table); let query = jedi_table.select_2(&name, &force_level.sum()).group_by(&[&name]); assert_...
let query = jedi_table.select_2(&name, &force_level.sum()).group_by(&[&name]); assert_sql!(query, "SELECT name, SUM(force_level) FROM jedi GROUP BY name;");
random_line_split
views.py
# Copyright (C) 2014 Universidad Politecnica de Madrid # # 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 la...
def get_organizations_data(self): organizations = [] # try: # organizations = fiware_api.keystone.project_list( # self.request, # user=self.request.user.id) # switchable_organizations = [org.id for org # ...
return False
identifier_body
views.py
# Copyright (C) 2014 Universidad Politecnica de Madrid # # 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 la...
# for org in organizations: # if org.id in switchable_organizations: # setattr(org, 'switchable', True) # except Exception: # exceptions.handle(self.request, # ("Unable to retrieve organization list.")) return idm...
# switchable_organizations = [org.id for org # in self.request.organizations] # organizations = sorted(organizations, key=lambda x: x.name.lower())
random_line_split
views.py
# Copyright (C) 2014 Universidad Politecnica de Madrid # # 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 la...
(self, request, *args, **kwargs): if request.organization.id != request.user.default_project_id: return redirect("/idm/home_orgs/") return super(IndexView, self).dispatch(request, *args, **kwargs) def has_more_data(self, table): return False def get_organizations_data(self)...
dispatch
identifier_name
views.py
# Copyright (C) 2014 Universidad Politecnica de Madrid # # 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 la...
return super(IndexView, self).dispatch(request, *args, **kwargs) def has_more_data(self, table): return False def get_organizations_data(self): organizations = [] # try: # organizations = fiware_api.keystone.project_list( # self.request, # ...
return redirect("/idm/home_orgs/")
conditional_block
test_api.py
_series_equal(result, expected) result = self.series_klass(d, index=['b', 'c', 'd', 'a']) expected = self.series_klass([1, 2, np.nan, 0], index=['b', 'c', 'd', 'a']) self._assert_series_equal(result, expected) def test_constructor_subclass_dict(self): ...
result = Series(np.ones_like(s)) expected = Series(1, index=range(10), dtype='float64') tm.assert_series_equal(result, expected)
random_line_split
test_api.py
.ts.copy() cp.name = 'something else' result = self.ts + cp assert result.name is None result = self.ts.add(cp) assert result.name is None ops = ['add', 'sub', 'mul', 'div', 'truediv', 'floordiv', 'mod', 'pow'] ops = ops + ['r' + op for op in ops] for op ...
# assert is lazy (genrators don't define reverse, lists do) assert not hasattr(self.series.iteritems(), 'reverse') def test_items(self): for idx, val in self.series.items(): assert val == self.series[idx] for idx, val in self.ts.items(): assert val == self...
assert val == self.ts[idx]
conditional_block
test_api.py
, self.series) assert_series_equal(unp_ts, self.ts) def _pickle_roundtrip(self, obj): with ensure_clean() as path: obj.to_pickle(path) unpickled = pd.read_pickle(path) return unpickled def test_argsort_preserve_name(self): result = self.ts.argsort()...
test_ndarray_compat
identifier_name
test_api.py
def test_scalarop_preserve_name(self): result = self.ts * 2 assert result.name == self.ts.name def test_copy_name(self): result = self.ts.copy() assert result.name == self.ts.name def test_copy_index_name_checking(self): # don't want to be able to modify the index...
"""Dispatch to series class dependent assertion""" raise NotImplementedError
identifier_body
ExportOverlay.tsx
import React, {PureComponent} from 'react' import {connect, ConnectedProps} from 'react-redux' import {get} from 'lodash' // Components import { Form, Button, SpinnerContainer, TechnoSpinner, Overlay, } from '@influxdata/clockface' import {Controlled as ReactCodeMirror} from 'react-codemirror2' import CopyBu...
color={ComponentColor.Primary} /> ) } private get toTemplateButton(): JSX.Element { return ( <Button text="Save as template" onClick={this.handleConvertToTemplate} color={ComponentColor.Primary} /> ) } private handleExport = (): void => { const...
<Button text="Download JSON" onClick={this.handleExport}
random_line_split
ExportOverlay.tsx
import React, {PureComponent} from 'react' import {connect, ConnectedProps} from 'react-redux' import {get} from 'lodash' // Components import { Form, Button, SpinnerContainer, TechnoSpinner, Overlay, } from '@influxdata/clockface' import {Controlled as ReactCodeMirror} from 'react-codemirror2' import CopyBu...
() { const {isVisible, resourceName, onDismissOverlay, status} = this.props return ( <Overlay visible={isVisible}> <Overlay.Container maxWidth={800}> <Form onSubmit={this.handleExport}> <Overlay.Header title={`Export ${resourceName}`} onDismiss={o...
render
identifier_name
ExportOverlay.tsx
import React, {PureComponent} from 'react' import {connect, ConnectedProps} from 'react-redux' import {get} from 'lodash' // Components import { Form, Button, SpinnerContainer, TechnoSpinner, Overlay, } from '@influxdata/clockface' import {Controlled as ReactCodeMirror} from 'react-codemirror2' import CopyBu...
private get copyButton(): JSX.Element { return ( <CopyButton textToCopy={this.resourceText} contentName={this.props.resourceName} onCopyText={this.props.onCopyText} size={ComponentSize.Small} color={ComponentColor.Secondary} /> ) } private get downloa...
{ return JSON.stringify(this.props.resource, null, 1) }
identifier_body
window_wall_ratio_south_MFH_by_building_age_correlation.py
# OeQ autogenerated correlation for 'Window/Wall Ratio South in Correlation to the Building Age' import math import numpy as np from . import oeqCorrelation as oeq def
(*xin): # OeQ autogenerated correlation for 'Window to Wall Ratio in Southern Direction' A_WIN_S_BY_AW= oeq.correlation( const= 20818.6194135, a= -42.6513518642, b= 0.0327511835635, c= -1.11718058834e-05, d= 1.42836626434e-09, mode= "lin") return dict(A_WIN_S_BY_AW=...
get
identifier_name
window_wall_ratio_south_MFH_by_building_age_correlation.py
# OeQ autogenerated correlation for 'Window/Wall Ratio South in Correlation to the Building Age' import math
A_WIN_S_BY_AW= oeq.correlation( const= 20818.6194135, a= -42.6513518642, b= 0.0327511835635, c= -1.11718058834e-05, d= 1.42836626434e-09, mode= "lin") return dict(A_WIN_S_BY_AW=A_WIN_S_BY_AW.lookup(*xin))
import numpy as np from . import oeqCorrelation as oeq def get(*xin): # OeQ autogenerated correlation for 'Window to Wall Ratio in Southern Direction'
random_line_split
window_wall_ratio_south_MFH_by_building_age_correlation.py
# OeQ autogenerated correlation for 'Window/Wall Ratio South in Correlation to the Building Age' import math import numpy as np from . import oeqCorrelation as oeq def get(*xin): # OeQ autogenerated correlation for 'Window to Wall Ratio in Southern Direction'
A_WIN_S_BY_AW= oeq.correlation( const= 20818.6194135, a= -42.6513518642, b= 0.0327511835635, c= -1.11718058834e-05, d= 1.42836626434e-09, mode= "lin") return dict(A_WIN_S_BY_AW=A_WIN_S_BY_AW.lookup(*xin))
identifier_body
stats.js
/*** * Copyright (c) 2016 - 2021 Alex Grant (@localnerve), LocalNerve LLC * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms. */ /*eslint no-console:0 */ import { promises as fs } from 'fs'; import merge from 'lodash/merge'; import AsyncLock from 'async-lock'; const lock = new ...
output.assets[key] = value; }); // Webpack can be running multiple configurations in parallel... // THIS IS NO LONGER TRUE from WEBPACK 2+ for multi-compiler invocations. // However, you can make it so using webpack-parallel or other packages. // No harm in forcing serial execution. retu...
{ key = matches[1]; }
conditional_block
stats.js
/*** * Copyright (c) 2016 - 2021 Alex Grant (@localnerve), LocalNerve LLC * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms. */ /*eslint no-console:0 */ import { promises as fs } from 'fs'; import merge from 'lodash/merge'; import AsyncLock from 'async-lock'; const lock = new ...
(settings, statsFile) { return new StatsPlugin(settings, statsFile); }
statsPluginFactory
identifier_name
stats.js
/*** * Copyright (c) 2016 - 2021 Alex Grant (@localnerve), LocalNerve LLC * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms. */ /*eslint no-console:0 */ import { promises as fs } from 'fs'; import merge from 'lodash/merge'; import AsyncLock from 'async-lock'; const lock = new ...
/** * Add the options for consumption by statsPlugin. * * @param {Object} settings - The project settings. */ function statsPluginOptions (settings) { return { assetsJson: settings.src.assetsJson, /* eslint-disable no-useless-escape */ CHUNK_REGEX: /^([A-Za-z0-9_\-]+)\..*/ /* eslint-enable no-usel...
random_line_split
mesos-gtest-runner.py
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "...
def run_test(opts): """ Perform an actual run of the test executable. Expects a list of parameters giving the number of the current shard, the total number of shards, and the executable to run. """ shard, nshards, executable = opts signal.signal(signal.SIGINT, signal.SIG_IGN) env =...
"""Decorate a string with a number of color codes.""" colors = ''.join(color_codes) return '{begin}{string}{end}'.format( begin=colors if sys.stdout.isatty() else '', string=string, end=Bcolors.ENDC if sys.stdout.isatty() else '')
identifier_body
mesos-gtest-runner.py
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "...
# Count the number of failed shards and print results from # failed shards. # # NOTE: The `RESULTS` array stores the result for each # `run_test` invocation returning a tuple (success, output). NFAILED = len([success for success, __ in RESULTS if not success]) ...
RESULTS.extend( POOL.map_async( run_test, options_gen( EXECUTABLE, OPTIONS.sequential, 1)).get( timeout=sys.maxint))
conditional_block
mesos-gtest-runner.py
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "...
(opts): """ Perform an actual run of the test executable. Expects a list of parameters giving the number of the current shard, the total number of shards, and the executable to run. """ shard, nshards, executable = opts signal.signal(signal.SIGINT, signal.SIG_IGN) env = os.environ.cop...
run_test
identifier_name
mesos-gtest-runner.py
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "...
timeout=sys.maxint)) # Now run sequential tests. if OPTIONS.sequential: RESULTS.extend( POOL.map_async( run_test, options_gen( EXECUTABLE, OPTIONS.sequential, 1)).get( ...
EXECUTABLE, OPTIONS.parallel, OPTIONS.jobs)).get(
random_line_split
player-container.js
/**Parent: ptravels * A container for the react audio player */ import React, { Component } from 'react'; import ReactPlayer from 'react-player'; export default class PlayerContainer extends React.Component { constructor(){ super(); this.state = { url: "", played: 0, ...
load = url => { this.setState({url: url, played: 0, playing: true}); } onSeekChange = e => { this.setState({ played: parseFloat(e.target.value) }); } onSeekMouseDown = e => { this.setState({ seeking: true }); } onSeekMouseUp = e => { this.setState({ seeki...
{ this.load(url.mp3Url); }
identifier_body
player-container.js
/**Parent: ptravels * A container for the react audio player */ import React, { Component } from 'react'; import ReactPlayer from 'react-player'; export default class PlayerContainer extends React.Component { constructor(){ super(); this.state = { url: "", played: 0, ...
} playPause = () => { console.log(this.state.playing) //this.setState({ playing: !this.state.playing }) } stop = () => { this.setState({ url: null, playing: false, played: 0 }) } ref = player => { this.player = player; } render() { let url = t...
{ this.setState(state); }
conditional_block
player-container.js
/**Parent: ptravels * A container for the react audio player */ import React, { Component } from 'react'; import ReactPlayer from 'react-player'; export default class PlayerContainer extends React.Component { constructor(){ super(); this.state = { url: "",
} } componentWillReceiveProps(url) { this.load(url.mp3Url); } load = url => { this.setState({url: url, played: 0, playing: true}); } onSeekChange = e => { this.setState({ played: parseFloat(e.target.value) }); } onSeekMouseDown = e => { this.se...
played: 0, playing: false
random_line_split
player-container.js
/**Parent: ptravels * A container for the react audio player */ import React, { Component } from 'react'; import ReactPlayer from 'react-player'; export default class
extends React.Component { constructor(){ super(); this.state = { url: "", played: 0, playing: false } } componentWillReceiveProps(url) { this.load(url.mp3Url); } load = url => { this.setState({url: url, played: 0, playing...
PlayerContainer
identifier_name
Errors.tsx
import Link from "@material-ui/core/Link"; import Typography from "@material-ui/core/Typography"; import React from "react"; import { Link as RouterLink } from "react-router-dom"; import { ClusterFeatureComponent, NodeFeatureComponent, WorkerFeatureComponent } from "./types"; export const makeClusterErrors = (er...
} return totalErrorCount === 0 ? ( <Typography color="textSecondary" component="span" variant="inherit"> No errors </Typography> ) : ( <React.Fragment> {totalErrorCount.toLocaleString()}{" "} {totalErrorCount === 1 ? "error" : "errors"} </React.Fragment> ); }; export const ma...
{ totalErrorCount += errorCounts[node.ip].total; }
conditional_block
Errors.tsx
import Link from "@material-ui/core/Link"; import Typography from "@material-ui/core/Typography"; import React from "react"; import { Link as RouterLink } from "react-router-dom"; import { ClusterFeatureComponent, NodeFeatureComponent, WorkerFeatureComponent } from "./types";
[pid: string]: number; }; total: number; }; }): ClusterFeatureComponent => ({ nodes }) => { let totalErrorCount = 0; for (const node of nodes) { if (node.ip in errorCounts) { totalErrorCount += errorCounts[node.ip].total; } } return totalErrorCount === 0 ? ( <Typography color="...
export const makeClusterErrors = (errorCounts: { [ip: string]: { perWorker: {
random_line_split
0009_auto_20191023_0906.py
# Generated by Django 2.2.6 on 2019-10-23 09:06
class Migration(migrations.Migration): dependencies = [ ('scanners', '0008_auto_20191021_1718'), ] operations = [ migrations.CreateModel( name='ScannerMatch', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, ve...
from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import olympia.amo.models
random_line_split
0009_auto_20191023_0906.py
# Generated by Django 2.2.6 on 2019-10-23 09:06 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import olympia.amo.models class
(migrations.Migration): dependencies = [ ('scanners', '0008_auto_20191021_1718'), ] operations = [ migrations.CreateModel( name='ScannerMatch', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'))...
Migration
identifier_name
0009_auto_20191023_0906.py
# Generated by Django 2.2.6 on 2019-10-23 09:06 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import olympia.amo.models class Migration(migrations.Migration):
), migrations.AddField( model_name='scannerresult', name='matched_rules', field=models.ManyToManyField(through='scanners.ScannerMatch', to='scanners.ScannerRule'), ), ]
dependencies = [ ('scanners', '0008_auto_20191021_1718'), ] operations = [ migrations.CreateModel( name='ScannerMatch', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created',...
identifier_body
worker.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
<Message> { pub work_type: WorkType<Message>, pub token: usize, pub handler_id: HandlerId, pub handler: Arc<IoHandler<Message>>, } /// An IO worker thread /// Sorts them ready for blockchain insertion. pub struct Worker { thread: Option<JoinHandle<()>>, wait: Arc<Condvar>, deleting: Arc<AtomicBool>, wait_mutex...
Work
identifier_name
worker.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
WorkType::Message(message) => { work.handler.message(&IoContext::new(channel, work.handler_id), &message); } } } } impl Drop for Worker { fn drop(&mut self) { trace!(target: "shutdown", "[IoWorker] Closing..."); let _ = self.wait_mutex.lock(); self.deleting.store(true, AtomicOrdering::Release); ...
{ work.handler.timeout(&IoContext::new(channel, work.handler_id), work.token); }
conditional_block
worker.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
} WorkType::Hup => { work.handler.stream_hup(&IoContext::new(channel, work.handler_id), work.token); } WorkType::Timeout => { work.handler.timeout(&IoContext::new(channel, work.handler_id), work.token); } WorkType::Message(message) => { work.handler.message(&IoContext::new(channel, work.ha...
} WorkType::Writable => { work.handler.stream_writable(&IoContext::new(channel, work.handler_id), work.token);
random_line_split
iconmap.js
require('css/iconmap.css'); module.exports = { componentIcons: { hypothesis: 'fa fa-lightbulb-o',
procedure: 'fa fa-cogs', instrumentation: 'fa fa-flask', data: 'fa fa-database', analysis: 'fa fa-bar-chart', communication: 'fa fa-comment', other: 'fa fa-th-large', '': 'fa fa-circle-o-notch' }, projectIcons: { collection: 'fa fa-cubes', ...
'methods and measures': 'fa fa-pencil',
random_line_split
vec-matching-autoslice.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x = [1, 2, 3]; match x { [2, _, _] => panic!(), [1, a, b] => { assert_eq!([a, b], [2, 3]); } [_, _, _] => panic!(), } let y = ([(1, true), (2, false)], 0.5f64); match y { ([(1, a), (b, false)], _) => { assert_eq!(a, true); ...
main
identifier_name
vec-matching-autoslice.rs
// Copyright 2014 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 ...
pub fn main() { let x = [1, 2, 3]; match x { [2, _, _] => panic!(), [1, a, b] => { assert_eq!([a, b], [2, 3]); } [_, _, _] => panic!(), } let y = ([(1, true), (2, false)], 0.5f64); match y { ([(1, a), (b, false)], _) => { assert_eq!(a,...
random_line_split
vec-matching-autoslice.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = [1, 2, 3]; match x { [2, _, _] => panic!(), [1, a, b] => { assert_eq!([a, b], [2, 3]); } [_, _, _] => panic!(), } let y = ([(1, true), (2, false)], 0.5f64); match y { ([(1, a), (b, false)], _) => { assert_eq!(a, true); ...
identifier_body
ArtworkSidebar.ts
import { ArtworkSidebar_Test_QueryRawResponse } from "v2/__generated__/ArtworkSidebar_Test_Query.graphql" export const ArtworkSidebarFixture: ArtworkSidebar_Test_QueryRawResponse["artwork"] = { id: "josef-albers-homage-to-the-square-85", internalID: "sdf222", is_biddable: false, is_in_auction: false, is_for_...
dimensions: { in: "15 × 20 in", cm: "38.1 × 50.8 cm", }, edition_of: "Edition of 1000", }, ], dimensions: { in: "15 × 20 in", cm: "38.1 × 50.8 cm", }, edition_of: "Edition of 1000", attribution_class: { id: "asdlfkjsdf", short_description: "This is an edit...
__typename: "ArtworkEditionSet", sale_message: "For sale",
random_line_split
hw5_tests.py
# -*- coding: utf8 -*- u""" Тесты на ДЗ#5. """ __author__ = "wowkalucky" __email__ = "wowkalucky@gmail.com" __date__ = "2014-11-17" import datetime from hw5_solution1 import Person def tests_for
"""Тесты задачи 1""" petroff = Person("Petrov", "Petro", "1952-01-02") ivanoff = Person("Ivanov", "Ivan", "2000-10-20") sydoroff = Person("Sidorov", "Semen", "1980-12-31", "Senya") assert "first_name" in dir(petroff) assert "get_fullname" in dir(ivanoff) assert "nickname" not in dir(petroff) ...
_hw5_solution1(): u
identifier_name
hw5_tests.py
# -*- coding: utf8 -*- u""" Тесты на ДЗ#5. """ __author__ = "wowkalucky" __email__ = "wowkalucky@gmail.com" __date__ = "2014-11-17" import datetime from hw5_solution1 import Person def tests_for_hw5_solution1(): u"""Тесты
задачи 1""" petroff = Person("Petrov", "Petro", "1952-01-02") ivanoff = Person("Ivanov", "Ivan", "2000-10-20") sydoroff = Person("Sidorov", "Semen", "1980-12-31", "Senya") assert "first_name" in dir(petroff) assert "get_fullname" in dir(ivanoff) assert "nickname" not in dir(petroff) assert...
identifier_body
hw5_tests.py
# -*- coding: utf8 -*- u""" Тесты на ДЗ#5. """ __author__ = "wowkalucky" __email__ = "wowkalucky@gmail.com" __date__ = "2014-11-17" import datetime from hw5_solution1 import Person def tests_for_hw5_solution1(): u"""Тесты задачи 1""" petroff = Person("Petrov", "Petro", "1952-01-02") ivanoff = Person(...
assert petroff.surname == "Petrov" assert petroff.first_name == "Petro" assert petroff.get_fullname() == "Petrov Petro" assert sydoroff.nickname == "Senya" assert petroff.birth_date == datetime.date(1952, 01, 02) assert isinstance(petroff.birth_date, datetime.date) assert petroff.get_age() ...
assert "get_fullname" in dir(ivanoff) assert "nickname" not in dir(petroff) assert "nickname" in dir(sydoroff)
random_line_split
videos.ts
import VideoRecorder from './recorder'; import BrowserJob from '../runner/browser-job'; import { Dictionary } from '../configuration/interfaces'; import WarningLog from '../notifications/warning-log'; import { VideoOptions, TestVideoInfo, TestRunVideoInfo, TestRunVideoSavedEventArgs, } from './interface...
} }
{ const testId: string = testRun.test.id; let testVideo: TestVideoInfo = this.testVideoInfos[testId]; if (!testVideo) { testVideo = { recordings: [] }; this.testVideoInfos[testId] = testVideo; } const recording: TestRunVideoInfo = { ...
identifier_body
videos.ts
import VideoRecorder from './recorder'; import BrowserJob from '../runner/browser-job'; import { Dictionary } from '../configuration/interfaces'; import WarningLog from '../notifications/warning-log'; import { VideoOptions, TestVideoInfo, TestRunVideoInfo, TestRunVideoSavedEventArgs, } from './interface...
const recording: TestRunVideoInfo = { testRunId: testRun.id, videoPath, singleFile, }; if (timecodes) recording.timecodes = timecodes; testVideo.recordings.push(recording); } }
{ testVideo = { recordings: [] }; this.testVideoInfos[testId] = testVideo; }
conditional_block
videos.ts
import VideoRecorder from './recorder'; import BrowserJob from '../runner/browser-job'; import { Dictionary } from '../configuration/interfaces'; import WarningLog from '../notifications/warning-log'; import { VideoOptions, TestVideoInfo, TestRunVideoInfo, TestRunVideoSavedEventArgs, } from './interface...
( browserJobs: BrowserJob[], { videoPath, videoOptions, videoEncodingOptions }: VideoOptions, warningLog: WarningLog, timeStamp: moment.Moment) { const options = { timeStamp: timeStamp, ...videoOptions }; this.testVideoInfos = {}; browserJobs.forEach(browserJob => { const ...
constructor
identifier_name
videos.ts
import VideoRecorder from './recorder'; import BrowserJob from '../runner/browser-job'; import { Dictionary } from '../configuration/interfaces'; import WarningLog from '../notifications/warning-log';
TestVideoInfo, TestRunVideoInfo, TestRunVideoSavedEventArgs, } from './interfaces'; import moment from 'moment'; export default class Videos { public testVideoInfos: Dictionary<TestVideoInfo>; public constructor ( browserJobs: BrowserJob[], { videoPath, videoOptions, videoEncodingOptions ...
import { VideoOptions,
random_line_split
lib.rs
//! Concurrent work-stealing deques. //! //! These data structures are most commonly used in work-stealing schedulers. The typical setup //! involves a number of threads, each having its own FIFO or LIFO queue (*worker*). There is also //! one global FIFO queue (*injector*) and a list of references to *worker* queues t...
//! ) -> Option<T> { //! // Pop a task from the local queue, if not empty. //! local.pop().or_else(|| { //! // Otherwise, we need to look for a task elsewhere. //! iter::repeat_with(|| { //! // Try stealing a batch of tasks from the global queue. //! global.steal_batch_an...
random_line_split
breakdown.styles.ts
import { css, SerializedStyles } from '@emotion/react'; import styled from '@emotion/styled'; import { rem } from 'polished'; import { Label as LabelBase } from '~client/components/fund-weights/styles'; import { breakpoint } from '~client/styled/mixins'; import { Button, Flex, FlexColumn } from '~client/styled/shared'...
(level: LabelBaseProps['level']): SerializedStyles { switch (level) { case 2: return css` color: ${colors.dark.light}; `; case 1: return css` font-size: ${rem(14)}; `; case 0: default: return css` font-size: ${rem(16)}; font-weight: bold; ...
labelLevelStyles
identifier_name
breakdown.styles.ts
import { css, SerializedStyles } from '@emotion/react'; import styled from '@emotion/styled'; import { rem } from 'polished'; import { Label as LabelBase } from '~client/components/fund-weights/styles'; import { breakpoint } from '~client/styled/mixins'; import { Button, Flex, FlexColumn } from '~client/styled/shared'...
text-align: center; `; export type LabelBaseProps = { level: 0 | 1 | 2 }; function labelLevelStyles(level: LabelBaseProps['level']): SerializedStyles { switch (level) { case 2: return css` color: ${colors.dark.light}; `; case 1: return css` font-size: ${rem(14)}; `;...
export const Title = styled(H3)` flex: 1; font-size: ${rem(14)}; margin: 0;
random_line_split
breakdown.styles.ts
import { css, SerializedStyles } from '@emotion/react'; import styled from '@emotion/styled'; import { rem } from 'polished'; import { Label as LabelBase } from '~client/components/fund-weights/styles'; import { breakpoint } from '~client/styled/mixins'; import { Button, Flex, FlexColumn } from '~client/styled/shared'...
export const Label = styled(LabelBase)<LabelBaseProps>( ({ level = 0 }) => css` color: ${colors.black}; font-size: ${rem(11)}; left: 0; line-height: ${rem(16)}; top: 0; transform: none; width: 100%; ${labelLevelStyles(level)} `, );
{ switch (level) { case 2: return css` color: ${colors.dark.light}; `; case 1: return css` font-size: ${rem(14)}; `; case 0: default: return css` font-size: ${rem(16)}; font-weight: bold; z-index: 3; `; } }
identifier_body
scalar.rs
// mrusty. mruby safe bindings for Rust // Copyright (C) 2016 Dragoș Tiselice // // 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 mrusty::MrubyImpl; use super::...
{ pub value: f32 } impl Scalar { pub fn new(value: f32) -> Scalar { Scalar { value: value } } pub fn set_value(&mut self, value: f32) { self.value = value; } } mrusty_class!(Scalar, { def!("initialize", |v: f64| { Scalar::new(v as f32) }); ...
calar
identifier_name