code stringlengths 281 23.7M |
|---|
def extractFanswebnovelbloggerBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name,... |
class OptionPlotoptionsVariablepieSonificationTracksPointgrouping(Options):
def algorithm(self):
return self._config_get('minmax')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
... |
def test_ComplexNumPyEncoder():
test = io._ComplexNumPyEncoder()
assert (type(test.default(np.int_(1))) is int)
assert (type(test.default(np.float_(1))) is float)
assert (type(test.default(np.bool_(1))) is bool)
assert (type(test.default(np.array([[1.0, 1.0], [1.0, 1.0]]))) is list)
cplx = test.... |
class PreConversationOperator(BaseConversationOperator, MapOperator[(ModelRequest, ModelRequest)]):
def __init__(self, storage: Optional[StorageInterface[(StorageConversation, Any)]]=None, message_storage: Optional[StorageInterface[(MessageStorageItem, Any)]]=None, **kwargs):
super().__init__(storage=storag... |
def test_hover_literal_string_sq():
string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)})
file_path = ((test_dir / 'hover') / 'parameters.f90')
string += hover_req(file_path, 9, 48)
(errcode, results) = run_request(string, fortls_args=['--sort_keywords'])
assert (errcode == 0)
... |
def extractFantasyBooksLive(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
if ('short story' in item['tags']):
return None
if ('69526' in item['tags']):
return... |
class Future():
def __init__(self, func):
self.func = func
self.thread = None
self.retval = None
self.finished = False
self.joined = False
def start(self, *args, **kwargs):
self.thread = threading.Thread(target=self._runAndCapture, args=args, kwargs=kwargs)
... |
def StockCutter1D(child_rolls, parent_rolls, output_json=True, large_model=True, cutStyle='exactCuts'):
parent_width = parent_rolls[0][1]
if (not checkWidths(demands=child_rolls, parent_width=parent_width)):
return []
print('child_rolls', child_rolls)
print('parent_rolls', parent_rolls)
if (... |
def get_image_stream(stream, class_mapping_dict, ip, port, model_name, thresh):
for eg in stream:
if (not eg['image'].startswith('data')):
msg = "Expected base64-encoded data URI, but got: '{}'."
raise ValueError(msg.format(eg['image'][:100]))
pil_image = Image.open(io.BytesI... |
class Fastq(object):
def __init__(self, name, sequence, name2, quality):
self.name = name
self.sequence = sequence
self.name2 = name2
self.quality = quality
def getShortname(self, separator):
if separator:
self.temp = self.name.split(separator)
del... |
def _get_priority_list(nid_to_exclude: int=None) -> List[SiacNote]:
if (nid_to_exclude is not None):
sql = ('\n select * from notes where position >= 0 and id != %s order by position asc\n ' % nid_to_exclude)
else:
sql = '\n select * from notes where position >= 0 or... |
class Geometric(Harmony):
COUNT = 0
def harmonize(self, color: 'Color', space: Optional[str]) -> List['Color']:
if (space is None):
space = color.HARMONY
orig_space = color.space()
color0 = color.convert(space)
if (not isinstance(color0._space, Cylindrical)):
... |
class _TenantIterator():
def __init__(self, current_page):
if (not current_page):
raise ValueError('Current page must not be None.')
self._current_page = current_page
self._index = 0
def next(self):
if (self._index == len(self._current_page.tenants)):
if s... |
def get_task(args, config, build_config_url_path=None, task_id=None):
task = {'task_id': task_id, 'source_type': None, 'source_json': {}}
if args.task_file:
task.update(read_task_from_file(args.task_file))
elif args.task_url:
task.update(get_vanilla_build_config(args.task_url))
elif buil... |
class OptionPlotoptionsFunnel3dSonificationContexttracksMappingRate(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
def get_executable_path(search_path: Path, executable_name: str) -> Path:
bin_dir = (search_path / 'bin').as_posix()
executable_path = shutil.which(executable_name, path=bin_dir)
if (executable_path is None):
raise RuntimeError(f'Could not find {executable_name} in {search_path}. Is the virtual envi... |
class SplitComplementary(Harmony):
def harmonize(self, color: 'Color', space: Optional[str]) -> List['Color']:
if (space is None):
space = color.HARMONY
orig_space = color.space()
color0 = color.convert(space)
if (not isinstance(color0._space, Cylindrical)):
r... |
def graphs_with_aliases():
var_18 = vars('var_18', 6, aliased=True)
var_14 = vars('var_14', 6, aliased=True)
var_28 = vars('var_28', 2, type=Pointer(int32))
var_10 = vars('var_10', 2, type=Pointer(int32))
eax = vars('eax', 2)
eax_2 = vars('eax_2', 4)
c = const(8)
in_n0 = BasicBlock(0, [_... |
def main():
args = _parse_commandline()
wallet = LocalWallet.generate()
ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet())
wallet_balance = ledger.query_bank_balance(wallet.address())
while (wallet_balance < (10 ** 18)):
... |
class Plugin(plugin.PluginProto):
PLUGIN_ID = 12
PLUGIN_NAME = 'Display - LCD2004 I2C'
PLUGIN_VALUENAME1 = 'LCD'
P12_Nlines = 4
def __init__(self, taskindex):
plugin.PluginProto.__init__(self, taskindex)
self.dtype = rpieGlobals.DEVICE_TYPE_I2C
self.vtype = rpieGlobals.SENSOR... |
def test_that_tests_dont_have_multiple_functions_with_same_name():
dir = os.path.dirname(__file__)
for fname in os.listdir(dir):
if (not (fname.startswith('test_') and fname.endswith('.py'))):
continue
print(fname)
text = open(os.path.join(dir, fname), 'rb').read().decode()
... |
class OptionPlotoptionsAreaSonificationContexttracksMappingTremoloDepth(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class TestComposerThread_eject_from_compose(ComposerThreadBaseTestCase):
def test_testing_request(self):
up = self.db.query(Update).one()
up.request = UpdateRequest.testing
self.db.commit()
task = self._make_task()
t = ComposerThread(self.semmock, task['composes'][0], 'bowlof... |
class OptionPlotoptionsSunburstSonificationContexttracksMappingTime(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
.parametrize('button, stored_value', [(left_click, 'leftclick'), (right_click, 'rightclick')])
def test_callback_handler_method(button, stored_value):
class TestClicks(IntervalModule):
def set_action(self, action):
self._action = action
on_leftclick = [set_action, 'leftclick']
on... |
def generate_htpasswd_entry(entry: bytes) -> dict:
(user_name, pw_hash) = entry.split(b':')
result_entry = {'type': 'htpasswd', 'entry': _to_str(entry), 'password-hash': _to_str(pw_hash)}
result_entry['cracked'] = crack_hash(entry, result_entry)
return {f'{_to_str(user_name)}:htpasswd': result_entry} |
class DiskCachedList(object):
def __init__(self, lst, strategy='batched_static'):
self._lst = lst
self._diskcache_strategy = strategy
def _serialize(data):
buffer = pickle.dumps(data, protocol=(- 1))
return np.frombuffer(buffer, dtype=np.uint8)
logger.info('Se... |
class _SimpleEditorWithCell(BaseSourceWithLocation):
source_class = SimpleEditor
locator_class = Cell
handlers = [(MouseClick, (lambda wrapper, _: wrapper._target._mouse_click(delay=wrapper.delay))), (KeyClick, (lambda wrapper, interaction: wrapper._target._key_click(key=interaction.key, delay=wrapper.delay... |
class Test(unittest.TestCase):
def test_parse(self):
converter = LcovCobertura('SF:foo/file.ext\nDA:1,1\nDA:2,0\nBRDA:1,1,1,1\nBRDA:1,1,2,0\nend_of_record\n')
result = converter.parse()
self.assertTrue(('packages' in result))
self.assertTrue(('foo' in result['packages']))
sel... |
class IdaRichJupyterWidget(RichJupyterWidget):
def _is_complete(self, source, interactive):
if ipyida.kernel.is_using_ipykernel_5():
return super(IdaRichJupyterWidget, self)._is_complete(source, interactive)
try:
from queue import Empty
except ImportError:
... |
class Recursive(Rule):
rule_maker: Callable[([], Rule)]
def __init__(self, rule_maker: Callable[([], Rule)], name: str='recursive') -> None:
Rule.__init__(self, name)
self.rule_maker = rule_maker
def apply(self, test: Any) -> RuleResult:
return self.rule_maker().apply(test)
def _... |
(scope='function')
def yotpo_loyalty_connection_config(db: Session, yotpo_loyalty_config, yotpo_loyalty_secrets) -> Generator:
fides_key = yotpo_loyalty_config['fides_key']
connection_config = ConnectionConfig.create(db=db, data={'key': fides_key, 'name': fides_key, 'connection_type': ConnectionType.saas, 'acce... |
def _get_item(model, view_arg, name):
if (has_request_context() and (not getattr(_request_ctx_stack.top, name, None)) and (view_arg in request.view_args)):
setattr(_request_ctx_stack.top, name, model.query.filter_by(id=request.view_args[view_arg]).first())
return getattr(_request_ctx_stack.top, name, No... |
class StandaloneApplication(gunicorn.app.base.BaseApplication):
def __init__(self, app, options=None):
self.options = (options or {})
self.application = app
super(StandaloneApplication, self).__init__()
scout_result = self.application.scout.report(mode='boot', action='boot1', no_cach... |
def separate_colors(xyz, axis=(- 1)):
n = len(xyz.shape)
if (axis < 0):
axis = (n + axis)
slices = makeslices(n)
slices[axis] = 0
x = xyz[tuple(slices)]
slices[axis] = 1
y = xyz[tuple(slices)]
slices[axis] = 2
z = xyz[tuple(slices)]
return (x, y, z, axis) |
class OptionSeriesWindbarbSonification(Options):
def contextTracks(self) -> 'OptionSeriesWindbarbSonificationContexttracks':
return self._config_sub_data('contextTracks', OptionSeriesWindbarbSonificationContexttracks)
def defaultInstrumentOptions(self) -> 'OptionSeriesWindbarbSonificationDefaultinstrume... |
def serialise_cat_shrine(save_data: list[int], shrine_data: dict[(str, Any)]) -> list[int]:
save_data = write_double(save_data, shrine_data['stamp_1'])
save_data = write_double(save_data, shrine_data['stamp_2'])
save_data = write(save_data, shrine_data['shrine_gone'], 1)
save_data = write_length_data(sa... |
.skip('These tests take a very long time to compute')
.parametrize('biort,qshift', [('near_sym_a', 'qshift_a'), ('near_sym_b', 'qshift_b'), ('near_sym_b_bp', 'qshift_b_bp')])
def test_grad_scatj2(biort, qshift):
x = torch.randn(1, 3, 32, 32, requires_grad=True, dtype=torch.double, device=dev)
scat = ScatLayerj2... |
def test_lexicographical_bfs_2():
interference_graph = InterferenceGraph()
interference_graph.add_edges_from([(1, 4), (1, 6), (2, 3), (2, 7), (3, 7), (3, 8), (4, 6), (4, 7), (4, 8), (5, 6), (5, 7), (6, 7), (6, 8), (7, 8)])
lex_bfs = LexicographicalBFS(interference_graph)
assert (list(lex_bfs.reverse_lex... |
def warp_inclusive_add_cuda(val: ti.template()):
global_tid = ti.global_thread_idx()
lane_id = (global_tid % 32)
offset_j = 1
n = ti.simt.warp.shfl_up_i32(ti.simt.warp.active_mask(), val, offset_j)
if (lane_id >= offset_j):
val += n
offset_j = 2
n = ti.simt.warp.shfl_up_i32(ti.simt.w... |
def check_params_supported(estimator):
from sklearn.utils.validation import check_is_fitted
check_is_fitted(estimator)
metric = estimator.effective_metric_
if (metric not in SUPPORTED_METRICS):
raise ValueError(f'Unsupported metric: {metric}. Supported: {SUPPORTED_METRICS}')
weights = estima... |
class OptionSeriesLineMarker(Options):
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def enabledThreshold(self):
return self._config_get(2)
def enabledThreshold(self, num: float):
self._config(num, js_typ... |
class DFITimingsChecker(Module):
CMDS = [('PRE', '0010'), ('REF', '0001'), ('ACT', '0011'), ('RD', '0101'), ('WR', '0100'), ('ZQCS', '0110')]
RULES = [('PRE', 'ACT', 'tRP'), ('PRE', 'REF', 'tRP'), ('ACT', 'WR', 'tRCD'), ('ACT', 'RD', 'tRCD'), ('ACT', 'PRE', 'tRAS'), ('REF', 'PRE', 'tRFC'), ('REF', 'ACT', 'tRFC'... |
def test_check_plot_kwargs(skip_if_no_mpl):
plot_kwargs = {}
defaults = {}
plot_kwargs_out = check_plot_kwargs(plot_kwargs, defaults)
assert (plot_kwargs_out == {})
plot_kwargs = None
defaults = {'alpha': 0.5}
plot_kwargs_out = check_plot_kwargs(plot_kwargs, defaults)
assert (plot_kwargs... |
class AlertsSchema(BaseModel):
tests: TestAlertsSchema
models: ModelAlertsSchema
source_freshnesses: SourceFreshnessAlertsSchema
def all_alerts(self) -> List[Union[(PendingTestAlertSchema, PendingModelAlertSchema, PendingSourceFreshnessAlertSchema)]]:
return [*self.tests.send, *self.models.send,... |
def do_fix(target_raw, antitarget_raw, reference, diploid_parx_genome=None, do_gc=True, do_edge=True, do_rmask=True, do_cluster=False, smoothing_window_fraction=None):
logging.info('Processing target: %s', target_raw.sample_id)
(cnarr, ref_matched) = load_adjust_coverages(target_raw, reference, True, do_gc, do_... |
def unstack_numpy_list_dict(list_dict: Dict[(str, np.ndarray)]) -> List[Dict[(str, np.ndarray)]]:
keys = list(list_dict.keys())
if (list_dict[keys[0]].shape == ()):
return [list_dict]
n_items = len(list_dict[keys[0]])
dict_list = []
for i in range(n_items):
action_dict = dict()
... |
()
('key')
('iv')
('message')
def aes_decrypt(key, iv, message):
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
digest.update(key.encode())
key_digest = digest.finalize()
cipher = Cipher(algorithms.AES(key_digest), modes.CFB(unhexlify(iv)), backend=default_backend())
decryptor = ci... |
def backward_solve(A, b, x, schur_builder, reconstruct_fields):
if (not isinstance(A, Tensor)):
raise ValueError('Left-hand operator must be a Slate Tensor')
all_fields = list(range(len(A.arg_function_spaces[0])))
nfields = len(all_fields)
reconstruct_fields = as_tuple(reconstruct_fields)
_b... |
class OptionPlotoptionsVennSonificationDefaultinstrumentoptionsMappingFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text... |
class OperatorConstructor_oneLevel(OperatorConstructor):
def __init__(self, OLT):
OperatorConstructor.__init__(self, OLT)
self._initializeOperatorConstruction()
def updateMassOperator(self, rho=1.0):
self._mass_val.fill(0.0)
try:
rho = self.model.coefficients.rho
... |
class Slider(Gtk.Scale):
def __init__(self, shell_player):
super().__init__()
self.set_orientation(Gtk.Orientation.HORIZONTAL)
self.adjustment = Gtk.Adjustment(0, 0, 10, 1, 10, 0)
self.set_adjustment(self.adjustment)
self.set_hexpand(True)
self.set_draw_value(False)
... |
def _deploy_emitter(eth_tester):
deploy_hash = eth_tester.send_transaction({'from': eth_tester.get_accounts()[0], 'gas': 500000, 'data': EMITTER_BYTECODE})
deploy_receipt = eth_tester.get_transaction_receipt(deploy_hash)
emitter_address = deploy_receipt['contract_address']
assert emitter_address
ret... |
def download_abide_freesurfer(subid, src_data_dir):
abide_amazon_addy = '
abide_freesurfer = os.path.join(src_data_dir, 'abide', 'freesurfer')
fs_subdir = os.path.join(abide_freesurfer, subid)
if (not os.path.exists(fs_subdir)):
run(['mkdir', '-p', fs_subdir])
for subdir in ['mri', 'surf', '... |
.usefixtures('use_tmpdir')
def test_ensemble_config_construct_refcase_and_grid():
grid_file = 'CASE.EGRID'
refcase_file = 'REFCASE_NAME'
xtgeo.create_box_grid(dimension=(10, 10, 1)).to_file('CASE.EGRID', 'egrid')
summary = Summary.writer('REFCASE_NAME', datetime(2014, 9, 10), 3, 3, 3)
summary.add_va... |
def od_pairs_from_topology(topology):
if topology.is_directed():
routes = dict(nx.all_pairs_shortest_path_length(topology))
return [(o, d) for o in routes for d in routes[o] if (o != d)]
else:
conn_comp = nx.connected_components(topology)
return [(o, d) for G in conn_comp for o i... |
def upgrade():
op.create_table('PriceLists', sa.Column('id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['id'], ['Entities.id']), sa.PrimaryKeyConstraint('id'))
op.create_table('Goods', sa.Column('id', sa.Integer(), nullable=False), sa.Column('cost', sa.Float(), nullable=True), sa.Column('msrp', sa.... |
class get_config_reply(message):
version = 2
type = 8
def __init__(self, xid=None, flags=None, miss_send_len=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
else:
self.flags =... |
def get_account(parent_type, parent_field, parent, company):
if parent_type:
return frappe.db.get_value('Party Account', {'parenttype': parent_type, 'parent': parent, 'company': company}, 'account')
if parent_field:
return frappe.db.get_value('Party Account', {'parentfield': parent_field, 'paren... |
class RegexConstrainedString(UserString):
REGEX = re.compile('.*', flags=re.DOTALL)
def __init__(self, seq: Union[(UserString, str)]) -> None:
super().__init__(seq)
if (not self.REGEX.fullmatch(self.data)):
self._handle_no_match()
def _handle_no_match(self) -> None:
raise... |
def get_task_status_info() -> List[TaskStatusInfo]:
assert (Session is not None)
task_status_query = Session.query(TaskInstance.dag_id, TaskInstance.task_id, TaskInstance.state, func.count(TaskInstance.dag_id).label('cnt')).group_by(TaskInstance.dag_id, TaskInstance.task_id, TaskInstance.state).subquery()
s... |
def test_simple() -> None:
dependencies: list[Dependency] = []
module_foobar_locations = [Location(Path('foo.py'), 1, 2), Location(Path('bar.py'), 3, 4)]
module_foobar = ModuleBuilder('foobar', {'foo'}, frozenset(), dependencies).build()
modules_locations = [ModuleLocations(module_foobar, module_foobar_... |
class Strategy():
def __init__(self, symbol, capital, start, end):
self.symbol = symbol
self.capital = capital
self.start = start
self.end = end
self.ts = None
self.tlog = None
self.dbal = None
self.stats = None
def _algo(self):
pf.TradeLog... |
def run_search_for_result(objective, max_depth_of_search, prompt_template, browser):
_crawler = Crawler(browser=browser)
depth_of_search = 0
gpt_cmd = ''
prev_cmd = ''
_crawler.go_to_page('google.com')
time.sleep(1)
content = '\n'.join(_crawler.crawl())
search_result = False
_crawler... |
def _interpolate_list(l, point):
if ((point < l[0][0]) or (point > l[(- 1)][0])):
return None
if (point == l[0][0]):
return l[0]
if (point == l[(- 1)][0]):
return l[(- 1)]
right_index = bisect.bisect_right(l, [point])
left_index = (right_index - 1)
right = l[right_index]
... |
def test_countries_are_in_not_in_nam_target_region():
result = gen.generate(props={'region': gen.choice(['NAM']), 'country': gen.country_codes(region_field='region', sampler=gen.bound_choice)}, count=100, randomstate=np.random.RandomState()).to_dataframe()
country_list = data.countries(region='EMEA')
for ro... |
class TestFilters(CuratorTestCase):
def test_filter_by_alias(self):
alias = 'testalias'
self.write_config(self.args['configfile'], testvars.client_config.format(HOST))
self.write_config(self.args['actionfile'], testvars.filter_by_alias.format('testalias', False))
self.create_index('m... |
_os(*metadata.platforms)
def main():
masquerade = '/tmp/defaults'
common.create_macos_masquerade(masquerade)
common.log('Launching commands to mimic defaults modifying safari configurations.')
common.execute([masquerade, 'write', 'com.apple.Safari', 'JavaScript'], timeout=10, kill=True)
common.remov... |
class PyTorchTPUBackend(backendFunctions):
def sayHello(self):
myhost = os.uname()[1]
device = self.get_device()
hw_device = self.get_hw_device()
global_rank = self.get_global_rank()
local_rank = self.get_local_rank()
world_size = self.get_world_size()
master_... |
def validate_array(value, validator):
validate_is_list_like(value)
item_errors = _accumulate_array_errors(value, validator)
if item_errors:
item_messages = tuple(('[{}]: {}'.format(index, str(err)) for (index, err) in sorted(item_errors)))
error_message = 'The following items failed to valid... |
def test_trivial_true():
cfg = ControlFlowGraph()
cfg.add_nodes_from([(n0 := BasicBlock(0, instructions=[Branch(Condition(OperationType.equal, [Constant(0), Constant(1)]))])), (n1 := BasicBlock(1, instructions=[])), (n2 := BasicBlock(2, instructions=[])), (n3 := BasicBlock(3, instructions=[Return([Constant(1)])... |
('cuda.dual_gemm_rcr_silu.func_decl')
def gen_function_decl(func_attrs):
func_name = func_attrs['name']
input_ndims = len(func_attrs['input_accessors'][0].original_shapes)
weight_ndims = len(func_attrs['input_accessors'][1].original_shapes)
return common_bias.FUNC_DECL_TEMPLATE.render(func_name=func_nam... |
class TestTraitEvent(unittest.TestCase):
def setUp(self):
self.foo = Foo()
def test_list_repr(self):
self.foo.alist[::2] = [4, 5]
event = self.foo.event
event_str = 'TraitListEvent(index=slice(0, 3, 2), removed=[1, 3], added=[4, 5])'
self.assertEqual(repr(event), event_st... |
class OptionPlotoptionsSeriesSonificationDefaultinstrumentoptionsPointgrouping(Options):
def algorithm(self):
return self._config_get('minmax')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, fla... |
class DomainNotActiveError(Exception):
message: str
domainName: str
currentCluster: str
activeCluster: str
def domain_name(self):
return self.domainName
def current_cluster(self):
return self.currentCluster
def active_cluster(self):
return self.activeCluster |
def get_label_widget(duration: float, text: str, start_at: float=BEGINNING, position: POSITION_T=RANDOM, additional_callbacks: typing.Optional[CALLBACKS_T]=None) -> Stimulus:
position = get_position(position, (0, 0))
if (additional_callbacks is None):
additional_callbacks = []
callbacks = [('setText... |
class PGCursorProxy(CursorProxy):
provider_name = 'postgresql'
def _bake_sql(self, sql):
if hasattr(sql, 'as_string'):
sql = sql.as_string(self.__wrapped__)
if isinstance(sql, bytes):
sql = sql.decode(self.connection.info.encoding)
return sql
def extract_signa... |
class OptionSeriesFunnelSonificationTracksMappingTime(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
self._conf... |
.parametrize('elasticapm_client', [{'collect_local_variables': 'errors'}, {'collect_local_variables': 'transactions', 'local_var_max_length': 20, 'local_var_max_list_length': 10}, {'collect_local_variables': 'all', 'local_var_max_length': 20, 'local_var_max_list_length': 10}, {'collect_local_variables': 'something'}], ... |
class OptionSeriesPictorialSonificationDefaultinstrumentoptionsMappingTime(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str... |
class OptionSeriesXrangeDataMarkerStatesSelect(Options):
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def fillColor(self):
return self._config_get('#cccccc')
def fillColor(self, text: str):
self._config(... |
class TributeAction(UserAction):
def apply_action(self):
tgt = self.target
migrate_cards([self.associated_card], tgt.showncards, unwrap=True)
src = self.source
src.tags['tribute_tag'] = src.tags['turn_count']
return True
def is_valid(self):
p = self.source
... |
def main():
t0 = time.time()
folder = (Path(__file__).parent / 'mnist_logs')
if folder.exists():
for file in folder.iterdir():
file.unlink()
ex = submitit.AutoExecutor(folder)
if (ex.cluster == 'slurm'):
print('Executor will schedule jobs on Slurm.')
else:
pri... |
_defaults()
class UserFavouriteEventSchema(SoftDeletionSchema):
class Meta():
type_ = 'user-favourite-event'
self_view = 'v1.user_favourite_event_detail'
self_view_kwargs = {'id': '<id>'}
inflect = dasherize
id = fields.Str(dump_only=True)
event = Relationship(self_view='v1.u... |
def test_generate_gpu_of_a_layout_of_an_environment(create_test_data, store_local_session, create_pymel, create_maya_env):
data = create_test_data
pm = create_pymel
maya_env = create_maya_env
gen = RepresentationGenerator()
gen.version = data['prop1_model_kisa_v003']
gen.generate_all()
gen.v... |
def rfc3925_decode(s, identifier_size=4):
data = {}
while s:
enterprise_number = conversion.listToNumber(s[:identifier_size])
payload_size = s[identifier_size]
payload = s[(1 + identifier_size):((1 + identifier_size) + payload_size)]
s = s[((1 + identifier_size) + payload_size):]... |
def test_raises_only_error_codes_match(test_error, auth_missing_error):
errors = [test_error, auth_missing_error]
with raises_only_error_codes(['AUTH_MISSING', 'TEST']) as exc_info:
raise Client.CallActionError(actions=[ActionResponse(action='', errors=errors)])
assert (exc_info.soa_errors == errors... |
class IgnoreGroup(Ignore):
def __init__(self, root: str, ignores: List[Type[Ignore]]):
super().__init__(root)
self.ignores = [ignore(root) for ignore in ignores]
def _is_ignored(self, path: str) -> bool:
for ignore in self.ignores:
if ignore.is_ignored(path):
... |
def check(ip, domain, port, args, timeout, payload_map):
username_list = payload_map.get('username')
password_list = payload_map.get('password')
try:
for username in username_list:
for password in password_list:
try:
ssh = pxssh.pxssh()
... |
class MsgBusFedmsg(MsgBus):
bus_type = 'fedmsg'
def __init__(self, log=None):
opts = type('', (), {})
opts.headers = {}
super(MsgBusFedmsg, self).__init__(opts, log)
fedmsg.init(name='relay_inbound', cert_prefix='copr', active=True)
def _send_message(self, message):
f... |
.usefixtures('use_tmpdir')
def test_move_pathfile_into_folder_file_exists(shell):
shell.mkdir('dst_folder')
shell.mkdir('source1/source2/')
with open('source1/source2/file', 'w', encoding='utf-8') as f:
f.write('stuff')
with open('dst_folder/file', 'w', encoding='utf-8') as f:
f.write('g... |
class Test_verify_event_path_base(AIOKafkaConsumerThreadFixtures):
last_request: Optional[float] = None
last_response: Optional[float] = None
highwater: int = 1
committed_offset: int = 1
acks_enabled: bool = False
stream_inbound: Optional[float] = None
last_commit: Optional[float] = None
... |
class TestAsyncAgentLoop():
AGENT_LOOP_CLASS: Type[BaseAgentLoop] = AsyncAgentLoop
FAKE_AGENT_CLASS = AsyncFakeAgent
def test_loop_start_stop(self):
agent = self.FAKE_AGENT_CLASS()
agent_loop = self.AGENT_LOOP_CLASS(agent, threaded=True)
agent.runtime.agent_loop = agent_loop
... |
class BaseHandler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(max_workers=THREADPOOL_MAX_WORKERS)
def __init__(self, *args, **kwargs):
super(BaseHandler, self).__init__(*args, **kwargs)
app_log.info('--- BaseHandler / __init__ : \n')
self.is_user_connected = self.get_if_us... |
def extract_location(recipient_hash):
location = {'address_line1': None, 'address_line2': None, 'address_line3': None, 'foreign_province': None, 'city_name': None, 'county_name': None, 'state_code': None, 'zip': None, 'zip4': None, 'foreign_postal_code': None, 'country_name': None, 'country_code': None, 'congressio... |
class Sensor(GenericSensor):
def setup_module(self) -> None:
from smbus2 import SMBus
self.SMBus = SMBus
self.bus_num: int = self.config['i2c_bus_num']
self.address: int = self.config['chip_addr']
def get_value(self, sens_conf: ConfigType) -> SensorValueType:
with self.SM... |
class Hardware(models.Model):
hardware_choices = (('MOB', _('Mobile')), ('NOTE', _('Notebook')), ('NET', _('Netbook')), ('TAB', _('Tablet')), ('DES', _('Desktop')), ('OTH', _('Other')))
type = models.CharField(_('Type'), choices=hardware_choices, max_length=200)
manufacturer = models.CharField(_('Manufactur... |
def collect_dataset(users: pd.Series, target: pd.Series, preds: pd.Series, recommendations_type: RecomType, min_rel_score: Optional[int], no_feedback_users: bool, bin_data: bool):
df = pd.concat([users, target, preds], axis=1)
df.columns = ['users', 'target', 'preds']
if min_rel_score:
df['target'] ... |
class github_issue_0198_test_case(unittest.TestCase):
def test_constructor_with_s3_url_and_s3_options_with_file_json(self):
aws_access_key_id = config('AWS_ACCESS_KEY_ID', default=None)
aws_secret_access_key = config('AWS_SECRET_ACCESS_KEY', default=None)
if (not all([aws_access_key_id, aws_... |
class ArchiverDialog(QtWidgets.QDialog):
def __init__(self, parent=None, versions=None, archiver=None):
super(ArchiverDialog, self).__init__(parent=parent)
self.archiver = archiver
if (versions is None):
versions = []
self.versions = versions
self.main_layout = No... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.