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 |
|---|---|---|---|---|
test_list.py | import sys
import unittest
from test import test_support, list_tests
class ListTest(list_tests.CommonTest):
type2test = list
def test_basic(self):
self.assertEqual(list([]), [])
l0_3 = [0, 1, 2, 3]
l0_3_bis = list(l0_3)
self.assertEqual(l0_3, l0_3_bis)
self.assertTrue(l... | self.assertTrue([] is not [])
def test_len(self):
super(ListTest, self).test_len()
self.assertEqual(len([]), 0)
self.assertEqual(len([0]), 1)
self.assertEqual(len([0, 1, 2]), 3)
@unittest.expectedFailure
def test_overflow(self):
lst = [4, 5, 6, 7]
n ... | self.assertTrue([42])
def test_identity(self): | random_line_split |
test_list.py | import sys
import unittest
from test import test_support, list_tests
class ListTest(list_tests.CommonTest):
type2test = list
def test_basic(self):
self.assertEqual(list([]), [])
l0_3 = [0, 1, 2, 3]
l0_3_bis = list(l0_3)
self.assertEqual(l0_3, l0_3_bis)
self.assertTrue(l... | (self):
super(ListTest, self).test_len()
self.assertEqual(len([]), 0)
self.assertEqual(len([0]), 1)
self.assertEqual(len([0, 1, 2]), 3)
@unittest.expectedFailure
def test_overflow(self):
lst = [4, 5, 6, 7]
n = int((sys.maxsize*2+2) // len(lst))
def mul(a,... | test_len | identifier_name |
main.rs | // Author: Alex Chernyakhovsky (achernya@mit.edu)
// TODO(achernya): Per the documentation on doc.rust-lang.org, std::io
// is not yet ready, so use old_io until 1.0-final.
#![feature(old_io)]
// std::env contains a lot of nice functions that otherwise would
// require std::os to use; std::os has lots of deprecated f... | let directory = dir.unwrap();
let result = env::set_current_dir(&directory);
match result {
Err(err) => {
println_stderr!("cd: {}: {}", directory.display(), err);
},
_ => {},
}
}
fn pwd() {
let p = env::current_dir().unwrap_or(Path::new("/"));
println!("{}", ... | };
if dir.is_none() {
println_stderr!("cd: no directory to change to");
return;
} | random_line_split |
main.rs | // Author: Alex Chernyakhovsky (achernya@mit.edu)
// TODO(achernya): Per the documentation on doc.rust-lang.org, std::io
// is not yet ready, so use old_io until 1.0-final.
#![feature(old_io)]
// std::env contains a lot of nice functions that otherwise would
// require std::os to use; std::os has lots of deprecated f... | (command: &Vec<&str>) -> bool {
match command[0] {
"cd" => cd(command),
"pwd" => pwd(),
_ => return false,
}
true
}
fn cd(command: &Vec<&str>) {
// cd is the "change directory" command. It can take either 0 or 1
// arguments. If given no arguments, then the $HOME directory i... | builtins | identifier_name |
main.rs | // Author: Alex Chernyakhovsky (achernya@mit.edu)
// TODO(achernya): Per the documentation on doc.rust-lang.org, std::io
// is not yet ready, so use old_io until 1.0-final.
#![feature(old_io)]
// std::env contains a lot of nice functions that otherwise would
// require std::os to use; std::os has lots of deprecated f... |
fn builtins(command: &Vec<&str>) -> bool {
match command[0] {
"cd" => cd(command),
"pwd" => pwd(),
_ => return false,
}
true
}
fn cd(command: &Vec<&str>) {
// cd is the "change directory" command. It can take either 0 or 1
// arguments. If given no arguments, then the $HOM... | {
// Clean up the string by removing the newline at the end
let expr = user_expr.trim_matches('\n');
let components: Vec<&str> = expr.split(' ').collect();
if builtins(&components) {
return;
}
} | identifier_body |
index.js | /*
* Network Access Status v2.1.0
*Copyright 2017
*Authors: Venkatesh Chinthakindi.
*All Rights Reserved.
*use ,reproduction, distribution, and modification of this code is subject to the terms and conditions of the MIT license
*
*/
debugger;
var networkAccessStatus=(function(){
return{
check: function() { ... | try{
setInterval(()=>{startNetworkCheck.callback()},interval);
}
catch(error){
console.log('inner file console catch'+error) ... | var blob=new Blob([
`var startNetworkCheck=(function(){
var interval=3000;
return{
checkNetwork:function(){ | random_line_split |
index.js | /*
* Network Access Status v2.1.0
*Copyright 2017
*Authors: Venkatesh Chinthakindi.
*All Rights Reserved.
*use ,reproduction, distribution, and modification of this code is subject to the terms and conditions of the MIT license
*
*/
debugger;
var networkAccessStatus=(function(){
return{
check: function() { ... |
};
img.onerror = function() {
if(status!=false)
{
status=false;
newEvent = new CustomEvent('networkStatusChanged', { detail... | {
status=true;
newEvent = new CustomEvent('networkStatusChanged', { detail:true});
window.dispatchEvent(newEvent);
} | conditional_block |
test_record_test.py | # Lint as: python3
"""Unit tests for test_record module."""
import sys
import unittest
from openhtf.core import test_record
def _get_obj_size(obj):
|
class TestRecordTest(unittest.TestCase):
def test_attachment_data(self):
expected_data = b'test attachment data'
attachment = test_record.Attachment(expected_data, 'text')
data = attachment.data
self.assertEqual(data, expected_data)
def test_attachment_memory_safety(self):
empty_attachment ... | size = 0
for attr in obj.__slots__: # pytype: disable=attribute-error
size += sys.getsizeof(attr)
size += sys.getsizeof(getattr(obj, attr))
return size | identifier_body |
test_record_test.py | # Lint as: python3
"""Unit tests for test_record module."""
import sys
import unittest
from openhtf.core import test_record
def _get_obj_size(obj):
size = 0
for attr in obj.__slots__: # pytype: disable=attribute-error
size += sys.getsizeof(attr)
size += sys.getsizeof(getattr(obj, attr))
return size
... | (unittest.TestCase):
def test_attachment_data(self):
expected_data = b'test attachment data'
attachment = test_record.Attachment(expected_data, 'text')
data = attachment.data
self.assertEqual(data, expected_data)
def test_attachment_memory_safety(self):
empty_attachment = test_record.Attachmen... | TestRecordTest | identifier_name |
test_record_test.py | # Lint as: python3
"""Unit tests for test_record module."""
import sys
import unittest
from openhtf.core import test_record
def _get_obj_size(obj):
size = 0
for attr in obj.__slots__: # pytype: disable=attribute-error
|
return size
class TestRecordTest(unittest.TestCase):
def test_attachment_data(self):
expected_data = b'test attachment data'
attachment = test_record.Attachment(expected_data, 'text')
data = attachment.data
self.assertEqual(data, expected_data)
def test_attachment_memory_safety(self):
emp... | size += sys.getsizeof(attr)
size += sys.getsizeof(getattr(obj, attr)) | conditional_block |
test_record_test.py | # Lint as: python3
"""Unit tests for test_record module."""
import sys
import unittest
from openhtf.core import test_record
def _get_obj_size(obj):
size = 0
for attr in obj.__slots__: # pytype: disable=attribute-error | size += sys.getsizeof(getattr(obj, attr))
return size
class TestRecordTest(unittest.TestCase):
def test_attachment_data(self):
expected_data = b'test attachment data'
attachment = test_record.Attachment(expected_data, 'text')
data = attachment.data
self.assertEqual(data, expected_data)
def... | size += sys.getsizeof(attr) | random_line_split |
paper-item.js | /**
* @module ember-paper
*/
import Ember from 'ember';
import RippleMixin from '../mixins/ripple-mixin';
import ProxyMixin from 'ember-paper/mixins/proxy-mixin';
const {
get,
set,
isEmpty,
computed,
run,
Component
} = Ember;
/**
* @class PaperItem
* @extends Ember.Component
* @uses ProxyMixin
* @us... | (ev) {
this.get('proxiedComponents').forEach((component)=> {
if (component.processProxy && !get(component, 'disabled') && (get(component, 'bubbles') | !get(this, 'hasPrimaryAction'))) {
component.processProxy();
}
});
this.sendAction('onClick', ev);
},
setupProxiedComponent() {
... | click | identifier_name |
paper-item.js | /**
* @module ember-paper
*/
import Ember from 'ember';
import RippleMixin from '../mixins/ripple-mixin';
import ProxyMixin from 'ember-paper/mixins/proxy-mixin';
const {
get,
set,
isEmpty,
computed,
run,
Component
} = Ember;
/**
* @class PaperItem
* @extends Ember.Component
* @uses ProxyMixin
* @us... |
el.on('blur', function proxyOnBlur() {
tEl.removeClass('md-focused');
el.off('blur', proxyOnBlur);
});
});
// If we don't have primary action then
// no need to bubble
if (!get(this, 'hasPrimaryAction')) {
let bubbles = get(component... | {
tEl.addClass('md-focused');
} | conditional_block |
paper-item.js | /**
* @module ember-paper
*/
import Ember from 'ember';
import RippleMixin from '../mixins/ripple-mixin';
import ProxyMixin from 'ember-paper/mixins/proxy-mixin';
const {
get,
set,
isEmpty,
computed,
run,
Component
} = Ember;
/**
* @class PaperItem
* @extends Ember.Component
* @uses ProxyMixin
* @us... | outline: false,
classNameBindings: ['shouldBeClickable:md-clickable', 'hasProxiedComponent:md-proxy-focus'],
attributeBindings: ['role', 'tabindex'],
role: 'listitem',
tabindex: '-1',
hasProxiedComponent: computed.bool('proxiedComponents.length'),
hasPrimaryAction: computed.notEmpty('onClick'),
hasS... | // Ripple Overrides
rippleContainerSelector: '.md-no-style',
center: false,
dimBackground: true, | random_line_split |
paper-item.js | /**
* @module ember-paper
*/
import Ember from 'ember';
import RippleMixin from '../mixins/ripple-mixin';
import ProxyMixin from 'ember-paper/mixins/proxy-mixin';
const {
get,
set,
isEmpty,
computed,
run,
Component
} = Ember;
/**
* @class PaperItem
* @extends Ember.Component
* @uses ProxyMixin
* @us... | el.on('focus', ()=> {
if (!get(this, 'mouseActive')) {
tEl.addClass('md-focused');
}
el.on('blur', function proxyOnBlur() {
tEl.removeClass('md-focused');
el.off('blur', proxyOnBlur);
});
});
// If we don't have primary ... | {
let tEl = this.$();
let proxiedComponents = get(this, 'proxiedComponents');
proxiedComponents.forEach((component)=> {
let isProxyHandlerSet = get(component, 'isProxyHandlerSet');
// we run init only once for each component.
if (!isProxyHandlerSet) {
// Allow proxied component to ... | identifier_body |
games-reducer.ts | import {ADD_ALL_GAMES_ACTION, ADD_GAME_ACTION, CLEAR_GAMES_ACTION, LOAD_GAMES_FINISHED_ACTION} from './games-actions';
import {TournamentGame} from '../../../shared/model/tournament-game';
import * as _ from 'lodash';
export interface GamesState {
allGames: TournamentGame[];
loadGames: boolean;
}
const initialSt... |
function clearGames(state: GamesState): GamesState {
const newState: GamesState = _.cloneDeep(state);
newState.allGames = [];
return newState;
}
function handleLoadGames(state: GamesState): GamesState {
const newStoreState = _.cloneDeep(state);
newStoreState.loadGames = false;
return newStoreState;... | {
const newStoreState: GamesState = _.cloneDeep(state);
if (action.payload !== undefined ) {
newStoreState.allGames.push(action.payload);
}
return newStoreState;
} | identifier_body |
games-reducer.ts | import {ADD_ALL_GAMES_ACTION, ADD_GAME_ACTION, CLEAR_GAMES_ACTION, LOAD_GAMES_FINISHED_ACTION} from './games-actions';
import {TournamentGame} from '../../../shared/model/tournament-game';
import * as _ from 'lodash';
export interface GamesState {
allGames: TournamentGame[];
loadGames: boolean;
}
const initialSt... |
function addAllGames(state: GamesState, action): GamesState {
const newStoreState: GamesState = _.cloneDeep(state);
if (action.payload !== undefined) {
newStoreState.allGames = action.payload;
}
return newStoreState;
}
function addGame(state: GamesState, action): GamesState {
const newStoreState: ... | } | random_line_split |
games-reducer.ts | import {ADD_ALL_GAMES_ACTION, ADD_GAME_ACTION, CLEAR_GAMES_ACTION, LOAD_GAMES_FINISHED_ACTION} from './games-actions';
import {TournamentGame} from '../../../shared/model/tournament-game';
import * as _ from 'lodash';
export interface GamesState {
allGames: TournamentGame[];
loadGames: boolean;
}
const initialSt... | (state: GamesState): GamesState {
const newStoreState = _.cloneDeep(state);
newStoreState.loadGames = false;
return newStoreState;
}
| handleLoadGames | identifier_name |
games-reducer.ts | import {ADD_ALL_GAMES_ACTION, ADD_GAME_ACTION, CLEAR_GAMES_ACTION, LOAD_GAMES_FINISHED_ACTION} from './games-actions';
import {TournamentGame} from '../../../shared/model/tournament-game';
import * as _ from 'lodash';
export interface GamesState {
allGames: TournamentGame[];
loadGames: boolean;
}
const initialSt... |
return newStoreState;
}
function clearGames(state: GamesState): GamesState {
const newState: GamesState = _.cloneDeep(state);
newState.allGames = [];
return newState;
}
function handleLoadGames(state: GamesState): GamesState {
const newStoreState = _.cloneDeep(state);
newStoreState.loadGames = fals... | {
newStoreState.allGames.push(action.payload);
} | conditional_block |
Exp6_LineFollowing_IRSensors.py | """//***********************************************************************
* Exp6_LineFollowing_IRSensors -- RedBot Experiment 6
*
* This code reads the three line following sensors on A3, A6, and A7
* and prints them out to the Serial Monitor. Upload this example to your
* RedBot and open up the Serial Monitor ... | * Revised, 31 Oct 2014 B. Huang
* Revices, 2 Oct 2015 L Mathews
***********************************************************************/"""
import sys
import signal
from pymata_aio.pymata3 import PyMata3
from library.redbot import RedBotSensor
WIFLY_IP_ADDRESS = None # Leave set as None if not using Wi... | *
* This sketch was written by SparkFun Electronics,with lots of help from
* the Arduino community. This code is completely free for any use.
*
* 8 Oct 2013 M. Hord | random_line_split |
Exp6_LineFollowing_IRSensors.py | """//***********************************************************************
* Exp6_LineFollowing_IRSensors -- RedBot Experiment 6
*
* This code reads the three line following sensors on A3, A6, and A7
* and prints them out to the Serial Monitor. Upload this example to your
* RedBot and open up the Serial Monitor ... |
def loop():
board.sleep(0.1)
print("IR Sensor Readings: {}, {}, {}".format(IR_sensor_1.read(), IR_sensor_2.read(), IR_sensor_3.read()))
if __name__ == "__main__":
setup()
while True:
loop()
| signal.signal(signal.SIGINT, signal_handler)
print("Welcome to Experiment 6!")
print("------------------------") | identifier_body |
Exp6_LineFollowing_IRSensors.py | """//***********************************************************************
* Exp6_LineFollowing_IRSensors -- RedBot Experiment 6
*
* This code reads the three line following sensors on A3, A6, and A7
* and prints them out to the Serial Monitor. Upload this example to your
* RedBot and open up the Serial Monitor ... | (sig, frame):
"""Helper method to shutdown the RedBot if Ctrl-c is pressed"""
print('\nYou pressed Ctrl+C')
if board is not None:
board.send_reset()
board.shutdown()
sys.exit(0)
def setup():
signal.signal(signal.SIGINT, signal_handler)
print("Welcome to Experiment 6!")
prin... | signal_handler | identifier_name |
Exp6_LineFollowing_IRSensors.py | """//***********************************************************************
* Exp6_LineFollowing_IRSensors -- RedBot Experiment 6
*
* This code reads the three line following sensors on A3, A6, and A7
* and prints them out to the Serial Monitor. Upload this example to your
* RedBot and open up the Serial Monitor ... | loop() | conditional_block | |
bigtable_input.py | izing the distribution of a given dataset in
the game keyspace.
"""
ds = ds.map(lambda row_key, cell: row_key)
# want 'g_0000001234_m_133' is '0000001234.133' and so forth
ds = ds.map(lambda x:
tf.strings.to_number(tf.strings.substr(x, 2, 10) +
'.... | (r):
rk = str(r.row_key, 'utf-8')
g, m = _game_row_key.match(rk).groups()
q = r.cell_value(METADATA, bleak)
return int(g), int(m), float(q)
return sorted([parse(r) for r in rows], key=operator.itemgetter(2))
def require_fresh_games(self, number_fresh):
... | parse | identifier_name |
bigtable_input.py | izing the distribution of a given dataset in
the game keyspace.
"""
ds = ds.map(lambda row_key, cell: row_key)
# want 'g_0000001234_m_133' is '0000001234.133' and so forth
ds = ds.map(lambda x:
tf.strings.to_number(tf.strings.substr(x, 2, 10) +
'.... |
return sorted([parse(r) for r in rows], key=operator.itemgetter(0))
def delete_row_range(self, format_str, start_game, end_game):
"""Delete rows related to the given game range.
Args:
format_str: a string to `.format()` by the game numbers
in order to create the row... | rk = str(r.row_key, 'utf-8')
game = _game_from_counter.match(rk).groups()[0]
return (r.cells[METADATA][move_count][0].timestamp, game) | identifier_body |
bigtable_input.py | , move_count))
def parse(r):
rk = str(r.row_key, 'utf-8')
game = _game_from_counter.match(rk).groups()[0]
return (r.cells[METADATA][move_count][0].timestamp, game)
return sorted([parse(r) for r in rows], key=operator.itemgetter(0))
def delete_row_range(self, for... | utils.dbg('Doing a complete shuffle of %d moves' % moves)
ds = ds.shuffle(moves) | conditional_block | |
bigtable_input.py | , 15, 3),
out_type=tf.float64))
return make_single_array(ds)
def _delete_rows(args):
"""Delete the given row keys from the given Bigtable.
The args are (BigtableSpec, row_keys), but are passed
as a single argument in order to work with
multiprocessing.Pool.map... | last_latest = latest_game | random_line_split | |
event.py | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... |
if dbi and i % 100 == 99:
dbi.abort()
i += 1
| from MaKaC.conference import CategoryManager, ConferenceHolder
confIdx = ConferenceHolder()._getIdx()
categIdx = CategoryManager()._getIdx()
i = 0
for cid, index in self._container.iteritems():
# simple data structure check
for problem in index._check():
... | identifier_body |
event.py | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... |
return self._container[categId]
def add_category(self, categId):
self._container[categId] = IOIndex(IIndexableByStartDateTime)
def index_obj(self, obj):
try:
category = self.getCategory(obj.getOwner().getId())
except KeyError:
# some legacy events are ... | raise KeyError(categId) | conditional_block |
event.py | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | (self, cset):
tsIndex = IOIndex(IIndexableByStartDateTime)
for conf in cset:
tsIndex.index_obj(conf)
return tsIndex
def initialize(self, dbi=None):
from MaKaC.conference import CategoryManager
for cid, categ in CategoryManager()._getIdx().iteritems():
... | _initializeSubIndex | identifier_name |
event.py | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | def _initializeSubIndex(self, cset):
tsIndex = IOIndex(IIndexableByStartDateTime)
for conf in cset:
tsIndex.index_obj(conf)
return tsIndex
def initialize(self, dbi=None):
from MaKaC.conference import CategoryManager
for cid, categ in CategoryManager()._getId... | del self._container[categId]
| random_line_split |
file_loader.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use about_loader;
use mime_classifier::MIMEClassifier;
use mime_guess::guess_mime_type;
use net_traits::ProgressMs... | cancel_listener: CancellationListener) {
assert!(&*load_data.url.scheme == "file");
spawn_named("file_loader".to_owned(), move || {
let file_path: Result<PathBuf, ()> = load_data.url.to_file_path();
match file_path {
Ok(file_path) => {
match File::open(... | random_line_split | |
file_loader.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use about_loader;
use mime_classifier::MIMEClassifier;
use mime_guess::guess_mime_type;
use net_traits::ProgressMs... |
pub fn factory(load_data: LoadData,
senders: LoadConsumer,
classifier: Arc<MIMEClassifier>,
cancel_listener: CancellationListener) {
assert!(&*load_data.url.scheme == "file");
spawn_named("file_loader".to_owned(), move || {
let file_path: Result<PathBuf, ()... | {
let mut metadata = Metadata::default(load_data.url);
let mime_type = guess_mime_type(file_path.as_path());
metadata.set_content_type(Some(&mime_type));
return start_sending_sniffed_opt(senders, metadata, classifier, buf, load_data.context);
} | identifier_body |
file_loader.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use about_loader;
use mime_classifier::MIMEClassifier;
use mime_guess::guess_mime_type;
use net_traits::ProgressMs... | (reader: &mut File, progress_chan: &ProgressSender, cancel_listener: &CancellationListener)
-> Result<LoadResult, String> {
loop {
if cancel_listener.is_cancelled() {
let _ = progress_chan.send(Done(Err("load cancelled".to_owned())));
return Ok(LoadResult::Cancelled);
... | read_all | identifier_name |
inward-entries.client.controller.js | 'use strict';
// InwardEntry controller
angular.module('inward-entries').controller('InwardEntriesController', ['$scope', '$stateParams', '$location', 'Authentication', 'InwardEntries',
function($scope, $stateParams, $location, Authentication, InwardEntries) {
$scope.authentication = Authentication;
// Create ne... |
}
} else {
$scope.inwardentry.$remove(function() {
$location.path('inward-entries');
});
}
};
// Update existing InwardEntry
$scope.update = function() {
var inwardentry = $scope.inwardentry;
inwardentry.$update(function() {
$location.path('inward-entries/' + inwardentry._id);
... | {
$scope.inwardentries.splice(i, 1);
} | conditional_block |
inward-entries.client.controller.js | 'use strict';
// InwardEntry controller
angular.module('inward-entries').controller('InwardEntriesController', ['$scope', '$stateParams', '$location', 'Authentication', 'InwardEntries',
function($scope, $stateParams, $location, Authentication, InwardEntries) {
$scope.authentication = Authentication;
// Create ne... | for (var i in $scope.InwardEntries) {
if ($scope.inwardentries [i] === inwardentry) {
$scope.inwardentries.splice(i, 1);
}
}
} else {
$scope.inwardentry.$remove(function() {
$location.path('inward-entries');
});
}
};
// Update existing InwardEntry
$scope.update = functi... | random_line_split | |
iptables_manager.py | (object):
"""An iptables table."""
def __init__(self, binary_name=binary_name):
self.rules = []
self.remove_rules = []
self.chains = set()
self.unwrapped_chains = set()
self.remove_chains = set()
self.wrap_name = binary_name[:16]
def add_chain(self, name, wr... | IptablesTable | identifier_name | |
iptables_manager.py | name, wrap=True):
"""Ensure the chain is removed.
This removal "cascades". All rule in the chain are removed, as are
all rules in other chains that jump to it.
"""
name = get_chain_name(name, wrap)
chain_set = self._select_chain_set(wrap)
if name not in chain_se... | def defer_apply_off(self):
self.iptables_apply_deferred = False
self._apply()
def apply(self):
if self.iptables_apply_deferred:
return
self._apply()
def _apply(self):
lock_name = 'iptables'
if self.namespace:
lock_name += '-' + self.... |
def defer_apply_on(self):
self.iptables_apply_deferred = True
| random_line_split |
iptables_manager.py | name, wrap=True):
"""Ensure the chain is removed.
This removal "cascades". All rule in the chain are removed, as are
all rules in other chains that jump to it.
"""
name = get_chain_name(name, wrap)
chain_set = self._select_chain_set(wrap)
if name not in chain_se... |
def apply(self):
if self.iptables_apply_deferred:
return
self._apply()
def _apply(self):
lock_name = 'iptables'
if self.namespace:
lock_name += '-' + self.namespace
try:
with lockutils.lock(lock_name, utils.SYNCHRONIZED_PREFIX, Tru... | self.iptables_apply_deferred = False
self._apply() | identifier_body |
iptables_manager.py | name, wrap=True):
"""Ensure the chain is removed.
This removal "cascades". All rule in the chain are removed, as are
all rules in other chains that jump to it.
"""
name = get_chain_name(name, wrap)
chain_set = self._select_chain_set(wrap)
if name not in chain_se... |
else:
self.execute = linux_utils.execute
self.use_ipv6 = use_ipv6
self.root_helper = root_helper
self.namespace = namespace
self.iptables_apply_deferred = False
self.wrap_name = binary_name[:16]
self.ipv4 = {'filter': IptablesTable(binary_name=self.... | self.execute = _execute | conditional_block |
p081.py | # https://projecteuler.net/problem=81
from projecteuler.FileReader import file_to_2D_array_of_ints
# this problem uses a similar solution to problem 18, "Maximum Path Sum 1."
# this problem uses a diamond instead of a pyramid
matrix = file_to_2D_array_of_ints("p081.txt", ",")
y_max = len(matrix) - 1
x_max = len(matri... | print(matrix[0][0]) | random_line_split | |
p081.py | # https://projecteuler.net/problem=81
from projecteuler.FileReader import file_to_2D_array_of_ints
# this problem uses a similar solution to problem 18, "Maximum Path Sum 1."
# this problem uses a diamond instead of a pyramid
matrix = file_to_2D_array_of_ints("p081.txt", ",")
y_max = len(matrix) - 1
x_max = len(matri... |
else:
matrix[y][x] += min(matrix[y][x + 1], matrix[y + 1][x])
print(matrix[0][0])
| matrix[y][x] += matrix[y + 1][x] | conditional_block |
test_param_methods.py | """
Testing for enumerate_param, enumerate_params, and enumerate_keyed_param
"""
import unittest
import mws
# pylint: disable=invalid-name
class TestParamsRaiseExceptions(unittest.TestCase):
"""
Simple test that asserts a ValueError is raised by an improper entry to
`utils.enumerate_keyed_param`.
"""
... | }
def test_multi_params():
"""
A series of params sent as a list of dicts to enumerate_params.
Each param should generate a unique set of keys and values.
Final result should be a flat dict.
"""
param1 = "Summat."
values1 = ("colorful", "cheery", "turkey")
param2 = "FooBaz.what"
... | values = "eleven"
result = mws.utils.enumerate_param(param, values)
assert result == {
"FooBar.1": "eleven", | random_line_split |
test_param_methods.py | """
Testing for enumerate_param, enumerate_params, and enumerate_keyed_param
"""
import unittest
import mws
# pylint: disable=invalid-name
class TestParamsRaiseExceptions(unittest.TestCase):
"""
Simple test that asserts a ValueError is raised by an improper entry to
`utils.enumerate_keyed_param`.
"""
... | ():
"""
A param string with no dot at the end and a list of ints.
List should be ingested in order.
"""
param = "SomethingOrOther"
values = (123, 765, 3512, 756437, 3125)
result = mws.utils.enumerate_param(param, values)
assert result == {
"SomethingOrOther.1": 123,
"Some... | test_single_param_not_dotted_list_values | identifier_name |
test_param_methods.py | """
Testing for enumerate_param, enumerate_params, and enumerate_keyed_param
"""
import unittest
import mws
# pylint: disable=invalid-name
class TestParamsRaiseExceptions(unittest.TestCase):
|
def test_single_param_default():
"""
Test each method type for their default empty dicts.
"""
# Single
assert mws.utils.enumerate_param("something", []) == {}
# Multi
assert mws.utils.enumerate_params() == {}
assert mws.utils.enumerate_params("antler") == {}
# Keyed
assert mws... | """
Simple test that asserts a ValueError is raised by an improper entry to
`utils.enumerate_keyed_param`.
"""
def test_keyed_param_fails_without_dict(self):
"""
Should raise ValueError for values not being a dict.
"""
param = "something"
values = ["this is not a ... | identifier_body |
ws_server.js | /** CONFIG **/
var debug = true;
var log_level = 1; // 1: No, 3: verbose
var encoding = 'utf-8';
var public_html_path = 'public_html';
var http_port = 8000;
var host_ip = '127.0.0.1';
if (process.argv.length > 2) {
host_ip = process.argv[2];
}
if (process.argv.length > 3) {
http_port = process.argv[3];
}
/** ... |
};
var ngv_client_logger = function(con, data) {
if (debug) {
console.log("[Client:"+con.id+"]");
console.log(data);
}
};
/** MAIN **/
/** START SERVER **/
// io = io.listen(http_server);
// io.set('log level', log_level);
http_server.listen(http_port, host_ip);
console.log('[Message]: HTTP ... | {
console.log('[Message]: '+con.id+' disconnected');
} | conditional_block |
ws_server.js | /** CONFIG **/
var debug = true;
var log_level = 1; // 1: No, 3: verbose
var encoding = 'utf-8';
var public_html_path = 'public_html';
var http_port = 8000;
var host_ip = '127.0.0.1';
if (process.argv.length > 2) {
host_ip = process.argv[2];
}
if (process.argv.length > 3) {
http_port = process.argv[3];
}
| /** DATA **/
var blank = {
count : 0,
poll : [0, 0, 0, 0, 0],
};
/** INIT SERVICES **/
var file = new(static.Server)(public_html_path);
var http_server = http.createServer(function(req, res) {
req.addListener('end', function() {
file.serve(req, res);
});
});
/** LOGGERS & ETC **/
var do_nothin... | /** IMPORT MODULES **/
var http = require('http');
var fs = require('fs');
var static = require('node-static');
| random_line_split |
UserManager.js | import UserInfo from "./UserInfo";
class UserManager{
/****************************************************
* static
****************************************************/
static _instance;
static getInstance() {
if (UserManager._instance)
return UserManager._instance;
else
return new UserManager(); |
/****************************************************
* private instance variables
****************************************************/
_info;
_users;
// _reloadLevelsCallback;
// _reloadSettingsCallback;
// _reloadMainCallback;
_reloadCallbacks;
/****************************************************
... | } | random_line_split |
UserManager.js | import UserInfo from "./UserInfo";
class UserManager{
/****************************************************
* static
****************************************************/
static _instance;
static getInstance() {
if (UserManager._instance)
return UserManager._instance;
else
return new UserManager();
... | nfo) ? userInfo : this._info;
this.saveCurrentUserId(info.id);
localStorage.setItem(info.id, JSON.stringify(info.data));
console.log('UserManager.saveUser() > localStorage :', localStorage);
}
saveCurrentUserId(id){
localStorage.setItem('currentUser', id);
}
/********************************************... | em('currentUser');
return this.getUserInfo(currentUserId);
}
saveUser(userInfo){
let info = (userI | identifier_body |
UserManager.js | import UserInfo from "./UserInfo";
class UserManager{
/****************************************************
* static
****************************************************/
static _instance;
static getInstance() {
if (UserManager._instance)
return UserManager._instance;
else
return new UserManager();
... | Info : this._info;
this.saveCurrentUserId(info.id);
localStorage.setItem(info.id, JSON.stringify(info.data));
console.log('UserManager.saveUser() > localStorage :', localStorage);
}
saveCurrentUserId(id){
localStorage.setItem('currentUser', id);
}
/****************************************************
... | ) ? user | identifier_name |
Rx.KitchenSink.d.ts | import { Subject } from './Subject';
import { Observable } from './Observable';
import { CoreOperators } from './CoreOperators';
import { Scheduler as IScheduler } from './Scheduler';
export interface KitchenSinkOperators<T> extends CoreOperators<T> {
isEmpty?: () => Observable<boolean>;
elementAt?: (index: num... | asap: AsapScheduler;
queue: QueueScheduler;
};
declare var Symbol: {
rxSubscriber: any;
};
export { Subject, Scheduler, Observable, Observer, Subscriber, Subscription, AsyncSubject, ReplaySubject, BehaviorSubject, ConnectableObservable, Notification, EmptyError, ArgumentOutOfRangeError, ObjectUnsubscribedEr... | random_line_split | |
penalizer.js | function initialise_sliders(){
$( "div.slider" ).slider({ | step: 0.000000001,
change: changed
});
populate();
};
function slid(event, ui){
update_indicator(event.target.id, ui.value);
}
function update_indicator(slider_id, penalty){
var indicator_id = "#" + slider_id + "Penalty";
$(indicator_id).text(penalty);
}
function changed(event, ui){
var new_... | slide: slid, | random_line_split |
penalizer.js | function initialise_sliders(){
$( "div.slider" ).slider({
slide: slid,
step: 0.000000001,
change: changed
});
populate();
};
function slid(event, ui){
update_indicator(event.target.id, ui.value);
}
function update_indicator(slider_id, penalty){
var indicator_id = "#" + slider_id + "Penalty";
$... | (constraints_list){
for(i=0; i<constraints_list.length; i++){
var constraint = constraints_list[i];
var slider_id = constraint.type;
var penalty = constraint.penalty;
$("#" + slider_id).slider("value",penalty);
update_indicator(slider_id, penalty);
}
}
| get_process_input | identifier_name |
penalizer.js | function initialise_sliders(){
$( "div.slider" ).slider({
slide: slid,
step: 0.000000001,
change: changed
});
populate();
};
function slid(event, ui){
update_indicator(event.target.id, ui.value);
}
function update_indicator(slider_id, penalty){
var indicator_id = "#" + slider_id + "Penalty";
$... |
}
| {
var constraint = constraints_list[i];
var slider_id = constraint.type;
var penalty = constraint.penalty;
$("#" + slider_id).slider("value",penalty);
update_indicator(slider_id, penalty);
} | conditional_block |
penalizer.js | function initialise_sliders(){
$( "div.slider" ).slider({
slide: slid,
step: 0.000000001,
change: changed
});
populate();
};
function slid(event, ui){
update_indicator(event.target.id, ui.value);
}
function update_indicator(slider_id, penalty) |
function changed(event, ui){
var new_constraint = {"type":event.target.id,"penalty":ui.value};
//old constraint value not important - ignored in DB, but stub inserted for consistency with db/ResourceUpdater.pm
var change = {"type":"edition", "old":"stub", "new":new_constraint};
var chang... | {
var indicator_id = "#" + slider_id + "Penalty";
$(indicator_id).text(penalty);
} | identifier_body |
gpio.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use erased_serde::Serialize;
use std::any::Any;
use structopt::StructOpt;
use opentitanlib::app::command::CommandDispatch;
use opentitanlib::app::Tr... | Read(GpioRead),
Write(GpioWrite),
SetMode(GpioSetMode),
SetPullMode(GpioSetPullMode),
} | }
/// Commands for manipulating GPIO pins.
#[derive(Debug, StructOpt, CommandDispatch)]
pub enum GpioCommand { | random_line_split |
gpio.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use erased_serde::Serialize;
use std::any::Any;
use structopt::StructOpt;
use opentitanlib::app::command::CommandDispatch;
use opentitanlib::app::Tr... | {
#[structopt(name = "PIN", help = "The GPIO pin to modify")]
pub pin: String,
#[structopt(
name = "PULLMODE",
possible_values = &PullMode::variants(),
case_insensitive=true,
help = "The weak pull mode of the pin"
)]
pub pull_mode: PullMode,
}
impl CommandDispatch f... | GpioSetPullMode | identifier_name |
log_usingThreadedStream.py | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import
from _... | logs = queue.pop_all()
if not logs:
continue
lines = []
for log in logs:
try:
if log is THREAD_STOP:
please_stop.go()
next_run = time()
else:
expanded = expand_template(lo... | random_line_split | |
log_usingThreadedStream.py | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import
from _... |
else:
self.stream = stream
name = "stream"
# WRITE TO STREAMS CAN BE *REALLY* SLOW, WE WILL USE A THREAD
from mo_threads import Queue
if use_UTF8:
def utf8_appender(value):
if isinstance(value, text_type):
value =... | if stream.startswith("sys."):
use_UTF8 = True # sys.* ARE OLD AND CAN NOT HANDLE unicode
self.stream = eval(stream)
name = stream | conditional_block |
log_usingThreadedStream.py | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import
from _... |
appender = utf8_appender
else:
appender = self.stream.write
self.queue = Queue("queue for " + self.__class__.__name__ + "(" + name + ")", max=10000, silent=True)
self.thread = Thread("log to " + self.__class__.__name__ + "(" + name + ")", time_delta_pusher, appender=ap... | if isinstance(value, text_type):
value = value.encode('utf8')
self.stream.write(value) | identifier_body |
log_usingThreadedStream.py | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import
from _... | (please_stop, appender, queue, interval):
"""
appender - THE FUNCTION THAT ACCEPTS A STRING
queue - FILLED WITH LOG ENTRIES {"template":template, "params":params} TO WRITE
interval - timedelta
USE IN A THREAD TO BATCH LOGS BY TIME INTERVAL
"""
next_run = time() + interval
while not ple... | time_delta_pusher | identifier_name |
mod.rs | pub use self::stack::Stack;
pub use self::word::Word;
use memory;
use memory::MemoryMap;
use self::opcode::{Opcode, PartialAddr, IWord};
mod alu;
mod opcode;
mod stack;
mod word;
pub struct CPU {
p: Word,
i: IWord,
a: Word,
b: Word,
dat: Stack,
ret: Stack,
mem: MemoryMap
}
impl CPU {
... | (&mut self, op: u8, increment: bool) {
let (reg, reg_op) = match (op, increment) {
(3, true) => (&mut self.p, 1), // @p
(7, true) => (&mut self.p, 2), // !p
(0...3, _) => (&mut self.a, op & 3), // a @ ! a!
(4...7, _) => (&mut self.b, op & 3), // b @b !... | exec_register | identifier_name |
mod.rs | pub use self::stack::Stack;
pub use self::word::Word;
use memory;
use memory::MemoryMap;
use self::opcode::{Opcode, PartialAddr, IWord};
mod alu;
mod opcode;
mod stack;
mod word;
pub struct CPU {
p: Word,
i: IWord,
a: Word,
b: Word,
dat: Stack,
ret: Stack,
mem: MemoryMap
}
impl CPU {
... |
fn exec_register(&mut self, op: u8, increment: bool) {
let (reg, reg_op) = match (op, increment) {
(3, true) => (&mut self.p, 1), // @p
(7, true) => (&mut self.p, 2), // !p
(0...3, _) => (&mut self.a, op & 3), // a @ ! a!
(4...7, _) => (&mut self... | {
use self::opcode::Opcode::*;
match opcode {
Unary(op) => alu::unary(op, &mut self.dat),
Binary(op) => alu::binary(op, &mut self.dat, &mut self.ret),
Stack(op) => alu::stack(op, &mut self.dat, &mut self.ret),
Register(op, inc) => self.exec_register(op... | identifier_body |
mod.rs | pub use self::stack::Stack;
pub use self::word::Word;
use memory;
use memory::MemoryMap;
use self::opcode::{Opcode, PartialAddr, IWord};
mod alu;
mod opcode;
mod stack;
mod word;
pub struct CPU {
p: Word,
i: IWord,
a: Word,
b: Word,
dat: Stack,
ret: Stack,
mem: MemoryMap
}
impl CPU {
... | }
}
fn exec_register(&mut self, op: u8, increment: bool) {
let (reg, reg_op) = match (op, increment) {
(3, true) => (&mut self.p, 1), // @p
(7, true) => (&mut self.p, 2), // !p
(0...3, _) => (&mut self.a, op & 3), // a @ ! a!
(4...7, _... | Stack(op) => alu::stack(op, &mut self.dat, &mut self.ret),
Register(op, inc) => self.exec_register(op, inc),
Control(op, addr) => self.exec_control(op, addr) | random_line_split |
test_missing_function_pycode.py | """
@brief test log(time=8s)
@author Xavier Dupre
"""
import sys
import os
import unittest
import shutil
from contextlib import redirect_stdout
from io import StringIO
from pyquickhelper.pycode import ExtTestCase
from pyquickhelper.pycode import process_standard_options_for_setup_help, get_temp_folder
from pyq... |
if __name__ == "__main__":
unittest.main()
| li = ['unittests', '-d', '5']
res = process_argv_for_unittest(li, None)
self.assertNotEmpty(res)
li = ['unittests']
res = process_argv_for_unittest(li, None)
self.assertEmpty(res)
li = ['unittests', '-e', '.*']
res = process_argv_for_unittest(li, None)
sel... | identifier_body |
test_missing_function_pycode.py | """
@brief test log(time=8s)
@author Xavier Dupre
"""
import sys
import os
import unittest
import shutil
from contextlib import redirect_stdout
from io import StringIO
from pyquickhelper.pycode import ExtTestCase
from pyquickhelper.pycode import process_standard_options_for_setup_help, get_temp_folder
from pyq... | (self):
li = [4, '5']
res = hash_list(li)
self.assertEqual(res, "1402b9d4")
li = []
res = hash_list(li)
self.assertEqual(res, "d41d8cd9")
def test_process_argv_for_unittest(self):
li = ['unittests', '-d', '5']
res = process_argv_for_unittest(li, None)... | test_hash_list | identifier_name |
test_missing_function_pycode.py | """
@brief test log(time=8s)
@author Xavier Dupre
"""
import sys
import os
import unittest
import shutil
from contextlib import redirect_stdout
from io import StringIO
from pyquickhelper.pycode import ExtTestCase
from pyquickhelper.pycode import process_standard_options_for_setup_help, get_temp_folder
from pyq... | text = f.getvalue()
self.assertIn('[process_standard_options_for_setup]', text)
self.assertExists(os.path.join(temp, 'bin'))
def test_numeric_module_version(self):
self.assertEqual(numeric_module_version((4, 5)), (4, 5))
self.assertEqual(numeric_module_version("4.5.e"), (4, ... | random_line_split | |
test_missing_function_pycode.py | """
@brief test log(time=8s)
@author Xavier Dupre
"""
import sys
import os
import unittest
import shutil
from contextlib import redirect_stdout
from io import StringIO
from pyquickhelper.pycode import ExtTestCase
from pyquickhelper.pycode import process_standard_options_for_setup_help, get_temp_folder
from pyq... | unittest.main() | conditional_block | |
easy-session-tests.ts | /// <reference path="./easy-session.d.ts" />
/// <reference path="../express-session/express-session.d.ts" />
/// <reference path="../cookie-parser/cookie-parser.d.ts" />
import express = require('express');
import session = require('express-session');
import cookieParser = require('cookie-parser');
import easySession... | req.session.logout(function (err) {
if(err) {
res.send(500);
return;
}
res.send(200);
});
});
app.get('/isloggedin', function (req, res, next) {
res.send(req.session.isLoggedIn('user'));
});
app.get('/isfresh', function (req, res, next) {
res.send(req.se... |
app.post('/logout', function (req, res, next) { | random_line_split |
easy-session-tests.ts | /// <reference path="./easy-session.d.ts" />
/// <reference path="../express-session/express-session.d.ts" />
/// <reference path="../cookie-parser/cookie-parser.d.ts" />
import express = require('express');
import session = require('express-session');
import cookieParser = require('cookie-parser');
import easySession... |
res.send(200);
});
});
app.post('/logout', function (req, res, next) {
req.session.logout(function (err) {
if(err) {
res.send(500);
return;
}
res.send(200);
});
});
app.get('/isloggedin', function (req, res, next) {
res.send(req.session.isLogged... | {
res.send(500);
return;
} | conditional_block |
animation_queue_spec.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 {AnimationQueue} from '@angular/core/src/animation/animation_queue';
import {NgZone} from '../../src/zone/ng_... | expect(() => flushMicrotasks()).not.toThrowError();
expect(log).toEqual(['1', '2', '3']);
}));
});
}
class PlayerThatFails extends MockAnimationPlayer {
private _animationStarted = false;
constructor(public doFail: boolean) { super(); }
play() {
super.play();
this._animation... | p2.onStart(() => log.push('2'));
queue.flush();
| random_line_split |
animation_queue_spec.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 {AnimationQueue} from '@angular/core/src/animation/animation_queue';
import {NgZone} from '../../src/zone/ng_... | queue.enqueue(p3);
expect(log).toEqual([]);
queue.flush();
expect(log).toEqual([]);
flushMicrotasks();
expect(log).toEqual(['1', '2', '3']);
}));
it('should always run each of the animation players outside of the angular zone on start',
fakeAsyn... | {
describe('AnimationQueue', function() {
beforeEach(() => { TestBed.configureTestingModule({declarations: [], imports: []}); });
it('should queue animation players and run when flushed, but only as the next scheduled microtask',
fakeAsync(() => {
const zone = TestBed.get(NgZone);
co... | identifier_body |
animation_queue_spec.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 {AnimationQueue} from '@angular/core/src/animation/animation_queue';
import {NgZone} from '../../src/zone/ng_... | (public doFail: boolean) { super(); }
play() {
super.play();
this._animationStarted = true;
if (this.doFail) {
throw new Error('Oh nooooo');
}
}
reset() { this._animationStarted = false; }
hasStarted() { return this._animationStarted; }
}
| constructor | identifier_name |
animation_queue_spec.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 {AnimationQueue} from '@angular/core/src/animation/animation_queue';
import {NgZone} from '../../src/zone/ng_... |
}
reset() { this._animationStarted = false; }
hasStarted() { return this._animationStarted; }
}
| {
throw new Error('Oh nooooo');
} | conditional_block |
configuration.py | # Copyright 2014 DreamHost, LLC
#
# Author: DreamHost, 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 applicabl... |
return allocations
def generate_floating_config(router):
return [
{'floating_ip': str(fip.floating_ip), 'fixed_ip': str(fip.fixed_ip)}
for fip in router.floating_ips
]
| r = re.compile('[:.]')
allocations = []
for port in ports:
addrs = {
str(fixed.ip_address): subnets_dict[fixed.subnet_id].enable_dhcp
for fixed in port.fixed_ips
}
if not addrs:
continue
allocations.append(
{
'ip_... | identifier_body |
configuration.py | # Copyright 2014 DreamHost, LLC
#
# Author: DreamHost, 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 applicabl... | (subnet):
return {
'cidr': str(subnet.cidr),
'dhcp_enabled': subnet.enable_dhcp and subnet.ipv6_ra_mode != 'slaac',
'dns_nameservers': subnet.dns_nameservers,
'host_routes': subnet.host_routes,
'gateway_ip': (str(subnet.gateway_ip)
if subnet.gateway_ip ... | _subnet_config | identifier_name |
configuration.py | # Copyright 2014 DreamHost, LLC
#
# Author: DreamHost, 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 applicabl... |
def _network_config(client, port, ifname, network_type, network_ports=[]):
subnets = client.get_network_subnets(port.network_id)
subnets_dict = dict((s.id, s) for s in subnets)
return _make_network_config_dict(
_interface_config(ifname, port, subnets_dict),
network_type,
port.netw... | return _make_network_config_dict(
iface, MANAGEMENT_NET, port.network_id) | conditional_block |
configuration.py | # Copyright 2014 DreamHost, LLC
#
# Author: DreamHost, 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 applicabl... | _management_network_config(
router.management_port,
iface_map[router.management_port.mac_address],
interfaces,
)]
retval.extend(
_network_config(
client,
p,
iface_map[p.mac_address],
INTERNAL_NET,
... | _network_config(
client,
router.external_port,
iface_map[router.external_port.mac_address],
EXTERNAL_NET), | random_line_split |
yahoo.py | (InfoExtractor):
IE_DESC = 'Yahoo screen and movies'
_VALID_URL = r'(?P<url>(?P<host>https?://(?:[a-zA-Z]{2}\.)?[\da-zA-Z_-]+\.yahoo\.com)/(?:[^/]+/)*(?P<display_id>.+)?-(?P<id>[0-9]+)(?:-[a-z]+)?\.html)'
_TESTS = [
{
'url': 'http://screen.yahoo.com/julian-smith-travis-legg-watch-2147271... | YahooIE | identifier_name | |
yahoo.py | 4',
'title': 'Communitary - Community Episode 1: Ladders',
'description': 'md5:8fc39608213295748e1e289807838c97',
'duration': 1646,
},
}, {
# it uses an alias to get the video_id
'url': 'https://www.yahoo.com/movies/the-stars-of... | rllib_parse.quote_plus(query), pagenum * 30)
info = self._download_json(result_url, query,
note='Downloading results page ' + str(pagenum + 1))
m = info['m']
results = info['results']
for (i, r) in enumerate(results):
... | conditional_block | |
yahoo.py | 'title': 'Communitary - Community Episode 1: Ladders',
'description': 'md5:8fc39608213295748e1e289807838c97',
'duration': 1646,
},
}, {
# it uses an alias to get the video_id
'url': 'https://www.yahoo.com/movies/the-stars-of-daddys-home-have-v... | n itertools.count(0):
result_url = 'http://video.search.yahoo.com/search/?p=%s&fr=screen&o=js&gs=0&b=%d' % (compat_urllib_parse.quote_plus(query), pagenum * 30)
info = self._download_json(result_url, query,
note='Downloading results page ' + str(pagenum + 1... | identifier_body | |
yahoo.py | tw.screen.yahoo.com/election-2014-askmayor/敢問市長-黃秀霜批賴清德-非常高傲-033009720.html',
'md5': '3a09cf59349cfaddae1797acc3c087fc',
'info_dict': {
'id': 'cac903b3-fcf4-3c14-b632-643ab541712f',
'ext': 'mp4',
'title': '敢問市長/黃秀霜批賴清德「非常高傲」',
'desc... | {
'url': 'https://ca.sports.yahoo.com/video/program-makes-hockey-more-affordable-013127711.html',
'md5': '57e06440778b1828a6079d2f744212c4',
'info_dict': {
'id': 'c9fa2a36-0d4d-3937-b8f6-cc0fb1881e73',
'ext': 'mp4',
'title': 'Pr... | 'duration': 97,
}
}, | random_line_split |
fake_browser.rs | extern crate cookie;
use self::cookie::CookieJar;
extern crate regex;
use self::regex::Regex;
extern crate hyper;
use self::hyper::client::{Client, RedirectPolicy};
use self::hyper::Url;
use std::io::prelude::*;
use std::error::Error;
use std::fmt::{Display, Formatter};
use api::CallError;
/// Function that return... | /// The function implement login process for user without browser
/// _Warning: use the thing careful to privacy and privacy policy of vk.com_
pub fn fake_browser(login: String, password: String, url: String) -> Result<(String, u64, u64),CallError> {
use std::thread::sleep_ms;
use self::hyper::header::{Cookie,L... | random_line_split | |
fake_browser.rs | extern crate cookie;
use self::cookie::CookieJar;
extern crate regex;
use self::regex::Regex;
extern crate hyper;
use self::hyper::client::{Client, RedirectPolicy};
use self::hyper::Url;
use std::io::prelude::*;
use std::error::Error;
use std::fmt::{Display, Formatter};
use api::CallError;
/// Function that return... | (client_id: u64, scope: String, version: String, redirect: String) -> String {
format!("https://oauth.vk.com/authorize?client_id={}&scope={}&redirect_uri={}&display=mobile&v={}&response_type=token", client_id, scope, redirect, version)
}
use std::collections::HashMap;
// Get params send by hidden fields on auth pa... | authorization_client_uri | identifier_name |
fake_browser.rs | extern crate cookie;
use self::cookie::CookieJar;
extern crate regex;
use self::regex::Regex;
extern crate hyper;
use self::hyper::client::{Client, RedirectPolicy};
use self::hyper::Url;
use std::io::prelude::*;
use std::error::Error;
use std::fmt::{Display, Formatter};
use api::CallError;
/// Function that return... |
// Get access token and other data from response URL
fn get_token(u: &Url) -> (String, u64, u64) {
let reg = Regex::new("access_token=([a-f0-9]+)&expires_in=([0-9]+)&user_id=([0-9]+)").unwrap();
let mut token: String = String::new();
let mut expires: u64 = 0u64;
let mut user_id: u64 = 0u64;
for cap... | {
let reg = Regex::new("action=\"([a-z:/?=&.0-9]*)\"").unwrap();
match reg.captures_iter(&*s).next() {
Some(x) => x.at(1).unwrap_or(""),
None => ""
}.into()
} | identifier_body |
gen.rs | use std::rand::Rng;
use std::rand;
fn main() | println!("{}", v.as_slice());
// `shuffle` shuffles a mutable slice in place
rng.shuffle(v.as_mut_slice());
println!("shuffle previous slice");
println!("{}", v.as_slice());
// `choose` will sample an slice *with* replacement
// i.e. the same element can be chosen more than one time
pr... | {
// create a task-local Random Number Generator
let mut rng = rand::task_rng();
// the `gen` methods generates values in the full range of each type using
// a uniform distribution
println!("randomly generate some values for different primitive types");
println!("u8: {}", rng.gen::<u8>());
... | identifier_body |
gen.rs | use std::rand::Rng;
use std::rand;
fn | () {
// create a task-local Random Number Generator
let mut rng = rand::task_rng();
// the `gen` methods generates values in the full range of each type using
// a uniform distribution
println!("randomly generate some values for different primitive types");
println!("u8: {}", rng.gen::<u8>());
... | main | identifier_name |
gen.rs | use std::rand::Rng;
use std::rand;
fn main() {
// create a task-local Random Number Generator
let mut rng = rand::task_rng();
// the `gen` methods generates values in the full range of each type using
// a uniform distribution
println!("randomly generate some values for different primitive types")... | println!("f32: {}", rng.gen::<f32>());
println!("f64: {}", rng.gen::<f64>());
// `gen_iter` returns an iterator that yields a infinite number of randomly
// generated numbers
let mut v: Vec<u8> = rng.gen_iter::<u8>().take(10).collect();
println!("10 randomly generated u8 values");
println!... | println!("u16: {}", rng.gen::<u16>());
println!("i16: {}", rng.gen::<i16>());
// except for floats which get generated in the range [0, 1> | random_line_split |
checkFile.ts | const fileTypeExts = {
pdf: ['pdf'],
image: ['jpg', 'jpeg', 'png'],
pdfImage: ['pdf', 'jpg', 'jpeg', 'png'],
};
const fileTypeAlerts = {
pdf: 'Please choose a pdf document',
image: 'Please choose an image file',
pdfImage: 'Please choose a pdf document or image file',
};
export default function checkFile(i... |
const ext = value
.split('.')
.pop()
.toLowerCase();
if (fileTypeExts[fileType] && !fileTypeExts[fileType].includes(ext)) {
alert(fileTypeAlerts[fileType]);
return false;
}
return true;
}
| {
alert(`The max file size is ${(maxKb || 500) / 1000}MB, please try again.`);
return false;
} | conditional_block |
checkFile.ts | const fileTypeExts = {
pdf: ['pdf'],
image: ['jpg', 'jpeg', 'png'],
pdfImage: ['pdf', 'jpg', 'jpeg', 'png'],
};
const fileTypeAlerts = {
pdf: 'Please choose a pdf document',
image: 'Please choose an image file',
pdfImage: 'Please choose a pdf document or image file',
};
export default function | (inputFiles, value, maxKb, fileType) {
if (
(window as any).FileReader &&
inputFiles &&
inputFiles[0] &&
inputFiles[0].size > (maxKb || 500) * 1000
) {
alert(`The max file size is ${(maxKb || 500) / 1000}MB, please try again.`);
return false;
}
const ext = value
.split('.')
.pop... | checkFile | identifier_name |
checkFile.ts | const fileTypeExts = {
pdf: ['pdf'],
image: ['jpg', 'jpeg', 'png'],
pdfImage: ['pdf', 'jpg', 'jpeg', 'png'],
};
const fileTypeAlerts = {
pdf: 'Please choose a pdf document',
image: 'Please choose an image file',
pdfImage: 'Please choose a pdf document or image file',
};
export default function checkFile(i... | alert(`The max file size is ${(maxKb || 500) / 1000}MB, please try again.`);
return false;
}
const ext = value
.split('.')
.pop()
.toLowerCase();
if (fileTypeExts[fileType] && !fileTypeExts[fileType].includes(ext)) {
alert(fileTypeAlerts[fileType]);
return false;
}
return true;
} | inputFiles &&
inputFiles[0] &&
inputFiles[0].size > (maxKb || 500) * 1000
) { | random_line_split |
checkFile.ts | const fileTypeExts = {
pdf: ['pdf'],
image: ['jpg', 'jpeg', 'png'],
pdfImage: ['pdf', 'jpg', 'jpeg', 'png'],
};
const fileTypeAlerts = {
pdf: 'Please choose a pdf document',
image: 'Please choose an image file',
pdfImage: 'Please choose a pdf document or image file',
};
export default function checkFile(i... | return true;
}
| {
if (
(window as any).FileReader &&
inputFiles &&
inputFiles[0] &&
inputFiles[0].size > (maxKb || 500) * 1000
) {
alert(`The max file size is ${(maxKb || 500) / 1000}MB, please try again.`);
return false;
}
const ext = value
.split('.')
.pop()
.toLowerCase();
if (fileType... | identifier_body |
q_box.rs | will delete its object on drop if it has no parent. If the object has a parent,
/// it's assumed that the parent is responsible for deleting the object, as per Qt ownership system.
/// Additionally, `QBox` will be automatically set to null when the object is deleted, similar
/// to `QPtr` (or `QPointer<T>` in C++). `Q... |
/// Returns the content as a const `Ptr`.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_ptr(&self) -> Ptr<T> {
self.0.as_ptr()
}
/// Returns the content as a raw const pointer.
///
/// ### Safety
///
/// See type level documentation.... | {
self.0.is_null()
} | identifier_body |
q_box.rs | pointer because
/// even if a non-null pointer is provided when constructing `QBox`, it will become null
/// automatically if the object is deleted.
///
/// To prevent the object from being deleted, convert `QBox` to another type of pointer using
/// `into_q_ptr()` or `into_ptr()`. Alternatively, setting a parent for ... | {
T::delete(&*ptr.as_raw_ptr());
} | conditional_block | |
q_box.rs | as_ref()`,
/// or a similar method to check
/// if the object is still alive before calling its methods.
///
/// Unlike `CppBox` (which is non-nullable), `QBox` is permitted to contain a null pointer because
/// even if a non-null pointer is provided when constructing `QBox`, it will become null
/// automatically if th... | drop | identifier_name | |
q_box.rs | will delete its object on drop if it has no parent. If the object has a parent,
/// it's assumed that the parent is responsible for deleting the object, as per Qt ownership system.
/// Additionally, `QBox` will be automatically set to null when the object is deleted, similar
/// to `QPtr` (or `QPointer<T>` in C++). `Q... | /// Returns the content as a raw const pointer.
///
/// ### Safety
///
/// See type level documentation.
pub unsafe fn as_raw_ptr(&self) -> *const T {
self.0.as_raw_ptr()
}
/// Returns the content as a raw mutable pointer.
///
/// ### Safety
///
/// See type leve... | pub unsafe fn as_ptr(&self) -> Ptr<T> {
self.0.as_ptr()
}
| random_line_split |
platform.rs | /*
* Copyright 2017 Sreejith Krishnan R
*
* 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... |
pub fn new_canvas(&self, width: f32, height: f32) -> Canvas {
Canvas::new(width.max(1.), height.max(1.),
self.ruler.get_sk_typeface())
}
}
impl ::platform::Platform for Platform {
fn get_text_ruler(&self, size: f32) -> &TextRuler {
self.ruler.set_size(size);
&s... | {
Platform { ruler: SnapshotRuler::new(typeface, 0) }
} | identifier_body |
platform.rs | /*
* Copyright 2017 Sreejith Krishnan R
*
* 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... | (&self, size: f32) -> &TextRuler {
self.ruler.set_size(size);
&self.ruler
}
fn get_math_ruler(&self, size: f32) -> &MathRuler {
self.ruler.set_size(size);
&self.ruler
}
fn px_to_du(&self, px: f32) -> f32 {
px
}
fn sp_to_du(&self, sp: f32) -> f32 {
... | get_text_ruler | identifier_name |
platform.rs | /*
* Copyright 2017 Sreejith Krishnan R
*
* 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
* | * See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::any::Any;
use ::paint::{TextRuler, MathRuler};
use super::ruler::Ruler as SnapshotRuler;
use super::canvas::Canvas;
pub struct Platform {
ruler: SnapshotRuler,
}
impl Platform {
pub fn new(ty... | * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | random_line_split |
calendar-state.ts | import ModulDate from './../../../../utils/modul-date/modul-date';
import { RangeDate, SingleDate } from './abstract-calendar-state';
export enum CalendarEvent {
DAY_SELECT = 'day-select',
DAY_MOUSE_ENTER = 'day-mouse-enter',
DAY_MOUSE_LEAVE = 'day-mouse-leave',
DAY_KEYBOARD_TAB = 'day-keyboard-tab',
... | isCurrent: boolean;
isDisabled: boolean;
}
export interface YearMonthState {
year: YearState;
months: MonthState[];
}
export interface DayState {
date: ModulDate;
day: number;
month: number;
year: number;
isDisabled: boolean;
isToday: boolean;
isSelected: boolean;
isSel... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.