code stringlengths 281 23.7M |
|---|
class CoverManager(GObject.GObject):
__gsignals__ = {'prefetch-started': (GObject.SignalFlags.RUN_LAST, None, ()), 'prefetch-progress': (GObject.SignalFlags.RUN_LAST, None, (GObject.TYPE_INT,)), 'prefetch-completed': (GObject.SignalFlags.RUN_LAST, None, (GObject.TYPE_INT,)), 'fetch-started': (GObject.SignalFlags.RU... |
def test_attention_sequential_masked_2():
in_dict = build_multi_input_dict(dims=[(2, 20, 10), (2, 7, 5), (2, 7, 15), (2, 7)])
in_dict['in_key_3'] = (in_dict['in_key_3'] != 0)
self_attn_block = MultiHeadAttentionBlock(in_keys=['in_key_0', 'in_key_1', 'in_key_2', 'in_key_3'], out_keys='self_attention', in_sha... |
def test_mine_all_uncle(chain, tx, tx2, funded_address):
if hasattr(chain, 'mine_all'):
starting_tip = chain.get_canonical_head()
canonical = chain.mine_all([tx])
uncled = chain.mine_all([], parent_header=starting_tip)
uncled_header = uncled[0].imported_block.header
new_tip =... |
class MessageWindow(Gtk.Window):
def __init__(self, text, title='Epoptes', markup=True, icon_name='dialog-information'):
super().__init__(title=title, icon_name=icon_name)
self.set_position(Gtk.WindowPosition.CENTER)
grid = Gtk.Grid(column_spacing=10, row_spacing=10, margin=10)
self.... |
def update_agent_config(ctx: Context) -> None:
update_aea_version_range(ctx.agent_config)
cli_author = ctx.config.get('cli_author')
if (cli_author and (ctx.agent_config.author != cli_author)):
click.echo(f'Updating author from {ctx.agent_config.author} to {cli_author}')
ctx.agent_config._aut... |
def get_data(session: Session, type: str='production') -> tuple[(list[Any], dict[(str, str)])]:
CSV_data = []
PLANT_TO_TYPE_MAP = {}
if (type == 'production'):
for index in range(1, 11):
if (index == 7):
continue
params = {'request': 'CSV_N_', 'p8_indx': index... |
def test_aes_keyschedule_not_too_slowed_down():
n = 100000
key_u8 = np.zeros((n, 16), dtype='uint8')
key_u32 = np.zeros((n, 16), dtype='uint32')
t0 = time.process_time()
scared.aes.key_schedule(key_u8)
pt_u8 = (time.process_time() - t0)
t0 = time.process_time()
scared.aes.key_schedule(ke... |
class CustomPromptTemplate(StringPromptTemplate):
template: str
tools: List[Tool]
agent_toolnames: List[str]
max_context_length: int = 5
keep_n_last_thoughts: int = 2
current_context_length: int = 0
model_steps_processed: int = 0
all_steps_processed: int = 0
my_summarize_agent: Any =... |
class SparkMetricImplementation(Generic[TMetric], MetricImplementation):
def __init__(self, engine: SparkEngine, metric: TMetric):
self.engine = engine
self.metric = metric
def calculate(self, context, data: SparkInputData):
raise NotImplementedError
def supported_engines(cls):
... |
class OptionSeriesStreamgraphSonificationTracksMapping(Options):
def frequency(self) -> 'OptionSeriesStreamgraphSonificationTracksMappingFrequency':
return self._config_sub_data('frequency', OptionSeriesStreamgraphSonificationTracksMappingFrequency)
def gapBetweenNotes(self) -> 'OptionSeriesStreamgraphS... |
class RelationshipMemberMutualAuthentication(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():
... |
def test_has_grim_support_raises_on_grim_call(monkeypatch, caplog):
if (not utils.shutil.which('grim')):
monkeypatch.setattr(utils.shutil, 'which', (lambda _: '/usr/bin/grim'))
def mocked_subprocess_run(*_, **__):
raise OSError
monkeypatch.setattr(utils.subprocess, 'run', mocked_subprocess_r... |
def prompt_for_stop_actions(item_id, data):
log.debug('prompt_for_stop_actions Called : {0}', data)
settings = xbmcaddon.Addon()
current_position = data.get('currentPossition', 0)
duration = data.get('duration', 0)
next_episode = data.get('next_episode')
item_type = data.get('item_type')
can... |
def run_migrations_online():
connectable = engine_from_config(config.get_section(config.config_ini_section), prefix='sqlalchemy.', poolclass=pool.NullPool)
with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata, include_object=include_object, c... |
def get_calendar_html() -> HTML:
html = "<div id='cal-row' class='w-100' onmouseleave='calMouseLeave()'>%s</div> "
day_of_year = datetime.datetime.now().timetuple().tm_yday
date_year_begin = datetime.datetime(year=datetime.datetime.utcnow().year, month=1, day=1, hour=0, minute=0)
nid_now = int((time.tim... |
def read_attachments(list, path, notespath) -> str:
attachments_list = '*Attachments:*\n'
for entry in list:
if ('image' in entry['mimetype']):
image = entry['filePath']
if (copy_file(image, path, notespath) is False):
image_type = mimetypes.guess_type(f'{path}{im... |
_group.command('collect-events')
('host-id')
('--query', '-q', help='KQL query to scope search')
('--index', '-i', multiple=True, help='Index(es) to search against (default: all indexes)')
('--rta-name', '-r', help='Name of RTA in order to save events directly to unit tests data directory')
('--rule-id', help='Updates ... |
class Downsample(Runner):
async def __call__(self, es, params):
(params, request_params, transport_params, request_headers) = self._transport_request_params(params)
es = es.options(**transport_params)
fixed_interval = mandatory(params, 'fixed-interval', self)
if (fixed_interval is No... |
class Migration(migrations.Migration):
dependencies = [('core', '0003_subscriptions')]
operations = [migrations.AlterField(model_name='communitysubscription', name='bills', field=models.ManyToManyField(to='core.SubscriptionBill', null=True, blank=True), preserve_default=True), migrations.AlterField(model_name='... |
class TextFilter(filters.Filter):
def __init__(self, options, default_encoding='utf-8'):
super().__init__(options, default_encoding)
def get_default_config(self):
return {'normalize': '', 'convert_encoding': '', 'errors': 'strict'}
def validate_options(self, k, v):
super().validate_o... |
def extractWwwSakuranovelsCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("I'm Back in the Other World?", "I'm Back in the Other World?", 'translated'), ('Reincarnated Into ... |
(scope='function')
def set_notification_service_type_to_none(db):
original_value = CONFIG.notifications.notification_service_type
CONFIG.notifications.notification_service_type = None
ApplicationConfig.update_config_set(db, CONFIG)
(yield)
CONFIG.notifications.notification_service_type = original_va... |
class ConsensusAPI(ABC):
def __init__(self, context: ConsensusContextAPI) -> None:
...
def validate_seal(self, header: BlockHeaderAPI) -> None:
...
def validate_seal_extension(self, header: BlockHeaderAPI, parents: Iterable[BlockHeaderAPI]) -> None:
...
def get_fee_recipient(cls,... |
class CRUDCasbin(CRUDBase[(CasbinRule, CreatePolicy, UpdatePolicy)]):
async def get_all_policy(self, ptype: str, sub: str) -> Select:
se = select(self.model).order_by(self.model.id)
where_list = []
if ptype:
where_list.append((self.model.ptype == ptype))
if sub:
... |
def clean_up_decoded_string_like_hf(out_string: str) -> str:
out_string = out_string.replace(' .', '.').replace(' ?', '?').replace(' !', '!').replace(' ,', ',').replace(" ' ", "'").replace(" n't", "n't").replace(" 'm", "'m").replace(" 's", "'s").replace(" 've", "'ve").replace(" 're", "'re")
return out_string |
def extractNovustreasuresBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Xuan Wang Above Di Daughter Runs Away', 'Xuan Wang Above Di Daughter Runs Away', 'translate... |
class TransactionProcessBehaviour(TickerBehaviour):
def setup(self) -> None:
def act(self) -> None:
game = cast(Game, self.context.game)
if (game.phase.value == Phase.GAME.value):
self._process_transactions()
def teardown(self) -> None:
def _process_transactions(self) -> None... |
def run_projection(mesh, expr, p):
V = FunctionSpace(mesh, 'KMV', p)
T = V.finat_element.cell
(u, v) = (TrialFunction(V), TestFunction(V))
qr = finat.quadrature.make_quadrature(T, p, 'KMV')
r = Function(V)
f = interpolate(expr(*SpatialCoordinate(mesh)), V)
solve(((inner(u, v) * dx(scheme=qr)... |
.parametrize('elasticapm_client', [{'client_class': AzureFunctionsTestClient}], indirect=['elasticapm_client'])
def test_cloud_info(elasticapm_client):
with mock.patch.dict(os.environ, {'REGION_NAME': 'eu-liechtenstein', 'WEBSITE_OWNER_NAME': '2491fc8e-f7c1-4020-b9c6-fd16+my-resource-group-ARegionShortNamewebspace'... |
def test_distribution_mapper():
act_space = spaces.Dict(spaces={'selection': spaces.Discrete(10), 'order': spaces.MultiBinary(15), 'scale_input': spaces.Box(shape=(5,), low=0, high=100, dtype=np.float64), 'order_by_weight': spaces.Box(shape=(5,), low=0, high=100, dtype=np.float64)})
config = [{'action_space': s... |
def delete_snapshots(snapshot_id, server_id):
url = ((base_url + '/images/') + str(snapshot_id))
r = requests.delete(url=url, headers=headers)
if (not r.ok):
print(f'Snapshot #{snapshot_id} (Server #{server_id}) could not be deleted: {r.reason}')
print(r.text)
else:
print(f'Snaps... |
class TherapyPlanTemplate(Document):
def after_insert(self):
if (not self.link_existing_item):
self.create_item_from_template()
elif (self.linked_item and self.total_amount):
make_item_price(self.linked_item, self.total_amount)
def validate(self):
self.set_totals(... |
class P3IntMomentsDualSet(DualSet):
def __init__(self, cell, order):
assert ((cell == UFCInterval()) and (order == 3))
entity_ids = {0: {0: [0], 1: [1]}, 1: {0: [2, 3]}}
vertnodes = [PointEvaluation(cell, xx) for xx in cell.vertices]
Q = make_quadrature(cell, 3)
ones = np.asa... |
class Subscription(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
created_by = models.ForeignKey(User, related_name='+')
location = models.ForeignKey(Location)
user = models.ForeignKey(User)
price = models.DecimalField(decimal_place... |
def config_twitter(config):
twitter_setup = input('Would you like the bot to post to Twitter? (Y/n) ')
if twitter_setup.lower().startswith('n'):
return config
if ('twitter' in config.keys()):
replace = input('Twitter configuration already exists. Replace? (Y/n) ')
if (replace.lower()... |
def keyframe_selection(shots: List[Shot], min_dist: float=4) -> List[int]:
camera_centers = np.stack([shot.pose.get_origin() for shot in shots], 0)
distances = np.linalg.norm(np.diff(camera_centers, axis=0), axis=1)
selected = [0]
cum = 0
for i in range(1, len(camera_centers)):
cum += distan... |
class OptionPlotoptionsSeriesTooltipDatetimelabelformats(Options):
def day(self):
return self._config_get('%A, %e %b %Y')
def day(self, text: str):
self._config(text, js_type=False)
def hour(self):
return self._config_get('%A, %e %b, %H:%M')
def hour(self, text: str):
sel... |
class AW1RegistrationHandler(Handler):
SUPPORTED_PROTOCOL = RegisterMessage.protocol_id
def setup(self) -> None:
def handle(self, message: Message) -> None:
register_msg = cast(RegisterMessage, message)
register_dialogues = cast(RegisterDialogues, self.context.register_dialogues)
reg... |
class InterComFrontEndBinding(InterComRedisInterface):
def add_analysis_task(self, fw):
self._add_to_redis_queue('analysis_task', fw, fw.uid)
def add_re_analyze_task(self, fw, unpack=True):
if unpack:
self._add_to_redis_queue('re_analyze_task', fw, fw.uid)
else:
s... |
class Alert():
def __init__(self, fn: Callable, args: Tuple=None, kwargs: Dict=None, delay: float=2, msg: str=None, callback: Callable=None, repeat: bool=False) -> None:
if (args is None):
args = ()
if (kwargs is None):
kwargs = {}
if (not callable(fn)):
r... |
def _user_group_changed(task_id, group_name, dc_name):
if (dc_name and group_name):
dc = Dc.objects.get_by_name(dc_name)
mon = get_monitoring(dc)
if (not mon.enabled):
logger.info('Monitoring is disabled in DC %s', dc)
return
try:
group = Role.obje... |
def splitrename(linkcurrent):
renamecurrent = ''
if ('>' in linkcurrent):
file_rename = linkcurrent.split('>')
file_rename = [file_rename.strip() for file_rename in file_rename]
linkcurrent = file_rename[0]
if file_rename[1]:
renamecurrent = file_rename[1]
return ... |
class ArrayTest(unittest.TestCase):
def test_double(self):
import array
for typecode in 'df':
a = array.array(typecode, (1.0, 2.0, 3.0, 4.5))
v = VARIANT()
v.value = a
self.assertEqual(v.value, (1.0, 2.0, 3.0, 4.5))
def test_int(self):
impo... |
def test_inference_error_reporting():
mh = bm.SingleSiteAncestralMetropolisHastings()
with pytest.raises(TypeError) as ex:
mh.infer(None, {}, 10)
assert (str(ex.value) == "Parameter 'queries' is required to be a list but is of type NoneType.")
with pytest.raises(TypeError) as ex:
mh.infe... |
class FlowSizer(wx.PySizer):
def __init__(self, orient=wx.HORIZONTAL):
super().__init__()
self._orient = orient
self._frozen = False
self._needed_size = None
def CalcMin(self):
if (self._needed_size is not None):
return self._needed_size
horizontal = (... |
class TestLLMClient(BaseEvenniaTestCase):
def setUp(self):
self.npc = create_object(LLMNPC, key='Test NPC')
self.npc.db_home = None
self.npc.save()
def tearDown(self):
self.npc.delete()
super().tearDown()
_settings(LLM_PROMPT_PREFIX='You are a test bot.')
('evenni... |
.smoke
def test_parse_workflow_with_multiple_generators():
filename = 'test/data/good-dags/multi_generators.yaml'
wf = Workflow.load(filename)
assert (frozenset((node.name for node in wf.specs.graphs.primary.graph.nodes())) == frozenset(['file_lister', 'file_lister_1', 'file_lister_2', 'file_lister_3', 'fil... |
def extractLandofLightNovels(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
if item['title'].startswith('C3'):
return buildReleaseMessageWithType(item, 'Cube x Cursed x Cu... |
class OptionPlotoptionsPackedbubbleSonificationTracksMapping(Options):
def frequency(self) -> 'OptionPlotoptionsPackedbubbleSonificationTracksMappingFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsPackedbubbleSonificationTracksMappingFrequency)
def gapBetweenNotes(self) -> 'Option... |
class TestDefaultOutput():
def setup_method(self):
class ExampleSerializer(serializers.Serializer):
has_default = serializers.CharField(default='x')
has_default_callable = serializers.CharField(default=(lambda : 'y'))
no_default = serializers.CharField()
self.Seri... |
def _get_valid_view_op_and_second_cat(view_ops: List[Operator]) -> Tuple[(Operator, Operator)]:
view_op = None
second_cat = None
for a_view_op in view_ops:
view_op_output = a_view_op._attrs['outputs'][0]
next_next_ops = view_op_output._attrs['dst_ops']
next_concats = [n for n in next... |
class SliderDate(Slider):
name = 'Slider Date'
def __init__(self, page: primitives.PageModel, number: Union[(float, list)], min_val: float, max_val: float, width: Union[(tuple, int)], height: Union[(tuple, int)], helper: str, options: dict, html_code: str, profile: Union[(dict, bool)], verbose: bool=False):
... |
def test_get_config_file():
c = get_config_file(None)
assert (c is None)
c = get_config_file(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'configs/good.config'))
assert (c is not None)
assert (c.legacy_config is not None)
with pytest.raises(configparser.Error):
get_config_fi... |
def execute(command: Iterable, hide_log=False, mute=False, timeout: int=30, wait=True, kill=False, drop=False, stdin: Optional[Union[(bytes, str)]]=None, shell=False, **kwargs):
command_string = command
close = None
if isinstance(command, (list, tuple)):
command_string = subprocess.list2cmdline(comm... |
class LTComponent(LTItem):
def __init__(self, bbox):
LTItem.__init__(self)
self.set_bbox(bbox)
return
def __repr__(self):
return ('<%s %s>' % (self.__class__.__name__, bbox2str(self.bbox)))
def __lt__(self, _):
raise ValueError
def __le__(self, _):
raise V... |
def extractAsadatranslationsWpcomstagingCom(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, nam... |
class PartialCaseTests(unittest.TestCase):
def test_can_add_case_to_pypher(self):
one = 1
two = 2
three = 3
case = Case(__.n.__eyes__)
case.WHEN('blue', one)
case.WHEN('brown', two)
case.ELSE(three)
p = Pypher()
p.apply_partial(case)
c ... |
class AnyValue(object):
def __init__(self, data_type, permit_none=False):
self.data_type = data_type
self.permit_none = permit_none
def __eq__(self, other):
if (other is None):
return self.permit_none
if isinstance(other, AnyValue):
return (self.data_type ... |
class Git():
def __init__(self, repo, cwd, branch='master'):
self.repo = repo
self.cwd = cwd
self.branch = branch
def clone_if_necessary(self):
try:
self.status()
except GitError:
logger.info('cloning %s', self.repo)
return _git('.', 'c... |
class StorageTestFile(StorageTestCase, TestCase):
CONFIG = "\n configurationVersion: '1'\n logFile: /dev/stderr\n databaseEngine: sqlite://\n defaultStorage: storage-1\n \n storages:\n - name: storage-1\n module: file\n configuration:\n ... |
class AdPreview(AdPreviewMixin, AbstractObject):
def __init__(self, api=None):
super(AdPreview, self).__init__()
self._isAdPreview = True
self._api = api
class Field(AbstractObject.Field):
body = 'body'
transformation_spec = 'transformation_spec'
class AdFormat():
... |
def whoami(ctx):
msg = 'Attempting to get user information associated with current API token'
LOGGER.info(msg)
index_event(ctx.obj.es, module=__name__, event_type='INFO', event=msg)
click.echo(f'[*] {msg}')
user = ctx.obj.okta.get_current_user(ctx)
if user:
user.list_roles(ctx, mute=Fals... |
class ReceiptsNormalizer(BaseNormalizer[(ReceiptsV65, ReceiptsBundles)]):
is_normalization_slow = True
def normalize_result(self, cmd: ReceiptsV65) -> ReceiptsBundles:
trie_roots_and_data = map(make_trie_root_and_nodes, cmd.payload)
return tuple(zip(cmd.payload, trie_roots_and_data)) |
def generate_mosquitto_entry(entry: bytes) -> dict:
entry_decoded = _to_str(entry)
(user, _, _, salt_hash, passwd_hash, *_) = re.split('[:$]', entry_decoded)
passwd_entry = f'{user}:$dynamic_82${b64decode(passwd_hash).hex()}$HEX${b64decode(salt_hash).hex()}'
result_entry = {'type': 'mosquitto', 'entry':... |
def initializePlugin(mobject):
mplugin = OpenMayaMPx.MFnPlugin(mobject, 'Ozgur Yilmaz', '1.0.0')
try:
mplugin.registerNode(kPluginNodeTypeName, cpomPluginId, nodeCreator, nodeInitializer)
except:
sys.stderr.write(('Failed to register node: %s' % kPluginNodeTypeName))
raise |
def questions_creator(y):
global options, position_over, j, template_options, answer
template_options = [data['results'][y]['correct_answer'], data['results'][y]['incorrect_answers'][0], data['results'][y]['incorrect_answers'][1], data['results'][y]['incorrect_answers'][2]]
for index in range(4):
pr... |
class OptionPlotoptionsLinePointEvents(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)
... |
class DoltTableNameTransformer(TypeTransformer[DoltTable]):
def __init__(self):
super().__init__(name='DoltTable', t=DoltTable)
def get_literal_type(self, t: Type[DoltTable]) -> LiteralType:
return LiteralType(simple=_type_models.SimpleType.STRUCT, metadata={})
def to_literal(self, ctx: Flyt... |
def test_everything_defined():
(list_instructions, task) = construct_graph_non_aliased(1)
InsertMissingDefinitions().run(task)
assert ([node.instructions for node in task.graph.nodes] == [list_instructions[0:2], list_instructions[2:5], [list_instructions[5]], [list_instructions[6]], list_instructions[7:9]]) |
class TestLoadStandardizedLanguage():
def test_valid_input_with_multi_provider(self, mocker: MockerFixture):
mocker.patch('edenai_apis.utils.languages.load_language_constraints', side_effect=[['en', 'fr'], ['fr', 'es']])
providers = ['provider1', 'provider2']
feature = 'test_feature'
... |
class BodhiClient():
def __init__(self, base_url: str=BASE_URL, client_id: str=CLIENT_ID, id_provider: str=IDP, staging: bool=False, oidc_storage_path: typing.Optional[str]=None):
if staging:
base_url = STG_BASE_URL
id_provider = STG_IDP
client_id = STG_CLIENT_ID
... |
def run_threaded(fal_dbt: FalDbt, parsed: argparse.Namespace, node_graph: NodeGraph) -> int:
from fal.dbt.planner.plan import OriginGraph, FilteredGraph, PlannedGraph, ScriptConnectedGraph
from fal.dbt.planner.schedule import schedule_graph
from fal.dbt.planner.executor import parallel_executor
executio... |
def create_logger(app):
Logger = logging.getLoggerClass()
class DebugLogger(Logger):
def getEffectiveLevel(x):
if ((x.level == 0) and app.debug):
return logging.DEBUG
return Logger.getEffectiveLevel(x)
class DebugHandler(StreamHandler):
def emit(x, rec... |
class LayoutParserComputerVisionModel(ComputerVisionModel):
def __init__(self, config: dict, model_path: str=DEFAULT_MODEL_PATH):
super().__init__()
self.score_threshold = float(config.get('score_threshold', DEFAULT_SCORE_THRESHOLD))
self.avoid_overlapping = bool(config.get('avoid_overlappin... |
def _parse_directive_options(content: str, directive_class: type[Directive], as_yaml: bool, line: (int | None), additional_options: (dict[(str, str)] | None)=None) -> _DirectiveOptions:
yaml_block: (None | str) = None
if content.startswith('---'):
line = (None if (line is None) else (line + 1))
... |
class TestEvalFormula(unittest.TestCase):
def setUp(self):
ws = XLSWorkSheet('Test Worksheet')
ws.insert_column_data('A', ['1.0', '2.0', '3.0'])
ws.insert_column_data('B', ['4.0', '5.0', '6.0'])
ws.insert_column_data('C', ['7.0', '8.0', '9.0'])
self.ws = ws
def test_simpl... |
class Screens():
async def cap_screens(msg: Message):
link = msg.text
duration_process_cmd = ['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=duration', '-of', 'default=noprint_wrappers=1:nokey=1', link]
process = (await asyncio.create_subprocess_exec(*duration_p... |
()
def get_appointment_billing_item_and_rate(doc):
if isinstance(doc, str):
doc = json.loads(doc)
doc = frappe.get_doc(doc)
service_item = None
practitioner_charge = None
department = (doc.medical_department if (doc.doctype == 'Patient Encounter') else doc.department)
service_unit = ... |
class AboutDialog(QDialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
self.setWindowTitle('About')
self.setModal(True)
self.setFixedSize(QSize(600, 480))
self.setWindowFlags((self.windowFlags() & (~ Qt.WindowContextHelpButtonHint)))
self.setWindowFlag... |
class GCIDTest(unittest.TestCase):
def setUpClass(cls):
cls.maxDiff = None
cls.font = FakeFont(['.notdef', 'A', 'B', 'C', 'D'])
def testDecompileToXML(self):
table = newTable('cidg')
table.decompile(CIDG_DATA, self.font)
self.assertEqual(getXML(table.toXML, self.font), CI... |
.compilertest
def test_delta_3(tmp_path):
builder1 = Builder(logger, tmp_path, 'cache_test_1.yaml')
builder2 = Builder(logger, tmp_path, 'cache_test_1.yaml', enable_cache=False)
b1 = builder1.build()
b2 = builder2.build()
builder1.check('baseline', b1, b2, strip_cache_keys=True)
deltas = [f'cach... |
def encrypt_access_request_results(data: Union[(str, bytes)], request_id: str) -> str:
cache = get_cache()
encryption_cache_key = get_encryption_cache_key(privacy_request_id=request_id, encryption_attr='key')
if isinstance(data, bytes):
data = data.decode(CONFIG.security.encoding)
encryption_key... |
.parametrize('alg,expected_hash', list(TINY_DATA_HASHES_HASHLIB.items()), ids=list(TINY_DATA_HASHES_HASHLIB.keys()))
def test_hash_matches_uppercase(alg, expected_hash):
fname = os.path.join(DATA_DIR, 'tiny-data.txt')
check_tiny_data(fname)
known_hash = f'{alg}:{expected_hash.upper()}'
assert hash_match... |
class TestIterateAll():
def test_iterate_all_should_return_an_generator(self):
assert isinstance(iterate_all({'1': 1}), Generator)
.parametrize(('expected', 'args', 'assert_desc'), [([1], {'iterable': {'1': 1}}, "should return [1] for dict {'1': 1}"), ([2], {'iterable': {'2': 2}}, "should return [2] for... |
def parse_int_list_list(list_of_lists: list[list[str]]) -> list[list[Any]]:
new_lists: list[list[Any]] = []
for lst in list_of_lists:
new_list: list[Any] = []
for item in lst:
try:
new_list.append(int(item))
except ValueError:
new_list.appe... |
class ClusterEnvironmentInfo(InternalTelemetryDevice):
serverless_status = serverless.Status.Public
def __init__(self, client, metrics_store, revision_override):
super().__init__()
self.metrics_store = metrics_store
self.client = client
self.revision_override = revision_override
... |
def test_get_alert_template_workflow_param():
alerts_data = AlertsDataMock()
workflow_integration = get_slack_integration_mock(is_slack_workflow=True, slack_token='mock', slack_channel_name='mock')
assert (workflow_integration._get_alert_template(alert=alerts_data.dbt_test).text == json.dumps(alerts_data.db... |
class KnativeIngressProcessor(ManagedKubernetesProcessor):
INGRESS_CLASS: ClassVar[str] = 'ambassador.ingress.networking.knative.dev'
service_dep: ServiceDependency
def __init__(self, manager: ResourceManager):
super().__init__(manager)
self.service_dep = self.deps.want(ServiceDependency)
... |
class DiscoveryPeerBackend(BasePeerBackend):
def __init__(self, event_bus: EndpointAPI) -> None:
self.event_bus = event_bus
async def get_peer_candidates(self, max_candidates: int, should_skip_fn: Callable[([NodeAPI], bool)]) -> Tuple[(NodeAPI, ...)]:
(await self.event_bus.wait_until_any_endpoin... |
def _prepare_trie(trie: Trie[(K, V)], get_storage_root: Callable[([Address], Root)]=None) -> Mapping[(Bytes, Bytes)]:
mapped: MutableMapping[(Bytes, Bytes)] = {}
for (preimage, value) in trie._data.items():
if isinstance(value, Account):
assert (get_storage_root is not None)
addr... |
class OptionSeriesVariablepieSonificationContexttracksMappingLowpass(Options):
def frequency(self) -> 'OptionSeriesVariablepieSonificationContexttracksMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionSeriesVariablepieSonificationContexttracksMappingLowpassFrequency)
def resonanc... |
def process_crawl(spider, setting={}):
p = Process(target=crawl, args=(spider, setting))
p.start()
max_run_time = 30
p.join((max_run_time * 60))
if p.is_alive():
logger.warning('kill the spider:{} which has run {} minutes,'.format(type(spider).__name__), max_run_time)
p.terminate() |
def mask_along_axis_(specgrams, num_masks, min_size, max_size, mask_val=None, axis=2):
device = specgrams.device
if (axis != 3):
specgrams = specgrams.transpose(axis, (- 1))
(n, _, _, a) = specgrams.shape
if (num_masks == 1):
masks = region_mask(n, min_size, max_size, a, device=device)
... |
def lpe_filename(line_program, file_index):
lp_header = line_program.header
file_entries = lp_header['file_entry']
file_entry = file_entries[(file_index - 1)]
dir_index = file_entry['dir_index']
if (dir_index == 0):
return file_entry.name.decode()
directory = lp_header['include_directory... |
class AskForCard(GenericAction):
card_usage = 'drop'
def __init__(self, source: Character, target: Character, card_cls: Type[PhysicalCard], categories: Sequence[str]=('cards', 'showncards')):
self.source = source
self.target = target
self.card_cls = card_cls
self.categories = cat... |
class TestGetSystemsUserManages():
(scope='function')
def url(self, viewer_user) -> str:
return (V1_URL_PREFIX + f'/user/{viewer_user.id}/system-manager')
def test_get_systems_managed_by_user_not_authenticated(self, api_client: TestClient, url: str) -> None:
resp = api_client.get(url, header... |
def visualize_spans(doc: Union[(spacy.tokens.Doc, Dict[(str, str)])], *, spans_key: str='sc', attrs: List[str]=SPAN_ATTRS, show_table: bool=True, title: Optional[str]='Spans', manual: bool=False, displacy_options: Optional[Dict]=None):
if (SPACY_VERSION < Version('3.3.0')):
raise ValueError(f"'visualize_spa... |
def generate_time_plot(methods, datasets, runtimes_per_method, colors):
num_methods = len(methods)
num_datasets = len(datasets)
x_ticks = np.linspace(0.0, 1.0, num_methods)
width = ((0.6 / num_methods) / num_datasets)
spacing = ((0.4 / num_methods) / num_datasets)
(fig, ax1) = plt.subplots()
... |
.django_db
def test_tas_program_activity_multiple_object_classes(client, tas_mulitple_oc_per_tas):
tas = '002-X-0000-000'
submission_year = 2020
query_params = f'?fiscal_year={submission_year}'
resp = client.get(url.format(tas=tas, query_params=query_params))
expected_result = {'fiscal_year': submis... |
class PacketInBodyMiss(base_tests.SimpleDataPlane):
def runTest(self):
logging.info('Running PacketInBodyMiss Test')
of_ports = config['port_map'].keys()
of_ports.sort()
delete_all_flows(self.controller)
logging.info('Sending set_config_request to set miss_send_len... ')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.