code stringlengths 281 23.7M |
|---|
class PrivacyNotice(PrivacyNoticeBase, Base):
origin = Column(String, ForeignKey(PrivacyNoticeTemplate.id_field_path), nullable=True)
version = Column(Float, nullable=False, default=1.0)
histories = relationship('PrivacyNoticeHistory', backref='privacy_notice', lazy='dynamic')
def privacy_notice_history... |
class OptionPlotoptionsDependencywheelSonificationDefaultspeechoptionsMappingTime(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, te... |
def create_fee_validity(appointment):
if patient_has_validity(appointment):
return
fee_validity = frappe.new_doc('Fee Validity')
fee_validity.practitioner = appointment.practitioner
fee_validity.patient = appointment.patient
fee_validity.medical_department = appointment.department
fee_va... |
class OptionSeriesArcdiagramLevelsDatalabels(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._conf... |
()
('--profiles-dir', '-p', type=click.Path(exists=True), default=None, help='Which directory to look in for the profiles.yml file. If not set, edr will look in the current working directory first, then HOME/.dbt/')
_context
def debug(ctx, profiles_dir):
config = Config(profiles_dir=profiles_dir)
anonymous_trac... |
def match_arp_target(self, of_ports, priority=None):
pkt_match = simple_arp_packet()
match = parse.packet_to_flow_match(pkt_match)
self.assertTrue((match is not None), 'Could not generate flow match from pkt')
match.wildcards = (((ofp.OFPFW_ALL ^ ofp.OFPFW_DL_TYPE) ^ ofp.OFPFW_NW_PROTO) ^ ofp.OFPFW_NW_D... |
class FlattenConcatStateValueNet(FlattenConcatBaseNet):
def __init__(self, obs_shapes: Dict[(str, Sequence[int])], hidden_units: List[int], non_lin: nn.Module):
super().__init__(obs_shapes, hidden_units, non_lin)
self.perception_dict['value'] = LinearOutputBlock(in_keys='latent', out_keys='value', i... |
def send_photo(token, chat_id, photo, caption=None, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None, timeout=None, caption_entities=None, allow_sending_without_reply=None, protect_content=None, message_thread_id=None, has_spoiler=None):
method_url = 'sendPhoto'
payload = ... |
class TestDailyBarsData():
data_classes = []
if os.path.exists(config['daily_bars_data_path']):
data_classes.append(DailyBarsData)
if (secrets['mongodb_adminusername'] is not None):
data_classes.append(DailyBarsDataMongo)
.parametrize('data_loader_class', data_classes)
.parametrize([... |
def get_unique_duplicated_dict(df, subset=None, only_dupl_entries=False):
is_dupl = df.duplicated(subset=subset, keep=False)
uniq_dupl_dict = _get_unique_duplicated_dict(df[is_dupl], subset)
if (not only_dupl_entries):
others = df.index[(~ is_dupl)]
uniq_empties = {o: [] for o in others}
... |
def test_event_graph_accumulated_time(mocker: Any) -> None:
message = DeferredMessage(MyMessage, 'unittest_args', kwargs_field='unittest_kwargs')
topic = Topic(MyMessage)
start = Event(message, topic, 0.0, 1.0)
graph = EventGraph(start)
parent = Event(message, topic, 0.0, 1.0)
child_1 = Event(me... |
class OptionPlotoptionsWindbarbSonificationContexttracksMappingPan(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 pytest_generate_tests(metafunc):
if ('fast_math' in metafunc.fixturenames):
fm = metafunc.config.option.fast_math
fms = dict(both=[False, True], no=[False], yes=[True])[fm]
fm_ids = [{False: 'nofm', True: 'fm'}[fm] for fm in fms]
metafunc.parametrize('fast_math', fms, ids=fm_ids)... |
.parametrize('vm_class', MAINNET_VMS[:13])
def test_selfdestruct_does_not_issue_deprecation_warning_pre_shanghai(vm_class):
with warnings.catch_warnings():
warnings.simplefilter('error')
run_computation(setup_vm(vm_class), CANONICAL_ADDRESS_B, code=assemble(opcode_values.SELFDESTRUCT)) |
.skipif((not has_torch), reason='needs PyTorch')
.skipif((not has_torch_cuda_gpu), reason='needs a GPU')
.skipif((not has_torch_amp), reason='requires PyTorch with mixed-precision support')
(X=one_of(tensors(), lists(tensors()), tuples(tensors())))
(deadline=None)
def test_scale_random_inputs(X):
import torch
d... |
class TestListOverrides(BodhiClientTestCase):
def test_with_user(self, mocker):
client = bindings.BodhiClient()
client.send_request = mocker.MagicMock(return_value='response')
response = client.list_overrides(user='bowlofeggs')
assert (response == 'response')
client.send_requ... |
.parametrize('expiry_date, ok', [(TOMORROW, True), (TWO_DAYS_AGO, False)])
def test_expiry_date(rf: RequestFactory, expiry_date: dt.datetime, ok: bool) -> None:
(_, key) = APIKey.objects.create_key(name='test', expiry_date=expiry_date)
authorization = f'Api-Key {key}'
request = rf.get('/test/', HTTP_AUTHORI... |
def test_copy_with_replacing_subcontainer_providers():
class X(containers.DeclarativeContainer):
foo = providers.Dependency(instance_of=str)
def build_x():
return X(foo='1')
class A(containers.DeclarativeContainer):
x = providers.DependenciesContainer(**X.providers)
y = x.foo... |
class RawSynchronousFlyteClient(object):
_dataproxy_stub: DataProxyServiceStub
def __init__(self, cfg: PlatformConfig, **kwargs):
self._cfg = cfg
self._channel = wrap_exceptions_channel(cfg, upgrade_channel_to_authenticated(cfg, upgrade_channel_to_proxy_authenticated(cfg, get_channel(cfg))))
... |
def test_elasticsearch_download_cached(common_test_data):
external_load_dates = [{'external_data_type__external_data_type_id': EXTERNAL_DATA_TYPE_DICT['fabs'], 'last_load_date': datetime(2021, 1, 30, 12, 0, 0, 0, timezone.utc)}, {'external_data_type__external_data_type_id': EXTERNAL_DATA_TYPE_DICT['fpds'], 'last_lo... |
class CssInline(Attrs):
classname: str = None
def __init__(self, component: primitives.HtmlModel=None, page: primitives.PageModel=None):
super(CssInline, self).__init__(component, page=page)
def stroke_dasharray(self):
return self.css('stroke-dasharray')
_dasharray.setter
def stroke_... |
class TestHelloWorldSkill(AEATestCaseEmpty):
capture_log = True
def test_hello_world(self):
self.generate_private_key()
self.add_private_key()
self.add_item('skill', 'fetchai/hello_world:0.1.5')
process = self.run_agent()
is_running = self.is_running(process)
asse... |
class OptionPlotoptionsArearangeMarkerStatesHover(Options):
def animation(self) -> 'OptionPlotoptionsArearangeMarkerStatesHoverAnimation':
return self._config_sub_data('animation', OptionPlotoptionsArearangeMarkerStatesHoverAnimation)
def enabled(self):
return self._config_get(True)
def enab... |
class FirewallIPSet():
def __init__(self, fw):
self._fw = fw
self._ipsets = {}
def __repr__(self):
return ('%s(%r)' % (self.__class__, self._ipsets))
def cleanup(self):
self._ipsets.clear()
def check_ipset(self, name):
if (name not in self.get_ipsets()):
... |
def parse_concessions_from_html(html, url=None):
if (url in UNPARSEABLE_URLS):
return
doc = bs4.BeautifulSoup(html, 'html.parser')
publish_date = get_single_item((parse_date(f"{match['day']} {match['month']} {match['year']}") for match in PUBLISH_DATE_RE.finditer(doc.text)))
date = get_single_it... |
class nvidia_arch(nn.Module):
def __str__(self):
return 'this is nvidia architecture'
def __init__(self):
super().__init__()
self.conv1 = nn.Sequential(nn.Conv2d(in_channels=1, out_channels=24, kernel_size=(5, 5), stride=(2, 2)), nn.ReLU(), nn.Conv2d(in_channels=24, out_channels=36, kern... |
def gen_struct_typedefs(out):
out.write('\n/* LOCI object typedefs */\n')
for cls in of_g.standard_class_order:
template = 'typedef of_object_t %(cls)s_t;\n'
out.write((template % dict(cls=cls)))
out.write('\n/\n *\n * Additional of_object defines\n * These are needed for some static inline ... |
class OptionSeriesNetworkgraphSonificationTracksMappingTremoloSpeed(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 Dataset(audioset.Dataset):
splits = {'train': ['train_si284'], 'validation': ['dev_93'], 'test': ['eval_92']}
sample_rate = 16000
def __init__(self, data_path, preprocessor, split, augment=False):
augmentation = []
if augment:
augmentation = [torchaudio.transforms.Frequency... |
def test_flush_mid_execution(accounts, tester):
addr = accounts[1]
value = ['blahblah', addr, ['yesyesyes', '0x1234']]
tester.setTuple(value)
with brownie.multicall:
tester.getTuple(addr)
assert (len([x for v in brownie.multicall._pending_calls.values() for x in v]) == 1)
brownie... |
def check_dependencies(ctx):
nofail = False
safety = which('safety')
if (not safety):
pipx = which('pipx')
if pipx:
safety = f'{pipx} run safety'
else:
safety = 'safety'
nofail = True
ctx.run(f'poetry export -f requirements.txt --without-hashes... |
def create_chunks(ffrom, fto, suffix_array_algorithm, use_mmap):
if (not use_mmap):
return create_chunks_heap(ffrom, fto, suffix_array_algorithm)
try:
return create_chunks_mmap(ffrom, fto, suffix_array_algorithm)
except (io.UnsupportedOperation, ValueError):
return create_chunks_heap... |
def export_cache_of_all_cacheable_nodes(start_frame=None, end_frame=None, handles=0, step=1, isolate=True, unload_refs=True, cache_format=ALEMBIC):
cacheable_nodes = get_cacheable_nodes()
return export_cache_of_nodes(cacheable_nodes=cacheable_nodes, start_frame=start_frame, end_frame=end_frame, handles=handles,... |
def _generate_security_groups(config_key):
raw_default_groups = validate_key_values(CONFIG, 'base', config_key, default='')
default_groups = _convert_string_to_native(raw_default_groups)
LOG.debug('Default security group for %s is %s', config_key, default_groups)
entries = {}
for env in ENVS:
... |
def extractLilacbluetranslationBlogspotCom(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... |
def _icmp_types_fragments(protocol, type, code=None):
fragments = [{'match': {'left': {'payload': {'protocol': protocol, 'field': 'type'}}, 'op': '==', 'right': type}}]
if (code is not None):
fragments.append({'match': {'left': {'payload': {'protocol': protocol, 'field': 'code'}}, 'op': '==', 'right': c... |
class NonlinearVariationalSolver(OptionsManager, NonlinearVariationalSolverMixin):
DEFAULT_SNES_PARAMETERS = {'snes_type': 'newtonls', 'snes_linesearch_type': 'basic'}
DEFAULT_KSP_PARAMETERS = solving_utils.DEFAULT_KSP_PARAMETERS.copy()
DEFAULT_KSP_PARAMETERS['ksp_rtol'] = 1e-05
.EventDecorator()
_a... |
class QtNodeState(lg.State):
app: typing.Optional[QtWidgets.QApplication] = None
keypress_callbacks: typing.Optional[typing.Dict[(int, typing.Callable[(..., typing.Any)])]] = None
view: typing.Optional[MainWindow] = None
current_trial: typing.Optional[Trial] = None
current_trial_started: bool = Fals... |
(cfg_file_path=plac.Annotation('path to the config file', 'option', 'c'), resume=plac.Annotation('resume crawling from last process', 'flag'), reset_elasticsearch=plac.Annotation('reset Elasticsearch indexes', 'flag'), reset_json=plac.Annotation('reset JSON files', 'flag'), reset_mysql=plac.Annotation('reset MySQL data... |
class flow_add(flow_mod):
version = 6
type = 14
_command = 0
def __init__(self, xid=None, cookie=None, cookie_mask=None, table_id=None, idle_timeout=None, hard_timeout=None, priority=None, buffer_id=None, out_port=None, out_group=None, flags=None, importance=None, match=None, instructions=None):
... |
class FPNRoiAlign(Module):
def __init__(self, num_rois, pooled_size, sampling_ratio, spatial_scale, position_sensitive, continuous_coordinate, im_shape):
super().__init__()
self.op = multi_level_roi_align(num_rois, pooled_size, sampling_ratio, spatial_scale, position_sensitive, continuous_coordinate... |
class OptionSeriesScatterCluster(Options):
def allowOverlap(self):
return self._config_get(True)
def allowOverlap(self, flag: bool):
self._config(flag, js_type=False)
def animation(self):
return self._config_get({'duration': 500})
def animation(self, flag: bool):
self._co... |
.usefixtures('use_tmpdir')
def test_that_workflows_with_errors_are_not_loaded():
test_config_file_name = 'test.ert'
Path('WFJOB').write_text('EXECUTABLE echo\n', encoding='utf-8')
Path('wf').write_text('WFJAB hello world\n', encoding='utf-8')
test_config_contents = dedent('\n NUM_REALIZATIONS 1\... |
def test_create_speaker_required_fields_complete(db, client, jwt):
speaker = get_simple_custom_form_speaker(db)
data = json.dumps({'data': {'type': 'speaker', 'attributes': {'name': 'Areeb', 'mobile': '', 'speaking-experience': 'Speaking since birth', 'complex-field-values': {'m.night': 'shyamalan'}}, 'relation... |
class TestNumericTraitOperators(BaseEvenniaTestCase):
def setUp(self):
self.st = traits.Trait({'name': 'Strength', 'trait_type': 'trait', 'value': 8})
self.at = traits.Trait({'name': 'Attack', 'trait_type': 'trait', 'value': 4})
def tearDown(self):
(self.st, self.at) = (None, None)
d... |
class OptionSeriesAreasplineDataEvents(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 CausalButterFilterNodeConfig(lg.Config):
sample_rate: float = (- 1.0)
initial_buffer_len: int = 10
highpass_cutoff: Optional[float] = 0.01
highpass_order: Optional[int] = 5
lowpass_cutoffs: List = field(default_factory=list)
invert_input: bool = True
pass_through: bool = False
def ... |
class OptionPlotoptionsSunburstSonificationDefaultinstrumentoptionsMappingHighpass(Options):
def frequency(self) -> 'OptionPlotoptionsSunburstSonificationDefaultinstrumentoptionsMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsSunburstSonificationDefaultinstrumentoptions... |
.usefixtures('mock_roxutils', 'polygon_set_in_roxvalues')
def test_load_polygons_from_roxar():
pol = xtgeo.polygons_from_roxar('project', 'Name', 'Category')
assert_frame_equal(pol.dataframe, pd.DataFrame([[1.0, 2.0, 44.0, 0], [1.1, 2.1, 45.0, 0], [1.2, 2.2, 46.0, 0], [1.3, 2.3, 47.0, 0], [1.4, 2.4, 48.0, 0], [... |
class EmailVerify(commands.Cog):
__version__ = '0.1.1'
__author__ = 'flare'
def format_help_for_context(self, ctx):
pre_processed = super().format_help_for_context(ctx)
return f'''{pre_processed}
Cog Version: {self.__version__}
Cog Author: {self.__author__}'''
def __init__(self, bot):
... |
(frozen=True)
class Entry():
name: str
folder: Optional[str] = ''
username: Optional[str] = ''
_property
def hashed(self) -> str:
m = sha1()
m.update(self.name.encode())
if self.folder:
m.update(self.folder.encode())
if self.username:
m.update(... |
class BaseMessage(ABC):
__slots__ = ()
__PROTOBUF_FIELDS_BY_NUMBER__: ClassVar[Dict[(int, Tuple[(str, _FieldDescriptor)])]]
__PROTOBUF_FIELDS_BY_NAME__: ClassVar[Dict[(str, _FieldDescriptor)]]
__PROTOBUF_SKIP__: ClassVar[Dict[(WireType, Skip)]] = {WireType.VARINT: skip_varint, WireType.I64: skip_fixed_6... |
class SignalR():
def __init__(self, url):
self.url = url
def update_res(self, msg):
if (msg != {}):
self.res = msg
def get_value(self, hub, method):
self.res = {}
with Session() as session:
connection = Connection(self.url, session)
chat = ... |
class TLSinTLSStream(NetworkStream):
TLS_RECORD_SIZE = 16384
def __init__(self, sock: socket.socket, ssl_context: ssl.SSLContext, server_hostname: typing.Optional[str]=None, timeout: typing.Optional[float]=None):
self._sock = sock
self._incoming = ssl.MemoryBIO()
self._outgoing = ssl.Mem... |
def run_async_emulated(simulations: Dict[(str, td.Simulation)], **kwargs) -> BatchData:
task_ids = {task_name: f'task_id={i}' for (i, task_name) in enumerate(simulations.keys())}
task_paths = {task_name: 'NONE' for task_name in simulations.keys()}
sim_data = {task_name: run_emulated(sim) for (task_name, sim... |
class SettingsWindow(Gtk.Window):
def __init__(self, config, parent_window=None):
Gtk.Window.__init__(self, title=('%s - %s' % (_('Settings'), APPLICATION_NAME)), icon=GdkPixbuf.Pixbuf.new_from_file(data_helpers.find_data_path('images/icon_64.png')), default_width=450, modal=True)
self.set_transient... |
def run_aea_subprocess(*args, cwd: str='.') -> Tuple[(subprocess.Popen, str, str)]:
result = subprocess.Popen([sys.executable, '-m', 'aea.cli', *args], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd)
result.wait()
(stdout, stderr) = result.communicate()
return (result, stdout.decode('utf-8'), s... |
def test_param_jitter():
params = [1, 1]
jitterer = param_jitter(params, [0.5, 0.5])
for (ind, jits) in zip(range(3), jitterer):
for (p1, j1) in zip(jits, params):
assert (p1 != j1)
jitterer = param_jitter(params, [0, 0.5])
for (ind, jits) in zip(range(3), jitterer):
asse... |
class DeltaRLastRounds():
def __new__(cls, guesses=_np.arange(64, dtype='uint8'), words=None, ciphertext_tag='ciphertext', key_tag='key'):
return _decorated_selection_function(_AttackSelectionFunctionWrapped, _delta_last_rounds, expected_key_function=_last_key, words=words, guesses=guesses, target_tag=ciphe... |
def _NetworkInterfacesAddrs(withMask=False):
try:
from ctypes import Structure, Union, POINTER, pointer, get_errno, cast, c_ushort, c_byte, c_void_p, c_char_p, c_uint, c_int, c_uint16, c_uint32
import ctypes.util
import ctypes
class struct_sockaddr(Structure):
_fields_ = ... |
class WallCaliper(_WallMountedBox):
def __init__(self) -> None:
super().__init__()
self.buildArgParser(h=100)
self.argparser.add_argument('--width', action='store', type=float, default=18.0, help='width of the long end')
self.argparser.add_argument('--height', action='store', type=fl... |
def _filename_to_module_name(name: str) -> str:
if (not (os.path.isfile(name) and (name.lower().endswith('.py') or name.lower().endswith('.pyc')))):
raise ValueError('Expected a .py file, got {}'.format(name))
if os.path.isabs(name):
name = os.path.relpath(name, os.getcwd())
if name.lower().... |
def get_git_tarball(repo_url: str, commit: str) -> str:
url = canonical_url(repo_url)
path = url.path.split('/')[1:]
assert (len(path) == 2)
owner = path[0]
if path[1].endswith('.git'):
repo = path[1].replace('.git', '')
else:
repo = path[1]
if (url.hostname == 'github.com'):... |
def load_osci_general_reports_to_bq(date: datetime.datetime):
report = OSCIGeneralRanking(date=date)
table = BigQueryOSCIGeneralRankingReport
log.debug(f'Load {report.name} for {date:%Y-%m-%d} to {table.table_id}')
report_df = report.read()
report_df = report_df[PublicSchemas.osci_general_report.req... |
class getStatus_result():
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
def isUnion():
return False
def read(self, iprot):
if ((isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtoco... |
class TestChoiceFieldWithGroupedChoices(FieldValues):
valid_inputs = {'poor': 'poor', 'medium': 'medium', 'good': 'good'}
invalid_inputs = {'awful': ['"awful" is not a valid choice.']}
outputs = {'good': 'good'}
field = serializers.ChoiceField(choices=[('Category', (('poor', 'Poor quality'), ('medium', ... |
class TestSpotifyChapter():
.xfail(reason='API inconsistencies.')
def test_chapter_no_market_not_found(self, app_client):
with pytest.raises(NotFound):
app_client.chapter(chapter_id)
def test_chapter_with_US_market_found(self, app_client):
chapter = app_client.chapter(chapter_id,... |
class TransferManager(object):
class Cache(object):
def __init__(self, element):
self.embedding_element = get_embedding_dg_element(element)
self._dat_versions = {}
self._V_DG_mass = {}
self._DG_inv_mass = {}
self._V_approx_inv_mass = {}
... |
class SQLAlchemyTask(PythonCustomizedContainerTask[SQLAlchemyConfig], SQLTask[SQLAlchemyConfig]):
_SQLALCHEMY_TASK_TYPE = 'sqlalchemy'
def __init__(self, name: str, query_template: str, task_config: SQLAlchemyConfig, inputs: typing.Optional[typing.Dict[(str, typing.Type)]]=None, output_schema_type: typing.Optio... |
class OptionSeriesTimelineSonificationContexttracksMappingGapbetweennotes(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_sqs_send_batch(instrument, elasticapm_client, sqs_client_and_queue):
(sqs, queue_url) = sqs_client_and_queue
elasticapm_client.begin_transaction('test')
response = sqs.send_message_batch(QueueUrl=queue_url, Entries=[{'Id': 'foo', 'MessageBody': 'foo', 'MessageAttributes': {'string': {'StringValue':... |
def segment_none(cnarr):
colnames = ['chromosome', 'start', 'end', 'log2', 'gene', 'probes']
rows = [(cnarr.chromosome.iat[0], cnarr.start.iat[0], cnarr.end.iat[(- 1)], segment_mean(cnarr), '-', len(cnarr))]
table = pd.DataFrame.from_records(rows, columns=colnames)
segarr = cnarr.as_dataframe(table)
... |
def test_headers_present_in_paginated_request(response_with_body_link):
config = LinkPaginationConfiguration(source='body', path='links.next')
request_params: SaaSRequestParams = SaaSRequestParams(method=HTTPMethod.GET, headers={'x-custom-header': 'abc'}, path='/customers', query_params={'page': 'abc'})
pag... |
class PortModPacketIn(base_tests.SimpleDataPlane):
def runTest(self):
logging.info('Running PortModPacketIn Test')
of_ports = config['port_map'].keys()
of_ports.sort()
logging.info('Sends Features Request and retrieve Port Configuration from reply')
(hw_addr, port_config, adv... |
def add_evaluator_args(parser: argparse.ArgumentParser):
parser.add_argument('--quality-metrics', nargs='+', default=['BLEU'], help='Quality metrics')
parser.add_argument('--latency-metrics', nargs='+', default=['LAAL', 'AL', 'AP', 'DAL', 'ATD'], help='Latency metrics')
parser.add_argument('--continue-unfin... |
class TestArraySource(unittest.TestCase):
def setUp(self):
d = ArraySource()
self.data = d
def make_2d_data(self):
s = numpy.array([[0, 1], [2, 3]], 'd')
v = numpy.array([[[1, 1, 1], [1, 0, 0]], [[0, 1, 0], [0, 0, 1]]], 'd')
tps = numpy.transpose
(s, v) = (tps(s),... |
def parse_arguments(args: list[str]) -> argparse.Namespace:
for argument in ('-c', '--coordinates', '-b', '--boundary-box'):
if (argument in args):
index: int = (args.index(argument) + 1)
if args[index].startswith('-'):
args[index] = (' ' + args[index])
br... |
def calculate_masking_accuracy(ground_truth, generated_mask):
gt = cv2.imread(ground_truth, cv2.IMREAD_GRAYSCALE)
gm = cv2.imread(generated_mask, cv2.IMREAD_GRAYSCALE)
print('INFO: Imported images...')
gt_bin = binarise(gt)
gm_bin = binarise(gm)
diff = (gt_bin.astype(np.int16) - gm_bin.astype(n... |
def delete_disabled_builds(apps, apkcache, repodirs):
for (appid, app) in apps.items():
for build in app.get('Builds', []):
if (not build.disable):
continue
apkfilename = common.get_release_filename(app, build)
iconfilename = ('%s.%s.png' % (appid, build.v... |
class UpdateThread(Thread):
def __init__(self, q, *args, **kwargs):
self.q = q
self.checked_buckets_since_last_update = 0
super().__init__(*args, **kwargs)
def run(self):
global THREAD_EVENT
while (not THREAD_EVENT.is_set()):
checked_buckets = len(self.q.check... |
def orgb_to_srgb(lcc: Vector) -> Vector:
theta0 = math.atan2(lcc[2], lcc[1])
theta = theta0
atheta0 = abs(theta0)
if (atheta0 < (math.pi / 2)):
theta = ((2 / 3) * theta0)
elif ((math.pi / 2) <= atheta0 <= math.pi):
theta = math.copysign(((math.pi / 3) + ((4 / 3) * (atheta0 - (math.pi... |
def _ask_user(lines: List[str], line: str, idx: int, old_string: str, type_: str, lines_num: int) -> str:
print(('=' * 50))
above_rows = lines[(idx - lines_num):idx]
below_rows = lines[(idx + 1):(idx + lines_num)]
print(''.join(above_rows))
print(line.rstrip().replace(old_string, (('\x1b[91m' + old_... |
def _serialize_header(oxx, mod, n, buf, offset):
try:
get_desc = getattr(mod, (('_' + oxx) + '_field_desc'))
desc = get_desc(n)
value_len = desc.type.size
except KeyError:
value_len = 0
(n, exp_hdr) = _make_exp_hdr(oxx, mod, n)
exp_hdr_len = len(exp_hdr)
pack_str = ('... |
def _desc_ranges(attr, die):
di = die.cu.dwarfinfo
if (not hasattr(di, '_rnglists')):
di._rangelists = di.range_lists()
rangelist = di._rangelists.get_range_list_at_offset(attr.value, die.cu)
base_ip = _get_cu_base(die.cu)
lines = []
addr_str_len = (die.cu.header.address_size * 2)
fo... |
def set_resolution(width: int, height: int, dpi_scale: int, refresh_rate: int=None):
if (platform.system() == 'Windows'):
devmode = pywintypes.DEVMODEType()
devmode.PelsWidth = width
devmode.PelsHeight = height
devmode.Fields = (win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT)
... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'name'
fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path':... |
class TestQueryWithSearchAfterScroll():
('elasticsearch.Elasticsearch')
.asyncio
async def test_search_after_with_pit(self, es):
es.options.return_value = es
pit_op = 'open-point-in-time1'
pit_id = 'abcdef'
params = {'name': 'search-with-pit', 'index': 'test-index', 'operatio... |
def _HKDF_mod_r(*, IKM: bytes, key_info: bytes=b'') -> int:
L = 48
salt = b'BLS-SIG-KEYGEN-SALT-'
SK = 0
while (SK == 0):
salt = SHA256(salt)
okm = HKDF(salt=salt, IKM=(IKM + b'\x00'), L=L, info=(key_info + L.to_bytes(2, 'big')))
SK = (int.from_bytes(okm, byteorder='big') % bls_c... |
class StrokeMode(BaseMode):
name = Mode.stroke
keymap = {Action.fine_control: False, Action.stroke: True}
def enter(self):
mouse.mode(MouseMode.RELATIVE)
Global.mode_mgr.mode_stroked_from = Global.mode_mgr.last_mode
visual.cue.track_stroke()
visual.cue.show_nodes(ignore=('cue... |
.django_db
def test_bad_params(client, create_gtas_data):
resp = client.get('/api/v2/references/total_budgetary_resources/?fiscal_period=3')
assert (resp.status_code == status.HTTP_400_BAD_REQUEST)
resp = client.get('/api/v2/references/total_budgetary_resources/?fiscal_year=2015&fiscal_period=1')
assert... |
.skipif((pyvista is None), reason='requires pyvista')
.parametrize('drop_null_prisms', (False, True))
def test_to_pyvista_drop_null_prisms(dummy_layer, drop_null_prisms):
((easting, northing), surface, reference, density) = dummy_layer
reference -= 1
properties = {'density': density}
layer = prism_layer... |
class _NodeSeeker(dunodes.GenericNodeVisitor, object):
def __init__(self, node, *args, **kwargs):
include = kwargs.pop('include')
exclude = kwargs.pop('exclude', (dunodes.system_message,))
super(_NodeSeeker, self).__init__(*args, **kwargs)
self.node = node
self.include = incl... |
def main(page: Page):
def button_clicked(e):
t.value = f"Textboxes values are: '{tb1.value}', '{tb2.value}', '{tb3.value}', '{tb4.value}', '{tb5.value}'."
page.update()
t = Text()
tb1 = TextField(label='Standard')
tb2 = TextField(label='Disabled', disabled=True, value='First name')
... |
.django_db
def test_show_collaborators_tab_when_can_register_installations_should_return_true(user1, event1, mocker):
mock_can_register_as_collaborator = mocker.patch('manager.templatetags.filters.can_register_as_collaborator')
mock_can_register_as_collaborator.return_value = False
mock_can_register_as_inst... |
class OptionPlotoptionsTreemapDatalabels(Options):
def align(self):
return self._config_get('center')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(False)
def allowOverlap(self, flag: bool):
self._config(flag... |
.order((- 1))
.parametrize(('user_id', 'status'), (('1', 200), ('20', 404), ('', 200)))
def test_get_users_posts(user_id, status):
if user_id:
response = client.get(('/posts?user_id=' + str(user_id)))
else:
response = client.get('/posts')
assert (status == response.status_code) |
def test_fiscal_year_period_selection(setup_test_data, client):
resp = client.get((url + '?fiscal_year=2018&fiscal_period=6'))
assert (resp.status_code == status.HTTP_200_OK)
response = resp.json()
assert (len(response['results']) == 3)
expected_results = [{'agency_name': 'Test Agency', 'abbreviatio... |
def extractWwwEvilationsCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in t... |
def preprocess():
check_processed_folder = (os.getcwd() + '\\training_data\\balanced')
if (not os.path.exists(check_processed_folder)):
os.mkdir(check_processed_folder)
data_name = input('which data do you want to preprocess: ')
file = (os.getcwd() + f''' raining_data
aw\{data_name}''')
if o... |
class OptionPlotoptionsScatterClusterZones(Options):
def className(self):
return self._config_get(None)
def className(self, text: str):
self._config(text, js_type=False)
def from_(self):
return self._config_get(None)
_.setter
def from_(self, num: float):
self._config(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.