code stringlengths 281 23.7M |
|---|
class TaskWindowLaunchGroup(Group):
id = 'TaskWindowLaunchGroup'
items = List
def _items_default(self):
manager = self
while isinstance(manager, Group):
manager = manager.parent
application = manager.controller.task.window.application
items = []
for factor... |
def version_list_normalize(vlist):
out_list = []
if (vlist.find(',') > 0):
vlist = vlist.split(',')
else:
vlist = vlist.split()
vlist.sort()
for ver in vlist:
try:
out_list.append(OFVersions.from_string(ver))
except KeyError:
sys.stderr.write((... |
def test_to_timedelta():
preprocessed_messages = 3600
expected = timedelta(seconds=3600)
processor = BuildTimedelta({'units': 'seconds'})
res = processor.process_arg(preprocessed_messages, None, {})
assert (res == expected)
preprocessed_messages = None
expected = None
processor = BuildTi... |
class meter_stats_reply(stats_reply):
version = 4
type = 19
stats_type = 9
def __init__(self, xid=None, flags=None, entries=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
else:
... |
def test_vom_manual_points_outside_domain():
for i in [0]:
parent_mesh = UnitSquareMesh(100, 100, quadrilateral=True)
points = [[0.1, 0.1], [0.2, 0.2], [1.1, 1.0]]
vom = True
with pytest.raises(VertexOnlyMeshMissingPointsError):
vom = VertexOnlyMesh(parent_mesh, points, missing_point... |
.parametrize('distance_matrix, expected_permutation, expected_distance', [(distance_matrix1, optimal_permutation1, optimal_distance1), (distance_matrix2, optimal_permutation2, optimal_distance2), (distance_matrix3, optimal_permutation3, optimal_distance3)])
def test_solution_is_optimal(distance_matrix, expected_permuta... |
class PairwiseBilinear(nn.Module):
def __init__(self, in_features: int, out_features: int, *, bias_u=True, bias_v=True):
super(PairwiseBilinear, self).__init__()
self.bias_u = bias_u
self.bias_v = bias_v
bias_u_dim = (1 if bias_u else 0)
bias_v_dim = (1 if bias_v else 0)
... |
def lsf_reader(filename: str) -> None:
tidy3d_file = 'import numpy as np\n'
tidy3d_file += 'import matplotlib.pyplot as plt\n'
tidy3d_file += 'import tidy3d as td\n'
tidy3d_file += 'import tidy3d.web as web\n'
tidy3d_file += '\n'
structures = '['
(rect, sph, cyl, polyslab) = (0, 0, 0, 0)
... |
.long_test
.download
def test_grib_index_eumetnet():
request = {'param': '2ti', 'date': '', 'step': ['0-24', '24-48', '48-72', '72-96', '96-120', '120-144', '144-168'], 'url': ' 'month': '12', 'year': '2017'}
PATTERN = '{url}data/fcs/efi/EU_forecast_efi_params_{year}-{month}_0.grb'
ds = load_source('indexed... |
class OptionSeriesBarSonificationContexttracksMappingTremoloDepth(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class Migration(migrations.Migration):
dependencies = [('core', '0001_initial')]
operations = [migrations.CreateModel(name='Todo', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('description', models.CharField(max_length=512)), ('done', models.Boolean... |
class PrintingOutputWriter():
def __init__(self, clear=False):
self.clear = clear
self.print_output = True
def add_decoder_state(*args, **kwargs):
pass
async def add_interpreter_head_state(self, variable, head, prompt, where, trace, is_valid, is_final, mask, num_tokens, program_varia... |
class MinorObjectClassFinancialSpendingViewSet(CachedDetailViewSet):
endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/financial_spending/object_class.md'
serializer_class = MinorObjectClassFinancialSpendingSerializer
def get_queryset(self):
json_request = self.request.query_params
... |
class PythonParser(BaseParser):
def parse(path: Path) -> List[str]:
try:
with tokenize.open(str(path)) as fd:
return fd.readlines()
except (SyntaxError, UnicodeError):
with open(str(path), encoding='utf8') as fd:
return fd.readlines() |
class TestHighlightLineAnchorsPymdownsTable(util.MdCase):
extension = ['pymdownx.highlight', 'pymdownx.superfences']
extension_configs = {'pymdownx.highlight': {'line_anchors': '__my_span', 'linenums_style': 'table'}}
def test_linespans(self):
self.check_markdown('\n ```python linenums="2... |
class FromReader(object):
def __init__(self, ffrom):
self._ffrom = BytesIO(file_read(ffrom))
def read(self, size=(- 1)):
return self._ffrom.read(size)
def seek(self, position, whence=os.SEEK_SET):
self._ffrom.seek(position, whence)
def _write_zeros_to_from(self, blocks, from_dict... |
def recite(start_verse, end_verse):
generated = [verse.strip().split('\n') for verse in verses(get_song())]
if (start_verse == end_verse):
return generated[(start_verse - 1)]
else:
result = []
for idx in range((start_verse - 1), end_verse):
result += (generated[idx] + [''... |
('Users > Get User Details for an Email Notification > Get User Details for an Email Notification')
def user_email_notification(transaction):
with stash['app'].app_context():
email_notification = EmailNotificationFactory()
db.session.add(email_notification)
db.session.commit() |
def extractTiredtranslationBlogspotCom(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... |
def main():
print('\nmodule top();\n (* KEEP, DONT_TOUCH *)\n LUT6 dummy();\n ')
site_to_cmt = dict(read_site_to_cmt())
luts = LutMaker()
wires = StringIO()
bufgs = StringIO()
clock_sources = ClockSources()
db = Database(util.get_db_root(), util.get_part())
grid = db.grid()
... |
def swap_partitioned_table_with_partitions(apps, _):
call_command('swap_in_new_table', '--table=transaction_search_fabs', '--keep-old-data')
call_command('swap_in_new_table', '--table=transaction_search_fpds', '--keep-old-data')
call_command('swap_in_new_table', '--table=transaction_search', '--keep-old-dat... |
def upgrade():
op.create_table('plus_custom_field_value_list', sa.Column('id', sa.String(length=255), nullable=False), sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=Tr... |
class OptionSeriesBarSonificationTracksActivewhen(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):
sel... |
def search_hnsw_minhash_jaccard_topk(index_data, query_data, index_params, k):
(index_sets, index_keys, index_minhashes, index_cache) = index_data
(query_sets, query_keys, query_minhashes) = query_data
num_perm = index_params['num_perm']
cache_key = json.dumps(index_params)
if (cache_key not in inde... |
class TestGetAccessManualWebhooks():
(scope='function')
def url(self, integration_manual_webhook_config) -> str:
return (V1_URL_PREFIX + ACCESS_MANUAL_WEBHOOKS)
def test_get_manual_webhook_not_authenticated(self, api_client: TestClient, url):
response = api_client.get(url, headers={})
... |
def test_dpa_update_accumulators():
traces = np.array([[0, 1, 2, 3], [1, 2, 3, 4], [4, 5, 6, 7], [2, 3, 4, 5], [3, 4, 5, 6]], dtype='uint8')
data = np.array([[1, 0], [0, 1], [1, 0], [1, 0], [0, 0]], dtype='uint8')
d = scared.DPADistinguisher()
d.update(traces, data)
assert ([3, 1] == d.processed_one... |
def _processDelayData(input_data, stats):
if (not isinstance(input_data, dict)):
return input_data
data = {}
for k in input_data:
d = input_data[k]
if (d is not None):
data[k] = copy.deepcopy(d)
if ('values' in d):
if ('summary' not in d):
... |
class OptionPlotoptionsBulletSonificationTracksMapping(Options):
def frequency(self) -> 'OptionPlotoptionsBulletSonificationTracksMappingFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsBulletSonificationTracksMappingFrequency)
def gapBetweenNotes(self) -> 'OptionPlotoptionsBulletS... |
class TestChangeEmailView(object):
def test_renders_get_okay(self, mocker):
form = self.produce_form()
handler = mocker.Mock(spec=ChangeSetHandler)
view = ChangeEmail(form=form, update_email_handler=handler)
view.get()
def test_update_user_email_successfully(self, user, mocker):
... |
class BaseEngine(ConfigurableWalker, ParserConfig):
def __init__(self, config=None):
ConfigurableWalker.__init__(self, config)
self.analytics = []
self.preprocessor = PreProcessor()
ParserConfig.__init__(self, preprocessor=self.preprocessor, schema=self._schema)
with self.sch... |
class AutoBackup(plugins.Plugin):
__author__ = '+.github.com'
__version__ = '1.0.0'
__license__ = 'GPL3'
__description__ = 'This plugin backups files when internet is available.'
def __init__(self):
self.ready = False
self.tries = 0
self.status = StatusFile('/root/.auto-backu... |
class HCSR04():
def __init__(self, device: SerialHandler, trig: str='SQ1', echo: str='LA1'):
self._device = device
self._la = LogicAnalyzer(self._device)
self._pwm = PWMGenerator(self._device)
self._trig = trig
self._echo = echo
self._measure_period = 0.06
sel... |
def require_exclusive_relationship(resource_list, data, optional=False):
present = False
multiple = False
for resource in resource_list:
if (resource in data):
if present:
multiple = True
present = True
if (multiple or (not (optional or present))):
... |
def test_open_yaml_as_json():
with tempfile.NamedTemporaryFile() as temp_json:
with open(temp_json.name, 'w') as temp_data:
temp_data.write(_TEST_YAML)
with pytest.raises(json.decoder.JSONDecodeError) as decode_error:
_ = file_ops.open_json(temp_json.name)
assert ('Ex... |
def parse(packet):
peer = packet.retrieve('peer')
rssi = packet.retrieve('rssi')
svc_data = packet.retrieve('Service Data uuid')
adv_payload = packet.retrieve('Adv Payload')
if (peer and rssi and svc_data and adv_payload):
mac = peer[0].val
uuid = svc_data[0].val
if (b'\x18\x... |
def check_ratelimit(response: Response) -> bool:
if (response.status_code == 429):
try:
time = int(response.headers['X-RateLimit-Reset'])
print(f'Ratelimit hit. Sleeping for {(time - int(pytime.time()))} seconds.')
sleep_until(time)
return False
except... |
class Migration(migrations.Migration):
dependencies = [('search', '0025_award_keys_upper_indexes')]
operations = [migrations.RunSQL(sql='\n ALTER TABLE rpt.award_search ALTER COLUMN generated_unique_award_id SET NOT NULL;\n CREATE UNIQUE INDEX as_idx_generated_unique_award_id_uq ON... |
class AMIEventTest(unittest.TestCase):
def test_dict(self):
keys = {'a': 1, 'b': 2}
event = ami.Event('TestEvent', dict(keys))
self.assertEqual(event['a'], 1)
self.assertEqual(event['b'], 2)
self.assertSetEqual(set(iter(keys)), set(iter(event)))
self.assertIn('a', eve... |
class ExceptHandler(excepthandler):
_fields = ('type', 'name', 'body')
_attributes = ('lineno', 'col_offset')
def __init__(self, type=None, name=None, body=[], lineno=0, col_offset=0, **ARGS):
excepthandler.__init__(self, **ARGS)
self.type = type
self.name = name
self.body = ... |
def get_executable_from_executable_config(executable_config: Config) -> Optional[str]:
if isinstance(executable_config, str):
return executable_config
if isinstance(executable_config, dict):
if ('path' in executable_config):
return executable_config['path']
if (('conda' in ex... |
class Solution():
def leastBricks(self, wall: List[List[int]]) -> int:
tr = {}
for row in wall:
s = 0
for e in row:
s += e
tr[s] = (tr.get(s, 0) + 1)
del tr[sum(wall[0])]
if (not tr):
return len(wall)
return ... |
def test_get(server):
url = str(server.url)
runner = CliRunner()
result = runner.invoke( [url])
assert (result.exit_code == 0)
assert (remove_date_header(splitlines(result.output)) == ['HTTP/1.1 200 OK', 'server: uvicorn', 'content-type: text/plain', 'Transfer-Encoding: chunked', '', 'Hello, world!'... |
def test_insert_aliased_variable_dominator_prev_block():
(list_instructions, aliased_variables, task) = construct_graph_aliased(3)
InsertMissingDefinitions().run(task)
assert ([node.instructions for node in task.graph.nodes] == [((([list_instructions[0], Assignment(aliased_variables[0], Variable('x', Intege... |
.skipcomplex
def test_firedrake_Adaptivity_netgen():
try:
from netgen.geom2d import SplineGeometry
import netgen
except ImportError:
pytest.skip(reason='Netgen unavailable, skipping Netgen test.')
try:
from slepc4py import SLEPc
except ImportError:
pytest.skip(rea... |
def get_announcement():
todays_date = str(datetime.today().strftime('%Y-%m-%d'))
file_name = (todays_date + '.json')
s3 = boto3.client('s3')
announcement_file_message = ''
try:
s3_file = s3.get_object(Bucket=os.environ['ANNOUNCEMENTS_BUCKET'], Key=file_name)
except Exception as e:
... |
class LayoutNumberLeaves(TreeLayout):
def __init__(self, name='Number of leaves', pos='branch_right', collapsed_only=True, formatter='(%s)', color='black', min_fsize=4, max_fsize=15, ftype='sans-serif', padding_x=5, padding_y=0):
super().__init__(name)
self.pos = pos
self.aligned_faces = (se... |
(image=cpu_image, secret=deepl_secret, shared_volumes={str(SHARED): volume}, cpu=1.1, memory=8000, timeout=(60 * 60))
def run(path_in: str, path_out: str, path_tmp: str, config: Config) -> Path:
logger.info(f'Processing {path_in} to {path_out} in {path_tmp}')
deepl_key = os.getenv('DEEPL_KEY', '')
path_audi... |
def oscilloscope(device, channels, duration):
headers = ['Timestamp', 'CH1', 'CH2', 'CH3', 'MIC'][:(1 + channels)]
timestamp = np.arange(0, (duration * 1000000.0), ((duration * 1000000.0) / SAMPLES))
data = ([np.random.random_sample(SAMPLES)] * channels)
return (headers, ([timestamp] + data)) |
class TestDataWrapper(TestCase):
def test_instantiate(self):
data_wrapper = DataWrapper()
self.assertEqual(data_wrapper.mimetypes(), set())
def test_mimedata_roundtrip(self):
data_wrapper = DataWrapper()
data_wrapper.set_mimedata('text/plain', b'hello world')
result = dat... |
class Reshape(Expression):
def __init__(self, t_colon):
super().__init__()
assert isinstance(t_colon, MATLAB_Token)
assert (t_colon.kind == 'COLON')
self.t_colon = t_colon
self.t_colon.set_ast(self)
def loc(self):
return self.t_colon.location
def set_parent(se... |
class TestUpgradeConnectionLocally(BaseTestCase):
ITEM_TYPE = 'connection'
ITEM_PUBLIC_ID = SOEF_PUBLIC_ID
LOCAL: List[str] = ['--local']
def setup(cls):
super(TestUpgradeConnectionLocally, cls).setup()
result = cls.runner.invoke(cli, ['-v', 'DEBUG', 'add', '--local', cls.ITEM_TYPE, str(... |
def setup_dropbox_loader(mocker):
mock_dropbox = mocker.patch('dropbox.Dropbox')
mock_dbx = mocker.MagicMock()
mock_dropbox.return_value = mock_dbx
os.environ['DROPBOX_ACCESS_TOKEN'] = 'test_token'
loader = DropboxLoader()
(yield (loader, mock_dbx))
if ('DROPBOX_ACCESS_TOKEN' in os.environ):... |
def test_composite_channel_arguments():
channel_name = 'default_channels'
with Image(filename='rose:') as img:
base = img.signature
left = base
right = base
with img.clone() as img1:
with Image(width=img.width, height=img.height, pseudo='gradient:') as mask:
... |
def get_gpus(num_gpu=1, worker_index=(- 1)):
try:
list_gpus = subprocess.check_output(['nvidia-smi', '--list-gpus']).decode()
logging.debug('all GPUs:\n{0}'.format(list_gpus))
gpus = [x for x in list_gpus.split('\n') if (len(x) > 0)]
except Exception as e:
gpus = []
retur... |
('/config')
def handle_config(self):
global TXBuffer, navMenuIndex
TXBuffer = ''
navMenuIndex = 1
if rpieGlobals.wifiSetup:
return self.redirect('/setup')
if (not isLoggedIn(self.get, self.cookie)):
return self.redirect('/login')
if (self.type == 'GET'):
responsearr = sel... |
class CummuNoiseEffTorch():
_grad()
def __init__(self, std, shapes, device, seed, test_mode=False):
seed = (seed if (seed is not None) else int.from_bytes(os.urandom(8), byteorder='big', signed=True))
self.test_mode = test_mode
self.std = std
self.shapes = shapes
self.dev... |
class TestPCF2LiftStageService(IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.mock_mpc_svc = MagicMock(spec=MPCService)
self.mock_mpc_svc.onedocker_svc = MagicMock()
self.run_id = '681ba82c-16d9-11ed-861d-0242ac120002'
onedocker_binary_config_map = defaultdict((lambda : OneD... |
class OptionSeriesXrangeOnpoint(Options):
def connectorOptions(self) -> 'OptionSeriesXrangeOnpointConnectoroptions':
return self._config_sub_data('connectorOptions', OptionSeriesXrangeOnpointConnectoroptions)
def id(self):
return self._config_get(None)
def id(self, text: str):
self._... |
class Image(_VirtModel, _JsonPickleModel, _OSType, _HVMType, _DcMixin, _UserTasksModel):
_MANIFEST_TEMPLATE = frozendict({u'v': 2, u'owner': u'-0000-0000-0000-', u'state': u'active', u'disabled': False, u'public': False})
OSTYPE2OS = frozendict({_OSType.LINUX: u'linux', _OSType.BSD: u'bsd', _OSType.WINDOWS: u'w... |
class BicincittaStation(BikeShareStation, BicincittaMixin):
station_statuses = {0: 'online', 1: 'maintenance', 2: 'offline', 3: 'under construction', 4: 'planned'}
def __init__(self, endpoint, uid, lat, lng, name, number, status, *_):
super(BicincittaStation, self).__init__()
self.endpoint = end... |
class TestFullTextModels():
def test_should_preload_models(self):
mock_models = {field.name: MagicMock(name=field.name) for field in dataclasses.fields(FullTextModels)}
mock_fulltext_models = FullTextModels(**mock_models)
mock_fulltext_models.preload()
for model in mock_models.values... |
class BertOutput(nn.Module):
def __init__(self, hidden_size, intermediate_size, layer_norm_eps, hidden_dropout_prob):
super().__init__()
assert (hidden_dropout_prob == 0.0)
self.dense = nn.Linear(intermediate_size, hidden_size, specialization='add')
self.dropout = nn.Dropout(hidden_d... |
class BaseSolver():
def __init__(self) -> None:
self.stateful = StateManager()
self.xp = get_xp()
self.register_stateful('history')
self.register_stateful('xp.cfg', 'xp.sig', write_only=True)
self.logger = logger
self.result_logger = ResultLogger(self.logger)
... |
def _gen_fusible_view_ops_after_strided_op() -> List[Tuple[(str, Callable[([Tensor], Tensor)], str)]]:
def reshape_op(input_tensor: Tensor):
shape = input_tensor._attrs['shape']
return ops.reshape()(input_tensor, [(- 1), (shape[1].value() * shape[2].value())])
def flatten_op(input_tensor: Tensor... |
_defaults()
class TaxSchemaPublic(SoftDeletionSchema):
class Meta():
type_ = 'tax'
self_view = 'v1.tax_detail'
self_view_kwargs = {'id': '<id>'}
inflect = dasherize
id = fields.Str(dump_only=True)
name = fields.Str(allow_none=True, default='')
rate = fields.Float(validate... |
class JsMedia(JsHtml):
def start(self):
return ('\nvar mediaConfig = { video: true };\nif(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {\n navigator.mediaDevices.getUserMedia(mediaConfig).then(function(stream) {\n%(varId)s.srcObject = stream; %(varId)s.play();});}\nelse if(navigator.ge... |
class DeclProjMixA(SimpleEntity, ProjectMixin):
__tablename__ = 'DeclProjMixAs'
__mapper_args__ = {'polymorphic_identity': 'DeclProjMixA'}
a_id = Column('id', Integer, ForeignKey('SimpleEntities.id'), primary_key=True)
def __init__(self, **kwargs):
super(DeclProjMixA, self).__init__(**kwargs)
... |
def download_pdf(link, location, name):
try:
response = requests.get(link)
with open(os.path.join(location, name), 'wb') as f:
f.write(response.content)
f.close()
except HTTPError:
print('>>> Error 404: cannot be downloaded!\n')
raise
except socket.tim... |
class layernorm_sigmoid_mul(Operator):
def __init__(self, layer_norm: Operator, sigmoid: Operator, mul: Operator) -> None:
super().__init__()
self._attrs['op'] = 'layernorm_sigmoid_mul'
self._attrs['has_profiler'] = False
assert layernorm_sigmoid_mul.is_valid(layer_norm, sigmoid, mul... |
def sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, *varBinds, **options):
def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx):
(lookupMib, future) = cbCtx
if future.cancelled():
return
try:
... |
def test_switch_branches():
asgraph = AbstractSyntaxInterface()
code_node_1 = asgraph._add_code_node([Assignment(var('e'), const(9))])
code_node_2 = asgraph._add_code_node([Assignment(var('d'), const(9))])
condition = asgraph._add_condition_node_with(LogicCondition.initialize_symbol('a', asgraph.factory... |
_data_source('homography')
class HomographyDataSource(DataSource):
def __init__(self, root: Path, image_hw: Tuple[(int, int)], subpath: str):
super().__init__(root, image_hw)
(self.homography, self.homography_size, self.homography_bounds) = self.load_homography((root / subpath))
def __len__(self... |
def get_RS_and_optimization_config(enable_filtering, enable_optimization):
(time_alignment_config, hand_eye_config) = get_RANSAC_scalar_part_inliers_config(enable_filtering)
optimiztion_config = OptimizationConfig()
optimiztion_config.enable_optimization = enable_optimization
optimiztion_config.optimiza... |
def main(arg, av):
if arg.filename:
fname = arg.filename
elif av:
fname = av.pop(0)
raw_dat = load_cmd_data(fname)
if arg.seek:
raw_dat = raw_dat[:arg.seek]
a_dat = list(map(abs, raw_dat))
max_pause = (int(statistics.stdev(a_dat)) * 2)
max_pause = (arg.preamble or max... |
.parametrize('current_data, reference_data, metric, expected_result', ((pd.DataFrame({'col': []}), None, ColumnValueRangeMetric(column_name='col', left=0, right=10.3), ColumnValueRangeMetricResult(column_name='col', left=0, right=10.3, current=ValuesInRangeStat(number_in_range=0, number_not_in_range=0, share_in_range=0... |
def test_query_more_multibatch_negative():
testutil.add_response('login_response_200')
testutil.add_response('query_more_multibatch_0_200')
testutil.add_response('query_more_multibatch_1_no_body')
testutil.add_response('api_version_response_200')
client = testutil.get_client()
query_result = cli... |
class YaraGenerator(object):
def __init__(self, sig_mode, instruction_set, instruction_mode, rule_name='generated_rule', do_comment=True):
self.instruction_set = instruction_set
self.instruction_mode = instruction_mode
self.do_comment_sig = do_comment
self.sig_mode = sig_mode
... |
class OptionSeriesGaugeSonificationDefaultinstrumentoptionsMappingTremolo(Options):
def depth(self) -> 'OptionSeriesGaugeSonificationDefaultinstrumentoptionsMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesGaugeSonificationDefaultinstrumentoptionsMappingTremoloDepth)
def speed(sel... |
def load_het_snps(vcf_fname, sample_id=None, normal_id=None, min_variant_depth=20, zygosity_freq=None, tumor_boost=False):
if (vcf_fname is None):
return None
varr = tabio.read(vcf_fname, 'vcf', sample_id=sample_id, normal_id=normal_id, min_depth=min_variant_depth, skip_somatic=True)
if ((zygosity_f... |
class LEAFDataLoader(IFLDataLoader):
SEED = 2137
random.seed(SEED)
def __init__(self, train_dataset: Dataset, eval_dataset: Dataset, test_dataset: Dataset, batch_size: int, drop_last: bool=False):
self.train_dataset = train_dataset
self.eval_dataset = eval_dataset
self.test_dataset =... |
class LoggingMiddleware(MiddlewareMixin):
server_logger = logging.getLogger('server')
start = None
log = None
def process_request(self, request):
self.start = time.perf_counter()
self.log = {'path': request.path, 'remote_addr': get_remote_addr(request), 'host': request.get_host(), 'metho... |
def _get_page(session, js_assets, css_assets, link, export):
pre_path = ('flexx/assets' if export else '/flexx/assets')
codes = []
for assets in [css_assets, js_assets]:
for asset in assets:
if (link in (0, 1)):
html = asset.to_html('{}', link)
elif asset.name... |
def get_snowflake_schemas(engine: Engine) -> Dict[(str, Dict[(str, List[str])])]:
schema_cursor = engine.execute(text('SHOW SCHEMAS'))
db_schemas = [row[1] for row in schema_cursor]
metadata: Dict[(str, Dict[(str, List)])] = {}
for schema in db_schemas:
if include_dataset_schema(schema=schema, d... |
class FusedType():
def is_fused_type(self):
raise NotImplementedError
def get_all_formatted_backend_types(self, type_formatter):
template_params = self.get_template_parameters()
values_template_parameters = {param.__name__: param.values for param in template_params}
names = tuple... |
def save_settings(path, settings):
LOG.debug('Saving settings')
with open(path, 'w') as f:
print('# This file is automatically generated', file=f)
print(file=f)
for (k, v) in sorted(settings.items()):
h = SETTINGS_AND_HELP.get(k)
if h:
print(file=f... |
def test_subset_COLRv1_downgrade_version(colrv1_path):
subset_path = (colrv1_path.parent / (colrv1_path.name + '.subset'))
subset.main([str(colrv1_path), '--glyph-names', f'--output-file={subset_path}', '--unicodes=E004'])
subset_font = TTFont(subset_path)
assert (set(subset_font.getGlyphOrder()) == {'.... |
class TestAPIBNFCodeViews(ApiTestBase):
api_prefix = '/api/1.0'
def assertNotJson(self, content):
try:
json.loads(content)
raise AssertionError(('Expected %s... to be non-JSON' % content[:10]))
except ValueError:
pass
def assertJson(self, content):
... |
def load(project_path: Union[(Path, str, None)]=None, name: Optional[str]=None, raise_if_loaded: bool=True) -> 'Project':
if (project_path is None):
project_path = check_for_project('.')
if ((project_path is not None) and (project_path != Path('.').absolute())):
warnings.warn(f"Loaded pr... |
class OptionSeriesColumnpyramidSonificationContexttracksMappingTremoloSpeed(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: st... |
def test_serialization_negative():
currency_change = {'FET': 10}
good_change = {'a_good': 1}
msg = StateUpdateMessage(performative=StateUpdateMessage.Performative.APPLY, amount_by_currency_id=currency_change, quantities_by_good_id=good_change)
with patch.object(StateUpdateMessage.Performative, '__eq__',... |
def validate_directory(path, checkmodes):
if (not (type(path) == str)):
logging.debug('got path which is not a string. Exiting..')
sys.exit('Function validate_directory got path which is not a string.')
if (not os.path.isdir(path)):
logging.debug(('Returning false in validate_directory/o... |
class _IndexedCustomCheckListEditor(BaseSourceWithLocation):
source_class = CustomEditor
locator_class = Index
handlers = [(MouseClick, (lambda wrapper, _: _interaction_helpers.mouse_click_checkbox_child_in_panel(control=wrapper._target.source.control, index=convert_index(source=wrapper._target.source, inde... |
class OptionSeriesStreamgraphDatalabelsTextpath(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def enabled(self):
return self._config_get(False)
def enabled(self, flag: bool):
self._config... |
(image=cpu_image, shared_volumes={str(SHARED): volume}, timeout=(30 * 60))
def main(storage: str, language: str='', video: bytes=b'', suffix: str='.mp4') -> bytes:
with tempfile.TemporaryDirectory(dir=storage) as tmp:
dirpath = Path(tmp)
lang = check_language(language)
config = Config(target... |
def multiplex_for_tensor_fields(func):
def inner(self, field):
if field.is_scalar_field:
return func(self, field)
else:
f = field.reshape(((- 1), field.grid.size))
res = [func(self, ff) for ff in f]
new_shape = np.concatenate((field.tensor_shape, [(- 1... |
class ColumnApi():
def __init__(self, page: primitives.PageModel, js_code: str):
self.varId = js_code
self.page = page
def sizeColumnsToFit(self, width):
return JsObjects.JsVoid(('%s.sizeColumnsToFit(%s)' % (self.varId, JsUtils.jsConvertData(width, None))))
def getColumnGroup(self, n... |
def CreateManifest(manifest_path, classpath, main_class=None, manifest_entries=None):
output = ['Manifest-Version: 1.0']
if main_class:
output.append(('Main-Class: %s' % main_class))
if manifest_entries:
for (k, v) in manifest_entries:
output.append(('%s: %s' % (k, v)))
if cl... |
def test_tensorflow_task_with_custom_config(serialization_settings: SerializationSettings):
task_config = TfJob(chief=Chief(replicas=1, requests=Resources(cpu='1'), limits=Resources(cpu='2'), image='chief:latest'), worker=Worker(replicas=5, requests=Resources(cpu='2', mem='2Gi'), limits=Resources(cpu='4', mem='2Gi'... |
class _InterEventIntervallLog():
def __init__(self):
self.clear()
def clear(self):
self.log_dict = {}
def add_event(self, event_tag, time):
try:
self.log_dict[event_tag].append(time)
except Exception:
self.log_dict[event_tag] = [time]
def _get_iei_... |
class RangeStringArgument(ArgumentDefinition):
NOT_A_VALID_RANGE_STRING = 'The input should be of the type: <b><pre>\n\t1,3-5,9,17\n</pre></b>i.e. integer values separated by commas, and dashes to represent ranges.'
VALUE_NOT_IN_RANGE = 'A value must be in the range from 0 to %d.'
def __init__(self, max_val... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.