code stringlengths 281 23.7M |
|---|
class SecondaryEndpoint(BaseEndpoint):
def __call__(self, id, **kwargs):
parameters = {}
for (key, value) in kwargs.items():
if (key == 'cursor_pagination'):
if (value is True):
parameters['page[size]'] = 100
elif (value is not False):
... |
()
('--server_config_path', default='./server.gz', help='The path to the previous server.gz file from a previous study.')
def resume(server_config_path: str):
try:
config = joblib.load(server_config_path)
except FileNotFoundError:
raise FileNotFoundError(f'''Server config file not found at the p... |
def test_deserialize_exception_with_traceback():
try:
raise Exception('blah')
except Exception as ex:
e = ex
assert (e.__traceback__ is not None)
f: Failure = serialize_exception(e)
assert isinstance(f, Failure)
s = failure_to_str(f)
assert isinstance(s, str)
f2: Failure ... |
def parse_rnde_query(s):
data = {}
m = re.search('^\\/xx\\/rnde\\.php\\?p=(-?\\d+)&f=(\\d+)&m=(\\d)$', s)
if (not m):
data['error'] = 'PARSING ERROR!'
return data
packed_ip = (int(m.group(1)) ^ ).to_bytes(4, byteorder='little', signed=True)
data['ip_reported'] = socket.inet_ntoa(pack... |
(frozen=True)
class QuotedString():
text: str
quote: Quote
def with_quotes(self) -> str:
qc = ("'" if (self.quote == Quote.single) else '"')
esc_qc = f'\{qc}'
match = None
if ('\\' in self.text):
text = (self.text + qc)
pattern = _ESC_QUOTED_STR[qc]
... |
def compare_bkz(classes, matrixf, dimensions, block_sizes, progressive_step_size, seed, threads=2, samples=2, tours=1, pickle_jar=None, logger='compare'):
jobs = []
for dimension in dimensions:
jobs.append((dimension, []))
for block_size in block_sizes:
if (dimension < block_size):
... |
def compute_sparsity(pReferencePoints, pViewpointObj, pArgs, pQueue):
sparsity_list = []
try:
chromosome_names = pViewpointObj.hicMatrix.getChrNames()
for (i, referencePoint) in enumerate(pReferencePoints):
if ((referencePoint is not None) and (referencePoint[0] in chromosome_names))... |
class _SkillComponentLoader():
def __init__(self, configuration: SkillConfig, skill_context: SkillContext, **kwargs: Any):
enforce((configuration.directory is not None), 'Configuration not associated to directory.')
self.configuration = configuration
self.skill_directory = cast(Path, configu... |
def main():
frameworks = ['bottle', 'django', 'falcon', 'falcon-ext', 'flask', 'pecan', 'werkzeug']
parser = argparse.ArgumentParser(description='Falcon benchmark runner')
parser.add_argument('-b', '--benchmark', type=str, action='append', choices=frameworks, dest='frameworks', nargs='+')
parser.add_arg... |
def test_cached_function(isolated_client, capsys, monkeypatch):
import inspect
import time
test_stamp = time.time()
real_getsource = inspect.getsource
def add_timestamp_to_source(func):
return (real_getsource(func) + f'''
# {test_stamp}''')
monkeypatch.setattr(inspect, 'getsource', add_t... |
class OptionSeriesWordcloudSonificationContexttracksMappingPan(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... |
('mopac')
def test_mopac():
geom = geom_loader('lib:h2o.xyz')
calc = MOPAC()
geom.set_calculator(calc)
forces = geom.forces
norm = np.linalg.norm(forces)
energy = geom.energy
assert (energy == pytest.approx((- 0.)))
assert (norm == pytest.approx(0.))
(nus, *_) = geom.get_normal_modes... |
class CheckExtensionAction(argparse.Action):
def __call__(self, parser, namespace, value, option_string=None):
if (os.getuid() == 0):
print('E: You must run nautilus-terminal as regular user to perform an installation check.')
sys.exit(1)
result = ''
retcode = 0
... |
class OptionSeriesPictorialSonificationContexttracksMappingTime(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class Stats(commands.Cog, name='Stats'):
def __init__(self, client):
self.client = client
self.last_time = self.load_stats()
async def cog_check(self, ctx):
return self.client.user_is_admin(ctx.author)
def load_state(self):
with open('../state.json', 'r') as statefile:
... |
def _assert_equal_entries(utest, found, output, count=None):
utest.assertEqual(found[0], output[0])
utest.assertEqual(found[1], (count or output[1]))
(found_time, output_time) = (MyTime.localtime(found[2]), MyTime.localtime(output[2]))
try:
utest.assertEqual(found_time, output_time)
except A... |
def test_get_identity():
for source_id in [proto_source.SourceRepository.SourceIdentity.SRCID_UNSPECIFIED, proto_source.SourceRepository.SourceIdentity.SRCID_ENVOY, proto_source.SourceRepository.SourceIdentity.SRCID_NIGHTHAWK]:
source_repository = proto_source.SourceRepository(identity=source_id)
tr... |
.skipif((not coreapi), reason='coreapi is not installed')
def test_schema_handles_exception():
schema_view = get_schema_view(permission_classes=[DenyAllUsingPermissionDenied])
request = factory.get('/')
response = schema_view(request)
response.render()
assert (response.status_code == 403)
assert... |
class NesterovAcceleratedGradient():
def __init__(self, learning_rate=0.001, momentum=0.4):
self.learning_rate = learning_rate
self.momentum = momentum
self.w_updt = np.array([])
def update(self, w, grad_func):
approx_future_grad = np.clip(grad_func((w - (self.momentum * self.w_u... |
def test_compiler_errors(solc4source, solc5source):
with pytest.raises(CompilerError):
compiler.compile_and_format({'path.sol': solc4source}, solc_version='0.5.7')
with pytest.raises(CompilerError):
compiler.compile_and_format({'path.sol': solc5source}, solc_version='0.4.25') |
def is_boxplot(name, f):
name_underscore = (os.path.basename(strip_ngs_extensions(name)) + '_')
name_dot = (os.path.basename(utils.rootname(name)) + '.')
if f.endswith('_boxplot.png'):
if (f.startswith(name_dot) or f.startswith(name_underscore)):
return True
f1 = f.replace('_QV',... |
def generateTCF3(iterationsMap, iteration, t):
msg = generateGenericMessage('EiffelTestCaseFinishedEvent', t, '1.0.0', 'TCF3', iteration)
link(msg, iterationsMap[iteration]['TCT3'], 'TEST_CASE_EXECUTION')
msg['data']['outcome'] = {'verdict': randomizeVerdict(0.99), 'conclusion': 'SUCCESSFUL'}
return msg |
def lambda_handler(event, context):
print(event)
cognito_id = event['requestContext']['authorizer']['claims']['sub']
if (event['body'] != None):
event_body = json.loads(event['body'])
if ((event_body['date_range'] == 7) or (event_body['date_range'] == 30)):
date_range = event_bod... |
class GroupTaggerTreeStore(Gtk.TreeStore, Gtk.TreeDragSource, Gtk.TreeDragDest):
def __init__(self):
super(GroupTaggerTreeStore, self).__init__(GObject.TYPE_BOOLEAN, GObject.TYPE_STRING, GObject.TYPE_BOOLEAN, GObject.TYPE_INT)
self.set_sort_column_id(1, Gtk.SortType.ASCENDING)
def add_category(s... |
def check_init_func():
with db.session_context() as sess:
raw_cur = sess.connection().connection.cursor()
cmd = "\n\t\t\tCREATE OR REPLACE FUNCTION upsert_link_raw(\n\t\t\t\t\turl_v text,\n\t\t\t\t\tstarturl_v text,\n\t\t\t\t\tnetloc_v text,\n\t\t\t\t\tdistance_v integer,\n\t\t\t\t\tpriority_v integ... |
def test_get_faas_data():
context = mock.Mock(invocation_id='fooid', function_name='fname')
with mock.patch.dict(os.environ, {'WEBSITE_OWNER_NAME': '2491fc8e-f7c1-4020-b9c6-fd16+my-resource-group-ARegionShortNamewebspace', 'WEBSITE_SITE_NAME': 'foo', 'WEBSITE_RESOURCE_GROUP': 'bar'}):
data = get_faas_da... |
def test_convert_marshmallow_json_schema_to_python_class():
class Foo(DataClassJsonMixin):
x: int
y: str
schema = JSONSchema().dump(typing.cast(DataClassJsonMixin, Foo).schema())
foo_class = convert_marshmallow_json_schema_to_python_class(schema['definitions'], 'FooSchema')
foo = foo_cla... |
def smartquotes(state: StateCore) -> None:
if (not state.md.options.typographer):
return
for token in state.tokens:
if ((token.type != 'inline') or (not QUOTE_RE.search(token.content))):
continue
if (token.children is not None):
process_inlines(token.children, sta... |
class Timer():
_formats = ('{:,} d', '{} h', '{} m', '{} s', '{} ms')
def __init__(self, message: Optional[str]=None, success_logger: Callable=print, failure_logger: Callable=print):
self.message = message
self.success_logger = success_logger
self.failure_logger = failure_logger
... |
class Empty(AmbassadorTest):
single_namespace = True
namespace = 'empty-namespace'
extra_ports = [8877]
def init(self):
if EDGE_STACK:
self.xfail = 'XFailing for now'
self.manifest_envs += '\n - name: AMBASSADOR_READY_PORT\n value: "8500"\n'
def variants(cls) -> G... |
def test_dashboard(client):
response = client.get('/', follow_redirects=True)
assert (response.status_code == 200)
assert (b'Dashboard' in response.data)
assert (b'Statistics' in response.data)
assert (b'Recent Calls' in response.data)
assert (b'Calls per Day' in response.data) |
def format_message(inserted):
created = [i for i in inserted if i['created']]
unmatched = [i for i in inserted if (i['vmpp_id'] is None)]
new_mismatched = [i for i in inserted if ((i['vmpp_id'] is not None) and (i['supplied_vmpp_id'] is not None) and (i['vmpp_id'] != i['supplied_vmpp_id']) and i['created'])... |
def count_of_records_to_process_in_delta(config: dict, spark: 'pyspark.sql.SparkSession') -> Tuple[(int, int, int)]:
start = perf_counter()
min_max_count_sql = obtain_min_max_count_sql(config).replace('"', '')
results = spark.sql(min_max_count_sql).collect()[0].asDict()
(min_id, max_id, count) = (result... |
class RunAEATestCase(TestCase):
def test_run_aea_positive_mock(self):
ctx = mock.Mock()
aea = mock.Mock()
ctx.config = {'skip_consistency_check': True}
with mock.patch('aea.cli.run._build_aea', return_value=aea):
run_aea(ctx, ['author/name:0.1.0'], 'env_file', False)
... |
(scope='function')
def attentive_email_connection_config(db: Session) -> Generator:
connection_config = ConnectionConfig.create(db=db, data={'name': 'Attentive', 'key': 'my_email_connection_config', 'connection_type': ConnectionType.attentive, 'access': AccessLevel.write, 'secrets': {'test_email_address': 'processo... |
def extractRainofsnowCom(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 tagm... |
def enter():
if (not isRoot.isRoot()):
sys.exit(text.notRoot)
rootDir = getRootDir.getEnvsDir()
name = getArg.getArg(0)
if (not name):
sys.exit(text.enterHelper)
template = getFlag.getFlag('-t')
if template:
create.executeTemplate(template)
path = (rootDir + name)
... |
class AuthService():
login_time = timezone.now()
async def swagger_login(self, *, form_data: OAuth2PasswordRequestForm) -> tuple[(str, User)]:
async with async_db_session() as db:
current_user = (await UserDao.get_by_username(db, form_data.username))
if (not current_user):
... |
class Test_DecimalField():
def test_init_options(self):
assert (DecimalField(max_digits=3).max_digits == 3)
assert (DecimalField(max_decimal_places=4).max_decimal_places == 4)
f = DecimalField(max_digits=3, max_decimal_places=4)
f2 = f.clone()
assert (f2.max_digits == 3)
... |
class Challenge():
def __init__(self):
(a, b, p, o, G, Go) = random.choice(PRECOMPUTED_CURVES)
self._a = a
self._b = b
self._p = p
self.curve = Curve('generic curve', p, a, b, Go, G[0], G[1])
self.curve_order = o
self.generator_order = Go
self.generato... |
def test_three_pool_arbitrage(get_transaction_hashes, get_addresses):
block_number = 123
[transaction_hash] = get_transaction_hashes(1)
[account_address, first_pool_address, second_pool_address, third_pool_address, first_token_address, second_token_address, third_token_address] = get_addresses(7)
first_... |
def serp_youtube(key, q=None, channelId=None, channelType=None, eventType=None, forContentOwner=None, forDeveloper=None, forMine=None, location=None, locationRadius=None, maxResults=None, onBehalfOfContentOwner=None, order=None, pageToken=None, publishedAfter=None, publishedBefore=None, regionCode=None, relatedToVideoI... |
class MetaMappingCalendar(MetaMapping):
supported_calendar_component = 'VEVENT'
_mappings = MetaMapping._mappings.copy()
_mappings.update({'C:calendar-description': ('description', None, None), 'ICAL:calendar-color': ('color', IntToRgb, RgbToInt)})
MetaMapping._reverse_mapping(_mappings) |
class TextSystem(object):
def __init__(self, args):
if (not args.show_log):
logger.setLevel(logging.INFO)
self.text_detector = predict_det.TextDetector(args)
self.text_recognizer = predict_rec.TextRecognizer(args)
self.use_angle_cls = args.use_angle_cls
self.drop_... |
def extension_controller_extender(data, fos):
vdom = data['vdom']
state = data['state']
extension_controller_extender_data = data['extension_controller_extender']
extension_controller_extender_data = flatten_multilists_attributes(extension_controller_extender_data)
filtered_data = underscore_to_hyph... |
class SecondTask(ExampleTask):
id = 'example.second_task'
name = 'Second Multi-Tab Editor'
menu_bar = SMenuBar(SMenu(TaskAction(name='New', method='new', accelerator='Ctrl+N'), id='File', name='&File'), SMenu(DockPaneToggleGroup(), TaskToggleGroup(), id='View', name='&View'))
tool_bars = [SToolBar(TaskA... |
class OptionSeriesArcdiagramSonificationDefaultinstrumentoptionsMappingFrequency(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... |
def backup(arg):
arg = path.expanduser(arg)
if ('*' in arg):
for file in glob.iglob(arg):
shutil.copyfile(file, (file + time.strftime('%Y-%m-%d_%H%M%S')))
else:
if (not is_file(arg)):
return
shutil.copyfile(arg, (arg + time.strftime('%Y-%m-%d_%H%M%S'))) |
def simple_verbosity_option(logger_: logging.Logger, *names: str, **kwargs: Any) -> Callable:
if (not names):
names = ('--verbosity', '-v')
kwargs.setdefault('default', 'INFO')
kwargs.setdefault('type', click.Choice(LOG_LEVELS, case_sensitive=False))
kwargs.setdefault('metavar', 'LVL')
kwarg... |
class NotificationTestBase(object):
def _prepare_events(self):
self.client.namespace = 'namespace_a'
self.client.sender = 'sender'
self.client.send_event(Event(event_key=EventKey(event_name='key'), message='value1'))
self.client.namespace = 'namespace_b'
self.client.send_even... |
def test_correlate():
outfile_heatmap = NamedTemporaryFile(suffix='heatmap.png', prefix='hicexplorer_test', delete=False)
outfile_scatter = NamedTemporaryFile(suffix='scatter.png', prefix='hicexplorer_test', delete=False)
args = "--matrices {} {} --labels 'first' 'second' --method spearman --log1p --colorM... |
def visualize_parser(doc: Union[(spacy.tokens.Doc, List[Dict[(str, str)]])], *, title: Optional[str]='Dependency Parse & Part-of-speech tags', key: Optional[str]=None, manual: bool=False, displacy_options: Optional[Dict]=None) -> None:
if (displacy_options is None):
displacy_options = dict()
if title:
... |
def test_06_take_control_02(interact):
with ExitStack() as stack:
mocks = [mock.patch('termios.tcsetattr'), mock.patch('termios.tcgetattr'), mock.patch('tty.setraw'), mock.patch('tty.setcbreak')]
[stack.enter_context(m) for m in mocks]
select_mock = stack.enter_context(mock.patch('select.sel... |
class OptionSeriesOrganizationSonificationDefaultspeechoptionsPointgrouping(Options):
def algorithm(self):
return self._config_get('last')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bo... |
def search(searchengine, what, sort, maxresult=20):
engines = glob(path.join(path.dirname(__file__), 'engines', '*.py'))
enginclasslist = []
for engine in engines:
engi = path.basename(engine).split('.')[0].strip()
if ((len(engi) == 0) or engi.startswith('_')):
continue
i... |
def make_axes_innermost(ndim, axes):
orig_order = list(range(ndim))
outer_axes = [i for i in orig_order if (i not in axes)]
transpose_to = (outer_axes + list(axes))
transpose_from = ([None] * ndim)
for (i, axis) in enumerate(transpose_to):
transpose_from[axis] = i
return (tuple(transpose... |
.parametrize('do_final_record', (True, False))
def test_journal_db_discard_to_deleted(journal_db, do_final_record):
journal_db[1] = b'original-value'
checkpoint_created = journal_db.record()
del journal_db[1]
checkpoint_deleted = journal_db.record()
journal_db[1] = b'value-after-delete'
if do_fi... |
class EnCh(hass.Hass):
def lg(self, msg: str, *args: Any, icon: Optional[str]=None, repeat: int=1, **kwargs: Any) -> None:
kwargs.setdefault('ascii_encode', False)
message = f"{(f'{icon} ' if icon else ' ')}{msg}"
_ = [self.log(message, *args, **kwargs) for _ in range(repeat)]
async def ... |
class OptionPlotoptionsLineStatesHover(Options):
def animation(self) -> 'OptionPlotoptionsLineStatesHoverAnimation':
return self._config_sub_data('animation', OptionPlotoptionsLineStatesHoverAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
se... |
class OptionPlotoptionsColumnrangeSonificationDefaultspeechoptionsPointgrouping(Options):
def algorithm(self):
return self._config_get('last')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag... |
def test_no_timestamp_modify(tmp_path):
file_path = (tmp_path / 'test.md')
file_path.write_bytes(b'lol\n')
initial_access_time = 0
initial_mod_time = 0
os.utime(file_path, (initial_access_time, initial_mod_time))
mdformat.file(file_path)
assert (os.path.getmtime(file_path) == initial_mod_tim... |
.long_test
.download
.skipif(NO_MARS, reason='No access to MARS')
.skip(reason='No access to MARS for now (DHS move)')
def test_mars_grib_2():
s = load_source('mars', param=['2t', 'msl'], levtype='sfc', area=[50, (- 50), 20, 50], grid=[1, 1], date='2012-12-13', split_on='param')
assert (len(s) == 2) |
class RewardWrapper(Wrapper[EnvType], ABC):
def step(self, action) -> Tuple[(Any, Any, bool, Dict[(Any, Any)])]:
(observation, reward, done, info) = self.env.step(action)
return (observation, self.reward(reward), done, info)
def reward(self, reward: Any) -> Any:
(Wrapper)
def get_observa... |
.parametrize('method,expected', (('test_endpoint', 'value-a'), ('not_implemented', NotImplementedError)))
def test_result_middleware(w3, method, expected):
def _callback(method, params):
return params[0]
w3.middleware_onion.add(construct_result_generator_middleware({'test_endpoint': _callback}))
if ... |
class BoundedSemaphore(Semaphore):
def __init__(self, value=1):
super().__init__(value)
self.original_counter = value
def release(self, blocking=True):
if (self.counter >= self.original_counter):
raise ValueError('Semaphore released too many times')
return super().rel... |
class TestGraphTaskAffectedConsentSystems():
()
def mock_graph_task(self, db, mailchimp_transactional_connection_config_no_secrets, privacy_request_with_consent_policy):
task_resources = TaskResources(privacy_request_with_consent_policy, privacy_request_with_consent_policy.policy, [mailchimp_transaction... |
class queue_stats_request(stats_request):
version = 2
type = 18
stats_type = 5
def __init__(self, xid=None, flags=None, port_no=None, queue_id=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
... |
class OptionPlotoptionsArearangeSonificationTracksPointgrouping(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):
... |
class _TestGlyph3(_TestGlyph):
def drawPoints(self, pen):
pen.beginPath(identifier='abc')
pen.addPoint((0.0, 0.0), 'line', False, 'start', identifier='0000')
pen.addPoint((10, 110), 'line', False, None, identifier='0001')
pen.endPath()
pen.beginPath(identifier='pth2')
... |
class OptionSeriesHeatmapSonificationTracksMappingVolume(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._c... |
def test_correct_lag_when_using_freq(df_time):
date_time = [pd.Timestamp('2020-05-15 12:00:00'), pd.Timestamp('2020-05-15 12:15:00'), pd.Timestamp('2020-05-15 12:30:00'), pd.Timestamp('2020-05-15 12:45:00'), pd.Timestamp('2020-05-15 13:00:00')]
expected_results = {'ambient_temp': [31.31, 31.51, 32.15, 32.39, 32... |
class MeetAllCondition(Condition):
def __init__(self, name: str, conditions: List[Condition]):
events = []
for c in conditions:
events.extend(c.expect_event_keys)
super().__init__(expect_event_keys=events)
self.conditions = conditions
self.name = name
def is_m... |
()
('path', nargs=(- 1), type=click.Path(exists=True, dir_okay=False))
('--kernel', help='The name of the Jupyter kernel to attach to this markdown file.')
def init(path, kernel):
from jupyter_book.utils import init_myst_file
for ipath in path:
init_myst_file(ipath, kernel, verbose=True) |
class EditReplyForm(ReplyForm):
def __init__(self, post_id, *args, **kwargs):
self.form = super(EditReplyForm, self).__init__(*args, **kwargs)
self.uploads.choices = generate_choices('Post', id=post_id)
uploads = MultiCheckBoxField('Label', coerce=int)
submit = SubmitField(lazy_gettext('Edit... |
class BenjiTestCaseBase(TestCaseBase):
def setUp(self):
super().setUp()
IOFactory.initialize(self.config)
StorageFactory.initialize(self.config)
def tearDown(self):
StorageFactory.close()
super().tearDown()
def benji_open(self, init_database=False, in_memory_database=... |
def get_dep_names(parsed_lockfile: dict, include_devel: bool=True) -> list:
dep_names = []
for (section, packages) in parsed_lockfile.items():
if (section == 'package'):
for package in packages:
if (((package['category'] == 'dev') and include_devel and (not package['optional'... |
def test_runs_before():
def t2(a: str, b: str) -> str:
return (b + a)
()
def sleep_task(a: int) -> str:
a = (a + 2)
return ('world-' + str(a))
def my_subwf(a: int) -> (typing.List[str], int):
s = []
for i in range(a):
s.append(sleep_task(a=i))
... |
def extractThesecretgardenWordpressCom(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 CreditMemo(DeleteMixin, QuickbooksTransactionEntity, QuickbooksManagedObject, LinkedTxnMixin):
class_dict = {'BillAddr': Address, 'ShipAddr': Address, 'DepartmentRef': Ref, 'ClassRef': Ref, 'CustomerRef': Ref, 'CurrencyRef': Ref, 'SalesTermRef': Ref, 'CustomerMemo': CustomerMemo, 'BillEmail': EmailAddress, 'T... |
.django_db
.skip(reason='Test based on pre-databricks loader code. Remove when fully cut over.')
def test_load_source_assistance_by_ids():
source_assistance_id_list = [101, 201, 301]
_assemble_source_assistance_records(source_assistance_id_list)
call_command('fabs_nightly_loader', '--ids', *source_assistanc... |
class TestAllOF11(unittest.TestCase):
def setUp(self):
mods = [ofp.action, ofp.message, ofp.common]
self.klasses = [klass for mod in mods for klass in mod.__dict__.values() if (isinstance(klass, type) and issubclass(klass, loxi.OFObject) and (not hasattr(klass, 'subtypes')))]
self.klasses.so... |
('/get_workflow_ports_md', methods=['POST'])
def get_workflow_ports_md():
wf = request.get_json(True)
try:
wf_unique_id = str(wf['wf_unique_id'])
except Exception as e:
return jsonify({'Error in your workflow': str(e)})
try:
result_dict = fsh.read_workflow_ports_meta_data(wf_uniq... |
def fatal(msg, code=1, end='\n'):
outfile = (args.log if args.log else sys.stderr)
tstamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:(- 3)]
full_msg = ('{:s}: [E] {:s}'.format(tstamp, msg) if args.log else '[E] {:s}'.format(msg))
print(full_msg, file=outfile, end=end)
sys.exit(code) |
class NodeType(GivElm):
total = 0
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = kwargs['name']
def __repr__(self):
return '(NodeType {})'.format(self.name)
def __str__(self):
return repr(self)
def stat(self):
super().stat()... |
def assert_valid_fields(transaction_dict):
missing_keys = REQUIRED_TRANSACTION_KEYS.difference(transaction_dict.keys())
if missing_keys:
raise TypeError(f'Transaction must include these fields: {repr(missing_keys)}')
superfluous_keys = set(transaction_dict.keys()).difference(ALLOWED_TRANSACTION_KEYS... |
def trange_years(start, end, years):
dt_start = safe_fromtimestamp(start)
dt_end = safe_fromtimestamp(end)
dyears = ((dt_start.year - 2000) % years)
if (dyears < 0):
dyears += years
dt = datetime((dt_start.year - dyears), 1, 1, 0, 0, 0, 0)
while (dt < dt_start):
dt = _advance_yea... |
def handle_images_found_in_markdown(markdown: str, new_img_dir: Path, lib_dir: Path) -> str:
markdown_image_pattern = re.compile('!\\[[^\\]]*\\]\\((.*?)(?=\\"|\\))(\\".*\\")?\\)')
searches = list(re.finditer(markdown_image_pattern, markdown))
if (not searches):
return markdown
markdown_list = li... |
def get_segmentation_label_result(layout_document: LayoutDocument, document_context: TrainingDataDocumentContext) -> LayoutDocumentLabelResult:
segmentation_label_model_data_lists = list(iter_labeled_model_data_list_for_model_and_layout_documents(model=document_context.fulltext_models.segmentation_model, model_layo... |
def set_logging_file(fname: str, filemode: str='w', level: LogValue=DEFAULT_LEVEL) -> None:
if (filemode not in 'wa'):
raise ValueError("filemode must be either 'w' or 'a'")
if ('file' in log.handlers):
try:
log.handlers['file'].file.close()
except Exception:
log.... |
def test_deprecated_setting():
watermark_hash_data = b'\x00$\x00\x03\x00 AAECAwQFBgcICQoLDA0ODw==\x00\x00\x00\x00\x00\x00\x00\x00'
inject_options_data = b'\x00$\x00\x01\x00\x02\x00\x03'
beacon1 = beacon.BeaconConfig(watermark_hash_data)
beacon2 = beacon.BeaconConfig(inject_options_data)
SETTING_INJE... |
class EfuseMacField(EfuseField):
def check_format(self, new_value_str):
if (new_value_str is None):
raise esptool.FatalError('Required MAC Address in AA:CD:EF:01:02:03 format!')
if (new_value_str.count(':') != 5):
raise esptool.FatalError('MAC Address needs to be a 6-byte hex... |
def extractKaystlsSite(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 tagmap... |
(scope='function')
def datadog_connection_config(db: session, datadog_config, datadog_secrets) -> Generator:
fides_key = datadog_config['fides_key']
connection_config = ConnectionConfig.create(db=db, data={'key': fides_key, 'name': fides_key, 'connection_type': ConnectionType.saas, 'access': AccessLevel.write, ... |
('Util.sdlog.error')
('Util.sdlog.warning')
('Util.sdlog.info')
def test_obtain_lock(mocked_info, mocked_warning, mocked_error):
with TemporaryDirectory() as tmpdir, mock.patch('Util.LOCK_DIRECTORY', tmpdir):
basename = 'test-obtain-lock.lock'
pid_str = str(os.getpid())
lh = util.obtain_lock... |
def func_args_hash_func(target):
import hashlib
import inspect
mod = inspect.getmodule(target)
path_hash = hashlib.sha224(bytes(mod.__file__, 'utf-8')).hexdigest()[:4]
def _cache_key(args, kwargs):
cache_key_obj = (to_hashable(args), to_hashable(kwargs))
cache_key_hash = hashlib.sha2... |
def _truncated_normal_sample(key, mean, std, noise_clip=0.3):
noise = (jax.random.normal(key=key, shape=mean.shape) * std)
noise = jnp.clip(noise, (- noise_clip), noise_clip)
sample = (mean + noise)
clipped_sample = jnp.clip(sample, (- 1), 1)
return ((sample - jax.lax.stop_gradient(sample)) + jax.la... |
def _build_submission_queryset_for_derived_fields(submission_closed_period_queryset, column_name):
if submission_closed_period_queryset:
queryset = Case(When(submission_closed_period_queryset, then=F(column_name)), default=Cast(Value(None), DecimalField(max_digits=23, decimal_places=2)), output_field=Decima... |
class GrpcExplainer(explain_pb2_grpc.ExplainServicer):
HANDLE_KEY = 'handle'
def _get_handle(self, context):
metadata = context.invocation_metadata()
metadata_dict = {}
for (key, value) in metadata:
metadata_dict[key] = value
return metadata_dict[self.HANDLE_KEY]
... |
def fetch_consumption(zone_key: str='IQ', session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> dict:
if target_datetime:
raise NotImplementedError('This parser is not yet able to parse past dates')
r = (session or requests.session())
(data, ... |
class DeleteComposableTemplate(Runner):
async def __call__(self, es, params):
templates = mandatory(params, 'templates', self)
only_if_exists = mandatory(params, 'only-if-exists', self)
request_params = mandatory(params, 'request-params', self)
ops_count = 0
prior_destructive... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.