code stringlengths 281 23.7M |
|---|
class OptionPlotoptionsArearangeSonificationContexttracksMappingPan(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 test_strict_allow_default_bug():
'
schema = {'namespace': 'namespace', 'name': 'name', 'type': 'record', 'fields': [{'name': 'some_field', 'type': 'string', 'default': 'test'}]}
test_record = {'eggs': 'eggs'}
with pytest.raises(ValueError, match='record contains more fields .*? eggs'):
round... |
class SVSession(RPCSession):
ca_path = certifi.where()
_connecting_tips: Dict[(bytes, asyncio.Event)] = {}
_need_checkpoint_headers = True
_subs_by_account: Dict[('AbstractAccount', List[str])] = {}
_keyinstance_map: Dict[(str, Tuple[(int, ScriptType)])] = {}
def __init__(self, network, server, ... |
((MAGICK_VERSION_NUMBER < 1801), reason='Trim by percent-background requires ImagesMagick-7.0.9')
def test_trim_percent_background():
with Image(filename='wizard:') as img:
was = img.size
img.trim(fuzz=0.0, percent_background=0.5, background_color='white')
assert (img.size != was) |
def span_position_distance_breakends(candidate1, candidate2):
(candidate1_hap, candidate1_pos1, candidate1_dir1, candidate1_pos2, candidate1_dir2) = candidate1
(candidate2_hap, candidate2_pos1, candidate2_dir1, candidate2_pos2, candidate2_dir2) = candidate2
if (candidate1_hap != candidate2_hap):
if ... |
def extractTrialntriedWordpressCom(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_typ... |
class OptionPlotoptionsColumnpyramidSonificationContexttracksMappingNoteduration(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... |
((API + '.get_dataset_identity'), MagicMock(return_value={'dataset_rid': DATASET_RID, 'dataset_path': DATASET_PATH, 'last_transaction_rid': TRANSACTION_RID, 'last_transaction': {'rid': TRANSACTION_RID, 'transaction': {'record': {'view': True}, 'metadata': {'fileCount': 1, 'hiddenFileCount': 0, 'totalFileSize': 0, 'tota... |
class TraceIDMiddleware(BaseHTTPMiddleware):
def __init__(self, app: ASGIApp, trace_context_var: ContextVar[TracerContext], tracer: Tracer, root_operation_name: str='DB-GPT-Web-Entry', include_prefix: str='/api', exclude_paths=_DEFAULT_EXCLUDE_PATHS):
super().__init__(app)
self.trace_context_var = t... |
def test_set_check_modes(tfm):
tfm = SpectralModel(verbose=False)
tfm.set_check_modes(False, False)
assert (tfm._check_freqs is False)
assert (tfm._check_data is False)
freqs = np.array([1, 2, 4])
powers = np.array([1, 2, 3])
tfm.add_data(freqs, powers)
assert tfm.has_data
freqs = ge... |
class BucketWorker(Thread):
def __init__(self, q, *args, **kwargs):
self.q = q
self.use_aws = (CONFIG['aws_access_key'] and CONFIG['aws_secret'])
if self.use_aws:
self.session = Session(aws_access_key_id=CONFIG['aws_access_key'], aws_secret_access_key=CONFIG['aws_secret']).resour... |
def processJsStacktrace(stack, allowInternal=False):
lines = []
message_line = ''
error_line = ''
found_main_line = False
stacks = (stack if (type(stack) is list) else stack.split('\n'))
for line in stacks:
if (not message_line):
message_line = line
if allowInternal:
... |
def test_new_awards_only_transaction_search_time_period():
default_start_date = '1111-11-11'
default_end_date = '9999-99-99'
transaction_search = TransactionSearchTimePeriod(default_start_date=default_start_date, default_end_date=default_end_date)
transaction_search_decorator = NewAwardsOnlyTimePeriod(t... |
def get_and_save_remote_with_click_context(ctx: click.Context, project: str, domain: str, save: bool=True, data_upload_location: Optional[str]=None) -> FlyteRemote:
if (ctx.obj.get(FLYTE_REMOTE_INSTANCE_KEY) is not None):
return ctx.obj[FLYTE_REMOTE_INSTANCE_KEY]
cfg_file_location = ctx.obj.get(CTX_CONF... |
class SummaryExtractor(Extractor):
def __init__(self, model_name: str=None, llm_metadata: LLMMetadata=None):
self.model_name = (model_name,)
self.llm_metadata = ((llm_metadata or LLMMetadata),)
async def extract(self, chunks: List[Document]) -> str:
texts = [doc.page_content for doc in c... |
.asyncio
.workspace_host
class TestUserPermissions():
async def test_unauthorized(self, unauthorized_dashboard_assertions: HTTPXResponseAssertion, test_client_dashboard: test_data: TestData):
response = (await test_client_dashboard.get(f"/users/{test_data['users']['regular'].id}/permissions"))
unau... |
def generate_tiles(options: argparse.Namespace) -> None:
directory: Path = workspace.get_tile_path()
zoom_levels: list[int] = parse_zoom_level(options.zoom)
min_zoom_level: int = min(zoom_levels)
scheme: Scheme = Scheme.from_file(workspace.find_scheme_path(options.scheme))
if options.input_file_name... |
def ert_config_values(draw, use_eclbase=booleans):
queue_system = draw(queue_systems)
install_jobs = draw(small_list(random_forward_model_names(words, file_names)))
forward_model = (draw(small_list(job(install_jobs))) if install_jobs else [])
simulation_job = (draw(small_list(sim_job(install_jobs))) if ... |
class UnitSquareRotation(TransportCoefficients.TC_base):
from proteus.ctransportCoefficients import unitSquareRotationEvaluate
def __init__(self):
mass = {0: {0: 'linear'}}
advection = {0: {0: 'linear'}}
diffusion = {}
potential = {}
reaction = {}
hamiltonian = {}... |
class TestNotificationService():
def test_service(self, reset_and_start_fledge, service_branch, fledge_url, wait_time, retries, remove_directories):
_configure_and_start_service(service_branch, fledge_url, remove_directories)
retry_count = 0
default_registry_count = 2
service_registr... |
_metaclass(abc.ABCMeta)
class BaseRedisClient(object):
DEFAULT_RECEIVE_TIMEOUT = 5
RESPONSE_QUEUE_SPECIFIER = '!'
def __init__(self, ring_size):
self.metrics_counter_getter = None
self._ring_size = ring_size
self._connection_index_generator = itertools.cycle(random.sample(range(self.... |
class TestMarkdownChained(util.PluginTestCase):
def setup_fs(self):
config = self.dedent("\n matrix:\n - name: markdown\n sources:\n - '{}/**/*.txt'\n aspell:\n lang: en\n d: en_US\n hunspell:\n ... |
def extractVasaandypresWordpressCom(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_ty... |
class DenseBlock(ShapeNormalizationBlock):
def __init__(self, in_keys: Union[(str, List[str])], out_keys: Union[(str, List[str])], in_shapes: Union[(Sequence[int], List[Sequence[int]])], hidden_units: List[int], non_lin: Union[(str, type(nn.Module))]):
super().__init__(in_keys=in_keys, out_keys=out_keys, in... |
class OptionPlotoptionsArearangeOnpoint(Options):
def connectorOptions(self) -> 'OptionPlotoptionsArearangeOnpointConnectoroptions':
return self._config_sub_data('connectorOptions', OptionPlotoptionsArearangeOnpointConnectoroptions)
def id(self):
return self._config_get(None)
def id(self, te... |
class mlfbf(primal_dual):
def _pre(self, functions, x0):
super(mlfbf, self)._pre(functions, x0)
if (len(functions) != 3):
raise ValueError('MLFBF requires 3 convex functions.')
self.non_smooth_funs.append(functions[0])
self.non_smooth_funs.append(functions[1])
sel... |
class TestGlobEscapes(unittest.TestCase):
def check_escape(self, arg, expected, raw=False, unix=None, raw_chars=True):
flags = 0
if (unix is False):
flags = glob.FORCEWIN
elif (unix is True):
flags = glob.FORCEUNIX
if raw:
self.assertEqual(glob.raw... |
(scope='function')
def friendbuy_nextgen_secrets(saas_config):
return {'domain': (pydash.get(saas_config, 'friendbuy_nextgen.domain') or secrets['domain']), 'key': (pydash.get(saas_config, 'friendbuy_nextgen.key') or secrets['key']), 'secret': (pydash.get(saas_config, 'friendbuy_nextgen.secret') or secrets['secret'... |
def c_generate_convenience_functions(module_name, name, feature_type='int16_t', clasification_return_type='int16_t'):
predict_function = f'''
{clasification_return_type}
{name}_predict(const {feature_type} *features, int32_t n_features)
{{
return {module_name}_predict(&{name}, features, n_featur... |
class Dolly(HuggingFace):
MODEL_NAMES = Literal[('dolly-v2-3b', 'dolly-v2-7b', 'dolly-v2-12b')]
def init_model(self) -> Any:
return transformers.pipeline(model=self._name, return_full_text=False, **self._config_init)
def __call__(self, prompts: Iterable[str]) -> Iterable[str]:
return [self._... |
class DBID():
__slots__ = ['_id', 'is_new', 'local_id']
next_id: int = 0
def __init__(self, id: Union[(int, None, DBID)]=None) -> None:
self.resolve(id)
self.local_id: int = DBID.next_id
DBID.next_id += 1
def resolve(self, id: Union[(int, None, DBID)], is_new: bool=True) -> DBID:... |
class TestOFPInstructionGotoTable(unittest.TestCase):
type_ = ofproto.OFPIT_GOTO_TABLE
len_ = ofproto.OFP_INSTRUCTION_GOTO_TABLE_SIZE
fmt = ofproto.OFP_INSTRUCTION_GOTO_TABLE_PACK_STR
def test_init(self):
table_id = 3
c = OFPInstructionGotoTable(table_id)
eq_(self.type_, c.type)
... |
class speed_checker(object):
def __init__(self, cnt=5):
self.cnt = cnt
self.speed_buffer = []
self.reset()
def check(self, l):
self.current_bytes += l
self.current_tm = time.time()
if ((self.current_tm - self.last_tm) > 1):
self.speed_buffer.append(((s... |
class OptionSeriesColumnpyramidSonificationTracksMappingLowpass(Options):
def frequency(self) -> 'OptionSeriesColumnpyramidSonificationTracksMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionSeriesColumnpyramidSonificationTracksMappingLowpassFrequency)
def resonance(self) -> 'Opt... |
class OptionSeriesDependencywheelSonificationDefaultinstrumentoptionsMappingGapbetweennotes(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 mapT... |
def _solve_bezier(target: float, a: float, b: float, c: float) -> float:
x = 0.0
t = 0.5
last = alg.nan
for _ in range(MAX_ITER):
x = (_bezier(t, a, b, c) - target)
dx = _bezier_derivative(t, a, b, c)
if (dx == 0):
break
t -= (x / dx)
if (t == last):
... |
class AnalysisPlugin(AnalysisBasePlugin):
NAME = 'tlsh'
DESCRIPTION = 'find files with similar tlsh and calculate similarity value'
DEPENDENCIES = ['file_hashes']
VERSION = '0.2'
FILE = __file__
def __init__(self, *args, **kwargs):
self.db = TLSHInterface()
super().__init__(*args... |
_parameters()
(name='daily_buckets', time_bucket={'period': 'day', 'count': 1}, dates_step=timedelta(days=1))
(name='six_hour_buckets', time_bucket={'period': 'hour', 'count': 6}, dates_step=timedelta(hours=6))
def test_exclude_specific_dates(test_id: str, dbt_project: DbtProject, time_bucket: dict, dates_step: timedel... |
def get_note_delete_confirm_modal_html(nid: int) -> Optional[HTML]:
note = get_note(nid)
if (not note):
return None
title = utility.text.trim_if_longer_than(note.get_title(), 100)
priority = note.priority
if ((priority is None) or (priority == 0)):
priority = '-'
fg = 'black'... |
('/knowledge/space/add')
def space_add(request: KnowledgeSpaceRequest):
print(f'/space/add params: {request}')
try:
knowledge_space_service.create_knowledge_space(request)
return Result.succ([])
except Exception as e:
return Result.failed(code='E000X', msg=f'space add error {e}') |
.skipif((django.VERSION < (1, 10)), reason='MIDDLEWARE new in Django 1.10')
def test_user_info_without_auth_middleware_django_2(django_elasticapm_client, client):
with override_settings(MIDDLEWARE_CLASSES=None, MIDDLEWARE=[m for m in settings.MIDDLEWARE if (m != 'django.contrib.auth.middleware.AuthenticationMiddlew... |
class TestCUSUM(unittest.TestCase):
def test_various_data(self):
with open((settings.APPS_ROOT + '/frontend/tests/fixtures/alert_test_cases.txt')) as expected:
test_cases = expected.readlines()
for test in each_cusum_test(test_cases):
cusum = bookmark_utils.CUSUM(test['data']... |
def upgrade():
op.create_table('submissions', sa.Column('id', sa.Integer(), nullable=False), sa.Column('submitted_at', sa.DateTime(), nullable=True), sa.Column('form_id', sa.Integer(), nullable=True), sa.Column('data', postgresql.JSON(), nullable=True), sa.ForeignKeyConstraint(['form_id'], ['forms.id']), sa.Primary... |
class EnsureRenderedStringPattern(PropertyPreprocessor):
type = 'ensure_rendered_string_pattern'
properties_schema_cls = EnsureRenderedStringPatternSchema
def process_arg(self, arg, node, raw_args):
regex = None
try:
regex = re.compile(self.pattern)
except Exception:
... |
class AccountingMethodIterator():
def __init__(self, acquired_lot_list: List[InTransaction], up_to_index: int, order_type: AcquiredLotCandidatesOrder) -> None:
self.__acquired_lot_list = acquired_lot_list
self.__start_index = (0 if (order_type == AcquiredLotCandidatesOrder.OLDER_TO_NEWER) else up_to... |
class TextOverviewPreset(MetricPreset):
column_name: str
def __init__(self, column_name: str, descriptors: Optional[Dict[(str, FeatureDescriptor)]]=None):
super().__init__()
self.column_name = column_name
self.descriptors = descriptors
def generate_metrics(self, data_definition: Data... |
def rebuild_index():
from redis.commands.search.field import TextField
from redis.commands.search.indexDefinition import IndexDefinition
from redis.exceptions import ResponseError
r = frappe.cache()
r.set_value('wiki_page_index_in_progress', True)
schema = (TextField('title', weight=3.0), TextFi... |
_type(OSPF_MSG_HELLO)
class OSPFHello(OSPFMessage):
_PACK_STR = '!4sHBBI4s4s'
_PACK_LEN = struct.calcsize(_PACK_STR)
_MIN_LEN = (OSPFMessage._HDR_LEN + _PACK_LEN)
def __init__(self, length=None, router_id='0.0.0.0', area_id='0.0.0.0', au_type=1, authentication=0, checksum=None, version=_VERSION, mask='0... |
class GlobalConstantNewton(proteus.NonlinearSolvers.NonlinearSolver):
def __init__(self, linearSolver, F, J=None, du=None, par_du=None, rtol_r=0.0001, atol_r=1e-16, rtol_du=0.0001, atol_du=1e-16, maxIts=100, norm=l2Norm, convergenceTest='r', computeRates=True, printInfo=True, fullNewton=True, directSolver=False, EW... |
def get_level_from_xp(shrine_xp: int, is_jp: bool) -> Optional[dict[(str, Any)]]:
xp_requirements = get_boundaries(is_jp)
if (xp_requirements is None):
return None
level = 1
for requirement in xp_requirements:
if (shrine_xp >= requirement):
level += 1
if (level > len(xp_r... |
_server.peripheral_model
class IEEE802_15_4(object):
IRQ_NAME = '802_15_4_RX_Frame'
frame_queue = deque()
calc_crc = True
rx_frame_isr = None
rx_isr_enabled = False
frame_time = deque()
def enable_rx_isr(cls, interface_id):
cls.rx_isr_enabled = True
if (cls.frame_queue and (c... |
def extractAlmightyEditorBplacedNet(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Isekai Tensei Harem', 'Isekai Tensei Harem', 'translated'), ('PRC', 'PRC', 'translated'), ('... |
def test_kronos_device_creation(client: TestClient):
from tests.test_database_models import SAMPLE_DEVICE_HID, SAMPLE_DEVICE
response = client.post('/api/v1/kronos/devices', json=SAMPLE_DEVICE)
assert (response.status_code == 200)
assert (response.json() == {'hid': SAMPLE_DEVICE_HID, 'links': {}, 'messa... |
class MT48LC16M16(SDRModule):
nbanks = 4
nrows = 8192
ncols = 512
technology_timings = _TechnologyTimings(tREFI=(.0 / 8192), tWTR=(2, None), tCCD=(1, None), tRRD=(None, 15))
speedgrade_timings = {'default': _SpeedgradeTimings(tRP=20, tRCD=20, tWR=15, tRFC=(None, 66), tFAW=None, tRAS=44)} |
class Vulnerability():
def __init__(self, rule, description, reliability, score, link, short_name):
try:
self.reliability = str(int(reliability))
self.score = score
self.description = description
self.rule = rule
self.link = link
self.s... |
class OptionSeriesArcdiagramStatesSelectMarker(Options):
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def enabledThreshold(self):
return self._config_get(2)
def enabledThreshold(self, num: float):
self._... |
def DoExpandDim(alloc_cursor, alloc_dim, indexing):
alloc_s = alloc_cursor._node
assert isinstance(alloc_s, LoopIR.Alloc)
assert isinstance(alloc_dim, LoopIR.expr)
assert isinstance(indexing, LoopIR.expr)
Check_IsPositiveExpr(alloc_cursor.get_root(), [alloc_s], alloc_dim)
old_typ = alloc_s.type
... |
class KeystoreCrypto(BytesDataclass):
kdf: KeystoreModule = KeystoreModule()
checksum: KeystoreModule = KeystoreModule()
cipher: KeystoreModule = KeystoreModule()
def from_json(cls, json_dict: Dict[(Any, Any)]) -> 'KeystoreCrypto':
kdf = KeystoreModule(**json_dict['kdf'])
checksum = Keys... |
class SuperCollider(Instrument):
NAME = 'supercollider'
def __init__(self, args):
Instrument.__init__(self, SuperCollider.NAME)
self.initialized = False
def enable(self):
self.initialized = True
def enabled(self):
return self.enabled
def supported(self):
retur... |
class LCInfo():
def __init__(self, locale, currency, columns):
self.columns = columns
if (locale == 'en_US'):
headers = ['Date', 'Description', 'Change']
self.datefmt = '{0.month:02}/{0.day:02}/{0.year:04}'
self.cur_fmt = '{}{}{}{}'
self.lead_neg = '('... |
class AdCreativeCollectionThumbnailInfo(AbstractObject):
def __init__(self, api=None):
super(AdCreativeCollectionThumbnailInfo, self).__init__()
self._isAdCreativeCollectionThumbnailInfo = True
self._api = api
class Field(AbstractObject.Field):
element_child_index = 'element_chil... |
class EventQuery(EqlNode):
__slots__ = ('event_type', 'query')
template = Template('$event_type where $query')
def __init__(self, event_type, query):
self.event_type = event_type
self.query = query
def _render(self):
query_text = self.query.render()
if ('\n' in query_text... |
def transform_df_to_time_count_view(period_data: pd.Series, datetime_column_name: str, datetime_data: pd.Series, data_column_name: str, column_data: pd.Series):
df = pd.DataFrame({'period': period_data, datetime_column_name: datetime_data, data_column_name: column_data})
df = df.groupby(['period', data_column_n... |
class StatusBaseInformationError(ErsiliaError):
def __init__(self):
self.message = 'Wrong Ersilia status'
self.hints = 'Only one of the following status is allowed: {}'.format(', '.join(_read_default_fields('Status')))
ErsiliaError.__init__(self, self.message, self.hints) |
class FancyValidator(Validator):
if_invalid = NoDefault
if_invalid_python = NoDefault
if_empty = NoDefault
not_empty = False
accept_python = True
strip = False
messages = dict(empty=_('Please enter a value'), badType=_('The input must be a string (not a %(type)s: %(value)r)'), noneType=_('Th... |
def test_double_slash_fails(casper, concise_casper, funded_account, validation_key, deposit_amount, induct_validator, mk_slash_votes, assert_tx_failed):
validator_index = induct_validator(funded_account, validation_key, deposit_amount)
(vote_1, vote_2) = mk_slash_votes(validator_index, validation_key)
asser... |
def get_fastas_cmd(o_dir, e_dir, o_file, request, incomplete=False):
program = 'bin/assembly/phyluce_assembly_get_fastas_from_match_counts'
cmd = [os.path.join(request.config.rootdir, program), '--locus-db', os.path.join(e_dir, 'probe-match', 'probe.matches.sqlite'), '--contigs', os.path.join(e_dir, 'spades', '... |
def test_phi_function_in_head3():
u1 = Variable('u', Integer.int32_t(), 1)
u2 = Variable('u', Integer.int32_t(), 2)
v0 = Variable('v', Integer.int32_t(), 0)
v1 = Variable('v', Integer.int32_t(), 1)
node = BasicBlock(0, [Phi(u1, [v0, u2]), Phi(v1, [v0, u1]), Assignment(u2, BinaryOperation(OperationTy... |
class TokenBase(object):
def __init__(self, prefix, intermediate, content):
self.prefix = prefix
self.intermediate = intermediate
self.content = content
def string(self):
return self.content
def __repr__(self):
ret = "<{:14} - contents: '{}' '{}' '{}'>".format(self.__... |
class OptionSeriesXrangeAccessibilityPoint(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._co... |
def main(sleep_timeout: int) -> None:
datasets_path = os.path.abspath('datasets')
if (not os.path.exists(datasets_path)):
exit('Cannot find datasets, try to run run_example.py script for initial setup')
print(f'Get production data from {datasets_path} and send the data to monitoring service each {ar... |
class TFLogger(SummaryWriter, Logger):
def __init__(self, log_dir=None, hps={}, save_every=1):
SummaryWriter.__init__(self, log_dir=log_dir)
Logger.__init__(self, **hps)
self.for_save_every = {}
self.save_every = save_every
f = open((log_dir + '/params.json'), 'wt')
f... |
def _back_sub_matrix(a: Matrix, b: Matrix, s: Shape) -> Matrix:
(size1, size2) = s
for i in range((size1 - 1), (- 1), (- 1)):
v = b[i]
for j in range((i + 1), size1):
for k in range(size2):
v[k] -= (a[i][j] * b[j][k])
for j in range(size2):
b[i][j]... |
class AppComponentMeta(ComponentMeta):
CLASSES = []
__repr__ = meta_repr
def _init_hook1(cls, cls_name, bases, dct):
CSS = dct.get('CSS', '')
if issubclass(cls, LocalComponent):
cls._make_js_proxy_class(cls_name, bases, dct)
elif issubclass(cls, ProxyComponent):
... |
class OptionSeriesPieDatalabelsTextpath(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def enabled(self):
return self._config_get(False)
def enabled(self, flag: bool):
self._config(flag, j... |
class ScreenChannel(ChannelInterface):
multiple_screens = Signal(str, dict)
log_dir_size_signal = Signal(str, float)
def clear_cache(self, grpc_url=''):
pass
def get_screen_manager(self, uri='localhost:12321'):
channel = self.get_insecure_channel(uri)
return (sstub.ScreenStub(cha... |
class InferenceTests(unittest.TestCase):
def test_simple_regression(self):
torch.manual_seed(1)
n_samples = 100
x_train = torch.linspace(0, 1, 10)
y_train = torch.sin((x_train * (2 * math.pi)))
kernel = ScaleKernel(base_kernel=PeriodicKernel(period_length_prior=UniformPrior(0... |
class TestTurnBattleRangeCmd(BaseEvenniaCommandTest):
def test_turnbattlerangecmd(self):
self.call(tb_range.CmdShoot(), '', 'You can only do that in combat. (see: help fight)')
self.call(tb_range.CmdApproach(), '', 'You can only do that in combat. (see: help fight)')
self.call(tb_range.CmdWi... |
def test_configure_project_should_configure_a_project_persistently(create_test_db, create_pymel, create_maya_env, create_test_data, temp_project):
pm = create_pymel
project = temp_project
repo = project.repository
assert isinstance(repo, Repository)
config_file_path = os.path.join(repo.path, project... |
def draw_combined(ast_root, cfg_root, reduced=True, only_blocks=False, format='png', highlight=None):
ast_dot = ASTVisualiser(ast_root).start(combined=True, reduced=reduced, highlight=highlight)
cfg_dot = CFGVisualiser(cfg_root).start(only_blocks=only_blocks, combined=True)
dot = Digraph(strict=True)
do... |
class CollectMissingAccount(BaseRequestResponseEvent[MissingAccountResult]):
missing_node_hash: Hash32
address_hash: Hash32
state_root_hash: Hash32
urgent: bool
block_number: BlockNumber
def expected_response_type() -> Type[MissingAccountResult]:
return MissingAccountResult |
class TestDIN99oSerialize(util.ColorAssertsPyTest):
COLORS = [('color(--din99o 75 10 -10 / 0.5)', {}, 'color(--din99o 75 10 -10 / 0.5)'), ('color(--din99o 75 10 -10)', {'alpha': True}, 'color(--din99o 75 10 -10 / 1)'), ('color(--din99o 75 10 -10 / 0.5)', {'alpha': False}, 'color(--din99o 75 10 -10)'), ('color(--din... |
class AlertEndPosition(object):
swagger_types = {}
attribute_map = {}
def __init__(self):
self.discriminator = None
def to_dict(self):
result = {}
for (attr, _) in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
... |
def register_config_iterator(name: str, iterator_class: Type[ConfigIterator]):
global config_iterator_map
logger.debug(f'register iterator: {name}')
if (name not in config_iterator_map):
config_iterator_map[name] = iterator_class
else:
raise ValueError(f'Duplicate iterator registration n... |
class OptionSeriesXrangeSonificationContexttracksPointgrouping(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):
... |
def lookup_file_in_cache(repo_id: str, revision: str, filename: str) -> Optional[str]:
resolved = huggingface_hub.try_to_load_from_cache(repo_id=repo_id, filename=filename, revision=revision)
if ((resolved is None) or (resolved is huggingface_hub._CACHED_NO_EXIST)):
return None
else:
return ... |
class AsyncENS(BaseENS):
w3: 'AsyncWeb3'
def __init__(self, provider: 'AsyncBaseProvider'=cast('AsyncBaseProvider', default), addr: ChecksumAddress=None, middlewares: Optional[Sequence[Tuple[('AsyncMiddleware', str)]]]=None) -> None:
self.w3 = init_async_web3(provider, middlewares)
ens_addr = (a... |
class ShadowIGMediaCollaborators(AbstractCrudObject):
def __init__(self, fbid=None, parent_id=None, api=None):
self._isShadowIGMediaCollaborators = True
super(ShadowIGMediaCollaborators, self).__init__(fbid, parent_id, api)
class Field(AbstractObject.Field):
id = 'id'
invite_stat... |
class Settings(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.maintain_presence.start()
(seconds=30)
async def maintain_presence(self):
(await self.bot.wait_until_ready())
current_activity = self.bot.activities.get()
(await self.bot.change_presence(activi... |
def generate_python_code(argv=sys.argv):
processed_args = process_args(_is_python_reserved_str, argv)
optlines = (' ' + '\n '.join([_generate_python_code_line(o) for o in processed_args]))
printlines = ''
env_print = os.environ.get('DUCKARGS_PRINT', 1)
try:
env_print_int = int(env_prin... |
def test_request_exception_signal():
app = flask.Flask(__name__)
recorded = []
('/')
def index():
(1 // 0)
def record(sender, exception):
recorded.append(exception)
flask.got_request_exception.connect(record, app)
try:
assert (app.test_client().get('/').status_code ==... |
class TestCollectionInterface(unittest.TestCase):
def setUp(self):
self.d = CreateObject('Scripting.Dictionary', dynamic=False)
def tearDown(self):
del self.d
def assertAccessInterface(self, d):
self.assertEqual(d.CompareMode, 42)
self.assertEqual(d['foo'], 1)
self.as... |
def _mypy_cmd(strict: bool, python_version: Optional[str]='3.7') -> List[str]:
mypy = ['mypy', '--install-types', '--non-interactive', '--config-file', f'{BASE}/.mypy.ini']
if strict:
mypy.append('--strict')
if (python_version is not None):
mypy.append(f'--python-version={python_version}')
... |
def read_use_stmt(line: str) -> (tuple[(Literal['use'], Use)] | None):
use_match = FRegex.USE.match(line)
if (use_match is None):
return None
trailing_line = line[use_match.end(0):].lower()
use_mod = use_match.group(2)
only_list: set[str] = set()
rename_map: dict[(str, str)] = {}
if ... |
class FactDb(FactBase):
PROGRAM_NAME = 'FACT DB-Service'
PROGRAM_DESCRIPTION = 'Firmware Analysis and Compare Tool (FACT) DB-Service'
COMPONENT = 'database'
def __init__(self):
super().__init__()
self._check_postgres_connection()
def _check_postgres_connection():
try:
... |
('ecs_deploy.cli.get_client')
def test_update_task_without_changing_secrets_value(get_client, runner):
get_client.return_value = EcsTestClient('acces_key', 'secret_key')
result = runner.invoke(cli.update, (TASK_DEFINITION_ARN_1, '-s', 'webserver', 'baz', 'qux'))
assert (result.exit_code == 0)
assert (no... |
_coconut_mark_as_match
def mean(_coconut_match_first_arg=_coconut_sentinel, *_coconut_match_args, **_coconut_match_kwargs):
_coconut_match_check_0 = False
_coconut_match_set_name_xs = _coconut_sentinel
_coconut_FunctionMatchError = _coconut_get_function_match_error()
if (_coconut_match_first_arg is not ... |
class ProjectFlag(Base):
__tablename__ = 'projects_flags'
id = sa.Column(sa.Integer, primary_key=True)
project_id = sa.Column(sa.Integer, sa.ForeignKey('projects.id', ondelete='cascade', onupdate='cascade'))
reason = sa.Column(sa.Text, nullable=False)
user = sa.Column(sa.String(200), index=True, nul... |
class Function():
def __init__(self, value):
functions = value.split('|')
self.name = functions[0]
self.variable = Variable(functions[0])
self.functions = functions[1:]
def substitute(self, params):
value = self.variable.substitute(params)
for f in self.functions:... |
def extractSuibiansubsTumblrCom(item):
badwords = ['audio drama', 'Manhua', 'MKV', 'badword']
if any([(bad in item['tags']) for bad in badwords]):
return None
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.