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 |
|---|---|---|---|---|
enable_transparency.rs | use super::internal_prelude::*;
use imageflow_types::{PixelFormat, CompositingMode};
use crate::ffi::BitmapCompositingMode;
use crate::graphics::bitmaps::BitmapCompositing;
pub static ENABLE_TRANSPARENCY: EnableTransparencyDef = EnableTransparencyDef{};
pub static ENABLE_TRANSPARENCY_MUT: EnableTransparencyMutDef = En... | w: parent.w as u32,
h: parent.h as u32,
x: 0,
y: 0
};
let canvas = ctx.graph
.add_node(Node::n(&CREATE_CANVAS,
NodeParams::Json(canvas_params)));
let copy = ctx.graph
... | from_x: 0,
from_y: 0, | random_line_split |
enable_transparency.rs | use super::internal_prelude::*;
use imageflow_types::{PixelFormat, CompositingMode};
use crate::ffi::BitmapCompositingMode;
use crate::graphics::bitmaps::BitmapCompositing;
pub static ENABLE_TRANSPARENCY: EnableTransparencyDef = EnableTransparencyDef{};
pub static ENABLE_TRANSPARENCY_MUT: EnableTransparencyMutDef = En... |
fn expand(&self, ctx: &mut OpCtxMut, ix: NodeIndex, p: NodeParams, parent: FrameInfo) -> Result<()> {
if parent.fmt == PixelFormat::Bgra32{
ctx.delete_node_and_snap_together(ix);
Ok(())
}else if parent.fmt == PixelFormat::Bgr32 {
let mutate = ctx.graph
... | {
"imazen.enable_transparency"
} | identifier_body |
enable_transparency.rs | use super::internal_prelude::*;
use imageflow_types::{PixelFormat, CompositingMode};
use crate::ffi::BitmapCompositingMode;
use crate::graphics::bitmaps::BitmapCompositing;
pub static ENABLE_TRANSPARENCY: EnableTransparencyDef = EnableTransparencyDef{};
pub static ENABLE_TRANSPARENCY_MUT: EnableTransparencyMutDef = En... | ;
impl NodeDef for EnableTransparencyMutDef{
fn as_one_mutate_bitmap(&self) -> Option<&dyn NodeDefMutateBitmap>{
Some(self)
}
}
impl NodeDefMutateBitmap for EnableTransparencyMutDef{
fn fqn(&self) -> &'static str{
"imazen.enable_transparency_mut"
}
fn mutate(&self, c: &Context, bitma... | EnableTransparencyMutDef | identifier_name |
director.py | # JoeAgent - A Multi-Agent Distributed Application Framework
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at... | self.addListener(shutdown_job)
shutdown_job.run() | random_line_split | |
director.py | # JoeAgent - A Multi-Agent Distributed Application Framework
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at... | (self, config):
self.config = config
def getConfig(self):
return self.config
def addAgentInfo(self, agnt):
assert isinstance(agnt, agent.AgentInfo)
self.agents.append(agnt)
def clearAgentInfoList(self):
self.agents = []
def getAgentInfoList(self):
retur... | setConfig | identifier_name |
director.py | # JoeAgent - A Multi-Agent Distributed Application Framework
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at... |
elif isinstance(evt, agent.MessageReceivedEvent) and \
isinstance(evt.getMessage(), agent.PingResponse):
log.debug("Ping Response recieved")
# Our ping request finally responded
key = evt.getMessage().getRequestKey()
if self.outgoing.has_key(key):
... | log.debug("Ping timeout!")
# A timer popped somewhere
conn = evt.getSource()
# This connection did not respond to the ping, drop it
self.getAgent().dropConnection(evt.getSource()) | conditional_block |
director.py | # JoeAgent - A Multi-Agent Distributed Application Framework
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at... | log.debug("Starting shutdown")
shutdown_job = ShutdownJob(self)
self.addListener(shutdown_job)
shutdown_job.run() | identifier_body | |
main.rs | extern crate rand;
use rand::{thread_rng, Rng};
use std::io::stdin;
const LOWEST: isize = 1;
const HIGHEST: isize = 100;
fn main() | None => println!("numbers only, please"),
Some(n) if n == number => {
println!("you got it in {} tries!", num_guesses);
break;
}
Some(n) if n < number => println!("too low!"),
Some(n) if n > number =>... | {
let mut rng = thread_rng();
loop {
let number: isize = rng.gen_range(LOWEST, HIGHEST + 1);
let mut num_guesses = 0;
println!(
"I have chosen my number between {} and {}. You know what to do",
LOWEST, HIGHEST
);
loop {
num_guesses +... | identifier_body |
main.rs | extern crate rand;
use rand::{thread_rng, Rng};
use std::io::stdin;
const LOWEST: isize = 1;
const HIGHEST: isize = 100;
fn | () {
let mut rng = thread_rng();
loop {
let number: isize = rng.gen_range(LOWEST, HIGHEST + 1);
let mut num_guesses = 0;
println!(
"I have chosen my number between {} and {}. You know what to do",
LOWEST, HIGHEST
);
loop {
num_guesse... | main | identifier_name |
main.rs | extern crate rand;
use rand::{thread_rng, Rng};
use std::io::stdin;
const LOWEST: isize = 1;
const HIGHEST: isize = 100;
fn main() {
let mut rng = thread_rng();
loop {
let number: isize = rng.gen_range(LOWEST, HIGHEST + 1);
let mut num_guesses = 0;
println!(
"I have chos... | }
}
} | Some(_) => println!("something went wrong"),
} | random_line_split |
ticTacToe.py | import random
import os
# TicTacToe
def createNewField():
result = []
for i in range(3):
tmp = []
for i2 in range(3):
tmp.append(' ')
result.append(tmp)
return result
def printField(field):
print ''
for element in field:
print element
print ''
def isFieldFull(field):
occupiedPlaces = 0
for row in... | columns = [[],[],[]]
for row in field:
columns[0].append(row[0])
columns[1].append(row[1])
columns[2].append(row[2])
for col in columns:
if col == ['X','X','X']:
winner = 'User'
return winner
elif col == ['O','O','O']:
winner = 'Computer'
return winner
else:
winner = ''
dia1 = [field[0... | winner = 'Computer'
return winner
else:
winner = ''
| random_line_split |
ticTacToe.py | import random
import os
# TicTacToe
def createNewField():
result = []
for i in range(3):
tmp = []
for i2 in range(3):
tmp.append(' ')
result.append(tmp)
return result
def printField(field):
print ''
for element in field:
print element
print ''
def isFieldFull(field):
occupiedPlaces = 0
for row in... | (field):
fieldStatus = isFieldFull(field)
if fieldStatus == True:
return field
result = field
running = True
"It is the turn of the computer."
while running == True:
row = random.randint(0,2)
column = random.randint(0,2)
if field[row][column] == ' ':
result[row][column] = 'O'
running = False
else:... | KI_Turn | identifier_name |
ticTacToe.py | import random
import os
# TicTacToe
def createNewField():
result = []
for i in range(3):
tmp = []
for i2 in range(3):
tmp.append(' ')
result.append(tmp)
return result
def printField(field):
print ''
for element in field:
print element
print ''
def isFieldFull(field):
occupiedPlaces = 0
for row in... |
else:
winner = ''
dia1 = [field[0][0],field[1][1],field[2][2]]
dia2 = [field[0][2],field[1][1],field[2][0]]
if dia1 == ['X','X','X'] or dia2 == ['X','X','X']:
winner = 'User'
return winner
elif dia1 == ['O','O','O'] or dia2 == ['O','O','O']:
winner = 'Computer'
return winner
else:
winner = ''
fi... | winner = 'Computer'
return winner | conditional_block |
ticTacToe.py | import random
import os
# TicTacToe
def createNewField():
result = []
for i in range(3):
tmp = []
for i2 in range(3):
tmp.append(' ')
result.append(tmp)
return result
def printField(field):
print ''
for element in field:
print element
print ''
def isFieldFull(field):
occupiedPlaces = 0
for row in... |
def Winner(field):
winner = ''
for row in field:
if row == ['X','X','X']:
winner = 'User'
return winner
elif row == ['O','O','O']:
winner = 'Computer'
return winner
else:
winner = ''
columns = [[],[],[]]
for row in field:
columns[0].append(row[0])
columns[1].append(row[1])
columns[2... | fieldStatus = isFieldFull(field)
if fieldStatus == True:
return field
result = field
running = True
print "User it's your turn"
while running == True:
row = int(raw_input('Which row? '))
column = int(raw_input('Which column? '))
if field[row][column] == ' ':
result[row][column] = 'X'
running = False
... | identifier_body |
conditions.js | var Conditions;
Conditions = function() {
var self = this;
this.compare = function( leftValue, rightValue, operator ) {
switch ( operator ) {
/* eslint-disable eqeqeq */
case '==':
return leftValue == rightValue;
case '!=':
return leftValue != rightValue;
/* eslint-enable eqeqeq */
case '!=... | comparisonResult = self.compare( value, term.value, term.operator );
}
if ( isOrCondition ) {
if ( comparisonResult ) {
conditionSucceed = true;
}
return ! comparisonResult;
}
if ( ! comparisonResult ) {
return conditionSucceed = false;
}
} );
return conditionSucceed;
};... | if ( parsedName[ 2 ] ) {
value = value[ parsedName[ 2 ] ];
}
| random_line_split |
conditions.js | var Conditions;
Conditions = function() {
var self = this;
this.compare = function( leftValue, rightValue, operator ) {
switch ( operator ) {
/* eslint-disable eqeqeq */
case '==':
return leftValue == rightValue;
case '!=':
return leftValue != rightValue;
/* eslint-enable eqeqeq */
case '!=... |
} );
return conditionSucceed;
};
};
module.exports = new Conditions();
| {
return conditionSucceed = false;
} | conditional_block |
manager.py | file_list:
file_path = self._filesystem.join(results_directory_path, dir)
if self._filesystem.isdir(file_path) and self._results_directory in file_path:
results_directories.append(file_path)
results_directories.sort(key=lambda x: self._filesystem.mtime(x))
self._... | _check_for_stale_w3c_dir | identifier_name | |
manager.py | , retry_attempt)
def _start_servers(self, tests_to_run):
if self._port.is_wpt_enabled() and any(self._port.is_wpt_test(test) for test in tests_to_run):
self._printer.write_update('Starting WPTServe ...')
self._port.start_wptserve()
self._wptserve_started = True
... | def _worker_number(worker_name):
return int(worker_name.split('/')[1]) if worker_name else -1
stats = {}
for result in initial_results.results_by_name.values():
if result.type != test_expectations.SKIP:
stats[result.test_name] = {'results': (_worker_number(result... | identifier_body | |
manager.py | if self._port.is_wpt_enabled() and self._port.is_wpt_test(test):
return False
return self.WEBSOCKET_SUBDIR in test
def _http_tests(self, test_names):
return set(test for test in test_names if self._is_http_test(test))
def _is_perf_test(self, test):
return self.PERF... | random_line_split | ||
manager.py | test for test in test_names if test not in tests_to_skip]
if not tests_to_run:
return tests_to_run, tests_to_skip
# Create a sorted list of test files so the subset chunk,
# if used, contains alphabetically consecutive tests.
if self._options.order == 'natural':
... | _log.warning('num regressions (%d) exceeds max exit status (%d)' %
(exit_code, test_run_results.MAX_FAILURES_EXIT_STATUS))
exit_code = test_run_results.MAX_FAILURES_EXIT_STATUS | conditional_block | |
xls.py | """ | The lower level xls/xlsm file format handler using xlrd/xlwt
:copyright: (c) 2016-2017 by Onni Software Ltd
:license: New BSD License
"""
import sys
import math
import datetime
import xlrd
from xlwt import Workbook, XFStyle
from pyexcel_io.book import BookReader, BookWriter
from pyexcel_io.sheet import Sh... | pyexcel_xls
~~~~~~~~~~~~~~~~~~~
| random_line_split |
xls.py | """
pyexcel_xls
~~~~~~~~~~~~~~~~~~~
The lower level xls/xlsm file format handler using xlrd/xlwt
:copyright: (c) 2016-2017 by Onni Software Ltd
:license: New BSD License
"""
import sys
import math
import datetime
import xlrd
from xlwt import Workbook, XFStyle
from pyexcel_io.book import BookReade... | (self):
self.skip_hidden_sheets = self._keywords.get(
'skip_hidden_sheets', True)
class XLSheetWriter(SheetWriter):
"""
xls sheet writer
"""
def set_sheet_name(self, name):
"""Create a sheet
"""
self._native_sheet = self._native_book.add_sheet(name)
... | _get_params | identifier_name |
xls.py | """
pyexcel_xls
~~~~~~~~~~~~~~~~~~~
The lower level xls/xlsm file format handler using xlrd/xlwt
:copyright: (c) 2016-2017 by Onni Software Ltd
:license: New BSD License
"""
import sys
import math
import datetime
import xlrd
from xlwt import Workbook, XFStyle
from pyexcel_io.book import BookReade... |
def number_of_columns(self):
"""
Number of columns in the xls sheet
"""
return self._native_sheet.ncols
def cell_value(self, row, column):
"""
Random access to the xls cells
"""
cell_type = self._native_sheet.cell_type(row, column)
value... | """
Number of rows in the xls sheet
"""
return self._native_sheet.nrows | identifier_body |
xls.py | """
pyexcel_xls
~~~~~~~~~~~~~~~~~~~
The lower level xls/xlsm file format handler using xlrd/xlwt
:copyright: (c) 2016-2017 by Onni Software Ltd
:license: New BSD License
"""
import sys
import math
import datetime
import xlrd
from xlwt import Workbook, XFStyle
from pyexcel_io.book import BookReade... |
return ret
_xls_reader_registry = {
"file_type": "xls",
"reader": XLSBook,
"writer": XLSWriter,
"stream_type": "binary",
"mime_type": "application/vnd.ms-excel",
"library": "pyexcel-xls"
}
_XLSM_MIME = (
"application/" +
"vnd.openxmlformats-officedocument.spreadsheetml.sheet")
_... | ret = datetime.datetime(
date_tuple[0],
date_tuple[1],
date_tuple[2],
date_tuple[3],
date_tuple[4],
date_tuple[5]
) | conditional_block |
evaluate_graph_reconstruction.py | try: import cPickle as pickle
except: import pickle
from gem.evaluation import metrics
from gem.utils import evaluation_util, graph_util
import networkx as nx
import numpy as np
def evaluateStaticGraphReconstruction(digraph, graph_embedding,
X_stat, node_l=None, file_suffix=None,... | prec_curv, _ = metrics.computePrecisionCurve(predicted_edge_list, digraph)
# If weighted, compute the error in reconstructed weights of observed edges
if is_weighted:
digraph_adj = nx.to_numpy_matrix(digraph)
estimated_adj[digraph_adj == 0] = 0
err = np.linalg.norm(digraph_adj - esti... | MAP = metrics.computeMAP(predicted_edge_list, digraph, is_undirected=is_undirected) | random_line_split |
evaluate_graph_reconstruction.py | try: import cPickle as pickle
except: import pickle
from gem.evaluation import metrics
from gem.utils import evaluation_util, graph_util
import networkx as nx
import numpy as np
def evaluateStaticGraphReconstruction(digraph, graph_embedding,
X_stat, node_l=None, file_suffix=None,... | (digraph, graph_embedding,
X, n_sampled_nodes, rounds,
res_pre, m_summ,
is_undirected=True):
print('\tGraph Reconstruction')
summ_file = open('%s_%s.grsumm' % (res_pre, m_summ), 'w')
summ_file.write('Method\t%s\n' % metrics.getMetricsHeader())
if len(digraph.nodes) <= n_sam... | expGR | identifier_name |
evaluate_graph_reconstruction.py | try: import cPickle as pickle
except: import pickle
from gem.evaluation import metrics
from gem.utils import evaluation_util, graph_util
import networkx as nx
import numpy as np
def evaluateStaticGraphReconstruction(digraph, graph_embedding,
X_stat, node_l=None, file_suffix=None,... | is_undirected=is_undirected,
edge_pairs=eval_edge_pairs
)
MAP = metrics.computeMAP(predicted_edge_list, digraph, is_undirected=is_undirected)
prec_curv, _ = metrics.computePrecisionCurve(predicted_edge_list, digraph)
# If weighted, compute the error in reconstructed weights of observed e... | node_num = len(digraph.nodes)
# evaluation
if sample_ratio_e:
eval_edge_pairs = evaluation_util.getRandomEdgePairs(
node_num,
sample_ratio_e,
is_undirected
)
else:
eval_edge_pairs = None
if file_suffix is None:
estimated_adj = graph_emb... | identifier_body |
evaluate_graph_reconstruction.py | try: import cPickle as pickle
except: import pickle
from gem.evaluation import metrics
from gem.utils import evaluation_util, graph_util
import networkx as nx
import numpy as np
def evaluateStaticGraphReconstruction(digraph, graph_embedding,
X_stat, node_l=None, file_suffix=None,... |
predicted_edge_list = evaluation_util.getEdgeListFromAdjMtx(
estimated_adj,
is_undirected=is_undirected,
edge_pairs=eval_edge_pairs
)
MAP = metrics.computeMAP(predicted_edge_list, digraph, is_undirected=is_undirected)
prec_curv, _ = metrics.computePrecisionCurve(predicted_edge_l... | estimated_adj = graph_embedding.get_reconstructed_adj(
X_stat,
file_suffix,
node_l
) | conditional_block |
InfixtoPostfixConverter.py | import string
from operator import ge as greater_than_or_equal, gt as greater_than
from collections import deque
OPERATOR_PRECEDENCE = {
'(':0,
'+':1,
'-':1,
'*':2,
'/':2,
'^':3,
}
RIGHT_ASSOCIATIVE_OPERATORS = '^'
LEFT_ASSOCIATIVE_OPERATORS = '+-/*'
def | (operators, output, token):
"""
Pop operators from the queue. left associative and right assoc fns are compared slightly differently!
:type operators: deque
:type output: deque
:type token: str
:return: None
"""
comparison_op = greater_than if token in RIGHT_ASSOCIATIVE_OPERATORS else gr... | pop_operator_queue | identifier_name |
InfixtoPostfixConverter.py | import string
from operator import ge as greater_than_or_equal, gt as greater_than
from collections import deque
OPERATOR_PRECEDENCE = {
'(':0,
'+':1,
'-':1,
'*':2,
'/':2,
'^':3,
}
RIGHT_ASSOCIATIVE_OPERATORS = '^'
LEFT_ASSOCIATIVE_OPERATORS = '+-/*'
def pop_operator_queue(operators, output,... | output.append(operators.pop())
return ''.join(output).replace('(','')
import unittest
class TestFirst(unittest.TestCase):
def testFirst(self):
test = self
Test = self
test.assert_equals = Test.assertEqual
Test.assert_equals = Test.assertEqual
Test.assert_equa... | infix = deque(infix)
output = deque()
operators = deque()
while infix:
token = infix.popleft()
if token in string.digits:
output.append(token)
elif token == '(':
operators.append(token)
elif token == ')':
while operators and operators[-1] !... | identifier_body |
InfixtoPostfixConverter.py | import string
from operator import ge as greater_than_or_equal, gt as greater_than
from collections import deque
OPERATOR_PRECEDENCE = {
'(':0,
'+':1,
'-':1,
'*':2,
'/':2,
'^':3,
}
RIGHT_ASSOCIATIVE_OPERATORS = '^'
LEFT_ASSOCIATIVE_OPERATORS = '+-/*'
def pop_operator_queue(operators, output,... |
output.append(operators.pop())
elif token in LEFT_ASSOCIATIVE_OPERATORS:
# >=
pop_operator_queue(operators, output, token)
elif token in RIGHT_ASSOCIATIVE_OPERATORS:
# >
pop_operator_queue(operators, output, token)
while operators:
... | output.append(operators.pop()) | conditional_block |
InfixtoPostfixConverter.py | import string
from operator import ge as greater_than_or_equal, gt as greater_than
from collections import deque
OPERATOR_PRECEDENCE = {
'(':0,
'+':1,
'-':1, | RIGHT_ASSOCIATIVE_OPERATORS = '^'
LEFT_ASSOCIATIVE_OPERATORS = '+-/*'
def pop_operator_queue(operators, output, token):
"""
Pop operators from the queue. left associative and right assoc fns are compared slightly differently!
:type operators: deque
:type output: deque
:type token: str
:return:... | '*':2,
'/':2,
'^':3,
}
| random_line_split |
assistant.rs | use std::mem::transmute;
use std::boxed::Box as Box_;
use Assistant;
use ffi;
use glib::object::IsA;
use glib_ffi;
pub trait AssistantExtManual {
fn set_forward_page_func<F: Fn(i32) -> i32 + 'static>(&self, f: F);
}
impl<O: IsA<Assistant>> AssistantExtManual for O {
fn set_forward_page_func<F: Fn(i32) -> i32... | }
unsafe extern "C" fn forward_page_trampoline(current_page: i32, f: glib_ffi::gpointer) -> i32 {
callback_guard!();
let f: &Box_<Fn(i32) -> i32 + 'static> = transmute(f);
f(current_page)
}
unsafe extern "C" fn destroy_closure(ptr: glib_ffi::gpointer) {
callback_guard!();
Box_::<Box_<Fn(i32) -> i3... | Some(forward_page_trampoline), Box_::into_raw(f) as *mut _, Some(destroy_closure))
}
} | random_line_split |
assistant.rs | use std::mem::transmute;
use std::boxed::Box as Box_;
use Assistant;
use ffi;
use glib::object::IsA;
use glib_ffi;
pub trait AssistantExtManual {
fn set_forward_page_func<F: Fn(i32) -> i32 + 'static>(&self, f: F);
}
impl<O: IsA<Assistant>> AssistantExtManual for O {
fn set_forward_page_func<F: Fn(i32) -> i32... | (current_page: i32, f: glib_ffi::gpointer) -> i32 {
callback_guard!();
let f: &Box_<Fn(i32) -> i32 + 'static> = transmute(f);
f(current_page)
}
unsafe extern "C" fn destroy_closure(ptr: glib_ffi::gpointer) {
callback_guard!();
Box_::<Box_<Fn(i32) -> i32 + 'static>>::from_raw(ptr as *mut _);
}
| forward_page_trampoline | identifier_name |
assistant.rs | use std::mem::transmute;
use std::boxed::Box as Box_;
use Assistant;
use ffi;
use glib::object::IsA;
use glib_ffi;
pub trait AssistantExtManual {
fn set_forward_page_func<F: Fn(i32) -> i32 + 'static>(&self, f: F);
}
impl<O: IsA<Assistant>> AssistantExtManual for O {
fn set_forward_page_func<F: Fn(i32) -> i32... | {
callback_guard!();
Box_::<Box_<Fn(i32) -> i32 + 'static>>::from_raw(ptr as *mut _);
} | identifier_body | |
test.rs | use std::thread::{self, sleep_ms};
use std::sync::{Arc};
use std::sync::atomic::{AtomicUsize};
use std::sync::atomic::Ordering::{SeqCst};
use spsc::unbounded::{new};
use super::{Select, Selectable};
fn ms_sleep(ms: i64) {
sleep_ms(ms as u32);
}
#[test]
fn no_wait_one() {
let (send, recv) = new();
send.se... | // make sure that we wait for the other thread before dropping anything else
drop(thread);
}
#[test]
fn select_chance() {
// Check that only one selecting thread wakes up.
let counter1 = Arc::new(AtomicUsize::new(0));
let counter2 = counter1.clone();
let counter3 = counter1.clone();
let (... | {
// Check that cross thread selecting works.
let (send1, recv1) = new();
let (send2, recv2) = new();
let id1 = recv1.id();
let id2 = recv2.id();
let select1 = Arc::new(Select::new());
let select2 = select1.clone();
let thread = thread::scoped(move || {
select2.add(&recv2);
... | identifier_body |
test.rs | use std::thread::{self, sleep_ms};
use std::sync::{Arc};
use std::sync::atomic::{AtomicUsize};
use std::sync::atomic::Ordering::{SeqCst};
use spsc::unbounded::{new};
use super::{Select, Selectable};
fn ms_sleep(ms: i64) {
sleep_ms(ms as u32);
}
#[test]
fn no_wait_one() {
let (send, recv) = new();
send.se... |
}
}
assert!(saw1);
}
#[test]
fn select_wrong_thread() {
// Check that cross thread selecting works.
let (send1, recv1) = new();
let (send2, recv2) = new();
let id1 = recv1.id();
let id2 = recv2.id();
let select1 = Arc::new(Select::new());
let select2 = select1.clone();
... | {
break 'outer;
} | conditional_block |
test.rs | use std::thread::{self, sleep_ms};
use std::sync::{Arc};
use std::sync::atomic::{AtomicUsize};
use std::sync::atomic::Ordering::{SeqCst};
use spsc::unbounded::{new};
use super::{Select, Selectable};
fn ms_sleep(ms: i64) {
sleep_ms(ms as u32);
}
#[test]
fn no_wait_one() {
let (send, recv) = new();
send.se... | fn no_wait_two() {
let (send, recv) = new();
let (send2, recv2) = new();
send.send(1u8).unwrap();
send2.send(1u8).unwrap();
let select = Select::new();
select.add(&recv);
select.add(&recv2);
assert!(select.wait(&mut [0, 0]).len() == 2);
}
#[test]
fn wait_two() {
let (send, recv) = n... | }
#[test] | random_line_split |
test.rs | use std::thread::{self, sleep_ms};
use std::sync::{Arc};
use std::sync::atomic::{AtomicUsize};
use std::sync::atomic::Ordering::{SeqCst};
use spsc::unbounded::{new};
use super::{Select, Selectable};
fn | (ms: i64) {
sleep_ms(ms as u32);
}
#[test]
fn no_wait_one() {
let (send, recv) = new();
send.send(1u8).unwrap();
let select = Select::new();
select.add(&recv);
assert!(select.wait(&mut [0]).len() == 1);
}
#[test]
fn wait_one() {
let (send, recv) = new();
thread::spawn(move || {
... | ms_sleep | identifier_name |
index.js | /*
* Copyright (c) 2014, Groupon, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditio... | (binPath, tempPath) {
return function withCallback(callback) {
return getLatestVersion((error, metadata) => {
if (error != null) {
return callback(error);
}
/* eslint no-console: 0 */
console.log(
'[testium] grabbing selenium chromedriver %s',
metadata.version
... | downloadChromeDriver | identifier_name |
index.js | /*
* Copyright (c) 2014, Groupon, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditio... |
/* eslint no-console: 0 */
console.log(
'[testium] grabbing selenium chromedriver %s',
metadata.version
);
return download(
binPath,
tempPath,
metadata.version,
metadata.downloadUrl,
callback
);
});
};
}
module.exports = downlo... | {
return callback(error);
} | conditional_block |
index.js | /*
* Copyright (c) 2014, Groupon, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditio... | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE... | * specific prior written permission.
* | random_line_split |
index.js | /*
* Copyright (c) 2014, Groupon, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditio... | }
module.exports = downloadChromeDriver;
| {
return function withCallback(callback) {
return getLatestVersion((error, metadata) => {
if (error != null) {
return callback(error);
}
/* eslint no-console: 0 */
console.log(
'[testium] grabbing selenium chromedriver %s',
metadata.version
);
return dow... | identifier_body |
NumPyUtil.py | # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from typing import Union, List, cast
import numpy
from copy import deepcopy
def immutableNDArray(nda: Union[List, numpy.ndarray]) -> numpy.ndarray:
"""Creates an immutable copy of the given narray
If the array... |
if not data.flags.writeable:
return data
copy = deepcopy(data)
copy.flags.writeable = False
return copy
| data = cast(numpy.ndarray, nda) | conditional_block |
NumPyUtil.py | # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from typing import Union, List, cast
import numpy
from copy import deepcopy
def | (nda: Union[List, numpy.ndarray]) -> numpy.ndarray:
"""Creates an immutable copy of the given narray
If the array is already immutable then it just returns it.
:param nda: :type{numpy.ndarray} the array to copy. May be a list
:return: :type{numpy.ndarray} an immutable narray
"""
if nda is None... | immutableNDArray | identifier_name |
NumPyUtil.py | # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from typing import Union, List, cast
import numpy
from copy import deepcopy
def immutableNDArray(nda: Union[List, numpy.ndarray]) -> numpy.ndarray:
| return copy
| """Creates an immutable copy of the given narray
If the array is already immutable then it just returns it.
:param nda: :type{numpy.ndarray} the array to copy. May be a list
:return: :type{numpy.ndarray} an immutable narray
"""
if nda is None:
return None
if type(nda) is list:
... | identifier_body |
NumPyUtil.py | # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from typing import Union, List, cast
import numpy
from copy import deepcopy
def immutableNDArray(nda: Union[List, numpy.ndarray]) -> numpy.ndarray:
"""Creates an immutable copy of the given narray
If the array... | copy.flags.writeable = False
return copy | random_line_split | |
regiment.js | 'use strict';
const os = require('os');
const cluster = require('cluster');
const DEFAULT_DEADLINE_MS = 30000;
function makeWorker(workerFunc) {
var server = workerFunc(cluster.worker.id);
server.on('close', function() {
process.exit();
});
process.on('SIGTERM', function() {
server.close();
});
... | ensureDeath(worker);
}
function ensureDeath(worker) {
setTimeout(() => {
logger.log(`Ensured death of ${worker.id}`);
worker.kill();
}, deadline).unref();
worker.disconnect();
}
function respawn(worker, code, signal) {
if (running && !worker.exitedAfterDisconnect) {
logge... | random_line_split | |
regiment.js | 'use strict';
const os = require('os');
const cluster = require('cluster');
const DEFAULT_DEADLINE_MS = 30000;
function makeWorker(workerFunc) {
var server = workerFunc(cluster.worker.id);
server.on('close', function() {
process.exit();
});
process.on('SIGTERM', function() {
server.close();
});
... | () {
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
cluster.on('exit', respawn);
}
function shutdown() {
running = false;
logger.log(`Shutting down!`);
for (var id in cluster.workers) {
kill(cluster.workers[id]);
}
}
listen();
fork();
}
Regiment.middlewar... | listen | identifier_name |
regiment.js | 'use strict';
const os = require('os');
const cluster = require('cluster');
const DEFAULT_DEADLINE_MS = 30000;
function makeWorker(workerFunc) {
var server = workerFunc(cluster.worker.id);
server.on('close', function() {
process.exit();
});
process.on('SIGTERM', function() {
server.close();
});
... |
listen();
fork();
}
Regiment.middleware = require('./middleware');
module.exports = Regiment;
| {
running = false;
logger.log(`Shutting down!`);
for (var id in cluster.workers) {
kill(cluster.workers[id]);
}
} | identifier_body |
DrawerPanel.tsx | import { themeColor, themeSpacing } from '@amsterdam/asc-ui'
import styled, { css } from 'styled-components'
import { DeviceMode, isMobile } from '../DrawerOverlay'
import { slideInDesktop, slideInMobile } from './keyframes'
const STACK_SPACING = 8
interface DrawerPanelProps {
stackLevel?: number
deviceMode?: Dev... |
${({ deviceMode = defaultDeviceMode, stackLevel = 0 }) => {
if (isMobile(deviceMode)) {
return css`
margin-top: ${themeSpacing(STACK_SPACING * stackLevel)};
`
}
}}
`
export default DrawerPanel | random_line_split | |
DrawerPanel.tsx | import { themeColor, themeSpacing } from '@amsterdam/asc-ui'
import styled, { css } from 'styled-components'
import { DeviceMode, isMobile } from '../DrawerOverlay'
import { slideInDesktop, slideInMobile } from './keyframes'
const STACK_SPACING = 8
interface DrawerPanelProps {
stackLevel?: number
deviceMode?: Dev... |
}}
`
export default DrawerPanel
| {
return css`
margin-top: ${themeSpacing(STACK_SPACING * stackLevel)};
`
} | conditional_block |
Core.ts | /*
* Copyright 2015-2017 Atomist Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | export { PomMutableViewMutatingFunctions };
export { PomMutableViewNonMutatingFunctions };
export { Project };
export { ProjectDecorating };
export { Properties };
export { PythonFile };
export { ScalaFile };
export { SpringBootProject };
export { TypeDeclarationView };
export { ViewSupport };
export { Xml };
export { ... | export { MutableTerminal };
export { MutableView };
export { OverwritableText };
export { Pair };
export { Pom }; | random_line_split |
titcoin.py | import os
import platform
from twisted.internet import defer
from .. import data, helper
from p2pool.util import pack | P2P_PREFIX = '25174c22'.decode('hex')
P2P_PORT = 8698
ADDRESS_VERSION = 0
RPC_PORT = 8697
RPC_CHECK = defer.inlineCallbacks(lambda bitcoind: defer.returnValue(
(yield helper.check_genesis_block(bitcoind, '00000000bb82b1cbe86b5fe62967c13ff2e8cdabf68adeea2038289771c3491f')) and
not (yield bitcoind... | random_line_split | |
dialog.ts | import { Component } from '@angular/core';
@Component({
selector: 'demo-dialog',
templateUrl: './dialog.html',
styleUrls: ['./dialog.less']
})
export class DialogDemo {
tsCodeBasic: string = require('!!raw-loader!./basic/dialog-basic.ts');
htmlCodeBasic: string = require('!!raw-loader!./basic/dial... | } | lessCodeContent: string = require('!!raw-loader!./content/dialog-content.less');
tsCodeDynamic: string = require('!!raw-loader!./dynamic/dialog-dynamic.ts');
htmlCodeDynamic: string = require('!!raw-loader!./dynamic/dialog-dynamic.html');
lessCodeDynamic: string = require('!!raw-loader!./dynamic/dialog... | random_line_split |
dialog.ts | import { Component } from '@angular/core';
@Component({
selector: 'demo-dialog',
templateUrl: './dialog.html',
styleUrls: ['./dialog.less']
})
export class | {
tsCodeBasic: string = require('!!raw-loader!./basic/dialog-basic.ts');
htmlCodeBasic: string = require('!!raw-loader!./basic/dialog-basic.html');
lessCodeBasic: string = require('!!raw-loader!./basic/dialog-basic.less');
tsCodeContent: string = require('!!raw-loader!./content/dialog-content.ts');
... | DialogDemo | identifier_name |
resource_scale_factors.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for Chromium browser resources.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about t... | (filename):
with open(filename, 'rb', buffering=0) as f:
data = f.read(24)
if data[:8] != '\x89PNG\r\n\x1A\n' or data[12:16] != 'IHDR':
raise InvalidPNGException
return struct.unpack('>ii', data[16:24])
# Returns a list of valid scaled image sizes. The valid sizes are the
# fl... | ImageSize | identifier_name |
resource_scale_factors.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for Chromium browser resources.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about t... |
corrupt_png_error = ('Corrupt PNG in file %s. Note that binaries are not '
'correctly uploaded to the code review tool and must be directly '
'submitted using the dcommit command.')
for f in files:
base_image = self.input_api.os_path.join(self.paths[0][1], f)
if not os.path.exists(... | files.append(relative_path) | conditional_block |
resource_scale_factors.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for Chromium browser resources.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about t... | having the correct dimensions.
"""
def ImageSize(filename):
with open(filename, 'rb', buffering=0) as f:
data = f.read(24)
if data[:8] != '\x89PNG\r\n\x1A\n' or data[12:16] != 'IHDR':
raise InvalidPNGException
return struct.unpack('>ii', data[16:24])
# Returns a li... | Returns:
An array of presubmit errors if any images were detected not | random_line_split |
resource_scale_factors.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for Chromium browser resources.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about t... |
def RunChecks(self):
"""Verifies the scale factors of resources being added or modified.
Returns:
An array of presubmit errors if any images were detected not
having the correct dimensions.
"""
def ImageSize(filename):
with open(filename, 'rb', buffering=0) as f:
data ... | """ Initializes ResourceScaleFactors with paths."""
self.input_api = input_api
self.output_api = output_api
self.paths = paths | identifier_body |
main.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 * as fs from 'fs';
import * as path from 'path';
import * as tsickle from 'tsickle';
import * as ts from 'typ... |
const file = files[0];
const indexModule = file.replace(/\.ts$/, '');
const bundler =
new MetadataBundler(indexModule, ngOptions.flatModuleId, new CompilerHostAdapter(host));
const metadataBundle = bundler.getMetadataBundle();
const metadata = JSON.stringify(metadataBundle.metadata);
const name =
... | {
return {
host,
errors: [{
file: null as any as ts.SourceFile,
start: null as any as number,
length: null as any as number,
messageText:
'Angular compiler option "flatModuleIndex" requires one and only one .ts file in the "files" field.',
category: ts... | conditional_block |
main.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 * as fs from 'fs';
import * as path from 'path';
import * as tsickle from 'tsickle';
import * as ts from 'typ... | (
project: string | VinylFile, cliOptions: CliOptions, codegen?: CodegenExtension,
options?: ts.CompilerOptions): Promise<any> {
try {
let projectDir = project;
// project is vinyl like file object
if (isVinylFile(project)) {
projectDir = path.dirname(project.path);
}
// project is p... | main | identifier_name |
main.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 * as fs from 'fs';
import * as path from 'path';
import * as tsickle from 'tsickle';
import * as ts from 'typ... | const DTS = /\.d\.ts$/;
const JS_EXT = /(\.js|)$/;
const TS_EXT = /\.ts$/;
export interface CodegenExtension {
/**
* Returns the generated file names.
*/
(ngOptions: NgOptions, cliOptions: CliOptions, program: ts.Program,
host: ts.CompilerHost): Promise<string[]>;
}
export function createBundleIndexHost(... | import {check, tsc} from './tsc';
import {isVinylFile, VinylFile} from './vinyl_file';
export {UserError} from './tsc';
| random_line_split |
main.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 * as fs from 'fs';
import * as path from 'path';
import * as tsickle from 'tsickle';
import * as ts from 'typ... | return ts.createProgram(rootFileNames.slice(0), parsed.options, host, oldProgram);
};
const addGeneratedFileName = (genFileName: string) => {
if (genFileName.startsWith(basePath) && TS_EXT.exec(genFileName)) {
rootFileNames.push(genFileName);
}
};
const diagnostics = (parsed.o... | {
try {
let projectDir = project;
// project is vinyl like file object
if (isVinylFile(project)) {
projectDir = path.dirname(project.path);
}
// project is path to project file
else if (fs.lstatSync(project).isFile()) {
projectDir = path.dirname(project);
}
// file names i... | identifier_body |
disk.py | #coding:UTF-8
"""
磁盘监控模块
"""
from config import disk
from lib import core
import os,re
def init():
"对外接口"
sign=True
for t in disk.DISK_PATH:
warn,data=check(t)
if not warn: | message="磁盘监控预警提示,磁盘使用率超过%s"%(disk.DISK_USED)+"%\n监控结果:"+data
message=message.decode("UTF-8")
print message
core.sendEmail(message)
print u"邮件已经发出"
sign=False
return sign
def getIntervalTime():
"获取检测间隔时间"
return disk.DISK_DELAY
... | login_time=time.time() | random_line_split |
disk.py | #coding:UTF-8
"""
磁盘监控模块
"""
from config import disk
from lib import core
import os,re
def init():
"对外接口"
sign=True
for t in disk.DISK_PATH:
warn,data=check(t)
if not warn:
login_time=time.time()
message="磁盘监控预警提示,磁盘使用率超过%s"%(disk.DISK_USED)+"%\n监控结果:"+data
... | 检测是否超出预警"
r=os.popen("df -h "+path)
for line in r:
data=line.rstrip()
datas=re.split(r'\s+',data)
used=datas[4].encode("UTF-8").replace("%","")
return int(used) < disk.DISK_USED,data
| ck(path):
" | identifier_name |
disk.py | #coding:UTF-8
"""
磁盘监控模块
"""
from config import disk
from lib import core
import os,re
def init():
"对外接口"
sign=True
for t in disk.DISK_PATH:
warn,data=check(t)
if not warn:
login_time=time.time()
message="磁盘监控预警提示,磁盘使用率超过%s"%(disk.DISK_USED)+"%\n监控结果:"+data
... | disk.DISK_USED,data
| eturn int(used) < | conditional_block |
disk.py | #coding:UTF-8
"""
磁盘监控模块
"""
from config import disk
from lib import core
import os,re
def init():
"对外接口"
s |
def check(path):
"检测是否超出预警"
r=os.popen("df -h "+path)
for line in r:
data=line.rstrip()
datas=re.split(r'\s+',data)
used=datas[4].encode("UTF-8").replace("%","")
return int(used) < disk.DISK_USED,data
| ign=True
for t in disk.DISK_PATH:
warn,data=check(t)
if not warn:
login_time=time.time()
message="磁盘监控预警提示,磁盘使用率超过%s"%(disk.DISK_USED)+"%\n监控结果:"+data
message=message.decode("UTF-8")
print message
core.sendEmail(message)
print u... | identifier_body |
util.rs | //! Module for utility functions.
/// Verifies equality between an array of length 16 and a slice of unknown length.
pub fn verify_16(x: &[u8; 16], y: &[u8]) -> bool |
#[inline(never)]
pub(crate) fn verify_inner(x: &impl AsRef<[u8]>, y: &[u8]) -> u8 {
let x = x.as_ref();
assert_eq!(x.len(), y.len());
x.iter().zip(y).fold(0, |acc, (x, y)| acc | (x ^ y))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_verify_16() {
assert!(verify_16(b"abcdef... | {
x.len() == y.len() && verify_inner(x, y) == 0
} | identifier_body |
util.rs | //! Module for utility functions.
/// Verifies equality between an array of length 16 and a slice of unknown length.
pub fn verify_16(x: &[u8; 16], y: &[u8]) -> bool {
x.len() == y.len() && verify_inner(x, y) == 0
}
#[inline(never)]
pub(crate) fn verify_inner(x: &impl AsRef<[u8]>, y: &[u8]) -> u8 {
let x = x.... | () {
assert!(verify_16(b"abcdefghijklmnop", b"abcdefghijklmnop"));
assert!(verify_16(&[0xff; 16], &[0xff; 16]));
assert!(verify_16(&[0x80; 16], &[0x80; 16]));
assert!(!verify_16(b"abcdefghijklmnop", b"ponmlkjihgfedcba"));
assert!(!verify_16(b"abcdefghijklmnop", b""));
as... | test_verify_16 | identifier_name |
util.rs | //! Module for utility functions.
/// Verifies equality between an array of length 16 and a slice of unknown length.
pub fn verify_16(x: &[u8; 16], y: &[u8]) -> bool {
x.len() == y.len() && verify_inner(x, y) == 0
}
#[inline(never)]
pub(crate) fn verify_inner(x: &impl AsRef<[u8]>, y: &[u8]) -> u8 {
let x = x.... | fn test_verify_inner() {
assert_eq!(0, verify_inner(b"", b""));
assert_eq!(0, verify_inner(b"Hello!", b"Hello!"));
assert_eq!(0, verify_inner(&[0x80, 0xff], &[0x80, 0xff]));
assert_ne!(0, verify_inner(b"ok", b"ko"));
assert_ne!(0, verify_inner(&[0x80, 0xff], &[0xff, 0x80]));... | random_line_split | |
cell.rs | be cloned and shared between multiple parties.
//! Because the contained values may be multiply-aliased, they can
//! only be borrowed as shared references, not mutable references.
//! Without cells it would be impossible to mutate data inside of
//! shared boxes at all!
//!
//! It's very common then to put a `RefCell... |
}
}
/// Immutably borrows the wrapped value.
///
/// The borrow lasts until the returned `Ref` exits scope. Multiple
/// immutable borrows can be taken out at the same time.
///
/// # Failure
///
/// Fails if the value is currently mutably borrowed.
#[unstable]
pub ... | {
self.borrow.set(borrow + 1);
Some(Ref { _parent: self })
} | conditional_block |
cell.rs | i);
//! shared_map.borrow_mut().insert("kyoto", 11837i);
//! shared_map.borrow_mut().insert("piccadilly", 11826i);
//! shared_map.borrow_mut().insert("marbles", 38i);
//! }
//! ```
//!
//! ## Implementation details of logically-immutable methods
//!
//! Occasionally it may be desirable not to expose in an A... | random_line_split | ||
cell.rs | .borrow_mut().insert("africa", 92388i);
//! shared_map.borrow_mut().insert("kyoto", 11837i);
//! shared_map.borrow_mut().insert("piccadilly", 11826i);
//! shared_map.borrow_mut().insert("marbles", 38i);
//! }
//! ```
//!
//! ## Implementation details of logically-immutable methods
//!
//! Occasionally it ma... | drop | identifier_name | |
util.rs | // Small functions of utility
use core::SearchType::{self, ExactMatch, StartsWith};
use core::Session;
use std::cmp;
use std::path::Path;
pub fn getline(filepath: &Path, linenum: usize, session: &Session) -> String {
let src = session.load_file(filepath);
src.code.lines().nth(linenum - 1).unwrap_or("not found... | match stype {
ExactMatch => searchstr == candidate,
StartsWith => candidate.starts_with(searchstr)
}
}
// pub fn get_backtrace() -> String {
// let mut m = std::old_io::MemWriter::new();
// let s = std::rt::backtrace::write(&mut m)
// .ok().map_or("NO backtrace".to_string(),
// ... | pub fn symbol_matches(stype: SearchType, searchstr: &str, candidate: &str) -> bool { | random_line_split |
util.rs | // Small functions of utility
use core::SearchType::{self, ExactMatch, StartsWith};
use core::Session;
use std::cmp;
use std::path::Path;
pub fn getline(filepath: &Path, linenum: usize, session: &Session) -> String {
let src = session.load_file(filepath);
src.code.lines().nth(linenum - 1).unwrap_or("not found... |
pub fn is_ident_char(c: char) -> bool {
c.is_alphanumeric() || (c == '_') || (c == '!')
}
pub fn txt_matches(stype: SearchType, needle: &str, haystack: &str) -> bool {
match stype {
ExactMatch => {
let n_len = needle.len();
let h_len = haystack.len();
if n_len == ... | {
c.is_alphanumeric() || (c == '_') || (c == ':') || (c == '.')
} | identifier_body |
util.rs | // Small functions of utility
use core::SearchType::{self, ExactMatch, StartsWith};
use core::Session;
use std::cmp;
use std::path::Path;
pub fn | (filepath: &Path, linenum: usize, session: &Session) -> String {
let src = session.load_file(filepath);
src.code.lines().nth(linenum - 1).unwrap_or("not found").to_string()
}
pub fn is_pattern_char(c: char) -> bool {
c.is_alphanumeric() || c.is_whitespace() || (c == '_') || (c == ':') || (c == '.')
}
pub ... | getline | identifier_name |
utils.py | from django.conf import settings
import sys
def import_name(name):
components = name.split('.')
if len(components) == 1:
# direct module, import the module directly
mod = __import__(name, globals(), locals(), [name])
else:
# the module is within another, so we
# need to im... |
def get_backend_settings(backend):
"""
Returns backend settings. If it does not exist it fails back to empty dict().
"""
backends_settings = getattr(settings, 'GETPAID_BACKENDS_SETTINGS', {})
try:
return backends_settings[backend]
except KeyError:
return {}
| """
Get active backends modules. Backend list can be filtered by supporting given currency.
"""
choices = []
backends_names = getattr(settings, 'GETPAID_BACKENDS', [])
for backend_name in backends_names:
backend = import_name(backend_name)
if currency:
if currency in bac... | identifier_body |
utils.py | from django.conf import settings
import sys
def import_name(name):
components = name.split('.')
if len(components) == 1:
# direct module, import the module directly
mod = __import__(name, globals(), locals(), [name])
else:
# the module is within another, so we
# need to im... | (submodule=None):
backends = getattr(settings, 'GETPAID_BACKENDS', [])
modules = {}
for backend_name in backends:
fqmn = backend_name
if submodule:
fqmn = '%s.%s' % (fqmn, submodule)
__import__(fqmn)
module = sys.modules[fqmn]
modules[backend_name] = modul... | import_backend_modules | identifier_name |
utils.py | from django.conf import settings
import sys
def import_name(name):
components = name.split('.')
if len(components) == 1:
# direct module, import the module directly
mod = __import__(name, globals(), locals(), [name])
else:
# the module is within another, so we
# need to im... |
else:
choices.append((backend_name, backend.PaymentProcessor.BACKEND_NAME, ))
return choices
def get_backend_settings(backend):
"""
Returns backend settings. If it does not exist it fails back to empty dict().
"""
backends_settings = getattr(settings, 'GETPAID_BACKENDS_SETTING... | choices.append((backend_name, backend.PaymentProcessor.BACKEND_NAME, )) | conditional_block |
utils.py | from django.conf import settings
import sys
def import_name(name):
components = name.split('.')
if len(components) == 1:
# direct module, import the module directly
mod = __import__(name, globals(), locals(), [name])
else:
# the module is within another, so we
# need to im... | backends = getattr(settings, 'GETPAID_BACKENDS', [])
modules = {}
for backend_name in backends:
fqmn = backend_name
if submodule:
fqmn = '%s.%s' % (fqmn, submodule)
__import__(fqmn)
module = sys.modules[fqmn]
modules[backend_name] = module
return modul... |
return mod
def import_backend_modules(submodule=None): | random_line_split |
main.py | #!/usr/bin/python
# -*- coding: gbk -*-
#coding=gbk
import pkgutil
import urlparse
import json
import logging
import urllib2
from argparse import ArgumentParser
import os
__all__ = ['main']
gfwlist_url = 'https://autoproxy-gfwlist.googlecode.com/svn/trunk/gfwlist.txt'
gfwlist_url = 'https://raw.githubusercontent.co... | new_domains.add(last_root_domain)
return new_domains
def generate_pac(domains, proxy):
# render the pac file
proxy_content = pkgutil.get_data('gfwlist2pacplus', 'resources/proxy.pac')
domains_dict = {}
for domain in domains:
domains_dict[domain] = 1
proxy_content = proxy_co... | if tlds.__contains__(root_domain):
continue
else:
break
if last_root_domain is not None: | random_line_split |
main.py | #!/usr/bin/python
# -*- coding: gbk -*-
#coding=gbk
import pkgutil
import urlparse
import json
import logging
import urllib2
from argparse import ArgumentParser
import os
__all__ = ['main']
gfwlist_url = 'https://autoproxy-gfwlist.googlecode.com/svn/trunk/gfwlist.txt'
gfwlist_url = 'https://raw.githubusercontent.co... | ():
args = parse_args()
user_rule = None
if (args.input):
with open(args.input, 'rb') as f:
content = f.read()
else:
if os.path.exists('gfwlist.txt'):
content = open('gfwlist.txt').read()
elif os.path.exists('wget.exe'):
print 'Downloading gfwl... | main | identifier_name |
main.py | #!/usr/bin/python
# -*- coding: gbk -*-
#coding=gbk
import pkgutil
import urlparse
import json
import logging
import urllib2
from argparse import ArgumentParser
import os
__all__ = ['main']
gfwlist_url = 'https://autoproxy-gfwlist.googlecode.com/svn/trunk/gfwlist.txt'
gfwlist_url = 'https://raw.githubusercontent.co... |
def decode_gfwlist(content):
# decode base64 if have to
try:
if '.' in content:
raise
return content.decode('base64')
except:
return content
def get_hostname(something):
try:
# quite enough for GFW
if not something.startswith('http:'):
... | parser = ArgumentParser()
parser.add_argument('-i', '--input', dest='input',
help='path to gfwlist', metavar='GFWLIST')
parser.add_argument('-f', '--file', dest='output', required=True,
help='path to output pac', metavar='PAC')
parser.add_argument('-p', '--proxy',... | identifier_body |
main.py | #!/usr/bin/python
# -*- coding: gbk -*-
#coding=gbk
import pkgutil
import urlparse
import json
import logging
import urllib2
from argparse import ArgumentParser
import os
__all__ = ['main']
gfwlist_url = 'https://autoproxy-gfwlist.googlecode.com/svn/trunk/gfwlist.txt'
gfwlist_url = 'https://raw.githubusercontent.co... | main() | conditional_block | |
fields.py | from django.db import models
from django.db.models.fields.related import (
RECURSIVE_RELATIONSHIP_CONSTANT, ManyToManyDescriptor,
ManyToManyField, ManyToManyRel, RelatedField,
create_many_to_many_intermediary_model,
)
from django.utils.functional import curry
class CustomManyToManyField(RelatedField):
... |
def get_internal_type(self):
return 'ManyToManyField'
# Copy those methods from ManyToManyField because they don't call super() internally
contribute_to_related_class = ManyToManyField.__dict__['contribute_to_related_class']
_get_m2m_attr = ManyToManyField.__dict__['_get_m2m_attr']
_get_m... | if self.remote_field.symmetrical and (
self.remote_field.model == "self" or self.remote_field.model == cls._meta.object_name):
self.remote_field.related_name = "%s_rel_+" % name
super(CustomManyToManyField, self).contribute_to_class(cls, name, **kwargs)
if not self.remote_fie... | identifier_body |
fields.py | from django.db import models
from django.db.models.fields.related import (
RECURSIVE_RELATIONSHIP_CONSTANT, ManyToManyDescriptor,
ManyToManyField, ManyToManyRel, RelatedField,
create_many_to_many_intermediary_model,
)
from django.utils.functional import curry
class CustomManyToManyField(RelatedField):
... |
super(CustomManyToManyField, self).__init__(**kwargs)
def contribute_to_class(self, cls, name, **kwargs):
if self.remote_field.symmetrical and (
self.remote_field.model == "self" or self.remote_field.model == cls._meta.object_name):
self.remote_field.related_name = "%s_... | assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used." | conditional_block |
fields.py | from django.db import models
from django.db.models.fields.related import (
RECURSIVE_RELATIONSHIP_CONSTANT, ManyToManyDescriptor,
ManyToManyField, ManyToManyRel, RelatedField,
create_many_to_many_intermediary_model,
)
from django.utils.functional import curry
class CustomManyToManyField(RelatedField):
... | _get_m2m_reverse_attr = ManyToManyField.__dict__['_get_m2m_reverse_attr']
_get_m2m_db_table = ManyToManyField.__dict__['_get_m2m_db_table']
class InheritedManyToManyField(ManyToManyField):
pass
class MediumBlobField(models.BinaryField):
"""
A MySQL BinaryField that uses a different blob size.
... | _get_m2m_attr = ManyToManyField.__dict__['_get_m2m_attr'] | random_line_split |
fields.py | from django.db import models
from django.db.models.fields.related import (
RECURSIVE_RELATIONSHIP_CONSTANT, ManyToManyDescriptor,
ManyToManyField, ManyToManyRel, RelatedField,
create_many_to_many_intermediary_model,
)
from django.utils.functional import curry
class | (RelatedField):
"""
Ticket #24104 - Need to have a custom ManyToManyField,
which is not an inheritor of ManyToManyField.
"""
many_to_many = True
def __init__(self, to, db_constraint=True, swappable=True, **kwargs):
try:
to._meta
except AttributeError:
to ... | CustomManyToManyField | identifier_name |
urls.rs | /* vim: set et: */
use url;
use hyper;
use types::FolderId;
use types::ProgramId;
use std::fmt;
pub enum EVUrl {
Login,
Folder(FolderId),
Program(ProgramId),
Move(ProgramId, FolderId)
}
impl hyper::client::IntoUrl for EVUrl {
fn into_url(self) -> Result<url::Url, url::ParseError> {
// TOD... | }
impl fmt::Display for EVUrl {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
EVUrl::Login => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/login.sl"),
EVUrl::Folder(ref id) => match *id {
FolderId::Root => write!(fmt, "https://api.elis... | } | random_line_split |
urls.rs | /* vim: set et: */
use url;
use hyper;
use types::FolderId;
use types::ProgramId;
use std::fmt;
pub enum EVUrl {
Login,
Folder(FolderId),
Program(ProgramId),
Move(ProgramId, FolderId)
}
impl hyper::client::IntoUrl for EVUrl {
fn into_url(self) -> Result<url::Url, url::ParseError> {
// TOD... |
}
#[cfg(test)]
mod tests {
use super::EVUrl;
use types::FolderId;
use types::ProgramId;
#[test]
fn show_login_url() {
let url = EVUrl::Login;
assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/login.sl");
}
#[test]
fn show_root_folder_url() {
l... | {
match *self {
EVUrl::Login => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/login.sl"),
EVUrl::Folder(ref id) => match *id {
FolderId::Root => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true"),
ref id => write!(fmt, "https://... | identifier_body |
urls.rs | /* vim: set et: */
use url;
use hyper;
use types::FolderId;
use types::ProgramId;
use std::fmt;
pub enum EVUrl {
Login,
Folder(FolderId),
Program(ProgramId),
Move(ProgramId, FolderId)
}
impl hyper::client::IntoUrl for EVUrl {
fn into_url(self) -> Result<url::Url, url::ParseError> {
// TOD... | () {
let url = EVUrl::Login;
assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/login.sl");
}
#[test]
fn show_root_folder_url() {
let url = EVUrl::Folder(FolderId::Root);
assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true");... | show_login_url | identifier_name |
index.js | /** | *
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | * @license Apache-2.0 | random_line_split |
index.js | /**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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 a... |
console.log( x );
var v = gnansum( x.length, x, 1 );
console.log( v );
| {
if ( randu() < 0.2 ) {
x[ i ] = NaN;
} else {
x[ i ] = round( randu()*100.0 );
}
} | conditional_block |
format.py | schema_row_out):
'''
Convert json schema to protobuf schema row.
'''
schema = json_load(schema_in)
if not schema:
raise LoomError('Schema is empty: {}'.format(schema_in))
value = loom.schema_pb2.ProductValue()
value.observed.sparsity = loom.schema_pb2.ProductValue.Observed.DENSE
... |
else:
builders = _make_encoder_builders_file((schema_in, rows_in))
encoders = [builder.build() for builder in builders]
encoders.sort(key=get_encoder_rank)
json_dump(encoders, encoding_out)
def ensure_fake_encoders_are_sorted(encoders):
dds = [e['symbols'] for e in encoders if e['model'] ... | builders = _make_encoder_builders_dir(schema_in, rows_in) | conditional_block |
format.py | schema_row_out):
'''
Convert json schema to protobuf schema row.
'''
schema = json_load(schema_in)
if not schema:
raise LoomError('Schema is empty: {}'.format(schema_in))
value = loom.schema_pb2.ProductValue()
value.observed.sparsity = loom.schema_pb2.ProductValue.Observed.DENSE
... | def build(self):
symbols = {int(value): value for value in xrange(self.max_value + 1)}
if self.model == 'dpd':
symbols[OTHER_DECODE] = dpd.OTHER
return {
'name': self.name,
'model': self.model,
'symbols': symbols,
}
FAKE_ENCODER_BUILD... | random_line_split | |
format.py | schema_row_out):
'''
Convert json schema to protobuf schema row.
'''
schema = json_load(schema_in)
if not schema:
raise LoomError('Schema is empty: {}'.format(schema_in))
value = loom.schema_pb2.ProductValue()
value.observed.sparsity = loom.schema_pb2.ProductValue.Observed.DENSE
... |
ENCODER_BUILDERS = defaultdict(lambda: DefaultEncoderBuilder)
ENCODER_BUILDERS['dd'] = CategoricalEncoderBuilder
ENCODER_BUILDERS['dpd'] = CategoricalEncoderBuilder
class CategoricalFakeEncoderBuilder(object):
def __init__(self, name, model):
self.name = name
self.model = model
self.max... | self.name = name
self.model = model
self.counts = defaultdict(lambda: 0)
self.counts.update(counts) | identifier_body |
format.py | schema_row_out):
'''
Convert json schema to protobuf schema row.
'''
schema = json_load(schema_in)
if not schema:
raise LoomError('Schema is empty: {}'.format(schema_in))
value = loom.schema_pb2.ProductValue()
value.observed.sparsity = loom.schema_pb2.ProductValue.Observed.DENSE
... | (self, value):
self.counts[value] += 1
def __iadd__(self, other):
for key, value in other.counts.iteritems():
self.counts[key] += value
def build(self):
sorted_keys = [(-count, key) for key, count in self.counts.iteritems()]
sorted_keys.sort()
symbols = {key... | add_value | identifier_name |
store.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::ErrorKind;
use async_trait::async_trait;
use bookmarks::BookmarkName;
use bytes::Bytes;
use changeset_info::ChangesetInfo;
use ... | {
Directory,
File(ContentId),
}
#[derive(Clone, Debug)]
pub enum FileChange {
Added(ContentId),
Changed(ContentId, ContentId),
Removed,
}
| PathContent | identifier_name |
store.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::ErrorKind;
use async_trait::async_trait;
use bookmarks::BookmarkName;
use bytes::Bytes;
use changeset_info::ChangesetInfo;
use ... | ctx: &'a CoreContext,
bookmark: BookmarkName,
paths: Vec<MPath>,
) -> Result<HashMap<MPath, PathContent>, ErrorKind>;
async fn file_changes<'a>(
&'a self,
ctx: &'a CoreContext,
new_cs_id: ChangesetId,
old_cs_id: ChangesetId,
) -> Result<Vec<(MPath, Fi... | &'a self, | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.