code stringlengths 281 23.7M |
|---|
def _read_from_stream(stream: (BytesIO | StringIO), size: (int | None), seek: (int | None)) -> Generator[(bytes, None, None)]:
was_at = stream.tell()
if (seek is not None):
stream.seek(seek)
try:
data = stream.read(size)
(yield (data if isinstance(data, bytes) else data.encode()))
... |
def test_optional_list_of_ints():
class Bob(TestSetup):
a: Optional[List[int]] = field(default_factory=list)
assert (Bob.setup('--a [1]') == Bob(a=[1]))
assert (Bob.setup('--a [1,2,3]') == Bob(a=[1, 2, 3]))
assert (Bob.setup('--a []') == Bob(a=[]))
assert (Bob.setup('') == Bob(a=[])) |
class ObjectNode(MultiValueTreeNodeObject):
def format_value(self, value):
try:
klass = value.__class__.__name__
except:
klass = '???'
return ('%s(0x%08X)' % (klass, id(value)))
def tno_has_children(self, node):
try:
return (len(self.value.__di... |
class Vk(IntervalModule):
API_LINK = '
app_id = 5160484
access_token = None
session = None
token_error = 'Vk: token error'
format = '{unread}/{total}'
interval = 1
color = '#ffffff'
color_unread = '#ffffff'
color_bad = '#ff0000'
settings = (('app_id', 'Id of your VK API app')... |
class Article(models.Model):
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
authors = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='')
category = models.ForeignKey(Category_Article, on_delete=models.CASCADE, verbose_name='')
title = models.CharField(max_length=100)
key... |
def getSpecialCase(specialcase):
log.info('Special case handler checking for deferred fetches.')
with FETCH_LOCK:
for key in RATE_LIMIT_ITEMS.keys():
if (RATE_LIMIT_ITEMS[key]['ntime'] < time.time()):
try:
(rid, joburl, netloc) = RATE_LIMIT_ITEMS[key]['que... |
class HistogramListStatsRequest(base_tests.SimpleProtocol):
def runTest(self):
request = ofp.message.bsn_generic_stats_request(name='histograms')
entries = get_stats(self, request)
names = []
for entry in entries:
self.assertEquals(1, len(entry.tlvs))
self.ass... |
class Vortex_phi(object):
def __init__(self, center=[0.5, 0.75, 0.5], radius=0.15):
self.radius = radius
self.center = center
def uOfX(self, X):
dx = (X[0] - self.center[0])
dy = (X[1] - self.center[1])
dBubble = (self.radius - sqrt(((dx ** 2) + (dy ** 2))))
retur... |
class OptionSeriesLineSonificationContexttracksMappingPan(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._... |
class CallResFrame(FrameWithArgs, CallFlags):
TYPE = 4
def __init__(self):
FrameWithArgs.__init__(self)
CallFlags.__init__(self)
self.code = 0
self.tracing = bytes(25)
self.headers = KVHeaders({}, 1)
self.csumtype = 0
def read_payload(self, fp: IOWrapper, size... |
class TestCTraitNotifiers(unittest.TestCase):
def test_notifiers_empty(self):
class Foo(HasTraits):
x = Int()
foo = Foo(x=1)
x_ctrait = foo.trait('x')
self.assertEqual(x_ctrait._notifiers(True), [])
def test_notifiers_on_trait(self):
class Foo(HasTraits):
... |
class UnionMeta(Meta):
def __getitem__(self, types):
types_in = types
if (not isinstance(types_in, tuple)):
types_in = (types_in,)
types = []
for type_ in types_in:
if isinstance(type_, str):
type_ = str2type(type_)
types.append(typ... |
def _tree_to_dict(config_file: str, pre_defines: Defines, tree: Tree[Instruction], schema: SchemaItemDict, site_config: Optional[ConfigDict]=None) -> ConfigDict:
config_dict = (site_config if site_config else {})
defines = pre_defines.copy()
config_dict['DEFINE'] = defines
errors = []
cwd = os.path.... |
def test_pytorch_task(serialization_settings: SerializationSettings):
(task_config=PyTorch(num_workers=10), cache=True, cache_version='1', requests=Resources(cpu='1'))
def my_pytorch_task(x: int, y: str) -> int:
return x
assert (my_pytorch_task(x=10, y='hello') == 10)
assert (my_pytorch_task.tas... |
class OptionsBasic(OptionsWithTemplates):
def bordered(self):
return self._config_get()
def bordered(self, flag):
if flag:
self.component.attr['class'].add('table-bordered')
else:
self.component.attr['class'].add('table-borderless')
def hover(self):
re... |
class OptionPlotoptionsOrganizationSonificationContexttracksPointgrouping(Options):
def algorithm(self):
return self._config_get('minmax')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bo... |
_set_stats_type(ofproto.OFPMP_GROUP_STATS, OFPGroupStats)
_set_msg_type(ofproto.OFPT_MULTIPART_REQUEST)
class OFPGroupStatsRequest(OFPMultipartRequest):
def __init__(self, datapath, flags=0, group_id=ofproto.OFPG_ALL, type_=None):
super(OFPGroupStatsRequest, self).__init__(datapath, flags)
self.grou... |
def search_get_image_arguments(provider_name: str) -> Dict:
if (provider_name == 'sentisight'):
project_id = '42874'
elif (provider_name == 'nyckel'):
project_id = 'yiilyy1cm0sxiw7n'
else:
raise NotImplementedError(f'Please add a project id for test arguments of provider: {provider_n... |
('/reports/<scanid>', methods=['GET'])
def report_alerts(scanid):
result = fetch_records(scanid)
styles = getSampleStyleSheet()
story = []
styleT = styles['Title']
styleB = styles['BodyText']
styleB.alignment = TA_LEFT
pTitle = Paragraph('<font size="18" color="darkblue">API Vulnerabilities ... |
def split_sequence(sequence, max_len):
seq = sequence.sequence
name = sequence.name
n_stretches = sorted(list(re.findall((('N{' + str(max_len)) + ',}'), seq)), cmp=(lambda x, y: cmp(len(x), len(y))), reverse=True)
for s in n_stretches:
seq = seq.replace(s, '_SPLIT-HERE_')
sequences = []
... |
class RMTTestReqClass(object):
def rmttest_positive_01(self):
(config, req) = create_parameters()
rt = ReqEffortEst(config)
(name, value) = rt.rewrite('EffortEstimation-test', req)
assert ('Effort estimation' == name)
assert (value is None)
def rmttest_positive_02(self):
... |
def _cast_ctx(context: Union[(Context, click.core.Context)]) -> Context:
if isinstance(context, Context):
return context
if isinstance(context, click.core.Context):
return cast(Context, context.obj)
raise AEAException('clean_after decorator should be used only on methods with Context or clic... |
class OptionSeriesPictorialDataEvents(Options):
def click(self):
return self._config_get(None)
def click(self, value: Any):
self._config(value, js_type=False)
def drag(self):
return self._config_get(None)
def drag(self, value: Any):
self._config(value, js_type=False)
... |
def test_invalid_geographic_region():
(w, e) = ((- 10), 10)
for (s, n) in [[(- 200), 90], [(- 90), 200]]:
with pytest.raises(ValueError):
longitude_continuity(None, [w, e, s, n])
(s, n) = ((- 10), 10)
for (w, e) in [[(- 200), 0], [0, 380]]:
with pytest.raises(ValueError):
... |
def cli(args=None):
parser = basic_argument_parser()
parser.add_argument('--predictor-path', type=str, help='Path (a directory) to the exported model that will be evaluated')
parser.add_argument('--num-threads', type=int, default=None, help="Number of omp/mkl threads (per process) to use in Caffe2's GlobalI... |
class InspectVisitor():
def process(self, instance: _Traversable):
try:
return getattr(self, 'visit_{}'.format(instance.__visit_name__))(instance)
except AttributeError as e:
raise RuntimeError('This visitor does not support {}'.format(type(instance))) from e |
def fuse_duplicate_fused_elementwise(sorted_graph: List[Tensor], _workdir: str) -> List[Tensor]:
fusion_groups = find_duplicate_fused_elementwise(sorted_graph)
for (primary_op, duplicate_ops) in fusion_groups.items():
for key in ('outputs', 'output_accessors'):
duplicate_ops_outputs = [outpu... |
_converter(acc_ops.full_like)
def acc_ops_full_like(target: Target, args: Tuple[(Argument, ...)], kwargs: Dict[(str, Argument)], name: str) -> ConverterOutput:
input_val = kwargs['input']
if (not isinstance(input_val, AITTensor)):
raise RuntimeError(f'Non-tensor inputs for {name}: {input_val}')
fill... |
class OptionSeriesItemSonificationDefaultinstrumentoptionsMappingGapbetweennotes(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, tex... |
.parametrize('model_meta,test_meta,expected', [(dict(attr='a'), None, ['a']), (dict(attr='a, b'), None, ['a', 'b']), (dict(), None, []), (dict(attr=['a']), None, ['a']), (dict(attr=['a', 'b']), None, ['a', 'b']), (dict(attr=['a', 'b', 'b']), None, ['a', 'b']), (dict(attr='a'), dict(attr='b'), ['a', 'b'])])
def test_get... |
class RWLockTestCase(unittest.TestCase):
def test_overrelease_read(self):
testLock = hamDb.BkHammingTree()
testLock.get_read_lock()
testLock.free_read_lock()
self.assertRaises(RuntimeError, testLock.free_read_lock)
def test_overrelease_write(self):
testLock = hamDb.BkHamm... |
class Object(AbstractSchemaNode):
attributes: Sequence[Union[(ExtractionSchemaNode, Selection, Object)]]
examples: Sequence[Tuple[(str, Union[(Sequence[Mapping[(str, Any)]], Mapping[(str, Any)])])]] = tuple()
def accept(self, visitor: AbstractVisitor[T], **kwargs: Any) -> T:
return visitor.visit_obj... |
def extractNextlevelforthePLOT(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not ((chp is not None) or (vol is not None) or (frag is not None))) or ('preview' in item['title'].lower())):
return None
if ('scan-trad' in item['tags']):
return None
t... |
def text_to_image_with_back(text, page_text, title):
font = ImageFont.truetype(fontpath, 28)
font_title = ImageFont.truetype('src/static/qmzl.ttf', 50)
font_page = ImageFont.truetype(fontpath, 30)
padding = 30
margin = 33
text_list = text.split('\n')
max_width = 0
(title_w, title_h) = fo... |
(params=[{'path_prefix': '', 'tenant_alias': 'default', 'client_alias': 'default_tenant', 'user_alias': 'regular', 'login_session_alias': 'default', 'registration_session_password_alias': 'default_password', 'registration_session_oauth_alias': 'default_oauth', 'session_token_alias': 'regular'}, {'path_prefix': '/second... |
def test_serializable_encoding_rlp_caching(rlp_obj):
assert (rlp_obj._cached_rlp is None)
rlp_code = encode(rlp_obj, cache=False)
assert (rlp_obj._cached_rlp is None)
assert (encode(rlp_obj, cache=True) == rlp_code)
assert (rlp_obj._cached_rlp == rlp_code)
rlp_obj._cached_rlp = b'test-uses-cache... |
_os(*metadata.platforms)
(MS_BUILD)
def main():
common.log('MsBuild Beacon')
(server, ip, port) = common.serve_web()
common.clear_web_cache()
common.log(('Updating the callback % (ip, port)))
target_task = 'tmp-file.csproj'
common.copy_file(common.get_path('bin', 'BadTasks.csproj'), target_task... |
class PoetryDependencyGetter(DependencyGetter):
def get(self) -> DependenciesExtract:
dependencies = self._get_poetry_dependencies()
self._log_dependencies(dependencies)
dev_dependencies = self._get_poetry_dev_dependencies()
self._log_dependencies(dev_dependencies, is_dev=True)
... |
class OptionPlotoptionsTreemapLevelsDatalabelsFilter(Options):
def operator(self):
return self._config_get(None)
def operator(self, value: Any):
self._config(value, js_type=False)
def property(self):
return self._config_get(None)
def property(self, text: str):
self._confi... |
def test_hic_transfer_pearson():
outfile = NamedTemporaryFile(suffix='pearson_.h5', delete=False)
outfile.close()
args = '--matrix {} --outFileName {} --method pearson'.format(original_matrix, outfile.name).split()
compute(hicTransform.main, args, 5)
test = hm.hiCMatrix((ROOT + 'hicTransform/pearson... |
def test_detail(app):
client = TestClient(app=app)
response = client.get('/admin/users/1')
assert (response.status_code == 200)
assert (response.template.name == 'dashboard/detail.html')
assert (response.text.count('Edit Row') == 1)
assert (response.text.count('Delete Row') == 2)
response = ... |
class DjangoTemplateSourceInstrumentation(AbstractInstrumentedModule):
name = 'django_template_source'
instrument_list = [('django.template.base', 'Parser.extend_nodelist')]
def call(self, module, method, wrapped, instance, args, kwargs):
ret = wrapped(*args, **kwargs)
if (len(args) > 1):
... |
_for(Repository, 'after_insert')
def receive_after_insert(mapper, connection, repo):
logger.debug(('auto creating env var for Repository: %s' % repo.name))
from stalker import defaults
os.environ[(defaults.repo_env_var_template % {'code': repo.code})] = repo.path
os.environ[(defaults.repo_env_var_templa... |
.django_db
def test_ignore_special_case():
baker.make(RecipientProfile, recipient_level='R', recipient_hash='00077a9a-5a70-8919-fd19-330762af6b85', recipient_unique_id=None, recipient_name='MULTIPLE RECIPIENTS', last_12_months=(- .0))
filters = {'limit': 10, 'page': 1, 'order': 'desc', 'sort': 'amount', 'award_... |
class OptionPlotoptionsPackedbubbleSonificationContexttracksPointgrouping(Options):
def algorithm(self):
return self._config_get('minmax')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bo... |
class Dataframe(object):
def __init__(self, keys=None, inputs=None, texts=None, values=None, features=None):
self.keys = keys
self.inputs = inputs
self.texts = texts
self.values = values
self.features = features
self._homogenize()
def _process(self, col, idx):
... |
class OptionPlotoptionsBarStatesSelect(Options):
def animation(self) -> 'OptionPlotoptionsBarStatesSelectAnimation':
return self._config_sub_data('animation', OptionPlotoptionsBarStatesSelectAnimation)
def borderColor(self):
return self._config_get('#000000')
def borderColor(self, text: str)... |
def group_qs_params(url):
purl = urlsplit(url)
qs = parse_qsl(purl.query)
nqs = list()
for t in reversed(qs):
if (t[0].endswith('[]') or (t[0] not in [f for (f, _) in nqs])):
nqs.append(t)
purl = purl._replace(query=join_qsl(reversed(nqs)))
return purl.geturl() |
def _pad_input_tensor(op: Operator, tensor_idx: int, f_extract_var_name: Callable[([int, int], str)], alignment_var_to_padding_length: Dict[(str, int)], tensor_list: List[Tensor]) -> None:
original_shape = op._attrs['inputs'][tensor_idx]._attrs['shape']
for (dim_idx, dim) in enumerate(original_shape):
t... |
class Config(BaseModel):
zmq_output_address: str
zmq_input_address: str
gpu_all: List[int]
health_check: HealthCheckerConfig
load_analyzer: LoadAnalyzerConfig
models: ModelsRunnerConfig
max_running_instances: int = 10
cloud_client: Union[(DockerConfig, KubeConfig)] = Field(choose_functio... |
def check(ip, domain, port, args, timeout, payload_map):
try:
socket.setdefaulttimeout(int(timeout))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, int(port)))
s.send((args + '\r\n').encode())
byte_result = s.recv(1024)
return ('Zookeeper\n' + by... |
class DistributedTrainingContext(object):
current_host: str
hosts: typing.List[str]
network_interface_name: str
(exceptions=KeyError, delay=1, tries=10, backoff=1)
def from_env(cls) -> DistributedTrainingContext:
curr_host = os.environ.get(SM_ENV_VAR_CURRENT_HOST)
raw_hosts = os.envi... |
def get_canon_types(is_jp: bool) -> Optional[list[str]]:
file_data = game_data_getter.get_file_latest('resLocal', 'CastleRecipeDescriptions.csv', is_jp)
if (file_data is None):
helper.error_text('Could not find CastleRecipeDescriptions.csv')
return None
data = csv_handler.parse_csv(file_data... |
class OFPPortModPropOptical(OFPPortModProp):
def __init__(self, type_=None, length=None, configure=None, freq_lmda=None, fl_offset=None, grid_span=None, tx_pwr=None):
self.type = type_
self.length = length
self.configure = configure
self.freq_lmda = freq_lmda
self.fl_offset =... |
def test_get_registrable_entities():
ctx = context_manager.FlyteContextManager.current_context().with_serialization_settings(flytekit.configuration.SerializationSettings(project='p', domain='d', version='v', image_config=flytekit.configuration.ImageConfig(default_image=flytekit.configuration.Image('def', 'docker.io... |
class Event():
def __init__(self) -> None:
self._event = threading.Event()
def set(self) -> None:
self._event.set()
def wait(self, timeout: Optional[float]=None) -> None:
if (timeout == float('inf')):
timeout = None
if (not self._event.wait(timeout=timeout)):
... |
def setup_to_pass_2():
with open('/etc/rsyslog.d/pytest.conf', 'w') as f:
f.writelines(['*.* action(type="omfwd" target="192.168.2.100" port="514" protocol="tcp"', ' action.resumeRetryCount="100"', ' queue.type="LinkedList" queue.size="1000")', ''])
(yield None)
os.remove('/etc/r... |
def write_sort_file(staging_dir, extension_priorities, sort_file):
for (dirpath, _dirname, filenames) in os.walk(staging_dir):
for filename in filenames:
fn = os.path.join(dirpath, filename)
for (idx, suffix) in enumerate(extension_priorities):
if fn.endswith(suffix):... |
class TestTupleTypeMiss():
def test_tuple_len_set(self, monkeypatch):
with monkeypatch.context() as m:
with pytest.raises(_SpockInstantiationError):
m.setattr(sys, 'argv', [''])
config = ConfigArgBuilder(TupleMixedTypeMiss, desc='Test Builder')
con... |
class Solution():
def maxProfit(self, prices: List[int]) -> int:
def get_transactions(prices):
if (len(prices) < 2):
return []
ret = []
start = prices[0]
for (i, price) in enumerate(prices):
if (i == 0):
cont... |
('cuda.gemm_rrr.gen_profiler')
def gen_profiler(func_attrs, workdir, profiler_filename, dim_info_dict):
output_addr_calculator = common.DEFAULT_OUTPUT_ADDR_CALCULATOR.render(stride_dim='N')
return common.gen_profiler(func_attrs=func_attrs, workdir=workdir, profiler_filename=profiler_filename, dim_info_dict=dim_... |
.use_numba
def test_potential_symmetry_cartesian():
point_mass = [1.1, 1.2, 1.3]
masses = [2670]
distance = 3.3
easting = (point_mass[0] * np.ones(6))
northing = (point_mass[1] * np.ones(6))
upward = (point_mass[2] * np.ones(6))
easting[0] += distance
easting[1] -= distance
northing[... |
def get_optimizer_cfg(lr, weight_decay=None, weight_decay_norm=None, weight_decay_bias=None, lr_mult=None):
runner = default_runner.Detectron2GoRunner()
cfg = runner.get_default_cfg()
if (lr is not None):
cfg.SOLVER.BASE_LR = lr
if (weight_decay is not None):
cfg.SOLVER.WEIGHT_DECAY = we... |
def test_contract_estimate_gas_with_arguments(w3, math_contract, estimate_gas, transact):
gas_estimate = estimate_gas(contract=math_contract, contract_function='add', func_args=[5, 6])
txn_hash = transact(contract=math_contract, contract_function='add', func_args=[5, 6])
txn_receipt = w3.eth.wait_for_transa... |
def extractShubham068JainWordpressCom(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_... |
class Rectangle(SVGItem):
name = 'SVG Rectangle'
tag = 'rect'
def __init__(self, page, x, y, width, height, fill, rx, ry):
super(Rectangle, self).__init__(page, '', css_attrs={'width': width, 'height': height})
self.set_attrs({'x': x, 'y': y, 'fill': fill, 'rx': rx, 'ry': ry})
self.c... |
def set_seeds_globally(seed: int, set_cudnn_determinism: bool, info_txt: str) -> None:
BColors.print_colored(f'Setting random seed globally to: {seed} - {info_txt}', BColors.OKGREEN)
random.seed(seed)
torch.random.manual_seed(seed)
np.random.seed(seed)
if set_cudnn_determinism:
if hasattr(to... |
class Task(UserControl):
def __init__(self, task_name, task_delete):
super().__init__()
self.task_name = task_name
self.task_delete = task_delete
def build(self):
self.display_task = Checkbox(value=False, label=self.task_name)
self.edit_name = TextField(expand=1)
... |
def _compute_workspace(sorted_graph: List[Tensor]) -> Workspace:
unique_workspace_size = 0
max_workspace = 0
for node in sorted_graph:
for func in node._attrs['src_ops']:
if ('workspace' in func._attrs):
max_workspace = max(max_workspace, func._attrs['workspace'])
... |
def test_rf_better_than_dt(dummy_titanic):
(X_train, y_train, X_test, y_test) = dummy_titanic
dt = DecisionTree(depth_limit=10)
dt.fit(X_train, y_train)
rf = RandomForest(depth_limit=10, num_trees=7, col_subsampling=0.8, row_subsampling=0.8)
rf.fit(X_train, y_train)
pred_test_dt = dt.predict(X_t... |
class WaterBuilder():
def __init__(self, space=3.0, bond_dist=1.85, pcharge=0.0, residue='WAT', ATYPE='W', verbose=False):
self.space = space
self.bond_dist = bond_dist
self.pcharge = pcharge
self.residue = residue
self.ATYPE = ATYPE
self.verbose = verbose
def ato... |
def test_current_case(qtbot, notifier, storage):
ensemble = storage.create_experiment().create_ensemble(name='default', ensemble_size=1)
widget = CaseSelector(notifier)
qtbot.addWidget(widget)
assert (widget.count() == 0)
notifier.set_storage(storage)
notifier.set_current_case(ensemble)
asse... |
class OptionPlotoptionsBarSonificationTracksPointgrouping(Options):
def algorithm(self):
return self._config_get('minmax')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
sel... |
class Encoder(hk.Module):
def __init__(self, num_layers=4, num_filters=32, activation=jax.nn.relu):
super().__init__()
self.num_layers = num_layers
self.num_filters = num_filters
self._activation = activation
def __call__(self, x):
x = (x.astype(jnp.float32) / 255.0)
... |
def valid_port_range(user_input: str) -> range:
if ('-' not in user_input):
raise ArgumentTypeError("Port range must contain two integers separated by '-'")
(a, b) = user_input.split('-')
(port_a, port_b) = (convert_port(a), convert_port(b))
if (port_b < port_a):
raise ArgumentTypeError(... |
class SpacesRecordingWrapper(Wrapper[MazeEnv]):
def __init__(self, env: Union[(gym.Env, MazeEnv)], output_dir: str='space_records'):
super().__init__(env)
self.episode_record: Optional[SpacesTrajectoryRecord] = None
self.last_observation = Optional[ObservationType]
self.last_env_time... |
class SpanCoTExample(FewshotExample, abc.ABC):
text: str
spans: List[SpanReason]
def _extract_span_reasons(spans: Iterable[Span]) -> List[SpanReason]:
span_reasons: List[SpanReason] = []
for span in spans:
span_reasons.append(SpanReason(text=span.text, is_entity=True, label=span.... |
class OptionPlotoptionsPolygonStatesSelectHalo(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def opacity(self):
return self._config_get(0.25)
def opacity(self, num: float):
self._config(n... |
class TupleMeta(Meta):
def __getitem__(self, types):
if (not isinstance(types, tuple)):
types = (types,)
trans_types = []
for type_in in types:
if isinstance(type_in, str):
type_in(str2type(type_in))
trans_types.append(type_in)
retu... |
class bsn_debug_counter_desc_stats_request(bsn_stats_request):
version = 6
type = 18
stats_type = 65535
experimenter = 6035143
subtype = 13
def __init__(self, xid=None, flags=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags !... |
class RelationshipMemberWafRuleRevision(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
... |
class TestClass():
def test_declaration(self, class_book: Struct, record_id: Union):
assert (class_book.declaration() == 'class ClassBook {\n\tchar * title;\n\tint num_pages;\n\tchar * author;\n}')
class_book.add_member((m := ComplexTypeMember(size=64, name='id', offset=12, type=record_id)))
... |
class OptionSeriesSunburstStatesInactive(Options):
def animation(self) -> 'OptionSeriesSunburstStatesInactiveAnimation':
return self._config_sub_data('animation', OptionSeriesSunburstStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
... |
class OptionSeriesTimelineDatalabels(Options):
def align(self):
return self._config_get('center')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(True)
def allowOverlap(self, flag: bool):
self._config(flag, js_... |
def monthly_download_data(db, monkeypatch):
for js in JOB_STATUS:
baker.make('download.JobStatus', job_status_id=js.id, name=js.name, description=js.desc)
baker.make('references.ToptierAgency', toptier_agency_id=1, toptier_code='001', name='Test_Agency', _fill_optional=True)
baker.make('references.A... |
def get_recognizer_image_generator(labels, height, width, alphabet, augmenter=None, shuffle=True):
n_with_illegal_characters = sum((any(((c not in alphabet) for c in text)) for (_, _, text) in labels))
if (n_with_illegal_characters > 0):
print(f'{n_with_illegal_characters} / {len(labels)} instances have... |
def aggregate(aggregate_type, factory_a, factory_b):
if (aggregate_type == 'empty'):
return providers.Aggregate()
elif (aggregate_type == 'non-string-keys'):
return providers.Aggregate({ExampleA: factory_a, ExampleB: factory_b})
elif (aggregate_type == 'default'):
return providers.Ag... |
class SCULPT_OT_push_undo(bpy.types.Operator):
bl_idname = 'sculpt.push_undo'
bl_label = 'Push Undo'
bl_description = 'Pushes an undo step in Sculpt mode'
bl_options = {'INTERNAL', 'UNDO'}
def poll(cls, context):
sculpt_object = context.sculpt_object
return (sculpt_object and (sculpt... |
def test_ngram_sentence_suggester():
nlp = spacy.blank('en')
text = 'The first sentence. The second sentence. And the third sentence.'
sents = [True, False, False, False, True, False, False, False, True, False, False, False, False]
tokenized = nlp(text)
spaces = [bool(t.whitespace_) for t in tokeniz... |
class BlockProcessor():
def __init__(self, parser):
self.parser = parser
self.tab_length = parser.md.tab_length
def lastChild(self, parent):
if len(parent):
return parent[(- 1)]
else:
return None
def detab(self, text):
newtext = []
line... |
def extractAjrgWordpressCom(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) in t... |
def arith(res_type, op, args):
target = get_db().target
arg_codes = list(args)
if (res_type == T.string):
assert (op == '+')
op = '||'
if (target is mysql):
return FuncCall(res_type, 'concat', arg_codes)
elif (op == '/'):
if (target != mysql):
arg_... |
def validate_provider_ids(provider_ids, required=False):
if (not provider_ids):
if required:
raise ValueError('Invalid provider IDs. Provider ids should be provided')
return []
for provider_id in provider_ids:
validate_provider_id(provider_id, True)
return provider_ids |
class Test_utils(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_hex_array_string(self):
expected_result = '0x01 0x02 0x03 0x04'
data = b'\x01\x02\x03\x04'
eq_(expected_result, utils.hex_array(data))
def test_hex_array_bytearray(self):
... |
(os.environ, {'FIDES__CONFIG_PATH': 'tests/ctl/test_default_config.toml'}, clear=True)
.unit
def test_get_config_default() -> None:
config = get_config()
assert (config.database.api_engine_pool_size == 50)
assert (config.security.env == 'dev')
assert (config.security.app_encryption_key == '')
assert... |
.usefixtures('use_tmpdir')
def test_that_quotations_in_forward_model_arglist_are_handled_correctly():
'This is a regression test, making sure that quoted strings behave consistently.\n They should all result in the same.\n See
test_config_file_name = 'test.ert'
test_config_contents = dedent('\n NU... |
def test_reaction_as_decorator_of_other_cls():
class C1(event.Component):
foo = event.AnyProp(settable=True)
c1 = C1()
class C2(event.Component):
.reaction('foo')
def on_foo(self, *events):
print('x')
self.xx = events[(- 1)].new_value
c2 = C2()
loop.it... |
def _extract_images(response):
page_has_images = response.xpath('//img')
if page_has_images:
img_df = pd.DataFrame([x.attrib for x in response.xpath('//img')])
if ('src' in img_df):
img_df['src'] = [response.urljoin(url) for url in img_df['src']]
img_df = img_df.apply((lambda... |
def test_llm_prompt_generations_response():
testutil.add_response('login_response_200')
testutil.add_response('api_version_response_v58_200')
testutil.add_response('einstein_llm_prompt_generations_200')
client = testutil.get_client()
prompt_request_body = {'promptTextorId': "I'm writing code in the ... |
class DummyStageFlowStatus(Enum):
STAGE_1_INITIALIZED = auto()
STAGE_1_STARTED = auto()
STAGE_1_COMPLETED = auto()
STAGE_1_FAILED = auto()
STAGE_2_INITIALIZED = auto()
STAGE_2_STARTED = auto()
STAGE_2_COMPLETED = auto()
STAGE_2_FAILED = auto()
STAGE_3_INITIALIZED = auto()
STAGE_3... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.