code stringlengths 281 23.7M |
|---|
_test_func_names
class TestShell(unittest.TestCase):
def test_version(self):
call(['coconut', '--version'])
def test_code(self):
call(['coconut', '-s', '-c', coconut_snip], assert_output=True)
if (not PY2):
def test_target_3_snip(self):
call(['coconut', '-t3', '-c', targe... |
class PelotonWorkoutMetrics(PelotonObject):
def __init__(self, **kwargs):
self.workout_duration = kwargs.get('duration')
self.fitness_discipline = kwargs.get('segment_list')[0]['metrics_type']
metric_summaries = ['total_output', 'distance', 'calories']
for metric in kwargs.get('summa... |
class SetLastLoginTest(unittest.TestCase):
('set_last_login.app.update_last_login', side_effect=mocked_update_last_login)
def test_build(self, update_last_login_mock):
response = lambda_handler(self.update_login_event(), '')
self.assertEqual(update_last_login_mock.call_count, 1)
def update_l... |
.integration
class TestCheckResponseAuth():
def test_check_response_auth_sys_exit(self) -> None:
response = requests.get('/api/v1/cryptography/encryption/key')
with pytest.raises(SystemExit):
common_utils.check_response_auth(response)
def test_check_response_auth_ok(self) -> None:
... |
def downgrade():
op.drop_constraint('uq_ugr_user_group_role', 'users_groups_roles', type_='unique')
op.drop_constraint('uq_ugr_email_group_role', 'users_groups_roles', type_='unique')
op.create_unique_constraint('uq_uer_user_group_role', 'users_groups_roles', ['user_id', 'group_id', 'role_id']) |
class _TestSegmentPen(AbstractPen):
def __init__(self):
self._commands = []
def __repr__(self):
return ' '.join(self._commands)
def moveTo(self, pt):
self._commands.append(('%s %s moveto' % (pt[0], pt[1])))
def lineTo(self, pt):
self._commands.append(('%s %s lineto' % (pt... |
(**DATACLASS_KWARGS)
class Token():
type: str
tag: str
nesting: Literal[((- 1), 0, 1)]
attrs: dict[(str, ((str | int) | float))] = dc.field(default_factory=dict)
map: (list[int] | None) = None
level: int = 0
children: (list[Token] | None) = None
content: str = ''
markup: str = ''
... |
class JzCzhz(LCh):
BASE = 'jzazbz'
NAME = 'jzczhz'
SERIALIZE = ('--jzczhz',)
WHITE = WHITES['2deg']['D65']
DYNAMIC_RANGE = 'hdr'
CHANNEL_ALIASES = {'lightness': 'jz', 'chroma': 'cz', 'hue': 'hz', 'h': 'hz', 'c': 'cz', 'j': 'jz'}
ACHROMATIC = Jzazbz.ACHROMATIC
CHANNELS = (Channel('jz', 0.... |
class Test_UnknownType(unittest.TestCase):
def setUp(self):
self.protocol_id = bpdu.PROTOCOL_IDENTIFIER
self.version_id = bpdu.RstBPDUs.VERSION_ID
self.bpdu_type = 222
self.flags = 126
self.root_priority = 4096
self.root_system_id_extension = 1
self.root_mac_a... |
def test_resolve_unresolved_reaching_conditions():
asforest = AbstractSyntaxForest(condition_handler=ConditionHandler())
code_node_1 = asforest.add_code_node([Assignment(var('u'), const(9))])
code_node_1.reaching_condition = LogicCondition.initialize_symbol('R2', asforest.factory.logic_context)
code_nod... |
def get_signatures_from_comments(comments):
comments = comments.replace('#', '').replace('\n', '')
signatures_tmp = [sig.split('->', 1)[0].strip() for sig in comments.split('transonic block')[1:]]
signatures = []
for sig in signatures_tmp:
if sig.startswith('('):
sig = sig[1:find_ind... |
class OptionPlotoptionsHeatmapSonificationDefaultinstrumentoptionsMappingGapbetweennotes(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(s... |
class OptionSeriesHeatmapSonificationContexttracksMappingTremoloSpeed(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 ActionRecordWorker(ParallelRolloutWorker):
def run(env_config: DictConfig, wrapper_config: DictConfig, agent_config: DictConfig, deterministic: bool, max_episode_steps: int, record_trajectory: bool, input_directory: str, reporting_queue: Queue, seeding_queue: Queue) -> None:
(env_seed, agent_seed) = (... |
def create_index_string(matview_name, index_name, idx):
if idx.get('cluster_on_this', False):
global CLUSTERING_INDEX
CLUSTERING_INDEX = index_name
idx_method = idx.get('method', 'BTREE')
idx_unique = ('UNIQUE ' if idx.get('unique', False) else '')
idx_where = ((' WHERE ' + idx['where'])... |
class NevergradSweeper(Sweeper):
def __init__(self, optim: OptimConf, parametrization: Optional[DictConfig]):
from ._impl import NevergradSweeperImpl
self.sweeper = NevergradSweeperImpl(optim, parametrization)
def setup(self, *, hydra_context: HydraContext, task_function: TaskFunction, config: D... |
def drop_columns(records, slices):
for record in records:
drop = set((i for slice in slices for i in range(*slice.indices(len(record)))))
keep = [(i not in drop) for i in range(len(record))]
record.seq = Seq(''.join(itertools.compress(record.seq, keep)))
(yield record) |
def extractBarrykaizerBlogspotCom(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... |
def make_request_args(tasks):
prompts = [t['prompt'] for t in tasks]
futures = [t['future'] for t in tasks]
request_ids = [t['request_id'] for t in tasks]
api_configs = [t.get('api_config', None) for t in tasks if (t.get('api_config') is not None)]
api_config = (api_configs[0] if (len(api_configs) >... |
def test_oidcclient_has_cookie(client):
client.client.cookies.clear()
assert (client.has_cookie('foo') is False)
client.client.cookies.set('foo', 'bar', domain='localhost.local')
assert (client.has_cookie('foo') is True)
assert (client.has_cookie('foo', domain='localhost') is True)
assert (clien... |
class Preferences(GObject.Object, PeasGtk.Configurable):
__gtype_name__ = 'AlternativeToolbarPreferences'
object = GObject.property(type=GObject.Object)
def __init__(self):
GObject.Object.__init__(self)
self.gs = GSetting()
self.plugin_settings = self.gs.get_setting(self.gs.Path.PLUG... |
class IamPolicy(object):
def __init__(self):
self.audit_configs = None
self.bindings = []
def create_from(cls, policy_json):
policy = cls()
if (not policy_json):
raise errors.InvalidIamPolicyError('Invalid policy {}'.format(policy_json))
policy.bindings = [Iam... |
def test_extruded_ope_hits_cache():
m = UnitSquareMesh(1, 1)
e = ExtrudedMesh(m, 2, layer_height=1)
U0 = FiniteElement('DG', 'triangle', 0)
U1 = FiniteElement('CG', 'interval', 2)
W0 = TensorProductElement(U0, U1)
W1 = FunctionSpace(e, HDiv(W0))
U0 = FiniteElement('DG', 'triangle', 0)
U1... |
class OptionPlotoptionsPyramidSonificationContexttracksMappingHighpassResonance(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... |
def test_is_valid_quarter():
assert (fyh.is_valid_quarter(1) is True)
assert (fyh.is_valid_quarter(2) is True)
assert (fyh.is_valid_quarter(3) is True)
assert (fyh.is_valid_quarter(4) is True)
assert (fyh.is_valid_quarter(0) is False)
assert (fyh.is_valid_quarter(5) is False)
assert (fyh.is_... |
class OptionExportingButtonsContextbutton(Options):
def _titleKey(self):
return self._config_get(None)
_titleKey.setter
def _titleKey(self, text: str):
self._config(text, js_type=False)
def align(self):
return self._config_get('right')
def align(self, text: str):
self... |
def test_align_convert_degen_bases(o_dir, e_dir, request):
program = 'bin/align/phyluce_align_convert_degen_bases'
output = os.path.join(o_dir, 'mafft-degen-bases-converted')
cmd = [os.path.join(request.config.rootdir, program), '--alignments', os.path.join(e_dir, 'mafft-degen-bases'), '--output', output, '... |
class DashCustom(Dash):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.requests_pathname_external_prefix = self.config.requests_pathname_prefix
def _config(self):
config = super()._config()
config.update({'url_base_pathname': self.config.url_base_path... |
class OptionSeriesWindbarbSonificationTracksMappingLowpass(Options):
def frequency(self) -> 'OptionSeriesWindbarbSonificationTracksMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionSeriesWindbarbSonificationTracksMappingLowpassFrequency)
def resonance(self) -> 'OptionSeriesWindba... |
def get_bert_feature(text, word2ph):
with torch.no_grad():
inputs = tokenizer(text, return_tensors='pt')
for i in inputs:
inputs[i] = inputs[i].to(device)
res = model(**inputs, output_hidden_states=True)
res = torch.cat(res['hidden_states'][(- 3):(- 2)], (- 1))[0].cpu()
... |
def parse_var_keywords(test_str: str) -> tuple[(list[str], str)]:
keyword_match = FRegex.KEYWORD_LIST.match(test_str)
keywords = []
while keyword_match:
tmp_str = re.sub('^[, ]*', '', keyword_match.group(0))
test_str = test_str[keyword_match.end(0):]
if tmp_str.lower().startswith('di... |
class DebugConfig():
instance = None
def __init__(self):
self.debug_dir = None
self.debugging = False
def set_debugging(self, debugging):
self.debugging = debugging
def set_debug_dir(self, debug_dir):
if (not self.debugging):
return
self.debug_dir = de... |
class DataplaneLatency(base_tests.SimpleDataPlane):
def runTest(self):
(in_port, out_port) = openflow_ports(2)
delete_all_flows(self.controller)
pkt = str(simple_tcp_packet())
request = ofp.message.flow_add(match=ofp.match(wildcards=ofp.OFPFW_ALL), buffer_id=, actions=[ofp.action.out... |
def test_raises_error_when_variables_not_datetime(df_datetime):
with pytest.raises(TypeError):
DatetimeFeatures(variables=['Age']).fit(df_datetime)
with pytest.raises(TypeError):
DatetimeFeatures(variables=['Name', 'Age', 'date_obj1']).fit(df_datetime)
with pytest.raises(TypeError):
... |
class OptionSeriesItemSonificationDefaultinstrumentoptionsMapping(Options):
def frequency(self) -> 'OptionSeriesItemSonificationDefaultinstrumentoptionsMappingFrequency':
return self._config_sub_data('frequency', OptionSeriesItemSonificationDefaultinstrumentoptionsMappingFrequency)
def gapBetweenNotes(s... |
class OptionSeriesHeatmapSonificationTracksMappingTremoloSpeed(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):
s... |
class BrowseUsersTests(DatabaseTestCase):
def setUp(self):
super().setUp()
session = Session()
self.user = models.User(email='', username='user')
user_social_auth = social_models.UserSocialAuth(user_id=self.user.id, user=self.user)
session.add(self.user)
session.add(u... |
class ArrowGlacierUnsignedLegacyTransaction(LondonUnsignedLegacyTransaction):
def as_signed_transaction(self, private_key: PrivateKey, chain_id: int=None) -> ArrowGlacierLegacyTransaction:
(v, r, s) = create_transaction_signature(self, private_key, chain_id=chain_id)
return ArrowGlacierLegacyTransac... |
class Object(Entity):
INFO = {'make': ['sensors', 'actuators', 'engine_states']}
def make(cls, *args: Any, **kwargs: Any):
pass
def pre_make(cls, entity_id, entity_type):
spec = super().pre_make(entity_id, entity_type)
params = spec.params
params['config'] = dict(name=None, s... |
class Scene(QCScene):
def __init__(self, attributes):
self._attributes = attributes
self.name = self._get_attribute('Name')
self.make_index = self._get_attribute('MakeIndex')
self.index = self._get_attribute('Idx')
self.split_horizontal = self._get_attribute('SplitHorizontal'... |
class JsD3Bubble():
alias = 'D3'
chartTypes = ['gravity']
params = ('seriesNames', 'xAxis')
value = "\n nbSeries = seriesNames.length;\n var temp = {}; var result = [];\n data.forEach(function(rec){\n for (var key in rec){\n if(key != xAxis && rec[key] != 0 && seriesNames.includes(k... |
.parametrize('encoder, df_test, df_expected', [(DecisionTreeEncoder(), pd.DataFrame({'x': ['a', 'a', 'b', 'b', 'c', 'c'], 'y': [21, 30, 21, 30, 51, 40]}, index=[101, 105, 42, 76, 88, 92]), pd.DataFrame({'x': [25.5, 25.5, 25.5, 25.5, 45.5, 45.5]}, index=[101, 105, 42, 76, 88, 92])), (MeanEncoder(), pd.DataFrame({'x': ['... |
class TestContentMatcher(unittest.TestCase):
def num_matches(self, pattern, text, **kwargs):
cm = ContentMatcher(pattern, **kwargs)
return len(list(cm.match_file(StringIO(text))))
def assertMatches(self, cm, text, exp_matches):
matches = list(cm.match_file(StringIO(text)))
self.a... |
def test_gauss_edge0():
print('0th Order Polynomial')
print('Edge')
gaussEdge.setOrder(1)
int0_f0 = dot(f0(gaussEdge.points), gaussEdge.weights)
print(int0_f0)
gaussEdge.setOrder(2)
int1_f0 = dot(f0(gaussEdge.points), gaussEdge.weights)
print(int1_f0)
gaussEdge.setOrder(3)
int2_f... |
def test_set_voltage_pv1(power: PowerSupply, multi: Multimeter):
voltages = np.arange((- 5), 5, 0.1)
measured = np.zeros(len(voltages))
for (i, v) in enumerate(voltages):
power.pv1 = v
measured[i] = multi.measure_voltage('CH1')
assert (measured == pytest.approx(voltages, rel=(RELTOL * 2)... |
class Command(BaseCommand):
help = __doc__
def handle(self, *args, **kwargs):
page_url = '
filename_re = re.compile('^BNF Snomed Mapping data (?P<date>20\\d{6})\\.zip$', re.IGNORECASE)
rsp = requests.get(page_url)
rsp.raise_for_status()
doc = BeautifulSoup(rsp.text, 'html... |
def vote(probs):
if (len(probs) == 0):
return 0
probs = sorted(probs)
if (probs[(len(probs) / 3)] >= 1):
return (probs[(len(probs) / 3)] + 1)
elif (probs[((len(probs) * 2) / 3)] <= (- 1)):
return (probs[((len(probs) * 2) / 3)] - 1)
else:
return probs[(len(probs) / 2)] |
def unlink():
keep(1)
wipe(1)
keep(2)
wipe(1)
keep(1)
keep(3)
wipe(3)
keep(3)
payload = p64(0)
payload += p64(33)
payload += p64((small_ptr - 24))
payload += p64((small_ptr - 16))
payload += p64(32)
payload += p64(400016)
renew(2, payload)
wipe(3) |
def _normal_faba(award):
ta1 = baker.make('references.ToptierAgency', name=f'Agency 00{award.award_id}', toptier_code=f'00{award.award_id}')
baker.make('references.Agency', toptier_agency=ta1, toptier_flag=True, _fill_optional=True)
defc_m = baker.make('references.DisasterEmergencyFundCode', code='M', publi... |
class XMLConverter(PDFConverter):
CONTROL = re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]')
def __init__(self, rsrcmgr, outfp, pageno=1, laparams=None, imagewriter=None, stripcontrol=False):
PDFConverter.__init__(self, rsrcmgr, outfp, pageno=pageno, laparams=laparams)
self.imagewriter = imagew... |
def test_perturbed_mediums_copy():
pp_real = td.ParameterPerturbation(heat=td.LinearHeatPerturbation(coeff=(- 0.01), temperature_ref=300, temperature_range=(200, 500)))
pp_complex = td.ParameterPerturbation(heat=td.LinearHeatPerturbation(coeff=0.01j, temperature_ref=300, temperature_range=(200, 500)), charge=td... |
def test_owly_short_method_bad_response_status():
params = urlencode({'apiKey': 'TEST_KEY', 'longUrl': expanded})
body = "{'rerrsults': {'shortUrl': shorten}}"
mock_url = f'{owly.api_url}shorten?{params}'
responses.add(responses.GET, mock_url, body=body, status=400, match_querystring=True)
with pyte... |
.parametrize('geometry', GEO_TYPES)
def test_to_gds(geometry, tmp_path):
fname = str((tmp_path / f'{geometry.__class__.__name__}.gds'))
geometry.to_gds_file(fname, z=0, gds_cell_name=geometry.__class__.__name__)
cell = gdstk.read_gds(fname).cells[0]
assert (cell.name == geometry.__class__.__name__)
... |
class ZshCompletion(CompletionPlugin):
def __init__(self, config_loader: ConfigLoader):
super().__init__(config_loader)
from hydra._internal.core_plugins.bash_completion import BashCompletion
self.delegate = BashCompletion(config_loader)
def install(self) -> None:
self.delegate.i... |
.usefixtures('use_tmpdir')
def test_that_a_failing_job_shows_error_message_with_context(opened_main_window_clean, qtbot):
gui = opened_main_window_clean
with open('poly_eval.py', 'w', encoding='utf-8') as f:
f.write(dedent(' #!/usr/bin/env python\n\n if __name__ == "__main_... |
class CanaryDiffMapping(MappingTest):
parent: AmbassadorTest
target: ServiceType
canary: ServiceType
weight: int
def variants(cls) -> Generator[(Node, None, None)]:
for v in variants(ServiceType):
for w in (0, 10, 50, 100):
(yield cls(v, v.clone('canary'), w, name... |
class OptionSeriesAreasplineSonificationContexttracksMappingTime(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
def get_tdx_kdata(security_item, start, end):
api = TdxHq_API()
with api.connect():
df = api.get_k_data(security_item['code'], start, end)
df = df[['date', 'code', 'low', 'open', 'close', 'high', 'vol', 'amount']]
df['securityId'] = df['code'].apply((lambda x: 'stock_{}_{}'.format(get_ex... |
class AutoBackend(AsyncNetworkBackend):
async def _init_backend(self) -> None:
if (not hasattr(self, '_backend')):
backend = current_async_library()
if (backend == 'trio'):
from .trio import TrioBackend
self._backend: AsyncNetworkBackend = TrioBackend(... |
class StringDecoder(ByteStringDecoder):
def __init__(self, handle_string_errors='strict'):
self.bytes_errors = handle_string_errors
super().__init__()
_type_str('string')
def from_type_str(cls, abi_type, registry):
return cls()
def decode(self, stream):
raw_data = self.re... |
def get_integration_manifests(integration: str, prerelease: Optional[bool]=False, kibana_version: Optional[str]='') -> list:
epr_search_url = '
if (not prerelease):
prerelease = 'false'
else:
prerelease = 'true'
epr_search_parameters = {'package': f'{integration}', 'prerelease': prerelea... |
class BigQueryValues(SqlTree):
type: Type
values: List[Sql]
def _compile(self, qb):
cols = list(self.type.elems)
rows = [(((['STRUCT('] + join_comma(((v.compile(qb).code + [' as ', name]) for (name, v) in safezip(cols, row.values)))) + [')']) if isinstance(row, Tuple) else row.compile(qb).co... |
def extract_flake8_bandit() -> Dict[(str, str)]:
from bandit.core.extension_loader import MANAGER
codes = dict()
for blacklist in MANAGER.blacklist.values():
for check in blacklist:
code = check['id'].replace('B', 'S')
codes[code] = check['message']
for plugin in MANAGER.... |
class ThreadedAsyncRunner(Thread):
def __init__(self, loop: Optional[AbstractEventLoop]=None) -> None:
self._loop = (loop or asyncio.new_event_loop())
if self._loop.is_closed():
raise ValueError('Event loop closed.')
super().__init__(daemon=True)
def start(self) -> None:
... |
(allow_guest=True)
def search(query, path, space):
if (not space):
space = get_space_route(path)
use_redisearch = frappe.db.get_single_value('Wiki Settings', 'use_redisearch_for_search')
if ((not use_redisearch) or (not _redisearch_available)):
result = web_search(query, space, 5)
fo... |
def stream_encode_multipart(values, threshold=(1024 * 500), boundary=None, charset='utf-8'):
if (boundary is None):
from time import time
from random import random
boundary = ('EmmettFormPart_%s%s' % (time(), random()))
_closure = [BytesIO(), 0, False]
write_binary = _closure[0].writ... |
def fl_json_to_dotlist(json_config: Dict[(str, Any)], append_or_override: bool=True) -> List[str]:
dotlist_dict = _flatten_dict(json_config)
dotlist_list = []
for (k, v) in dotlist_dict.items():
if k.endswith('._base_'):
k = k.replace('._base_', '')
config_group = k.split('.'... |
class SyncSecAggSQServer(SyncSecAggServer):
def __init__(self, *, global_model: IFLModel, channel: Optional[ScalarQuantizationChannel]=None, **kwargs):
init_self_cfg(self, component_class=__class__, config_class=SyncSecAggSQServerConfig, **kwargs)
super().__init__(global_model=global_model, channel=... |
def test_instantiate_target_raising_exception_taking_no_arguments(instantiate_func: Any) -> None:
_target_ = 'tests.instantiate.raise_exception_taking_no_argument'
with raises(InstantiationException, match=dedent(f'''
Error in call to target '{re.escape(_target_)}':
ExceptionTaki... |
class OptionPlotoptionsFunnelSonificationDefaultinstrumentoptionsMappingFrequency(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, te... |
def update_common_site_config(ddict, bench_path='.'):
filename = os.path.join(bench_path, 'sites', 'common_site_config.json')
if os.path.exists(filename):
with open(filename) as f:
content = json.load(f)
else:
content = {}
content.update(ddict)
with open(filename, 'w') as... |
class UserPermissionMixin(BaseModel):
__table_args__ = (sa.PrimaryKeyConstraint('user_id', 'perm_name', name='pk_users_permissions'), {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'})
_attr
def __tablename__(self):
return 'users_permissions'
_attr
def user_id(self):
return sa.Colu... |
def test_mode_imputation_with_multiple_variables(df_na):
imputer = CategoricalImputer(imputation_method='frequent', variables=['Studies', 'City'])
X_transformed = imputer.fit_transform(df_na)
X_reference = df_na.copy()
X_reference['City'] = X_reference['City'].fillna('London')
X_reference['Studies']... |
class OptionSeriesScatter3dSonificationTracksMappingPlaydelay(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):
se... |
class CssPivotFilterBoxPopUpButton(CssStyle.Style):
classname = 'pvtFilterBox button'
_attrs = {'font-weight': 'bold', 'padding': '0 20px', 'margin': 0, 'text-decoration': 'none', 'border-radius': '4px', 'white-space': 'nowrap', 'display': 'inline-block', 'line-height': '20px', '-webkit-appearance': 'none', '-m... |
class Migration(migrations.Migration):
dependencies = [('references', '0053_office')]
operations = [migrations.AddField(model_name='gtassf133balances', name='disaster_emergency_fund', field=models.ForeignKey(blank=True, db_column='disaster_emergency_fund_code_temp', null=True, on_delete=django.db.models.deletio... |
class TestInlineHiliteNoClassNoPygments(util.MdCase):
extension = ['pymdownx.highlight', 'pymdownx.inlinehilite']
extension_configs = {'pymdownx.highlight': {'css_class': '', 'use_pygments': False}}
def test_no_class_no_pygments(self):
self.check_markdown('Lets test inline highlight no guessing and ... |
def _context_similarity(ctx_ref, ctx_trg, repeats, same_len):
def alignment(ref, trg):
GAP = (- 2)
def match(a, b):
mult = (1 if ((abs(a) in repeats) or (abs(b) in repeats)) else 2)
if (a != b):
return (- mult)
else:
return mult
... |
.skipif((not has_torch), reason='needs PyTorch')
.skipif(has_torch_amp, reason='needs PyTorch without gradient scaling support')
def test_raises_on_old_pytorch():
import torch
scaler = PyTorchGradScaler(enabled=True)
with pytest.raises(ValueError, match='not supported.*1.9.0'):
scaler.scale([torch.t... |
_arguments
def count_events(args):
client = EmbeddedNotificationClient(server_uri=args.server_uri)
offset = 0
if args.begin_offset:
offset = args.begin_offset
elif args.begin_time:
offset = client.time_to_offset(time_utils.timestamp_to_datetime(args.begin_time))
res = client.count_ev... |
_blueprint.route('/api/by_ecosystem/<ecosystem>/<project_name>/', methods=['GET'])
_blueprint.route('/api/by_ecosystem/<ecosystem>/<project_name>', methods=['GET'])
def api_get_project_ecosystem(ecosystem, project_name):
project = models.Project.by_name_and_ecosystem(Session, project_name, ecosystem)
if (not pr... |
('task_function, expected_file, expected_module', [param(data.foo, None, 'tests.data', id='function'), param(data.foo_main_module, data.__file__, None, id='function-main-module'), param(data.Bar, None, 'tests.data', id='class'), param(data.bar_instance, None, 'tests.data', id='class_inst'), param(data.bar_instance_main... |
class CLICommand(RegionalCommand):
def regional_from_cli(cls, parser, argv, cfg):
parser.add_argument('--verbose', action='store_true', help='include each VIF and its status in output', default=cfg('verbose', type=Bool))
stats = ['Average', 'Minimum', 'Maximum', 'p90', 'p95', 'p99', 'p99.9']
... |
.skipif(('pandas' not in sys.modules), reason='Pandas is not installed.')
def test_workflow():
import pandas as pd
def my_task(df: pd.DataFrame) -> int:
return len(df[df.columns[0]])
sql_task = SQLite3Task('test', query_template='select * from tracks limit {{.inputs.limit}}', inputs=kwtypes(limit=in... |
def setup_ List[str]=None):
if (not exclude_paths):
exclude_paths = ['/api/controller/heartbeat']
uvicorn_logger = logging.getLogger('uvicorn.access')
if uvicorn_logger:
for path in exclude_paths:
uvicorn_logger.addFilter(EndpointFilter(path=path))
= logging.getLogger('
... |
class OptionSeriesWindbarbSonificationContexttracksMappingPlaydelay(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 OptionSeriesVectorSonificationDefaultspeechoptionsMappingPitch(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('undefined')
def mapTo(self, text: st... |
class Transpose(UnaryOp):
_property
def arg_function_spaces(self):
(tensor,) = self.operands
return tensor.arg_function_spaces[::(- 1)]
def arguments(self):
(tensor,) = self.operands
return tensor.arguments()[::(- 1)]
def _output_string(self, prec=None):
(tensor,)... |
class Node():
previous: 'Node'
next: 'Node'
key: bytes
value: Transaction
def __init__(self, previous: Optional['Node']=None, next: Optional['Node']=None, key: bytes=b'', value=None, value_size: int=0) -> None:
self.previous = (previous if (previous is not None) else self)
self.next ... |
.django_db
def test_parent_recipient_with_id_and_name(recipient_lookup):
recipient_parameters = {'recipient_name': 'Parent Recipient Tester', 'recipient_uei': None, 'parent_recipient_uei': None, 'recipient_unique_id': '123', 'parent_recipient_unique_id': None, 'is_parent_recipient': True}
expected_result = '01c... |
def test_spec(store: Connection) -> None:
req = request('spec', mode='sign')
r = do_request(store, req)
assert (r == 'signature required'), 'sig required'
r = do_signed(store, req)
assert ('def sign' in r), 'mode=sign'
req = request('spec', mode='verify')
r = do_signed(store, req)
assert... |
def create_patch_sequential(ffrom, fto, fpatch, compression, suffix_array_algorithm, data_format, data_segment, use_mmap, heatshrink_window_sz2, heatshrink_lookahead_sz2):
fpatch.write(pack_header(PATCH_TYPE_SEQUENTIAL, compression_string_to_number(compression)))
fpatch.write(pack_size(file_size(fto)))
crea... |
def plot_graph(G, ax=None, k=2, pos=None):
if (ax is None):
(env, ax) = plt.subplots(nrows=1, ncols=1)
if (pos is None):
pos = nx.spring_layout(G, k=k)
bbox = dict(facecolor='skyblue', edgecolor='black', boxstyle='round,pad=0.2', alpha=0.5)
labels = nx.draw_networkx_labels(G, pos, bbox=b... |
def list_from_array_of_namedtupes(array_of_namedtupes: Union[(List[Any], NamedTuple)], key, func, join: bool=False) -> Union[(List[Any], str)]:
result = list()
for tup in array_of_namedtupes:
if (key in tup._fields):
result.append(getattr(tup, key))
else:
raise Exception(... |
class TestFuseExpand(unittest.TestCase):
([param(True, 'test_fuse_expand_elementwise_exact'), param(False, 'test_fuse_expand_elementwise_non_exact')])
def test_fuse_expand_elementwise(self, exact_match: bool, name: str):
(N, M) = ((2, 10) if exact_match else (1, 1))
x = Tensor([IntVar([1, 10], n... |
class Operations(object):
def __init__(self):
self.objects = OrderedDict()
def format_key(self, target):
return (target.__class__, identity(target))
def __contains__(self, target):
return (self.format_key(target) in self.objects)
def __setitem__(self, key, operation):
sel... |
def remove_vscode_tasks_launch_files(fips_dir, proj_dir, impex, cfg):
for dep_proj_name in reversed(impex):
dep_proj_dir = util.get_project_dir(fips_dir, dep_proj_name)
tasks_path = (dep_proj_dir + '/.vscode/tasks.json')
launch_path = (dep_proj_dir + '/.vscode/launch.json')
if os.pat... |
class FBPrintObjectInObjc(fb.FBCommand):
def name(self):
return 'poobjc'
def description(self):
return 'Print the expression result, with the expression run in an ObjC++ context. (Shortcut for "expression -O -l ObjC++ -- " )'
def args(self):
return [fb.FBCommandArgument(arg='expressi... |
class Aiterate(Event):
__slots__ = ('_task',)
def __init__(self, ait):
Event.__init__(self, ait.__qualname__)
loop = get_event_loop()
self._task = asyncio.ensure_future(self._looper(ait), loop=loop)
async def _looper(self, ait):
try:
async for args in ait:
... |
class ADCEntity():
def __init__(self, busnum=0, devnum=0, dtype=3008):
self.busy = False
self.initialized = False
self.busnum = int(busnum)
self.devnum = int(devnum)
self.values = [0, 0, 0, 0, 0, 0, 0, 0, 0]
try:
self.spi = spidev.SpiDev()
self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.