code stringlengths 281 23.7M |
|---|
def default(template='index'):
template = (template if template.endswith('.html') else (template + '.html'))
try:
return render_template(('static_pages/' + template), is_redirect=request.args.get('redirected'))
except TemplateNotFound:
return (render_template('static_pages/404.html'), 404) |
class OptionSeriesArcdiagramMarker(Options):
def fillColor(self):
return self._config_get(None)
def fillColor(self, text: str):
self._config(text, js_type=False)
def fillOpacity(self):
return self._config_get(1)
def fillOpacity(self, num: float):
self._config(num, js_type... |
def _only_reshape(array, source, target):
(source, target) = (source.split(), target.replace(' * ', '*').split())
input_shape = {key: array.shape[index] for (index, key) in enumerate(source)}
output_shape = []
for t in target:
product = 1
if (not (t == '1')):
t = t.split('*')... |
def add_bgp_error_metadata(code, sub_code, def_desc='unknown'):
if (_EXCEPTION_REGISTRY.get((code, sub_code)) is not None):
raise ValueError(('BGPSException with code %d and sub-code %d already defined.' % (code, sub_code)))
def decorator(subclass):
if issubclass(subclass, BGPSException):
... |
def upgrade():
op.create_table('event_model', sa.Column('offset', sa.BigInteger().with_variant(sa.Integer(), 'sqlite'), nullable=False), sa.Column('key', sa.String(length=1024), nullable=False), sa.Column('value', sa.Text(), nullable=True), sa.Column('context', sa.Text(), nullable=True), sa.Column('namespace', sa.S... |
class StructureStructureInterface(AbstractBCPlacement):
structures: Tuple[(str, str)] = pd.Field(title='Structures', description='Names of two structures.')
('structures', always=True)
def unique_names(cls, val):
if (val[0] == val[1]):
raise SetupError("The same structure is provided twi... |
()
def system_with_dataset_reference() -> Generator:
(yield [models.System(organization_fides_key=1, fides_key='test_system', system_type='test', privacy_declarations=[models.PrivacyDeclaration(name='test_privacy_declaration', data_categories=[], data_use='test_data_use', data_subjects=[], dataset_references=['test... |
def get_nodes(request, sr=(), pr=(), order_by=('hostname',), annotate=None, extra=None, **kwargs):
if (not request.user.is_staff):
kwargs['dc'] = request.dc
if sr:
qs = Node.objects.select_related(*sr)
else:
qs = Node.objects
if pr:
qs = qs.prefetch_related(*pr)
if an... |
def test_nested_schema_array():
artist = typesystem.Schema(fields={'name': typesystem.String(max_length=100)})
definitions = typesystem.Definitions()
definitions['Artist'] = artist
album = typesystem.Schema(fields={'title': typesystem.String(max_length=100), 'release_year': typesystem.Integer(), 'artist... |
def test_digest_change(flyte_project):
ignore = IgnoreGroup(flyte_project, [GitIgnore, DockerIgnore, StandardIgnore])
digest1 = compute_digest(flyte_project, ignore.is_ignored)
change_file = (((flyte_project / 'src') / 'workflows') / 'hello_world.py')
assert (not ignore.is_ignored(change_file))
chan... |
class OptionPlotoptionsItemSonificationContexttracksMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsItemSonificationContexttracksMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsItemSonificationContexttracksMappingLowpassFrequency)
def resonance(self... |
def init_params(networks: TDMPCNetworks, spec: specs.EnvironmentSpec, key: jax.random.PRNGKeyArray):
keys = jax.random.split(key, 6)
dummy_obs = utils.add_batch_dim(utils.zeros_like(spec.observations))
dummy_act = utils.add_batch_dim(utils.zeros_like(spec.actions))
encoder_params = networks.encoder_netw... |
def test_capture_serverless_elb(event_elb, context, elasticapm_client):
os.environ['AWS_LAMBDA_FUNCTION_NAME'] = 'test_func'
_serverless
def test_func(event, context):
with capture_span('test_span'):
time.sleep(0.01)
return {'statusCode': 200, 'headers': {'foo': 'bar'}}
test_... |
def _cmp_by_origin(path1, path2):
def get_origin_pref(origin):
if (origin.value == BGP_ATTR_ORIGIN_IGP):
return 3
elif (origin.value == BGP_ATTR_ORIGIN_EGP):
return 2
elif (origin.value == BGP_ATTR_ORIGIN_INCOMPLETE):
return 1
else:
LOG... |
def _generate_c_usage_code(processed_args):
lines = []
positionals = []
opts = []
for arg in processed_args:
if arg.is_positional():
positionals.append(arg)
else:
opts.append(arg)
lines.append('"\\n"')
lines.append('"USAGE:\\n\\n"')
line = 'program_nam... |
class HeadlessBrowser():
WEBDRIVER_TIMEOUT = 12
WEBDRIVER_ARGUMENTS = ('--disable-dev-shm-usage', '--ignore-certificate-errors', '--headless', '--incognito', '--no-sandbox', '--disable-gpu', '--disable-extensions', '--disk-cache-size=0', '--aggressive-cache-discard', '--disable-notifications', '--disable-remote... |
class SettingsDialog(QDialog):
def __init__(self, parent):
if (not parent):
parent = mw.app.activeWindow()
QDialog.__init__(self, parent)
self.parent = parent
self.setWindowTitle('SIAC Settings')
self.setup_ui()
self.exec_()
def setup_ui(self):
... |
def imdho_abs_cross_section(dEs_inc: np.ndarray, dE_exc: float, gamma: float, displs: np.ndarray, nus: np.ndarray, ithresh: float=1e-06):
integrand = get_crossec_integrand(dE_exc, gamma, displs, nus)
tmax = ((- np.log(ithresh)) / nu2angfreq_au(gamma))
print(f'tmax={tmax:.4f} au for ={gamma:.2f} cm1')
te... |
class TestDiscountCodeValidation(TestCase):
def test_quantity_pass(self):
schema = DiscountCodeSchemaTicket()
original_data = {'data': {}}
data = {'min_quantity': 10, 'max_quantity': 20, 'tickets_number': 30}
DiscountCodeSchemaTicket.validate_quantity(schema, data, original_data)
... |
def _export_interaction(contents: t.Any, extension: str) -> None:
path = interaction.get_save_filename_input('Filename to export as?', extension)
if path:
path = ((path + '.') + extension)
else:
interaction.show_message_box('Error', 'Did not get required path name for export.')
retur... |
def test_skip_bad_plugin(caplog, plugin_creator: PluginCreator) -> None:
caplog.set_level(logging.WARNING, logger='submitit')
plugin_creator.add_plugin('submitit_bad', entry_points='[submitit]\nexecutor = submitit_bad:NonExisitingExecutor\njob_environment = submitit_bad:BadEnvironment\nunsupported_key = submiti... |
def meatFunction(delay):
global HUNGER_UPDATE, meatApplied, money
if (money >= 15):
if (alive == True):
btnFeed.config(state='disabled')
money -= 15
meatApplied = True
_thread.start_new_thread(updateLabel, (3, (TAMA_NAME + ' is eating!')))
time... |
def gsm8k_samples():
return "\nQ: Every hour Joanne has to collect the coins out of the fountain inside the mall. During the first hour, she collected 15 coins. For the next two hours, she collected 35 coins from the fountain. In the fourth hour, she collected 50 coins from the fountain but she gave 15 of them to h... |
def test_Vector():
v = Vector((100, 200))
assert (repr(v) == 'Vector((100, 200))')
assert (v == Vector((100, 200)))
assert (v == Vector([100, 200]))
assert (v == (100, 200))
assert ((100, 200) == v)
assert (v == [100, 200])
assert ([100, 200] == v)
assert (v is Vector(v))
assert ... |
class CreditChargeResponseTests(unittest.TestCase):
def test_init(self):
response = CreditChargeResponse()
self.assertEqual(response.CCTransId, '')
self.assertEqual(response.AuthCode, '')
self.assertEqual(response.TxnAuthorizationTime, '')
self.assertEqual(response.Status, ''... |
class TestPropertyNotifications(unittest.TestCase):
def test_property_notifications(self):
output_buffer = io.StringIO()
test_obj = HasPropertySubclass(output_buffer=output_buffer)
test_obj.value = 'value_1'
self.assertEqual(output_buffer.getvalue(), 'value_1')
test_obj.value... |
class _ComplexNumPyEncoder(json.JSONEncoder):
def default(self, obj):
if np.iscomplexobj(obj):
obj = np.stack([np.asarray(obj).real, np.asarray(obj).imag])
if isinstance(obj, np.integer):
return int(obj)
if isinstance(obj, np.floating):
return float(obj)
... |
class TiktokenTokenizer():
def __init__(self, name) -> None:
self.enc = tiktoken.get_encoding(name)
self.encode = (lambda s: self.enc.encode(s, allowed_special={'<|endoftext|>'}))
self.pad_token = self.enc.eot_token
def __call__(self, text, max_length=None, padding=None, truncation=False... |
def main():
create_new_db(NEW_DB_URL)
old_connection = get_connection(OLD_DB_URL)
import timeit
start = timeit.default_timer()
move_rules(old_connection)
t1 = timeit.default_timer()
print(('Moving rules took %f seconds' % (t1 - start)))
move_function_calls(old_connection)
t2 = timeit... |
class CLICommand(RegionalCommand):
def regional_from_cli(cls, parser, argv, cfg):
parser.add_argument('--exclude-block', action='append', dest='exclude_blocks', default=cfg('exclude_block', type=List(IPNet), default=[]), help='exclude CIDR blocks from check')
args = parser.parse_args(argv)
r... |
class LogTarget():
def __init__(self):
self.fd = None
def write(self, data, level, logger, is_debug=0):
raise NotImplementedError('LogTarget.write is an abstract method')
def flush(self):
raise NotImplementedError('LogTarget.flush is an abstract method')
def close(self):
... |
class Migration(migrations.Migration):
dependencies = [('references', '0061_gtassf133balances_add_status_of_budgetary_resources_total_cpe_field')]
operations = [migrations.RemoveField(model_name='gtassf133balances', name='adjustments_to_unobligated_balance_cpe'), migrations.AddField(model_name='gtassf133balance... |
def search_albums(artist):
artist_id = [x for x in select([artists.c.id]).where((artists.c.nome == artist.lower())).execute()]
if artist_id:
query = select([discs.c.id, discs.c.album, discs.c.ano, discs.c.artista_id]).where((discs.c.artista_id == artist_id[0][0])).execute()
return {_id: {'album'... |
.parametrize('numGlyphs, indices, extra_indices, expected_data', [(5, TSI0_INDICES, TSI0_EXTRA_INDICES, TSI0_DATA), (0, [], EMPTY_TSI0_EXTRA_INDICES, EMPTY_TSI0_DATA)], ids=['simple', 'empty'])
def test_compile(table, numGlyphs, indices, extra_indices, expected_data):
assert (table.compile(ttFont=None) == b'')
... |
('xtb')
def test_opt_coord_type(this_dir):
(preopt_ct, tsopt_ct, endopt_ct) = ('dlc', 'redund', 'tric')
run_dict = {'geom': {'type': 'cart', 'fn': str((this_dir / 'test_geoms.trj'))}, 'calc': {'type': 'xtb', 'quiet': True, 'pal': 2}, 'preopt': {'geom': {'type': preopt_ct, 'freeze_atoms': [0]}, 'max_cycles': 1},... |
def extractCrazysilvermoonWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Number One Zombie Wife', 'Number One Zombie Wife', 'translated'), ('PRC', 'PRC', 'transla... |
def copy_database(raw_conn, from_database, to_database):
logger.debug('copy_database(%r, %r)', from_database, to_database)
terminate_database_connections(raw_conn, from_database)
if (raw_conn.engine.dialect.name == 'postgresql'):
raw_conn.execute(('\n CREATE DATABASE "%s" WITH TEMPLAT... |
.external
.skipif((has_openai_key is False), reason='OpenAI API key not available')
.parametrize('cfg_string', ['zeroshot_cfg_string', 'fewshot_cfg_string', 'ext_template_cfg_string'])
def test_summarization_config(cfg_string, request):
cfg_string = request.getfixturevalue(cfg_string)
orig_config = Config().fro... |
class DeclStatMixA(SimpleEntity, StatusMixin):
__tablename__ = 'DeclStatMixAs'
__mapper_args__ = {'polymorphic_identity': 'DeclStatMixA'}
declStatMixAs_id = Column('id', Integer, ForeignKey('SimpleEntities.id'), primary_key=True)
def __init__(self, **kwargs):
super(DeclStatMixA, self).__init__(*... |
class TestABC(unittest.TestCase):
def test_basic_abc(self):
self.assertRaises(TypeError, AbstractFoo)
concrete = ConcreteFoo()
self.assertEqual(concrete.foo(), 'foo')
self.assertEqual(concrete.bar, 'bar')
self.assertEqual(concrete.x, 10)
self.assertEqual(concrete.y, 2... |
def _get_region_data_sources(coordinates, points):
data_region = get_region(coordinates)
sources_region = get_region(points)
region = (min(data_region[0], sources_region[0]), max(data_region[1], sources_region[1]), min(data_region[2], sources_region[2]), max(data_region[3], sources_region[3]))
return re... |
def get_window_width():
try:
if (platform.system() in ['Linux', 'Darwin', 'Java']):
with os.popen('stty size', 'r') as size:
columns = size.read().split()[1]
return int(columns)
else:
return None
except Exception as exp:
return None |
def writehtmllist(space, namehead, hashtaghead):
spaces = ''
for _ in range(space):
spaces += ' '
if (initialspace >= 2):
return (spaces + f'<ul><li><a href="{hashtaghead}">{namehead}</a></li></ul>')
else:
return (spaces + f'<li><a href="{hashtaghead}">{namehead}</a></li>') |
class OptionSeriesBubbleSonificationContexttracksMappingNoteduration(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):
... |
(ITaskWindowBackend)
class MTaskWindowBackend(HasTraits):
control = DelegatesTo('window')
window = Instance('pyface.tasks.task_window.TaskWindow')
def create_contents(self, parent):
raise NotImplementedError()
def destroy(self):
pass
def hide_task(self, state):
raise NotImple... |
class SenseloafApi(ProviderInterface, OcrInterface):
provider_name = 'senseloaf'
def __init__(self, api_keys: Dict={}):
super().__init__()
self.api_settings = load_provider(ProviderDataEnum.KEY, self.provider_name, api_keys=api_keys)
self.client = Client(self.api_settings.get('api_key', ... |
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [migrations.CreateModel(name='Livro', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nome', models.CharField(max_length=30)), ('categoria', models.CharField(max_... |
class OpenEventTestCase(unittest.TestCase):
def setUpClass(cls) -> None:
cls.app = Setup.create_app()
def tearDownClass(cls) -> None:
Setup.drop_db()
def setUp(self):
with self.app.test_request_context():
self._connection = db.engine.connect()
self._transactio... |
def extract_kinetic_features(motion, thresholds, up_vec):
features = kinetic.KineticFeatures(motion, (1 / motion.fps), thresholds, up_vec)
kinetic_feature_vector = []
for i in range(motion.skel.num_joints()):
(positions_mean, positions_stddev) = features.local_position_stats(i)
feature_vecto... |
class OAuthCallbackHandler(BaseHTTPRequestHandler):
def do_GET(self):
split_url = urlsplit(self.path)
if (split_url.path == '/callback'):
parsed_url = parse_qs(split_url.query)
self.server.callback_code = parsed_url.get('code', [None])[0]
self.server.callback_stat... |
def example():
async def on_pan_update1(e: ft.DragUpdateEvent):
c.top = max(0, (c.top + e.delta_y))
c.left = max(0, (c.left + e.delta_x))
(await c.update_async())
async def on_pan_update2(e: ft.DragUpdateEvent):
e.control.top = max(0, (e.control.top + e.delta_y))
e.contro... |
class OptionSeriesLollipopDataAccessibility(Options):
def description(self):
return self._config_get(None)
def description(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag... |
.xfail(raises=ImageComparisonFailure, reason='Matplotlib plots for reasons a different image size.')
.skipif((LOW_MEMORY > memory), reason='Travis has too less memory to run it.')
def test_hicPlotMatrix_perChr_pca1_bigwig():
outfile = NamedTemporaryFile(suffix='.png', prefix='hicexplorer_test', delete=False)
ar... |
class QLineEditDrop(QtWidgets.QLineEdit):
def __init__(self):
super().__init__()
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def dropEvent(self, event):
files = [... |
class TestNumberOfOutRangeValues(BaseDataQualityValueRangeMetricsTest):
name: ClassVar = 'Number of Out-of-Range Values '
def calculate_value_for_test(self) -> Numeric:
return self.metric.get_result().current.number_not_in_range
def get_description(self, value: Numeric) -> str:
return f'The ... |
class GrowingNT():
logger = logging.getLogger('cos')
def __init__(self, geom, step_len=0.5, rms_thresh=0.0017, r=None, final_geom=None, between=None, bonds=None, r_update=True, r_update_thresh=1.0, stop_after_ts=False, require_imag_freq=0.0, hessian_at_ts=False, out_dir='.', dump=True):
assert (geom.coo... |
('/version', strict_slashes=False)
('/allure-docker-service/version', strict_slashes=False)
def version_endpoint():
try:
version = get_file_as_string(ALLURE_VERSION).strip()
except Exception as ex:
body = {'meta_data': {'message': str(ex)}}
resp = jsonify(body)
resp.status_code =... |
def test_correct_response(client, monkeypatch, elasticsearch_transaction_index, awards_and_transactions):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
resp = client.post('/api/v2/search/spending_by_category/naics', content_type='application/json', data=json.dumps({'filters': {'time_per... |
class FieldGrid(Tidy3dBaseModel):
x: Coords = pd.Field(..., title='X Positions', description='x,y,z coordinates of the locations of the x-component of a vector field.')
y: Coords = pd.Field(..., title='Y Positions', description='x,y,z coordinates of the locations of the y-component of a vector field.')
z: C... |
def create_system_image(image_file=None, upload_path=None, unique_identifier=None, ext='jpg'):
filename = f'{get_file_name()}.{ext}'
if image_file:
with urllib.request.urlopen(image_file) as img_data:
image_file = io.BytesIO(img_data.read())
else:
file_relative_path = 'static/def... |
class OptionPlotoptionsItemAccessibility(Options):
def description(self):
return self._config_get(None)
def description(self, text: str):
self._config(text, js_type=False)
def descriptionFormat(self):
return self._config_get(None)
def descriptionFormat(self, text: str):
s... |
(ACCESS_MANUAL_WEBHOOK, status_code=HTTP_200_OK, dependencies=[Security(verify_oauth_client, scopes=[WEBHOOK_CREATE_OR_UPDATE])], response_model=AccessManualWebhookResponse)
def patch_access_manual_webhook(connection_config: ConnectionConfig=Depends(_get_connection_config), *, db: Session=Depends(deps.get_db), request_... |
class BaseLoadAnalyzer(ABC):
def __init__(self, cloud_client: BaseCloudClient, input_batch_queue: InputBatchQueue, output_batch_queue: OutputBatchQueue, model_instances_storage: ModelInstancesStorage, config: dm.Config):
logger.info('Start load analyzer')
self.sleep_time = config.load_analyzer.sleep... |
class BuilderTests(unittest.TestCase):
def test_can_create_pypher(self):
p = Pypher()
self.assertIsInstance(p, Pypher)
def test_pypher_created_statements(self):
p = Pypher()
expected = []
for s in _PREDEFINED_STATEMENTS:
getattr(p, s[0])
try:
... |
def map_func(context):
java_file = JavaFile(context.from_java(), context.to_java())
try:
res = java_file.read(4)
(data_len,) = struct.unpack('<i', res)
print('res', type(data_len), data_len)
data = java_file.read(data_len)
print('data', str(data))
except Exception as ... |
class Formatter(object):
delimiter = '\n'
def __init__(self, max_width=None):
self.max_width = (get_terminal_width() if (max_width is None) else max_width)
self.wrapper = textwrap.TextWrapper()
self.lines = []
self._indent = 0
def append(self, line, indent=0):
if (not... |
.django_db
def test_federal_account_award_empty(client, monkeypatch, helpers, generic_account_data):
helpers.patch_datetime_now(monkeypatch, 2022, 12, 31)
resp = helpers.post_for_spending_endpoint(client, url, def_codes=['A'], spending_type='award')
assert (resp.status_code == status.HTTP_200_OK)
assert... |
class JSONWriter(GenericWriter):
def __init__(self, fo: AvroJSONEncoder, schema: Schema, codec: str='null', sync_interval: int=(1000 * SYNC_SIZE), metadata: Optional[Dict[(str, str)]]=None, validator: bool=False, sync_marker: bytes=b'', codec_compression_level: Optional[int]=None, options: Dict[(str, bool)]={}):
... |
class dual_gemm_rcr_fast_gelu(gemm_rcr):
def __init__(self):
super().__init__()
self._attrs['op'] = 'dual_gemm_rcr_fast_gelu'
self._attrs['epilogue2'] = 'LeftFastGeluAndMul'
def _infer_shapes(self, a: Tensor, b: Tensor, bias: Tensor):
return super()._infer_shapes(a, b)
def __... |
def test_deploy(BrownieTester, otherproject, accounts):
t = BrownieTester.deploy(True, {'from': accounts[0]})
assert (len(BrownieTester) == 1)
assert (len(otherproject.BrownieTester) == 0)
assert (t not in otherproject.BrownieTester)
t2 = otherproject.BrownieTester.deploy(True, {'from': accounts[0]}... |
_ns.route('/new/', methods=['GET', 'POST'])
_required
def api_new_token():
user = flask.g.user
copr64 = (base64.b64encode(b'copr') + b'##')
api_login = helpers.generate_api_token((flask.current_app.config['API_TOKEN_LENGTH'] - len(copr64)))
user.api_login = api_login
user.api_token = helpers.generat... |
def picker_callback(picker):
if (picker.actor in red_glyphs.actor.actors):
point_id = (picker.point_id // glyph_points.shape[0])
if (point_id != (- 1)):
(x, y, z) = (x1[point_id], y1[point_id], z1[point_id])
outline.bounds = ((x - 0.1), (x + 0.1), (y - 0.1), (y + 0.1), (z - 0... |
def test_options_database_cleared():
opts = PETSc.Options()
expect = len(opts.getAll())
mesh = UnitIntervalMesh(1)
V = FunctionSpace(mesh, 'DG', 0)
u = TrialFunction(V)
v = TestFunction(V)
A = assemble((inner(u, v) * dx))
b = assemble((conj(v) * dx))
u = Function(V)
solvers = []
... |
class PrivateComputationPIDOnlyTestStageFlow(PrivateComputationBaseStageFlow):
_order_ = 'CREATED PID_SHARD PID_PREPARE ID_MATCH ID_MATCH_POST_PROCESS'
CREATED = PrivateComputationStageFlowData(initialized_status=PrivateComputationInstanceStatus.CREATION_INITIALIZED, started_status=PrivateComputationInstanceSta... |
class OptionSeriesTreemapSonificationDefaultinstrumentoptionsActivewhen(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, nu... |
class PrivateComputationMRStageFlow(PrivateComputationBaseStageFlow):
_order_ = 'CREATED PC_PRE_VALIDATION UNION_PID_MR_MULTIKEY ID_SPINE_COMBINER RESHARD PCF2_ATTRIBUTION PCF2_AGGREGATION AGGREGATE POST_PROCESSING_HANDLERS'
CREATED = PrivateComputationStageFlowData(initialized_status=PrivateComputationInstance... |
_cli.command('up', short_help='Upgrades the database to the selected migration.')
('--revision', '-r', default='head', help='The migration to upgrade to.')
('--dry-run', default=False, is_flag=True, help='Only print SQL instructions, without actually applying the migration.')
_script_info
def migrations_up(info, revisi... |
.integration
.ledger
(scope='session')
_for_platform('Linux', skip=False)
def ganache(ganache_configuration, ganache_addr, ganache_port, timeout: float=2.0, max_attempts: int=10):
client = docker.from_env()
image = GanacheDockerImage(client, ' 8545, config=ganache_configuration)
(yield from _launch_image(im... |
def test_add_details_to_slack_alert():
block = SlackAlertMessageBuilder.create_divider_block()
message_builder = SlackAlertMessageBuilder()
message_builder.add_details_to_slack_alert()
assert (json.dumps(message_builder.slack_message, sort_keys=True) == json.dumps({'blocks': [], 'attachments': [{'blocks... |
class LoggerAcquireProgress(apt.progress.text.AcquireProgress):
def __init__(self, logger):
class FileLike():
def write(self, text):
text = text.strip()
if text:
logger.debug(text)
def flush(self):
pass
super... |
class open_raw_session_result():
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
def isUnion():
return False
def read(self, iprot):
if ((isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeader... |
class ProductFeed(AbstractCrudObject):
def __init__(self, fbid=None, parent_id=None, api=None):
self._isProductFeed = True
super(ProductFeed, self).__init__(fbid, parent_id, api)
class Field(AbstractObject.Field):
country = 'country'
created_time = 'created_time'
default_... |
def using(path, rem_on_start=True, rem_on_end=False):
if (rem_on_start and os.path.exists(path)):
if os.path.isdir(path):
shutil.rmtree(path)
elif os.path.isfile(path):
os.remove(path)
assert (not os.path.exists(path)), 'failed to remove: {_coconut_format_0}'.format(_... |
class OptionPlotoptionsHeatmapSonificationDefaultspeechoptionsPointgrouping(Options):
def algorithm(self):
return self._config_get('last')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bo... |
class OptionPlotoptionsWordcloudSonificationDefaultspeechoptionsActivewhen(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,... |
_os(*metadata.platforms)
def main():
common.log('WinRAR StartUp Folder Persistence')
win_rar_path = Path('WinRAR.exe').resolve()
ace_loader_path = Path('Ace32Loader.exe').resolve()
batch_file_path = '\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\mssconf.bat'
startup_path = (... |
class TestUtils():
def test_is_valid_attr_name(self):
assert is_valid_attr_name('_piZZa')
assert is_valid_attr_name('nice_pizza_with_2_mushrooms')
assert is_valid_attr_name('_2_pizze')
assert is_valid_attr_name('_')
assert is_valid_attr_name('___')
assert (not is_vali... |
class HistoryView(View):
_super_method
def post(self, request, **kwargs):
res = {'msg': '!', 'code': 412, 'self': None}
if (not request.user.is_superuser):
res['msg'] = ''
return JsonResponse(res)
data = request.data
form = HistoryForm(data)
if (no... |
def _get_normal_forms(form):
terms = [(~ z3_x[1].copy()), (((~ z3_x[1].copy()) | z3_x[2].copy()) & (z3_x[3].copy() | (~ z3_x[1].copy()))), ((((~ z3_x[1].copy()) | z3_x[2].copy()) & (z3_x[3].copy() | (~ z3_x[1].copy()))) & (z3_x[4].copy() | (z3_x[2].copy() & z3_x[3].copy()))), ((z3_x[2].copy() & (~ z3_x[1].copy())) ... |
def lazy_import():
from fastly.model.aws_region import AwsRegion
from fastly.model.logging_format_version_string import LoggingFormatVersionString
from fastly.model.logging_kinesis_additional import LoggingKinesisAdditional
from fastly.model.logging_placement import LoggingPlacement
from fastly.mode... |
def get_version():
current_dir = os.path.abspath(os.path.dirname(__file__))
version_file = os.path.join(current_dir, 'video_transformers', '__init__.py')
with io.open(version_file, encoding='utf-8') as f:
return re.search('^__version__ = [\\\'"]([^\\\'"]*)[\\\'"]', f.read(), re.M).group(1) |
class ExerciseInfo():
__init__ = _custom_dataclass_init
path: Path
slug: str
name: str
uuid: str
prerequisites: List[str]
type: str = 'practice'
status: ExerciseStatus = ExerciseStatus.Active
concepts: List[str] = None
difficulty: int = 1
topics: List[str] = None
practice... |
def extract_forkid(enr: ENRAPI) -> ForkID:
try:
eth_cap = enr[b'eth']
except KeyError:
raise ENRMissingForkID()
try:
[forkid] = rlp.sedes.List([ForkID]).deserialize(eth_cap)
return forkid
except rlp.exceptions.ListDeserializationError:
raise MalformedMessage('Unab... |
class GroupsScannerTest(ForsetiTestCase):
def setUp(self):
pass
def _render_ascii(self, starting_node, attr):
rows = []
for (pre, fill, node) in anytree.RenderTree(starting_node, style=anytree.AsciiStyle()):
value = getattr(node, attr, '')
if isinstance(value, (li... |
_toolkit([ToolkitName.qt, ToolkitName.wx])
class TestInstanceEditor(BaseTestMixin, unittest.TestCase):
def setUp(self):
BaseTestMixin.setUp(self)
def tearDown(self):
BaseTestMixin.tearDown(self)
def test_simple_editor(self):
obj = ObjectWithInstance()
tester = UITester()
... |
class Solaar(IntervalModule):
color = '#FFFFFF'
error_color = '#FF0000'
interval = 30
settings = (('nameOfDevice', "name of the logitech's unifying device"), ('color', 'standard color'), ('error_color', 'color to use when non zero exit code is returned'))
required = ('nameOfDevice',)
def findDev... |
class Ml_modelSerializer(serializers.ModelSerializer):
access = serializers.SerializerMethodField('_get_access')
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super().__init__(*args, **kwargs)
self.user = user
def _get_access(self, ml_model):
if Ml_model.obje... |
class Ml_modelsList(APIView):
permission_classes = [AUTH_METHOD]
def get(self, request, format=None):
ml_models = Ml_model.objects.filter(user_id=request.user.id)
serializer = ml_modelSerializer(ml_models, user=None, many=True)
return Response(serializer.data)
def post(self, request,... |
class ProjectTest(ForsetiTestCase):
def setUp(self):
self.org = Organization('', display_name='My org name')
self.folder = Folder('55555', display_name='My folder', parent=self.org)
self.project1 = Project('project-1', 11111, display_name='Project 1')
self.project2 = Project('project... |
def _get_leaves(session: Session, issue_instance_id: DBID, kind: SharedTextKind) -> Set[str]:
message_ids = [int(id) for (id,) in session.query(SharedText.id).distinct(SharedText.id).join(IssueInstanceSharedTextAssoc, (SharedText.id == IssueInstanceSharedTextAssoc.shared_text_id)).filter((IssueInstanceSharedTextAss... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.