code stringlengths 281 23.7M |
|---|
_lifespan
def test_app_sync_gen_lifespan(test_client_factory):
startup_complete = False
cleanup_complete = False
def lifespan(app):
nonlocal startup_complete, cleanup_complete
startup_complete = True
(yield)
cleanup_complete = True
app = Starlette(lifespan=lifespan)
a... |
def cluster_chunks(chunks: List[Span], stopwords: bool=False, filter_pos: List[str]=None, min_score: float=None):
(key2index, key2vector) = _map_key_to_vector(chunks, stopwords, filter_pos)
if ((not key2index) or (not key2vector)):
return
model = KeyedVectors(chunks[0].vector.size)
keys = list(k... |
def create_hook(raw_hook: Any, default_environment_name: Optional[str]=None) -> Hook:
if isinstance(raw_hook, str):
raw_hook = {'path': raw_hook}
if (not isinstance(raw_hook, dict)):
raise ValueError(f'Unrecognized hook value: {raw_hook}')
if ('path' not in raw_hook):
raise ValueErro... |
.parametrize('command_type,payload', ((((Ping, None), (Pong, None)) + tuple(itertools.product((Disconnect,), DisconnectReason))) + ((Hello, HelloPayloadFactory()),)))
.parametrize('snappy_support', (True, False))
def test_p2p_command_encode_and_decode_round_trips(command_type, payload, snappy_support):
cmd = comman... |
def test_slave_message_generate_group_linked_self(generate_message_template, group):
message = build_dummy_message(group, group.self)
header = generate_message_template(message, True)
assert (group.name not in header)
assert (group.alias not in header)
assert (group.channel_emoji not in header)
... |
class ABIDecoder():
def __init__(self, abi: ABI):
self._functions_by_selector: Dict[(str, ABIFunctionDescription)] = {description.get_selector(): description for description in abi if isinstance(description, ABIFunctionDescription)}
def decode(self, data: str) -> Optional[CallData]:
(selector, p... |
class Inputs():
def validate_day(year: int, month: int, day: int) -> bool:
max_days = LONG_MONTH
if (month == FEB):
max_days = (FEB_LEAP_MONTH if ((((year % 4) == 0) and ((year % 100) != 0)) or ((year % 400) == 0)) else FEB_MONTH)
elif (month in MONTHS_30):
max_days =... |
def compute_best_path(local_asn, path1, path2):
best_path = None
best_path_reason = BPR_UNKNOWN
if (best_path is None):
best_path = _cmp_by_reachable_nh(path1, path2)
best_path_reason = BPR_REACHABLE_NEXT_HOP
if (best_path is None):
best_path = _cmp_by_highest_wg(path1, path2)
... |
def extractFanswebnovelBlogspotCom(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, tl_typ... |
def init_cache():
global memory_cache
with session_scope() as session:
last_req_dict = dict(get_last_requested(session))
hits_dict = dict(get_endpoints_hits(session))
averages_dict = dict(get_endpoint_averages(session))
for rule in get_rules():
memory_cache[rule.endpo... |
def _test_success_with_all_filters_place_of_performance_state(client):
resp = client.post('/api/v2/search/spending_by_geography', content_type='application/json', data=json.dumps({'scope': 'place_of_performance', 'geo_layer': 'state', 'filters': non_legacy_filters()}))
assert (resp.status_code == status.HTTP_20... |
def read_csv_file(filename):
tools = {}
with open(filename, 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
tool_name = row['Orphan tool']
tags = row['Related_pages'].split(',')
description = row['Orphan tool description']
url ... |
class LiteEthPHYMIIRX(LiteXModule):
def __init__(self, pads):
self.source = source = stream.Endpoint(eth_phy_description(8))
converter = stream.Converter(4, 8)
converter = ResetInserter()(converter)
self.submodules += converter
self.sync += [converter.reset.eq((~ pads.rx_dv))... |
class OpenPointInTime(Runner):
async def __call__(self, es, params):
op_name = mandatory(params, 'name', self)
index = mandatory(params, 'index', self)
keep_alive = params.get('keep-alive', '1m')
response = (await es.open_point_in_time(index=index, params=params.get('request-params')... |
class MasterButtonDelegate(QStyledItemDelegate):
def editorEvent(self, event, model, option, index):
if (event.type() == QEvent.MouseButtonRelease):
item = index.model().itemFromIndex(index)
item.button.widget.click()
return True
return QStyledItemDelegate.editorE... |
def test_clk_gen(BEGIN, END):
for i in count(BEGIN):
if ((i % 50000) == 0):
log.info('attack_tests i: {:10}, BEGIN: {}, END: {}'.format(i, BEGIN, END))
CLK_HEX = hex(i)[2:]
if ((len(CLK_HEX) % 2) == 1):
CLK_HEX = ('0' + CLK_HEX)
CLK = bytearray.fromhex(CLK_HEX... |
class TaskSpec(_common.FlyteIdlEntity):
def __init__(self, template: TaskTemplate, docs: typing.Optional[Documentation]=None):
self._template = template
self._docs = docs
def template(self):
return self._template
def docs(self):
return self._docs
def to_flyte_idl(self):
... |
.parametrize('name,state', [('12_0', 'R'), ('12_1', 'U'), ('12_2', 'X'), ('12_3', 'U'), ('12_4', 'X')])
def test_read_info_array(name: str, state: str) -> None:
example = 'JobID|State\n12_0|R\n12_[2,4-12]|X'
watcher = slurm.SlurmInfoWatcher()
for jobid in ['12_2', '12_4']:
watcher.register_job(jobid... |
def test_rule_header():
(app, db, admin) = setup()
with app.app_context():
(Model1, _) = create_models(db)
db.create_all()
view = CustomModelView(Model1, db.session, form_create_rules=(rules.Header('hello'),))
admin.add_view(view)
client = app.test_client()
rv = c... |
class OptionSeriesPackedbubbleSonificationContexttracksMapping(Options):
def frequency(self) -> 'OptionSeriesPackedbubbleSonificationContexttracksMappingFrequency':
return self._config_sub_data('frequency', OptionSeriesPackedbubbleSonificationContexttracksMappingFrequency)
def gapBetweenNotes(self) -> '... |
class Sequence(EditBase, NameMixin, DurationMixin):
def __init__(self, name='', duration=0.0, rate=None, timecode='00:00:00:00'):
NameMixin.__init__(self, name=name)
DurationMixin.__init__(self, duration=duration)
self.ntsc = False
self.timecode = timecode
if (rate is None):
... |
def test_unit_conversion_factors():
metres = ggrid.Units.METRES
feet = ggrid.Units.FEET
cm = ggrid.Units.CM
assert (metres.conversion_factor(metres) == 1.0)
assert (metres.conversion_factor(cm) == 100)
assert (metres.conversion_factor(feet) == pytest.approx(3.28084))
assert (cm.conversion_fa... |
def test_extract_title(lowercased_df):
result = extract_title(lowercased_df, col='string')
assert (result['title'].tolist() == ['mme', 'ms', 'mr', 'lady', 'major'])
title_replacement = {'mme': 'mrs', 'ms': 'miss', 'lady': 'rare', 'major': 'rare'}
result = extract_title(lowercased_df, col='string', repla... |
class Uptime(IntervalModule):
settings = (('format', 'Format string'), ('color', 'String color'), ('alert', 'If you want the string to change color'), ('seconds_alert', 'How many seconds necessary to start the alert'), ('color_alert', 'Alert color'))
file = '/proc/uptime'
format = 'up {hours}:{mins}'
co... |
class TCPClientConnection(TCPConnection):
def __init__(self, configuration: ConnectionConfig, **kwargs: Any) -> None:
address = cast(str, configuration.config.get('address'))
port = cast(int, configuration.config.get('port'))
if ((address is None) or (port is None)):
raise ValueE... |
class Migration(migrations.Migration):
dependencies = [('admin_interface', '0011_add_environment_options')]
operations = [migrations.AlterField(model_name='theme', name='logo_color', field=colorfield.fields.ColorField(blank=True, default='#FFFFFF', help_text='#FFFFFF', max_length=10, verbose_name='color')), mig... |
def count_zero_crossings(x, y):
sample_rate = ((np.diff(x)[0] * MICROSECONDS) ** (- 1))
samples_per_period = (sample_rate / FREQUENCY)
zero_crossings = np.where(np.diff(np.sign(y)))[0]
real_crossings = np.where((np.diff(zero_crossings) > (samples_per_period * 0.01)))
real_crossings = np.append(real_... |
def upgrade():
op.create_table('tax', sa.Column('id', sa.Integer(), nullable=False), sa.Column('country', sa.String(), nullable=True), sa.Column('tax_name', sa.String(), nullable=False), sa.Column('tax_rate', sa.Float(), nullable=False), sa.Column('tax_id', sa.String(), nullable=False), sa.Column('send_invoice', sa... |
class TestCopyPyToThrift(TestCase):
def setUp(self) -> None:
self.python_object = PollForActivityTaskResponse()
self.python_object.task_token = 'TASK_TOKEN'
self.python_object.workflow_execution = WorkflowExecution()
self.python_object.workflow_execution.workflow_id = 'WORKFLOW_ID'
... |
def test_function_space_cached(mesh):
assert (FunctionSpace(mesh, 'CG', 1) == FunctionSpace(mesh, 'CG', 1))
assert (FunctionSpace(mesh, 'CG', 1).topological == FunctionSpace(mesh, 'CG', 1).topological)
assert (FunctionSpace(mesh, 'CG', 1)._shared_data == FunctionSpace(mesh, 'CG', 1)._shared_data) |
class ExplainerTest(ForsetiTestCase):
def setUp(self):
self.setup = create_tester()
def test_list_resources(self):
def test(client):
list_resources_reply = set((r.full_resource_name for r in client.explain.list_resources('')))
self.assertEqual(list_resources_reply, set(['... |
def _solve(ball: Ball, cushion: Cushion, restitution: bool=True) -> Tuple[(Ball, Cushion)]:
rvw = ball.state.rvw
normal = cushion.get_normal(rvw)
normal = (normal if (np.dot(normal, rvw[1]) > 0) else (- normal))
psi = ptmath.angle(normal)
rvw_R = ptmath.coordinate_rotation(rvw.T, (- psi)).T
rvw_... |
def export_feature_embedding(model, device):
has_pitch_shift = hasattr(model, 'pitch_shift_encoder')
logger.info(f'The model has pitch shift encoder: {has_pitch_shift}')
model = FeatureEmbeddingWrapper(model).to(device)
n_frames = 10
speakers = torch.tensor([0], dtype=torch.long, device=device)
... |
class Square(QWidget):
ps_color_changed = pyqtSignal(bool)
ps_index_changed = pyqtSignal(bool)
def __init__(self, wget, args, idx):
super().__init__(wget)
self._args = args
self._idx = idx
def paintEvent(self, event):
if False:
self._args.sys_activated_assit_i... |
class GithubDailyPushEventAction(Action):
def help_text(cls) -> str:
return 'Command for downloading daily push event commits from Github'
def name(cls):
return 'get-github-daily-push-events'
def _execute(self, day: datetime):
return get_github_daily_push_events(day=day) |
def test_search():
pattern = tm.TreePattern('\n (\n "len(ch) > 2",\n "name in [\'hello\', \'bye\']"\n )\n "(len(name) < 3 or name == \'accept\') and d >= 0.5"\n ')
for (newick, expected_result) in [('((hello:1,(1:1,2:1,3:1)xx:1)accept:1, NODE):0;', ['accept']), ('((hello:1,(1:1,2:1,3:1)xx:... |
.parametrize('c_args, c_kwargs, f_args, f_kwargs', [([Output('celsius', 'value'), CycleBreakerInput('fahrenheit', 'value')], dict(), [Output('fahrenheit', 'value'), Input('celsius', 'value')], dict()), ([], dict(output=Output('celsius', 'value'), inputs=dict(value=CycleBreakerInput('fahrenheit', 'value'))), [], dict(ou... |
class Search(Options):
def caseInsensitive(self):
return self._config_get()
def caseInsensitive(self, val):
self._config(val)
def search(self):
return self._config_get()
def search(self, val):
self._config(val)
def regex(self):
return self._config_get()
de... |
def run():
print('\nmodule top();\n ')
params = {}
sites = list(gen_sites())
for ((tile_name, sites), isone) in zip(sites, util.gen_fuzz_states(len(sites))):
site_name = sites[0]
params[tile_name] = (site_name, isone)
print('\n wire clk_{site};\n BUFMRCE ... |
class Engine():
def get_local_player():
return (mem.read_i32((nv.clientState + nv.getLocalPlayer)) + 1)
def get_view_angles():
return mem.read_vec3((nv.clientState + nv.dwViewAngles))
def get_max_clients():
return mem.read_i32((nv.clientState + nv.dwMaxClients))
def is_in_game():... |
class OptionPlotoptionsColumnpyramidSonificationDefaultinstrumentoptionsMappingPan(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, t... |
def get_first_signer_certificate(apkpath):
certs = None
cert_encoded = None
with zipfile.ZipFile(apkpath, 'r') as apk:
cert_files = [n for n in apk.namelist() if SIGNATURE_BLOCK_FILE_REGEX.match(n)]
if (len(cert_files) > 1):
logging.error(_('Found multiple JAR Signature Block Fil... |
class RepresentChildTests(TestCase):
def setUp(self):
self.internal_value = dict(child=dict(id=1))
self.context = dict(label='Label')
self.serializer = CalculatedParentTestSerializer(self.internal_value, context=self.context)
self.serialized = self.serializer.data
def test_hierar... |
def extractCfensiWordpressCom(item):
bad = ['general news', 'Photoshoot', 'Music', 'Television', 'Drama', 'mainland china']
if any([(tmp in item['tags']) for tmp in bad]):
return None
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview'... |
.benchmark
('xtb')
def test_xtb_rx_synthesis(fixture_store):
for (i, fix) in enumerate(fixture_store):
print(i, fix)
tot_opt_cycles = 0
opt_converged = 0
tot_tsopt_cycles = 0
bags = fixture_store['results_bag']
for (k, v) in bags.items():
if (not k.startswith('test_xtb_rx')):
... |
class DirectiveLocation(Enum):
QUERY = 0
MUTATION = 1
SUBSCRIPTION = 2
FIELD = 3
FRAGMENT_DEFINITION = 4
FRAGMENT_SPREAD = 5
INLINE_FRAGMENT = 6
SCHEMA = 7
SCALAR = 8
OBJECT = 9
FIELD_DEFINITION = 10
ARGUMENT_DEFINITION = 11
INTERFACE = 12
UNION = 13
ENUM = 14... |
class PlayQueue(playlist.Playlist):
def __init__(self, player, name, location=None):
playlist.Playlist.__init__(self, name=name)
self.__queue_has_tracks_val = False
self.__current_playlist = self
self.last_playlist = None
self.player = player
if (player is not None):
... |
def extractTheVerbosePlayground(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag,... |
class UnreadReports(MethodView):
decorators = [allows.requires(IsAtleastModerator, on_fail=FlashAndRedirect(message=_('You are not allowed to view reports.'), level='danger', endpoint='management.overview'))]
def get(self):
page = request.args.get('page', 1, type=int)
reports = Report.query.filt... |
class DiscriminatorLow():
def __init__(self, width=256, height=256, channels=3, learning_rate=0.0002, decay_rate=2e-06, gpus=0):
self.width = width
self.height = height
self.channels = channels
self.gpus = gpus
self.learning_rate = learning_rate
self.decay_rate = deca... |
('cuda.gemm_rcr_softmax.gen_profiler')
def gen_profiler(func_attrs, workdir, profiler_filename, dim_info_dict):
return common_gen_profiler(func_attrs=func_attrs, workdir=workdir, profiler_filename=profiler_filename, dim_info_dict=dim_info_dict, src_template=common_softmax.SRC_TEMPLATE, problem_args_template=PROBLEM... |
def parse_format_gnmap(data, protocol):
line_regex_str = '(?P<port>\\d+)/\\w+/{}'.format(protocol)
line_regex = re.compile(line_regex_str)
ports = set()
for line in data.split('\n'):
if ('Ports:' not in line):
continue
content = line.split('Ports: ')[1]
for c in conte... |
class NumericToken(TokenBase):
def __repr__(self):
is_ascii = False
try:
is_ascii = self.is_ascii()
except TypeError:
is_ascii = False
ret = "<{:14} - contents: '{}' '{}' '{}' (numeric: {}, ascii: {}, parsed: {}>".format(self.__class__.__name__, self.prefix, s... |
class OptionSeriesVectorSonificationDefaultinstrumentoptionsMappingTremoloDepth(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 DbGptsTaskStep():
task_num: str
task_content: str
state: str
result: str
agent_name: str
model_name: str
def from_dict(d: Dict[(str, Any)]) -> DbGptsTaskStep:
return DbGptsTaskStep(task_num=d['task_num'], task_content=d['task_content'], state=d['state'], result=d['result'], age... |
def cluster_distribution_version(hosts, client_options, client_factory=EsClientFactory):
es = client_factory(hosts, client_options).create()
version = es.info()['version']
version_build_flavor = version.get('build_flavor', 'oss')
version_build_hash = version.get('build_hash', version_build_flavor)
v... |
def parse_tracks(toc_entries, mcn, device):
real_track_count = (len(toc_entries) - 1)
tracks = []
for toc_entry_index in range(0, real_track_count):
(track_index, is_data_track, _, _, _) = toc_entries[toc_entry_index]
if is_data_track:
continue
if (track_index is not (toc... |
def test_latest_block_based_cache_middleware_pulls_from_cache(w3_base, block_data_middleware, result_generator_middleware):
w3 = w3_base
w3.middleware_onion.add(block_data_middleware)
w3.middleware_onion.add(result_generator_middleware)
current_block_hash = w3.eth.get_block('latest')['hash']
def cac... |
class AltSoundCloudController(AltGenericController):
__gtype_name = 'AltSoundCloudController'
def __init__(self, header):
super(AltSoundCloudController, self).__init__(header)
self._has_toolbar = None
def valid_source(self, source):
return ('SoundCloud' in type(source).__name__)
... |
def context_of_sender(bus, sender):
dbus_obj = bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')
dbus_iface = dbus.Interface(dbus_obj, 'org.freedesktop.DBus')
try:
context = dbus_iface.GetConnectionSELinuxSecurityContext(sender)
except Exception:
return None
return ''.j... |
class LabTestTemplate(Document):
def before_insert(self):
if (self.link_existing_item and self.item):
price_list = frappe.db.get_all('Item Price', {'item_code': self.item}, ['price_list_rate'], order_by='valid_from desc')
if price_list:
self.lab_test_rate = price_list... |
class PurchaseOrderTests(unittest.TestCase):
def test_unicode(self):
purchase_order = PurchaseOrder()
purchase_order.TotalAmt = 1000
self.assertEqual(str(purchase_order), '1000')
def test_valid_object_name(self):
obj = PurchaseOrder()
client = QuickBooks()
result ... |
_app.callback(Output('click-data', 'children'), [Input('galaxy-map', 'clickData')])
def galaxy_map_system_info(clickData):
if (not clickData):
return ''
points = clickData.get('points')
if (not points):
return ''
p = points[0]
custom_data = p.get('customdata', {})
system_id = cus... |
def trace_kind_to_shared_text_kind(trace_kind: Optional[TraceKind]) -> SharedTextKind:
if (trace_kind == TraceKind.POSTCONDITION):
return SharedTextKind.SOURCE
if (trace_kind == TraceKind.PRECONDITION):
return SharedTextKind.SINK
raise AssertionError(f'{trace_kind} is invalid') |
def add(proj_dir, update=False):
check_exists_with_error()
cmd = (('git add ' + '-u') if update else '.')
try:
subprocess.check_call('git add .', cwd=proj_dir, shell=True)
except subprocess.CalledProcessError as e:
log.error("'git add .' failed with '{}'".format(e.returncode)) |
class HtmlJson(Html.Html):
name = 'Pretty Json'
tag = 'div'
requirements = ('json-formatter-js',)
_option_cls = OptJsonFormatter.OptionsJsonFmt
def __init__(self, page: primitives.PageModel, tree_data, width, height, options, profile):
super(HtmlJson, self).__init__(page, tree_data, profile=... |
.parallel(nprocs=7)
.parametrize('case', ['interval', 'interval_small', 'interval_periodic', 'triangle', 'triangle_small', 'quadrilateral', 'triangle_periodic', 'quadrilateral_periodic', 'triangle_extrusion'])
def test_io_freeze_dist_perm_base(case, tmpdir):
filename = os.path.join(str(tmpdir), 'test_io_freeze_dist... |
def extractBokutowlWordpressCom(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, tl_type) ... |
class RefineGraphTestCase(unittest.TestCase):
(**filter_test_cases_by_params({TestEnv.CUDA_LESS_THAN_SM80: ['float16'], TestEnv.CUDA_SM80: ['float32']}))
def test_elementwise_ops(self, dtype):
target = detect_target()
if ((dtype == 'float32') and (target.name == 'rocm')):
self.skipTe... |
def get_precision_timestamp(time: str) -> PrecisionTimestamp:
try:
(_, s_fraction) = time.split('.')
except ValueError:
return PrecisionTimestamp.SECONDS
(s_fraction, _) = (s_fraction.split('Z') if ('Z' in s_fraction) else s_fraction.split('z'))
if (len(s_fraction) > 6):
return P... |
def trait_definition(*, cls, trait_name):
source = inspect.getsource(cls)
string_io = io.StringIO(source)
tokens = tokenize.generate_tokens(string_io.readline)
trait_found = False
name_found = False
while (not trait_found):
item = next(tokens, None)
if (item is None):
... |
class StockSpanner():
def __init__(self):
self.prices = []
self.weights = []
def next(self, price: int) -> int:
w = 1
while (self.prices and (self.prices[(- 1)] <= price)):
self.prices.pop()
w += self.weights.pop()
self.prices.append(price)
... |
def test_resample_small():
xs1 = RegularSurface(xori=0, yori=0, ncol=3, nrow=3, xinc=100, yinc=100, values=(- 888.0), yflip=1)
xs2 = RegularSurface(xori=0, yori=0, ncol=3, nrow=3, xinc=100, yinc=100, values=888.0, yflip=1)
xs3 = RegularSurface(xori=0, yori=200, ncol=3, nrow=3, xinc=100, yinc=100, values=288... |
_action_type(ofproto.OFPAT_POP_VLAN, ofproto.OFP_ACTION_HEADER_SIZE)
class OFPActionPopVlan(OFPAction):
def __init__(self, type_=None, len_=None):
super(OFPActionPopVlan, self).__init__()
def parser(cls, buf, offset):
(type_, len_) = struct.unpack_from(ofproto.OFP_ACTION_HEADER_PACK_STR, buf, of... |
class OptionSeriesBulletSonificationContexttracksActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, num: float):
... |
def _fix_overlabelings(doc):
good_labelings = set()
for span in doc._.labelings:
should_add_span = False
for other_span in doc._.labelings:
if (((span.start == other_span.start) and (span.end == other_span.end)) or (span.start >= other_span.end) or (span.end <= other_span.start)):
... |
class OSKenAppSmokeTest(unittest.TestCase):
def _fake_dp():
datapath = namedtuple('datapath', ['id', 'close'])(0, (lambda : None))
return datapath
def test_faucet(self):
os.environ['FAUCET_CONFIG'] = '/dev/null'
os.environ['FAUCET_LOG'] = '/dev/null'
os.environ['FAUCET_EX... |
def _update_feed_name(sess, netloc, oldname, newname):
have = sess.query(db.RssFeedUrlMapper).filter((db.RssFeedUrlMapper.feed_netloc == netloc)).scalar()
if (not have):
print('Missing: ', have)
return
print('Have: ', have, have.feed_entry, have.feed_entry.feed_name)
if (have.feed_entry.... |
class HCI_Sco(HCI):
def from_data(data):
handle = u16(unbits(bits_str(data[0:2])[0:12].rjust(16, '0')))
ps = u8(unbits(bits_str(data[1:2])[4:6].rjust(8, '0')))
return HCI_Sco(handle, ps, u16(data[2]), data[3:])
def getRaw(self):
raw = bits(p16(self.handle))[4:]
raw.extend... |
def upgrade():
op.alter_column('events', 'background_url', new_column_name='original_image_url')
op.alter_column('events', 'logo', new_column_name='logo_url')
op.alter_column('events', 'large', new_column_name='large_image_url')
op.alter_column('events', 'thumbnail', new_column_name='thumbnail_image_url... |
.usefixtures('use_tmpdir')
def test_that_all_iterations_gets_correct_name_and_iteration_number(storage, monkeypatch):
minimum_args = ESMDARunArguments(random_seed=None, active_realizations=[True], target_case='target_%d', weights='1, 2, 3', restart_run=False, prior_ensemble='', minimum_required_realizations=1, ense... |
_required
_required('REGISTRATION_ENABLED')
def forgot_passwd_check_done(request):
dc1_settings = DefaultDc().settings
if dc1_settings.SMS_REGISTRATION_ENABLED:
text_blocks = (_('Your password has been reset and send to your phone number via text message (SMS).'),)
else:
text_blocks = ()
... |
def SSZType(fields):
class SSZObject():
def __init__(self, **kwargs):
for (f, t) in fields.items():
if (f not in kwargs):
setattr(self, f, get_zero_value(t))
else:
setattr(self, f, kwargs[f])
validate(self.__clas... |
class ProjectVersion(DatabaseTestCase):
def test_pre_release(self):
project = models.Project(name='test', homepage=' backend='custom', ecosystem_name='pypi', version_scheme='Semantic')
self.session.add(project)
self.session.flush()
version = models.ProjectVersion(project_id=project.i... |
def extractTinysalttranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('icdi', 'I Can Do It', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Lo... |
class TestVhdl():
def test_vhdl_write(self, tmpdir):
output_file = str(tmpdir.join('regs.vhd'))
print('output_file:', output_file)
rmap = utils.create_template()
generators.Vhdl(rmap, output_file).generate()
with open(output_file, 'r') as f:
raw_str = ''.join(f.re... |
class AltQueueController(AltGenericController):
__gtype_name = 'AltQueueController'
def __init__(self, header):
super(AltQueueController, self).__init__(header)
self._gicon = Gio.ThemedIcon(name='audio-x-queue-symbolic')
def valid_source(self, source):
return ('RBPlayQueueSource' in ... |
class FirewallD(DbusServiceObject):
persistent = True
default_polkit_auth_required = config.dbus.PK_ACTION_CONFIG
_exceptions
def __init__(self, *args, **kwargs):
super(FirewallD, self).__init__(*args, **kwargs)
self.fw = Firewall()
self.busname = args[0]
self.path = args... |
class FeaturesRequest(base_tests.SimpleProtocol):
def runTest(self):
logging.info('Running Features_Request test')
of_ports = config['port_map'].keys()
of_ports.sort()
delete_all_flows(self.controller)
logging.info('Sending Features_Request')
logging.info('Expecting F... |
_register_parser
_set_msg_type(ofproto.OFPT_STATS_REPLY)
class OFPStatsReply(MsgBase):
_STATS_TYPES = {}
def register_stats_reply_type(type_, body_single_struct=False):
def _register_stats_reply_type(cls):
OFPStatsReply._STATS_TYPES[type_] = cls
cls.cls_body_single_struct = body_... |
class StakingRestClientTestCase(TestCase):
def test_Validators():
content = {'validators': [{'operator_address': 'string', 'jailed': True, 'status': 'BOND_STATUS_UNSPECIFIED', 'tokens': '123', 'delegator_shares': 'string', 'description': {'moniker': 'string', 'identity': 'string', 'website': 'string', 'secu... |
class TestTransitions(unittest.TestCase):
def test_ngram_counts(self):
lines = 'abcdefg'
tokens_to_idx = {l: e for (e, l) in enumerate(lines)}
counts = count_ngrams([lines], 1, tokens_to_idx)
unigrams = counts[0].most_common()
expected_unigrams = [((i,), 1) for i in range(len... |
class TestNotificationServer(unittest.TestCase):
def _clean_db(self):
if os.path.exists(_SQLITE_FILE):
os.remove(_SQLITE_FILE)
def setUp(self) -> None:
self._clean_db()
config = NotificationServerConfig(config_file)
db.clear_engine_and_session()
db.create_all_... |
class Fastqs(object):
def __init__(self):
self.r1 = None
self.r2 = None
self.singleton = None
self.type = None
self.gzip = False
self.type = 'fastq'
self.reads = ()
def __str__(self):
return 'Fastq container of R1, R2, Singletons'
def set_read(... |
def repeat_last(call_data):
global __last_commands__
index = len(__last_commands__)
callable_ = call_data[0]
args = call_data[1]
kwargs = call_data[2]
command = ('print \\"\\";python(\\"from anima.dcc.mayaEnv.toolbox import repeater; repeater(%s);\\");' % index)
repeat_last_command = ('repea... |
class OverprintFork(BandFork):
__slots__ = ('contrast', 'basicgcr')
inks = CMYKInk.CMYK()
def __init__(self, processor_factory, gcr=20, *args, **kwargs):
self.contrast = AutoContrast()
self.basicgcr = BasicGCR(percentage=gcr)
super(OverprintFork, self).__init__(processor_factory, *ar... |
class TestShopifyGetIdEmail():
.asyncio
async def test_success(self, get_respx_call_args):
request = respx.get(client.profile_endpoint).mock(return_value=Response(200, json=profile_response))
(user_id, user_email) = (await client.get_id_email('TOKEN'))
(url, headers, content) = (await ge... |
class OrgPolicyQueryMixin(object):
def get_effective_org_policy(self, resource, constraint, fields=None, verb='getEffectiveOrgPolicy', **kwargs):
arguments = {'resource': resource, 'fields': fields, 'body': {'constraint': constraint}}
if kwargs:
arguments.update(kwargs)
return se... |
class OptionPlotoptionsErrorbarSonificationDefaultspeechoptionsMappingTime(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 test_reference_method_updates_the_inputs_of_the_referenced_version(create_test_data, create_pymel, create_maya_env):
data = create_test_data
pm = create_pymel
maya_env = create_maya_env
maya_env.open(data['asset2_model_take1_v003'])
assert (data['asset2_model_take1_v002'] not in data['asset2_mod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.