code stringlengths 281 23.7M |
|---|
def butterworth(data, frequency, cutoff, filter_type=FilterType.LOW_PASS, order=3, axis=(- 1), precision='float32'):
(data, frequency, cutoff, filter_type, order, axis, precision) = _butterworth_args_check(data, frequency, cutoff, filter_type, order, axis, precision)
(b_coef, a_coef) = _signal_butter_wrapper(or... |
class ErrorFrame(Frame):
TYPE = 255
message: str
tracing: bytes
code: int
def __init__(self):
super().__init__()
self.code = 0
self.tracing = bytes(25)
self.message = ''
def read_payload(self, fp: IOWrapper, size: int):
offset = 0
self.code = fp.re... |
class TestPseudoLabeler(unittest.TestCase):
def test_noop(self):
pseudo_labeler = NoopPseudoLabeler()
x = np.random.randn(1)
output = pseudo_labeler.label(x)
torch.testing.assert_close(x, output)
def test_relabeltargetinbatch(self):
teacher = DivideInputDictBy2()
... |
def fetch_production(zone_key: ZoneKey, session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list[dict[(str, Any)]]:
if target_datetime:
raise NotImplementedError('This parser is not yet able to parse past dates')
data = get_data(session)
(d... |
class GroupResourcePermissionMixin(BaseModel):
__table_args__ = (sa.PrimaryKeyConstraint('group_id', 'resource_id', 'perm_name', name='pk_users_resources_permissions '), {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'})
_attr
def __tablename__(self):
return 'groups_resources_permissions'
_att... |
def get_sample(item_array, n_iter=None, sample_size=2):
np.random.seed(42)
n = len(item_array)
start_idx = ((n_iter * sample_size) % n)
if (((start_idx + sample_size) >= n) or (start_idx <= sample_size)):
np.random.shuffle(item_array)
return item_array[start_idx:(start_idx + sample_size)] |
def test_workflow_node_sw():
obj = _workflow.WorkflowNode(sub_workflow_ref=_generic_id)
assert (obj.sub_workflow_ref == _generic_id)
assert (obj.reference == _generic_id)
obj2 = _workflow.WorkflowNode.from_flyte_idl(obj.to_flyte_idl())
assert (obj == obj2)
assert (obj2.reference == _generic_id)
... |
class IntersectionType(abcdtype):
_fields = ('types',)
_attributes = ('lineno', 'col_offset')
def __init__(self, types=[], lineno=0, col_offset=0, **ARGS):
abcdtype.__init__(self, **ARGS)
self.types = list(types)
self.lineno = int(lineno)
self.col_offset = int(col_offset) |
_validator
def validate_groups(request, **kwargs):
groups = request.validated.get('groups')
if (groups is None):
return
db = request.db
bad_groups = []
validated_groups = []
for g in groups:
group = db.query(Group).filter((Group.name == g)).first()
if (not group):
... |
class OptionSeriesVariablepieSonificationContexttracksMappingTime(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 pot_job(hash_file=None, session=None, hash_mode=None, attack_mode=None, rules=None, pot_path=None, username=False):
pot_wordlist = valid.val_filepath(path_string=log_dir, file_string='pot_wordlist.txt')
if (not pot_check(pot_wordlist)):
potter(pot_path, pot_wordlist)
outfile = valid.val_filepath... |
def main(argv):
if (len(argv) < 3):
usage()
model_dir = sys.argv[1]
data_file = sys.argv[2]
tokenizer = WordTokenizer()
tokenizer.load(os.path.join(model_dir, 'tokenizer'))
classifier = ProductClassifier()
classifier.load(os.path.join(model_dir, 'classifier'))
ner = ProductNER()
... |
def find_files_mentioning_zone(text):
IGNORED_PATHS = ['mobileapp/ios', 'mobileapp/android', 'node_modules', 'dist', 'archived']
VALID_EXTENSIONS = ('.py', '.js', '.jsx', '.ts', '.tsx', '.yaml', '.json', '.md', '.html')
results = []
for (root, dirs, files) in os.walk(ROOT_PATH):
if any([(ignored... |
def extractCleverneckohomeWpcomstagingCom(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,... |
def _format_instances(instances, namespace=None):
nested = isinstance(instances, dict)
if nested:
instances_dict = instances
vacuous = list()
case_map = dict()
instances = list()
for (case, instance_list) in sorted(instances_dict.items()):
case = '-'.join(case... |
def test_rsprfo_hcn_ts_xtb():
geom = geom_from_library('hcn_iso_ts.xyz', coord_type='redund')
xtb = XTB()
geom.set_calculator(xtb)
opt_kwargs = {'thresh': 'gau_tight', 'max_micro_cycles': 1}
opt = RSPRFOptimizer(geom, **opt_kwargs)
opt.run()
assert opt.is_converged
assert (opt.cur_cycle ... |
class SessionTester(Session):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.assets_js = []
self.assets_css = []
def send_command(self, *command):
if (command[0] == 'DEFINE'):
if ('JS' in command[1]):
(_, _, name, _) = comm... |
.parametrize('exclude_attrs, expected', [([], [{'id': '10', 'bu': 'a', 'env': 'prd'}]), (['bu'], [{'id': '10', 'env': 'prd'}]), (['bu', 'env'], [{'id': '10'}]), (['bu', 'env', 'not_there'], [{'id': '10'}])])
def test_load_with_exclude_attrs(exclude_attrs, one_acct_list, expected):
mal = acctload.MetaAccountLoader(o... |
def lru_cache(func):
cache = {}
(func)
def wrapped(*args):
key = []
bases = []
for arg in args:
if isinstance(arg, numpy.ndarray):
for base in _array_bases(arg):
if base.flags.writeable:
return func(*args)
... |
('/controllers')
def handle_controllers(self):
global TXBuffer, navMenuIndex
TXBuffer = ''
navMenuIndex = 2
if rpieGlobals.wifiSetup:
return self.redirect('/setup')
if (not isLoggedIn(self.get, self.cookie)):
return self.redirect('/login')
sendHeadandTail('TmplStd', _HEAD)
if... |
class TestAsyncProfiler():
.asyncio
async def test_profiler_is_a_transparent_wrapper(self):
f_called = False
async def f(x):
nonlocal f_called
f_called = True
return (x * 2)
profiler = driver.AsyncProfiler(f)
assert ((await profiler(1)) == 2)
... |
def test_map_pod_task_serialization():
pod = Pod(pod_spec=V1PodSpec(restart_policy='OnFailure', containers=[V1Container(name='primary')]), primary_container_name='primary')
(task_config=pod, environment={'FOO': 'bar'})
def simple_pod_task(i: int):
pass
mapped_task = map_task(simple_pod_task, met... |
def build_log_name(name: (str | None), addresses: list[str], connected_address: (str | None)) -> str:
preferred_address = connected_address
for address in addresses:
if (((not name) and address_is_local(address)) or host_is_name_part(address)):
name = address.partition('.')[0]
elif (... |
class OptionPlotoptionsGaugeSonificationDefaultspeechoptionsMappingVolume(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 Space(Plugin, metaclass=SpaceMeta):
BASE = ''
NAME = ''
SERIALIZE = ()
CHANNELS = ()
CHANNEL_ALIASES = {}
COLOR_FORMAT = True
GAMUT_CHECK = None
CLIP_SPACE = None
EXTENDED_RANGE = False
WHITE = (0.0, 0.0)
DYNAMIC_RANGE = 'sdr'
def __init__(self, **kwargs: Any) -> No... |
def generate_differing_bits(basename1, basename2):
with open(basename1, 'r') as path1:
with open(basename2, 'r') as path2:
diff = difflib.unified_diff(path1.read().splitlines(), path2.read().splitlines(), fromfile='path1', tofile='path2')
for line in diff:
if line.sta... |
class TestGetFastqGzFiles(unittest.TestCase):
def test_get_fastq_gz_files(self):
file_list = ['sample1.fastq.gz', 'sample2.fastq.gz', 'sample3.fastq', 'sample4.fastq', 'out.log', 'README']
expected = [('sample1.fastq.gz',), ('sample2.fastq.gz',)]
fastqgzs = GetFastqGzFiles('test', file_list=... |
class TestIntrospectionAction(unittest.TestCase):
maxDiff = 65000
def test_null_action_name(self):
action = IntrospectionAction(FakeServerOne())
with self.assertRaises(ActionError) as error_context:
action(EnrichedActionRequest(action='introspect', body={'action_name': None}))
... |
def _sortino_ratio(rets, risk_free=0.0, period=TRADING_DAYS_PER_YEAR):
mean = np.mean(rets, axis=0)
negative_rets = rets[(rets < 0)]
if (len(negative_rets) == 0):
dev = 0
else:
dev = np.std(negative_rets, axis=0)
if math.isclose(dev, 0):
sortino = 0
else:
sortino ... |
def parse_model_performance_report(model_performance_report: Dict) -> Dict:
assert (len(model_performance_report['metrics']) == 1)
quality_metric: Dict = model_performance_report['metrics'][0]
assert (quality_metric['metric'] == 'RegressionQualityMetric')
raw_quality_metric_result: Dict = quality_metric... |
class Number(RangeValidator):
messages = dict(number=_('Please enter a number'))
def _convert_to_python(self, value, state):
try:
value = float(value)
try:
int_value = int(value)
except OverflowError:
int_value = None
if (va... |
def filter_application_group_data(json):
option_list = ['application', 'behavior', 'category', 'comment', 'name', 'popularity', 'protocols', 'risk', 'technology', 'type', 'vendor']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and (json[... |
class Test_WindowSet():
def wset(self, *, wtable, event):
return WindowSet('k', wtable.table, wtable, event)
def test_constructor(self, *, event, table, wset, wtable):
assert (wset.key == 'k')
assert (wset.table is table)
assert (wset.wrapper is wtable)
assert (wset.event... |
def extractIclynnfrostHomeBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) i... |
class OptionSeriesWaterfallSonificationDefaultspeechoptions(Options):
def activeWhen(self) -> 'OptionSeriesWaterfallSonificationDefaultspeechoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesWaterfallSonificationDefaultspeechoptionsActivewhen)
def language(self):
return ... |
def test_recall_by_class_test() -> None:
test_dataset = pd.DataFrame({'target': ['a', 'a', 'a', 'b'], 'prediction': ['a', 'a', 'b', 'b']})
column_mapping = ColumnMapping(pos_label='a')
suite = TestSuite(tests=[TestRecallByClass(label='b', gt=0.8)])
suite.run(current_data=test_dataset, reference_data=Non... |
class TestEmptyTabFile(unittest.TestCase):
def test_make_empty_tabfile(self):
tabfile = TabFile()
self.assertEqual(len(tabfile), 0, 'new TabFile should have zero length')
def test_add_data_to_new_tabfile(self):
data = ['chr1', 10000, 20000, '+']
tabfile = TabFile()
tabfil... |
class TCPMappingTLSOriginationContextWithDotTest(AmbassadorTest):
extra_ports = [6789]
target: ServiceType
def init(self) -> None:
self.target = HTTP()
def manifests(self) -> str:
return (f'''
---
apiVersion: v1
kind: Secret
metadata:
name: {self.path.k8s}-clientcert
type: kubernetes.i... |
class SelectableListModel(QObject):
modelChanged = Signal()
selectionChanged = Signal()
def __init__(self, items):
QObject.__init__(self)
self._selection = {}
self._items = items
def getList(self):
return self._items
def isValueSelected(self, value):
return se... |
def test_correctly_decodes_random_large_matrices():
scores = np.array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.4744205], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.6448661], [0., 0., 0., 0.1424588, 0., 0., 0.9688441, 0., 0., 0.], [0., 0.... |
def _validate_init_params_and_return_if_found(module_class: Any) -> List[str]:
init_params_raw = list(inspect.signature(module_class.__init__).parameters)
module_init_params = [param for param in init_params_raw if (param not in ['self', 'args', 'kwargs'])]
if (len(module_init_params) > 1):
raise Un... |
class EyeTribe():
def __init__(self, logfilename='default', host='localhost', port=6555):
self._logfile = codecs.open('{}.tsv'.format(logfilename), 'w', 'utf-8')
self._separator = '\t'
self._log_header()
self._queue = Queue()
self._connection = connection(host=host, port=port... |
class WordWrapRenderer(AbstractTreeNodeRenderer):
padding = HasBorder(0)
width_hint = Int(100)
max_lines = Int(5)
extra_space = Int(8)
def paint(self, editor, node, column, object, paint_context):
(painter, option, index) = paint_context
text = self.get_label(node, object, column)
... |
def extractFallengodssanctuaryWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Eiyuu Seirei Musume', 'Chichi wa Eiyuu, Haha wa Seirei, Musume no Watashi wa Tenseish... |
def is_syncing(request):
def get(*args, **kwargs):
class Response():
def json(*args, **kwargs):
if request.param:
return REPLIES[1]
return REPLIES[0]
def status_code(self):
if (request.param == ERROR):
... |
class ApplicationType(Type):
_REQUIRED = {'key', 'title', 'urlconf', 'app_namespace'}
def __init__(self, **kwargs):
kwargs.setdefault('template_name', '')
kwargs.setdefault('regions', [])
kwargs.setdefault('app_namespace', (lambda instance: instance.page_type))
super().__init__(*... |
def test_add_logging_handle(tmpdir):
with tmpdir.as_cwd():
pm = ErtPluginManager(plugins=[dummy_plugins])
pm.add_logging_handle_to_root(logging.getLogger())
logging.critical('I should write this to spam.log')
with open('spam.log', encoding='utf-8') as fin:
result = fin.re... |
def deserialize_value(klass: Type[McapRecord], field: str, value: Any) -> Any:
field_type = klass.__dataclass_fields__[field].type
if (field_type == str):
return value
if (field_type == int):
return int(value)
if (field_type == bytes):
return bytes([int(v) for v in value])
if... |
class NumericUpDownControl(Widget):
DEFAULT_CSS = '\n NumericUpDownControl {\n height: 5;\n }\n NumericUpDownControl Button {\n min-width: 5;\n }\n\n NumericUpDownControl .value-holder {\n min-width: 2;\n border: thick $primary;\n text-style: bold;\n padding:... |
def parse_arguments():
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description='\nUses a BED file of domains or TAD boundaries to merge\nthe bin counts of a Hi-C matrix per TAD.\n\nThe output matrix contains the total counts per TAD and\nthe total contacts with all other T... |
class OptionSeriesAreasplinerangeMarkerStates(Options):
def hover(self) -> 'OptionSeriesAreasplinerangeMarkerStatesHover':
return self._config_sub_data('hover', OptionSeriesAreasplinerangeMarkerStatesHover)
def normal(self) -> 'OptionSeriesAreasplinerangeMarkerStatesNormal':
return self._config_... |
def extractTaekanWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Seiken Tsukai no World Break', 'Seiken Tsukai no World Break', 'translated'), ('rakudai kishi no e... |
class OptionSeriesVennSonificationTracksMappingRate(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._config... |
def recognize_column_type_(dataset: pd.DataFrame, column_name: str, columns: DatasetColumns) -> ColumnType:
column = dataset[column_name]
reg_condition = ((columns.task == 'regression') or (pd.api.types.is_numeric_dtype(column) and (columns.task != 'classification') and (column.nunique() > 5)))
if (column_n... |
def _download_and_copy(configured_logger: logging.Logger, cursor: psycopg2._psycopg.cursor, s3_client: BaseClient, s3_bucket_name: str, s3_obj_key: str, target_pg_table: str, ordered_col_names: List[str], gzipped: bool, partition_prefix: str=''):
start = time.time()
configured_logger.info(f'{partition_prefix}St... |
class AssetStore():
def __init__(self):
self._known_component_classes = set()
self._modules = {}
self._assets = {}
self._associated_assets = {}
self._data = {}
self._used_assets = set()
asset_reset = Asset('reset.css', RESET)
asset_loader = Asset('flex... |
def _save_svc_state(slave_vm, jsons):
service_state = None
for out in jsons:
if ('service_state' in out):
service_state = REPLICA_SERVICE_STATES.get(out['service_state'], SlaveVm.OFF)
if (service_state is not None):
slave_vm.sync_status = service_state
return service_state |
class OptionSeriesFunnelSonificationTracksMappingHighpassResonance(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 ProgressBar():
def __init__(self, description='', disabled=False):
self.progress = None
self.description = description
self.disabled = disabled
self.start = None
def init_progress(self, total):
if (self.progress is None):
self.start = time.time()
... |
def run_scenarios(scenario):
config['SimulationDirectory'] = ((config['SimulationDirectory'][:(- 8)] + scenario) + str('2015'))
if (scenario == 'Baseline_'):
config['NTC'] = (config['NTC'][:(- 8)] + '2018.csv')
elif ((scenario == 'Baseline_NTC_') or (scenario == 'TEMBA_Reference_') or (scenario == '... |
def compute(chart):
almutems = {}
hylegic = [chart.getObject(const.SUN), chart.getObject(const.MOON), chart.getAngle(const.ASC), chart.getObject(const.PARS_FORTUNA), chart.getObject(const.SYZYGY)]
for hyleg in hylegic:
row = newRow()
digInfo = essential.getInfo(hyleg.sign, hyleg.signlon)
... |
def pytest_generate_tests(metafunc):
if ('testvs' in metafunc.fixturenames):
global_sizes = [(35,), (((31 * 31) * 4),), (15, 13), (13, 35), (17, 15, 13), (5, 33, 75), (10, 10, 10, 5)]
local_sizes = [None, (4,), (2, 4), (6, 4, 2)]
mngs = [(26, 31), (34, 56, 25)]
mwiss = [(4, 4), (5, 3... |
def reduce_collection(collection, set=5, reducer='mean', scoreband='score'):
reducers = {'mean': ee.Reducer.mean(), 'median': ee.Reducer.median(), 'mode': ee.Reducer.mode(), 'interval_mean': ee.Reducer.intervalMean(50, 90), 'first': ee.Reducer.first()}
if (reducer in reducers.keys()):
selected_reducer =... |
class DocumentHasBinaryMetadata(models.Model):
id = models.AutoField(primary_key=True)
name = models.TextField(null=False)
document = models.ForeignKey(Document, null=False, related_name='binary_metadata', db_column='document_uuid', on_delete=models.CASCADE)
metadata = models.ForeignKey(BinaryMetadata, ... |
.django_db
def test_double_require(client, monkeypatch, elasticsearch_award_index, subaward_with_tas):
_setup_es(client, monkeypatch, elasticsearch_award_index)
resp = query_by_tas_subaward(client, {'require': [_fa_path(BASIC_TAS), _tas_path(BASIC_TAS)]})
assert (resp.json()['results'] == [_subaward1()]) |
def test_async_w3_ens_for_empty_ens_sets_w3_object_reference(local_async_w3):
assert local_async_w3.strict_bytes_type_checking
assert local_async_w3.ens.w3.strict_bytes_type_checking
assert (local_async_w3 == local_async_w3.ens.w3)
local_async_w3.strict_bytes_type_checking = False
assert (not local_... |
def filter_log_fortiguard_override_filter_data(json):
option_list = ['anomaly', 'dlp_archive', 'dns', 'filter', 'filter_type', 'forward_traffic', 'free_style', 'gtp', 'local_traffic', 'multicast_traffic', 'netscan_discovery', 'netscan_vulnerability', 'severity', 'sniffer_traffic', 'ssh', 'voip', 'ztna_traffic']
... |
('cuda.gemm_rrr.func_decl')
def gen_function_decl(func_attrs):
func_name = func_attrs['name']
input_ndims = len(func_attrs['input_accessors'][0].original_shapes)
weight_ndims = len(func_attrs['input_accessors'][1].original_shapes)
return common.FUNC_DECL_TEMPLATE.render(func_name=func_name, input_ndims=... |
class MsrBamBlock(nn.Module):
def __init__(self, conv=default_conv, n_feats=64):
super(MsrBamBlock, self).__init__()
kernel_size_1 = 3
kernel_size_2 = 5
self.conv_3_1 = conv(n_feats, n_feats, kernel_size_1)
self.conv_3_2 = conv((n_feats * 2), (n_feats * 2), kernel_size_1)
... |
('/report_bugs', methods=['GET', 'POST'])
def report_bugs():
if current_user.is_authenticated:
MAC_KEY = 'kfggfgiihuerbtjgrjrABCDD'
if (request.method == 'GET'):
bugs = Bug.query.filter((Bug.owner_id == current_user.id)).order_by(Bug.id.desc()).limit(100).all()
timeout = (int... |
class Auth(_common.FlyteIdlEntity):
def __init__(self, assumable_iam_role=None, kubernetes_service_account=None):
self._assumable_iam_role = assumable_iam_role
self._kubernetes_service_account = kubernetes_service_account
def assumable_iam_role(self):
return self._assumable_iam_role
... |
def make_header_lines(all_bits):
lines = []
bit_names = [('%d_%d' % (b[0], b[1])) for b in all_bits]
bit_len = 6
for i in range(bit_len):
line = ''
for j in range(len(all_bits)):
bstr = bit_names[j].ljust(bit_len).replace('_', '|')
line += bstr[i]
lines.ap... |
_models('spacy.Claude-2.v1')
def anthropic_claude_2(config: Dict[(Any, Any)]=SimpleFrozenDict(), name: Literal[('claude-2', 'claude-2-100k')]='claude-2', strict: bool=Anthropic.DEFAULT_STRICT, max_tries: int=Anthropic.DEFAULT_MAX_TRIES, interval: float=Anthropic.DEFAULT_INTERVAL, max_request_time: float=Anthropic.DEFAU... |
def test_adding_envs():
config = '\ndaemonset:\n extraEnvs:\n - name: LOG_LEVEL\n value: DEBUG\n'
r = helm_template(config)
assert ({'name': 'LOG_LEVEL', 'value': 'DEBUG'} in r['daemonset'][name]['spec']['template']['spec']['containers'][0]['env'])
assert ({'name': 'LOG_LEVEL', 'value': 'DEBUG'} no... |
def geti2cdevname(devaddr):
global I2CDevices
name = ''
for i in range(len(I2CDevices)):
if (int(devaddr) in I2CDevices[i]['addr']):
if (name != ''):
name += '; '
name += I2CDevices[i]['name']
if (name == ''):
name = 'Unknown'
return name |
class HTTPResponse():
status: int = 200
headers: HTTPHeaders = HTTPHeaders()
body: bytes = b''
def __post_init__(self):
if (self.headers is None):
self.headers = HTTPHeaders()
elif isinstance(self.headers, dict):
self.headers = HTTPHeaders.from_dict(self.headers)
... |
class LAMB(LARS):
def __init__(self, params, lr=0.001, beta1=0.9, beta2=0.999, eps=1e-08, weight_decay=0):
if (not (0.0 <= lr)):
raise ValueError('Invalid learning rate: {}'.format(lr))
if (not (0.0 <= eps)):
raise ValueError('Invalid epsilon value: {}'.format(eps))
i... |
class github_issue_0088_test_case(unittest.TestCase):
def test_flatten_without_keypath_separator(self):
d = benedict({'a': {'b': {'c': 1}}}, keypath_separator=None)
f = d.flatten('.')
self.assertEqual(f, {'a.b.c': 1})
def test_flatten_with_separator_equal_to_keypath_separator(self):
... |
class HCI(object):
HCI_CMD = 1
ACL_DATA = 2
SCO_DATA = 3
HCI_EVT = 4
HCI_UART_TYPE_STR = {HCI_CMD: 'HCI_CMD', ACL_DATA: 'ACL_DATA', SCO_DATA: 'SCO_DATA', HCI_EVT: 'HCI_EVT'}
def from_data(data):
uart_type = ord(data[0])
return HCI_UART_TYPE_CLASS[uart_type].from_data(data[1:])
... |
class Agent():
def __init__(self):
pass
def require_history(self):
return False
def __call__(self, state: DictTensor, input: DictTensor, user_info: DictTensor, history: TemporalDictTensor=None):
raise NotImplementedError
def update(self, info):
raise NotImplementedError
... |
def extractStudentcntranslationsWordpressCom(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, na... |
class TrafficLight(Html.Html):
name = 'Light'
tag = 'div'
def __init__(self, page: primitives.PageModel, color, label, height, tooltip, helper, options, profile, html_code: str=None):
super(TrafficLight, self).__init__(page, color, css_attrs={'width': height, 'height': height}, options=options, prof... |
class RoBERTaTokenizer(ByteBPETokenizer, LegacyFromHFHub):
vocab_files: Dict[(str, str)] = {'vocab': 'vocab.json', 'merges': 'merges.txt'}
def __init__(self, *, vocab: Dict[(str, int)], merges: List[Tuple[(str, str)]], special_pieces: Optional[Dict[(str, int)]]=None, bos_piece: str='<s>', eos_piece: str='</s>')... |
class LMQLContext():
def __init__(self, interpreter, state, prompt):
self.interpreter = interpreter
if state:
self.program_state: ProgramState = state.program_state
self.state = state
self.prompt = state.prompt
else:
self.program_state = Progra... |
class FlickerWalker():
def __init__(self, startView):
self.setCurrentView(startView)
def run(self):
self.keepRunning = True
initialAsync = lldb.debugger.GetAsync()
lldb.debugger.SetAsync(True)
while self.keepRunning:
charRead = sys.stdin.readline().rstrip('\n'... |
def test_robotstxt_test():
user_agents = ['Googlebot', 'Baiduspider', '*']
urls_to_check = ['/', '/help', 'something.html']
result = robotstxt_test(robots_file, user_agents, urls_to_check)
assert isinstance(result, pd.core.frame.DataFrame)
assert all(((col in result) for col in ['robotstxt_url', 'us... |
def get_function(reply: Dict, response_json: Dict):
try:
if ('function' not in response_json):
return ('Error:', "Missing 'function' object in JSON")
if (not isinstance(response_json, dict)):
return ('Error:', f"'response_json' object is not dictionary {response_json}")
... |
def count_coins_and_fragments(coins):
user_count = (max(coins) + 1)
coin_count = ([0] * user_count)
frag_count = ([0] * user_count)
for i in range(len(coins)):
coin_count[coins[i]] += 1
if ((i > 0) and (coins[i] != coins[(i - 1)])):
frag_count[coins[i]] += 1
return (coin_... |
('socket.create_connection')
def test_azure_metadata(mock_socket, monkeypatch):
class MockPoolManager():
def request(self, *args, **kwargs):
self.data = AZURE_DATA
return self
monkeypatch.setattr(urllib3, 'PoolManager', MockPoolManager)
metadata = elasticapm.utils.cloud.azure... |
class AsyncMinHashLSH(object):
def __init__(self, threshold: float=0.9, num_perm: int=128, weights: Tuple[(float, float)]=(0.5, 0.5), params: Tuple[(int, int)]=None, storage_config: Dict=None, prepickle: bool=None):
if (storage_config is None):
storage_config = {'type': 'aiomongo', 'mongo': {'ho... |
def interpolator(interpolator: str, create: type[Color], colors: Sequence[((ColorInput | stop) | Callable[(..., float)])], space: (str | None), out_space: (str | None), progress: ((Mapping[(str, Callable[(..., float)])] | Callable[(..., float)]) | None), hue: str, premultiplied: bool, extrapolate: bool, domain: (Vector... |
def load_config_files(paths):
raw_config = _read_config_files(paths)
tree_config1 = _arrange_config_tree(raw_config)
tree_config2 = _perform_key_renames(tree_config1)
complete_config = _build_node_section(tree_config2)
object_tree = _validate_and_convert(complete_config)
deref_config = _derefere... |
def serialize_css(obj: 'Color', func: str='', color: bool=False, alpha: (bool | None)=None, precision: (int | None)=None, fit: ((bool | str) | dict[(str, Any)])=True, none: bool=False, percent: (bool | Sequence[bool])=False, hexa: bool=False, upper: bool=False, compress: bool=False, name: bool=False, legacy: bool=False... |
class OptionPlotoptionsWaterfallSonificationDefaultinstrumentoptionsMappingVolume(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... |
class OptionSeriesItemSonificationDefaultspeechoptionsMappingPlaydelay(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 deprecated(instructions: str, is_property: bool=False, method_name: Optional[str]=None) -> Callable[([Callable[(..., Any)]], Any)]:
def decorator(func: Callable[(..., Any)]) -> Callable[([Callable[(..., Any)]], Any)]:
object_name = ('property' if is_property else 'function')
post_name = ('' if i... |
class SingletonHasTraits(HasTraits):
('SingletonHasTraits has been deprecated and will be removed in the future. Avoid using it')
def __new__(cls, *args, **traits):
if ('_the_instance' not in cls.__dict__):
cls._the_instance = HasTraits.__new__(cls, *args, **traits)
return cls._the_i... |
.django_db
def test_defc_date_filter(client, monkeypatch, elasticsearch_transaction_index):
defc1 = baker.make('references.DisasterEmergencyFundCode', code='L', public_law='PUBLIC LAW FOR CODE L', title='TITLE FOR CODE L', group_name='covid_19', earliest_public_law_enactment_date='2020-03-06')
baker.make('accou... |
def common_options(f):
for decorator in reversed([click.argument('database', type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False), required=True), click.argument('table', type=click.STRING, required=True), click.option('-l', '--location', type=click.STRING, default='{location}', help='Loca... |
def segment_dataset_config(db: Session, segment_connection_config: ConnectionConfig, segment_dataset: Dict[(str, Any)]) -> Generator:
fides_key = segment_dataset['fides_key']
segment_connection_config.name = fides_key
segment_connection_config.key = fides_key
segment_connection_config.save(db=db)
ct... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.