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
bip65-cltv-p2p.py
#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.test_framework import ComparisonTestFramework from test_framework.util import start_nodes
from binascii import unhexlify import cStringIO ''' This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY). Connect to a single node. Mine a coinbase block, and then ... Mine 1 version 4 block. Check that the CLTV rules are enforced. TODO: factor out common code from {bipdersig-p2p,bip65-cltv-p2p}.py. ''' class...
from test_framework.mininode import CTransaction, NetworkThread from test_framework.blocktools import create_coinbase, create_block from test_framework.comptool import TestInstance, TestManager from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP
random_line_split
bip65-cltv-p2p.py
#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.test_framework import ComparisonTestFramework from test_framework.util import start_nodes from test_framework.mininode import CTran...
(self): self.num_nodes = 1 def setup_network(self): self.nodes = start_nodes(1, self.options.tmpdir, extra_args=[['-debug', '-whitelist=127.0.0.1']], binary=[self.options.testbinary]) self.is_network_split = False def ru...
__init__
identifier_name
kibana_export.py
''' Copyright(C) 2016, Stamus Networks Written by Laurent Defert <lds@stamus-networks.com> This file is part of Scirius. Scirius 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, o...
def handle(self, *args, **options): tar_name, tar_file = self.kibana_export(options['full']) os.rename(tar_file, tar_name) self.stdout.write('Kibana dashboards saved to %s' % tar_name)
dest='full', default=False, help='Save everything (SN dashboards and index)' )
random_line_split
kibana_export.py
''' Copyright(C) 2016, Stamus Networks Written by Laurent Defert <lds@stamus-networks.com> This file is part of Scirius. Scirius 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, o...
def add_arguments(self, parser): parser.add_argument( '--full', action='store_true', dest='full', default=False, help='Save everything (SN dashboards and index)' ) def handle(self, *args, **options): tar_name, tar_file = self...
BaseCommand.__init__(self, *args, **kw) ESData.__init__(self)
identifier_body
kibana_export.py
''' Copyright(C) 2016, Stamus Networks Written by Laurent Defert <lds@stamus-networks.com> This file is part of Scirius. Scirius 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, o...
(self, *args, **options): tar_name, tar_file = self.kibana_export(options['full']) os.rename(tar_file, tar_name) self.stdout.write('Kibana dashboards saved to %s' % tar_name)
handle
identifier_name
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { AuthService } fr...
import { SearchBoxComponent } from './search-box/search-box.component'; import { AppFooterComponent } from './app-footer/app-footer.component'; import { NavbarMobileComponent } from './navbar-mobile/navbar-mobile.component'; import { RecipeModule } from './recipe/recipe.module'; import { BrowserAnimationsModule } from...
SplitButtonModule, MessagesModule, GrowlModule, InputSwitchModule } from 'primeng/primeng';
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { AuthService } fr...
{ }
AppModule
identifier_name
cardgen.rs
, DeckConf>, } impl CardGenContext<'_> { pub(crate) fn new(nt: &NoteType, usn: Usn) -> CardGenContext<'_> { CardGenContext { usn, notetype: &nt, cards: nt .templates .iter() .map(|tmpl| SingleCardGenContext { ...
fn deck_for_adding(&mut self, did: Option<DeckID>) -> Result<(DeckID, DeckConfID)> { if let Some(did) = did { if let Some(deck) = self.deck_conf_if_normal(did)? {
random_line_split
cardgen.rs
>, } #[derive(Debug)] pub(crate) struct CardToGenerate { pub ord: u32, pub did: Option<DeckID>, pub due: Option<u32>, } /// Info required to determine whether a particular card ordinal should exist, /// and which deck it should be placed in. pub(crate) struct SingleCardGenContext { template: Option<Pa...
impl Collection { pub(crate) fn generate_cards_for_new_note( &mut self, ctx: &CardGenContext, note: &Note, target_deck_id: DeckID, ) -> Result<()> { self.generate_cards_for_note( ctx, note, &[], Some(target_deck_id), ...
{ let mut due = None; let mut deck_ids = HashSet::new(); for card in cards { if due.is_none() && card.position_if_new.is_some() { due = card.position_if_new; } deck_ids.insert(card.original_deck_id); } let existing_ords: HashSet<_> = cards.iter().map(|c| c.ord).co...
identifier_body
cardgen.rs
>, } #[derive(Debug)] pub(crate) struct CardToGenerate { pub ord: u32, pub did: Option<DeckID>, pub due: Option<u32>, } /// Info required to determine whether a particular card ordinal should exist, /// and which deck it should be placed in. pub(crate) struct SingleCardGenContext { template: Option<Pa...
( items: Vec<AlreadyGeneratedCardInfo>, ) -> Vec<(NoteID, Vec<AlreadyGeneratedCardInfo>)> { let mut out = vec![]; for (key, group) in &items.into_iter().group_by(|c| c.nid) { out.push((key, group.collect())); } out } #[derive(Debug, PartialEq, Default)] pub(crate) struct ExtractedCardInfo {...
group_generated_cards_by_note
identifier_name
menu-list.ts
/**
import Head from './head/index' import Link from './link/index' import Italic from './italic/index' import Underline from './underline/index' import StrikeThrough from './strike-through/index' import FontStyle from './font-style/index' import FontSize from './font-size' import Justify from './justify/index' import Quot...
* @description 所有菜单的构造函数 * @author wangfupeng */ import Bold from './bold/index'
random_line_split
concurrent_hash_map.rs
use std::ptr; use std::marker::Copy; use std::clone::Clone; use std::ops::Deref; use std::ops::DerefMut; use std::sync::{RwLock, RwLockWriteGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::fmt::{Debug, Formatter, Result}; use super::super::round_up_to_next_highest_power_of_two; struct Bucket { ...
} impl Debug for Bucket { fn fmt(&self, fmt: &mut Formatter) -> Result { write!(fmt, "[ Key = {:?} Value = {:?} ]", self.key, self.value) } } struct Link { ptr: *mut Bucket } impl Link { fn new(bucket: Bucket) -> Link { Link { ptr: Box::into_raw(Box::new(bucket)) ...
{ Bucket { key: Some(key), value: Some(value), next: None } }
identifier_body
concurrent_hash_map.rs
use std::ptr; use std::marker::Copy; use std::clone::Clone; use std::ops::Deref; use std::ops::DerefMut; use std::sync::{RwLock, RwLockWriteGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::fmt::{Debug, Formatter, Result}; use super::super::round_up_to_next_highest_power_of_two; struct Bucket { ...
else { None } } fn iterate(key: i32, guard: &RwLockWriteGuard<Link>) -> Link { let mut link = **guard; while (*link).key != Some(key) && (*link).next.is_some() { link = (*link).next.unwrap(); } link }
{ let mut link = iterate(key, guard); match (*link).next { Some(next) => link.next = next.next, None => link.ptr = ptr::null_mut(), } (*link).value }
conditional_block
concurrent_hash_map.rs
use std::ptr; use std::marker::Copy; use std::clone::Clone; use std::ops::Deref; use std::ops::DerefMut; use std::sync::{RwLock, RwLockWriteGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::fmt::{Debug, Formatter, Result}; use super::super::round_up_to_next_highest_power_of_two; struct Bucket { ...
(bucket: Bucket) -> Link { Link { ptr: Box::into_raw(Box::new(bucket)) } } } impl Deref for Link { type Target = Bucket; fn deref(&self) -> &Bucket { unsafe { &*self.ptr } } } impl DerefMut for Link { fn deref_mut(&mut self) -> &mut Bucket { unsafe { &...
new
identifier_name
concurrent_hash_map.rs
use std::ptr; use std::marker::Copy; use std::clone::Clone; use std::ops::Deref; use std::ops::DerefMut; use std::sync::{RwLock, RwLockWriteGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::fmt::{Debug, Formatter, Result}; use super::super::round_up_to_next_highest_power_of_two; struct Bucket { ...
table: Vec<RwLock<Link>>, size: AtomicUsize } impl Default for ConcurrentHashMap { fn default() -> ConcurrentHashMap { ConcurrentHashMap::new() } } impl ConcurrentHashMap { /// Create hash table with vector of locks-buckets with default size which is 16 pub fn new() -> Concurrent...
/// Currnet implementation is non resizeble vector of Read-Write locks-buckets /// which resolve hash collisions with link to the next key value pair pub struct ConcurrentHashMap {
random_line_split
coin_play.py
# Consider a row of n coins of values v1 . . . vn, where n is even. # We play a game against an opponent by alternating turns. In each turn, # a player selects either the first or last coin from the row, removes it # from the row permanently, and receives the value of the coin. Determine the # maximum possible amount o...
(coins,l,r): if l + 1 == r: return max(coins[l],coins[r]) if l == r: return coins[i] left_choose = coins[l] + min(find_max_val_recur(coins,l+1,r - 1),find_max_val_recur(coins,l+2,r)) right_choose = coins[r] + min(find_max_val_recur(coins,l + 1,r-1),find_max_val_recur(coins,l,r-2)) ...
find_max_val_recur
identifier_name
coin_play.py
# Consider a row of n coins of values v1 . . . vn, where n is even. # We play a game against an opponent by alternating turns. In each turn, # a player selects either the first or last coin from the row, removes it # from the row permanently, and receives the value of the coin. Determine the # maximum possible amount o...
coin_map = {} def find_max_val_memo(coins,l,r): if l + 1 == r: return max(coins[l],coins[r]) if l == r: return coins[i] if (l,r) in coin_map: return coin_map[(l,r)] left_choose = coins[l] + min(find_max_val_memo(coins,l+1,r - 1),find_max_val_memo(coins,l+2,r)) right_choos...
if l + 1 == r: return max(coins[l],coins[r]) if l == r: return coins[i] left_choose = coins[l] + min(find_max_val_recur(coins,l+1,r - 1),find_max_val_recur(coins,l+2,r)) right_choose = coins[r] + min(find_max_val_recur(coins,l + 1,r-1),find_max_val_recur(coins,l,r-2)) return max(left_c...
identifier_body
coin_play.py
# Consider a row of n coins of values v1 . . . vn, where n is even. # We play a game against an opponent by alternating turns. In each turn, # a player selects either the first or last coin from the row, removes it # from the row permanently, and receives the value of the coin. Determine the # maximum possible amount o...
if l + 1 == r: return max(coins[l],coins[r]) if l == r: return coins[i] left_choose = coins[l] + min(find_max_val_recur(coins,l+1,r - 1),find_max_val_recur(coins,l+2,r)) right_choose = coins[r] + min(find_max_val_recur(coins,l + 1,r-1),find_max_val_recur(coins,l,r-2)) return max(le...
def find_max_val_recur(coins,l,r):
random_line_split
coin_play.py
# Consider a row of n coins of values v1 . . . vn, where n is even. # We play a game against an opponent by alternating turns. In each turn, # a player selects either the first or last coin from the row, removes it # from the row permanently, and receives the value of the coin. Determine the # maximum possible amount o...
if (l,r) in coin_map: return coin_map[(l,r)] left_choose = coins[l] + min(find_max_val_memo(coins,l+1,r - 1),find_max_val_memo(coins,l+2,r)) right_choose = coins[r] + min(find_max_val_memo(coins,l + 1,r-1),find_max_val_memo(coins,l,r-2)) max_val = max(left_choose,right_choose) coin_map[(l...
return coins[i]
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...
// 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
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-appname fn AppName(&self) -> DOMString { navigatorinfo::AppName() } // https://html.spec.whatwg.org/multipage/#dom-navigator-appcodename fn AppCodeName(&self) -> DOMString { navigatorinfo::AppCodeName() } // https://...
navigatorinfo::TaintEnabled() }
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...
(&self) -> DOMString { navigatorinfo::Platform() } // https://html.spec.whatwg.org/multipage/#dom-navigator-useragent fn UserAgent(&self) -> DOMString { navigatorinfo::UserAgent() } // https://html.spec.whatwg.org/multipage/#dom-navigator-appversion fn AppVersion(&self) -> DOMS...
Platform
identifier_name
100 world bodies.js
var config = { type: Phaser.WEBGL, width: 800, height: 600, parent: 'phaser-example', pixelArt: true, physics: { default: 'matter', matter: { gravity: { y: 0 }, debug: true } }, scene: { create: create, ...
{ var width = Phaser.Math.Between(16, 128); var height = Phaser.Math.Between(8, 64); this.matter.add.rectangle(x, y, width, height, { restitution: 0.9 }); } } this.matter.add.mouseSpring(); var cursors = this.input.keyboard.createCursorKeys(); var ...
{ var worldWidth = 1600; var worldHeight = 1200; this.matter.world.setBounds(0, 0, worldWidth, worldHeight); // Create loads of random bodies for (var i = 0; i < 100; i++) { var x = Phaser.Math.Between(0, worldWidth); var y = Phaser.Math.Between(0, worldHeight); if (M...
identifier_body
100 world bodies.js
var config = { type: Phaser.WEBGL, width: 800, height: 600, parent: 'phaser-example', pixelArt: true, physics: { default: 'matter', matter: { gravity: { y: 0 }, debug: true } }, scene: { create: create, ...
this.matter.add.mouseSpring(); var cursors = this.input.keyboard.createCursorKeys(); var controlConfig = { camera: this.cameras.main, left: cursors.left, right: cursors.right, up: cursors.up, down: cursors.down, zoomIn: this.input.keyboard.addKey(Phaser.Inp...
} }
random_line_split
100 world bodies.js
var config = { type: Phaser.WEBGL, width: 800, height: 600, parent: 'phaser-example', pixelArt: true, physics: { default: 'matter', matter: { gravity: { y: 0 }, debug: true } }, scene: { create: create, ...
(time, delta) { controls.update(delta); }
update
identifier_name
100 world bodies.js
var config = { type: Phaser.WEBGL, width: 800, height: 600, parent: 'phaser-example', pixelArt: true, physics: { default: 'matter', matter: { gravity: { y: 0 }, debug: true } }, scene: { create: create, ...
else { var width = Phaser.Math.Between(16, 128); var height = Phaser.Math.Between(8, 64); this.matter.add.rectangle(x, y, width, height, { restitution: 0.9 }); } } this.matter.add.mouseSpring(); var cursors = this.input.keyboard.createCursorKey...
{ var sides = Phaser.Math.Between(3, 14); var radius = Phaser.Math.Between(8, 50); this.matter.add.polygon(x, y, sides, radius, { restitution: 0.9 }); }
conditional_block
__init__.py
#ckwg +28 # Copyright 2012 by Kitware, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditio...
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from pkgut...
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
random_line_split
file_name.py
import os from jedi._compatibility import FileNotFoundError, force_unicode, scandir from jedi.api import classes from jedi.api.strings import StringName, get_quote_ending from jedi.api.helpers import match from jedi.inference.helpers import get_str_or_none class PathName(StringName): api_type = u'path' def com...
else: string = to_be_added + string base_path = os.path.join(inference_state.project.path, string) try: listed = sorted(scandir(base_path), key=lambda e: e.name) # OSError: [Errno 36] File name too long: '...' except (FileNotFoundError, OSError): return quote...
is_in_os_path_join = False
conditional_block
file_name.py
import os from jedi._compatibility import FileNotFoundError, force_unicode, scandir from jedi.api import classes from jedi.api.strings import StringName, get_quote_ending from jedi.api.helpers import match from jedi.inference.helpers import get_str_or_none class PathName(StringName): api_type = u'path' def com...
if start_leaf.type == 'error_leaf': # Unfinished string literal, like `join('` value_node = start_leaf.parent index = value_node.children.index(start_leaf) if index > 0: error_node = value_node.children[index - 1] if error_node.type == 'error_node' and len(e...
if maybe_bracket.start_pos != bracket_start: return None if not nodes: return '' context = module_context.create_context(nodes[0]) return _add_strings(context, nodes, add_slash=True) or ''
identifier_body
file_name.py
import os from jedi._compatibility import FileNotFoundError, force_unicode, scandir from jedi.api import classes from jedi.api.strings import StringName, get_quote_ending from jedi.api.helpers import match from jedi.inference.helpers import get_str_or_none class PathName(StringName): api_type = u'path' def com...
(): node = addition.parent was_addition = True for child_node in reversed(node.children[:node.children.index(addition)]): if was_addition: was_addition = False yield child_node continue if child_node != '+': ...
iterate_nodes
identifier_name
file_name.py
import os from jedi._compatibility import FileNotFoundError, force_unicode, scandir from jedi.api import classes from jedi.api.strings import StringName, get_quote_ending from jedi.api.helpers import match from jedi.inference.helpers import get_str_or_none class PathName(StringName): api_type = u'path' def com...
if searched_node_child.get_first_leaf() is not start_leaf: return None searched_node = searched_node_child.parent if searched_node is None: return None index = searched_node.children.index(searched_node_child) arglist_nodes = searched_node.children[:index] if searched_node.type ...
random_line_split
regions-early-bound-used-in-bound.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let b1 = Box { t: &3i }; assert_eq!(add(b1, b1), 6i); }
main
identifier_name
regions-early-bound-used-in-bound.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { let b1 = Box { t: &3i }; assert_eq!(add(b1, b1), 6i); }
{ *g1.get() + *g2.get() }
identifier_body
regions-early-bound-used-in-bound.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
*g1.get() + *g2.get() } pub fn main() { let b1 = Box { t: &3i }; assert_eq!(add(b1, b1), 6i); }
fn add<'a,G:GetRef<'a, int>>(g1: G, g2: G) -> int {
random_line_split
redis.config.js
/* Copyright 2016 Covistra Technologies Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writ...
}, $default: { host: 'localhost', port: 6379 } } };
host: 'redis', port: 6379
random_line_split
client.py
FixSimApplication, create_fix_version, instance_safe_call, create_logger, IncrementID, load_yaml) class Subscription(object): def __init__(self, symbol): super(Subscription, self).__init__() self.symbol = symbol self.currency = self.symbol.split("/")[0] def __repr__(...
self.loop = task.LoopingCall(self.subscribe) self.loop.start(self.subscribeInterval, True) def onCreate(self, sessionID): pass def onLogon(self, sessionID): sid = str(sessionID) # print "ON LOGON sid", sid if sid.find(self.MKD_TOKEN) != -1: self.mark...
random_line_split
client.py
FixSimApplication, create_fix_version, instance_safe_call, create_logger, IncrementID, load_yaml) class Subscription(object): def __init__(self, symbol): super(Subscription, self).__init__() self.symbol = symbol self.currency = self.symbol.split("/")[0] def
(self): return "<Subscription %s>" % self.symbol class Subscriptions(object): def __init__(self): self.subscriptions = {} def add(self, subscription): if subscription.symbol in self.subscriptions: raise KeyError("Subscription for symbol has already exist") self.sub...
__repr__
identifier_name
client.py
FixSimApplication, create_fix_version, instance_safe_call, create_logger, IncrementID, load_yaml) class Subscription(object): def __init__(self, symbol): super(Subscription, self).__init__() self.symbol = symbol self.currency = self.symbol.split("/")[0] def __repr__(...
def onCreate(self, sessionID): pass def onLogon(self, sessionID): sid = str(sessionID) # print "ON LOGON sid", sid if sid.find(self.MKD_TOKEN) != -1: self.marketSession = sessionID self.logger.info("FIXSIM-CLIENT MARKET SESSION %s", self.marketSession) ...
super(Client, self).__init__(fixVersion, logger) self.skipSnapshotChance = skipSnapshotChance self.subscribeInterval = subscribeInterval self.subscriptions = subscriptions self.orderSession = None self.marketSession = None self.idGen = IDGenerator() self.loop = t...
identifier_body
client.py
FixSimApplication, create_fix_version, instance_safe_call, create_logger, IncrementID, load_yaml) class Subscription(object): def __init__(self, symbol): super(Subscription, self).__init__() self.symbol = symbol self.currency = self.symbol.split("/")[0] def __repr__(...
self.subscriptions[subscription.symbol] = subscription def get(self, symbol): subscription = self.subscriptions.get(symbol, None) return subscription def __iter__(self): return self.subscriptions.values().__iter__() class OrderBook(object): def __init__(self): se...
raise KeyError("Subscription for symbol has already exist")
conditional_block
upload.js
/* global UTILS */ 'use strict'; angular.module('alienUiApp').controller('UploadCtrl', [ '$scope', '$upload', function($scope, $upload) { // states classes var statesToClasses = { 'error': 'danger', 'success': 'success', 'progress': 'info' }; $scope.uploadInfos = []; $scope.upload = []; $scope...
}); $scope.upload[index] = $upload.upload({ url: $scope.targetUrl, file: file }).progress(function(evt) { $scope.uploadInfos[index].progress = parseInt(100.0 * evt.loaded / evt.total); }).success(function(data) { // file is uploaded successfully and the server respond without er...
'name': file.name, 'progress': 0, 'infoType': statesToClasses.progress, 'isErrorBlocCollapsed': true
random_line_split
upload.js
/* global UTILS */ 'use strict'; angular.module('alienUiApp').controller('UploadCtrl', [ '$scope', '$upload', function($scope, $upload) { // states classes var statesToClasses = { 'error': 'danger', 'success': 'success', 'progress': 'info' }; $scope.uploadInfos = []; $scope.upload = []; $scope...
$scope.doUpload = function(file) { var index = $scope.uploadInfos.length; $scope.uploadInfos.push({ 'name': file.name, 'progress': 0, 'infoType': statesToClasses.progress, 'isErrorBlocCollapsed': true }); $scope.upload[index] = $upload.upload({ url: $scope.targetUrl, ...
{ if (data.data === null) { $scope.uploadInfos[index].otherError = {}; $scope.uploadInfos[index].otherError.code = data.error.code; $scope.uploadInfos[index].otherError.message = data.error.message; } else if (UTILS.isMapNotNullOrEmpty(data.data.errors)) { $scope.uploadInfos[index].error...
identifier_body
upload.js
/* global UTILS */ 'use strict'; angular.module('alienUiApp').controller('UploadCtrl', [ '$scope', '$upload', function($scope, $upload) { // states classes var statesToClasses = { 'error': 'danger', 'success': 'success', 'progress': 'info' }; $scope.uploadInfos = []; $scope.upload = []; $scope...
else if (UTILS.isMapNotNullOrEmpty(data.data.errors)) { $scope.uploadInfos[index].errors = data.data.errors; } } $scope.doUpload = function(file) { var index = $scope.uploadInfos.length; $scope.uploadInfos.push({ 'name': file.name, 'progress': 0, 'infoType': statesToClasses.pro...
{ $scope.uploadInfos[index].otherError = {}; $scope.uploadInfos[index].otherError.code = data.error.code; $scope.uploadInfos[index].otherError.message = data.error.message; }
conditional_block
upload.js
/* global UTILS */ 'use strict'; angular.module('alienUiApp').controller('UploadCtrl', [ '$scope', '$upload', function($scope, $upload) { // states classes var statesToClasses = { 'error': 'danger', 'success': 'success', 'progress': 'info' }; $scope.uploadInfos = []; $scope.upload = []; $scope...
(index, data) { if (data.data === null) { $scope.uploadInfos[index].otherError = {}; $scope.uploadInfos[index].otherError.code = data.error.code; $scope.uploadInfos[index].otherError.message = data.error.message; } else if (UTILS.isMapNotNullOrEmpty(data.data.errors)) { $scope.uploadInfo...
handleUploadErrors
identifier_name
generate.py
is difficult to show how it integrates when PLSR is also dispatched\n""" filtered_reserve = reserve.efilter(*args, **kargs) estimate_number = len(filtered_energy[["Node", "Trading_Period_ID"]].drop_duplicates()) * 2 if verbose: print """I'm beginning to cre...
""" Create the fan information for a given station and single reserve type. If multiple reserve types are passed this will fail miserably. Parameters: ----------- energy: Energy OfferFrame containing the information about a single station and trading period reserve: PLSR OfferFrame...
def station_fan(energy, reserve, assumed_reserve=None):
random_line_split
generate.py
estimate_number = len(filtered_energy[["Node", "Trading_Period_ID"]].drop_duplicates()) * 2 if verbose: print """I'm beginning to create fan curves, I estimate I'll need to do at least %s of these which may take at least %s seconds, hold tight""" % ( estima...
print """Warning, TWDSR is still a little funky and the visualisation of it in a composite fan diagram can be misleading. Most notably it is difficult to show how it integrates when PLSR is also dispatched\n""" filtered_reserve = reserve.efilter(*args, **kargs)
conditional_block
generate.py
fan_assembly = [] for index, station, tpid in station_dates.itertuples(): single_energy = energy.efilter(Trading_Period_ID=tpid, Node=station) for reserve_type in ("FIR", "SIR"): single_reserve = reserve.efilter(Trading_Period_ID=tpid, ...
""" Create a feasible region array with information about energy and reserve prices for a single band. This array contains information on an incremental fashion regarding the energy and reserve tradeoff. Ideally should keep all of the data together in one place: Parameters: ----------- stac...
identifier_body
generate.py
difficult to show how it integrates when PLSR is also dispatched\n""" filtered_reserve = reserve.efilter(*args, **kargs) estimate_number = len(filtered_energy[["Node", "Trading_Period_ID"]].drop_duplicates()) * 2 if verbose: print """I'm beginning to create...
(energy, reserve, assumed_reserve=None): """ Create the fan information for a given station and single reserve type. If multiple reserve types are passed this will fail miserably. Parameters: ----------- energy: Energy OfferFrame containing the information about a single station and tra...
station_fan
identifier_name
newtype-struct-drop-run.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&mut self) { ***self = 23; } } fn main() { let y = @mut 32; { let _x = Foo(y); } assert_eq!(*y, 23); }
drop
identifier_name
dialogue.py
import numpy as np from numpy import cumsum, sum, searchsorted from numpy.random import rand import math import utils import core.sentence as sentence import core.markovchain as mc import logging logger = logging.getLogger(__name__) # Dialogue making class. Need to review where to return a string, where to return a l...
def after(self, speaker_id): """Pick next person to speak""" row = self._transitions[speaker_id] sucessor = searchsorted(cumsum(row), rand() * sum(row)) return sucessor def speaker_sequence(self, speaker_id, n): """Random walk through transitions matrix to produce a se...
"""Make transition matrix between speakers, with random symmetric biases added in""" n = len(self.speakers) # TODO why this line ??? transitions = np.random.randint(5, size=(n, n)) + 1 transitions += transitions.transpose() for i in range(0, math.floor(n / 2)): s1 = np.rando...
identifier_body
dialogue.py
import numpy as np from numpy import cumsum, sum, searchsorted from numpy.random import rand import math import utils import core.sentence as sentence import core.markovchain as mc import logging logger = logging.getLogger(__name__) # Dialogue making class. Need to review where to return a string, where to return a l...
return seq_map def report_seq(self, seq_map): """Convert sequence of speeches to a tokens.""" sents = [] for i in range(0, len(seq_map)): if seq_map[i]['paragraph']: # text += "\n " quote_start = '"' else: ...
seq_map[i]['speaker_str'] = seq_map[i]['speaker_name'] # default # Same speaker contiues: if i > 0 and seq_map[i]['seq_id'] == seq_map[i - 1]['seq_id']: seq_map[i]['speaker_str'] = "" seq_map[i]['speech_act'] = "" seq_map[i]['paragraph'] = False ...
conditional_block
dialogue.py
import numpy as np from numpy import cumsum, sum, searchsorted from numpy.random import rand import math import utils import core.sentence as sentence import core.markovchain as mc import logging logger = logging.getLogger(__name__) # Dialogue making class. Need to review where to return a string, where to return a l...
quote_start = "" if i > len(seq_map) - 2 or seq_map[i + 1]['paragraph']: quote_end = '"' else: quote_end = " " if len(seq_map[i]['speech_act']) > 0: speech_act = seq_map[i]['speech_act'] + "," else: ...
if seq_map[i]['paragraph']: # text += "\n " quote_start = '"' else:
random_line_split
dialogue.py
import numpy as np from numpy import cumsum, sum, searchsorted from numpy.random import rand import math import utils import core.sentence as sentence import core.markovchain as mc import logging logger = logging.getLogger(__name__) # Dialogue making class. Need to review where to return a string, where to return a l...
(object): """Class to handle creating dialogue based on a list of speakers and a sentence generator.""" def __init__(self, names, pronouns, mc): self.speakers = [{"name": n, "pronoun": p} for n, p in list(zip(names, pronouns))] self._transitions = self.make_transition_probs() self._speec...
dialogue_maker
identifier_name
demo_tokenizer_roberta.py
from transformers import RobertaTokenizerFast import scattertext as st tokenizer_fast = RobertaTokenizerFast.from_pretrained( "roberta-base", add_prefix_space=True) tokenizer = st.RobertaTokenizerWrapper(tokenizer_fast) df = st.SampleCorpora.ConventionData2012.get_data().assign( parse = lambda df: df.text.app...
not_category_name='Republican', width_in_pixels=1000, suppress_text_column='Display', metadata=corpus.get_df()['speaker'], use_non_text_features=True, ignore_categories=False, use_offsets=True, unified_context=False, color_score_column='ColorScore', left_list_column='ColorScore'...
category_name='Democratic',
random_line_split
alert_processor.py
""" Copyright 2017-present Airbnb, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
'sse_kms_key_arn': '${aws_kms_key.server_side_encryption.arn}', 'output_lambda_functions': [ # Strip qualifiers: only the function name is needed for the IAM permissions func.split(':')[0] for func in list(config['outputs'].get('aws-lambda', {}).values()) ], 'outp...
"""Generate Terraform for the Alert Processor Args: config (dict): The loaded config from the 'conf/' directory Returns: dict: Alert Processor dict to be marshaled to JSON """ prefix = config['global']['account']['prefix'] result = infinitedict() # Set variables for the IAM p...
identifier_body
alert_processor.py
""" Copyright 2017-present Airbnb, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
(config): """Generate Terraform for the Alert Processor Args: config (dict): The loaded config from the 'conf/' directory Returns: dict: Alert Processor dict to be marshaled to JSON """ prefix = config['global']['account']['prefix'] result = infinitedict() # Set variables...
generate_alert_processor
identifier_name
alert_processor.py
""" Copyright 2017-present Airbnb, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
'ALERTS_TABLE': '{}_streamalert_alerts'.format(prefix), 'AWS_ACCOUNT_ID': config['global']['account']['aws_account_id'], 'STREAMALERT_PREFIX': prefix } ) return result
environment={
random_line_split
test-models.js
'use strict' var request = require('supertest') , assert = require('assert') , models = require('../models'); describe('makeUser', function() { // 정상적인 유저 생성 확인 it('valid make user', function (done) { var gameId = 1000;
models.makeUser(gameId, facebookId, inventorySize, maxHeart, status) .then(function (userId) { assert(userId > 0); }).then(done, done); }) // 비정상적인 유저 생성 확인 it('invalid make user', function (done) { models.makeUser() .catch(function (err) { assert(err); }).then(don...
var facebookId = 0; var inventorySize = 100; var maxHeart = 80; var status = 1;
random_line_split
binner.py
import numpy as N class Binner(object): """Class to perform averages of arbitary variables over some bin (i.e. range) of a coordinate. An example: r, u = calculateVelocitiesAtPositions() # r is nx X ny X nz X 3 array of positions # v is the same but for velocities at the corresp...
uNorm = N.sqrt(N.sum(u**2, axis=-1)) b = Binner(rNorm.ravel(), bins=100) uBin = b.mean(uNorm.ravel()) g = Gnuplot.Gnuplot() g('set datafile missing "nan"') g('set logscale') g.plot(Gnuplot.Data(b.means, b.mean(uNorm.ravel()), ...
rNorm = N.sqrt(N.sum(r**2, axis=-1)) # velocity magnitude
random_line_split
binner.py
import numpy as N class Binner(object): """Class to perform averages of arbitary variables over some bin (i.e. range) of a coordinate. An example: r, u = calculateVelocitiesAtPositions() # r is nx X ny X nz X 3 array of positions # v is the same but for velocities at the corresp...
self.masks = [N.ma.masked_not_equal(self.binmap, i, copy=False).mask for i in range(self.nBins)] self.maskedCoords = [N.ma.array(coord, mask=msk) for msk in self.masks] self.means = N.array([mc.mean() for mc in self.m...
self.binmap[N.where(coord>self.edges[i])] = i continue
conditional_block
binner.py
import numpy as N class Binner(object): """Class to perform averages of arbitary variables over some bin (i.e. range) of a coordinate. An example: r, u = calculateVelocitiesAtPositions() # r is nx X ny X nz X 3 array of positions # v is the same but for velocities at the corresp...
(self, coord, **kwargs): """coord -- the coordinate on which we're constructing the bins The following arguments are as for numpy.histogram. bins : int or sequence of scalars, optional If `bins` is an int, it defines the number of equal-width bins in the...
__init__
identifier_name
binner.py
import numpy as N class Binner(object): """Class to perform averages of arbitary variables over some bin (i.e. range) of a coordinate. An example: r, u = calculateVelocitiesAtPositions() # r is nx X ny X nz X 3 array of positions # v is the same but for velocities at the corresp...
""" self.coordShape = coord.shape self.counts, self.edges = N.histogram(coord, new=True, normed=False, **kwargs) self.centres = 0.5*(self.edges[:-1]+self.edges[1:]) self.widths = self.edges[1:]-self.edges[:-...
"""coord -- the coordinate on which we're constructing the bins The following arguments are as for numpy.histogram. bins : int or sequence of scalars, optional If `bins` is an int, it defines the number of equal-width bins in the given range (10, by default). If...
identifier_body
heap_utils.js
'use strict'; const { Symbol } = primordials; const { kUpdateTimer, onStreamRead, } = require('internal/stream_base_commons'); const { owner_symbol } = require('internal/async_hooks').symbols; const { Readable } = require('stream'); const kHandle = Symbol('kHandle'); class HeapSnapshotStream extends Readable { ...
_read() { if (this[kHandle]) this[kHandle].readStart(); } _destroy() { // Release the references on the handle so that // it can be garbage collected. this[kHandle][owner_symbol] = undefined; this[kHandle] = undefined; } [kUpdateTimer]() { // Does nothing } } module.exports...
super({ autoDestroy: true }); this[kHandle] = handle; handle[owner_symbol] = this; handle.onread = onStreamRead; }
random_line_split
heap_utils.js
'use strict'; const { Symbol } = primordials; const { kUpdateTimer, onStreamRead, } = require('internal/stream_base_commons'); const { owner_symbol } = require('internal/async_hooks').symbols; const { Readable } = require('stream'); const kHandle = Symbol('kHandle'); class HeapSnapshotStream extends Readable { ...
[kUpdateTimer]() { // Does nothing } } module.exports = { HeapSnapshotStream };
{ // Release the references on the handle so that // it can be garbage collected. this[kHandle][owner_symbol] = undefined; this[kHandle] = undefined; }
identifier_body
heap_utils.js
'use strict'; const { Symbol } = primordials; const { kUpdateTimer, onStreamRead, } = require('internal/stream_base_commons'); const { owner_symbol } = require('internal/async_hooks').symbols; const { Readable } = require('stream'); const kHandle = Symbol('kHandle'); class HeapSnapshotStream extends Readable { ...
() { // Release the references on the handle so that // it can be garbage collected. this[kHandle][owner_symbol] = undefined; this[kHandle] = undefined; } [kUpdateTimer]() { // Does nothing } } module.exports = { HeapSnapshotStream };
_destroy
identifier_name
webpack.config.dev.js
import webpack from 'webpack'; import path from 'path'; export default { debug: true, devtool: 'cheap-module-eval-source-map', noInfo: false, entry: [ // 'eventsource-polyfill', // necessary for hot reloading with IE 'webpack-hot-middleware/client?reload=true', //note that it reloads the page if hot mo...
contentBase: './src' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [ {test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']}, {test: /(\.css)$/, loaders: ['style', 'css']}, {test: /\.eot(\?v=\d+\.\d+...
path: __dirname + '/dist', // Note: Physical files are only output by the production build task `npm run build`. publicPath: '/', filename: 'bundle.js' }, devServer: {
random_line_split
tracelog.py
# # A PyGtk-based Python Trace Collector window # # Copyright (C) 2007 TK Soh <teekaysoh@gmail.com> # import pygtk pygtk.require("2.0") import gtk import gobject import pango import threading import Queue import win32trace try: from gitgtk.gitlib import toutf except ImportError: import locale _encoding = ...
def write(self, msg, append=True): msg = toutf(msg) if append: enditer = self.textbuffer.get_end_iter() self.textbuffer.insert(enditer, msg) else: self.textbuffer.set_text(msg) def main(self): self.window.show_all() gtk.main(...
msg = win32trace.read() if msg: self.queue.put(msg)
conditional_block
tracelog.py
# # A PyGtk-based Python Trace Collector window # # Copyright (C) 2007 TK Soh <teekaysoh@gmail.com> # import pygtk pygtk.require("2.0") import gtk import gobject
import threading import Queue import win32trace try: from gitgtk.gitlib import toutf except ImportError: import locale _encoding = locale.getpreferredencoding() def toutf(s): return s.decode(_encoding, 'replace').encode('utf-8') class TraceLog(): def __init__(self): self.window = g...
import pango
random_line_split
tracelog.py
# # A PyGtk-based Python Trace Collector window # # Copyright (C) 2007 TK Soh <teekaysoh@gmail.com> # import pygtk pygtk.require("2.0") import gtk import gobject import pango import threading import Queue import win32trace try: from gitgtk.gitlib import toutf except ImportError: import locale _encoding = ...
(): dlg = TraceLog() dlg.main() if __name__ == "__main__": run()
run
identifier_name
tracelog.py
# # A PyGtk-based Python Trace Collector window # # Copyright (C) 2007 TK Soh <teekaysoh@gmail.com> # import pygtk pygtk.require("2.0") import gtk import gobject import pango import threading import Queue import win32trace try: from gitgtk.gitlib import toutf except ImportError: import locale _encoding = ...
def _stop_read_thread(self): self._read_trace = False # wait for worker thread to to fix Unhandled exception in thread self.thread1.join() def _process_queue(self): """ Handle all the messages currently in the queue (if any). """ while self.qu...
self._read_trace = True self.thread1 = threading.Thread(target=self._do_read_trace) self.thread1.start()
identifier_body
intern.ts
// A fully qualified URL to the Intern proxy export const proxyUrl = 'http://localhost:9000/'; // Default desired capabilities for all environments. Individual capabilities can be overridden by any of the // specified browser environments in the `environments` array below as well. See // https://code.google.com/p/sele...
export const proxyPort = 9000;
random_line_split
intern.ts
export const proxyPort = 9000; // A fully qualified URL to the Intern proxy export const proxyUrl = 'http://localhost:9000/'; // Default desired capabilities for all environments. Individual capabilities can be overridden by any of the // specified browser environments in the `environments` array below as well. See /...
return null; })(); // The desired AMD loader to use when running unit tests (client.html/client.js). Omit to use the default Dojo // loader export const loaders = { 'host-node': 'dojo-loader' }; // Configuration options for the module loader; any AMD configuration options supported by the specified AMD loader // c...
{ return '/'; }
conditional_block
urls.py
from django.conf.urls.defaults import * from django.contrib.auth import views as auth_views from app_auth.views import * from app_auth.views import login as custom_login, logout as custom_logout urlpatterns = patterns('', # Home url(r'^$', home, name="app_auth.home"), # Login / logout url(r'^login/...
(r'^accounts/', include('registration.urls')), # Social login (r'', include('social_auth.urls')), # Default django login module (r'', include('registration.auth_urls')), ) # Password Reset # url(r'^password/reset/$', password_reset, {'template_name': 'registration/password_reset_form.html'}, na...
# Registration links
random_line_split
broker.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from . import SearchBa...
self._servers[server].update(language, obj)
conditional_block
broker.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from . import SearchBa...
for server in self._settings: if config_name is None or server in config_name: try: _module = '.'.join(self._settings[server]['ENGINE'].split('.')[:-1]) _search_class = self._settings[server]['ENGINE'].split('.')[-1] except KeyE...
random_line_split
broker.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from . import SearchBa...
def update(self, language, obj): for server in self._servers: self._servers[server].update(language, obj)
if not self._servers: return [] results = [] counter = {} for server in self._servers: for result in self._servers[server].search(unit): translation_pair = result['source'] + result['target'] if translation_pair not in counter: ...
identifier_body
broker.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from . import SearchBa...
(SearchBackend): def __init__(self, config_name=None): super(SearchBroker, self).__init__(config_name) self._servers = {} if self._settings is None: return for server in self._settings: if config_name is None or server in config_name: try: ...
SearchBroker
identifier_name
RNA.py
#!/usr/bin/env python """ segmentation-fold can predict RNA 2D structures including K-turns. Copyright (C) 2012-2016 Youri Hoogstrate This file is part of segmentation-fold and originally taken from yh-kt-fold. segmentation-fold is free software: you can redistribute it and/or modify it under the terms of the GNU Ge...
def get_structures(self): return self.structures def get_unique_associated_segments(self): segments = [] for structure in self.structures: for associated_segment in structure['associated_segments']: segments.append(associated_segment) ...
return self.sequence
identifier_body
RNA.py
#!/usr/bin/env python """ segmentation-fold can predict RNA 2D structures including K-turns. Copyright (C) 2012-2016 Youri Hoogstrate This file is part of segmentation-fold and originally taken from yh-kt-fold. segmentation-fold is free software: you can redistribute it and/or modify it under the terms of the GNU Ge...
return list(set(segments))
segments.append(associated_segment)
conditional_block
RNA.py
#!/usr/bin/env python """ segmentation-fold can predict RNA 2D structures including K-turns. Copyright (C) 2012-2016 Youri Hoogstrate This file is part of segmentation-fold and originally taken from yh-kt-fold. segmentation-fold is free software: you can redistribute it and/or modify it under the terms of the GNU Ge...
(self): return self.sequence def get_structures(self): return self.structures def get_unique_associated_segments(self): segments = [] for structure in self.structures: for associated_segment in structure['associated_segments']: segme...
get_sequence
identifier_name
RNA.py
#!/usr/bin/env python """ segmentation-fold can predict RNA 2D structures including K-turns. Copyright (C) 2012-2016 Youri Hoogstrate This file is part of segmentation-fold and originally taken from yh-kt-fold. segmentation-fold is free software: you can redistribute it and/or modify it under the terms of the GNU Ge...
return list(set(segments))
random_line_split
tuple-struct-constructor-pointer.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(int); #[derive(PartialEq, Debug)] struct Bar(int, int); pub fn main() { let f: fn(int) -> Foo = Foo; let g: fn(int, int) -> Bar = Bar; assert_eq!(f(42), Foo(42)); assert_eq!(g(4, 7), Bar(4, 7)); }
Foo
identifier_name
tuple-struct-constructor-pointer.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { let f: fn(int) -> Foo = Foo; let g: fn(int, int) -> Bar = Bar; assert_eq!(f(42), Foo(42)); assert_eq!(g(4, 7), Bar(4, 7)); }
#[derive(PartialEq, Debug)] struct Foo(int); #[derive(PartialEq, Debug)] struct Bar(int, int);
random_line_split
frost-combobox-test.js
import { expect } from 'chai' import { describeComponent, it } from 'ember-mocha' import { beforeEach, afterEach } from 'mocha' import sinon from 'sinon' import hbs from 'htmlbars-inline-precompile' const testTemplate = hbs`{{frost-combobox on-change=onChange data=data greeting=greeting}}` describeComponent( 'frost...
this.render(testTemplate) dropDown = this.$('> div') }) afterEach(function () { sandbox.restore() }) it('has correct initial state', function () { expect(dropDown).to.have.length(1) }) })
greeting: 'Hola' } this.setProperties(props)
random_line_split
stackoverflow.py
""" Stackoverflow OAuth2 backend, docs at: https://python-social-auth.readthedocs.io/en/latest/backends/stackoverflow.html """ from .oauth import BaseOAuth2 class StackoverflowOAuth2(BaseOAuth2): """Stackoverflow OAuth2 authentication backend""" name = 'stackoverflow' ID_KEY = 'user_id' AUTHORIZAT...
(self, response): """Return user details from Stackoverflow account""" fullname, first_name, last_name = self.get_user_names( response.get('display_name') ) return {'username': response.get('link').rsplit('/', 1)[-1], 'full_name': fullname, 'fi...
get_user_details
identifier_name
stackoverflow.py
""" Stackoverflow OAuth2 backend, docs at: https://python-social-auth.readthedocs.io/en/latest/backends/stackoverflow.html """ from .oauth import BaseOAuth2 class StackoverflowOAuth2(BaseOAuth2): """Stackoverflow OAuth2 authentication backend""" name = 'stackoverflow' ID_KEY = 'user_id' AUTHORIZAT...
return self.get_querystring(*args, **kwargs)
def request_access_token(self, *args, **kwargs):
random_line_split
stackoverflow.py
""" Stackoverflow OAuth2 backend, docs at: https://python-social-auth.readthedocs.io/en/latest/backends/stackoverflow.html """ from .oauth import BaseOAuth2 class StackoverflowOAuth2(BaseOAuth2): """Stackoverflow OAuth2 authentication backend""" name = 'stackoverflow' ID_KEY = 'user_id' AUTHORIZAT...
def request_access_token(self, *args, **kwargs): return self.get_querystring(*args, **kwargs)
"""Loads user data from service""" return self.get_json( 'https://api.stackexchange.com/2.1/me', params={ 'site': 'stackoverflow', 'access_token': access_token, 'key': self.setting('API_KEY') } )['items'][0]
identifier_body
forgotPassword.component.ts
import {Component, OnDestroy, OnInit} from "@angular/core"; import {ActivatedRoute, Router} from "@angular/router"; import {UserLoginService} from "../../../service/user-login.service"; import {CognitoCallback} from "../../../service/cognito.service"; @Component({ selector: 'awscognito-angular2-app', templateU...
this.sub.unsubscribe(); } onNext() { this.errorMessage = null; this.userService.confirmNewPassword(this.email, this.verificationCode, this.password, this); } cognitoCallback(message: string) { if (message != null) { //error this.errorMessage = message; ...
}); this.errorMessage = null; } ngOnDestroy() {
random_line_split
forgotPassword.component.ts
import {Component, OnDestroy, OnInit} from "@angular/core"; import {ActivatedRoute, Router} from "@angular/router"; import {UserLoginService} from "../../../service/user-login.service"; import {CognitoCallback} from "../../../service/cognito.service"; @Component({ selector: 'awscognito-angular2-app', templateU...
else { //success this.errorMessage = message; } } } @Component({ selector: 'awscognito-angular2-app', templateUrl: './forgotPasswordStep2.html' }) export class ForgotPassword2Component implements CognitoCallback, OnInit, OnDestroy { verificationCode: string; email: string; ...
{ //error this.router.navigate(['/home/forgotPassword', this.email]); }
conditional_block
forgotPassword.component.ts
import {Component, OnDestroy, OnInit} from "@angular/core"; import {ActivatedRoute, Router} from "@angular/router"; import {UserLoginService} from "../../../service/user-login.service"; import {CognitoCallback} from "../../../service/cognito.service"; @Component({ selector: 'awscognito-angular2-app', templateU...
}
{ if (message != null) { //error this.errorMessage = message; console.log("result: " + this.errorMessage); } else { //success this.router.navigate(['/home/login']); } }
identifier_body
forgotPassword.component.ts
import {Component, OnDestroy, OnInit} from "@angular/core"; import {ActivatedRoute, Router} from "@angular/router"; import {UserLoginService} from "../../../service/user-login.service"; import {CognitoCallback} from "../../../service/cognito.service"; @Component({ selector: 'awscognito-angular2-app', templateU...
(message: string) { if (message != null) { //error this.errorMessage = message; console.log("result: " + this.errorMessage); } else { //success this.router.navigate(['/home/login']); } } }
cognitoCallback
identifier_name
sniffer_winpcap.py
# Copyright (C) 2012 Thomas "stacks" Birn (@stacksth) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program...
(self): indicators = [ ".*\\\\packet\.dll$", ".*\\\\npf\.sys$", ".*\\\\wpcap\.dll$" ] for indicator in indicators: if self.check_file(pattern=indicator, regex=True): return True return False
run
identifier_name
sniffer_winpcap.py
# Copyright (C) 2012 Thomas "stacks" Birn (@stacksth) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program...
indicators = [ ".*\\\\packet\.dll$", ".*\\\\npf\.sys$", ".*\\\\wpcap\.dll$" ] for indicator in indicators: if self.check_file(pattern=indicator, regex=True): return True return False
identifier_body
sniffer_winpcap.py
# Copyright (C) 2012 Thomas "stacks" Birn (@stacksth) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program...
return False
if self.check_file(pattern=indicator, regex=True): return True
conditional_block
sniffer_winpcap.py
# Copyright (C) 2012 Thomas "stacks" Birn (@stacksth) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program...
# along with this program. If not, see <http://www.gnu.org/licenses/>. from lib.cuckoo.common.abstracts import Signature class InstallsWinpcap(Signature): name = "sniffer_winpcap" description = "Installs WinPCAP" severity = 3 categories = ["sniffer"] authors = ["Thomas Birn", "nex"] minimum =...
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License
random_line_split
index.js
import lazyLoading from './../../store/modules/routeConfig/lazyLoading' export default { name: 'UI Features', expanded: false, sidebarMeta: { title: 'UI Features', icon: 'ion-android-laptop', order: 1 }, subMenu: [{ name: 'Panels', path: '/ui/panels', component: lazyLoading('ui/panels'...
/** * Created by Cai Kang Jie on 2017/7/31. */
random_line_split
blog-dashboard-navbar-breadcrumb.component.spec.ts
// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distribu...
// Copyright 2021 The Oppia Authors. All Rights Reserved.
random_line_split
blog-dashboard-navbar-breadcrumb.component.spec.ts
// Copyright 2021 The Oppia Authors. 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 ap...
() { return this.location._hashChange; }, }; } beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule, ], declarations: [ BlogDashboardNavbarBreadcrumbComponent, ], providers: [ BlogDashboardPag...
onhashchange
identifier_name
dest.js
var through = require('through2'); var should = require('should'); var dat = require('dat'); var File = require('vinyl'); var bops = require('bops'); var vdat = require('..'); describe('dest stream', function () { var destPath = 'test/data/test-dest'; beforeEach(function (done) { var db = dat(destPath, func...
}); }); });
}); output.write(expected); output.end();
random_line_split
url.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/. */ //! Common handling for the specified value CSS url() values. use cssparser::CssStringWriter; use gecko_bindings:...
(&self) -> ServoBundledURI { let (ptr, len) = self.as_slice_components(); ServoBundledURI { mURLString: ptr, mURLStringLength: len as u32, mExtraData: self.extra_data.get(), } } } impl ToCss for SpecifiedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt:...
for_ffi
identifier_name
url.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/. */ //! Common handling for the specified value CSS url() values. use cssparser::CssStringWriter; use gecko_bindings:...
} /// Little helper for Gecko's ffi. pub fn as_slice_components(&self) -> (*const u8, usize) { (self.serialization.as_str().as_ptr(), self.serialization.as_str().len()) } /// Create a bundled URI suitable for sending to Gecko /// to be constructed into a css::URLValue pub fn for_ff...
pub fn as_str(&self) -> &str { &*self.serialization
random_line_split