code stringlengths 281 23.7M |
|---|
class VonKries(CAT, metaclass=VonKriesMeta):
NAME = 'von-kries'
MATRIX = [[0.40024, 0.7076, (- 0.08081)], [(- 0.2263), 1.16532, 0.0457], [0.0, 0.0, 0.91822]]
def adapt(self, w1: Tuple[(float, float)], w2: Tuple[(float, float)], xyz: VectorLike) -> Vector:
if (w1 == w2):
return list(xyz)
... |
.parallel(nprocs=3)
def test_extruded_periodic_annulus():
m = 5
n = 7
mesh = CircleManifoldMesh(n)
mesh0 = ExtrudedMesh(mesh, layers=m, layer_height=(1.0 / m), extrusion_type='radial')
mesh = IntervalMesh(m, 1.0, 2.0)
mesh1 = ExtrudedMesh(mesh, layers=n, layer_height=((2 * pi) / n), extrusion_ty... |
class ToptierAgency(models.Model):
toptier_agency_id = models.AutoField(primary_key=True)
create_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now=True)
toptier_code = models.TextField(db_index=True, unique=True)
abbreviation = models.TextField(blank=True, nu... |
def test_flatten_is_working_properly_with_no_references(create_test_data, trash_bin):
data = create_test_data
arch = Archiver()
project_path = arch.flatten([data['asset2_model_main_v001'].absolute_full_path])
trash_bin.append(project_path)
assert os.path.exists(project_path)
assert os.path.exist... |
class AccountService(object):
def __init__(self, bot_name, timestamp, base_capital=1000000, buy_cost=0.001, sell_cost=0.001, slippage=0.001, stock_fuquan='hfq'):
self.logger = logging.getLogger(__name__)
self.base_capital = base_capital
self.buy_cost = buy_cost
self.sell_cost = sell_... |
class TestMACCore(unittest.TestCase):
def test(self):
dut = DUT()
generators = {'sys': [main_generator(dut), dut.streamer.generator(), dut.streamer_randomizer.generator(), dut.logger_randomizer.generator(), dut.logger.generator()], 'eth_tx': [dut.phy_model.phy_sink.generator(), dut.phy_model.generat... |
class TestFixEpoch(TestCase):
def test_fix_epoch(self):
for (long_epoch, epoch) in [(, ), (, ), (, ), (, ), (, ), (, ), (, ), (, )]:
assert (epoch == fix_epoch(long_epoch))
def test_fix_epoch_raise(self):
with pytest.raises(ValueError):
fix_epoch(None) |
class User(GraphObject):
__primarykey__ = 'username'
username = Property()
def __init__(self, username):
self.username = username
def find(self):
user = self.match(graph, self.username).first()
return user
def register(self, password):
if (not self.find()):
... |
def get_serializable_launch_plan(entity_mapping: OrderedDict, settings: SerializationSettings, entity: LaunchPlan, recurse_downstream: bool=True, options: Optional[Options]=None) -> _launch_plan_models.LaunchPlan:
if recurse_downstream:
wf_spec = get_serializable(entity_mapping, settings, entity.workflow, o... |
def extract_concrete_prefix_index(bv):
try:
get_concrete_int(bv)
return (- 1)
except AttributeError as e:
pass
hi = (bv.size() - 1)
lo = 0
while (hi > lo):
mid = (lo + ((hi - lo) // 2))
hi_bv = z3.Extract(hi, mid, bv)
lo_bv = z3.Extract((mid - 1), lo, ... |
def common_top_matter(out, name):
loxi_utils.gen_c_copy_license(out)
out.write(('\n/\n * File: %s\n *\n * DO NOT EDIT\n *\n * This file is automatically generated\n *\n /\n\n' % name))
if (name[(- 2):] == '.h'):
out.write(('\n#if !defined(%(h)s)\n#define %(h)s\n\n' % dict(h=h_file_to_define(name)))) |
class GPIO(GenericGPIO):
def setup_module(self) -> None:
import smbus as gpio
addr = self.config['dev_addr']
bus = self.config['i2c_bus_num']
self.bus = gpio.SMBus(bus)
self.address = addr
def setup_pin(self, pin: PinType, direction: PinDirection, pullup: PinPUD, pin_conf... |
def valid_ovsdb_addr(addr):
m = re.match('unix:(\\S+)', addr)
if m:
file = m.group(1)
return os.path.isfile(file)
m = re.match('(tcp|ssl):(\\S+):(\\d+)', addr)
if m:
address = m.group(2)
port = m.group(3)
if ('[' in address):
address = address.strip('[... |
class ArgumentParser():
def parse_args(self, args: Optional[Sequence[str]]=None, namespace: Optional[Namespace]=None) -> Namespace:
raise NotImplementedError
def parse_known_args(self, args: Optional[Sequence[str]]=None, namespace: Optional[Namespace]=None) -> Tuple[(Namespace, List[str])]:
rais... |
def extractTimelesspavilionCom(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) i... |
class Util():
def async_requests_available():
return (sys.version_info >= (3, 5, 3))
def ca_bundle_path():
return os.path.join(os.path.dirname(__file__), '..', '..', 'fb_ca_chain_bundle.crt')
def appsecret_proof(appsecret, access_token):
hmac_object = hmac.new(appsecret.encode('utf-8... |
def upgrade():
c = get_context()
insp = sa.inspect(c.connection.engine)
groups_permissions_pkey = 'groups_permissions_pkey'
groups_pkey = 'groups_pkey'
groups_resources_permissions_pkey = 'groups_resources_permissions_pkey'
users_groups_pkey = 'users_groups_pkey'
users_permissions_pkey = 'us... |
def defaults_from_env(f):
sig = inspect.signature(f)
params = []
changed = False
for param in sig.parameters.values():
envname = f'NUTILS_{param.name.upper()}'
if ((envname in os.environ) and (param.annotation != param.empty) and (param.default != param.empty)):
try:
... |
class ProductionOps():
def production_info(self) -> ProductionInfo:
return getattr(self, '__production')
def root(self):
return getattr(self, '__root', None)
def parent(self):
return getattr(self, '__parent', None)
def children(self):
children_info = self.production_info(... |
class Delaunay2D(FilterBase):
__version__ = 0
filter = Instance(tvtk.Delaunay2D, args=(), allow_none=False, record=True)
input_info = PipelineInfo(datasets=['structured_grid', 'poly_data', 'unstructured_grid'], attribute_types=['any'], attributes=['any'])
output_info = PipelineInfo(datasets=['poly_data'... |
def test_namedtuple():
T = namedtuple('T', 'foo bar')
def default(o):
if isinstance(o, T):
return dict(o._asdict())
raise TypeError(('Unsupported type %s' % (type(o),)))
packed = packb(T(1, 42), strict_types=True, use_bin_type=True, default=default)
unpacked = unpackb(packed,... |
class OptionPlotoptionsPyramid3dSonificationTracksMappingPitch(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('y')
def mapTo(self, text: str):
se... |
def zone_chart(activity_id=None, sport='run', metrics=['power_zone', 'hr_zone'], chart_id='zone-chart', days=90, height=400, intensity='all'):
if activity_id:
df_samples = pd.read_sql(sql=app.session.query(stravaSamples).filter((stravaSamples.activity_id == activity_id)).statement, con=engine, index_col=['t... |
def test_explode_get_fastas_file_by_taxon(o_dir, e_dir, request):
program = 'bin/assembly/phyluce_assembly_explode_get_fastas_file'
output = os.path.join(o_dir, 'exploded-by-taxa')
cmd = [os.path.join(request.config.rootdir, program), '--input', os.path.join(e_dir, 'taxon-set.complete.fasta'), '--output', o... |
def test_extend_memory_doesnt_increase_until_32_bytes_are_used(computation):
computation.extend_memory(0, 1)
computation.extend_memory(1, 1)
assert (len(computation._memory._bytes) == 32)
computation.extend_memory(2, 32)
assert (len(computation._memory._bytes) == 64)
assert (computation._gas_met... |
class Foo(HasTraits):
bar = Float
baz = Float
fuz = Float
def _bar_changed(self):
pass
_trait_change('bar')
def _on_bar_change_notification(self):
pass
_trait_change('baz')
def _on_baz_change_notification(self):
self.bar += 1
_trait_change('fuz')
def _on_f... |
class TestAsyncAggregator():
def _test_one_step(self, param_after_local_training: float, param_after_global_training: float, weight: float, config: AsyncAggregatorConfig) -> None:
init_val = 1
global_model = MockQuadratic1DFL(Quadratic1D())
async_aggregator = instantiate(config, global_model... |
def format_mr0(bl, cl, wr, dll_reset):
bl_to_mr0 = {4: 2, 8: 0}
wr_to_mr0 = {10: 0, 12: 1, 14: 2, 16: 3, 18: 4, 20: 5, 24: 6, 22: 7, 26: 8, 28: 9}
mr0 = bl_to_mr0[bl]
mr0 |= ((cl_to_mr0[cl] & 1) << 2)
mr0 |= (((cl_to_mr0[cl] >> 1) & 7) << 4)
mr0 |= (((cl_to_mr0[cl] >> 4) & 1) << 12)
mr0 |= (... |
class VideoRecordingList(ResourceList):
def before_get(self, args, kwargs):
if kwargs.get('video_stream_id'):
stream = safe_query_kwargs(VideoStream, kwargs, 'video_stream_id', 'id')
if (stream.channel and (stream.channel.provider == 'bbb')):
if (not has_access('is_or... |
def extractGourmetscansNet(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) in ta... |
def get_dbt_command_list(args: argparse.Namespace, models_list: List[str]) -> List[str]:
command_list = []
if args.debug:
command_list += ['--debug']
command_list += ['run']
command_list += ['--threads', str(1)]
if args.project_dir:
command_list += ['--project-dir', args.project_dir]... |
def get_columns(table_name: str, schema_name: Optional[str]=None, dblink_name: Optional[str]=None) -> List[str]:
sql = "\n select attname as column_name\n from pg_attribute\n where attnum > 0 and attisdropped is false and attrelid = '{table}'::regclass\n order by attnum\n ... |
def evaluate_policy_rule(taxonomy: Taxonomy, policy_rule: PolicyRule, data_subjects: List[str], data_categories: List[str], data_use: str, declaration_violation_message: str) -> List[Violation]:
category_hierarchies = [get_fides_key_parent_hierarchy(taxonomy=taxonomy, fides_key=declaration_category) for declaration... |
class CuratorTestCase(TestCase):
def setUp(self):
super(CuratorTestCase, self).setUp()
self.logger = logging.getLogger('CuratorTestCase.setUp')
self.client = get_client()
args = {}
args['HOST'] = HOST
args['time_unit'] = 'days'
args['prefix'] = 'logstash-'
... |
(scope='function')
def fullstory_secrets(saas_config):
return {'domain': (pydash.get(saas_config, 'fullstory.domain') or secrets['domain']), 'api_key': (pydash.get(saas_config, 'fullstory.api_key') or secrets['api_key']), 'fullstory_user_id': {'dataset': 'fullstory_postgres', 'field': 'fullstory_users.fullstory_use... |
_abort.register_cause_code
_error.register_cause_code
class cause_invalid_stream_id(cause_with_value):
_PACK_STR = '!HHH2x'
_MIN_LEN = struct.calcsize(_PACK_STR)
def cause_code(cls):
return CCODE_INVALID_STREAM_ID
def __init__(self, value=0, length=0):
super(cause_invalid_stream_id, self... |
def iamdb_pieces(args):
iamdb = module_from_file('iamdb', os.path.join(root_dir, 'datasets/iamdb.py'))
forms = iamdb.load_metadata(args.data_dir, '')
ds_keys = set()
for (_, v) in iamdb.SPLITS.items():
for ds in v:
with open(os.path.join(args.data_dir, f'{ds}.txt'), 'r') as fid:
... |
def parse_note(note_str):
try:
elements = re.findall('^(\\d{0,2})([pbeh]|[cdfga]#?)(\\d?)(\\.?)$', note_str)[0]
funcs = (parse_duration, parse_pitch, parse_octave, has_dot)
elements = [func(element) for (func, element) in zip(funcs, elements)]
except:
return False
keys = ('du... |
def serialise_cat_upgrades(save_data: list[int], cat_upgrades: dict[(str, list[int])]) -> list[int]:
data: list[int] = []
length = len(cat_upgrades['Base'])
for cat_id in range(length):
data.append(cat_upgrades['Plus'][cat_id])
data.append(cat_upgrades['Base'][cat_id])
write_length_data(... |
class StateCondition(Condition):
def is_met(self, event: Event, context: Context) -> bool:
state: ValueState = context.get_state(ValueStateDescriptor(name='count'))
v = state.value()
if (v is None):
v = 0
v = (v + 1)
state.update(v)
if (0 == (v % 2)):
... |
def get_messages_positions(path):
fd = os.open(path, os.O_RDONLY)
try:
def get(count):
buf = os.read(fd, count)
assert (len(buf) == count)
return int.from_bytes(buf, byteorder='big', signed=False)
offset = 0
while True:
code = os.read(fd, 4... |
def _dataIsString(data):
data = (('(' + data) + ')')
result = fb.evaluateExpressionValue((('(NSString*)[[NSString alloc] initWithData:' + data) + ' encoding:4]'))
if ((result.GetError() is not None) and (str(result.GetError()) != 'success')):
return False
else:
isString = (result.GetValu... |
class OptionPlotoptionsStreamgraphSonificationContexttracks(Options):
def activeWhen(self) -> 'OptionPlotoptionsStreamgraphSonificationContexttracksActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsStreamgraphSonificationContexttracksActivewhen)
def instrument(self):
retur... |
class ConfigFile():
def __init__(self, config_name):
self.user_home = os.getenv('RALLY_HOME', os.path.expanduser('~'))
self.rally_home = os.path.join(self.user_home, '.rally')
if (config_name is not None):
self.config_file_name = f'rally-{config_name}.ini'
else:
... |
class ColormappedSelectionOverlay(AbstractOverlay):
plot = Property
fade_alpha = Float(0.15)
minimum_delta = Float(0.01)
selected_outline_width = Float(1.0)
unselected_outline_width = Float(0.0)
selection_type = Enum('range', 'mask')
_plot = Instance(ColormappedScatterPlot)
_visible = Bo... |
class Dependencies():
def __init__(self, build_dependencies: Dict[(str, 'Package')]) -> None:
self.build_dependencies = build_dependencies
def __getitem__(self, key: str) -> 'Package':
return self.build_dependencies.get(key)
def __contains__(self, key: str) -> bool:
return (key in se... |
def compile_unet(pt_mod, batch_size=2, height=64, width=64, dim=320, hidden_dim=1024, use_fp16_acc=False, convert_conv_to_gemm=False, attention_head_dim=[5, 10, 20, 20], model_name='UNet2DConditionModel', use_linear_projection=False):
ait_mod = ait_UNet2DConditionModel(sample_size=64, cross_attention_dim=hidden_dim... |
def get_generator_and_config_args(tool):
args = []
cmake_generator = CMAKE_GENERATOR
if (('Visual Studio 16' in CMAKE_GENERATOR) or ('Visual Studio 17' in CMAKE_GENERATOR)):
args += ['-A', cmake_target_platform(tool)]
args += [('-Thost=' + cmake_host_platform())]
elif (('Visual Studio' i... |
class TestFilePathFieldRequired():
def test_required_passed_to_both_django_file_path_field_and_base(self):
field = serializers.FilePathField(path=os.path.abspath(os.path.dirname(__file__)), required=False)
assert ('' in field.choices)
assert (field.required is False)
with pytest.rais... |
def test_client_create_access_code_jwe(oauth_client, config):
jwe = oauth_client.create_access_code_jwe(config.security.app_encryption_key)
token_data = json.loads(extract_payload(jwe, config.security.app_encryption_key))
assert (token_data[JWE_PAYLOAD_CLIENT_ID] == oauth_client.id)
assert (token_data[J... |
def test_init_raw_transaction():
ledger_id = 'some_ledger'
body = {'body': 'value'}
rt = RawTransaction(ledger_id, body)
assert (rt.ledger_id == ledger_id)
assert (rt.body == body)
assert (str(rt) == "RawTransaction: ledger_id=some_ledger, body={'body': 'value'}")
assert (rt == rt) |
class Module02(Digraph.Node):
depends_on = ['Module01']
def __init__(self, config):
Digraph.Node.__init__(self, 'Module02')
def get_type_set(self):
return set([InputModuleTypes.reqtag])
def set_modules(self, mods):
pass
def rewrite(self, rid, reqs):
return ('SameTag',... |
def check_create_keys(wallet: Wallet, account_script_type: ScriptType) -> None:
def check_rows(rows: List[KeyInstanceRow], script_type: ScriptType) -> None:
for row in rows:
assert isinstance(row.keyinstance_id, int)
assert (account.get_id() == row.account_id)
assert (1 =... |
def extractKudarajin(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
if (('I Appear to have been Reincarnated as a Love Interest in an Otome Game' in item['tags']) or item['title']... |
class Translator(object):
ParseTree = ParseTree
parser = parser
ST = ast
def __init__(self, st):
for (value, name) in self.parser.tokenizer.tok_name.items():
setattr(self, name, value)
def isdict(obj):
return isinstance(obj, dict)
for (name, d) in inspect.... |
def test_bitly_total_clicks():
body = json.dumps({'link_clicks': [{'clicks': 20}]})
headers = {'Authorization': f'Bearer {token}'}
url = ''.join(urlparse(shorten)[1:3])
url = f'{bitly.api_url}/bitlinks/{url}/clicks'
responses.add(responses.GET, url, headers=headers, body=body, match_querystring=True... |
def map_fun(context):
tf_context = TFContext(context)
job_name = tf_context.get_node_type()
index = tf_context.get_index()
cluster_json = tf_context.get_tf_cluster_config()
print(cluster_json)
sys.stdout.flush()
cluster = tf.train.ClusterSpec(cluster=cluster_json)
server = tf.train.Serve... |
_eh
class LaevateinHandler(THBEventHandler):
interested = ['attack_aftergraze']
card_usage = 'drop'
def handle(self, evt_type, arg):
if (evt_type == 'attack_aftergraze'):
(act, succeed) = arg
assert isinstance(act, basic.BaseAttack)
if succeed:
ret... |
def test_api_version_ord():
assert (APIVersion(1, 0) == APIVersion(1, 0))
assert (APIVersion(1, 0) < APIVersion(1, 1))
assert (APIVersion(1, 1) <= APIVersion(1, 1))
assert (APIVersion(1, 0) < APIVersion(2, 0))
assert (not (APIVersion(2, 1) <= APIVersion(2, 0)))
assert (APIVersion(2, 1) > APIVers... |
class GraphAdjacencyMethods():
def _dummy_symmetric_adj_tensor_factory(cls, in_shape: Sequence[int]) -> Callable[([], torch.Tensor)]:
def create_binary_sym_tensor() -> torch.Tensor:
xx_np = np.random.randint(0, 2, size=in_shape).astype(np.float32)
xx = torch.from_numpy(xx_np)
... |
def upgrade():
for table_name in tables_to_update:
logger.info(('upgrading table: %s' % table_name))
with op.batch_alter_table(table_name) as batch_op:
for column_name in tables_to_update[table_name]:
logger.info(('altering column: %s' % column_name))
batc... |
('ecs_deploy.cli.get_client')
def test_update_task_empty_environment_variable_again(get_client, runner):
get_client.return_value = EcsTestClient('acces_key', 'secret_key')
result = runner.invoke(cli.update, (TASK_DEFINITION_ARN_1, '-e', 'webserver', 'empty', ''))
assert (result.exit_code == 0)
assert (n... |
def test_boundaryspec_classmethods():
boundary_spec = BoundarySpec.pml(x=False, y=True, z=True)
boundaries = boundary_spec.to_list
assert (isinstance(boundaries[0][0], Periodic) and isinstance(boundaries[0][1], Periodic) and isinstance(boundaries[1][0], PML) and isinstance(boundaries[1][1], PML) and isinsta... |
def patch_len(fit_generator):
(fit_generator)
def fit_generator_patch_len(*args, **kwargs):
generator = args[1]
steps_per_epoch = kwargs.get('steps_per_epoch', len(generator))
patch_train_sequence_len = patch.object(generator.__class__, '__len__', return_value=steps_per_epoch)
va... |
class Ops(enum.Enum):
ADD = 1
MUL = 2
SUB = 3
DIV = 4
SDIV = 5
MOD = 6
SMOD = 7
ADDMOD = 8
MULMOD = 9
EXP = 10
SIGNEXTEND = 11
LT = 16
GT = 17
SLT = 18
SGT = 19
EQ = 20
ISZERO = 21
AND = 22
OR = 23
XOR = 24
NOT = 25
BYTE = 26
SH... |
class SwapFacePipelineOptions():
def __init__(self):
self.parser = ArgumentParser()
self.initialize()
def initialize(self):
self.parser.add_argument('--num_seg_cls', type=int, default=12, help='Segmentation mask class number')
self.parser.add_argument('--train_G', default=True, t... |
def test_raises_field_errors_unexpected_only(invalid_event_id_field_error, unknown_event_id_field_error):
errors = [invalid_event_id_field_error, unknown_event_id_field_error]
with pytest.raises(pytest.raises.Exception):
with raises_field_errors({'event_id': ['UNKNOWN']}, only=True):
raise C... |
.skip('require proper tests case')
def test_data_quality_test_target_features_correlation() -> None:
test_dataset = pd.DataFrame({'feature1': [0, 1, 2, 3], 'target': [0, 0, 0, 1]})
column_mapping = ColumnMapping(task='regression')
suite = TestSuite(tests=[TestTargetFeaturesCorrelations()])
suite.run(cur... |
class Solution(object):
def combinationSum2(self, candidates, target):
def fill_results(candidates, index, target, curr, results):
if ((index >= len(candidates)) and (target > 0)):
return
elif (target == 0):
results.add(tuple(curr))
ret... |
_module()
class SampleDataset(Dataset):
def __init__(self, dataset: Union[(dict, Dataset)], num_samples: int=8, collate_fn=None) -> None:
super().__init__()
self.num_samples = num_samples
self.collate_fn = collate_fn
if isinstance(dataset, dict):
self.dataset = DATASETS.b... |
class OptionSeriesColumnpyramidDatasorting(Options):
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def matchByName(self):
return self._config_get(None)
def matchByName(self, flag: bool):
self._config(flag... |
_bad_request
def practice_price_per_unit(request, code):
date = _specified_or_last_date(request, 'prescribing')
practice = get_object_or_404(Practice, code=code)
context = {'entity': practice, 'entity_name': practice.cased_name, 'entity_name_and_status': practice.name_and_status, 'highlight': practice.code,... |
def create_multiple_website_clicks_ads(account, name, country, titles, bodies, urls, image_paths, bid_strategy, daily_budget=None, lifetime_budget=None, start_time=None, end_time=None, age_min=None, age_max=None, genders=None, campaign=None, paused=False):
if (daily_budget is None):
if (lifetime_budget is N... |
def fetch_dag_data(dag_dump_dir: str, epoch_seed: bytes) -> Tuple[(bytes, ...)]:
dag_file_path = f'{dag_dump_dir}/full-R23-{epoch_seed.hex()[:16]}'
with open(dag_file_path, 'rb') as fp:
dag_dataset = fp.read()
dag_dataset = dag_dataset[8:]
dag_dataset_items = []
for i in range(0, len(dag... |
class Language(Options):
def decimal(self):
return self._config_get()
def decimal(self, val):
self._config(val)
def url(self):
return self._config_get()
def url(self, val):
self._config(val)
def thousands(self):
return self._config_get()
def thousands(self... |
class CmdUnconnectedCreate(COMMAND_DEFAULT_CLASS):
key = 'create'
aliases = ['cre', 'cr']
locks = 'cmd:all()'
arg_regex = '\\s.*?|$'
def at_pre_cmd(self):
if (not settings.NEW_ACCOUNT_REGISTRATION_ENABLED):
self.msg('Registration is currently disabled.')
return True
... |
class GCRARCArchive():
def __init__(self, file_path: Path, file_bytes):
self.file_path = file_path
self.compression = 'none'
file_bytes = self.try_decompress_archive(file_bytes)
self.magic = struct.unpack_from('>I', file_bytes, 0)[0]
self.file_size = struct.unpack_from('>I', ... |
class WafFirewallResponseDataAllOf(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
lazy_... |
def _test_success_with_all_filters_recipient_location_state(client):
resp = client.post('/api/v2/search/spending_by_geography', content_type='application/json', data=json.dumps({'scope': 'recipient_location', 'geo_layer': 'state', 'filters': non_legacy_filters()}))
assert (resp.status_code == status.HTTP_200_OK... |
class TestNTESMO(unittest.TestCase):
def setUp(self):
self.session = Session()
self.adapter = Adapter()
self.session.mount(' self.adapter)
data = open('parsers/test/mocks/AU/NTESMO.xlsx', 'rb')
self.adapter.register_uri(ANY, ANY, content=data.read())
index_page = '<di... |
class BreakScreen(Subscriber):
def __init__(self, monitor: Monitor, session: Session, config: Config):
logger.debug('action=init_screen monitor=%s', monitor)
self.monitor = monitor
self.session = session
self.options = self.create_options(config)
self.countdown = Gtk.Label(la... |
('/models')
def update_all_models(models: Optional[List[Model]]=None, connector: Connector=Depends(get_connection)):
try:
if (models is None):
models = []
connector.save_models(models)
models += connector.load_models()
except exc.CannotSaveModel:
raise HTTPException(s... |
class RadiusPenalty(Penalty):
min_radius: float = 0.15
alpha: float = 1.0
kappa: float = 10.0
wrap: bool = False
def evaluate(self, points: ArrayFloat2D) -> float:
def quad_fit(p0, pc, p2):
p1 = (((2 * pc) - (p0 / 2)) - (p2 / 2))
def p(t):
term0 = (((1... |
class Statement(BaseElement):
def __init__(self, Action, Effect, Resource):
self.Action = Action
self.Effect = Effect
self.Resource = Resource
def json_repr(self):
return {'Action': self.Action, 'Effect': self.Effect, 'Resource': self.Resource}
def merge(self, other):
... |
class Command(object):
comp = None
runner = None
executor = None
exit_code = 0
errmsg = None
display = False
jobs = 0
mypy_args = None
argv_args = None
stack_size = 0
use_cache = USE_CACHE
fail_fast = False
prompt = Prompt()
def start(self, run=False):
if ... |
def lazy_import():
from fastly.model.logging_common_response_all_of import LoggingCommonResponseAllOf
from fastly.model.logging_common_response_all_of1 import LoggingCommonResponseAllOf1
globals()['LoggingCommonResponseAllOf'] = LoggingCommonResponseAllOf
globals()['LoggingCommonResponseAllOf1'] = Loggi... |
def make_testcase(contract_address):
def test_robustness(self):
contract = get_contract_from_blockchain(contract_address, '../../../api_key.txt')
contract = fix_pragma(contract)
config = AnalysisConfiguration(ast_compiler=(lambda t: solidity_ast_compiler.compile_ast(t.source_file)), cfg_comp... |
def handle(editor, cmd: str) -> bool:
if cmd.startswith('siac-hl-clicked '):
id = int(cmd.split()[1])
color = ' '.join(cmd.split()[2:])
Reader.highlight_color = color
Reader.highlight_type = id
return True
elif cmd.startswith('siac-pdf-page-loaded '):
page = int(c... |
class TestAlgebra(unittest.TestCase):
def test_cross(self):
self.assertEqual(alg.cross([1, 2, 3], [4, 5, 6]), [(- 3), 6, (- 3)])
self.assertEqual(alg.cross([1, 2], [4, 5]), [(- 3)])
self.assertEqual(alg.cross([1, 2, 3], [4, 5]), [(- 15), 12, (- 3)])
self.assertEqual(alg.cross([1, 2],... |
def extractTamingwangxianWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('mdzs', 'Grandmaster of Demonic Cultivation', 'translated'), ('PRC', 'PRC', 'translated'), ... |
def JoinArgs(args):
arr = []
for item in args:
if (hasattr(item, 'savefig') and callable(item.savefig)):
d = io.BytesIO()
item.savefig(d, format='png')
arr.append(('`data:image/png;base64,%s`' % base64.b64encode(d.getvalue()).decode('utf-8')))
elif (isinstance... |
class MainWindow(QtWidgets.QMainWindow):
_default_window_width = 1200
_default_window_height = 800
_sidemenu_width = 400
def __init__(self, onnx_model_path='', parent=None):
super(MainWindow, self).__init__(parent)
self.graph: ONNXNodeGraph = None
self.load_graph()
self.g... |
def ait_register_custom_acc_mapper_fn(op_and_target: Tuple[(str, Union[(str, Callable)])], arg_replacement_tuples: List[Union[(Tuple[(Union[(str, Tuple[(str, ...)])], str)], Tuple[(Union[(str, Tuple[(str, ...)])], str, bool)])]], needs_shapes_for_normalization=False, allow_normalize_from_torch_package=False):
def i... |
(scope='session')
def rollbar_secrets(saas_config):
return {'domain': (pydash.get(saas_config, 'rollbar.domain') or secrets['domain']), 'read_access_token': (pydash.get(saas_config, 'rollbar.read_access_token') or secrets['read_access_token']), 'write_access_token': (pydash.get(saas_config, 'rollbar.write_access_to... |
class bsn_generic_stats_reply(bsn_stats_reply):
version = 4
type = 19
stats_type = 65535
experimenter = 6035143
subtype = 16
def __init__(self, xid=None, flags=None, entries=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags !=... |
def _get_base_model_descriptions(model_cls: 'BaseModel') -> List[ParameterDescription]:
from dbgpt._private import pydantic
version = int(pydantic.VERSION.split('.')[0])
schema = (model_cls.model_json_schema() if (version >= 2) else model_cls.schema())
required_fields = set(schema.get('required', []))
... |
('request-certificate', cls=FandoghCommand)
('--name', 'name', prompt='Domain name', help='The domain name')
def request_certificate(name):
create_certificate(name)
command = format_text('fandogh domain details --name {}'.format(name), TextStyle.OKBLUE)
click.echo("Your request has been submitted and we are... |
def load(file, enforce_filetype=True):
(s, lim) = get_ivals()
if enforce_filetype:
file = pickled(file)
try:
return pickle_load(file)
except (EOFError, OSError, IOError) as exc:
msg = str(exc)
warnings.warn(('Could not load transformer at %s. Will check every %.1f seconds... |
class Test_HotStart_rans3p(object):
def setup_class(cls):
cls._scriptdir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, cls._scriptdir)
def teardown_class(cls):
sys.path.remove(cls._scriptdir)
pass
def setup_method(self, method):
self.aux_names = []
... |
class AdCreativeLinkData(AbstractObject):
def __init__(self, api=None):
super(AdCreativeLinkData, self).__init__()
self._isAdCreativeLinkData = True
self._api = api
class Field(AbstractObject.Field):
ad_context = 'ad_context'
additional_image_index = 'additional_image_ind... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.