code stringlengths 281 23.7M |
|---|
def fmt_smart_range_tight(value: float, range: float) -> str:
if np.isnan(value):
return '---'
absolute_range = abs(range)
if (absolute_range < 1.0):
return f'{value:.3f}'
elif (absolute_range < 10):
return f'{value:.2f}'
elif (absolute_range < 100):
return f'{value:,... |
def _find_self_tests():
classes = []
method = []
rtn = []
namesspace = {}
namesspace['expyriment'] = expyriment
for module in ['expyriment.io', 'expyriment.io.extras']:
exec('classes = dir({0})'.format(module), namesspace)
for cl in namesspace['classes']:
if ((not cl.... |
.django_db
def test_new_award_count_future(client, monkeypatch, new_award_data, elasticsearch_award_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_award_index)
resp = client.get(url.format(code='123', filter=f'?fiscal_year={(current_fiscal_year() + 1)}'))
assert (resp.status_code == status.HTTP... |
class OptionPlotoptionsParetoSonificationDefaultinstrumentoptionsMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsParetoSonificationDefaultinstrumentoptionsMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsParetoSonificationDefaultinstrumentoptionsMappingL... |
def _make_run_stages(block_sizes, resolve_repeats):
stages = []
for block in block_sizes:
stages.append(RunStage(name=str(block), block_size=block, ref_indels=False, repeats=False, rearrange=True))
stages.append(RunStage(name='refine', block_size=block_sizes[ID_SMALLEST], ref_indels=True, repeats=re... |
class ActorModel(ITVTKActorModel):
actor_type = Enum('cone', 'sphere', 'plane_widget', 'box_widget')
actor_map = Dict()
view = View(Item(name='actor_type'), Item(name='actor_map', editor=ActorEditor(scene_kwds={'background': (0.2, 0.2, 0.2)}), show_label=False, resizable=True, height=500, width=500))
de... |
def wrap_group_queries_pfams(queries_pfams, queries_fasta, pfam_db, resume, translate, trans_table, temp_dir, pfam_file, data_dir):
for queries_pfams_group in group_queries_pfams(queries_pfams):
(yield (queries_pfams_group, queries_fasta, pfam_db, temp_dir, resume, translate, trans_table, pfam_file, 1, data... |
def load_from_mat(weights_path):
from scipy.io import loadmat
data = loadmat(weights_path)
if (not all(((i in data) for i in ('layers', 'classes', 'normalization')))):
raise ValueError('You are using the wrong VGG-19 data.')
params = data['layers'][0]
weights = []
for (i, name) in enumer... |
class OptionSeriesPyramidSonificationTracksMappingPan(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._conf... |
def test():
assert Doc.has_extension('author'), "As-tu defini l'extension author du Doc ?"
ext = Doc.get_extension('author')
assert all(((v is None) for v in ext)), "As-tu affecte la valeur par defaut a l'extension author ?"
assert Doc.has_extension('book'), "As-tu defini l'extension book du Doc ?"
... |
class SaveTextualInversion(Callback[TextualInversionLatentDiffusionTrainer]):
def on_checkpoint_save(self, trainer: TextualInversionLatentDiffusionTrainer) -> None:
embedding_extender = trainer.text_encoder.ensure_find(EmbeddingExtender)
tensors = {trainer.config.textual_inversion.placeholder_token:... |
def parse_latlng(s: str) -> s2sphere.LatLng:
a = s.split(',')
if (len(a) != 2):
raise ValueError(f'Cannot parse coordinates string "{s}" (not a comma-separated lat/lng pair)')
try:
lat = float(a[0].strip())
lng = float(a[1].strip())
except ValueError as e:
raise ValueErro... |
def test_generate():
schema = {'type': 'record', 'name': 'Test', 'namespace': 'test', 'fields': [{'name': 'null', 'type': 'null'}, {'name': 'boolean', 'type': 'boolean'}, {'name': 'string', 'type': 'string'}, {'name': 'bytes', 'type': 'bytes'}, {'name': 'int', 'type': 'int'}, {'name': 'long', 'type': 'long'}, {'nam... |
class OptionPlotoptionsArearangeSonificationTracksActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, num: float):
... |
class ClassTest(QuickbooksTestCase):
def setUp(self):
super(ClassTest, self).setUp()
self.name = 'Test Class {0}'.format(datetime.now().strftime('%d%H%M'))
def test_create(self):
tracking_class = Class()
tracking_class.Name = self.name
tracking_class.save(qb=self.qb_clien... |
class _atomic(callable_context_manager):
def __init__(self, adapter):
self.adapter = adapter
def __enter__(self):
if (self.adapter.transaction_depth() == 0):
self._helper = self.adapter.db.transaction()
else:
self._helper = self.adapter.db.savepoint()
retu... |
class GnuBackendtests(DatabaseTestCase):
def setUp(self):
super().setUp()
create_distro(self.session)
self.create_project()
def create_project(self):
project = models.Project(name='gnash', homepage=' version_url=' backend=BACKEND)
self.session.add(project)
self.se... |
('HardTanh.v1')
def HardTanh(nO: Optional[int]=None, nI: Optional[int]=None, *, init_W: Optional[Callable]=None, init_b: Optional[Callable]=None, dropout: Optional[float]=None, normalize: bool=False) -> Model[(Floats2d, Floats2d)]:
if (init_W is None):
init_W = glorot_uniform_init
if (init_b is None):
... |
def error(status: int):
def decorator(func):
func.bottle_error = status
(func)
def wrapped_func(*args, **kwargs):
body = json.dumps(func(*args, **kwargs))
response.content_type = 'application/json; charset=utf-8'
return body
return wrapped_func()
... |
def test():
assert Token.has_extension('is_country'), '?'
ext = Token.get_extension('is_country')
assert (ext[0] == False), '?'
country_values = [False, False, True, False]
assert ([t._.is_country for t in doc] == country_values), '?'
assert ('print([(token.text, token._.is_country)' in __soluti... |
class OptionSeriesColumnrangeSonificationContexttracksMappingLowpassResonance(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 upgrade():
op.create_table('feedback', sa.Column('id', sa.Integer(), nullable=False), sa.Column('rating', sa.String(), nullable=False), sa.Column('comment', sa.String(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('event_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint... |
def test___setitem__checks_the_given_data_11():
wh = WorkingHours()
with pytest.raises(RuntimeError) as cm:
wh[0] = [[4, 100, 3]]
assert (str(cm.value) == 'WorkingHours.working_hours value should be a list of lists of two integers between and the range of integers should be 0-1440, not [[4, 100, 3]]... |
def load_background_options():
background_options = {}
with open('./utils/background_videos.json') as json_file:
background_options['video'] = json.load(json_file)
with open('./utils/background_audios.json') as json_file:
background_options['audio'] = json.load(json_file)
del background_... |
class StructOrUnion(StructOrUnionOrEnum):
fixedlayout = None
completed = False
partial = False
packed = False
def __init__(self, name, fldnames, fldtypes, fldbitsize):
self.name = name
self.fldnames = fldnames
self.fldtypes = fldtypes
self.fldbitsize = fldbitsize
... |
class OptionPlotoptionsDumbbellAccessibilityPoint(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):
s... |
class Components():
def __init__(self, ui):
self.page = ui.page
def button(self, text: str='', icon: str=None, category: str='primary', width: types.SIZE_TYPE=(None, '%'), height: types.SIZE_TYPE=(None, 'px'), html_code: str=None, tooltip: str=None, align: str=None, profile: types.PROFILE_TYPE=None, opt... |
class Explainer(object):
def __init__(self, config):
self.config = config
def list_resources(self, model_name, full_resource_name_prefix):
LOGGER.debug('Listing resources, model_name = %s, full_resource_name_prefix = %s', model_name, full_resource_name_prefix)
model_manager = self.config... |
def test_various_fdata_in_one_iflr():
fpath = 'data/chap4-7/iflr/various-fdata-in-one-iflr.dlis'
curves = load_curves(fpath)
assert (curves[0][1] == datetime(1971, 3, 21, 18, 4, 14, 386000))
assert (curves[0][2] == 'VALUE')
assert (curves[0][3] == 89)
assert (curves[1][1] == datetime(1970, 3, 21... |
class TestAsciidoc():
def test_adoc(self, tmpdir):
adoc_path = str(tmpdir.join('regs.adoc'))
print('adoc_path:', adoc_path)
rmap = utils.create_template()
generators.Asciidoc(rmap, adoc_path).generate()
with open(adoc_path, 'r') as f:
raw_str = ''.join(f.readlines... |
def extractLazypandaDreamwidthOrg(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... |
class GrowingString(GrowingChainOfStates):
def __init__(self, images, calc_getter, perp_thresh=0.05, param='equi', reparam_every=2, reparam_every_full=3, reparam_tol=None, reparam_check='rms', max_micro_cycles=5, reset_dlc=True, climb=False, **kwargs):
assert (len(images) >= 2), 'Need at least 2 images for ... |
def test_string_with_pointer_compare():
base_args = ['python', 'decompile.py', 'tests/samples/bin/systemtests/64/0/globals']
args1 = (base_args + ['global_string_compare'])
output = str(subprocess.run(args1, check=True, capture_output=True).stdout)
assert (output.count('Hello Decompiler') == 1) |
class CustomFormListPost(ResourceList):
def before_post(self, args, kwargs, data):
require_relationship(['event'], data)
if (not has_access('is_coorganizer', event_id=data['event'])):
raise ObjectNotFound({'parameter': 'event_id'}, 'Event: {} not found'.format(data['event_id']))
... |
def _test_correct_response_of_grants(client):
resp = post(client, award_type_codes=list(grant_type_mapping.keys()), def_codes=['L', 'M'], geo_layer='state', geo_layer_filters=['SC', 'WA'], spending_type='obligation')
expected_response = {'geo_layer': 'state', 'scope': 'recipient_location', 'spending_type': 'obl... |
.skipif((django.VERSION > (1, 9)), reason='MIDDLEWARE_CLASSES removed in Django 2.0')
def test_user_info_without_auth_middleware(django_elasticapm_client, client):
with override_settings(MIDDLEWARE_CLASSES=[m for m in settings.MIDDLEWARE_CLASSES if (m != 'django.contrib.auth.middleware.AuthenticationMiddleware')]):... |
def _frequency_order_transform(sets):
logging.debug('Applying frequency order transform on tokens...')
counts = reversed(Counter((token for s in sets for token in s)).most_common())
order = dict(((token, i) for (i, (token, _)) in enumerate(counts)))
sets = [np.sort([order[token] for token in s]) for s i... |
def okhsl_to_oklab(hsl: Vector, lms_to_rgb: Matrix, ok_coeff: List[List[Vector]]) -> Vector:
(h, s, l) = hsl
h = (h / 360.0)
L = toe_inv(l)
a = b = 0.0
if ((L != 0.0) and (L != 1.0) and (s != 0)):
a_ = math.cos((alg.tau * h))
b_ = math.sin((alg.tau * h))
(c_0, c_mid, c_max) =... |
def deep_quotes(token, column_names=[]):
if hasattr(token, 'tokens'):
for token_child in token.tokens:
deep_quotes(token_child, column_names)
elif (token.ttype == sqlparse.tokens.Name):
if (len(column_names) > 0):
if (token.value in column_names):
token.va... |
class Stmt():
def __init__(self, *args, **kwargs):
self.t = kwargs['t']
self.tid = kwargs['tid']
self.insn = None
self.pc = None
if ('insn' in kwargs):
self.insn = kwargs['insn']
if ('pc' in kwargs):
self.pc = kwargs['pc']
def __repr__(self... |
def extractPineappletranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Suspicious Manager Moon', 'Suspicious Manager Moon', 'translated')]
for (tagnam... |
class OptionSeriesOrganizationNodesDatalabels(Options):
def align(self):
return self._config_get('undefined')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(False)
def allowOverlap(self, flag: bool):
self._con... |
_command
def run_flow(dm: DataManager, key: str, keep_backward: bool=False):
ds = dm.datasets[key]
if (not ds.local.images):
raise ValueError('no images available')
root = dm.get_local_data_path(key)
rgb_dir = (root / 'rgb_1x')
flow_dir = (root / 'flow')
need_forward = (not isdir((flow_d... |
class ApplicationSyntax(TypeCoercionHackMixIn, univ.Choice):
componentType = namedtype.NamedTypes(namedtype.NamedType('address', NetworkAddress()), namedtype.NamedType('counter', Counter()), namedtype.NamedType('gauge', Gauge()), namedtype.NamedType('ticks', TimeTicks()), namedtype.NamedType('arbitrary', Opaque())) |
class timer():
def __init__(self, timerid):
self.timerid = timerid
self.state = 0
self.starttime = 0
self.pausetime = 0
self.lefttime = 0
self.timer = None
self.timeractive = False
self.callback = None
self.retvalue = [(- 1), (- 1)]
sel... |
class TDE4PointManager(object):
def __init__(self):
self.points = []
def read(self, file_path):
with open(file_path, 'r') as f:
data = f.readlines()
self.reads(data)
def reads(self, data):
number_of_points = int(data[0])
cursor = 1
for i in range(n... |
class Login(TokenObtainPairView):
serializer_class = CustomTokenObtainPairSerializer
def post(self, request, *args, **kwargs):
username = request.data.get('username')
password = request.data.get('password')
if ((not username) or (not password)):
return Response({'error': 'Ple... |
class EventLocationSchema(Schema):
class Meta():
type_ = 'event-location'
inflect = dasherize
id = fields.Str(dump_only=True)
name = fields.Str(required=True)
slug = fields.Str(dump_only=True)
events = Relationship(related_view='v1.event_list', related_view_kwargs={'event_location_id... |
def load_plugins(app):
app.pluggy.add_hookspecs(spec)
flaskbb_modules = set((module for (name, module) in sys.modules.items() if name.startswith('flaskbb')))
for module in flaskbb_modules:
app.pluggy.register(module, internal=True)
try:
with app.app_context():
plugins = Plugi... |
class ChartNetwork(Chart):
_option_cls = OptVis.OptionsNetwork
def __init__(self, page, width, height, html_code, options, profile):
super(ChartNetwork, self).__init__(page, width, height, html_code, options, profile)
(self._nodes, self._edges, self.__grps) = ([], [], None)
def options(self)... |
def put_quiz_result(cognito_id, body, date):
data = {'PK': ('USER#' + cognito_id), 'SK': ('QUIZ#' + body['quiz_id']), 'Quiz data': body['quiz_data'], 'Date created': date, 'List id': body['list_id'], 'Character set': body['character_set'], 'Question quantity': body['question_quantity'], 'Correct answers': body['cor... |
def _format_quiz_results(quiz_results_item):
formatted_quiz_results_item = QuizResults(quiz_id=quiz_results_item['SK'][5:], date_created=quiz_results_item['Date created'], list_id=quiz_results_item['List id'], character_set=quiz_results_item['Character set'], question_quantity=int(quiz_results_item['Question quanti... |
class Migration(migrations.Migration):
dependencies = [('core', '0006_auto__0846'), ('gather', '0003_auto__0846')]
operations = [migrations.AddField(model_name='eventnotifications', name='location_publish', field=models.ManyToManyField(related_name='event_published', to='core.Location')), migrations.AlterField(... |
.parametrize('variable, name', ([(Variable(('var_' + str(i)), typ), EXPECTED_BASE_NAMES[i]) for (i, typ) in enumerate(ALL_TYPES)] + [(Variable(('var_' + str(i)), Pointer(typ)), EXPECTED_POINTER_NAMES[i]) for (i, typ) in enumerate(ALL_TYPES)]))
def test_hungarian_notation(variable, name):
true_value = LogicCondition... |
class Translation(BaseObject):
def __init__(self, api=None, body=None, created_at=None, created_by_id=None, draft=None, hidden=None, html_url=None, id=None, locale=None, outdated=None, source_id=None, source_type=None, title=None, updated_at=None, updated_by_id=None, url=None, **kwargs):
self.api = api
... |
class TestETW(unittest.TestCase):
def setUpClass(cls):
cls.event_tufo_list = list()
cls.context_fields = {'Description', 'Task Name'}
cls.user_agent = 'TestAgent'
cls.url = 'www.gmail.com'
cls.port = 80
cls.verb = 'GET'
cls.size = 1337
return
def m... |
def test_eth_valid_account_address_sign_data_with_intended_validator(acct, message_encodings):
account = acct.create()
signable = encode_intended_validator(account.address, **message_encodings)
signed = account.sign_message(signable)
signed_classmethod = acct.sign_message(signable, account.key)
asse... |
_settings(REST_FRAMEWORK=dict(SERIALIZER_EXTENSIONS=dict(USE_HASH_IDS=True, HASH_IDS_SOURCE='tests.base.TEST_HASH_IDS')))
class ExternalIdViewMixinTests(TestCase):
fixtures = ['test_data.json']
def setUp(self):
self.owner = test_models.Owner.objects.get()
self.sku_p100d = test_models.Sku.objects... |
class Comment(Base):
__tablename__ = 'comments'
__exclude_columns__ = tuple()
__get_by__ = ('id',)
karma = Column(Integer, default=0)
karma_critpath = Column(Integer, default=0)
text = Column(UnicodeText, nullable=False)
timestamp = Column(DateTime, default=datetime.utcnow)
bug_feedback ... |
def test_geometry_sizes():
for size in (((- 1), 1, 1), (1, (- 1), 1), (1, 1, (- 1))):
with pytest.raises(pydantic.ValidationError):
_ = td.Box(size=size, center=(0, 0, 0))
with pytest.raises(pydantic.ValidationError):
_ = td.Simulation(size=size, run_time=1e-12, grid_spec=td.... |
class _ManyMultiMetaMatcher():
__slots__ = ['matchers', 'tags']
tag = None
def __init__(self, matchers):
self.matchers = matchers
self.tags = set()
def match(self, srtrack):
self.tags = set()
matched = False
for ma in self.matchers:
if ma.match(srtrack... |
def updateRecall(prior, successes, total, tnow, rebalance=True, tback=None, q0=None):
assert ((0 <= successes) and (successes <= total) and (1 <= total))
if (total == 1):
return _updateRecallSingle(prior, successes, tnow, rebalance=rebalance, tback=tback, q0=q0)
(alpha, beta, t) = prior
dt = (tn... |
def basic_object_class_faba_with_loan_value(award_count_sub_schedule, award_count_submission, defc_codes):
award = _normal_award(1)
award_loan = _loan_award(2)
basic_object_class = major_object_class_with_children('001', [1])
baker.make('awards.FinancialAccountsByAwards', award=award, parent_award_id='b... |
def okhsv_to_oklab(hsv: Vector, lms_to_rgb: Matrix, ok_coeff: list[Matrix]) -> Vector:
(h, s, v) = hsv
h = (h / 360.0)
l = toe_inv(v)
a = b = 0.0
if ((l != 0.0) and (s != 0.0)):
a_ = math.cos((math.tau * h))
b_ = math.sin((math.tau * h))
cusp = find_cusp(a_, b_, lms_to_rgb, o... |
def performance_summary(equity_diffs, quantile=0.99, precision=4):
def _format_out(v, precision=4):
if isinstance(v, dict):
return {k: _format_out(v) for (k, v) in list(v.items())}
if isinstance(v, (float, np.float)):
v = round(v, precision)
if isinstance(v, np.generi... |
class BundleRequirementsFile(ErsiliaBase):
def __init__(self, model_id, config_json=None):
ErsiliaBase.__init__(self, config_json=config_json)
self.model_id = model_id
self.dir = os.path.abspath(self._get_bundle_location(model_id))
self.path = os.path.join(self.dir, REQUIREMENTS_TXT)... |
()
def get_sms_text(doc):
sms_text = {}
doc = frappe.get_doc('Lab Test', doc)
context = {'doc': doc, 'alert': doc, 'comments': None}
emailed = frappe.db.get_single_value('Healthcare Settings', 'sms_emailed')
sms_text['emailed'] = frappe.render_template(emailed, context)
printed = frappe.db.get_s... |
class BaseChatHistoryMemory(ABC):
store_type: MemoryStoreType
def __init__(self):
self.conversations: List[OnceConversation] = []
def messages(self) -> List[OnceConversation]:
def create(self, user_name: str) -> None:
def append(self, message: OnceConversation) -> None:
def update(self, ... |
_tlv_types(CFM_LTM_EGRESS_IDENTIFIER_TLV)
class ltm_egress_identifier_tlv(tlv):
_PACK_STR = '!BHH6s'
_MIN_LEN = struct.calcsize(_PACK_STR)
def __init__(self, length=0, egress_id_ui=0, egress_id_mac='00:00:00:00:00:00'):
super(ltm_egress_identifier_tlv, self).__init__(length)
self._type = CFM... |
class UserSSHKeySerializer(s.InstanceSerializer):
_model_ = UserSSHKey
_update_fields_ = ('title', 'key')
_default_fields_ = ('title', 'key')
title = s.SafeCharField(max_length=32)
fingerprint = s.SafeCharField(max_length=64, read_only=True, required=False)
key = s.SafeCharField(max_length=65536... |
def get_medal_names(is_jp: bool) -> Optional[list[str]]:
file_data = game_data_getter.get_file_latest('resLocal', 'medalname.tsv', is_jp)
if (file_data is None):
helper.error_text('Failed to get medal names')
return None
medal_names = file_data.decode('utf-8').splitlines()
names: list[st... |
('/<string:search_id>', doc={'description': 'Get the results of a previously initiated binary search', 'params': {'search_id': 'Search ID'}})
class RestBinarySearchGet(RestResourceBase):
URL = '/rest/binary_search'
_accepted(*PRIVILEGES['pattern_search'])
(responses={200: 'Success', 400: 'Unknown search ID'... |
def test_working_hours_attribute_data_is_not_in_correct_range2():
import copy
from stalker import defaults
wh_ins = WorkingHours()
wh = copy.copy(defaults.working_hours)
wh['sat'] = [[900, 1080], [1090, 1500]]
with pytest.raises(ValueError) as cm:
wh_ins.working_hours = wh
assert (st... |
class ChatHistory():
def __init__(self):
self.memory_type = MemoryStoreType.DB.value
self.mem_store_class_map = {}
from .store_type.duckdb_history import DuckdbHistoryMemory
from .store_type.file_history import FileHistoryMemory
from .store_type.mem_history import MemHistoryM... |
class LedgerApiDialogue(Dialogue):
INITIAL_PERFORMATIVES: FrozenSet[Message.Performative] = frozenset({LedgerApiMessage.Performative.GET_BALANCE, LedgerApiMessage.Performative.GET_STATE, LedgerApiMessage.Performative.GET_RAW_TRANSACTION, LedgerApiMessage.Performative.SEND_SIGNED_TRANSACTION, LedgerApiMessage.Perfor... |
def main(page: ft.Page):
page.title = 'Flet counter example'
page.vertical_alignment = ft.MainAxisAlignment.CENTER
txt_number = ft.TextField(value='0', text_align=ft.TextAlign.RIGHT, width=100)
def minus_click(e):
txt_number.value = str((int(txt_number.value) - 1))
page.update()
def ... |
.integration_mysql
.integration
class TestMySQLConnector():
def test_mysql_db_connector(self, api_client: TestClient, db: Session, generate_auth_header, connection_config_mysql, mysql_example_secrets) -> None:
connector = get_connector(connection_config_mysql)
assert (connector.__class__ == MySQLCon... |
class BlameIterator(object):
def __init__(self, blame):
self._count = len(blame)
self._index = 0
self._blame = blame
def __next__(self):
if (self._index >= self._count):
raise StopIteration
hunk = self._blame[self._blame]
self._index += 1
retur... |
(AUTHORIZE, dependencies=[Security(verify_oauth_client, scopes=[CONNECTION_AUTHORIZE])], response_model=str)
def authorize_connection(request: Request, db: Session=Depends(deps.get_db), connection_config: ConnectionConfig=Depends(_get_saas_connection_config)) -> Optional[str]:
referer = request.headers.get('Referer... |
def test_diff_attrs_vs_cols(tmpdir):
fname = os.path.join(TEST_DATA_DIR, 'icgem-sample.gdf')
corrupt = str(tmpdir.join('diff_attributes_vs_cols.gdf'))
with open(fname) as gdf_file, open(corrupt, 'w') as corrupt_gdf:
for line in gdf_file:
if ((('longitude' in line) and ('latitude' in line... |
class Solution(object):
def twoSum(self, numbers, target):
(i, j) = (0, (len(numbers) - 1))
while (i < j):
s = (numbers[i] + numbers[j])
if (s == target):
return [(i + 1), (j + 1)]
elif (s > target):
j -= 1
else:
... |
def generate_email_body(date: datetime, company=Config().default_company):
report = OSCIChangeRanking(date=date)
company_contributors_ranking_schema = DataLake().public.schemas.company_contributors_ranking
change_ranking = report.read().reset_index()
change_ranking = change_ranking.rename(columns={'inde... |
class Client():
def __init__(self):
self.isConnected = False
self.sock = []
def connect(self, hostname, port=1972):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((hostname, port))
self.sock.setblocking(True)
self.isConnected = Tru... |
def _filter_releases(session, query, releases=None, states=[ReleaseState.current, ReleaseState.pending]):
_releases = []
releases_query = session.query(Release.name).filter(Release.composed_by_bodhi.is_(True))
releases_query = releases_query.filter(Release.state.in_(states))
if releases:
for r i... |
def test_filter_array_with_static_val():
config = FilterPostProcessorConfiguration(field='email_contact', value='')
data = [{'id': , 'email_contact': '', 'name': 'Somebody Awesome'}, {'id': , 'email_contact': 'somebody-', 'name': 'Somebody Cool'}]
processor = FilterPostProcessorStrategy(configuration=config... |
_cache()
def list_plugins(directory: str) -> List[Plugin]:
blacklist = ['.isort.cfg', 'examples']
_plugin_directories = [x for x in sorted(os.listdir(os.path.join(BASE, directory))) if (x not in blacklist)]
subprocess.check_output([sys.executable, '-m', 'pip', 'install', 'read-version', 'toml'])
plugins... |
class ActionValidator(Validator):
def __init__(self, accepted_list: list, message='This is not a valid action.'):
self.accepted_list = accepted_list
self.message = message
def validate(self, document):
if (document.text not in self.accepted_list):
raise ValidationError(messag... |
class TestVisual(unittest.TestCase):
def setUp(self):
self.viewer = DummyViewer()
visual.set_viewer(self.viewer)
def tearDown(self):
visual.set_viewer(None)
def test_ring(self):
r = visual.ring()
assert_allclose(r.polydata.bounds, (0.0, 0.0, (- 0.5), 0.5, (- 0.5), 0.5... |
_tuple
def normalize_event_input_types(abi_args: Collection[Union[(ABIFunction, ABIEvent)]]) -> Iterable[Union[(ABIFunction, ABIEvent, Dict[(TypeStr, Any)])]]:
for arg in abi_args:
if is_recognized_type(arg['type']):
(yield arg)
elif is_probably_enum(arg['type']):
(yield {k: ... |
class OptionSeriesTilemapSonificationTracksMappingTremoloDepth(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 OptionsStatus(Options):
component_properties = ('change_menu',)
def states(self):
return self.get({})
def states(self, values: dict):
self.set({k.upper(): v for (k, v) in values.items()})
def color(self):
return self.get('white')
def color(self, color: str):
sel... |
def gen_unpack_expr(oftype, reader_expr, version, pyversion):
type_data = lookup_type_data(oftype, version)
if type_data:
if (pyversion == 3):
fmt = (type_data.unpack3 or type_data.unpack or None)
return ((fmt % reader_expr) if fmt else ("loxi.unimplemented('unpack %s')" % oftype... |
class Mainwin(QMainWindow):
def __init__(self):
super(Mainwin, self).__init__()
self.resize(600, 400)
self.startbot = QPushButton('', self)
self.startbot.move(10, 10)
self.startbot.clicked.connect(self.changeActionRun)
self.recbot = QPushButton('', self)
self.... |
def _validate_unique_names(conf_content: Sequence[Tuple[(Any, FileContextToken, Any)]]) -> None:
names_counter = Counter((n for (_, n, *_) in conf_content))
duplicate_names = [n for (n, c) in names_counter.items() if (c > 1)]
errors = [ErrorInfo(f'Duplicate observation name {n}').set_context(n) for n in dup... |
def extractZer0TranslationsBlogspotCom(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... |
def getPdbInfoNoNull(atom):
res = atom.GetResidue()
if (res is None):
name = ('%-2s' % mini_periodic_table[atom.GetAtomicNum()])
chain = ' '
resNum = 1
resName = 'UNL'
else:
name = res.GetAtomID(atom)
chain = res.GetChain()
resNum = int(res.GetNumStrin... |
class HPDeviceData():
device_data: dict
def __init__(self, hass, config_manager: ConfigManager):
self._hass = hass
self._config_manager = config_manager
self._storage_manager = StorageManager(self._hass, self._config_manager)
self._usage_data_manager = ProductUsageDynPrinterDataA... |
def graphs_test1():
cfg = ControlFlowGraph()
cfg.add_nodes_from((vertices := [BasicBlock(0, [Assignment(ListOperation([]), Call(imp_function_symbol('__x86.get_pc_thunk.bx'), [], Pointer(CustomType('void', 0), 32), 1))]), BasicBlock(1, [Phi(Variable('var_10', Integer(32, True), 2, False), [Constant(0, Integer(32... |
def get_practice_data_from_api(practice_id):
url = '
params = {'format': 'json', 'measure': 'desogestrel', 'org': practice_id}
rsp = requests.get(url, params)
for record in rsp.json()['measures'][0]['data']:
if (record['date'] == '2018-08-01'):
return record
assert False |
def test_new_mnemonic_bls_withdrawal(monkeypatch) -> None:
def mock_get_mnemonic(language, words_path, entropy=None) -> str:
return 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'
monkeypatch.setattr(new_mnemonic, 'get_mnemonic', mock_get_mnemonic)
my_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.