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
aggregator_test.py
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions ...
unittest.main()
conditional_block
aggregator_test.py
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions ...
if __name__ == '__main__': unittest.main()
random_line_split
aggregator_test.py
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions ...
(unittest.TestCase): """Unit tests for misc. aggregator functions.""" def testFixAggregationDict(self): # Simplest case. result = aggregator._aggr_weighted_mean((1.0, 1.0), (1, 1)) self.assertAlmostEqual(result, 1.0, places=7) # Simple non-uniform case. result = aggregator._aggr_weighted_mean((...
AggregatorTest
identifier_name
primitive.rs
// Copyright 2012-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-MI...
let span = variant.span; // expr for `$n == $variant as $name` let path = cx.path(span, vec![substr.type_ident, variant.node.name]); let variant = cx.expr_path(path); let ty = cx.ty_ident(span, cx.i...
{ cx.span_err(trait_span, "`FromPrimitive` cannot be derived for \ enum variants with arguments"); return cx.expr_fail(trait_span, Inter...
conditional_block
primitive.rs
// Copyright 2012-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-MI...
let inline = cx.meta_word(span, InternedString::new("inline")); let attrs = vec!(cx.attribute(span, inline)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path_std!(cx, core::num::FromPrimitive), additional_bounds: Vec::new(), generics: Lifetim...
{
random_line_split
primitive.rs
// Copyright 2012-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-MI...
attributes: attrs.clone(), combine_substructure: combine_substructure(box |c, s, sub| { cs_from("i64", c, s, sub) }), }, MethodDef { name: "from_u64", generics: LifetimeBounds::empty(), ...
{ let inline = cx.meta_word(span, InternedString::new("inline")); let attrs = vec!(cx.attribute(span, inline)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path_std!(cx, core::num::FromPrimitive), additional_bounds: Vec::new(), generics: Lifet...
identifier_body
primitive.rs
// Copyright 2012-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-MI...
<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: F) where F: FnOnce(P<Item>), { let inline = cx.meta_word(span, InternedString...
expand_deriving_from_primitive
identifier_name
string.rs
extern crate llvm_sys; use codegen::llvm::core::{Builder, Context, Module, Type}; use self::llvm_sys::LLVMIntPredicate; // TODO: Remove // TODO: Change to put string def in module if not already there // use std.string.String pub fn string_type(context: &Context) -> Type { let field_types = vec![ context....
context.struct_type(field_types) } // TODO: Move out of the string file: pub fn print_function_definition(builder: &Builder, context: &Context, module: &Module) { // Types let void = context.void_type(); let i32_type = context.i32_type(); let i64_type = context.i64_type(); let i32_ptr_type = i3...
];
random_line_split
string.rs
extern crate llvm_sys; use codegen::llvm::core::{Builder, Context, Module, Type}; use self::llvm_sys::LLVMIntPredicate; // TODO: Remove // TODO: Change to put string def in module if not already there // use std.string.String pub fn string_type(context: &Context) -> Type
// TODO: Move out of the string file: pub fn print_function_definition(builder: &Builder, context: &Context, module: &Module) { // Types let void = context.void_type(); let i32_type = context.i32_type(); let i64_type = context.i64_type(); let i32_ptr_type = i32_type.ptr_type(0); let string_typ...
{ let field_types = vec![ context.i8_type().ptr_type(0), context.i64_type(), // len context.i64_type(), // cap ]; context.struct_type(field_types) }
identifier_body
string.rs
extern crate llvm_sys; use codegen::llvm::core::{Builder, Context, Module, Type}; use self::llvm_sys::LLVMIntPredicate; // TODO: Remove // TODO: Change to put string def in module if not already there // use std.string.String pub fn string_type(context: &Context) -> Type { let field_types = vec![ context....
(builder: &Builder, context: &Context, module: &Module) { // Types let void = context.void_type(); let i32_type = context.i32_type(); let i64_type = context.i64_type(); let i32_ptr_type = i32_type.ptr_type(0); let string_type_ptr = string_type(context).ptr_type(0); let mut args = vec![strin...
print_function_definition
identifier_name
RecentFile.tsx
import React from 'react'; import styled from '../../styles/styled-components'; const Wrapper = styled.div` border-radius: 8px; width: 256px; margin: 16px; `; const VideoThumbnailWrapper = styled.div` background-color: ${props => props.theme.pallete.gray[4]}; background-position: center; background-repeat...
export default RecentFile;
random_line_split
atkinson_wald_2007.py
# coding: utf-8 # The Hazard Library # Copyright (C) 2012 GEM Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later...
REQUIRES_RUPTURE_PARAMETERS = set(('mag',)) REQUIRES_DISTANCES = set(('rrup', )) def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result v...
""" Implements IPE developed by Atkinson and Wald (2007) California, USA MS! """ DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.ACTIVE_SHALLOW_CRUST DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([ MMI ]) DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.AVERAGE_HORIZONTAL DEF...
identifier_body
atkinson_wald_2007.py
# coding: utf-8 # The Hazard Library # Copyright (C) 2012 GEM Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later...
(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ h = 14.0 R = np.sqrt(dists.rrup**2 + h**2) B = np.zeros_like(dists.rrup) ...
get_mean_and_stddevs
identifier_name
atkinson_wald_2007.py
# coding: utf-8
# Copyright (C) 2012 GEM Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distrib...
# The Hazard Library
random_line_split
card_view.test.ts
/** * 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 * "License"); you...
cy.get('.ant-card .card-actions') .first() .find("[data-test='favorite-selected']") .should('not.exist'); }); it('should sort correctly', () => { // sort alphabetical cy.get('.Select__control').last().should('be.visible'); cy.get('.Select__control').last().click({ force: true }); ...
.find("[data-test='favorite-unselected']") .should('exist');
random_line_split
logger.rs
use log::{Log, LogRecord, LogLevel, LogMetadata, SetLoggerError}; pub fn setup(level: LogLevel) -> Result<(), SetLoggerError>{ use log; log::set_logger(|filter|{ filter.set(level.to_log_level_filter()); Box::new(Logger(level)) }) } pub fn setup_default() -> Result<(), SetLoggerError>
pub struct Logger(LogLevel); impl Log for Logger{ fn enabled(&self, metadata: &LogMetadata) -> bool{ metadata.level() <= self.0 } fn log(&self, record: &LogRecord){ if self.enabled(record.metadata()){ let location = record.location(); // Get the filename from the location use std::path::Path; let ...
{ setup(LogLevel::Debug) }
identifier_body
logger.rs
use log::{Log, LogRecord, LogLevel, LogMetadata, SetLoggerError}; pub fn setup(level: LogLevel) -> Result<(), SetLoggerError>{ use log; log::set_logger(|filter|{ filter.set(level.to_log_level_filter()); Box::new(Logger(level)) }) } pub fn setup_default() -> Result<(), SetLoggerError>{ setup(LogLevel::Debug) }...
(LogLevel); impl Log for Logger{ fn enabled(&self, metadata: &LogMetadata) -> bool{ metadata.level() <= self.0 } fn log(&self, record: &LogRecord){ if self.enabled(record.metadata()){ let location = record.location(); // Get the filename from the location use std::path::Path; let filename = Path::ne...
Logger
identifier_name
logger.rs
use log::{Log, LogRecord, LogLevel, LogMetadata, SetLoggerError}; pub fn setup(level: LogLevel) -> Result<(), SetLoggerError>{ use log; log::set_logger(|filter|{ filter.set(level.to_log_level_filter()); Box::new(Logger(level)) }) } pub fn setup_default() -> Result<(), SetLoggerError>{ setup(LogLevel::Debug) }...
} } }
random_line_split
logger.rs
use log::{Log, LogRecord, LogLevel, LogMetadata, SetLoggerError}; pub fn setup(level: LogLevel) -> Result<(), SetLoggerError>{ use log; log::set_logger(|filter|{ filter.set(level.to_log_level_filter()); Box::new(Logger(level)) }) } pub fn setup_default() -> Result<(), SetLoggerError>{ setup(LogLevel::Debug) }...
} }
{ let location = record.location(); // Get the filename from the location use std::path::Path; let filename = Path::new(record.location().file()).file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or(String::from("Unknown location")); println!("[{:?}][{2}:{3}][{1}] {4}", record.level(), locat...
conditional_block
navigator.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::NavigatorBinding; use dom::bindings::codegen::Bindings::NavigatorBinding::Na...
() -> Navigator { Navigator { reflector_: Reflector::new(), bluetooth: Default::default(), plugins: Default::default(), mime_types: Default::default(), service_worker: Default::default(), vr: Default::default(), permissions: Def...
new_inherited
identifier_name
navigator.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::NavigatorBinding; use dom::bindings::codegen::Bindings::NavigatorBinding::Na...
} // https://html.spec.whatwg.org/multipage/#dom-navigator-plugins fn Plugins(&self) -> Root<PluginArray> { self.plugins.or_init(|| PluginArray::new(&self.global())) } // https://html.spec.whatwg.org/multipage/#dom-navigator-mimetypes fn MimeTypes(&self) -> Root<MimeTypeArray> { ...
random_line_split
navigator.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::NavigatorBinding; use dom::bindings::codegen::Bindings::NavigatorBinding::Na...
// https://html.spec.whatwg.org/multipage/#dom-navigator-taintenabled fn TaintEnabled(&self) -> bool { navigatorinfo::TaintEnabled() } // https://html.spec.whatwg.org/multipage/#dom-navigator-appname fn AppName(&self) -> DOMString { navigatorinfo::AppName() } // https://h...
{ navigatorinfo::Product() }
identifier_body
borrowck-preserve-box-in-field.rs
// xfail-pretty // 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 //...
{ let mut x = @F {f: ~3}; borrow(x.f, |b_x| { assert_eq!(*b_x, 3); assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x))); x = @F {f: ~4}; info!("ptr::to_unsafe_ptr(*b_x) = {:x}", ptr::to_unsafe_ptr(&(*b_x)) as uint); assert_eq!(*b_x, 3); ...
identifier_body
borrowck-preserve-box-in-field.rs
// xfail-pretty // 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 //...
() { let mut x = @F {f: ~3}; borrow(x.f, |b_x| { assert_eq!(*b_x, 3); assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x))); x = @F {f: ~4}; info!("ptr::to_unsafe_ptr(*b_x) = {:x}", ptr::to_unsafe_ptr(&(*b_x)) as uint); assert_eq!(*b_x, 3); ...
main
identifier_name
borrowck-preserve-box-in-field.rs
// xfail-pretty // 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 //...
f(x); let after = *x; assert_eq!(before, after); } struct F { f: ~int } pub fn main() { let mut x = @F {f: ~3}; borrow(x.f, |b_x| { assert_eq!(*b_x, 3); assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x))); x = @F {f: ~4}; info!("ptr::to_unsafe_ptr(...
fn borrow(x: &int, f: |x: &int|) { let before = *x;
random_line_split
label_column.js
goog.provide('recoil.ui.widgets.table.LabelColumn'); goog.require('recoil.frp.Behaviour'); goog.require('recoil.frp.struct'); goog.require('recoil.ui.BoolWithExplanation'); goog.require('recoil.ui.widgets.LabelWidget'); goog.require('recoil.ui.widgets.table.Column'); /** * @implements {recoil.ui.widgets.table.Colum...
*/ recoil.ui.widgets.table.LabelColumn.defaultWidgetFactory = recoil.ui.widgets.table.LabelColumn.defaultWidgetFactory_; /** * @return {recoil.structs.table.ColumnKey} */ recoil.ui.widgets.table.LabelColumn.prototype.getKey = function() { return this.key_; };
* @param {!recoil.ui.WidgetScope} scope * @param {!recoil.frp.Behaviour<recoil.structs.table.TableCell>} cellB * @return {!recoil.ui.Widget}
random_line_split
WintersChill.js
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import EnemyInstances from 'parser/shared/modules/EnemyInstances'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import Sta...
else { this.error(`Unexpected number of Ice Lances inside Winter's Chill -> ${this.iceLanceHits}`); } if (this.hardcastHits === 0) { this.missedHardcasts += 1; } else if (this.hardcastHits === 1) { this.singleHardcasts += 1; } else { this.error(`Unexpected number of Frostbolt h...
{ this.doubleIceLanceCasts += 1; }
conditional_block
WintersChill.js
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import EnemyInstances from 'parser/shared/modules/EnemyInstances'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import Sta...
() { return ( <Statistic position={STATISTIC_ORDER.CORE(30)} size="flexible" tooltip={( <> Every Brain Freeze Flurry should be preceded by a Frostbolt, Glacial Spike, or Ebonbolt and followed by an Ice Lance, so that both the preceding and following spells benefit...
statistic
identifier_name
WintersChill.js
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import EnemyInstances from 'parser/shared/modules/EnemyInstances'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import Sta...
get iceLanceUtil() { return 1 - this.iceLanceMissedPercent; } get iceLanceUtilSuggestionThresholds() { return { actual: this.iceLanceUtil, isLessThan: { minor: 0.95, average: 0.85, major: 0.75, }, style: 'percentage', }; } get hardcastMissedPercen...
return (this.missedIceLanceCasts / this.totalProcs) || 0; }
random_line_split
WintersChill.js
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import EnemyInstances from 'parser/shared/modules/EnemyInstances'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import Sta...
statistic() { return ( <Statistic position={STATISTIC_ORDER.CORE(30)} size="flexible" tooltip={( <> Every Brain Freeze Flurry should be preceded by a Frostbolt, Glacial Spike, or Ebonbolt and followed by an Ice Lance, so that both the preceding and following s...
{ when(this.iceLanceUtilSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>You failed to Ice Lance into <SpellLink id={SPELLS.WINTERS_CHILL.id} /> {this.missedIceLanceCasts} times ({formatPercentage(this.iceLanceMissedPercent)}%). Make sure you cast <SpellLink id...
identifier_body
NewRoomInfo.js
import { Template } from 'meteor/templating'; import { Academy } from '/imports/api/databasedriver.js'; import { Challenges } from '/imports/api/databasedriver.js'; import { Rooms } from '/imports/api/databasedriver.js'; import { Badges } from '/imports/api/databasedriver.js'; import { ROOMS_ACTIVE_ELEMENT_KEY } from ...
(){ var badges = Badges.find({}).fetch(); return badges; }, teamBadge() { let roomType = "Team"; let roomBadges = Badges.find({'type': roomType }).fetch(); return roomBadges; } }); const TABLE_ROOMS_ACTIVE_TEMPLATE_NAME = "TableRoomInfo"; const NEW_ROOM_ACTIVE_TEMPLA...
badges
identifier_name
NewRoomInfo.js
import { Template } from 'meteor/templating'; import { Academy } from '/imports/api/databasedriver.js'; import { Challenges } from '/imports/api/databasedriver.js'; import { Rooms } from '/imports/api/databasedriver.js'; import { Badges } from '/imports/api/databasedriver.js'; import { ROOMS_ACTIVE_ELEMENT_KEY } from ...
let data = {}; let roomName = $("#roomName").val(); let roomDecision = $("#roomDecision").val(); let roomDescription = $("#roomDescription").val(); let roomBadge = $("#roomBadge").val(); data = { name: roomName, dailyDecision: roomDecision, description: roomDescripti...
event.preventDefault();
random_line_split
NewRoomInfo.js
import { Template } from 'meteor/templating'; import { Academy } from '/imports/api/databasedriver.js'; import { Challenges } from '/imports/api/databasedriver.js'; import { Rooms } from '/imports/api/databasedriver.js'; import { Badges } from '/imports/api/databasedriver.js'; import { ROOMS_ACTIVE_ELEMENT_KEY } from ...
//Modal.show('roomsInsertModal', this); Meteor.call("insertRoom", data, function(error, result) { if (error) { alert(error); } }); $("#addRoom")[0].reset(); Session.set(ROOMS_ACTIVE_ELEMENT_KEY, TABLE_ROOMS_ACTIVE_TEMPLATE_NAME); } , 'click #nopRoom' (event){ event....
{ event.preventDefault(); let data = {}; let roomName = $("#roomName").val(); let roomDecision = $("#roomDecision").val(); let roomDescription = $("#roomDescription").val(); let roomBadge = $("#roomBadge").val(); data = { name: roomName, dailyDecision: roomDecision, ...
identifier_body
NewRoomInfo.js
import { Template } from 'meteor/templating'; import { Academy } from '/imports/api/databasedriver.js'; import { Challenges } from '/imports/api/databasedriver.js'; import { Rooms } from '/imports/api/databasedriver.js'; import { Badges } from '/imports/api/databasedriver.js'; import { ROOMS_ACTIVE_ELEMENT_KEY } from ...
}); $("#addRoom")[0].reset(); Session.set(ROOMS_ACTIVE_ELEMENT_KEY, TABLE_ROOMS_ACTIVE_TEMPLATE_NAME); }, 'click #nopRoom' (event){ event.preventDefault(); Session.set(ROOMS_ACTIVE_ELEMENT_KEY, TABLE_ROOMS_ACTIVE_TEMPLATE_NAME); } });
{ alert(error); }
conditional_block
recipe-141934.py
def xmerge(*ln): """ Iterator version of merge. Assuming l1, l2, l3...ln sorted sequences, return an iterator that yield all the items of l1, l2, l3...ln in ascending order. Input values doesn't need to be lists: any iterable sequence can be used. """ pqueue = [] for i in map(iter, ...
if pqueue: d,f = pqueue[0] yield d try: while 1: yield f() except StopIteration:pass def merge(*ln): """ Merge several sorted sequences into a sorted list. Assuming l1, l2, l3...ln sorted sequences, return a list that contain all the items ...
d,f = pqueue.pop() yield d try: # Insort in reverse order to avoid pop(0) lo, hi, d = 0, X, f() while lo < hi: mid = (lo+hi)//2 if d > pqueue[mid][0]: hi = mid else: lo = mid+1 pqueue.insert(lo, (d,f...
conditional_block
recipe-141934.py
def xmerge(*ln): """ Iterator version of merge. Assuming l1, l2, l3...ln sorted sequences, return an iterator that yield all the items of l1, l2, l3...ln in ascending order. Input values doesn't need to be lists: any iterable sequence can be used. """ pqueue = [] for i in map(iter, ...
yield d try: # Insort in reverse order to avoid pop(0) lo, hi, d = 0, X, f() while lo < hi: mid = (lo+hi)//2 if d > pqueue[mid][0]: hi = mid else: lo = mid+1 pqueue.insert(lo, (d,f)) except ...
while X: d,f = pqueue.pop()
random_line_split
recipe-141934.py
def xmerge(*ln): """ Iterator version of merge. Assuming l1, l2, l3...ln sorted sequences, return an iterator that yield all the items of l1, l2, l3...ln in ascending order. Input values doesn't need to be lists: any iterable sequence can be used. """ pqueue = [] for i in map(iter, ...
""" Merge several sorted sequences into a sorted list. Assuming l1, l2, l3...ln sorted sequences, return a list that contain all the items of l1, l2, l3...ln in ascending order. Input values doesn't need to be lists: any iterable sequence can be used. """ return list(xmerge(*ln))
identifier_body
recipe-141934.py
def xmerge(*ln): """ Iterator version of merge. Assuming l1, l2, l3...ln sorted sequences, return an iterator that yield all the items of l1, l2, l3...ln in ascending order. Input values doesn't need to be lists: any iterable sequence can be used. """ pqueue = [] for i in map(iter, ...
(*ln): """ Merge several sorted sequences into a sorted list. Assuming l1, l2, l3...ln sorted sequences, return a list that contain all the items of l1, l2, l3...ln in ascending order. Input values doesn't need to be lists: any iterable sequence can be used. """ return list(xmerge(*l...
merge
identifier_name
VFB2PhisXML.py
(a, b): AB = (a, b) pa = phisSchema.PercentArray() pa.extend(AB) return pa def gen_GenotypeComponent(gf_symbol=False, gf_id=False, gene_symbol=False, gene_id=False, gf_ensembl_id=False): ## How to specify channel. Use defaults? ### """Generate a phisSchema.GenotypeComponent object. All ar...
_gen_PercentArray
identifier_name
VFB2PhisXML.py
(a, b) pa = phisSchema.PercentArray() pa.extend(AB) return pa def gen_GenotypeComponent(gf_symbol=False, gf_id=False, gene_symbol=False, gene_id=False, gf_ensembl_id=False): ## How to specify channel. Use defaults? ### """Generate a phisSchema.GenotypeComponent object. All args are strings. ...
def set_image_and_sample_type(self, wt_or_mut, exp_anat_phen): self.image.image_description.sample_type = "wild type" ita = phisSchema.ImageTypeArray() ita.append("expression") # Use Expression if depicts expression pattern - otherwise use anatomy/phenotype. Don't this there is a...
"""x, y and z are dimensions in pixels. Z is optional (default 0)""" dimensions = phisSchema.Dimensions() dimensions.image_width = x dimensions.image_height = y dimensions.image_depth = z self.image_description.image_dimensions = dimensions
identifier_body
VFB2PhisXML.py
return coord def _gen_PercentArray(a, b): AB = (a, b) pa = phisSchema.PercentArray() pa.extend(AB) return pa def gen_GenotypeComponent(gf_symbol=False, gf_id=False, gene_symbol=False, gene_id=False, gf_ensembl_id=False): ## How to specify channel. Use defaults? ### """Generate a phisSchem...
coord.z_coordinates = _gen_PercentArray(*z)
random_line_split
VFB2PhisXML.py
(a, b) pa = phisSchema.PercentArray() pa.extend(AB) return pa def gen_GenotypeComponent(gf_symbol=False, gf_id=False, gene_symbol=False, gene_id=False, gf_ensembl_id=False): ## How to specify channel. Use defaults? ### """Generate a phisSchema.GenotypeComponent object. All args are strings. ...
if gf_id: gc.genetic_feature_id = gf_id if gf_ensembl_id: gc.genetic_feature_ensembl_id = gf_ensembl_id return gc class imageDataSet(): """Class to use for generating sets of images from a common source. Assumes all datasets have common source name and URL. And that they share...
gc.genetic_feature_symbol = gf_symbol
conditional_block
james.py
from telnetlib import Telnet class James: def __init__(self, app): self.app = app def ensure_user_exists(self, username, password): james_config = self.app.config['james'] session = James.Session(james_config['host'], james_config['port'], james_config['username'], james_config['pass...
def read_until(self, text): self.telnet.read_until(text.encode("ascii"), 5) def write(self, text): self.telnet.write(text.encode("ascii"))
self.write("quit\n")
identifier_body
james.py
from telnetlib import Telnet class James: def __init__(self, app): self.app = app def ensure_user_exists(self, username, password): james_config = self.app.config['james'] session = James.Session(james_config['host'], james_config['port'], james_config['username'], james_config['pass...
else: session.create_user(username, password) session.quit() class Session: def __init__(self, host, port, username, password): self.telnet = Telnet(host, port, 10) self.read_until("login id:") self.write(username + '\n') self.re...
session.reset_password(username, password)
conditional_block
james.py
from telnetlib import Telnet class James: def __init__(self, app): self.app = app def ensure_user_exists(self, username, password): james_config = self.app.config['james'] session = James.Session(james_config['host'], james_config['port'], james_config['username'], james_config['pass...
self.write("setpassword %s %s\n" % (username, password)) self.read_until("Password for %s reset" % username) def quit(self): self.write("quit\n") def read_until(self, text): self.telnet.read_until(text.encode("ascii"), 5) def write(self, text): ...
def reset_password(self, username, password):
random_line_split
james.py
from telnetlib import Telnet class
: def __init__(self, app): self.app = app def ensure_user_exists(self, username, password): james_config = self.app.config['james'] session = James.Session(james_config['host'], james_config['port'], james_config['username'], james_config['password']) if session.is_user_registe...
James
identifier_name
app.component.ts
import {Component} from 'angular2/core'; import {InputComponent} from "./bindings/input.component"; import {ConfirmComponent} from "./bindings/confirm.component"; @Component({ selector: 'app', template: ` <div class="container"> <flwi-input
</div> <div class="container"> <flwi-confirm (confirmed)="onConfirm($event)" [myself]="myself" ></flwi-confirm> </div> `, directives: [InputComponent, ConfirmComponent] }) export class AppComponent { myself = {name: '', age: ''}; ...
(submitted)="onSubmit($event)" [myself]="myself"></flwi-input>
random_line_split
app.component.ts
import {Component} from 'angular2/core'; import {InputComponent} from "./bindings/input.component"; import {ConfirmComponent} from "./bindings/confirm.component"; @Component({ selector: 'app', template: ` <div class="container"> <flwi-input (submitted)="onSubmit($event)" ...
(confirmedObj: {name: string, age: string}) { //create a copy here, because the two-way-databinding would otherwise update my object. console.log ("confirmed", JSON.stringify(confirmedObj)); this.myself = {name: confirmedObj.name, age: confirmedObj.age}; } }
onConfirm
identifier_name
UserRepository.js
import bcrypt from 'bcrypt-nodejs' import { dd } from 'server/resources/logger' import db from 'server/resources/db' import User from 'server/models/User' import Login from 'server/models/Login' const TABLE = 'users'; class UserRepository { constructor() { this.error = this.error.bind(this) } login({ email,...
} changePassword({ currentPassword, newPassword }) { return Promise.resolve(null) } getById(id) { return User.where({id}).fetch() } getByEmail(email) { return User.where({email}).fetch() } registerSuccessfulLogin({ user, ip }) { new Login({ user_id: user.get('id'), created_at: new Date(), ...
return Promise.resolve(null)
random_line_split
UserRepository.js
import bcrypt from 'bcrypt-nodejs' import { dd } from 'server/resources/logger' import db from 'server/resources/db' import User from 'server/models/User' import Login from 'server/models/Login' const TABLE = 'users'; class UserRepository { constructor() { this.error = this.error.bind(this) } login({ email,...
(email) { return User.where({email}).fetch() } registerSuccessfulLogin({ user, ip }) { new Login({ user_id: user.get('id'), created_at: new Date(), ip }).save() } error(err) { dd(err) throw new Error('ERROR') } } export default new UserRepository()
getByEmail
identifier_name
UserRepository.js
import bcrypt from 'bcrypt-nodejs' import { dd } from 'server/resources/logger' import db from 'server/resources/db' import User from 'server/models/User' import Login from 'server/models/Login' const TABLE = 'users'; class UserRepository { constructor() { this.error = this.error.bind(this) } login({ email,...
return Promise.resolve(null) }, (err) => { return Promise.reject(err) }) } login({ email, password }) { return User.where({email}).fetch().then((user) => { if (! user) { return Promise.resolve(null) } if (bcrypt.compareSync(password, user.get('password'))) { return Promise.resolve(use...
{ return Promise.resolve(user); }
conditional_block
UserRepository.js
import bcrypt from 'bcrypt-nodejs' import { dd } from 'server/resources/logger' import db from 'server/resources/db' import User from 'server/models/User' import Login from 'server/models/Login' const TABLE = 'users'; class UserRepository { constructor() { this.error = this.error.bind(this) } login({ email,...
forgotPassword({ email }) { return Promise.resolve(null) } resetPassword({ password, token }) { return Promise.resolve(null) } changePassword({ currentPassword, newPassword }) { return Promise.resolve(null) } getById(id) { return User.where({id}).fetch() } getByEmail(email) { return User.where(...
{ return new User({ email, first_name: firstName, last_name: lastName, password: bcrypt.hashSync(password) }).save() }
identifier_body
block_add.rs
below */ use std::time::Instant; use hash::*; use util::*; use buffer::*; use rayon::prelude::*; use slog ; use store::Store; use transaction; use transaction::TransactionStats; use merkle_tree; use block::*; use store::Record; use store::BlockPtr; use store::HashIndexGuard; use store::tips; type BlockResult<T> = R...
// we couldn't add this block to the index, which means some block is awaiting connection let guards = store.block_index.get(conn.block_hash.as_ref()); if guards.iter().any(|ptr| !ptr.is_guard()) { // this is not a guard, this is _this_ block. This means the block // w...
{ trace!(store.logger, "Connect block - set-hash-loop - ok"); continue; }
conditional_block
block_add.rs
below */ use std::time::Instant; use hash::*; use util::*; use buffer::*; use rayon::prelude::*; use slog ; use store::Store; use transaction; use transaction::TransactionStats; use merkle_tree; use block::*; use store::Record; use store::BlockPtr; use store::HashIndexGuard; use store::tips; type BlockResult<T> = R...
let mut chunk_stats = TransactionStats { cloning: cloning, ..Default::default() }; for tx in chunk_tx { let p1 = Instant::now(); let hash = Hash32Buf::double_sha256(tx.to_raw()); hashes.push(hash); let p2 = Instant::now(); let res = tx...
{ let timer = ::std::time::Instant::now(); // We use chunked parallelization because otherwise we need to clone() the stores on each // iteration // The main procedure here is to hash and call verify_and_store for each transaction let chunks: Vec<_> = block.txs.par_chunks(PARALLEL_HASHING_...
identifier_body
block_add.rs
Returns true if the block is already stored fn block_exists(store: & mut Store, block_hash: Hash32) -> bool { let ptr = store.block_index.get(block_hash); ptr.iter().any( | ptr | !ptr.is_guard()) } /// Verifies and stores the transactions in the block. /// This does not yet check the order /// Also verifie...
add_block(&mut store, &block2); add_block(&mut store, &block1);
random_line_split
block_add.rs
_block) ?; } // The to_do list contains blocks that are connected to their previous but not yet added to the // block-index. Start with the one we just connected; let mut todo = vec![Connection { block: this_block, block_hash: this_block_hash.as_buf(), solved_guards: ...
X
identifier_name
TemplateSearchBar.ts
import m, {Children, Component, Vnode} from "mithril" import type {TranslationKey} from "../../misc/LanguageViewModel" import {lang} from "../../misc/LanguageViewModel" import {inputLineHeight, px} from "../../gui/size" import type {keyHandler} from "../../misc/KeyManager" import {theme} from "../../gui/theme" import t...
(a: TemplateSearchBarAttrs): Children { return m("input.input", { placeholder: a.placeholder && lang.getMaybeLazy(a.placeholder), oncreate: vnode => { this.domInput = vnode.dom as HTMLInputElement this.domInput.value = a.value() this.domInput.focus() }, onkeydown: (e: KeyboardEvent) => { l...
_getInputField
identifier_name
TemplateSearchBar.ts
import m, {Children, Component, Vnode} from "mithril" import type {TranslationKey} from "../../misc/LanguageViewModel" import {lang} from "../../misc/LanguageViewModel" import {inputLineHeight, px} from "../../gui/size" import type {keyHandler} from "../../misc/KeyManager" import {theme} from "../../gui/theme" import t...
}) } }
random_line_split
TemplateSearchBar.ts
import m, {Children, Component, Vnode} from "mithril" import type {TranslationKey} from "../../misc/LanguageViewModel" import {lang} from "../../misc/LanguageViewModel" import {inputLineHeight, px} from "../../gui/size" import type {keyHandler} from "../../misc/KeyManager" import {theme} from "../../gui/theme" import t...
_getInputField(a: TemplateSearchBarAttrs): Children { return m("input.input", { placeholder: a.placeholder && lang.getMaybeLazy(a.placeholder), oncreate: vnode => { this.domInput = vnode.dom as HTMLInputElement this.domInput.value = a.value() this.domInput.focus() }, onkeydown: (e: Keyboard...
{ const a = vnode.attrs return m( ".inputWrapper.pt-xs.pb-xs", { style: { "border-bottom": `1px solid ${theme.content_border}`, }, }, this._getInputField(a), ) }
identifier_body
edalize_common.py
= os.path.dirname(__file__) class TestFixture: """A fixture that makes an edalize backend with work_root directory Create this object using the make_edalize_test factory fixture. This passes through its `tool_name` and sets up a temporary directory for `work_root`, then passes its keyword arguments ...
(tool_name, **kwargs): work_root = tmpdir / str(len(created)) work_root.mkdir() fixture = TestFixture(tool_name, str(work_root), **kwargs) created.append(fixture) return fixture return _fun def compare_files(ref_dir, work_root, files): """Check that all *files* in *wor...
_fun
identifier_name
edalize_common.py
os.path.dirname(__file__) class TestFixture: """A fixture that makes an edalize backend with work_root directory Create this object using the make_edalize_test factory fixture. This passes through its `tool_name` and sets up a temporary directory for `work_root`, then passes its keyword arguments th...
return defs def _setup_backend( name, tool, paramtypes, files, tool_options, work_root, use_vpi, toplevel ): """Set up a backend. The backend is called *name*, is set up for *tool* with *tool_options*, *paramtypes*, and, if *use_vpi* is ``True``, definitions from :attr:`VPI`. If *files* is N...
if datatype == "int": default = 42 elif datatype == "str": default = "hello" else: default = True defs[paramtype + "_" + datatype] = { "datatype": datatype, "default": default, "descriptio...
conditional_block
edalize_common.py
= os.path.dirname(__file__) class TestFixture: """A fixture that makes an edalize backend with work_root directory Create this object using the make_edalize_test factory fixture. This passes through its `tool_name` and sets up a temporary directory for `work_root`, then passes its keyword arguments ...
ref_dir = os.path.normpath(os.path.join(self.ref_dir, ref_subdir)) return compare_files(ref_dir, self.work_root, files) def copy_to_work_root(self, path): shutil.copy( os.path.join(self.ref_dir, path), os.path.join(self.work_root, path) ) @pytest.fixture def make_edali...
documentation for how to use the :envvar:`GOLDEN_RUN` environment variable to copy across a golden reference. """
random_line_split
edalize_common.py
= os.path.dirname(__file__) class TestFixture: """A fixture that makes an edalize backend with work_root directory Create this object using the make_edalize_test factory fixture. This passes through its `tool_name` and sets up a temporary directory for `work_root`, then passes its keyword arguments ...
def compare_files(ref_dir, work_root, files): """Check that all *files* in *work_root* match those in *ref_dir*. If the environment variable :envvar:`GOLDEN_RUN` is set, the *files* in *work_root* are copied to *ref_dir* to become the new reference. """ for f in files: reference_file = ...
"""A factory fixture to make an edalize backend with work_root directory The returned factory method takes a `tool_name` (the name of the tool) and the keyword arguments supported by :class:`TestFixture`. It returns a :class:`TestFixture` object, whose `work_root` is a temporary directory. """ # P...
identifier_body
index.js
import toDate from '../../toDate/index.js'; import startOfUTCISOWeek from '../startOfUTCISOWeek/index.js'; import startOfUTCISOWeekYear from '../startOfUTCISOWeekYear/index.js'; import requiredArgs from '../requiredArgs/index.js'; var MILLISECONDS_IN_WEEK = 604800000; // This function will be a part of public API when ...
{ requiredArgs(1, arguments); var date = toDate(dirtyDate); var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime(); // Round the number of days to the nearest integer // because the number of milliseconds in a week is not constant // (e.g. it's different in the week of the daylig...
identifier_body
index.js
import toDate from '../../toDate/index.js'; import startOfUTCISOWeek from '../startOfUTCISOWeek/index.js'; import startOfUTCISOWeekYear from '../startOfUTCISOWeekYear/index.js'; import requiredArgs from '../requiredArgs/index.js'; var MILLISECONDS_IN_WEEK = 604800000; // This function will be a part of public API when ...
// because the number of milliseconds in a week is not constant // (e.g. it's different in the week of the daylight saving time clock shift) return Math.round(diff / MILLISECONDS_IN_WEEK) + 1; }
random_line_split
index.js
import toDate from '../../toDate/index.js'; import startOfUTCISOWeek from '../startOfUTCISOWeek/index.js'; import startOfUTCISOWeekYear from '../startOfUTCISOWeekYear/index.js'; import requiredArgs from '../requiredArgs/index.js'; var MILLISECONDS_IN_WEEK = 604800000; // This function will be a part of public API when ...
(dirtyDate) { requiredArgs(1, arguments); var date = toDate(dirtyDate); var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime(); // Round the number of days to the nearest integer // because the number of milliseconds in a week is not constant // (e.g. it's different in the week o...
getUTCISOWeek
identifier_name
run.rs
use super::{Async, Pair, AsyncError, Future}; use syncbox::Task; use syncbox::TaskBox; use syncbox::Run; /// This method defers a task onto a task runner until we can complete that call. /// Currently we only support using a ThreadPool as the task runner itself. pub fn
<R: Run<Box<TaskBox>> + Send + 'static, A: Async + 'static>(task_runner: R, future_in: A) -> Future<A::Value, A::Error> { let (complete, future_out) = Future::pair(); complete.receive(|result_or_error| { if let Ok(complete) = result_or_error { future_in.receive(move | result_or_...
defer
identifier_name
run.rs
use super::{Async, Pair, AsyncError, Future}; use syncbox::Task; use syncbox::TaskBox; use syncbox::Run; /// This method defers a task onto a task runner until we can complete that call. /// Currently we only support using a ThreadPool as the task runner itself. pub fn defer<R: Run<Box<TaskBox>> + Send + 'static, ...
/// This method backgrounds a task onto a task runner waiting for complete to be called. /// Currently we only support using a ThreadPool as the task runner itself. pub fn background<R: Run<Box<TaskBox>> + Send + 'static, F: FnOnce() -> T + Send + 'static, T: Send>(task_runner: R, closure: Box<F>) ...
{ let (complete, future_out) = Future::pair(); complete.receive(|result_or_error| { if let Ok(complete) = result_or_error { future_in.receive(move | result_or_error | { match result_or_error { Ok(val) => task_runner.run(Box::new(|| complete.complete(val)))...
identifier_body
run.rs
use super::{Async, Pair, AsyncError, Future}; use syncbox::Task; use syncbox::TaskBox; use syncbox::Run; /// This method defers a task onto a task runner until we can complete that call. /// Currently we only support using a ThreadPool as the task runner itself.
pub fn defer<R: Run<Box<TaskBox>> + Send + 'static, A: Async + 'static>(task_runner: R, future_in: A) -> Future<A::Value, A::Error> { let (complete, future_out) = Future::pair(); complete.receive(|result_or_error| { if let Ok(complete) = result_or_error { future_in.receive(move ...
random_line_split
application.component.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 requi...
loadConsents() { this.userService.consents(this.domainId, this.userId, null).subscribe(consents => { this.consents = consents.filter(consent => consent.clientId === this.clientId); this.consents = [...this.consents]; }); } canRevokeAccess() { return _.find(this.consents, {status: 'appro...
{ event.preventDefault(); this.dialogService .confirm('Revoke access', 'Are you sure you want to revoke this permission ?') .subscribe(res => { if (res) { this.userService.revokeConsent(this.domainId, this.userId, consent.id).subscribe(response => { this.snackbarService...
identifier_body
application.component.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 requi...
() { this.application = this.route.snapshot.data['application']; this.domainId = this.route.snapshot.data['domain']?.id; this.userId = this.route.snapshot.params['userId']; this.consents = this.route.snapshot.data['consents']; this.clientId = this.route.snapshot.queryParamMap.get('clientId'); th...
ngOnInit
identifier_name
application.component.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 requi...
styleUrls: ['./application.component.scss'] }) export class UserApplicationComponent implements OnInit { private domainId: string; private userId: string; application: any; clientId: string; consents: any[]; canRevoke: boolean; constructor(private route: ActivatedRoute, private router: Ro...
import {AuthService} from "../../../../../../services/auth.service"; @Component({ selector: 'app-user-application', templateUrl: './application.component.html',
random_line_split
application.component.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 requi...
}); } revokeConsent(event, consent) { event.preventDefault(); this.dialogService .confirm('Revoke access', 'Are you sure you want to revoke this permission ?') .subscribe(res => { if (res) { this.userService.revokeConsent(this.domainId, this.userId, consent.id).subscrib...
{ this.userService.revokeConsents(this.domainId, this.userId, this.clientId).subscribe(response => { this.snackbarService.open('Access for application ' + this.application.name + ' revoked'); this.router.navigate(['..'], { relativeTo: this.route }); }); }
conditional_block
test_G33.py
from __future__ import absolute_import import mock import numpy as np from .MockPrinter import MockPrinter from redeem.Gcode import Gcode class G33_Tests(MockPrinter): def setUp(self): pass def test_G33_properties(self): self.assertGcodeProperties("G33", is_buffered=True, is_async=True) @mock.patch("...
(self): """ Set probe offset to 0. Since processor.execute has been mocked the G33 code will not actually execute G30 commands """ offset_z = self.printer.config.set('Probe', 'offset_z', str(0.000)) self.printer.probe_points = [ # roughly 120 degree equalateral triangle, 30mm off the deck {0.080,...
test_gcodes_G33_correct_args_to_autocalibrate_delta_printer
identifier_name
test_G33.py
from __future__ import absolute_import
import numpy as np from .MockPrinter import MockPrinter from redeem.Gcode import Gcode class G33_Tests(MockPrinter): def setUp(self): pass def test_G33_properties(self): self.assertGcodeProperties("G33", is_buffered=True, is_async=True) @mock.patch("redeem.gcodes.G33.Gcode") def test_G33_abort_on_ba...
import mock
random_line_split
test_G33.py
from __future__ import absolute_import import mock import numpy as np from .MockPrinter import MockPrinter from redeem.Gcode import Gcode class G33_Tests(MockPrinter): def setUp(self): pass def test_G33_properties(self): self.assertGcodeProperties("G33", is_buffered=True, is_async=True) @mock.patch("...
def test_gcodes_G33_correct_args_to_autocalibrate_delta_printer(self): """ Set probe offset to 0. Since processor.execute has been mocked the G33 code will not actually execute G30 commands """ offset_z = self.printer.config.set('Probe', 'offset_z', str(0.000)) self.printer.probe_points = [ # roughly...
self.printer.processor.execute = mock.Mock() # prevent macro command execution macro_gcodes = self.printer.config.get("Macros", "G29").split("\n") self.execute_gcode("G33 N3") """ compare macro from config, to macro commands created using Gcode() inside G33.execute """ for i, v in enumerate(macro_gc...
identifier_body
test_G33.py
from __future__ import absolute_import import mock import numpy as np from .MockPrinter import MockPrinter from redeem.Gcode import Gcode class G33_Tests(MockPrinter): def setUp(self): pass def test_G33_properties(self): self.assertGcodeProperties("G33", is_buffered=True, is_async=True) @mock.patch("...
mock_Gcode.assert_not_called() @mock.patch("redeem.gcodes.G33.Gcode") def test_gcodes_G33_runs_G29_macro(self, mock_Gcode): self.printer.processor.execute = mock.Mock() # prevent macro command execution macro_gcodes = self.printer.config.get("Macros", "G29").split("\n") self.execute_gcode("G...
self.execute_gcode("G33 N" + str(f))
conditional_block
lib.rs
// 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
// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language go...
// to you 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
random_line_split
test-preloads.js
const { Cc, Ci } = require("chrome"); const { storage } = require("sdk/simple-storage"); const userStorage = require("./userStorage"); userStorage.init(); // Hack: import main first to trigger correct order of dependency resolution const main = require("./main"); const utils = require('./utils'); const { Policy } = re...
}); main.clearData(true, true); main.onUnload("disabled"); }; require("sdk/test").run(exports);
assert.ok(!Policy._isPreloadedWhitelistRequest(utils.makeURI(element)), "test that " + element + " is NOT whitelisted");
random_line_split
util.rs
use libc::{c_int, c_void, setsockopt, socklen_t, timespec}; use std::{io, ptr}; use std::mem::size_of; use std::time::{Duration, SystemTime, UNIX_EPOCH}; /// `setsockopt` wrapper /// /// The libc `setsockopt` function is set to set various options on a socket. /// `set_socket_option` offers a somewhat type-safe wrapp...
pub fn set_socket_option_mult<T>(fd: c_int, level: c_int, name: c_int, values: &[T]) -> io::Result<()> { let rv = if values.len() < 1 { // can't pass in a pointer to the fir...
{ let rv = unsafe { let val_ptr: *const T = val as *const T; setsockopt(fd, level, name, val_ptr as *const c_void, size_of::<T>() as socklen_t) }; if rv != 0 { return Err(io::Error::last_os_error()); } ...
identifier_body
util.rs
use libc::{c_int, c_void, setsockopt, socklen_t, timespec}; use std::{io, ptr}; use std::mem::size_of; use std::time::{Duration, SystemTime, UNIX_EPOCH}; /// `setsockopt` wrapper /// /// The libc `setsockopt` function is set to set various options on a socket. /// `set_socket_option` offers a somewhat type-safe wrapp...
<T>(fd: c_int, level: c_int, name: c_int, values: &[T]) -> io::Result<()> { let rv = if values.len() < 1 { // can't pass in a pointer to the first element if a 0-length slice,...
set_socket_option_mult
identifier_name
util.rs
use libc::{c_int, c_void, setsockopt, socklen_t, timespec}; use std::{io, ptr}; use std::mem::size_of; use std::time::{Duration, SystemTime, UNIX_EPOCH}; /// `setsockopt` wrapper /// /// The libc `setsockopt` function is set to set various options on a socket. /// `set_socket_option` offers a somewhat type-safe wrapp...
else { unsafe { let val_ptr = &values[0] as *const T; setsockopt(fd, level, name, val_ptr as *const c_void, (size_of::<T>() * values.len()) as socklen_t) } }; if rv != 0 { ...
{ // can't pass in a pointer to the first element if a 0-length slice, // pass a nullpointer instead unsafe { setsockopt(fd, level, name, ptr::null(), 0) } }
conditional_block
util.rs
use libc::{c_int, c_void, setsockopt, socklen_t, timespec}; use std::{io, ptr}; use std::mem::size_of; use std::time::{Duration, SystemTime, UNIX_EPOCH}; /// `setsockopt` wrapper /// /// The libc `setsockopt` function is set to set various options on a socket. /// `set_socket_option` offers a somewhat type-safe wrapp...
unsafe { let val_ptr = &values[0] as *const T; setsockopt(fd, level, name, val_ptr as *const c_void, (size_of::<T>() * values.len()) as socklen_t) } }; if rv != 0 { retur...
random_line_split
cli.ts
#!/usr/bin/env node import * as minimist from 'minimist' import * as log from './logger' import * as path from 'path' import chalk = require('chalk') const script = path.resolve(__dirname, 'index.js') const pm2 = require('pm2') const args = minimist(process.argv.slice(1)) const name = 'the-concierge' const commands =...
if (state === 'status') { const status = result[0] if (!status) { return log.error(`Unable to determine status: Try running "the-concierge start"`) } const online = status.pm2_env.status === 'online' // tslint:disable-next-line:no-console console.log( `${chalk.cy...
log.error(`Failed to ${state} Concierge: ${err.message || err}`) process.exit(1) }
random_line_split
cli.ts
#!/usr/bin/env node import * as minimist from 'minimist' import * as log from './logger' import * as path from 'path' import chalk = require('chalk') const script = path.resolve(__dirname, 'index.js') const pm2 = require('pm2') const args = minimist(process.argv.slice(1)) const name = 'the-concierge' const commands =...
if (dbPath) { process.env.CONCIERGE_DB_PATH = dbPath } if (!commands.some(cmd => cmd === state)) { log.error( `Unknown command '${state}' Allowed commands: ${commands.join(', ')}` ) process.exit(1) } pm2.connect((err: any) => { if (err) { log.error(`Failed to connect to PM2: ${err.message || err}`...
{ process.env.CONCIERGE_PORT = port.toString() }
conditional_block
api.py
from django.shortcuts import get_object_or_404 from apps.canvas_auth.models import User from canvas.api_decorators import api_decorator from canvas.metrics import Metrics from canvas.models import Comment from canvas.view_guards import require_user urlpatterns = [] api = api_decorator(urlpatterns) @api('hide_comment...
@api('hide_thread') @require_user def hide_thread(request, comment_id): """ `comment_id` may be the thread OP or any reply in it. Also downvotes. """ comment = get_object_or_404(Comment, pk=comment_id) request.user.redis.hidden_threads.hide_thread(comment) sticker_count = comment.downvot...
comment = get_object_or_404(Comment, pk=comment_id) request.user.redis.hidden_comments.hide_comment(comment) Metrics.downvote_action.record(request, comment=comment.id) Metrics.hide_comment.record(request)
identifier_body
api.py
from django.shortcuts import get_object_or_404 from apps.canvas_auth.models import User from canvas.api_decorators import api_decorator from canvas.metrics import Metrics from canvas.models import Comment from canvas.view_guards import require_user urlpatterns = [] api = api_decorator(urlpatterns) @api('hide_comment...
(request, comment_id): comment = get_object_or_404(Comment, pk=comment_id) request.user.redis.hidden_comments.hide_comment(comment) Metrics.downvote_action.record(request, comment=comment.id) Metrics.hide_comment.record(request) @api('hide_thread') @require_user def hide_thread(request, comment_id): ...
hide_comment
identifier_name
api.py
from django.shortcuts import get_object_or_404 from apps.canvas_auth.models import User from canvas.api_decorators import api_decorator from canvas.metrics import Metrics from canvas.models import Comment
from canvas.view_guards import require_user urlpatterns = [] api = api_decorator(urlpatterns) @api('hide_comment') @require_user def hide_comment(request, comment_id): comment = get_object_or_404(Comment, pk=comment_id) request.user.redis.hidden_comments.hide_comment(comment) Metrics.downvote_action.reco...
random_line_split
plot_geneset_score_bar.py
from Module import AbstractModule class Module(AbstractModule): def __init__(self): AbstractModule.__init__(self) def run( self, network, antecedents, out_attributes, user_options, num_cores, outfile): from genomicode import filelib import os
from genomicode import jmath in_data = antecedents matrix = [x for x in filelib.read_cols(in_data.identifier)] matrix = [x[1:] for x in matrix] matrix = jmath.transpose(matrix) sample = matrix[0][1:] data = matrix[1:] if not os.path.exists(outfile): ...
random_line_split
plot_geneset_score_bar.py
from Module import AbstractModule class Module(AbstractModule): def __init__(self): AbstractModule.__init__(self) def run( self, network, antecedents, out_attributes, user_options, num_cores, outfile): from genomicode import filelib import os from genomicode imp...
assert filelib.exists_nz(outfile), ( 'the output file %s for plot_geneset_score_bar fails' % outfile ) def name_outfile(self, antecedents, user_options): from Betsy import module_utils original_file = module_utils.get_inputid(antecedents.identifi...
value = one_data[1:] value = [float(i) for i in value] pair = [(value[i], sample[i]) for i in range(len(value))] pair.sort() gene_value = [i[0] for i in pair] label = [i[1] for i in pair] ylabel = one_data[0] from genomicode import mplg...
conditional_block
plot_geneset_score_bar.py
from Module import AbstractModule class Module(AbstractModule):
for one_data in data: value = one_data[1:] value = [float(i) for i in value] pair = [(value[i], sample[i]) for i in range(len(value))] pair.sort() gene_value = [i[0] for i in pair] label = [i[1] for i in pair] ylabel = one_data[...
def __init__(self): AbstractModule.__init__(self) def run( self, network, antecedents, out_attributes, user_options, num_cores, outfile): from genomicode import filelib import os from genomicode import jmath in_data = antecedents matrix = [x for x in ...
identifier_body
plot_geneset_score_bar.py
from Module import AbstractModule class Module(AbstractModule): def
(self): AbstractModule.__init__(self) def run( self, network, antecedents, out_attributes, user_options, num_cores, outfile): from genomicode import filelib import os from genomicode import jmath in_data = antecedents matrix = [x for x in filelib.read...
__init__
identifier_name
CoreXT.System.Collections.IndexedObjectCollection.ts
// ############################################################################################################################################ // Collections: IndexedObjectCollection // ####################################################################################################################################...
// ------------------------------------------------------------------------------------------------------------------------------- /** * Holds the name of the internal property created on the objects in order to track indexes. * This defaults to the global 'IndexedObje...
static __validIDIndexPropertyName = "__.validIDIndex.__"; // (should never need to be accessed, so named as such to discourage it) } export namespace IndexedObjectCollection { export class $__type<TObject extends object> extends FactoryType(Array)<TObject> {
random_line_split
CoreXT.System.Collections.IndexedObjectCollection.ts
// ############################################################################################################################################ // Collections: IndexedObjectCollection // ####################################################################################################################################...
/** Return the object associated with the specified ID (index) value cast to the specified type. */ getObject<T extends TObject>(id: number): T { if (!(id === 0 || id > 0 && id < this.__objects.length)) return void 0; // (make sure the ID is valid) return <T>this....
var id: number, obj: TObject, objGiven: {} = null; id = typeof idOrObj === 'number' ? idOrObj : (objGiven = idOrObj)[this.__IDPropertyName]; if (!(id === 0 || id > 0 && id < this.__objects.length)) return void 0; // (make sure the ID is valid) obj = this._...
identifier_body
CoreXT.System.Collections.IndexedObjectCollection.ts
// ############################################################################################################################################ // Collections: IndexedObjectCollection // ####################################################################################################################################...
Object extends object>(...objects: TObject[]): IIndexedObjectCollection<TObject> { return null; } static init<TObject extends object>(o: IIndexedObjectCollection<TObject>, isnew: boolean, ...objects: TObject[]): void { this.super.init.apply(this.super, arguments); o.clear(); ...
ew'<T
identifier_name
xencreate.py
""" Virtualization installation functions. Currently somewhat Xen/paravirt specific, will evolve later. Copyright 2006-2008 Red Hat, Inc. Michael DeHaan <mdehaan@redhat.com> Original version based on virtguest-install Jeremy Katz <katzj@redhat.com> Option handling added by Andrew Puch <apuch@redhat.com> Simplified ...
for iname in interfaces: counter = counter + 1 intf = profile_data["interfaces"][iname] mac = intf["mac_address"] if mac == "": mac = random_mac() if not bridge: profile_bridge = profile_data["virt_bridge"] ...
if profile_data.has_key("interfaces"): interfaces = profile_data["interfaces"].keys() interfaces.sort() counter = -1
random_line_split
xencreate.py
""" Virtualization installation functions. Currently somewhat Xen/paravirt specific, will evolve later. Copyright 2006-2008 Red Hat, Inc. Michael DeHaan <mdehaan@redhat.com> Original version based on virtguest-install Jeremy Katz <katzj@redhat.com> Option handling added by Andrew Puch <apuch@redhat.com> Simplified ...
else: profile_bridge = bridge if profile_bridge == "": raise koan.InfoException("virt-bridge setting is not defined in cobbler") nic_obj = virtinst.XenNetworkInterface(macaddr=random_mac(), bridge=profile_bridge) guest.nics.append(nic_ob...
profile_bridge = profile_data["virt_bridge"]
conditional_block
xencreate.py
""" Virtualization installation functions. Currently somewhat Xen/paravirt specific, will evolve later. Copyright 2006-2008 Red Hat, Inc. Michael DeHaan <mdehaan@redhat.com> Original version based on virtguest-install Jeremy Katz <katzj@redhat.com> Option handling added by Andrew Puch <apuch@redhat.com> Simplified ...
(): """ from xend/server/netif.py Generate a random MAC address. Uses OUI 00-16-3E, allocated to Xensource, Inc. Last 3 fields are random. return: MAC address string """ mac = [ 0x00, 0x16, 0x3e, random.randint(0x00, 0x7f), random.randint(0x00, 0xff), random.rand...
random_mac
identifier_name
xencreate.py
""" Virtualization installation functions. Currently somewhat Xen/paravirt specific, will evolve later. Copyright 2006-2008 Red Hat, Inc. Michael DeHaan <mdehaan@redhat.com> Original version based on virtguest-install Jeremy Katz <katzj@redhat.com> Option handling added by Andrew Puch <apuch@redhat.com> Simplified ...
def start_install(name=None, ram=None, disks=None, uuid=None, extra=None, vcpus=None, profile_data=None, arch=None, no_gfx=False, fullvirt=False, bridge=None): if profile_data.has_key("file"): ...
""" from xend/server/netif.py Generate a random MAC address. Uses OUI 00-16-3E, allocated to Xensource, Inc. Last 3 fields are random. return: MAC address string """ mac = [ 0x00, 0x16, 0x3e, random.randint(0x00, 0x7f), random.randint(0x00, 0xff), random.randint(0x00...
identifier_body
nw_threat_2_file_attachment.py
#!/usr/bin/env python # Copyright (C) 2012 nwmaltego Developer. # This file is part of nwmaltego - https://github.com/bostonlink/nwmaltego # See the file 'LICENSE' for copying permission. # Netwitness Threat to Filename Maltego transform # Author: David Bressler (@bostonlink) import sys import urllib2, urllib, json f...
else: where_clause = '(time=%s) && risk.warning="%s"' % (diff, risk_name) field_name = 'attachment' json_data = json.loads(nwmodule.nwValue(0, 0, 25, field_name, 'application/json', where_clause)) file_list = [] # Print the Maltego XML Header print trans_header for d in json_data['results']['fields']: ...
parse = i.split('=') ip = parse[1] where_clause = '(time=%s) && risk.warning="%s" && ip.src=%s || ip.dst=%s' % (diff, risk_name, ip, ip)
conditional_block