file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
udp-multicast.rs
use std::{env, str}; use std::net::{UdpSocket, Ipv4Addr}; fn main() { let mcast_group: Ipv4Addr = "239.0.0.1".parse().unwrap(); let port: u16 = 6000; let any = "0.0.0.0".parse().unwrap(); let mut buffer = [0u8; 1600]; if env::args().count() > 1
else { let socket = UdpSocket::bind((any, 0)).expect("Could not bind socket"); socket.send_to("Hello world!".as_bytes(), &(mcast_group, port)).expect("Failed to write data"); } }
{ let socket = UdpSocket::bind((any, port)).expect("Could not bind client socket"); socket.join_multicast_v4(&mcast_group, &any).expect("Could not join multicast group"); socket.recv_from(&mut buffer).expect("Failed to write to server"); print!("{}", str::from_utf8(&buffe...
conditional_block
udp-multicast.rs
use std::{env, str}; use std::net::{UdpSocket, Ipv4Addr}; fn main()
{ let mcast_group: Ipv4Addr = "239.0.0.1".parse().unwrap(); let port: u16 = 6000; let any = "0.0.0.0".parse().unwrap(); let mut buffer = [0u8; 1600]; if env::args().count() > 1 { let socket = UdpSocket::bind((any, port)).expect("Could not bind client socket"); socket.join_mul...
identifier_body
bgp.py
# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation. # # 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 appli...
def from_inet_ptoi(bgp_id): """Convert an IPv4 address string format to a four byte long. """ four_byte_id = None try: packed_byte = socket.inet_pton(socket.AF_INET, bgp_id) four_byte_id = int(packed_byte.encode('hex'), 16) except ValueError: LOG.debug('Invalid bgp id given ...
is_withdraw=path.is_withdraw)
random_line_split
bgp.py
# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation. # # 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 appli...
(): """Construct end-of-rib (EOR) Update instance.""" mpunreach_attr = BGPPathAttributeMpUnreachNLRI(RF_IPv4_VPN.afi, RF_IPv4_VPN.safi, []) eor = BGPUpdate(path_attributes=[mpunreach_attr]) return eor ...
create_end_of_rib_update
identifier_name
bgp.py
# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation. # # 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 appli...
def clone_rtcpath_update_rt_as(path, new_rt_as): """Clones given RT NLRI `path`, and updates it with new RT_NLRI AS. Parameters: - `path`: (Path) RT_NLRI path - `new_rt_as`: AS value of cloned paths' RT_NLRI """ assert path and new_rt_as if not path or path.route_fami...
assert path and med route_family = path.route_family if route_family not in _ROUTE_FAMILY_TO_PATH_MAP.keys(): raise ValueError('Clone is not supported for address-family %s' % route_family) path_cls = _ROUTE_FAMILY_TO_PATH_MAP.get(route_family) pattrs = path.pathattr_map...
identifier_body
bgp.py
# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation. # # 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 appli...
old_nlri = path.nlri new_rt_nlri = RouteTargetMembershipNLRI(new_rt_as, old_nlri.route_target) return RtcPath(path.source, new_rt_nlri, path.source_version_num, pattrs=path.pathattr_map, nexthop=path.nexthop, is_withdraw=path.is_withdraw) def from_inet_ptoi(bgp_id): ...
raise ValueError('Expected RT_NLRI path')
conditional_block
mod.rs
//! Messaging primitives for discovering devices and services. use std::io; #[cfg(windows)] use std::net; use std::net::SocketAddr; use net::connector::UdpConnector; use net::IpVersionMode; mod notify; mod search; mod ssdp; pub mod listen; pub mod multicast; pub use message::multicast::Multicast; pub use message::s...
} // Filter all loopback and global IPv6 addresses SocketAddr::V6(n) if !n.ip().is_loopback() && !n.ip().is_global() => { if let Some(x) = try!(f(&addr)) { obj_list.push(x); } } _ => (), } } ...
{ obj_list.push(x); }
conditional_block
mod.rs
//! Messaging primitives for discovering devices and services. use std::io; #[cfg(windows)] use std::net; use std::net::SocketAddr; use net::connector::UdpConnector; use net::IpVersionMode; mod notify; mod search; mod ssdp; pub mod listen; pub mod multicast; pub use message::multicast::Multicast; pub use message::s...
self.ttl = value; self } pub fn set_mode(mut self, value: IpVersionMode) -> Self { self.mode = value; self } } impl Default for Config { fn default() -> Self { Config { ipv4_addr: UPNP_MULTICAST_IPV4_ADDR.to_string(), ipv6_addr: UPNP_MULT...
} pub fn set_ttl(mut self, value: u32) -> Self {
random_line_split
mod.rs
//! Messaging primitives for discovering devices and services. use std::io; #[cfg(windows)] use std::net; use std::net::SocketAddr; use net::connector::UdpConnector; use net::IpVersionMode; mod notify; mod search; mod ssdp; pub mod listen; pub mod multicast; pub use message::multicast::Multicast; pub use message::s...
pub fn set_ipv6_addr<S: Into<String>>(mut self, value: S) -> Self { self.ipv6_addr = value.into(); self } pub fn set_port(mut self, value: u16) -> Self { self.port = value; self } pub fn set_ttl(mut self, value: u32) -> Self { self.ttl = value; sel...
{ self.ipv4_addr = value.into(); self }
identifier_body
mod.rs
//! Messaging primitives for discovering devices and services. use std::io; #[cfg(windows)] use std::net; use std::net::SocketAddr; use net::connector::UdpConnector; use net::IpVersionMode; mod notify; mod search; mod ssdp; pub mod listen; pub mod multicast; pub use message::multicast::Multicast; pub use message::s...
() -> io::Result<Vec<SocketAddr>> { let iface_iter = try!(ifaces::Interface::get_all()).into_iter(); Ok(iface_iter.filter(|iface| iface.kind != ifaces::Kind::Packet) .filter_map(|iface| iface.addr) .collect()) }
get_local_addrs
identifier_name
speech-recognition.js
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(d...
* // Request permissions * SpeechRecognition.requestPermission() * .then( * () => console.log('Granted'), * () => console.log('Denied') * ) * * ``` */ export var SpeechRecognition = (function () { function SpeechRecognition() { } /** * Check feature available * @return {Promis...
random_line_split
speech-recognition.js
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(d...
() { } /** * Check feature available * @return {Promise<boolean>} */ SpeechRecognition.isRecognitionAvailable = function () { return; }; /** * Start the recognition process * @return {Promise< Array<string> >} list of recognized terms */ SpeechRecognition.st...
SpeechRecognition
identifier_name
speech-recognition.js
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(d...
/** * Check feature available * @return {Promise<boolean>} */ SpeechRecognition.isRecognitionAvailable = function () { return; }; /** * Start the recognition process * @return {Promise< Array<string> >} list of recognized terms */ SpeechRecognition.startListeni...
{ }
identifier_body
operation_display.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
"""The object that represents the operation. :param provider: Service provider: Microsoft.ResourceProvider :type provider: str :param resource: Resource on which the operation is performed: Profile, endpoint, etc. :type resource: str :param operation: Operation type: Read, write, delete, etc. ...
identifier_body
operation_display.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(Model): """The object that represents the operation. :param provider: Service provider: Microsoft.ResourceProvider :type provider: str :param resource: Resource on which the operation is performed: Profile, endpoint, etc. :type resource: str :param operation: Operation type: Read, write, ...
OperationDisplay
identifier_name
operation_display.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
:param provider: Service provider: Microsoft.ResourceProvider :type provider: str :param resource: Resource on which the operation is performed: Profile, endpoint, etc. :type resource: str :param operation: Operation type: Read, write, delete, etc. :type operation: str :param descriptio...
class OperationDisplay(Model): """The object that represents the operation.
random_line_split
win.rs
use std::fs; use std::path::Path; use app_dirs::{self, AppDataType}; use util::*; const CG_MN_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cg.dll"; const CG_GL_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgGL.dll"; const CG_D9_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgD3D9.dll"; #[c...
tempdir::TempDir; let target = TempDir::new("lolupdater-cg-target").unwrap(); download_cg(&target.path().join("cg")).unwrap(); } fn backup_cg() -> Result<()> { let cg_backup = app_dirs::get_app_dir(AppDataType::UserData, &APP_INFO, "Backups/Cg")?; if cg_backup.exists() { info!("Skipping NVIDIA...
works() { use
identifier_name
win.rs
use std::fs; use std::path::Path; use app_dirs::{self, AppDataType}; use util::*; const CG_MN_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cg.dll"; const CG_GL_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgGL.dll"; const CG_D9_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgD3D9.dll"; #[c...
nfo!("Restoring Nvidia Cg…"); update_cg(&cg_backup_path)?; fs::remove_dir_all(&cg_backup_path)?; info!("Removing Nvidia Cg backup…"); let cg_cache_path = app_dirs::get_app_dir(AppDataType::UserCache, &APP_INFO, "Cg")?; if cg_cache_path.exists() { info!("Removing Nvidia Cg download cache…");...
return Err("No Cg backup found!".into()); } i
conditional_block
win.rs
use std::fs; use std::path::Path; use app_dirs::{self, AppDataType}; use util::*; const CG_MN_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cg.dll"; const CG_GL_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgGL.dll"; const CG_D9_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgD3D9.dll"; #[c...
&LOLSLN_GC_PATH.with(|k| k.clone()).join("cgD3D9.dll"), )?; Ok(()) }
random_line_split
win.rs
use std::fs; use std::path::Path; use app_dirs::{self, AppDataType}; use util::*; const CG_MN_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cg.dll"; const CG_GL_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgGL.dll"; const CG_D9_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgD3D9.dll"; #[c...
cg(cg_dir: &Path) -> Result<()> { update_file( &cg_dir.join("Cg.dll"), &LOLP_GC_PATH.with(|k| k.clone()).join("Cg.dll"), )?; update_file( &cg_dir.join("CgGL.dll"), &LOLP_GC_PATH.with(|k| k.clone()).join("CgGL.dll"), )?; update_file( &cg_dir.join("cgD3D9.dll"),...
_backup = app_dirs::get_app_dir(AppDataType::UserData, &APP_INFO, "Backups/Cg")?; if cg_backup.exists() { info!("Skipping NVIDIA Cg backup! (Already exists)"); } else { fs::create_dir(&cg_backup)?; update_file( &LOLP_GC_PATH.with(|k| k.clone()).join("Cg.dll"), &cg...
identifier_body
0006_auto_20190926_1218.py
# Generated by Django 2.2.5 on 2019-09-26 12:18 from django.db import migrations, models import weblate.utils.backup class Migration(migrations.Migration):
dependencies = [("wladmin", "0005_auto_20190926_1332")] operations = [ migrations.AddField( model_name="backupservice", name="paperkey", field=models.TextField(default=""), preserve_default=False, ), migrations.AddField( model_name...
identifier_body
0006_auto_20190926_1218.py
# Generated by Django 2.2.5 on 2019-09-26 12:18 from django.db import migrations, models import weblate.utils.backup class Migration(migrations.Migration): dependencies = [("wladmin", "0005_auto_20190926_1332")] operations = [ migrations.AddField(
model_name="backupservice", name="paperkey", field=models.TextField(default=""), preserve_default=False, ), migrations.AddField( model_name="backupservice", name="passphrase", field=models.CharField( defa...
random_line_split
0006_auto_20190926_1218.py
# Generated by Django 2.2.5 on 2019-09-26 12:18 from django.db import migrations, models import weblate.utils.backup class
(migrations.Migration): dependencies = [("wladmin", "0005_auto_20190926_1332")] operations = [ migrations.AddField( model_name="backupservice", name="paperkey", field=models.TextField(default=""), preserve_default=False, ), migrations.Add...
Migration
identifier_name
guess-the-number.rs
use std::string::String; use std::fs::File; use std::io::{Read, BufRead}; static mut TRIES_LEFT: i32 = 5; static mut RAND_INT: i32 = -1; static mut GUESS: i32 = -1; fn main() { unsafe { // Open /dev/random let mut devrandom = File::open("/dev/random").unwrap(); // Create a 1 byte large buffer let ...
TRIES_LEFT -= 1; if GUESS == RAND_INT { println!("🎉 YOU WIN 🎉"); break; } else if GUESS > RAND_INT { println!("Too high, guy."); } else { println!("Too low, bro."); } } } }
random_line_split
guess-the-number.rs
use std::string::String; use std::fs::File; use std::io::{Read, BufRead}; static mut TRIES_LEFT: i32 = 5; static mut RAND_INT: i32 = -1; static mut GUESS: i32 = -1; fn main()
{ unsafe { // Open /dev/random let mut devrandom = File::open("/dev/random").unwrap(); // Create a 1 byte large buffer let mut randombyte: [u8; 1] = [0]; // Read exactly 1 byte from /dev/random1 byte wide buffer devrandom.read_exact(&mut randombyte).unwrap(); // Clamp it to 0-100 with mo...
identifier_body
guess-the-number.rs
use std::string::String; use std::fs::File; use std::io::{Read, BufRead}; static mut TRIES_LEFT: i32 = 5; static mut RAND_INT: i32 = -1; static mut GUESS: i32 = -1; fn
() { unsafe { // Open /dev/random let mut devrandom = File::open("/dev/random").unwrap(); // Create a 1 byte large buffer let mut randombyte: [u8; 1] = [0]; // Read exactly 1 byte from /dev/random1 byte wide buffer devrandom.read_exact(&mut randombyte).unwrap(); // Clamp it to 0-100 with...
main
identifier_name
AnnotationNote.tsx
import { createElement } from 'react' import omit from 'lodash/omit' import { useSpring, animated } from '@react-spring/web' import { useTheme, useMotionConfig } from '@nivo/core' import { NoteSvg } from './types' export const AnnotationNote = <Datum,>({ datum, x, y, note, }: { datum: Datum x: ...
const animatedProps = useSpring({ x, y, config: springConfig, immediate: !animate, }) if (typeof note === 'function') { return createElement(note, { x, y, datum }) } return ( <> {theme.annotations.text.outlineWidth > 0 && ( ...
}) => { const theme = useTheme() const { animate, config: springConfig } = useMotionConfig()
random_line_split
AnnotationNote.tsx
import { createElement } from 'react' import omit from 'lodash/omit' import { useSpring, animated } from '@react-spring/web' import { useTheme, useMotionConfig } from '@nivo/core' import { NoteSvg } from './types' export const AnnotationNote = <Datum,>({ datum, x, y, note, }: { datum: Datum x: ...
return ( <> {theme.annotations.text.outlineWidth > 0 && ( <animated.text x={animatedProps.x} y={animatedProps.y} style={{ ...theme.annotations.text, strokeLinejoin: 'roun...
{ return createElement(note, { x, y, datum }) }
conditional_block
synapsecollection.py
# -*- coding: utf-8 -*- # # synapsecollection.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 2 of the Licen...
return aa def plotMatrix(srcs, tgts, weights, title, pos): """ Plots weight matrix. """ plt.subplot(pos) plt.matshow(makeMatrix(srcs, tgts, weights), fignum=False) plt.xlim([min(tgts)-0.5, max(tgts)+0.5]) plt.xlabel('target') plt.ylim([max(srcs)+0.5, min(srcs)-0.5]) plt.ylabe...
aa[src, trg] += wght
conditional_block
synapsecollection.py
# -*- coding: utf-8 -*- # # synapsecollection.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 2 of the Licen...
def plotMatrix(srcs, tgts, weights, title, pos): """ Plots weight matrix. """ plt.subplot(pos) plt.matshow(makeMatrix(srcs, tgts, weights), fignum=False) plt.xlim([min(tgts)-0.5, max(tgts)+0.5]) plt.xlabel('target') plt.ylim([max(srcs)+0.5, min(srcs)-0.5]) plt.ylabel('source') ...
""" Returns a matrix with the weights between the source and target node_ids. """ aa = np.zeros((max(sources)+1, max(targets)+1)) for src, trg, wght in zip(sources, targets, weights): aa[src, trg] += wght return aa
identifier_body
synapsecollection.py
# -*- coding: utf-8 -*- # # synapsecollection.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 2 of the Licen...
nest.Connect(nrns[5:10], nrns[:5], {'rule': 'fixed_total_number', 'N': 5}, {'weight': 3.0}) nest.Connect(nrns[10:], nrns[:12], 'all_to_all', {'synapse_model': 'stdp_synapse', 'weight': {'distribution': 'uniform', 'low': 1., 'high': 5.}}) nest.Connect(nrn...
random_line_split
synapsecollection.py
# -*- coding: utf-8 -*- # # synapsecollection.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 2 of the Licen...
(sources, targets, weights): """ Returns a matrix with the weights between the source and target node_ids. """ aa = np.zeros((max(sources)+1, max(targets)+1)) for src, trg, wght in zip(sources, targets, weights): aa[src, trg] += wght return aa def plotMatrix(srcs, tgts, weights, titl...
makeMatrix
identifier_name
esprelay.py
#!/usr/bin/env python # # Simple TCP line-based text chat server. Clients connect and send a # conversation ID (any string) as the first line, then they are connected # to other clients who sent the same conversation ID. # # Uses a thread pair per connection, so not highly scalable. from Queue import Queue, Empty fro...
class ConversationConnectionHandler(StreamRequestHandler): """Handles TCP connections with the conversation protocol""" def __init__(self, request, client_address, server): self._conversation_id = None self._messages = Queue() # This is a blocking call, so we have to set our fields b...
"""Prints a line about which handlers are attached to a conversation""" handler_addrs = sorted(['%s:%d' % h.client_address for h in handlers]) handlers_str = '(%s)' % (', '.join(handler_addrs)) print('conversation "%s" -> %s' % (conversation_id, handlers_str))
identifier_body
esprelay.py
#!/usr/bin/env python # # Simple TCP line-based text chat server. Clients connect and send a # conversation ID (any string) as the first line, then they are connected # to other clients who sent the same conversation ID. # # Uses a thread pair per connection, so not highly scalable. from Queue import Queue, Empty fro...
line = self.rfile.readline() except error: # Client disconnected or other socket error break if not line: # Client disconnected break # Send the message to each connected client with conversat...
# Spawn another thread to handle writes Thread(target=self._write_handler).start() while True: try:
random_line_split
esprelay.py
#!/usr/bin/env python # # Simple TCP line-based text chat server. Clients connect and send a # conversation ID (any string) as the first line, then they are connected # to other clients who sent the same conversation ID. # # Uses a thread pair per connection, so not highly scalable. from Queue import Queue, Empty fro...
self._conversation_id = line.strip() # Register this handler instance for the conversation ID with conversations_lock: handlers = conversations[self._conversation_id] handlers.add(self) print_conversation(self._conversation_id, handlers) # Spawn an...
return
conditional_block
esprelay.py
#!/usr/bin/env python # # Simple TCP line-based text chat server. Clients connect and send a # conversation ID (any string) as the first line, then they are connected # to other clients who sent the same conversation ID. # # Uses a thread pair per connection, so not highly scalable. from Queue import Queue, Empty fro...
(self, request, client_address, server): self._conversation_id = None self._messages = Queue() # This is a blocking call, so we have to set our fields before calling StreamRequestHandler.__init__(self, request, client_address, server) def setup(self): print('connect %s:%d' %...
__init__
identifier_name
account.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(&self) -> Account { Account { balance: self.balance.clone(), nonce: self.nonce.clone(), storage_root: self.storage_root.clone(), storage_cache: Self::empty_storage_cache(), storage_changes: HashMap::new(), code_hash: self.code_hash.clone(), code_size: self.code_size.clone(), code_cache: self....
clone_basic
identifier_name
account.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
/// Increase account balance. pub fn add_balance(&mut self, x: &U256) { self.balance = self.balance + *x; } /// Decrease account balance. /// Panics if balance is less than `x` pub fn sub_balance(&mut self, x: &U256) { assert!(self.balance >= *x); self.balance = self.balance - *x; } /// Commit the `st...
{ self.nonce = self.nonce + U256::from(1u8); }
identifier_body
account.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
let mut a = Account::new_contract(69.into(), 0.into()); a.set_storage(H256::from(&U256::from(0x00u64)), H256::from(&U256::from(0x1234u64))); a.commit_storage(&Default::default(), &mut db); a.init_code(vec![]); a.commit_code(&mut db); a.rlp() }; let a = Account::from_rlp(&rlp); assert_eq!(a.stor...
fn storage_at() { let mut db = MemoryDB::new(); let mut db = AccountDBMut::new(&mut db, &Address::new()); let rlp = {
random_line_split
account.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
, _ => { warn!("Failed reverse get of {}", self.code_hash); None }, } } /// Provide code to cache. For correctness, should be the correct code for the /// account. pub fn cache_given_code(&mut self, code: Arc<Bytes>) { trace!("Account::cache_given_code: ic={}; self.code_hash={:?}, self.code_cache...
{ self.code_size = Some(x.len()); self.code_cache = Arc::new(x.to_vec()); Some(self.code_cache.clone()) }
conditional_block
fsu-moves-and-copies.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 b = MoveFoo {moved: box 13, ..f}; let c = MoveFoo {copied: 14, ..f}; assert_eq!(b.copied, 11); assert_eq!(*b.moved, 13); assert_eq!(c.copied, 14); assert_eq!(*c.moved, 12); } fn test2() { // move non-copyable field let f = NoFoo::new(21, 22); let b = NoFoo {nocopy: n...
// copying move-by-default fields from `f`, so it moves: let f = MoveFoo::new(11, 12);
random_line_split
fsu-moves-and-copies.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...
} impl Drop for DropMoveFoo { fn drop(&mut self) { } } fn test0() { // just copy implicitly copyable fields from `f`, no moves // (and thus it is okay that these are Drop; compare against // compile-fail test: borrowck-struct-update-with-dtor.rs). // Case 1: Nocopyable let f = DropNoFoo::new(1, ...
{ DropMoveFoo { inner: MoveFoo::new(x,y) } }
identifier_body
fsu-moves-and-copies.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...
(x:int,y:int) -> MoveFoo { MoveFoo { copied: x, moved: box y } } } struct DropNoFoo { inner: NoFoo } impl DropNoFoo { fn new(x:int,y:int) -> DropNoFoo { DropNoFoo { inner: NoFoo::new(x,y) } } } impl Drop for DropNoFoo { fn drop(&mut self) { } } struct DropMoveFoo { inner: MoveFoo } impl DropMoveFoo { fn new(x...
new
identifier_name
transactionPending.js
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
renderGasEditor () { const { className } = this.props; return ( <div className={ `${styles.container} ${className}` }> <GasPriceEditor store={ this.gasStore }> <Button label='view transaction' onClick={ this.toggleGasEditor } /> </GasPriceEdi...
random_line_split
transactionPending.js
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
() { const { className } = this.props; return ( <div className={ `${styles.container} ${className}` }> <GasPriceEditor store={ this.gasStore }> <Button label='view transaction' onClick={ this.toggleGasEditor } /> </GasPriceEditor> </div> ...
renderGasEditor
identifier_name
transactionPending.js
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
onConfirm = (data) => { const { id, transaction } = this.props; const { password, wallet } = data; const { gas, gasPrice } = this.gasStore.overrideTransaction(transaction); this.props.onConfirm({ gas, gasPrice, id, password, wallet }); } onReject = () => { ...
{ const { className } = this.props; return ( <div className={ `${styles.container} ${className}` }> <GasPriceEditor store={ this.gasStore }> <Button label='view transaction' onClick={ this.toggleGasEditor } /> </GasPriceEditor> </div> ...
identifier_body
ng_component_outlet.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ComponentFactoryResolver, ComponentRef, Directive, Injector, Input, NgModuleFactory, NgModuleRef, OnChanges,...
* ``` * * ### A simple example * * {@example common/ngComponentOutlet/ts/module.ts region='SimpleExample'} * * A more complete example with additional options: * * {@example common/ngComponentOutlet/ts/module.ts region='CompleteExample'} * A more complete example with ngModuleFactory: * * {@example common/...
* ngModuleFactory: moduleFactory;"> * </ng-container>
random_line_split
ng_component_outlet.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ComponentFactoryResolver, ComponentRef, Directive, Injector, Input, NgModuleFactory, NgModuleRef, OnChanges,...
() { if (this._moduleRef) this._moduleRef.destroy(); } }
ngOnDestroy
identifier_name
ng_component_outlet.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ComponentFactoryResolver, ComponentRef, Directive, Injector, Input, NgModuleFactory, NgModuleRef, OnChanges,...
ngOnDestroy() { if (this._moduleRef) this._moduleRef.destroy(); } }
{ this._viewContainerRef.clear(); this._componentRef = null; if (this.ngComponentOutlet) { const elInjector = this.ngComponentOutletInjector || this._viewContainerRef.parentInjector; if (changes['ngComponentOutletNgModuleFactory']) { if (this._moduleRef) this._moduleRef.destroy(); ...
identifier_body
index.ts
import * as nodes from './nodes' import {BaseNode, Tick, State, Tree, Blackboard} from './BaseNode' export function buildNode(data: IDataBehaviorNode) { var type = data.nodeType var node: BaseNode = new nodes[type]() node.config = data.config if (data.children.length > 0) { if (node instanceof ...
export {BaseNode, Tick, State, Tree, Blackboard, nodes}
{ if (nodes[name]) throw new Error('nodeType already exist:' + name) nodes[name] = func }
identifier_body
index.ts
import * as nodes from './nodes' import {BaseNode, Tick, State, Tree, Blackboard} from './BaseNode' export function buildNode(data: IDataBehaviorNode) { var type = data.nodeType var node: BaseNode = new nodes[type]() node.config = data.config if (data.children.length > 0) {
var childNode = buildNode(data.children[0]) node.addChild(childNode) } else if (node instanceof nodes.Composite) { for (var i = 0; i < data.children.length; i++) { var childNode = buildNode(data.children[i]) node.addChild(childNode) ...
if (node instanceof nodes.Decorator) {
random_line_split
index.ts
import * as nodes from './nodes' import {BaseNode, Tick, State, Tree, Blackboard} from './BaseNode' export function
(data: IDataBehaviorNode) { var type = data.nodeType var node: BaseNode = new nodes[type]() node.config = data.config if (data.children.length > 0) { if (node instanceof nodes.Decorator) { var childNode = buildNode(data.children[0]) node.addChild(childNode) } else...
buildNode
identifier_name
IRIS_DF_Controller.py
#!/usr/bin/env python '''====================================================== Created by: D. Spencer Maughan Last updated: May 2015 File name: IRIS_DF_Controller.py Organization: RISC Lab, Utah State University
Notes: ======================================================''' import roslib; roslib.load_manifest('risc_msgs') import rospy from math import * import numpy as np import time #=======================# # Messages Needed # #=======================# from risc_msgs.msg import * from std_msgs.ms...
random_line_split
IRIS_DF_Controller.py
#!/usr/bin/env python '''====================================================== Created by: D. Spencer Maughan Last updated: May 2015 File name: IRIS_DF_Controller.py Organization: RISC Lab, Utah State University Notes: ======================================================''' import roslib;...
import sys rospy.init_node('IRIS_DF_Controller') #=====================================# # Set up Publish/Subscribe Loop # #=====================================# r = rospy.Rate(rate) while not rospy.is_shutdown(): sub_cortex = rospy.Subscriber('/cortex_raw' , Cortex, GetStates,...
conditional_block
IRIS_DF_Controller.py
#!/usr/bin/env python '''====================================================== Created by: D. Spencer Maughan Last updated: May 2015 File name: IRIS_DF_Controller.py Organization: RISC Lab, Utah State University Notes: ======================================================''' import roslib;...
(S): global ctrl_status ctrl_status = S.data #========================# # Basic Controller # #========================# def Basic_Controller(): global states, euler_max, max_yaw_rate, pub_ctrl,K,traj Ctrl = Controls() Ctrl.Obj = [Control()]*1 Ctrl.header.stamp = s...
GetStatus
identifier_name
IRIS_DF_Controller.py
#!/usr/bin/env python '''====================================================== Created by: D. Spencer Maughan Last updated: May 2015 File name: IRIS_DF_Controller.py Organization: RISC Lab, Utah State University Notes: ======================================================''' import roslib;...
def GetStatus(S): global ctrl_status ctrl_status = S.data #========================# # Basic Controller # #========================# def Basic_Controller(): global states, euler_max, max_yaw_rate, pub_ctrl,K,traj Ctrl = Controls() Ctrl.Obj = [Control()]*1 Ctrl.h...
global nominal_thrust B = S.battery_remaining # coefficients for fourth order fit # determined 11 May 2015 by Spencer Maughan and Ishmaal Erekson c0 = 0.491674747062374 c1 = -0.024809293286468 c2 = 0.000662710609466 c3 = -0.000008160593348 c4 = 0.000000033699651 nominal_thrust = c...
identifier_body
NodePush.ts
/* * Copyright (c) 2012 - 2020, Tim Düsterhus * * 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. * * ...
}); socket.on("rekey", (newToken: string) => { token = newToken; }); socket.on("authenticated", () => { this.connected = true; }); socket.on("disconnect", () => { this.connected = false; }); this.initResolve(socket); } catch (err) { co...
socket.emit("token", token); }
conditional_block
NodePush.ts
/* * Copyright (c) 2012 - 2020, Tim Düsterhus * * 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. * * ...
/** * Connect to the given host and provide the given signed authentication string. */ async init(host: string, connectData: string): Promise<void> { if (this.initialized) { return; } this.initialized = true; try { const socket = (await import("socket.io-client")).default(host);...
this.waitForInit = new Promise((resolve, reject) => { this.initResolve = resolve; this.initReject = reject; }); }
identifier_body
NodePush.ts
/* * Copyright (c) 2012 - 2020, Tim Düsterhus * * 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. * * ...
message: string, callback: (payload: unknown) => unknown ): Promise<void> { if (!/^[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)+$/.test(message)) { throw new Error("Invalid message identifier"); } const socket = await this.waitForInit; socket.on(message, (payload: unknown) => { ...
nMessage(
identifier_name
NodePush.ts
/* * Copyright (c) 2012 - 2020, Tim Düsterhus * * 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. * * ...
socket.on(message, (payload: unknown) => { callback(payload); }); } } export = new NodePush();
const socket = await this.waitForInit;
random_line_split
linktest_rsp_header.py
##################################################################### # linktest_rsp_header.py # # (c) Copyright 2021, Benjamin Parzella. All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free...
from .header import HsmsHeader class HsmsLinktestRspHeader(HsmsHeader): """ Header for Linktest Response. Header for message with SType 6. """ def __init__(self, system): """ Initialize a hsms linktest response. :param system: message ID :type system: integer ...
##################################################################### """Header for the hsms linktest response."""
random_line_split
linktest_rsp_header.py
##################################################################### # linktest_rsp_header.py # # (c) Copyright 2021, Benjamin Parzella. All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free...
""" Initialize a hsms linktest response. :param system: message ID :type system: integer **Example**:: >>> import secsgem.hsms >>> >>> secsgem.hsms.HsmsLinktestRspHeader(10) HsmsLinktestRspHeader({sessionID:0xffff, stream:00, function:00...
identifier_body
linktest_rsp_header.py
##################################################################### # linktest_rsp_header.py # # (c) Copyright 2021, Benjamin Parzella. All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free...
(HsmsHeader): """ Header for Linktest Response. Header for message with SType 6. """ def __init__(self, system): """ Initialize a hsms linktest response. :param system: message ID :type system: integer **Example**:: >>> import secsgem.hsms ...
HsmsLinktestRspHeader
identifier_name
PostsItemMetaInfo.tsx
import React from 'react'; import { registerComponent, Components } from '../../lib/vulcan-lib'; import classNames from 'classnames' const styles = (theme: ThemeType): JssStyles => ({ root: { color: theme.palette.grey[600], fontSize: "1.1rem", display: "flex", alignItems: "center", }, }) const Pos...
component='span' className={classNames(classes.root, className)} variant='body2'> {children} </Components.Typography> } const PostsItemMetaInfoComponent = registerComponent('PostsItemMetaInfo', PostsItemMetaInfo, {styles}); declare global { interface ComponentTypes { PostsItemMetaInfo: typeo...
}) => { return <Components.Typography
random_line_split
tabmenu.py
# from pytigon_js.tools import history_push_state, correct_href, remove_element, process_resize # from pytigon_js.ajax_region import mount_html class Page: def __init__(self, id, page): self.id = id self.page = page def set_href(self, href): self.page.attr("_href", href) def get_...
def new_page(self, title, data_or_html, href, title_alt=None): _id = "tab" + self.id menu_item = TabMenuItem(_id, title, href, data_or_html) self.titles[title] = menu_item if title_alt and title_alt != title: self.titles[title_alt] = menu_item menu_pos = vsprin...
self.titles[title] = "$$$"
identifier_body
tabmenu.py
# from pytigon_js.tools import history_push_state, correct_href, remove_element, process_resize # from pytigon_js.ajax_region import mount_html class Page: def __init__(self, id, page): self.id = id self.page = page def set_href(self, href): self.page.attr("_href", href) def get_...
: def __init__(self): self.id = 0 self.titles = {} self.active_item = None def get_active_item(self): return self.active_item def is_open(self, title): if self.titles and title in self.titles and self.titles[title]: return True else: ...
TabMenu
identifier_name
tabmenu.py
# from pytigon_js.tools import history_push_state, correct_href, remove_element, process_resize # from pytigon_js.ajax_region import mount_html class Page: def __init__(self, id, page): self.id = id self.page = page def set_href(self, href): self.page.attr("_href", href) def get_...
else: window.ACTIVE_PAGE = None if window.PUSH_STATE: history_push_state("", window.BASE_PATH) if jQuery("#body_desktop").find(".content").length == 0: window.init_start_wiki_page() jQuery("#body_desktop").show() #'standard' '...
last_a.tab("show")
conditional_block
tabmenu.py
# from pytigon_js.tools import history_push_state, correct_href, remove_element, process_resize # from pytigon_js.ajax_region import mount_html class Page: def __init__(self, id, page): self.id = id self.page = page def set_href(self, href): self.page.attr("_href", href) def get_...
jQuery("#tabs2 a:last").on("shown.bs.tab", _on_show_tab) jQuery("#tabs2 a:last").tab("show") mount_html(document.getElementById(_id), data_or_html, None) def _on_button_click(self, event): get_menu().remove_page(jQuery(this).attr("id").replace("button_", "")) ...
jQuery("#tabs2 a:first").tab("show") else:
random_line_split
avi_cloudproperties.py
#!/usr/bin/python # # Created on Aug 25, 2016 # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Eric Anderson (eanderson@avinetworks.com) # module_check: supported # Avi Version: 17.1.1 # # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the te...
return avi_ansible_api(module, 'cloudproperties', set([])) if __name__ == '__main__': main()
return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.'))
conditional_block
avi_cloudproperties.py
#!/usr/bin/python # # Created on Aug 25, 2016 # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Eric Anderson (eanderson@avinetworks.com) # module_check: supported # Avi Version: 17.1.1 # # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the te...
(): argument_specs = dict( state=dict(default='present', choices=['absent', 'present']), cc_props=dict(type='dict',), cc_vtypes=dict(type='list',), hyp_props=dict(type='list',), info=dict(type='list',), url=dict(type='str',), uuid=dict(type=...
main
identifier_name
avi_cloudproperties.py
#!/usr/bin/python # # Created on Aug 25, 2016 # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Eric Anderson (eanderson@avinetworks.com) # module_check: supported # Avi Version: 17.1.1 # # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the te...
RETURN = ''' obj: description: CloudProperties (api/cloudproperties) object returned: success, changed type: dict ''' from ansible.module_utils.basic import AnsibleModule try: from ansible.module_utils.network.avi.avi import ( avi_common_argument_spec, HAS_AVI, avi_ansible_api) except ImportErr...
random_line_split
avi_cloudproperties.py
#!/usr/bin/python # # Created on Aug 25, 2016 # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Eric Anderson (eanderson@avinetworks.com) # module_check: supported # Avi Version: 17.1.1 # # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the te...
if __name__ == '__main__': main()
argument_specs = dict( state=dict(default='present', choices=['absent', 'present']), cc_props=dict(type='dict',), cc_vtypes=dict(type='list',), hyp_props=dict(type='list',), info=dict(type='list',), url=dict(type='str',), uuid=dict(type='str',),...
identifier_body
tiles.rs
use super::Tile; use colors; use pixset; use pixset::PixLike; use units; pub struct Tiles<P: PixLike> { size: units::Size2D, pub tiles: Vec<Tile<P>>, // TODO impl Index } impl<P> Tiles<P> where P: pixset::PixLike, { pub fn new(size: units::Size2D) -> Self { let tiles = { // TODO ar...
(&mut self, loc: units::ScreenTile2D, pix: P, fg: colors::Rgb, bg: colors::Rgb) { // TODO asserts let idx = (self.size.width * loc.y + loc.x) as usize; self.tiles[idx].pix = pix; self.tiles[idx].fg = fg; self.tiles[idx].bg = bg; } }
set
identifier_name
tiles.rs
use super::Tile; use colors; use pixset; use pixset::PixLike; use units; pub struct Tiles<P: PixLike> { size: units::Size2D, pub tiles: Vec<Tile<P>>, // TODO impl Index } impl<P> Tiles<P> where P: pixset::PixLike, { pub fn new(size: units::Size2D) -> Self { let tiles = { // TODO ar...
} } pub fn set(&mut self, loc: units::ScreenTile2D, pix: P, fg: colors::Rgb, bg: colors::Rgb) { // TODO asserts let idx = (self.size.width * loc.y + loc.x) as usize; self.tiles[idx].pix = pix; self.tiles[idx].fg = fg; self.tiles[idx].bg = bg; } }
#[allow(dead_code)] pub fn clear(&mut self) { for t in self.tiles.iter_mut() { t.clear();
random_line_split
hw2.py
__author__ = 'eric' import pandas as pd import numpy as np import math import copy import QSTK.qstkutil.qsdateutil as du import datetime as dt import QSTK.qstkutil.DataAccess as da import QSTK.qstkutil.tsutil as tsu import QSTK.qstkstudy.EventProfiler as ep dataObj = da.DataAccess('Yahoo') def find_events(ls_symbol...
return df_events def create_study(ls_symbols, ldt_timestamps, s_study_name): global dataObj print "Grabbing data to perform {0}".format(s_study_name) ls_keys = ['close', 'actual_close'] ldf_data = dataObj.get_data(ldt_timestamps, ls_symbols, ls_keys) print "Got data for study {0}".format(s...
df_events[s_sym].ix[ldt_timestamps[i]] = 1
conditional_block
hw2.py
__author__ = 'eric' import pandas as pd import numpy as np import math import copy import QSTK.qstkutil.qsdateutil as du import datetime as dt import QSTK.qstkutil.DataAccess as da import QSTK.qstkutil.tsutil as tsu import QSTK.qstkstudy.EventProfiler as ep dataObj = da.DataAccess('Yahoo') def find_events(ls_symbol...
(): dt_start = dt.datetime(2008, 1, 1) dt_end = dt.datetime(2009, 12, 31) ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt.timedelta(hours=16)) global dataObj ls_symbols_2012 = dataObj.get_symbols_from_list('sp5002012') ls_symbols_2012.append('SPY') ls_symbols_2008 = dataObj.get_symbo...
main
identifier_name
hw2.py
__author__ = 'eric' import pandas as pd import numpy as np import math import copy import QSTK.qstkutil.qsdateutil as du import datetime as dt import QSTK.qstkutil.DataAccess as da import QSTK.qstkutil.tsutil as tsu import QSTK.qstkstudy.EventProfiler as ep dataObj = da.DataAccess('Yahoo') def find_events(ls_symbol...
ls_symbols_2008 = dataObj.get_symbols_from_list('sp5002008') ls_symbols_2008.append('SPY') #create_study(ls_symbols_2008, ldt_timestamps, '2008Study2.pdf') create_study(ls_symbols_2012, ldt_timestamps, '2012Study2.pdf') if __name__ == '__main__': main()
ls_symbols_2012 = dataObj.get_symbols_from_list('sp5002012') ls_symbols_2012.append('SPY')
random_line_split
hw2.py
__author__ = 'eric' import pandas as pd import numpy as np import math import copy import QSTK.qstkutil.qsdateutil as du import datetime as dt import QSTK.qstkutil.DataAccess as da import QSTK.qstkutil.tsutil as tsu import QSTK.qstkstudy.EventProfiler as ep dataObj = da.DataAccess('Yahoo') def find_events(ls_symbol...
def main(): dt_start = dt.datetime(2008, 1, 1) dt_end = dt.datetime(2009, 12, 31) ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt.timedelta(hours=16)) global dataObj ls_symbols_2012 = dataObj.get_symbols_from_list('sp5002012') ls_symbols_2012.append('SPY') ls_symbols_2008 = dataOb...
global dataObj print "Grabbing data to perform {0}".format(s_study_name) ls_keys = ['close', 'actual_close'] ldf_data = dataObj.get_data(ldt_timestamps, ls_symbols, ls_keys) print "Got data for study {0}".format(s_study_name) d_data = dict(zip(ls_keys, ldf_data)) for s_key in ls_keys: ...
identifier_body
gulpfile.babel.js
'use strict'; import gulp from 'gulp'; import webpack from 'webpack'; import path from 'path'; import sync from 'run-sequence'; import rename from 'gulp-rename'; import template from 'gulp-template'; import fs from 'fs'; import yargs from 'yargs'; import lodash from 'lodash'; import gutil ...
gutil.log("[clean]", paths); cb(); }) }); gulp.task('default', ['watch']);
gulp.task('clean', (cb) => { del([paths.dest]).then(function (paths) {
random_line_split
gulpfile.babel.js
'use strict'; import gulp from 'gulp'; import webpack from 'webpack'; import path from 'path'; import sync from 'run-sequence'; import rename from 'gulp-rename'; import template from 'gulp-template'; import fs from 'fs'; import yargs from 'yargs'; import lodash from 'lodash'; import gutil ...
gutil.log("[webpack]", stats.toString({ colors: colorsSupported, chunks: false, errorDetails: true })); cb(); }); }); gulp.task('serve', () => { const config = require('./webpack.dev.config'); config.entry.app = [ // this modules required to make HRM working // it respons...
{ throw new gutil.PluginError("webpack", err); }
conditional_block
story.tsx
/* Copyright (C) 2017 Cloudbase Solutions SRL 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 distribute...
import React from 'react' import { storiesOf } from '@storybook/react' import ProgressBar from '.' // eslint-disable-next-line react/jsx-props-no-spreading const Wrapper = (props: any) => <div style={{ width: '800px' }}><ProgressBar {...props} /></div> storiesOf('ProgressBar', module) .add('default 100%', () => (...
GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */
random_line_split
bljsystem.py
""" start a gui for a binary lennard jones cluster. All that is really needed to start a gui is define a system and call run_gui system = BLJCluster(natoms, ntypeA) run_gui(system) """ import sys from PyQt4 import QtGui from pele.systems import BLJCluster from pele.gui import run_gui from _blj_dialog impo...
def on_buttonBox_accepted(self): self.get_input() self.close() def on_buttonBox_rejected(self): self.close() if __name__ == "__main__": # create a pop up window to get the number of atoms app = QtGui.QApplication(sys.argv) dialog = BLJDialog() dialog.exec_() ...
self.natoms = int(self.ui.lineEdit_natoms.text()) self.ntypeA = int(self.ui.lineEdit_ntypeA.text()) self.sigAB = float(self.ui.lineEdit_sigAB.text()) self.epsAB = float(self.ui.lineEdit_epsAB.text()) self.sigBB = float(self.ui.lineEdit_sigBB.text()) self.epsBB = float(self.ui.lin...
identifier_body
bljsystem.py
""" start a gui for a binary lennard jones cluster. All that is really needed to start a gui is define a system and call run_gui system = BLJCluster(natoms, ntypeA) run_gui(system) """ import sys from PyQt4 import QtGui from pele.systems import BLJCluster from pele.gui import run_gui from _blj_dialog impo...
(self): self.natoms = int(self.ui.lineEdit_natoms.text()) self.ntypeA = int(self.ui.lineEdit_ntypeA.text()) self.sigAB = float(self.ui.lineEdit_sigAB.text()) self.epsAB = float(self.ui.lineEdit_epsAB.text()) self.sigBB = float(self.ui.lineEdit_sigBB.text()) self.epsBB = f...
get_input
identifier_name
bljsystem.py
""" start a gui for a binary lennard jones cluster. All that is really needed to start a gui is define a system and call run_gui system = BLJCluster(natoms, ntypeA) run_gui(system) """ import sys from PyQt4 import QtGui from pele.systems import BLJCluster from pele.gui import run_gui from _blj_dialog impo...
def get_input(self): self.natoms = int(self.ui.lineEdit_natoms.text()) self.ntypeA = int(self.ui.lineEdit_ntypeA.text()) self.sigAB = float(self.ui.lineEdit_sigAB.text()) self.epsAB = float(self.ui.lineEdit_epsAB.text()) self.sigBB = float(self.ui.lineEdit_sigBB.text()) ...
random_line_split
bljsystem.py
""" start a gui for a binary lennard jones cluster. All that is really needed to start a gui is define a system and call run_gui system = BLJCluster(natoms, ntypeA) run_gui(system) """ import sys from PyQt4 import QtGui from pele.systems import BLJCluster from pele.gui import run_gui from _blj_dialog impo...
print dialog.ntypeA, "A atoms interacting with eps", dialog.epsAA, "sig", dialog.sigAA print dialog.natoms - dialog.ntypeA, "B atoms interacting with eps", dialog.epsBB, "sig", dialog.sigBB print "The A and B atoms interact with eps", dialog.epsAB, "sig", dialog.sigAB # create the system and star...
sys.exit()
conditional_block
CommentsMenu.tsx
import React, { useState } from 'react'; import { registerComponent, Components } from '../../../lib/vulcan-lib'; import MoreVertIcon from '@material-ui/icons/MoreVert'; import Menu from '@material-ui/core/Menu'; import { useCurrentUser } from '../../common/withUser'; import { useTracking } from "../../../lib/analytics...
icon?: any, }) => { const [anchorEl, setAnchorEl] = useState<any>(null); // Render menu-contents if the menu has ever been opened (keep rendering // contents when closed after open, because of closing animation). const [everOpened, setEverOpened] = useState(false); const currentUser = useCurrentUser()...
classes: ClassesType, className?: string, comment: CommentsList, post?: PostsMinimumInfo, showEdit: ()=>void,
random_line_split
feature_artist.py
# (C) British Crown Copyright 2011 - 2015, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option)...
""" A subclass of :class:`~matplotlib.artist.Artist` capable of drawing a :class:`cartopy.feature.Feature`. """ _geometry_to_path_cache = weakref.WeakKeyDictionary() """ A nested mapping from geometry and target projection to the resulting transformed matplotlib paths:: {geom: {tar...
identifier_body
feature_artist.py
# (C) British Crown Copyright 2011 - 2015, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option)...
(self, feature, **kwargs): """ Args: * feature: an instance of :class:`cartopy.feature.Feature` to draw. * kwargs: keyword arguments to be used when drawing the feature. These will override those shared with the feature. """ super(Fea...
__init__
identifier_name
feature_artist.py
# (C) British Crown Copyright 2011 - 2015, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option)...
self._kwargs = dict(kwargs) # Set default zorder so that features are drawn before # lines e.g. contours but after images. # Note that the zorder of Patch, PatchCollection and PathCollection # are all 1 by default. Assuming equal zorder drawing takes place in # the foll...
kwargs = {}
conditional_block
feature_artist.py
# (C) British Crown Copyright 2011 - 2015, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option)...
def draw(self, renderer, *args, **kwargs): """ Draws the geometries of the feature that intersect with the extent of the :class:`cartopy.mpl.GeoAxes` instance to which this object has been added. """ if not self.get_visible(): return ax = self.ge...
self._feature = feature @matplotlib.artist.allow_rasterization
random_line_split
wsregex.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import re class
(object): """ A class containing all regular expressions used throughout the DataHound application. """ # Class Members # Potentially better email regex # "([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})" # http://www.webmonkey.com/2008/08/four_regular_expressions_to_check_email_addr...
RegexLib
identifier_name
wsregex.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import re class RegexLib(object):
""" A class containing all regular expressions used throughout the DataHound application. """ # Class Members # Potentially better email regex # "([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})" # http://www.webmonkey.com/2008/08/four_regular_expressions_to_check_email_addresses/ ca...
identifier_body
wsregex.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import re class RegexLib(object): """ A class containing all regular expressions used throughout the DataHound application. """ # Class Members # Potentially better email regex # "([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{...
protocol_regex = re.compile("^([A-Z]{1,10})://", flags=re.IGNORECASE) query_string_regex = re.compile( "^([\\\\\w\-!@\$%\^\*\(\)_`~+\[\]{}|;'\",<>]+=([\\\\\w\-!@\$%\^\*\(\)_`~+\[\]{}|;'\",<>]*)?(&[\\\\\w\-!@\$%\^\*\(\)_`~+\[\]{}|;'\",<>]+=([\\\\\w\-!@\$%\^\*\(\)_`~+\[\]{}|;'\",<>]*)?)*)$", flags...
order_name_regex = re.compile("^[A-Za-z-_0-9]+$")
random_line_split
__init__.py
""" Read & write Java .properties files ``javaproperties`` provides support for reading & writing Java ``.properties`` files (both the simple line-oriented format and XML) with a simple API based on the ``json`` module — though, for recovering Java addicts, it also includes a ``Properties`` class intended to match the...
"join_key_value", "load", "load_xml", "loads", "loads_xml", "parse", "to_comment", "unescape", ] codecs.register_error("javapropertiesreplace", javapropertiesreplace_errors)
random_line_split
menu-panel.js
'use strict'; define([ 'jquery', 'underscore', 'view/widget/panel/panel', 'view/widget/body/body', 'view/widget/navigation/navigation', ], function ($, _, Panel, Body, Navigation) { return Panel.extend({ initialize: function () {
positionFixed: true, display: 'overlay', body: new Body({ items: { navigation: new Navigation({ activeState: false, rows: [ { dashboard: {te...
Panel.prototype.initialize.call(this, { id: 'menu-panel', position: 'right',
random_line_split
block-scoping.js
import traverse from "../../../traversal"; import object from "../../../helpers/object"; import * as util from "../../../util"; import * as t from "../../../types"; import values from "lodash/object/values"; import extend from "lodash/object/extend"; function isLet(node, parent) { if (!t.isVariableDeclaration(node)...
/** * Description */ remap() { var hasRemaps = false; var letRefs = this.letReferences; var scope = this.scope; // alright, so since we aren't wrapping this block in a closure // we have to check if any of our let variables collide with // those in upper scopes and then if th...
{ var block = this.block; if (block._letDone) return; block._letDone = true; var needsClosure = this.getLetReferences(); // this is a block within a `Function/Program` so we can safely leave it be if (t.isFunction(this.parent) || t.isProgram(this.block)) return; // we can skip everything ...
identifier_body
block-scoping.js
import traverse from "../../../traversal"; import object from "../../../helpers/object"; import * as util from "../../../util"; import * as t from "../../../types"; import values from "lodash/object/values"; import extend from "lodash/object/extend"; function isLet(node, parent) { if (!t.isVariableDeclaration(node)...
var assign = t.assignmentExpression("=", decl.id, decl.init); assign._ignoreBlockScopingTDZ = true; nodes.push(t.expressionStatement(assign)); } decl.init = file.addHelper("temporal-undefined"); } node._blockHoist = 2; return nodes; } } export function Loop(node, par...
if (decl.init) {
random_line_split
block-scoping.js
import traverse from "../../../traversal"; import object from "../../../helpers/object"; import * as util from "../../../util"; import * as t from "../../../types"; import values from "lodash/object/values"; import extend from "lodash/object/extend"; function isLet(node, parent) { if (!t.isVariableDeclaration(node)...
if (this.isReturnStatement()) { state.hasReturn = true; replace = t.objectExpression([ t.property("init", t.identifier("v"), node.argument || t.identifier("undefined")) ]); } if (replace) { replace = t.returnStatement(replace); return t.inherits(replace, node); }...
{ if (node.label) { // we shouldn't be transforming this because it exists somewhere inside if (state.innerLabels.indexOf(node.label.name) >= 0) { return; } loopText = `${loopText}|${node.label.name}`; } else { // we shouldn't be transforming these statemen...
conditional_block
block-scoping.js
import traverse from "../../../traversal"; import object from "../../../helpers/object"; import * as util from "../../../util"; import * as t from "../../../types"; import values from "lodash/object/values"; import extend from "lodash/object/extend"; function isLet(node, parent) { if (!t.isVariableDeclaration(node)...
(loopPath?: TraversalPath, block: Object, parent: Object, scope: Scope, file: File) { this.parent = parent; this.scope = scope; this.block = block; this.file = file; this.outsideLetReferences = object(); this.hasLetReferences = false; this.letReferences = block._letReferences...
constructor
identifier_name
import_visits.py
import csv, os from Products.CMFCore.utils import getToolByName def get_folder(self, type, name): folder_brains = self.queryCatalog({'portal_type':type, 'title':name})[0] return folder_brains.getObject() def
(self, container, type): id = container.generateUniqueId(type) container.invokeFactory(id=id, type_name=type) return container[id] def get_type_or_create(self, type, folder, cmp, val): brains = self.queryCatalog({'portal_type':type, cmp:val}) if len(brains) > 0: return brains[0].getObject()...
create_object_in_directory
identifier_name