code stringlengths 281 23.7M |
|---|
.usefixtures('use_tmpdir')
def test_load_forward_model_missing_raises():
with open('CONFIG', 'w', encoding='utf-8') as f:
f.write('EXECUTABLE missing_script.sh\n')
with pytest.raises(ConfigValidationError, match='Could not find executable'):
_ = ForwardModel.from_config_file('CONFIG') |
(scope='module')
def df():
(X, y) = make_classification(n_samples=1000, n_features=6, n_redundant=2, n_clusters_per_class=1, weights=[0.5], class_sep=2, random_state=1)
colnames = [('var_' + str(i)) for i in range(6)]
X = pd.DataFrame(X, columns=colnames)
X['cat_1'] = (['A', 'B'] * int((X.shape[0] / 2))... |
_renderer(wrap_type=ConflictTargetMetric)
class ConflictTargetMetricRenderer(MetricRenderer):
def render_html(self, obj: ConflictTargetMetric) -> List[BaseWidgetInfo]:
metric_result = obj.get_result()
counters = [CounterData('number of conflicts (current)', self._get_string(metric_result.number_not_... |
def main(server, username, infile, infotype):
password = getpass.getpass()
sessionkey = auth(server, username, password)
n = 0
for line in file(infile):
n += 1
(timestamp, track, artist, album, trackmbid, artistmbid, albummbid) = line.strip('\n').split('\t')
if submit(server, inf... |
class Migration(migrations.Migration):
dependencies = [('awards', '0088_drop_old_defc_field'), ('financial_activities', '0007_drop_old_defc_field'), ('references', '0056_use_new_defc_text_field')]
operations = [migrations.RemoveField(model_name='gtassf133balances', name='disaster_emergency_fund'), migrations.Re... |
class TableManager(Service, TableManagerT):
_channels: MutableMapping[(CollectionT, ChannelT)]
_changelogs: MutableMapping[(str, CollectionT)]
_tables_finalized: asyncio.Event
_tables_registed: asyncio.Event
_recovery_started: asyncio.Event
_changelog_queue: Optional[ThrowableQueue]
_pending... |
class TestNull(util.ColorAsserts, unittest.TestCase):
def test_null_input(self):
c = Color('cubehelix', [NaN, 0.5, 1], 1)
self.assertTrue(c.is_nan('hue'))
def test_none_input(self):
c = Color('color(--cubehelix none 0% 75% / 1)')
self.assertTrue(c.is_nan('hue'))
def test_null... |
class OracleInterface(SqlInterfaceCursor):
target = oracle
id_type_decl = 'NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY'
def __init__(self, host, port, database, user, password, print_sql=False):
self._print_sql = print_sql
self.args = dict(dsn=(('%s/%s' % (host, database)) if database el... |
def retryable(which_block_arg_name: str) -> Func:
def make_meth_retryable(meth: Meth) -> Meth:
sig = inspect.signature(meth)
if (which_block_arg_name not in sig.parameters):
raise Exception(f'"{which_block_arg_name}" does not name an argument to this function')
setattr(meth, RETR... |
class DE94(DeltaE):
NAME = '94'
def __init__(self, kl: float=1, k1: float=0.045, k2: float=0.015):
self.kl = kl
self.k1 = k1
self.k2 = k2
def distance(self, color: 'Color', sample: 'Color', kl: Optional[float]=None, k1: Optional[float]=None, k2: Optional[float]=None, **kwargs: Any) -... |
def rem_and_collect_indents(inputstr):
(non_indent_chars, change_in_level) = rem_and_count_indents(inputstr)
if (change_in_level == 0):
indents = ''
elif (change_in_level < 0):
indents = (closeindent * (- change_in_level))
else:
indents = (openindent * change_in_level)
return... |
def test_advanced_package_override_simple(tmpdir: Path) -> None:
cmd = ['examples/advanced/package_overrides/simple.py', ('hydra.run.dir=' + str(tmpdir)), 'hydra.job.chdir=True']
(result, _err) = run_python_script(cmd)
assert (OmegaConf.create(result) == {'db': {'driver': 'mysql', 'user': 'omry', 'pass': 's... |
class OptionPlotoptionsSankeyLevelsDatalabelsTextpath(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._... |
def _stimulus_timing(exp):
def _test1():
info = 'This will test the visual stimulus presentation timing specifics of your system.\nDuring the test, you will see two squares on the screen.\nAfter the test, you will be asked to indicate which (if any) of those two squares were flickering.\n\n[Press RETURN to ... |
def test_create_plan_start_model_upstream_and_downstream():
parsed = Namespace(select=['+modelA+'])
graph = _create_test_graph()
execution_plan = ExecutionPlan.create_plan_from_graph(parsed, graph, MagicMock(project_name=PROJECT_NAME))
assert_contains_only(execution_plan.before_scripts, ['script.model.B... |
def _parse(mod, buf, offset):
(oxx_type_num, total_hdr_len, hasmask, value_len, field_len) = _parse_header_impl(mod, buf, offset)
value_offset = (offset + total_hdr_len)
value_pack_str = ('!%ds' % value_len)
assert (struct.calcsize(value_pack_str) == value_len)
(value,) = struct.unpack_from(value_pa... |
def set_observation_idx(doc):
if doc.parent_observation:
parent_template = frappe.db.get_value('Observation', doc.parent_observation, 'observation_template')
idx = frappe.db.get_value('Observation Component', {'parent': parent_template, 'observation_template': doc.observation_template}, 'idx')
... |
class ElasticsearchDisasterBase(DisasterBase):
query_fields: List[str]
agg_key: str
agg_group_name: str = 'group_by_agg_key'
sub_agg_key: str = None
sub_agg_group_name: str = 'sub_group_by_sub_agg_key'
filter_query: ES_Q
bucket_count: int
pagination: Pagination
sort_column_mapping: D... |
def apply_png_predictor(pred, colors, columns, bitspercomponent, data):
if (bitspercomponent != 8):
raise ValueError(("Unsupported `bitspercomponent': %d" % bitspercomponent))
nbytes = (((colors * columns) * bitspercomponent) // 8)
i = 0
buf = b''
line0 = (b'\x00' * columns)
for i in ran... |
_type(ofproto.OFPTFPT_NEXT_TABLES)
_type(ofproto.OFPTFPT_NEXT_TABLES_MISS)
_type(ofproto.OFPTFPT_TABLE_SYNC_FROM)
class OFPTableFeaturePropNextTables(OFPTableFeatureProp):
_TABLE_ID_PACK_STR = '!B'
def __init__(self, type_=None, length=None, table_ids=None):
table_ids = (table_ids if table_ids else [])
... |
class OptionSeriesWindbarbSonificationContexttracksMappingHighpassFrequency(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... |
.parametrize('contents, expected_errors', [(dedent('\n QUEUE_OPTION DOCAL MAX_RUNNING 4\n STOP_LONG_RUNNING flase 0 1\n NUM_REALIZATIONS not_int\n ENKF_ALPHA not_float\n RUN_TEMPLATE dsajldkald/sdjkahsjka/wqehwqhdsa\n JOB_SCRIPT d... |
class ToolBarManager(pyface.ToolBarManager):
window = Instance('pyface.workbench.api.WorkbenchWindow')
def create_tool_bar(self, parent, controller=None, **kwargs):
if (controller is None):
controller = ActionController(window=self.window)
tool_bar = super().create_tool_bar(parent, c... |
def test_config_file_dir_parsing_options():
(server, r) = unittest_server_init()
assert (server.source_dirs == {'pp/**', 'subdir'})
assert (server.incl_suffixes == {'.FF', '.fpc', '.h', 'f20'})
assert (server.excl_suffixes == {'_tmp.f90', '_h5hut_tests.F90'})
assert (server.excl_paths == {'excldir',... |
def _diff(trivial_changes: List[Tuple[(str, str, re.RegexFlag)]], ignore_in_name: List[str], old_path: str, new_path: str, diff_path: str, input_path: str, output_path: str, diff_index_path: str, pickles_len: int, count: int, pickle_path: str) -> None:
old_pickle_path = os.path.join(old_path, pickle_path)
new_p... |
def render_query(query, engine_type, config=None):
metadata = {}
if (not isinstance(query, PipedQuery)):
metadata['_source'] = query
query = parse_query(query)
analytic = EqlAnalytic(query=query, metadata=metadata)
rendered = render_analytic(analytic, engine_type=engine_type, config=conf... |
class OptionPlotoptionsTreegraphMarker(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_... |
def find_object_given_state(needle, haystack, object):
if (needle is haystack):
return object
if hasattr(object, 'filter'):
return find_object_given_state(needle, haystack.filter, object.filter)
elif hasattr(object, 'filters'):
for (h, obj) in zip(haystack.filters, object.filters):
... |
class TestPriceList(unittest.TestCase):
def test_price_list(self):
price_list = PriceList(logging.Logger('test'))
price_list.append(zoneKey=ZoneKey('AT'), datetime=datetime(2023, 1, 1, tzinfo=timezone.utc), price=1, source='trust.me', currency='EUR')
assert (len(price_list.events) == 1)
... |
def extractLangyanirvanaWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if (item['title'].startswith('Chapter ') and (item['tags'] == ['Uncategorized'])):
return build... |
class Ui_DumpSoDialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName('Dialog')
Dialog.resize(372, 316)
self.gridLayout_3 = QtWidgets.QGridLayout(Dialog)
self.gridLayout_3.setObjectName('gridLayout_3')
self.groupBox = QtWidgets.QGroupBox(Dialog)
self.groupBox... |
class Container(containers.DeclarativeContainer):
wiring_config = containers.WiringConfiguration(modules=['.endpoints'])
config = providers.Configuration(yaml_files=['config.yml'])
db = providers.Singleton(Database, db_url=config.db.url)
user_repository = providers.Factory(UserRepository, session_factor... |
class OptionSeriesGaugeAccessibilityPoint(Options):
def dateFormat(self):
return self._config_get(None)
def dateFormat(self, text: str):
self._config(text, js_type=False)
def dateFormatter(self):
return self._config_get(None)
def dateFormatter(self, value: Any):
self._con... |
def test_transaction_cost_valid(london_plus_miner, funded_address, funded_address_private_key):
chain = london_plus_miner
vm = chain.get_vm()
base_fee_per_gas = vm.get_header().base_fee_per_gas
assert (base_fee_per_gas > 0)
account_balance = vm.state.get_balance(funded_address)
tx = new_dynamic_... |
class TestLang(util.TestCase):
MARKUP = '\n <div lang="de-DE">\n <p id="1"></p>\n </div>\n <div lang="de-DE-1996">\n <p id="2"></p>\n </div>\n <div lang="de-Latn-DE">\n <p id="3"></p>\n </div>\n <div lang="de-Latf-DE">\n <p id="4"></p>\n </div>\n <div lang="de-... |
class KeyboardControlsTester(flx.Widget):
def init(self):
combo_options = ['Paris', 'New York', 'Enschede', 'Tokio']
with flx.HBox():
self.tree = TreeWithControls(flex=1, max_selected=1)
with flx.VBox(flex=1):
self.combo = flx.ComboBox(options=combo_options, e... |
def test_missing_units(tmpdir):
fname = os.path.join(TEST_DATA_DIR, 'icgem-sample.gdf')
corrupt = str(tmpdir.join('missing_units.gdf'))
with open(fname) as gdf_file, open(corrupt, 'w') as corrupt_gdf:
for line in gdf_file:
if ('[mgal]' in line):
continue
corru... |
class LevelModel(proteus.Transport.OneLevelTransport):
nCalls = 0
def __init__(self, uDict, phiDict, testSpaceDict, matType, dofBoundaryConditionsDict, dofBoundaryConditionsSetterDict, coefficients, elementQuadrature, elementBoundaryQuadrature, fluxBoundaryConditionsDict=None, advectiveFluxBoundaryConditionsSet... |
def test_value():
enum = EnumValue(value=5)
assert (enum.value == 5)
enum = EnumValue(value='0x5')
assert (enum.value == 5)
enum.value = 3
assert (enum.value == 3)
enum.value = '0x6'
assert (enum.value == 6)
with pytest.raises(ValueError):
enum.value = 'zz'
enum.value = (... |
def _save_item_locally(ctx: Context, item_type: str, item_id: PublicId) -> None:
item_type_plural = (item_type + 's')
try:
source_path = try_get_item_source_path(ctx.cwd, None, item_type_plural, item_id.name)
except ClickException:
source_path = try_get_item_source_path(os.path.join(ctx.cwd,... |
class KMSRuleBook(bre.BaseRuleBook):
supported_resource_types = frozenset(['organization'])
def __init__(self, rule_defs=None):
super(KMSRuleBook, self).__init__()
self._lock = threading.Lock()
self.resource_rules_map = {}
if (not rule_defs):
self.rule_defs = {}
... |
def cone_actor(center=(0, 0, 0), height=1.0, radius=0.5, direction=(1, 0, 0), resolution=100, color=colors.red, opacity=1.0):
source = tvtk.ConeSource(center=center, height=height, radius=radius, direction=direction, resolution=resolution)
mapper = tvtk.PolyDataMapper()
configure_input_data(mapper, source.o... |
class FaucetDelPortTest(FaucetConfigReloadTestBase):
CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "untagged"\n 200:\n description: "untagged"\n'
CONFIG = '\n interfaces:\n %(port_1)d:\n native_vlan: 100\n acl_in: allow\n %(port_2)... |
def extractLalalylyWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
titlemap = [('[CEO] Chapter', 'CEO Above, Me Below', 'translated')]
for (titlecomponent, name, tl_type) ... |
class DashboardPanelCounter(DashboardPanel):
agg: CounterAgg
value: Optional[PanelValue] = None
text: Optional[str] = None
_panel_id
def build(self, data_storage: 'DataStorage', project_id: ProjectID, timestamp_start: Optional[datetime.datetime], timestamp_end: Optional[datetime.datetime]):
... |
class BroadcastingContainer():
def __init__(self):
self._policy_version_counter = 0
self._pickled_policy_state_dict = None
self._stop_flag = False
self._aux_data = None
def stop_flag(self) -> bool:
return self._stop_flag
def set_stop_flag(self) -> NoReturn:
se... |
class CloudWatchLogService(LogService):
def __init__(self, log_group: str, region: str='us-west-1', access_key_id: Optional[str]=None, access_key_data: Optional[str]=None, config: Optional[Dict[(str, Any)]]=None) -> None:
self.cloudwatch_gateway = CloudWatchGateway(region, access_key_id, access_key_data, co... |
_meter_band_type(ofproto.OFPMBT_DSCP_REMARK, ofproto.OFP_METER_BAND_DSCP_REMARK_SIZE)
class OFPMeterBandDscpRemark(OFPMeterBandHeader):
def __init__(self, rate=0, burst_size=0, prec_level=0, type_=None, len_=None):
super(OFPMeterBandDscpRemark, self).__init__()
self.rate = rate
self.burst_si... |
class ChainedTransforms(TestCase, Common, Edges):
def setUp(self):
super().setUp()
self.seq = nutils.transformseq.ChainedTransforms((nutils.transformseq.PlainTransforms(((x1, i10), (x1, i11)), 1, 1), nutils.transformseq.PlainTransforms(((x1, i12), (x1, i13)), 1, 1)))
self.check = ((x1, i10),... |
class OptionPlotoptionsVennSonificationTracksMappingHighpassResonance(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 Select(Block):
def __init__(self, file_ast: FortranAST, line_number: int, name: str, select_info):
super().__init__(file_ast, line_number, name)
self.select_type = select_info.type
self.binding_name = None
self.bound_var = None
self.binding_type = None
if (self.... |
def get_snapshot(client, repository=None, snapshot=''):
if (not repository):
raise MissingArgument('No value for "repository" provided')
snapname = ('*' if (snapshot == '') else snapshot)
try:
return client.snapshot.get(repository=repository, snapshot=snapshot)
except (es8exc.TransportEr... |
class OptionSeriesAreaMarkerStatesSelect(Options):
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def fillColor(self):
return self._config_get('#cccccc')
def fillColor(self, text: str):
self._config(text, ... |
def test_extract_features_from_different_timezones():
df = pd.DataFrame()
df['time'] = pd.concat([pd.Series(pd.date_range(start='2014-08-01 09:00', freq='H', periods=3, tz='Europe/Berlin')), pd.Series(pd.date_range(start='2014-08-01 09:00', freq='H', periods=3, tz='US/Central'))], axis=0)
df.reset_index(inp... |
class OptionSeriesPackedbubbleSonificationContexttracks(Options):
def activeWhen(self) -> 'OptionSeriesPackedbubbleSonificationContexttracksActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesPackedbubbleSonificationContexttracksActivewhen)
def instrument(self):
return self._conf... |
class OptionTitle(Options):
def align(self):
return self._config_get()
def align(self, position: str):
self._config(position)
def floating(self):
return self._config_get()
def floating(self, flag: bool):
self._config(flag)
def text(self):
return self._config_g... |
def prune(path, days, dry_run=False, stdout=False):
path = os.path.normpath(path)
too_old = (datetime.now() - timedelta(days=days))
for (root, subdirs, files) in walk_limited(path, mindepth=3, maxdepth=3):
parsed = os.path.normpath(root).split(os.sep)
if (parsed[(- 1)] != 'srpm-builds'):
... |
def get_options(option_type, from_options):
_options = dict()
for key in option_type.keys:
key_with_prefix = '{prefix}{key}'.format(prefix=option_type.prefix, key=key)
if ((key not in from_options) and (key_with_prefix not in from_options)):
_options[key] = ''
elif (key in fr... |
def test_config_app_encryption_key_validation() -> None:
app_encryption_key = 'atestencryptionkeythatisvalidlen'
with patch.dict(os.environ, {**REQUIRED_ENV_VARS, 'FIDES__SECURITY__APP_ENCRYPTION_KEY': app_encryption_key}, clear=True):
config = get_config()
assert (config.security.app_encryption... |
class ConfigHelper(BaseModel):
conf: AppConfigModel
dependency_files: List[str] = []
ignore_files: Dict[(str, List[str])] = {}
language_names: Dict[(str, str)] = {}
language_setup: Dict[(str, List[str])] = {}
class Config():
allow_mutation = True
def __init__(self, conf: AppConfigMod... |
def task_msgfmt():
sources = glob.glob(f'./{PACKAGE}/**/*.po', recursive=True)
dests = [(i[:(- 3)] + '.mo') for i in sources]
actions = [['msgfmt', sources[i], '-o', dests[i]] for i in range(len(sources))]
return {'actions': actions, 'targets': dests, 'file_dep': sources, 'task_dep': ['crowdin', 'crowdi... |
(scope='session')
def surveymonkey_secrets(saas_config) -> Dict[(str, Any)]:
return {'domain': (pydash.get(saas_config, 'surveymonkey.domain') or secrets['domain']), 'api_token': (pydash.get(saas_config, 'surveymonkey.api_token') or secrets['api_token']), 'survey_id': (pydash.get(saas_config, 'surveymonkey.survey_i... |
def run_model(prompt: str, activation: str, graph_mode: bool, use_fp16_acc: bool, verify: bool, model_path='bert-base-uncased'):
inputs = prepare_data(prompt, model_path)
inputs_pt = {name: data.cuda() for (name, data) in inputs.items()}
(batch_size, seq_len) = inputs['input_ids'].size()
pt_model = Bert... |
class TensorFlow2ONNXConfig(DataClassJsonMixin):
input_signature: Union[(tf.TensorSpec, np.ndarray)]
custom_ops: Optional[Dict[(str, Any)]] = None
target: Optional[List[Any]] = None
custom_op_handlers: Optional[Dict[(Any, Tuple)]] = None
custom_rewriter: Optional[List[Any]] = None
opset: Optiona... |
.scheduler
.integration_test
.parametrize('prior_mask,reals_rerun_option,should_resample', [pytest.param(range(5), '0-4', False, id='All realisations first, subset second run'), pytest.param([1, 2, 3, 4], '2-3', False, id='Subset of realisation first run, subs-subset second run'), pytest.param([0, 1, 2], '0-5', True, i... |
def extractReLibrary(item):
if (item['tags'] == ['rhapsody of mulan']):
return None
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Starting Anew as the New Me', '... |
class AtomTests(TestCase):
def test_truthiness(self):
self.assertEquals(TRUE, Symbol('t'))
def test_falsiness(self):
self.assertEquals(FALSE, List())
def test_atomness(self):
foo = Atom('foo')
another_foo = Atom('foo')
bar = Atom('bar')
baz = Atom('baz')
... |
class TextSection(SectionWithData):
def get_data_offset(self, addr):
byte_size = self.binary.config.ADDRESS_BYTE_SIZE
if (self.is_in_sec(addr) and self.is_in_sec((addr + byte_size))):
off = (addr - self.addr)
addr = utils.decode_address(self.data[off:(off + byte_size)], self.... |
def get_html(filename_rel, height):
astyle = 'font-size:small; float:right;'
dstyle = 'width: 500px; height: %ipx; align: center; resize:both; overflow: hidden; box-shadow: 5px 5px 5px #777; padding: 4px;'
istyle = 'width: 100%; height: 100%; border: 2px solid #094;'
html = ''
html += ("<a target='n... |
class OozieMetaPlugin(object):
def __init__(self, plugins, args):
self.args = args
sorted_plugins = sorted(plugins, key=(lambda p: p.priority.value), reverse=True)
self._plugin_containers = [OoziePluginContainer(name=plugin.name, priority=plugin.priority, plugin=plugin.oozie_plugin_cls(args)... |
class BamBlock(nn.Module):
def __init__(self, in_planes, reduction=16):
super(BamBlock, self).__init__()
self.ca = ChannelAttention(in_planes, reduction)
self.sa = SpatialAttention()
def forward(self, x):
ca_ch = self.ca(x)
sa_ch = self.sa(x)
out = (ca_ch.mul(sa_c... |
class OptCheckboxes(Options):
component_properties = ('icon', 'all_selected', 'tooltip')
def icon(self):
return self._config_get('fas fa-check')
def icon(self, value: str):
self._config(value)
def all_selected(self):
return self._config_get(False)
_selected.setter
def all... |
def test_builder_with_link_references(registry_package, dummy_ipfs_backend, monkeypatch):
(root, expected_manifest, compiler_output) = registry_package
monkeypatch.chdir(root)
inliner = source_inliner(compiler_output)
manifest = build({}, package_name('solidity-registry'), manifest_version('ethpm/3'), v... |
class InterlacedDofOrderType(DofOrderInfo):
def __init__(self, model_info='no model info set'):
DofOrderInfo.__init__(self, 'interlaced', model_info=model_info)
def create_DOF_lists(self, ownership_range, num_equations, num_components):
pressureDOF = numpy.arange(start=ownership_range[0], stop=(... |
class OptionSeriesParetoSonificationTracksMappingVolume(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):
self._co... |
_os(*metadata.platforms)
def main():
powershell = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'
unusualext = 'C:\\Users\\Public\\powershell.exe.pdf'
common.copy_file(powershell, unusualext)
common.execute([unusualext], timeout=1, kill=True)
common.remove_file(unusualext) |
def v2ToV1(v2Pdu, origV1Pdu=None):
((debug.logger & debug.FLAG_PRX) and debug.logger(('v2ToV1: v2Pdu %s' % v2Pdu.prettyPrint())))
pduType = v2Pdu.tagSet
if (pduType in V2_TO_V1_PDU_MAP):
v1Pdu = V2_TO_V1_PDU_MAP[pduType].clone()
else:
raise error.ProtocolError('Unsupported PDU type')
... |
class SubLearner(object):
def __init__(self, job, parent, estimator, in_index, out_index, in_array, targets, out_array, index):
self.job = job
self.estimator = estimator
self.in_index = in_index
self.out_index = out_index
self.in_array = in_array
self.targets = target... |
def _calculate_snapshots_size(ns, snap_model=None, dc=None):
qs = ns.snapshot_set.exclude(status__in=(snap_model.PENDING, snap_model.LOST), size__isnull=True)
if dc:
qs = qs.filter(vm__dc=dc)
size = qs.aggregate(models.Sum('size')).get('size__sum')
if size:
return b_to_mb(size)
else:... |
.django_db
def test_program_activity_list_sort_by_gross_outlay_amount(client, agency_account_data, helpers):
query_params = f'?fiscal_year={helpers.get_mocked_current_fiscal_year()}&order=asc&sort=gross_outlay_amount'
resp = client.get(url.format(code='007', query_params=query_params))
expected_result = {'f... |
class OptionPlotoptionsScatterSonification(Options):
def contextTracks(self) -> 'OptionPlotoptionsScatterSonificationContexttracks':
return self._config_sub_data('contextTracks', OptionPlotoptionsScatterSonificationContexttracks)
def defaultInstrumentOptions(self) -> 'OptionPlotoptionsScatterSonificatio... |
class Good(Entity, UnitMixin):
__auto_name__ = False
__tablename__ = 'Goods'
__mapper_args__ = {'polymorphic_identity': 'Good'}
good_id = Column('id', Integer, ForeignKey('Entities.id'), primary_key=True)
price_lists = relationship('PriceList', secondary='PriceList_Goods', primaryjoin='Goods.c.id==P... |
def list_name_extract(list_type):
base_type = list_type[5:(- 1)]
list_name = base_type
if (list_name.find('of_') == 0):
list_name = list_name[3:]
if (list_name[(- 2):] == '_t'):
list_name = list_name[:(- 2)]
list_name = ('of_list_' + list_name)
return (list_name, base_type) |
class OptionPlotoptionsNetworkgraphStatesHover(Options):
def animation(self) -> 'OptionPlotoptionsNetworkgraphStatesHoverAnimation':
return self._config_sub_data('animation', OptionPlotoptionsNetworkgraphStatesHoverAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self,... |
class ColumnValueListMetric(Metric[ColumnValueListMetricResult]):
column_name: str
values: Optional[list]
def __init__(self, column_name: str, values: Optional[list]=None, options: AnyOptions=None) -> None:
self.values = values
self.column_name = column_name
super().__init__(options=... |
class JsClassList():
def __init__(self, js_code: str, component: primitives.HtmlModel=None):
self.varId = js_code
self.component = component
def length(self):
return JsNumber.JsNumber.get(('%s.length' % self.varId))
def style_select(self):
if (self.component is None):
... |
.django_db
def test_category_recipient_subawards(recipient_test_data):
test_payload = {'category': 'recipient', 'subawards': True, 'page': 1, 'limit': 50}
spending_by_category_logic = RecipientViewSet().perform_search(test_payload, {})
expected_response = {'category': 'recipient', 'limit': 50, 'page_metadat... |
def create_run_path(run_context: RunContext, substitution_list: SubstitutionList, ert_config: ErtConfig) -> None:
t = time.perf_counter()
substitution_list = copy(substitution_list)
substitution_list['<ERT-CASE>'] = run_context.sim_fs.name
substitution_list['<ERTCASE>'] = run_context.sim_fs.name
for... |
class searchInfoNumero():
def search(self, num):
def mob_fix(pfx):
if ((pfx == '06') or (pfx == '07')):
return 'Portable'
elif ((pfx == '08') or (pfx == '09')):
return 'internet'
else:
return 'Fixe'
location = {'01':... |
('rocm.groupnorm.func_call')
def groupnorm_gen_func_call(func_attrs, indent=' '):
assert (len(func_attrs['outputs']) == 1)
assert (len(func_attrs['inputs']) == 3)
input_name = FUNC_CALL_FP16_PARAM_TEMPLATE.render(name=func_attrs['inputs'][0]._attrs['name'])
gamma_name = FUNC_CALL_FP16_PARAM_TEMPLATE.re... |
def mock_handler():
data = bytes(Message(Integer(3), HeaderData(123, 65000, V3Flags(False, False, False), 3), bytes(USMSecurityParameters(b'engine-id', 1, 2, b'username', b'auth', b'priv')), ScopedPDU(OctetString(b'engine-id'), OctetString(b'context'), GetResponse(PDUContent(123, [VarBind(ObjectIdentifier(), Intege... |
def fetch_price(zone_key: str='NZ', session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> dict:
if target_datetime:
raise NotImplementedError('This parser is not able to retrieve data for past dates')
r = (session or Session())
url = '
re... |
class TextClassificationInferenceOptions(InferenceConfig):
def __init__(self, *, classification_labels: t.Union[(t.List[str], t.Tuple[(str, ...)])], tokenization: NlpTokenizationConfig, results_field: t.Optional[str]=None, num_top_classes: t.Optional[int]=None):
super().__init__(configuration_type='text_cla... |
('cuda.dynamic_slice.func_call')
def gen_function_call(func_attrs, indent=' '):
return slice_common.gen_function_call(backend_spec=CUDASpec(), func_name=func_attrs['name'], inputs=func_attrs['inputs'], outputs=func_attrs['outputs'], start_indices=[func_attrs['start_indices']], end_indices=[func_attrs['end_indices'... |
def test_differential_all():
outfile = NamedTemporaryFile(suffix='.tar.gz', delete=False)
outfile.close()
args = '-f {} -o {} -om {}'.format((ROOT + 'chicDifferentialTest/differential.hdf5'), outfile.name, 'all').split()
chicExportData.main(args)
file_obj_new = tarfile.open(outfile.name, 'r')
na... |
class T():
def __init__(self, userConfig):
self.userConfig = userConfig
self.compiler = fc.Compiler(userConfig)
self.f = fractal.T(self.compiler)
def run(self, options):
for path in options.extra_paths:
self.compiler.add_func_path(path)
if (options.flags is no... |
def _normalize_type_list(k, v):
if isinstance(v, dict):
msg = _('{build_flag} must be list or string, found: {value}')
_warn_or_exception(msg.format(build_flag=k, value=v))
elif (type(v) not in (list, tuple, set)):
v = [v]
return [_normalize_type_string(i) for i in v] |
_custom_acc_mapper_fn(op_and_target=('call_function', torch.addcmul), arg_replacement_tuples=[('input', 'input'), ('tensor1', 'tensor1'), ('tensor2', 'tensor2'), ('value', 'value')])
def addcmul_mapper(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node:
with node.graph.inserting_before(node):
mul_kwargs = ... |
def _substitute_token(defines: Defines, token: FileContextToken, expand_env: bool=True) -> FileContextToken:
current: FileContextToken = token
if expand_env:
for (key, val) in os.environ.items():
current = current.replace_value(f'${key}', val)
if (not defines):
return current
... |
.parametrize('transformer', _estimators)
def test_transformers_in_pipeline_with_set_output_pandas(transformer):
X = pd.DataFrame({'feature_1': [1, 2, 3, 4, 5], 'feature_2': [6, 7, 8, 9, 10]})
y = pd.Series([0, 1, 0, 1, 0])
pipe = Pipeline([('trs', transformer)]).set_output(transform='pandas')
Xtt = tran... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.