code stringlengths 281 23.7M |
|---|
()
_flag()
_context
_aea_project
def add(click_context: click.Context, local: bool, remote: bool) -> None:
ctx = cast(Context, click_context.obj)
enforce((not (local and remote)), "'local' and 'remote' options are mutually exclusive.")
if ((not local) and (not remote)):
try:
ctx.registry... |
class Subquery(SqlTree):
table_name: str
fields: Optional[List[Name]]
query: Sql
type = property(X.query.type)
def _compile(self, qb):
query = self.query.compile(qb).code
if (qb.target == bigquery):
fields_str = []
else:
fields = [f.compile_wrap(qb.rep... |
class ShellSu(BaseTest):
def setUp(self):
self.session = SessionURL(self.url, self.password, volatile=True)
modules.load_modules(self.session)
self.vector_list = modules.loaded['shell_su'].vectors.get_names()
self.run_argv = modules.loaded['shell_su'].run_argv
def test_param_vect... |
def test_post_collision_spawn():
pool = DAGPool()
pool.spawn('a', (), (lambda key, result: 1))
with assert_raises(Collision):
pool.post('a', 2)
pool.kill('a')
pool.post('a', 3)
assert_equal(pool.get('a'), 3)
pool = DAGPool()
pool.spawn('a', (), (lambda key, result: 4))
spin()... |
class PeerDBServer(Service):
logger = logging.getLogger('trinity.components.network_db.PeerDBServer')
def __init__(self, event_bus: EndpointAPI, tracker: BaseEth1PeerTracker) -> None:
self.tracker = tracker
self.event_bus = event_bus
async def handle_track_peer_event(self) -> None:
a... |
def script_version(alias: str, script_details: dict, with_prefix: bool=False):
if ('version' in script_details):
if with_prefix:
if ('v_prefix' in JS_IMPORTS[alias]):
return ('%s%s' % (JS_IMPORTS[alias]['v_prefix'], script_details['version']))
return script_details['versi... |
class ReportModel(BaseModel):
id: uuid.UUID
timestamp: datetime.datetime
metrics: List[MetricModel]
metadata: Dict[(str, MetadataValueType)]
tags: List[str]
def from_report(cls, report: Report):
return cls(id=report.id, timestamp=report.timestamp, metrics=[MetricModel.from_metric(m) for ... |
class AdhocCOCODataset(AdhocDataset):
def __init__(self, src_ds_name, new_ds_name):
super().__init__(new_ds_name)
assert isinstance(src_ds_name, str)
self.src_ds_name = src_ds_name
def new_json_dict(self, json_dict):
raise NotImplementedError()
def register_catalog(self):
... |
class TestSend():
_DEFAULT_RESPONSE = json.dumps({'name': 'message-id'})
_CLIENT_VERSION = 'fire-admin-python/{0}'.format(firebase_admin.__version__)
def setup_class(cls):
cred = testutils.MockCredential()
firebase_admin.initialize_app(cred, {'projectId': 'explicit-project-id'})
def tear... |
.django_db
def test_award_no_federal_accounts(client, awards_federal_account_data):
resp = client.get('/api/v2/awards/count/federal_account/ASST_NON_bbb_abc123/')
assert (resp.status_code == status.HTTP_200_OK)
assert (resp.data['federal_accounts'] == 0)
resp = client.get('/api/v2/awards/count/federal_a... |
def send_voice(token, chat_id, voice, caption=None, duration=None, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None, timeout=None, caption_entities=None, allow_sending_without_reply=None, protect_content=None, message_thread_id=None):
method_url = 'sendVoice'
payload = {'c... |
class RetryPolicyTest(AmbassadorTest):
target: ServiceType
def init(self) -> None:
self.target = HTTP()
def config(self) -> Generator[(Union[(str, Tuple[(Node, str)])], None, None)]:
(yield (self, self.format('\n---\napiVersion: getambassador.io/v3alpha1\nkind: Mapping\nname: {self.name}-no... |
class ChatPermissions(JsonDeserializable, JsonSerializable, Dictionaryable):
def de_json(cls, json_string):
if (json_string is None):
return json_string
obj = cls.check_json(json_string, dict_copy=False)
return cls(**obj)
def __init__(self, can_send_messages=None, can_send_me... |
class OptionPlotoptionsArearangeLowmarkerStatesHover(Options):
def animation(self) -> 'OptionPlotoptionsArearangeLowmarkerStatesHoverAnimation':
return self._config_sub_data('animation', OptionPlotoptionsArearangeLowmarkerStatesHoverAnimation)
def enabled(self):
return self._config_get(True)
... |
def dbus_handle_exceptions(func):
(func)
def _impl(*args, **kwargs):
try:
return func(*args, **kwargs)
except FirewallError as error:
code = FirewallError.get_code(str(error))
if (code in [errors.ALREADY_ENABLED, errors.NOT_ENABLED, errors.ZONE_ALREADY_SET, er... |
def test_bounds_inference_tiled_blur2d():
def blur2d_tiled(n: size, consumer: i8[(n, n)], sin: i8[((n + 1), (n + 1))]):
assert ((n % 4) == 0)
producer: i8[((n + 1), (n + 1))]
for i in seq(0, (n + 1)):
for j in seq(0, (n + 1)):
producer[(i, j)] = sin[(i, j)]
... |
class ResponseStreamSliceIterator():
def __init__(self, slice):
self.slice = slice
self.retries = 0
self.text = ''
self.consumed_tokens = []
self.n = 0
self.waiting_tasks = []
async def recover(self):
recovery_kwargs = self.slice.kwargs.copy()
if (... |
def deactivate_node(tree_id):
(tid, subtree) = get_tid(tree_id)
tree_data = app.trees[tid]
node = tree_data.tree[subtree]
tree_data.active.nodes.results.discard(node)
tree_data.active.nodes.parents.clear()
tree_data.active.nodes.parents.update(get_parents(tree_data.active.nodes.results)) |
def extractWuwuwu555(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, postfix=po... |
def dipole3d_43(ax, da, A, bx, db, B, R):
result = numpy.zeros((3, 15, 10), dtype=float)
x0 = (0.5 / (ax + bx))
x1 = ((ax + bx) ** (- 1.0))
x2 = ((- x1) * ((ax * A[0]) + (bx * B[0])))
x3 = ((- x2) - A[0])
x4 = ((- x2) - B[0])
x5 = ((ax * bx) * x1)
x6 = numpy.exp(((- x5) * ((A[0] - B[0]) ... |
class VersionCreatorTester(unittest.TestCase):
repo_path = ''
def setUpClass(cls):
DBSession.remove()
cls.repo_path = tempfile.mkdtemp()
from anima import defaults
defaults.local_storage_path = tempfile.mktemp()
db.setup({'sqlalchemy.url': 'sqlite:///:memory:', 'sqlalchem... |
.requires_dbt_version('1.4.0')
def test_artifacts_caching(dbt_project: DbtProject):
dbt_project.dbt_runner.vars['disable_dbt_artifacts_autoupload'] = False
dbt_project.dbt_runner.run(select=TEST_MODEL, vars={'one_tags': ['hello', 'world']})
first_row = read_model_artifact_row(dbt_project)
dbt_project.db... |
class AppropriationAccountBalancesSerializer(LimitableSerializer):
class Meta():
model = AppropriationAccountBalances
fields = '__all__'
nested_serializers = {'treasury_account_identifier': {'class': TasSerializer, 'kwargs': {'read_only': True}}, 'submission': {'class': SubmissionAttributesS... |
def inference(model: ChatModel, predict_data: List[Dict], **input_kwargs):
res = []
for item in tqdm(predict_data, desc='Inference Progress', unit='item'):
print(f'''item[input]
{item['input']}''')
(response, _) = model.chat(query=item['input'], history=[], **input_kwargs)
res.append(re... |
class TestNull(util.ColorAsserts, unittest.TestCase):
def test_null_input(self):
c = Color('lch', [90, 50, NaN], 1)
self.assertTrue(c.is_nan('hue'))
def test_none_input(self):
c = Color('lch(90% 0 none / 1)')
self.assertTrue(c.is_nan('hue'))
def test_near_zero_null(self):
... |
class SlowExit(DefaultExit):
def at_traverse(self, traversing_object, target_location):
move_speed = (traversing_object.db.move_speed or 'walk')
move_delay = MOVE_DELAY.get(move_speed, 4)
def move_callback():
source_location = traversing_object.location
if traversing_... |
def parse_date(string, force_datetime=False):
matches = DATE.match(string)
if (not matches):
return None
values = {k: (v if (v[0] in '+-') else int(v)) for (k, v) in matches.groupdict().items() if (v and int(v))}
if ('timestamp' in values):
value = (datetime.datetime.utcfromtimestamp(0) ... |
class TestRequests():
def test_timeout_error(self):
error = requests.exceptions.Timeout('Test error')
firebase_error = _utils.handle_requests_error(error)
assert isinstance(firebase_error, exceptions.DeadlineExceededError)
assert (str(firebase_error) == 'Timed out while making an API... |
def test_correlation_raises_exception_with_trace_not_having_more_elements_than_pattern():
with pytest.raises(ValueError):
scared.signal_processing.correlation(np.random.rand(50), np.random.rand(50))
with pytest.raises(ValueError):
scared.signal_processing.correlation(trace=np.random.rand(49), pa... |
.parametrize(('testcase', 'convrate'), [(('BDM', 1, 'CG', 1, 'h'), 1.82), (('BDM', 2, 'CG', 2, 'h'), 2.9), (('RT', 2, 'CG', 1, 'h'), 1.87), (('RT', 3, 'CG', 2, 'h'), 2.95), (('BDFM', 2, 'CG', 1, 'h'), 1.77), (('N1curl', 2, 'CG', 1, 'h'), 1.87), (('N2curl', 1, 'CG', 1, 'h'), 1.82), (('N2curl', 2, 'CG', 2, 'h'), 2.9), ((... |
class FaucetTaggedSwapVidOrderedOutputTest(FaucetTaggedTest):
CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "tagged"\n unicast_flood: False\n 101:\n description: "tagged"\n unicast_flood: False\nacls:\n 1:\n - rule:\n vlan_vid: 100\n actions:\n ... |
def highpass(Data, n=48):
a = (((0.707 * 2) * math.pi) / n)
alpha1 = (((math.cos(a) + math.sin(a)) - 1) / math.cos(a))
b = (1 - (alpha1 / 2))
c = (1 - alpha1)
ret = ([0] * len(Data))
for i in range(2, len(Data)):
ret[i] = ((((b * b) * ((Data.iloc[i] - (2 * Data[(i - 1)])) + Data.iloc[(i ... |
('cuda.full.gen_function')
def gen_function(func_attrs: Dict[(str, Any)]) -> str:
y = func_attrs['outputs'][0]
backend_spec = CUDASpec()
num_elements = 1
for dim in y.shape():
num_elements *= dim.upper_bound()
dtype = y.dtype()
data_type = backend_spec.dtype_to_backend_type(dtype)
re... |
class ParamProcessor(_coconut.object):
def __init__(self):
self.handlers = _coconut.dict()
self.placeholder_funcs = _coconut.dict()
self.support_checkers = _coconut.dict()
def registered_base_rand_funcs(self):
return tuple(self.handlers)
def register(self, func, handler, plac... |
_type(MrtRecord.TYPE_BGP4MP_ET)
class Bgp4MpEtMrtRecord(ExtendedTimestampMrtRecord):
MESSAGE_CLS = Bgp4MpMrtMessage
SUBTYPE_BGP4MP_STATE_CHANGE = 0
SUBTYPE_BGP4MP_MESSAGE = 1
SUBTYPE_BGP4MP_MESSAGE_AS4 = 4
SUBTYPE_BGP4MP_STATE_CHANGE_AS4 = 5
SUBTYPE_BGP4MP_MESSAGE_LOCAL = 6
SUBTYPE_BGP4MP_ME... |
class DDPM(Scheduler):
def __init__(self, num_inference_steps: int, num_train_timesteps: int=1000, initial_diffusion_rate: float=0.00085, final_diffusion_rate: float=0.012, device: (Device | str)='cpu') -> None:
super().__init__(num_inference_steps=num_inference_steps, num_train_timesteps=num_train_timestep... |
_os(*metadata.platforms)
def main():
commands = '\n %comspec% /c "cm%OS:~-7,1% /c start%CommonProgramFiles(x86):~29,1%%PUBLIC:~-1%alc && ping -%APPDATA:~-2,-1% 2 127.0.0.1>nul &&%CommonProgramFiles(x86):~-6,1%taskkil%CommonProgramFiles:~-3,-2% /im %TMP:~-8,1%alc.exe\n cmd /c "%pUBLIc:~ 14%%PRogRam... |
def load_config(name):
config_path = ((Path(__file__).parent.parent / 'config') / name)
config_obj = configparser.ConfigParser()
config_obj.read(config_path)
config = {}
for section in config_obj.sections():
config[section] = {}
for (k, v) in config_obj[section].items():
... |
def _build_server(tmpdir, host):
ca = trustme.CA()
ca_cert_path = str((tmpdir / 'ca.pem'))
ca.cert_pem.write_to_path(ca_cert_path)
server_cert = ca.issue_cert(host)
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
server_crt = server_cert.cert_chain_pems[0]
server_key = server_c... |
def test_verify_status_message(base_message):
msg = base_message
msg.type = MsgType.Status
msg.attributes = StatusAttribute(status_type=StatusAttribute.Types.TYPING)
msg.verify()
with pytest.raises(AssertionError):
StatusAttribute(status_type=StatusAttribute.Types.UPLOADING_FILE, timeout=(- ... |
.parametrize(argnames='path_builder', argvalues=[os.path.join, Path])
def test_open_file(change_directory, path_builder):
expected_string = 'hello\nworld'
path = path_builder(change_directory, 'temporary-file')
with open_file(path, 'w') as file_out:
file_out.write(expected_string)
with open_file... |
class OptionPlotoptionsArearangeSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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(se... |
def extractTamwryntranslationsHomeBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("Boss's Death Guide", "Boss's Death Guide", 'translated'), ('Always with the Old Attack', ... |
class AS4C32M8(SDRModule):
nbanks = 4
nrows = 8192
ncols = 1024
technology_timings = _TechnologyTimings(tREFI=(.0 / 8192), tWTR=(2, None), tCCD=(1, None), tRRD=(None, 15))
speedgrade_timings = {'default': _SpeedgradeTimings(tRP=20, tRCD=20, tWR=15, tRFC=(None, 66), tFAW=None, tRAS=44)} |
.parametrize('version_info', [(sys.version_info[0], (sys.version_info[1] + 1), 0), (sys.version_info[0], (sys.version_info[1] + 1), 13), ((sys.version_info[0] + 1), sys.version_info[1], 0), (sys.version_info[0], (sys.version_info[1] + 1), 0, 'beta', 1), (sys.version_info[0], (sys.version_info[1] + 1), 0, 'candidate', 1... |
class Rule(object):
def __init__(self, rule_name, rule_index, rules):
self.rule_name = rule_name
self.rule_index = rule_index
self.rules = rules
def find_violations(self, instance_network_interface_list):
for instance_network_interface in instance_network_interface_list:
... |
def db_needs_migration():
with OperateInDirectory(get_src_dir()), AdminConnection().engine.connect().engine.begin() as connection:
logging.getLogger('alembic.runtime.migration').setLevel(logging.WARNING)
context = migration.MigrationContext.configure(connection)
current_revision = context.ge... |
def test_adding_in_es_config():
config = '\nesConfig:\n elasticsearch.yml: |\n key:\n nestedkey: value\n dot.notation: test\n\n log4j2.properties: |\n appender.rolling.name = rolling\n'
r = helm_template(config)
c = r['configmap'][(uname + '-config')]['data']
assert ('elasticsearch.yml' ... |
class NumberWords():
_WORD_MAP = ('one', 'two', 'three', 'four', 'five')
def __init__(self, start: int, stop: int) -> None:
self.start = start
self.stop = stop
def __iter__(self) -> NumberWords:
return self
def __next__(self) -> str:
if ((self.start > self.stop) or (self.... |
class CamelCaseTestCase(unittest.TestCase):
def test_python_conversion(self):
c_names = ['GetFooBar', 'GetOBBTree', 'XMLDataReader', 'GetFooXML', 'HTMLIsSGML', '_SetMe', '_XYZTest', 'Actor2D', 'Actor3D', 'Actor6D', 'PLOT3DReader', 'Actor61Dimension', 'GL2PSExporter', 'Volume16Reader']
t_names = ['ge... |
def extractTranSlationsCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if (item['tags'] == []):
titlemap = [('OWID - Chapter ', "Office Worker's Immortal Dungeon", 'translated'... |
_admin_required
def LocationEditSettings(request, location_slug):
location = get_object_or_404(Location, slug=location_slug)
if (request.method == 'POST'):
form = LocationSettingsForm(request.POST, instance=location)
if form.is_valid():
form.save()
messages.add_message(re... |
def _execute_bid_query(bid_id, details):
if (not details):
result = InternalServer.get_mongodb_driver().get_products_by_bid(bid_id)
else:
result = InternalServer.get_mongodb_driver().get_bid_info_by_id(bid_id)
if (len(result) == 0):
return (json.dumps({'err': 404, 'msg': 'BugTraq Id ... |
def test_squash_a_pruning_trie_keeps_unchanged_short_root_node():
db = {}
trie = HexaryTrie(db, prune=True)
trie[b'any'] = b'short'
root_hash = trie.root_hash
with trie.squash_changes() as trie_batch:
trie_batch[b'any'] = b'short'
assert (trie.root_hash == root_hash)
assert (... |
def test_serialization_branch_complex_2():
def t1(a: int) -> typing.NamedTuple('OutputsBC', t1_int_output=int, c=str):
return ((a + 2), 'world')
def t2(a: str) -> str:
return a
def my_wf(a: int, b: str) -> (int, str):
(x, y) = t1(a=a)
d = conditional('test1').if_((x == 4)).th... |
class AdImage(AdImageMixin, AbstractCrudObject):
def __init__(self, fbid=None, parent_id=None, api=None):
self._isAdImage = True
super(AdImage, self).__init__(fbid, parent_id, api)
class Field(AbstractObject.Field):
account_id = 'account_id'
created_time = 'created_time'
... |
('bodhi.server.tasks.expire_overrides.log')
class TestMain(BaseTaskTestCase):
def test_no_expire(self, log):
buildrootoverride = self.db.query(models.BuildrootOverride).all()[0]
buildrootoverride.expiration_date = (buildrootoverride.expiration_date + timedelta(days=500))
self.db.commit()
... |
class Migration(migrations.Migration):
dependencies = [('user', '0003_auto__1543')]
operations = [migrations.AddField(model_name='usermessage', name='is_supper', field=models.BooleanField(default=False, verbose_name='')), migrations.AlterField(model_name='usermessage', name='ids', field=models.UUIDField(blank=T... |
def getDBC_u(x, flag):
if (flag in [boundaryTags['left']]):
return (lambda x, t: ((((velRamp(t) * 4.0) * x[1]) * (fl_H - x[1])) / (fl_H ** 2)))
elif (flag in [boundaryTags['front'], boundaryTags['back'], boundaryTags['top'], boundaryTags['bottom']]):
return (lambda x, t: 0.0)
elif (flag in [... |
def _recorder(pid, stop, ival):
t = t0 = time()
process = psutil.Process(pid)
if (stop is None):
while True:
m = process.memory_info()
print(psutil.cpu_percent(), ',', m[0], ',', m[1])
sleep(ival)
t = time()
else:
while ((t - t0) < stop):
... |
class AdAssetFeedSpecEvents(AbstractCrudObject):
def __init__(self, fbid=None, parent_id=None, api=None):
self._isAdAssetFeedSpecEvents = True
super(AdAssetFeedSpecEvents, self).__init__(fbid, parent_id, api)
class Field(AbstractObject.Field):
id = 'id'
_field_types = {'id': 'string'... |
def mock_quantization_type(quant_func):
import builtins
import functools
from unittest import mock
import detectron2.layers as d2l
type_mapping = {d2l.Linear: torch.nn.Linear}
from d2go.utils.misc import check_version
if check_version(torch, '1.7.2', warning_only=True):
add_d2_quant_... |
_view(('PUT',))
_data()
def vm_define_user(request, hostname_or_uuid, data=None):
vm = get_vm(request, hostname_or_uuid, sr=('owner', 'node', 'template', 'slavevm'), check_node_status=None, exists_ok=True, noexists_fail=True)
allowed = {'hostname', 'alias', 'installed'}
for i in data.keys():
if (i n... |
class Ck401(BaseScanner):
def init(self, argv):
return True
def get_settings(self):
return dict(request_types='link,redirect,xhr,form,fetch', num_threads=10)
class Scan(ScannerThread):
def run(self):
try:
resp = self.send_request(proxy=' ignore_errors=True... |
class OptionPlotoptionsNetworkgraphSonificationTracksMappingHighpassFrequency(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 BinaryField():
def __init__(self, modulus):
self.modulus = modulus
self.height = log2(self.modulus)
self.order = ((2 ** self.height) - 1)
for base in range(2, (modulus - 1)):
powers = [1]
while (((len(powers) == 1) or (powers[(- 1)] != 1)) and (len(power... |
.parametrize('private_key, password, kdf, iterations, expected_decrypted_key, expected_kdf', get_encrypt_test_params(), ids=['hex_str', 'eth_keys.datatypes.PrivateKey', 'hex_str_provided_kdf', 'hex_str_default_kdf_provided_iterations', 'hex_str_pbkdf2_provided_iterations', 'hex_str_scrypt_provided_iterations'])
def tes... |
def __get_include_args(content, resolve_args):
included_files = []
try:
xml_nodes = minidom.parseString(content).getElementsByTagName('include')
for node in xml_nodes:
if ((node.nodeType == node.ELEMENT_NODE) and node.hasAttributes()):
filename = ''
fo... |
class XSSerCheckerResource(resource.Resource):
def __init__(self, name, parent):
self.name = str(name)
self.parent = parent
def render_GET(self, request):
print('SUCCESS!!', request)
self.parent.xsser.final_attack_callback(request)
response = 'thx for use XSSer ( !!'
... |
def get_info_bytes(rom_bytes: bytes, header_encoding: str) -> N64Rom:
(program_counter,) = struct.unpack('>I', rom_bytes[8:12])
libultra_version = chr(rom_bytes[15])
checksum = rom_bytes[16:24].hex().upper()
try:
name = (rom_bytes[32:52].decode(header_encoding).rstrip(' \x00') or 'empty')
ex... |
class BaseTool():
def __init__(self, *args, **kwargs):
self._agent = None
def agent(self):
return (loopgpt.agent.ACTIVE_AGENT or self._agent)
def agent(self, agent):
self._agent = agent
def id(self) -> str:
return '_'.join(camel_case_split(self.__class__.__name__)).lower(... |
def _validate(datum, schema, named_schemas, field, raise_errors, options):
record_type = extract_record_type(schema)
result = None
if ((datum is NoValue) and options.get('strict')):
result = False
else:
if (datum is NoValue):
datum = None
logical_type = extract_logica... |
class ChartParallelCoord(Chart):
builder_name = 'ChartSunbrust'
def dom(self) -> JsNvd3.JsNvd3ParallelCoordinates:
if (self._dom is None):
self._dom = JsNvd3.JsNvd3ParallelCoordinates(page=self.page, js_code=self.js_code, component=self)
return self._dom
def set_dimension_names(s... |
def stage_table(source: ETLObjectBase, destination: ETLWritableObjectBase, staging: ETLTemporaryTable) -> int:
shared_columns = _get_shared_columns(source.columns, destination.columns)
sql = '\n create temporary table {staging_object_representation} as\n select {select_columns}\n from {so... |
class UnionEt(Et):
def __init__(self, *ets):
self.ets = ets
super().__init__(self, str(self), is_array=False)
def __repr__(self):
inner = ''
for et in self.ets:
inner += f'{et}, '
inner = inner[:(- 2)]
return f'Union({inner})'
def __eq__(self, othe... |
def set_webhook(token, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None, drop_pending_updates=None, timeout=None, secret_token=None):
method_url = 'setWebhook'
payload = {'url': (url if url else '')}
files = None
if certificate:
files = {'certificate': cert... |
class MetaLexer(Lexer):
def process(self, ctx, value):
ctx.python_node('for name, value in current.response._meta_tmpl():')
ctx.variable('\'<meta name="%s" content="%s" />\' % (name, value)', escape=False)
ctx.python_node('pass')
ctx.python_node('for name, value in current.response._... |
class RegisterAddress(object):
def __init__(self, frame_offsets, bit_offset):
self.frame_index = 0
self.frame_offsets = frame_offsets
self.bit_offset = bit_offset
self.bits_used = set()
def next_bit(self, used=True):
output = '{}_{}'.format(self.frame_offsets[self.frame_i... |
class Velocity(java.Java):
def init(self):
self.update_actions({'render': {'render': '%(code)s', 'header': '\n#set($h=%(header)s)\n${h}\n', 'trailer': '\n#set($t=%(trailer)s)\n${t}\n', 'test_render': ('#set($c=%(n1)s*%(n2)s)\n${c}\n' % {'n1': rand.randints[0], 'n2': rand.randints[1]}), 'test_render_expected... |
def test_precision_validation():
class MyConfig(_ConfigBase):
sample_rate = _ConfigValue('SR', type=float, validators=[PrecisionValidator(4, 0.0001)])
c = MyConfig({'SR': '0.0000001'})
assert (c.sample_rate == 0.0001)
c = MyConfig({'SR': '0.555555'})
assert (c.sample_rate == 0.5556) |
def parse_repeated_value(definition, parcel: ParcelParser, parent_field: Field):
repeated = definition['__repeated']
backreference = definition['__backreference']
backreference_field = parent_field.walk_back_to(backreference)
if (not backreference_field):
raise ParseError('Failed to find back re... |
def check_legacy_parent_of_imported_privkey_wallet(wallet: Wallet, keypairs: Optional[Dict[(str, str)]]=None, password: Optional[str]=None) -> None:
assert (len(wallet.get_accounts()) == 1)
account: ImportedPrivkeyAccount = wallet.get_accounts()[0]
parent_keystores = wallet.get_keystores()
assert (len(p... |
def _load_config(options, verbose=False):
if (not os.path.exists('apistar.yml')):
if (options['schema']['path'] is None):
raise click.UsageError('Missing option "--path".')
config = options
else:
with open('apistar.yml', 'rb') as config_file:
content = config_file... |
_node(_get_all_wares_to_sell, select=_select_ware_to_sell, pagesize=20)
def node_start_sell(caller, raw_string, **kwargs):
coins = caller.coins
used_slots = caller.equipment.count_slots()
max_slots = caller.equipment.max_slots
text = f'"Anything you want to sell?" [you have |y{coins}|n coins, using |b{u... |
class BucketAccessControls(object):
def __init__(self, project_id, bucket, full_name, entity, email, domain, role, raw_json):
self.project_id = project_id
self.bucket = bucket
self.full_name = full_name
self.entity = entity
self.email = email
self.domain = domain
... |
(scope='function')
def vend_create_erasure_data(vend_connection_config: ConnectionConfig, vend_erasure_identity_email: str) -> None:
vend_secrets = vend_connection_config.secrets
headers = {'Authorization': f"Bearer {vend_secrets['token']}"}
base_url = f"
body = {'first_name': 'Ethyca', 'last_name': 'Te... |
def test_records_multiple_episodes():
env = build_dummy_maze_env()
env = SpacesRecordingWrapper.wrap(env, output_dir='space_records')
env.reset()
for _ in range(5):
for _ in range(10):
action = env.action_space.sample()
env.step(action)
env.reset()
dumped_file... |
class TestBinaryPath(TestCase):
def test_s3_package_path(self) -> None:
test_cases = [{'binary_info': BinaryInfo('data_processing/attribution_id_combiner'), 'version': 'latest', 'expected': f'{TEST_REPO}data_processing/attribution_id_combiner/latest/attribution_id_combiner'}, {'binary_info': BinaryInfo('pcf... |
class OptionPlotoptionsAreasplinerangeSonificationContexttracksMappingTime(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_mask_arguments_null_list():
configuration = HmacMaskingConfiguration()
masker = HmacMaskingStrategy(configuration)
expected = [None]
secret_key = MaskingSecretCache[str](secret='test_key', masking_strategy=HmacMaskingStrategy.name, secret_type=SecretType.key)
cache_secret(secret_key, reques... |
()
def get_therapy_sessions_distribution_data(patient, field):
if (field == 'therapy_type'):
result = frappe.db.get_all('Therapy Session', filters={'patient': patient, 'docstatus': 1}, group_by=field, order_by=field, fields=[field, 'count(*)'], as_list=True)
elif (field == 'exercise_type'):
data... |
def get_os_all_ipaddrs():
addrs_v4 = []
addrs_v6 = []
fd = os.popen('ip addr show')
for line in fd:
is_ipv6 = False
line = line.strip()
line = line.replace('\r', '')
line = line.replace('\n', '')
if (not line):
continue
p1 = line.find('inet')
... |
def test_circular_dependency_lift_minimal(graph_circular_dependency, variable):
(nodes, _, cfg) = graph_circular_dependency
run_out_of_ssa(cfg, SSAOptions.lift_minimal)
variable[0].is_aliased = True
variable[1].is_aliased = True
assert ((nodes[0].instructions == [Assignment(ListOperation([]), Call(i... |
.parametrize('ops', ALL_OPS)
.parametrize('dtype', FLOAT_TYPES)
def test_backprop_reduce_max(ops, dtype):
dX = ops.backprop_reduce_max(ops.xp.arange(1, 7, dtype=dtype).reshape(2, 3), ops.xp.array([[2, 1, 0], [1, 0, 1]]).astype('int32'), ops.xp.array([3, 2], dtype='int32'))
assert (dX.dtype == dtype)
ops.xp.... |
class ThreadPool():
def __init__(self, telebot, num_threads=2):
self.telebot = telebot
self.tasks = Queue.Queue()
self.workers = [WorkerThread(self.on_exception, self.tasks) for _ in range(num_threads)]
self.num_threads = num_threads
self.exception_event = threading.Event()
... |
def node_choose_ability(caller, raw_string, **kwargs):
text = 'Choose the ability to apply'
action_dict = kwargs['action_dict']
options = [{'desc': abi.value, 'goto': (_step_wizard, {**kwargs, **{'action_dict': {**action_dict, **{'stunt_type': abi, 'defense_type': abi}}}})} for abi in (Ability.STR, Ability.... |
.parametrize('test_input, expected', [({'10': {'id': '10'}}, [{'id': '10'}]), ({'10': {'id': '10'}, '20': {'id': '20'}}, [{'id': '10'}, {'id': '20'}]), ({'10': {'bu': 'a'}, '20': {'bu': 'b'}}, [{'id': '10', 'bu': 'a'}, {'id': '20', 'bu': 'b'}]), ({'10': {'bu': 'a'}, '20': {'bu': 'b'}}, [{'id': '10', 'bu': 'a'}, {'id': ... |
class BillingResponseLineItems(ModelSimple):
allowed_values = {}
validations = {}
additional_properties_type = None
_nullable = False
_property
def openapi_types():
lazy_import()
return {'value': ([BillingResponseLineItem],)}
_property
def discriminator():
return ... |
def f_build_srpm(f_build_something):
config = f_build_something
config.ssh.resultdir = 'srpm-builds/'
config.fe_client.return_value.get.return_value = _get_srpm_job()
config.ssh.set_command('copr-rpmbuild --verbose --drop-resultdir --srpm --task-url --detached', 0, '666', '')
patcher = mock.patch('... |
def unpack_bl(upper_16, lower_16):
s = ((upper_16 & 1024) >> 10)
imm10 = (upper_16 & 1023)
imm11 = (lower_16 & 2047)
j1 = ((lower_16 & 8192) >> 13)
j2 = ((lower_16 & 2048) >> 11)
i1 = (- ((j1 ^ s) - 1))
i2 = (- ((j2 ^ s) - 1))
value = (s << 23)
value |= (i1 << 22)
value |= (i2 <<... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.