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 |
|---|---|---|---|---|
domains.ts | /**
* Functions for finding scale domains from data object
*/
/**
* Doc guard
*/
import * as d3 from 'd3'
import * as errors from '../errors'
import { Range } from '../../interfaces'
import { getDateTime } from './timepoints'
/**
* Return max of a pred object { point, high?, low? }
*/
function predMax(pred): nu... | export function xPoint (data, dataConfig): Range {
return dataConfig.ticks
}
/**
* Return domain for given curveid
*/
export function xCurve (data, curveIdx: number): Range {
// This assumes an ordinal scale
for (let i = 0; i < data.models.length; i++) {
let curveData = data.models[i].curves[curveIdx].data... |
/**
* Return point scale domain
*/ | random_line_split |
domains.ts | /**
* Functions for finding scale domains from data object
*/
/**
* Doc guard
*/
import * as d3 from 'd3'
import * as errors from '../errors'
import { Range } from '../../interfaces'
import { getDateTime } from './timepoints'
/**
* Return max of a pred object { point, high?, low? }
*/
function predMax(pred): nu... | (data, curveIdx: number): Range {
// This assumes an ordinal scale
for (let i = 0; i < data.models.length; i++) {
let curveData = data.models[i].curves[curveIdx].data
if (curveData) {
// Return the x series directly
return curveData.map(d => d[0])
}
}
return [0, 0]
}
/**
* Get shared ... | xCurve | identifier_name |
domains.ts | /**
* Functions for finding scale domains from data object
*/
/**
* Doc guard
*/
import * as d3 from 'd3'
import * as errors from '../errors'
import { Range } from '../../interfaces'
import { getDateTime } from './timepoints'
/**
* Return max of a pred object { point, high?, low? }
*/
function predMax(pred): nu... |
/**
* Return domain for y axis using limits of data
*/
export function y (data, dataConfig): Range {
let min = 0
let max = 0
if (dataConfig.actual) {
max = Math.max(max, ...data.actual.filter(d => d))
}
if (dataConfig.observed) {
data.observed.forEach(d => {
max = Math.max(max, ...d.map(la... | {
let max = pred.point
if (pred.high) {
max = Math.max(max, ...pred.high)
}
return max
} | identifier_body |
domains.ts | /**
* Functions for finding scale domains from data object
*/
/**
* Doc guard
*/
import * as d3 from 'd3'
import * as errors from '../errors'
import { Range } from '../../interfaces'
import { getDateTime } from './timepoints'
/**
* Return max of a pred object { point, high?, low? }
*/
function predMax(pred): nu... |
data.models.forEach(md => {
md.predictions.forEach(p => {
if (p) {
max = Math.max(max, ...p.series.map(predMax))
if (dataConfig.predictions.peak) {
max = Math.max(max, predMax(p.peakValue))
}
}
})
})
return [min, 1.1 * max]
}
/**
* Return domain of x
*/
... | {
data.history.forEach(h => {
max = Math.max(max, ...h.actual)
})
} | conditional_block |
miner_service.rs | but WITHOUT ANY WARRANTY; without even the implied warranty of
// 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
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! T... |
/// Set the lower gas limit we wish to target when sealing a new block.
fn set_gas_floor_target(&self, target: U256) {
self.gas_range_target.write().0 = target;
}
/// Set the upper gas limit we wish to target when sealing a new block.
fn set_gas_ceil_target(&self, target: U256) {
self.gas_range_target.write... | {
*self.extra_data.write() = extra_data;
} | identifier_body |
miner_service.rs | but WITHOUT ANY WARRANTY; without even the implied warranty of
// 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
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! T... |
fn all_transactions(&self) -> Vec<SignedTransaction> {
self.pending_transactions.lock().values().cloned().collect()
}
fn pending_transactions(&self, _best_block: BlockNumber) -> Vec<SignedTransaction> {
self.pending_transactions.lock().values().cloned().collect()
}
fn pending_receipt(&self, _best_block: Blo... | fn transaction(&self, _best_block: BlockNumber, hash: &H256) -> Option<SignedTransaction> {
self.pending_transactions.lock().get(hash).cloned()
} | random_line_split |
miner_service.rs | but WITHOUT ANY WARRANTY; without even the implied warranty of
// 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
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! T... |
// lets assume that all txs are valid
self.imported_transactions.lock().push(transaction);
Ok(TransactionImportResult::Current)
}
/// Returns hashes of transactions currently in pending
fn pending_transactions_hashes(&self, _best_block: BlockNumber) -> Vec<H256> {
vec![]
}
/// Removes all transactions... | {
let nonce = self.last_nonce(sender).unwrap_or(chain.latest_nonce(sender));
self.last_nonces.write().insert(sender.clone(), nonce + U256::from(1));
} | conditional_block |
miner_service.rs | but WITHOUT ANY WARRANTY; without even the implied warranty of
// 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
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! T... | (&self, extra_data: Bytes) {
*self.extra_data.write() = extra_data;
}
/// Set the lower gas limit we wish to target when sealing a new block.
fn set_gas_floor_target(&self, target: U256) {
self.gas_range_target.write().0 = target;
}
/// Set the upper gas limit we wish to target when sealing a new block.
fn ... | set_extra_data | identifier_name |
bug2175.js | /*
* Copyright (c) 2012-2014 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSame
} = Assert;
// 22.2.1.2 %TypedArray%: Different [[Prototype]] for copied ArrayBuffer depending on element types
// https://... | extends ArrayBuffer {}
let source = new Int8Array(new MyArrayBuffer(10));
let copySameType = new Int8Array(source);
assertSame(copySameType.buffer.constructor, MyArrayBuffer);
assertSame(Object.getPrototypeOf(copySameType.buffer), MyArrayBuffer.prototype);
let copyDifferentType = new Uint8Array(source);
assertSame(co... | yArrayBuffer | identifier_name |
bug2175.js | /*
* Copyright (c) 2012-2014 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSame
} = Assert;
// 22.2.1.2 %TypedArray%: Different [[Prototype]] for copied ArrayBuffer depending on element types
// https://... | let copyDifferentType = new Uint8Array(source);
assertSame(copyDifferentType.buffer.constructor, MyArrayBuffer);
assertSame(Object.getPrototypeOf(copyDifferentType.buffer), MyArrayBuffer.prototype); | random_line_split | |
windows.rs | _ => unreachable!(),
};
}
}
}
struct KeyReader {
surrogate: Option<u16>,
tx: Sender<Box<Event>>,
}
impl KeyReader {
fn new(tx: Sender<Box<Event>>) -> KeyReader {
KeyReader {
surrogate: None,
tx,
}
}
fn send(&self, event: InputEvent)... | Resizer | identifier_name | |
windows.rs | , just
// exit when the event loop exits).
let _ = event_loop(tx);
}
#[cfg_attr(feature = "cargo-clippy",
allow(needless_range_loop, needless_pass_by_value))]
fn event_loop(tx: Sender<Box<Event>>) -> Result<()> {
let mut resizer = Resizer::from_conout()?;
let in_hndl = Handle::Stdin.win_hand... | 0 | 2 => {
let new_btns = Btn::from_bits(evt.dwButtonState & 0x7).unwrap(); | random_line_split | |
windows.rs | let in_hndl = Handle::Stdin.win_handle();
let mut buffer: [winapi::INPUT_RECORD; 128] =
unsafe { ::std::mem::uninitialized() };
let mut key_reader = KeyReader::new(tx.clone());
let mut mouse_reader = MouseReader::new(tx.clone());
loop {
let mut read_count: winapi::DWORD = 0;
... | {
use input::ButtonMotion::*;
use input::MouseButton::*;
use input::WheelMotion::*;
let coords = (
(evt.dwMousePosition.X as u16),
(evt.dwMousePosition.Y as u16),
);
let mods = Mods::win32(evt.dwControlKeyState);
match evt.dwEventFlags {
... | identifier_body | |
quickOpenController.ts | (): void {
if (this.environmentService.args['sticky-quickopen']) {
this.closeOnFocusLost = false;
} else {
this.closeOnFocusLost = this.configurationService.getValue(CLOSE_ON_FOCUS_LOST_CONFIG);
}
this.preserveInput = this.configurationService.getValue(PRESERVE_INPUT_CONFIG);
this.searchInEditorHistory... | updateConfiguration | identifier_name | |
quickOpenController.ts | OpenWidget.isVisible()) {
this.quickOpenWidget.focus();
}
}
close(): void |
private emitQuickOpenVisibilityChange(isVisible: boolean): void {
if (isVisible) {
this._onShow.fire();
} else {
this._onHide.fire();
}
}
show(prefix?: string, options?: IShowOptions): Promise<void> {
let quickNavigateConfiguration = options ? options.quickNavigateConfiguration : void 0;
let input... | {
if (this.quickOpenWidget && this.quickOpenWidget.isVisible()) {
this.quickOpenWidget.hide(HideReason.CANCELED);
}
} | identifier_body |
quickOpenController.ts |
}
accept(): void {
if (this.quickOpenWidget && this.quickOpenWidget.isVisible()) {
this.quickOpenWidget.accept();
}
}
focus(): void {
if (this.quickOpenWidget && this.quickOpenWidget.isVisible()) {
this.quickOpenWidget.focus();
}
}
close(): void {
if (this.quickOpenWidget && this.quickOpenWidg... | {
this.quickOpenWidget.navigate(next, quickNavigate);
} | conditional_block | |
quickOpenController.ts | OpenWidget.isVisible()) {
this.quickOpenWidget.focus();
}
}
close(): void {
if (this.quickOpenWidget && this.quickOpenWidget.isVisible()) {
this.quickOpenWidget.hide(HideReason.CANCELED);
}
}
private emitQuickOpenVisibilityChange(isVisible: boolean): void {
if (isVisible) {
this._onShow.fire();
... | private setQuickOpenContextKey(id?: string): void {
let key: IContextKey<boolean>;
if (id) {
key = this.mapContextKeyToContext[id];
if (!key) {
key = new RawContextKey<boolean>(id, false).bindTo(this.contextKeyService);
this.mapContextKeyToContext[id] = key;
}
}
if (key && key.get()) {
ret... | random_line_split | |
dj.rs | extern crate discord;
use discord::model::Event;
use discord::{Discord, State};
use std::env;
// A simple DJ bot example.
// Use by issuing the command "!dj <youtube-link>" in PM or a visible text channel.
// The bot will join the voice channel of the person issuing the command.
// "!dj stop" will stop playing, and "... | () {
// Log in to Discord using a bot token from the environment
let discord = Discord::from_bot_token(&env::var("DISCORD_TOKEN").expect("Expected token"))
.expect("login failed");
// establish websocket and voice connection
let (mut connection, ready) = discord.connect().expect("connect failed");
println!(
"... | main | identifier_name |
dj.rs | extern crate discord;
use discord::model::Event;
use discord::{Discord, State};
use std::env;
// A simple DJ bot example.
// Use by issuing the command "!dj <youtube-link>" in PM or a visible text channel.
// The bot will join the voice channel of the person issuing the command.
// "!dj stop" will stop playing, and "... |
if let discord::Error::Closed(..) = err {
break;
}
continue;
}
};
state.update(&event);
match event {
Event::MessageCreate(message) => {
// safeguard: stop if the message is from us
if message.author.id == state.user().id {
continue;
}
// reply to a command if there ... | {
// Handle the websocket connection being dropped
let (new_connection, ready) = discord.connect().expect("connect failed");
connection = new_connection;
state = State::new(ready);
println!("[Ready] Reconnected successfully.");
} | conditional_block |
dj.rs | extern crate discord;
use discord::model::Event;
use discord::{Discord, State};
use std::env;
// A simple DJ bot example.
// Use by issuing the command "!dj <youtube-link>" in PM or a visible text channel.
// The bot will join the voice channel of the person issuing the command.
// "!dj stop" will stop playing, and "... | println!("[Warning] Receive error: {:?}", err);
if let discord::Error::WebSocket(..) = err {
// Handle the websocket connection being dropped
let (new_connection, ready) = discord.connect().expect("connect failed");
connection = new_connection;
state = State::new(ready);
println!("[Read... | {
// Log in to Discord using a bot token from the environment
let discord = Discord::from_bot_token(&env::var("DISCORD_TOKEN").expect("Expected token"))
.expect("login failed");
// establish websocket and voice connection
let (mut connection, ready) = discord.connect().expect("connect failed");
println!(
"[Re... | identifier_body |
dj.rs | extern crate discord;
use discord::model::Event;
use discord::{Discord, State};
use std::env;
// A simple DJ bot example.
// Use by issuing the command "!dj <youtube-link>" in PM or a visible text channel.
// The bot will join the voice channel of the person issuing the command.
// "!dj stop" will stop playing, and "... | }
}
}
_ => {} // discard other events
}
}
}
fn warn<T, E: ::std::fmt::Debug>(result: Result<T, E>) {
match result {
Ok(_) => {}
Err(err) => println!("[Warning] {:?}", err),
}
} | connection.voice(server_id).disconnect();
}
}
} | random_line_split |
lib.rs | #[allow(unused_variables)]
// Because these are passed without & to some functions,
// it will probably be necessary for these two types to be Copy.
pub type CellID = ();
pub type CallbackID = ();
pub struct Reactor<T> {
// Just so that the compiler doesn't complain about an unused type parameter.
// You prob... | unimplemented!()
}
} | random_line_split | |
lib.rs | #[allow(unused_variables)]
// Because these are passed without & to some functions,
// it will probably be necessary for these two types to be Copy.
pub type CellID = ();
pub type CallbackID = ();
pub struct Reactor<T> {
// Just so that the compiler doesn't complain about an unused type parameter.
// You prob... | (&mut self, id: CellID, new_value: T) -> Result<(), ()> {
unimplemented!()
}
// Adds a callback to the specified compute cell.
//
// Return an Err (and you can change the error type) if the cell does not exist.
//
// Callbacks on input cells will not be tested.
//
// The semanti... | set_value | identifier_name |
lib.rs | #[allow(unused_variables)]
// Because these are passed without & to some functions,
// it will probably be necessary for these two types to be Copy.
pub type CellID = ();
pub type CallbackID = ();
pub struct Reactor<T> {
// Just so that the compiler doesn't complain about an unused type parameter.
// You prob... |
// Removes the specified callback, using an ID returned from add_callback.
//
// Return an Err (and you can change the error type) if either the cell or callback
// does not exist.
//
// A removed callback should no longer be called.
pub fn remove_callback(&mut self, cell: CellID, callback... | {
unimplemented!()
} | identifier_body |
ovl.py | # Copyright (C) 2015 Red Hat, Inc.
#
# Authors: Pavel Odvody <podvody@redhat.com>
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This progr... | ():
"""
Touch the files only once we've verified that
we're on overlay mount
"""
with open(mtab, 'r') as f:
line = f.readline()
return line and line.startswith('overlay /')
return False
def prereposetup_hook(conduit):
if not should_touch():
return
rpmdb_path = c... | should_touch | identifier_name |
ovl.py | # Copyright (C) 2015 Red Hat, Inc.
#
# Authors: Pavel Odvody <podvody@redhat.com>
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This progr... | if not should_touch():
return
rpmdb_path = conduit.getRpmDB()._rpmdbpath
try:
for root, _, files in walk(rpmdb_path):
for f in files:
p = path.join(root, f)
with open(p, 'a'):
utime(p, None)
except Exception as e:
condui... | identifier_body | |
ovl.py | # Copyright (C) 2015 Red Hat, Inc.
#
# Authors: Pavel Odvody <podvody@redhat.com>
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This progr... | """
Touch the files only once we've verified that
we're on overlay mount
"""
with open(mtab, 'r') as f:
line = f.readline()
return line and line.startswith('overlay /')
return False
def prereposetup_hook(conduit):
if not should_touch():
return
rpmdb_path = condu... |
def should_touch(): | random_line_split |
ovl.py | # Copyright (C) 2015 Red Hat, Inc.
#
# Authors: Pavel Odvody <podvody@redhat.com>
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This progr... |
except Exception as e:
conduit.error(1, "Error while doing RPMdb copy-up:\n%s" % e)
| p = path.join(root, f)
with open(p, 'a'):
utime(p, None) | conditional_block |
eroTypeahead.js | import React, {Component} from 'react';
import {Typeahead} from 'react-bootstrap-typeahead';
import {inject, observer} from 'mobx-react';
import {action, toJS, autorunAsync} from 'mobx';
import myClient from '../agents/client'
require('react-bootstrap-typeahead/css/ClearButton.css');
require('react-bootstrap-typeahead... | );
}
} | random_line_split | |
eroTypeahead.js | import React, {Component} from 'react';
import {Typeahead} from 'react-bootstrap-typeahead';
import {inject, observer} from 'mobx-react';
import {action, toJS, autorunAsync} from 'mobx';
import myClient from '../agents/client'
require('react-bootstrap-typeahead/css/ClearButton.css');
require('react-bootstrap-typeahead... | extends Component {
constructor(props) {
super(props);
}
state = {
options: []
};
// this will keep updating the next -ERO options as the ERO changes;
disposeOfEroOptionsUpdate = autorunAsync('ero options update', () => {
let ep = this.props.controlsStore.editPipe;
... | EroTypeahead | identifier_name |
eroTypeahead.js | import React, {Component} from 'react';
import {Typeahead} from 'react-bootstrap-typeahead';
import {inject, observer} from 'mobx-react';
import {action, toJS, autorunAsync} from 'mobx';
import myClient from '../agents/client'
require('react-bootstrap-typeahead/css/ClearButton.css');
require('react-bootstrap-typeahead... |
}));
}, 500);
componentWillUnmount() {
this.disposeOfEroOptionsUpdate();
}
onTypeaheadSelection = selection => {
if (selection.length === 0) {
return;
}
let wasAnOption = false;
let through = '';
let urn = '';
let ... | {
let opts = [];
nextHops.map(h => {
let entry = {
id: h.urn,
label: h.urn + ' through ' + h.through + ' to ' + h.to,
through: h.through,
... | conditional_block |
eroTypeahead.js | import React, {Component} from 'react';
import {Typeahead} from 'react-bootstrap-typeahead';
import {inject, observer} from 'mobx-react';
import {action, toJS, autorunAsync} from 'mobx';
import myClient from '../agents/client'
require('react-bootstrap-typeahead/css/ClearButton.css');
require('react-bootstrap-typeahead... |
} | {
return (
<Typeahead
minLength={0}
ref={(ref) => {
this.typeAhead = ref;
}}
placeholder='choose from selection'
options={this.state.options}
onInputChange={this.onTypeaheadSelection... | identifier_body |
direct_irq.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{ioctl_with_ref, AsRawDescriptor, Event, RawDescriptor};
use data_model::vec_with_array_field;
use std::fs::{File, OpenOptions};
use std::io;... | /// Note: this feature is not part of VFIO, but provides
/// missing IRQ forwarding functionality.
///
/// # Arguments
///
/// * `irq_num` - host interrupt number (GSI).
///
pub fn irq_enable(&self, irq_num: u32) -> Result<(), DirectIrqError> {
if let Some(resample) = &self.resam... | /// | random_line_split |
direct_irq.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{ioctl_with_ref, AsRawDescriptor, Event, RawDescriptor};
use data_model::vec_with_array_field;
use std::fs::{File, OpenOptions};
use std::io;... |
/// Enable hardware triggered interrupt handling.
///
/// Note: this feature is not part of VFIO, but provides
/// missing IRQ forwarding functionality.
///
/// # Arguments
///
/// * `irq_num` - host interrupt number (GSI).
///
pub fn irq_enable(&self, irq_num: u32) -> Result<(... | {
let dev = OpenOptions::new()
.read(true)
.write(true)
.open("/dev/plat-irq-forward")
.map_err(DirectIrqError::Open)?;
Ok(DirectIrq {
dev,
trigger,
resample,
})
} | identifier_body |
direct_irq.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{ioctl_with_ref, AsRawDescriptor, Event, RawDescriptor};
use data_model::vec_with_array_field;
use std::fs::{File, OpenOptions};
use std::io;... | else {
Ok(())
}
}
}
impl AsRawDescriptor for DirectIrq {
fn as_raw_descriptor(&self) -> i32 {
self.dev.as_raw_descriptor()
}
}
| {
Err(DirectIrqError::Enable)
} | conditional_block |
direct_irq.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{ioctl_with_ref, AsRawDescriptor, Event, RawDescriptor};
use data_model::vec_with_array_field;
use std::fs::{File, OpenOptions};
use std::io;... | (&self, irq_num: u32) -> Result<(), DirectIrqError> {
if let Some(resample) = &self.resample {
self.plat_irq_ioctl(
irq_num,
PLAT_IRQ_FORWARD_SET_LEVEL_TRIGGER_EVENTFD,
self.trigger.as_raw_descriptor(),
)?;
self.plat_irq_ioctl(
... | irq_enable | identifier_name |
295.js | "use strict";
var SHOW_DATA = {
"venue_name": "Merriweather Post Pavilion, Columbia, Maryland",
"venue_id": 76,
"show_date": "26th of Jun, 1984",
"sets": [
{"set_title": "1st set",
"encore": false,
"songs": [
{"name": "Casey Jones", "length":"5:59", "trans":"/"},
{"name": "Feel Like A Stranger", "len... | "encore": false,
"songs": [
{"name": "China Cat Sunflower", "length":"3:32", "trans":">"},
{"name": "Weir's Segue", "length":"3:53", "trans":">"},
{"name": "I Know You Rider", "length":"5:37", "trans":"/"},
{"name": "Man Smart, Woman Smarter", "length":"6:30", "trans":"/"},
{"name": "He's Gone", "l... | {"name": "Tennessee Jed", "length":"7:58", "trans":"/"},
{"name": "Looks Like Rain", "length":"6:32", "trans":"/"},
{"name": "Might As Well", "length":"4:47", "trans":"/"},
]},
{"set_title": "2nd set", | random_line_split |
translation_label.py | # FreeSpeak - a GUI frontend to online translator engines
# freespeak/ui/translation.py
#
## Copyright (C) 2005, 2006, 2007, 2008, 2009 Luca Bruno <lethalman88@gmail.com>
##
## This file is part of FreeSpeak.
##
## FreeSpeak is free software; you can redistribute it and/or modify
## it under the terms of the GNU Ge... |
def on_event_box_key_press_event (self, event_box, event):
"""
Handle the ESC key as a good key for becoming back a label
and reject the entry changes
"""
# ESC key
if event.keyval == 65307:
self.entry.handler_block (self.entry_focus_out)
sel... | self.menu.popup (None, None, None, event.button, event.time, None) | conditional_block |
translation_label.py | # FreeSpeak - a GUI frontend to online translator engines
# freespeak/ui/translation.py
#
## Copyright (C) 2005, 2006, 2007, 2008, 2009 Luca Bruno <lethalman88@gmail.com>
##
## This file is part of FreeSpeak.
##
## FreeSpeak is free software; you can redistribute it and/or modify
## it under the terms of the GNU Ge... |
def setup_entry (self):
"""
Setup the entry that will take place for modifying the label
"""
self.entry = gtk.Entry ()
self.entry_focus_out = self.entry.connect ('focus-out-event',
self.on_entry_activate)
self.entry... | """
Setup the label
"""
self.label = gtk.Label ()
self.label.show () | identifier_body |
translation_label.py | # FreeSpeak - a GUI frontend to online translator engines
# freespeak/ui/translation.py
#
## Copyright (C) 2005, 2006, 2007, 2008, 2009 Luca Bruno <lethalman88@gmail.com>
##
## This file is part of FreeSpeak.
##
## FreeSpeak is free software; you can redistribute it and/or modify
## it under the terms of the GNU Ge... | (self, title):
"""
Set the suggested title of the page
"""
if not self.is_custom:
self.title = title
self.label.set_text (title)
def start_loading (self):
"""
Make the tab busy by animating the spinner
"""
self.icon.start ()
... | set_suggested_title | identifier_name |
translation_label.py | # FreeSpeak - a GUI frontend to online translator engines
# freespeak/ui/translation.py
#
## Copyright (C) 2005, 2006, 2007, 2008, 2009 Luca Bruno <lethalman88@gmail.com>
##
## This file is part of FreeSpeak.
##
## FreeSpeak is free software; you can redistribute it and/or modify
## it under the terms of the GNU Ge... | self.title = entry.get_text ()
self.entry.handler_block (self.entry_focus_out)
self.be_label ()
self.entry.handler_unblock (self.entry_focus_out)
self.is_custom = True
def on_close (self, button):
"""
Close the translation
"""
self.translatio... | """ | random_line_split |
debruijn.py | # DOCUMENTATION (explain args too)
from bidict import bidict
import sys
pieces = []
kmers = []
debruijn = bidict()
# filename = raw_input("Filename: ")
filename = sys.argv[1]
if filename[-4:] == ".csv":
with open(filename, "r") as infile:
for line in infile:
line = line.strip()
... |
# build debruijn graph
for i in range(0, len(kmers)):
for j in range(0, len(kmers)):
if i != j: # don't look at itself
# print "Testing if %s is %s" % (kmers[i][leftover:], kmers[j][:overlapSize])
if kmers[i][leftover:] == kmers[j][:overlapSize]:
# print "%s... | for i in range(0, len(piece) - kSize + 1):
# if piece[i:i + kSize] not in kmers:
kmers.append(piece[i:i + kSize]) | conditional_block |
debruijn.py | # DOCUMENTATION (explain args too)
from bidict import bidict
import sys
pieces = []
kmers = []
debruijn = bidict()
# filename = raw_input("Filename: ")
filename = sys.argv[1]
if filename[-4:] == ".csv":
with open(filename, "r") as infile:
for line in infile:
line = line.strip()
... | outfile.write(finalString + "\n") |
outfile = open("puzzle-out.txt", "w+")
| random_line_split |
query_result.rs | use std::marker::PhantomData;
use serde::{de, Deserialize, Deserializer};
use uuid::Uuid;
/// A report about the outcome of a write.
#[derive(Debug)]
pub struct WriteStatus<T> {
/// The number of new documents inserted. This counter is zero in case of an update or delete
/// operation. In case of a replace ope... | <V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error>
where V: de::MapVisitor
{
let mut inserted = None;
let mut replaced = None;
let mut unchanged = None;
let mut skipped = None;
let mut deleted = None... | visit_map | identifier_name |
query_result.rs | use std::marker::PhantomData;
use serde::{de, Deserialize, Deserializer};
use uuid::Uuid;
/// A report about the outcome of a write.
#[derive(Debug)]
pub struct WriteStatus<T> {
/// The number of new documents inserted. This counter is zero in case of an update or delete
/// operation. In case of a replace ope... | Field::FirstError => first_error = Some(try!(visitor.visit_value())),
Field::GeneratedKeys => generated_keys = Some(try!(visitor.visit_value())),
Field::Warnings => warnings = Some(try!(visitor.visit_value())),
Field::Change... | {
let mut inserted = None;
let mut replaced = None;
let mut unchanged = None;
let mut skipped = None;
let mut deleted = None;
let mut errors = None;
let mut first_error = None;
let mut generat... | identifier_body |
query_result.rs | use std::marker::PhantomData;
use serde::{de, Deserialize, Deserializer};
use uuid::Uuid;
/// A report about the outcome of a write.
#[derive(Debug)]
pub struct WriteStatus<T> {
/// The number of new documents inserted. This counter is zero in case of an update or delete
/// operation. In case of a replace ope... |
/// The number of documents that would have been modified except the new value was the same as
/// the old value. This counter is zero in case of a delete operation or an insert operation
/// where `confict` is set to "error".
pub unchanged: u32,
/// The number of documents that were skipped becau... |
/// The number of documents that were updated or replaced. This counter is zero in case of a
/// delete operation or an insert operation where `conflict` isn't set to "replace" or "update".
pub replaced: u32, | random_line_split |
mq_handler.rs | // Copyright Cryptape Technologies LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed ... | {
responses: RpcMap,
}
impl MqHandler {
pub fn new(responses: RpcMap) -> Self {
MqHandler { responses }
}
pub fn handle(&mut self, key: &str, body: &[u8]) -> Result<(), ()> {
trace!("get msg from routing_key {}", key);
let mut msg = Message::try_from(body).map_err(|e| {
... | MqHandler | identifier_name |
mq_handler.rs | // Copyright Cryptape Technologies LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::helper::{RpcMap, TransferType};
use jsonrpc_proto::response::OutputExt;
use jsonrpc_types::rpc_response::Output;
use libproto::... | //
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
timesheet.js | function changeNameLength(name, limit) {
return (name.length > limit) ? name.substring(0, limit - 3) + "..." : name;
}
function getTimesheet(data) {
data = $.parseJSON(data);
$(".alert").addClass("display-hide");
$(".schedule-info").removeClass("display-hide");
$("#turn").hide();
$(".table-cont... | (data) {
var i = 0;
var turn = 0;
$(".table-timesheet tr td").children().remove();
$.each(data, function (weekDay, schedules) {
$.each(schedules, function (schedule, info) {
if (i == 0) {
if (info.turn == 0) turn = "Manhã";
if (info.turn == 1) turn = "... | generateTimesheet | identifier_name |
timesheet.js | function changeNameLength(name, limit) {
return (name.length > limit) ? name.substring(0, limit - 3) + "..." : name;
}
function getTimesheet(data) {
data = $.parseJSON(data);
$(".alert").addClass("display-hide");
$(".schedule-info").removeClass("display-hide");
$("#turn").hide();
$(".table-cont... | var instructorId = $(this).attr("instructor_id");
var disciplineId = $(this).parent().find(".discipline-name").attr("discipline_id");
var scheduleId = $(this).parent().attr("schedule");
$.ajax({
'url': getInstructorsUrl,
'type': 'POST',
'data': {
'discipline':discipl... | $(document).on("click", ".schedule-selected .instructor-name",function(){ | random_line_split |
timesheet.js | function changeNameLength(name, limit) {
return (name.length > limit) ? name.substring(0, limit - 3) + "..." : name;
}
function getTimesheet(data) {
data = $.parseJSON(data);
$(".alert").addClass("display-hide");
$(".schedule-info").removeClass("display-hide");
$("#turn").hide();
$(".table-cont... | changeSchedule(firstSchedule, secondSchedule);
}else { //Primeira seleção
$(this).addClass("schedule-selected");
}
}
});
function changeSchedule(firstSchedule, secondSchedule){
$.ajax({
'url': changeSchedulesURL,
'type': 'POST',
'data': {
... | secondSchedule = {"id":null, "week_day": secondSelected.attr("week_day"), "schedule":secondSelected.parent().attr("id").replace("h","")};
}
| conditional_block |
timesheet.js | function changeNameLength(name, limit) {
return (name.length > limit) ? name.substring(0, limit - 3) + "..." : name;
}
function getTimesheet(data) |
$(document).on("click", ".btn-generate-timesheet", function () {
var classroom = $("select.classroom-id").val();
$.ajax({
'url': generateTimesheetURL,
'type': 'POST',
'data': {
'classroom': classroom,
},
}).success(function (result) {
getTimesheet(result... | {
data = $.parseJSON(data);
$(".alert").addClass("display-hide");
$(".schedule-info").removeClass("display-hide");
$("#turn").hide();
$(".table-container").hide();
if (data.valid == null) {
$(".schedule-info").addClass("display-hide");
} else if (!data.valid) {
if (data.error... | identifier_body |
test.py | ############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the co... | ():
startApplication("qtcreator" + SettingsPath)
if not startedWithoutPluginError():
return
checkedTargets, projectName = createNewQtQuickApplication(tempDir(), "SampleApp")
# run project for debug and release and verify results
runVerify(checkedTargets)
#close Qt Creator
invokeMenuI... | main | identifier_name |
test.py | ############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the co... |
checkedTargets, projectName = createNewQtQuickApplication(tempDir(), "SampleApp")
# run project for debug and release and verify results
runVerify(checkedTargets)
#close Qt Creator
invokeMenuItem("File", "Exit")
| return | conditional_block |
test.py | ############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the co... | checkedTargets, projectName = createNewQtQuickApplication(tempDir(), "SampleApp")
# run project for debug and release and verify results
runVerify(checkedTargets)
#close Qt Creator
invokeMenuItem("File", "Exit") | def main():
startApplication("qtcreator" + SettingsPath)
if not startedWithoutPluginError():
return | random_line_split |
test.py | ############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the co... | startApplication("qtcreator" + SettingsPath)
if not startedWithoutPluginError():
return
checkedTargets, projectName = createNewQtQuickApplication(tempDir(), "SampleApp")
# run project for debug and release and verify results
runVerify(checkedTargets)
#close Qt Creator
invokeMenuItem("Fil... | identifier_body | |
release_zh-cn.js.uncompressed.js | define('dojorama/layers/nls/release_zh-cn',{
'dojorama/ui/release/mixin/nls/_ReleaseActionsMixin':{"indexLabel":"Overview","createLabel":"Create New Release"}
,
'dojorama/ui/release/mixin/nls/_ReleaseBreadcrumbsMixin':{"homeLabel":"Home","releaseIndexLabel":"Releases","releaseCreateLabel":"Create New Release"}
,
'dojor... | 'dojorama/ui/release/nls/ReleaseUpdatePage':{"pageTitle":"Releases"}
}); | random_line_split | |
reader.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 ... |
}
impl<R: Reader> Rng for ReaderRng<R> {
fn next_u32(&mut self) -> u32 {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
if cfg!(target_endian="lit... | {
ReaderRng {
reader: r
}
} | identifier_body |
reader.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) -> u32 {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
if cfg!(target_endian="little") {
self.reader.read_le_u32_()
} e... | next_u32 | identifier_name |
reader.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 ... | mod test {
use super::*;
use rt::io::mem::MemReader;
use cast;
#[test]
fn test_reader_rng_u64() {
// transmute from the target to avoid endianness concerns.
let v = ~[1u64, 2u64, 3u64];
let bytes: ~[u8] = unsafe {cast::transmute(v)};
let mut rng = ReaderRng::new(MemR... | #[cfg(test)] | random_line_split |
prefill_an_array.py | """
Prefill an Array
(6 kyu)
https://www.codewars.com/kata/54129112fb7c188740000162/train/python
Create the function prefill that returns an array of n elements that all have
the same value v. See if you can do this without using a loop.
You have to validate input:
- v can be anything (primitive or otherwise)
- if... | (n, v=None):
try:
n = int(n)
except (ValueError, TypeError):
raise TypeError("{} is invalid".format(n))
return [v] * n
| prefill | identifier_name |
prefill_an_array.py | """
Prefill an Array
(6 kyu)
https://www.codewars.com/kata/54129112fb7c188740000162/train/python
Create the function prefill that returns an array of n elements that all have
the same value v. See if you can do this without using a loop.
You have to validate input:
- v can be anything (primitive or otherwise)
- if... | try:
n = int(n)
except (ValueError, TypeError):
raise TypeError("{} is invalid".format(n))
return [v] * n | identifier_body | |
prefill_an_array.py | """
Prefill an Array
(6 kyu)
https://www.codewars.com/kata/54129112fb7c188740000162/train/python
Create the function prefill that returns an array of n elements that all have
the same value v. See if you can do this without using a loop.
You have to validate input:
- v can be anything (primitive or otherwise)
- if... | n = int(n)
except (ValueError, TypeError):
raise TypeError("{} is invalid".format(n))
return [v] * n |
def prefill(n, v=None):
try: | random_line_split |
api-keys-index.js | import {inject} from 'aurelia-dependency-injection';
import { Router } from 'aurelia-router';
import ApiKeyService from 'resources/services/api-key-service';
@inject(ApiKeyService)
export class ApiKeysIndex {
constructor(apiKeyService) {
this.apiKeyService = apiKeyService;
}
async activate() {
this.apiK... | } | selectText(keyElement);
document.execCommand('copy');
} | random_line_split |
api-keys-index.js | import {inject} from 'aurelia-dependency-injection';
import { Router } from 'aurelia-router';
import ApiKeyService from 'resources/services/api-key-service';
@inject(ApiKeyService)
export class ApiKeysIndex {
constructor(apiKeyService) {
this.apiKeyService = apiKeyService;
}
async activate() {
this.apiK... |
const keyElement = document.getElementsByClassName('w-api-key')[keyIndex]
selectText(keyElement);
document.execCommand('copy');
}
}
| {
var range = document.createRange(); // Create new range object
range.selectNodeContents(element); // Set range to encompass desired element text
var selection = window.getSelection(); // Get Selection object from currently user selected text
selection.removeAllRanges(); // Un... | identifier_body |
api-keys-index.js | import {inject} from 'aurelia-dependency-injection';
import { Router } from 'aurelia-router';
import ApiKeyService from 'resources/services/api-key-service';
@inject(ApiKeyService)
export class ApiKeysIndex {
constructor(apiKeyService) {
this.apiKeyService = apiKeyService;
}
async activate() {
this.apiK... | (element) {
var range = document.createRange(); // Create new range object
range.selectNodeContents(element); // Set range to encompass desired element text
var selection = window.getSelection(); // Get Selection object from currently user selected text
selection.removeAllRanges(); ... | selectText | identifier_name |
afd_relisted_null_editor.py | import pywikibot
pywikibot.config.family = "wikipedia"
pywikibot.config.mylang = "en"
site = pywikibot.Site()
site.login()
class AFDRelistedNullEditor(object):
"""Makes a null edit to AfDs transcluded in the logs on [[Category:Relisted AfD debates]]"""
def __init__(self):
self.afd_prefix = "Wikiped... | page.touch()
except pywikibot.Error:
pass
def run(self):
for page in self.category.articles():
if page.title().startswith(self.afd_prefix + "Log/"):
self.process_log(page)
if __name__ == "__main__":
try:
b... | try:
if self.category.title() in page.get(): | random_line_split |
afd_relisted_null_editor.py | import pywikibot
pywikibot.config.family = "wikipedia"
pywikibot.config.mylang = "en"
site = pywikibot.Site()
site.login()
class AFDRelistedNullEditor(object):
"""Makes a null edit to AfDs transcluded in the logs on [[Category:Relisted AfD debates]]"""
def __init__(self):
self.afd_prefix = "Wikiped... |
if __name__ == "__main__":
try:
bot = AFDRelistedNullEditor()
bot.run()
finally:
pywikibot.stopme()
| if page.title().startswith(self.afd_prefix + "Log/"):
self.process_log(page) | conditional_block |
afd_relisted_null_editor.py | import pywikibot
pywikibot.config.family = "wikipedia"
pywikibot.config.mylang = "en"
site = pywikibot.Site()
site.login()
class AFDRelistedNullEditor(object):
"""Makes a null edit to AfDs transcluded in the logs on [[Category:Relisted AfD debates]]"""
def __init__(self):
self.afd_prefix = "Wikiped... | (self, log):
for page in log.itertemplates():
if page.title().startswith(self.afd_prefix):
try:
if self.category.title() in page.get():
page.touch()
except pywikibot.Error:
pass
def run(self):
... | process_log | identifier_name |
afd_relisted_null_editor.py | import pywikibot
pywikibot.config.family = "wikipedia"
pywikibot.config.mylang = "en"
site = pywikibot.Site()
site.login()
class AFDRelistedNullEditor(object):
"""Makes a null edit to AfDs transcluded in the logs on [[Category:Relisted AfD debates]]"""
def __init__(self):
self.afd_prefix = "Wikiped... |
def run(self):
for page in self.category.articles():
if page.title().startswith(self.afd_prefix + "Log/"):
self.process_log(page)
if __name__ == "__main__":
try:
bot = AFDRelistedNullEditor()
bot.run()
finally:
pywikibot.stopme()
| for page in log.itertemplates():
if page.title().startswith(self.afd_prefix):
try:
if self.category.title() in page.get():
page.touch()
except pywikibot.Error:
pass | identifier_body |
segment_stats.rs | use search::segment::Segment;
| pub struct SegmentStatistics {
total_docs: i64,
deleted_docs: i64,
}
impl SegmentStatistics {
fn read<S: Segment>(segment: &S) -> Result<SegmentStatistics, String> {
let total_docs = try!(segment.load_statistic(b"total_docs")).unwrap_or(0);
let deleted_docs = try!(segment.load_statistic(b"d... | use super::RocksDBStore;
#[derive(Debug)] | random_line_split |
segment_stats.rs | use search::segment::Segment;
use super::RocksDBStore;
#[derive(Debug)]
pub struct SegmentStatistics {
total_docs: i64,
deleted_docs: i64,
}
impl SegmentStatistics {
fn read<S: Segment>(segment: &S) -> Result<SegmentStatistics, String> {
let total_docs = try!(segment.load_statistic(b"total_docs")... |
}
impl RocksDBStore {
pub fn get_segment_statistics(&self) -> Result<Vec<(u32, SegmentStatistics)>, String> {
let mut segment_stats = Vec::new();
let reader = self.reader();
for segment in self.segments.iter_active(&reader) {
let stats = try!(SegmentStatistics::read(&segment))... | {
self.deleted_docs
} | identifier_body |
segment_stats.rs | use search::segment::Segment;
use super::RocksDBStore;
#[derive(Debug)]
pub struct SegmentStatistics {
total_docs: i64,
deleted_docs: i64,
}
impl SegmentStatistics {
fn read<S: Segment>(segment: &S) -> Result<SegmentStatistics, String> {
let total_docs = try!(segment.load_statistic(b"total_docs")... | (&self) -> i64 {
self.total_docs
}
#[inline]
pub fn deleted_docs(&self) -> i64 {
self.deleted_docs
}
}
impl RocksDBStore {
pub fn get_segment_statistics(&self) -> Result<Vec<(u32, SegmentStatistics)>, String> {
let mut segment_stats = Vec::new();
let reader = self.r... | total_docs | identifier_name |
settings.component.ts | import {Component} from "@angular/core";
import {MdButton} from "@angular2-material/button";
import {MD_CARD_DIRECTIVES} from "@angular2-material/card";
import {MdInput} from "@angular2-material/input";
import {MdCheckbox} from "@angular2-material/checkbox";
import {MdRadioButton, MdRadioGroup, MdRadioDispatcher} from ... | extends ITab {
constructor(protected TabService:TabService) {
super(TabService, 'Settings', true, 'settings');
this.icon = 'settings';
this.title = 'Settings';
this.description = 'Change settings here';
this.closeable = false;
}
}
| Settings | identifier_name |
settings.component.ts | import {Component} from "@angular/core";
import {MdButton} from "@angular2-material/button";
import {MD_CARD_DIRECTIVES} from "@angular2-material/card";
import {MdInput} from "@angular2-material/input";
import {MdCheckbox} from "@angular2-material/checkbox"; | import {MdIcon, MdIconRegistry} from "@angular2-material/icon";
import {ITab, TabService} from "../../../../../shared";
@Component({
moduleId: module.id,
selector: 'settings',
directives: [
MD_CARD_DIRECTIVES,
MdButton,
MdInput,
MdCheckbox,
MdRadioGroup,
MdRadioButton,
MdIcon
],
s... | import {MdRadioButton, MdRadioGroup, MdRadioDispatcher} from "@angular2-material/radio"; | random_line_split |
itn-byron-wallet-importer.ts | /* eslint-disable no-console */
import axios from "axios";
import https from "https";
import fs from "fs";
import { sampleSize, shuffle } from "lodash";
import { itnByronMnemonics } from "./mnemonics";
const names = ['Nash', 'Nate', 'Nathan', 'Nelson', 'Neo', 'Newton', 'Nick', 'Nigel', 'Nino', 'Noah'];
const API_PORT ... | (mnemonic, name) {
return {
name,
mnemonic_sentence: mnemonic,
passphrase: 'Secret1234',
style: 'random'
};
}
const shuffledMnemonics = shuffle(itnByronMnemonics);
const shuffledNames = shuffle(names);
try {
if (IS_HTTPS) {
const httpsAgent = new https.Agent({
... | generateImportPayload | identifier_name |
itn-byron-wallet-importer.ts | /* eslint-disable no-console */
import axios from "axios";
import https from "https";
import fs from "fs";
import { sampleSize, shuffle } from "lodash";
import { itnByronMnemonics } from "./mnemonics";
const names = ['Nash', 'Nate', 'Nathan', 'Nelson', 'Neo', 'Newton', 'Nick', 'Nigel', 'Nino', 'Noah'];
const API_PORT ... |
const shuffledMnemonics = shuffle(itnByronMnemonics);
const shuffledNames = shuffle(names);
try {
if (IS_HTTPS) {
const httpsAgent = new https.Agent({
cert: fs.readFileSync('tls/client/client.pem'),
key: fs.readFileSync('tls/client/client.key'),
ca: fs.readFileSync('tls/client... | {
return {
name,
mnemonic_sentence: mnemonic,
passphrase: 'Secret1234',
style: 'random'
};
} | identifier_body |
itn-byron-wallet-importer.ts | /* eslint-disable no-console */
import axios from "axios";
import https from "https";
import fs from "fs";
import { sampleSize, shuffle } from "lodash";
import { itnByronMnemonics } from "./mnemonics";
const names = ['Nash', 'Nate', 'Nathan', 'Nelson', 'Neo', 'Newton', 'Nick', 'Nigel', 'Nino', 'Noah'];
const API_PORT ... | const payload = generateImportPayload(mnemonic, name);
return request.post(`https://localhost:${API_PORT}/v2/byron-wallets`, payload);
}));
} else {
// @ts-ignore ts-migrate(2769) FIXME: No overload matches this call.
await Promise.all(sampleSize(shuffledMnemonics, WALLET_COUNT).ma... | });
// @ts-ignore ts-migrate(2769) FIXME: No overload matches this call.
await Promise.all(sampleSize(shuffledMnemonics, WALLET_COUNT).map((mnemonic, index) => {
const name = shuffledNames[index]; | random_line_split |
itn-byron-wallet-importer.ts | /* eslint-disable no-console */
import axios from "axios";
import https from "https";
import fs from "fs";
import { sampleSize, shuffle } from "lodash";
import { itnByronMnemonics } from "./mnemonics";
const names = ['Nash', 'Nate', 'Nathan', 'Nelson', 'Neo', 'Newton', 'Nick', 'Nigel', 'Nino', 'Noah'];
const API_PORT ... | else {
// @ts-ignore ts-migrate(2769) FIXME: No overload matches this call.
await Promise.all(sampleSize(shuffledMnemonics, WALLET_COUNT).map((mnemonic, index) => {
const name = shuffledNames[index];
const payload = generateImportPayload(mnemonic, name);
return axios.post(`http://lo... | {
const httpsAgent = new https.Agent({
cert: fs.readFileSync('tls/client/client.pem'),
key: fs.readFileSync('tls/client/client.key'),
ca: fs.readFileSync('tls/client/ca.crt')
});
const request = axios.create({
httpsAgent
});
// @ts-ignore ts-migrate(2769) FI... | conditional_block |
general_script_L1_PACS.py | ### This script fetches level-1 PACS imaging data, using a list generated by the
### archive (in the CSV format), attaches sky coordinates and masks to them | ### (by calling the convertL1ToScanam task) and save them to disk in the correct
### format for later use by Scanamorphos.
### See important instructions below.
#######################################################
### This script is part of the Scanamorphos package.
### HCSS is free software: you can redistribu... | random_line_split | |
general_script_L1_PACS.py | ### This script fetches level-1 PACS imaging data, using a list generated by the
### archive (in the CSV format), attaches sky coordinates and masks to them
### (by calling the convertL1ToScanam task) and save them to disk in the correct
### format for later use by Scanamorphos.
### See important instructions below.
... |
print ""
print "Downloading obsid " + `num_obsid`
obs = getObservation(num_obsid, useHsa=True, instrument="PACS", verbose=True)
###
frames = obs.level1.refs["HPPAVGR"].product.refs[0].product
convertL1ToScanam(frames, cancelGlitch=1, assignRaDec=1, outDir=dir_out)
###
frames = obs.level... | os.system('mkdir '+dir_out)
## | conditional_block |
ip2_convolve3x3.rs | /*
* Copyright (C) 2012 The Android Open Source Project
* | *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the Licen... | * 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 | random_line_split |
example1.js | // Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... | serviceName: 'server'
}).send('func2', 'arg 1', 'arg 2', function onResp(err, res, arg2, arg3) {
if (err) {
finish(err);
} else {
assert.equal(res.ok, false);
console.log('err res: ', {
ok: res.ok,
message: String(arg3)
... | clientChan.request({ | random_line_split |
example1.js | // Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... | (err) {
if (err) {
throw err;
}
if (--counter === 0) {
server.close();
client.close();
}
}
| finish | identifier_name |
example1.js | // Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... | {
if (err) {
throw err;
}
if (--counter === 0) {
server.close();
client.close();
}
} | identifier_body | |
example1.js | // Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... | else {
assert.equal(res.ok, false);
console.log('err res: ', {
ok: res.ok,
message: String(arg3)
});
finish();
}
});
});
function finish(err) {
if (err) {
throw err;
}
if (--counter === 0) {
server... | {
finish(err);
} | conditional_block |
commandtest.py | # Copyright (C) 2009 Google 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 conditions and the f... | class CommandsTest(unittest.TestCase):
def assert_execute_outputs(self, command, args=[], expected_stdout="", expected_stderr="", expected_exception=None, expected_logs=None, options=MockOptions(), tool=MockTool()):
options.blocks = None
options.cc = 'MOCK cc'
options.component = 'MOCK comp... |
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.tool.mocktool import MockOptions, MockTool
| random_line_split |
commandtest.py | # Copyright (C) 2009 Google 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 conditions and the f... | (self, command, args=[], expected_stdout="", expected_stderr="", expected_exception=None, expected_logs=None, options=MockOptions(), tool=MockTool()):
options.blocks = None
options.cc = 'MOCK cc'
options.component = 'MOCK component'
options.confirm = True
options.email = 'MOCK em... | assert_execute_outputs | identifier_name |
commandtest.py | # Copyright (C) 2009 Google 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 conditions and the f... | options.blocks = None
options.cc = 'MOCK cc'
options.component = 'MOCK component'
options.confirm = True
options.email = 'MOCK email'
options.git_commit = 'MOCK git commit'
options.obsolete_patches = True
options.open_bug = True
options.port = 'MOCK port'
... | identifier_body | |
it.js | /**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
| contents: 'Contenuti di Aiuto. Per chiudere questa finestra premi ESC.',
legend: [
{
name: 'Generale',
items: [
{
name: 'Barra degli strumenti Editor',
legend: 'Premere ${toolbarFocus} per passare alla barra degli strumenti. Usare TAB per spostarsi al gruppo successivo, MAIUSC+TAB per spostarsi ... | CKEDITOR.plugins.setLang( 'a11yhelp', 'it', {
title: 'Istruzioni di Accessibilità',
| random_line_split |
Gruntfile.js | /*
* poeditor_htmid
*
* This is an adaptation of a plugin found https://github.com/Philoozushi/grunt-poeditor-pz . This plugin will download the localizations for a particular project ID and then get all of the string associated with the project. This plugin is to be used in combination with the other htmid plugin... | options: {
jshintrc: '.jshintrc'
}
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp']
},
// Configuration to be run (and then tested).
poeditor_htmid: {
},
// Unit tests.
nodeunit: {
tests: ['test/*_t... | ], | random_line_split |
lzw.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Lempel–Ziv–Welch compression algorithm example, with 4096 dictionary size."""
from multipack.datastructures import HashTable, DynamicArray
class Lzw:
"""Lempel-Ziv-Welch compression implementation."""
def __init__(self, stream, dict_size=4096):
sel... |
return byte_1, byte_2, byte_3
def _int8_to_int12(first, second, third=None):
"""Convert three or two bytes to 12-bit integers."""
if first > 256 or second > 256:
raise Exception("More than 8 bits")
elif third is not None and third > 256:
raise Exception("Third more than 8 bits")
... | if second is None:
return byte_1, byte_2
byte_2 |= second >> 8
byte_3 = 0xff & second | random_line_split |
lzw.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Lempel–Ziv–Welch compression algorithm example, with 4096 dictionary size."""
from multipack.datastructures import HashTable, DynamicArray
class Lzw:
"""Lempel-Ziv-Welch compression implementation."""
def __init__(self, stream, dict_size=4096):
sel... | ef _int12_to_int8(first, second=None):
"""Convert two 12-bit integers to three 8-bit integers for serialization.
:param first: First 12-bit integer for conversion.
:param second: Second 12-bit integer for conversion.
:return: tuple of three 8-bit integers.
"""
if first > 4095 or (second is not N... | _1 = self.stream.read(1)
byte_2 = self.stream.read(1)
byte_3 = self.stream.read(1)
if not byte_1 or not byte_2:
break
int_8_1 = int.from_bytes(byte_1, byteorder="little")
int_8_2 = int.from_bytes(byte_2, byteorder="little")
int_8_3... | conditional_block |
lzw.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Lempel–Ziv–Welch compression algorithm example, with 4096 dictionary size."""
from multipack.datastructures import HashTable, DynamicArray
class Lzw:
"""Lempel-Ziv-Welch compression implementation."""
def __in | f, stream, dict_size=4096):
self.stream = stream
self.dictionary = None
self.index = 0
self.str = b""
self.max = dict_size
self.init_dict()
def _dict_add(self, dict_string):
"""Add new string to dictionary, and increment the index. Key is a
string and... | it__(sel | identifier_name |
lzw.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Lempel–Ziv–Welch compression algorithm example, with 4096 dictionary size."""
from multipack.datastructures import HashTable, DynamicArray
class Lzw:
"""Lempel-Ziv-Welch compression implementation."""
def __init__(self, stream, dict_size=4096):
sel... | yield int_2
d
ef _int12_to_int8(first, second=None):
"""Convert two 12-bit integers to three 8-bit integers for serialization.
:param first: First 12-bit integer for conversion.
:param second: Second 12-bit integer for conversion.
:return: tuple of three 8-bit integers.
"""
if firs... | ead the binary stream until there is no more characters.
:return: Indices for the dictionary.
"""
while True:
byte_1 = self.stream.read(1)
byte_2 = self.stream.read(1)
byte_3 = self.stream.read(1)
if not byte_1 or not byte_2:
break
... | identifier_body |
parser.js | /**
* Created by JiaHao on 27/10/15.
*/
var fs = require('fs');
var path = require('path');
var normalizeNewline = require('normalize-newline');
function occurenceIndexes(inp, toFind) {
var indices = [];
var element = toFind;
var idx = inp.indexOf(element);
while (idx != -1) {
indices.push(i... |
counter += 1;
}
var subtractFunction = function (element) {
return element - subtractIndexes[element];
};
result = result.map(function (tuple) {
return tuple.map(subtractFunction);
});
return result;
}
module.exports = parseText;
if (require.main === module) {
... | {
var stackNext = stack.pop();
result.push([stackNext, endOccuranceNext]);
endOccuranceCounter+=1;
} | conditional_block |
parser.js | /**
* Created by JiaHao on 27/10/15.
*/
var fs = require('fs');
var path = require('path');
var normalizeNewline = require('normalize-newline');
function occurenceIndexes(inp, toFind) { | idx = inp.indexOf(element, idx + 1);
}
return indices;
}
const ANNONATION = {
start: '{',
end: '}'
};
/**
* Parses a file at a path
* @param path
* @returns {Array}
* @param annotation
*/
function parseText(path, annotation) {
var rawText = normalizeNewline(fs.readFileSync(path).toStr... | var indices = [];
var element = toFind;
var idx = inp.indexOf(element);
while (idx != -1) {
indices.push(idx); | random_line_split |
parser.js | /**
* Created by JiaHao on 27/10/15.
*/
var fs = require('fs');
var path = require('path');
var normalizeNewline = require('normalize-newline');
function occurenceIndexes(inp, toFind) {
var indices = [];
var element = toFind;
var idx = inp.indexOf(element);
while (idx != -1) {
indices.push(i... |
var startOccuranceNext;
var endOccuranceNext;
while (counter < rawText.length) {
startOccuranceNext = startOccurances[startOccuranceCounter];
endOccuranceNext = endOccurances[endOccuranceCounter];
if (counter === startOccuranceNext) {
stack.push(startOccuranceNext);
... | {
var rawText = normalizeNewline(fs.readFileSync(path).toString());
var annotationToken = annotation || ANNONATION;
var startOccurances = occurenceIndexes(rawText, annotationToken.start);
var endOccurances = occurenceIndexes(rawText, annotationToken.end);
var allOccurances = startOccurances.concat... | identifier_body |
parser.js | /**
* Created by JiaHao on 27/10/15.
*/
var fs = require('fs');
var path = require('path');
var normalizeNewline = require('normalize-newline');
function | (inp, toFind) {
var indices = [];
var element = toFind;
var idx = inp.indexOf(element);
while (idx != -1) {
indices.push(idx);
idx = inp.indexOf(element, idx + 1);
}
return indices;
}
const ANNONATION = {
start: '{',
end: '}'
};
/**
* Parses a file at a path
* @param ... | occurenceIndexes | identifier_name |
LoadoutEdit.tsx | === 'Armor'
);
for (const item of equippedArmor) {
mods.push(...extractArmorModHashes(item));
}
stateDispatch({ type: 'updateMods', mods });
};
const onModsByBucketUpdated = (
modsByBucket:
| {
[bucketHash: number]: number[];
}
| undefined
) => stateDispat... | {
draftLoadout.parameters = {
...draftLoadout.parameters,
modsByBucket,
};
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.