code stringlengths 281 23.7M |
|---|
def dedent(text, baseline_index=None, indent=None):
if (not text):
return ''
if (indent is not None):
lines = text.split('\n')
ind = (' ' * indent)
indline = ('\n' + ind)
return (ind + indline.join((line.strip() for line in lines)))
elif (baseline_index is None):
... |
class SimpleModelSemanticExtractor(ModelSemanticExtractor):
def __init__(self, semantic_content_class_by_tag: Optional[Mapping[(str, SemanticContentFactoryProtocol)]]=None):
super().__init__()
self.semantic_content_class_by_tag = (semantic_content_class_by_tag or {})
def get_semantic_content_for... |
class HtmlNavBar(Html.Html):
name = 'Nav Bar'
def __init__(self, page: primitives.PageModel, components: Optional[List[Html.Html]], width: tuple, height: tuple, options: Optional[dict], html_code: str, profile: Optional[Union[(dict, bool)]]):
super(HtmlNavBar, self).__init__(page, [], html_code=html_cod... |
class geneve(packet_base.PacketBase):
_HEADER_FMT = '!BBHI'
_MIN_LEN = struct.calcsize(_HEADER_FMT)
OAM_PACKET_FLAG = (1 << 7)
CRITICAL_OPTIONS_FLAG = (1 << 6)
def __init__(self, version=0, opt_len=0, flags=0, protocol=ether_types.ETH_TYPE_TEB, vni=None, options=None):
super(geneve, self).__... |
.unit
def test_transform_redshift_systems(redshift_describe_clusters: Generator, redshift_systems: Generator) -> None:
actual_result = aws_connector.create_redshift_systems(describe_clusters=redshift_describe_clusters, organization_key='default_organization')
assert (actual_result == redshift_systems) |
def main():
try:
base_conf(project='ryu', version=('ryu %s' % version))
except cfg.RequiredOptError as e:
base_conf.print_help()
raise SystemExit(1)
subcmd_name = base_conf.subcommand
try:
subcmd_mod_name = subcommands[subcmd_name]
except KeyError:
base_conf.p... |
class OptionPlotoptionsStreamgraphSonificationDefaultinstrumentoptionsMappingFrequency(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(sel... |
_func
def get_message(query: fixieai.Message) -> str:
if (not query.embeds):
return 'You need to specify the embed ID of the message you want to read.'
for embed in query.embeds.values():
if (embed.content_type != 'text/plain'):
return f'I can only read plain-text emails specified by... |
def test_MeshAdaptRestart_adaptiveTime_BackwardEuler_baseline(verbose=0):
currentPath = os.path.dirname(os.path.abspath(__file__))
runCommand = (('cd ' + currentPath) + '; parun -C "gen_mesh=False usePUMI=True adapt=0 fixedTimeStep=False" -D "baseline" dambreak_Colagrossi_so.py;')
subprocess.check_call(runC... |
def extract_config(t: Type[TensorFlow2ONNX]) -> Tuple[(Type[TensorFlow2ONNX], TensorFlow2ONNXConfig)]:
config = None
if (get_origin(t) is Annotated):
(base_type, config) = get_args(t)
if isinstance(config, TensorFlow2ONNXConfig):
return (base_type, config)
else:
r... |
def rolling_median_by_h(x, h, w, name):
df = pd.DataFrame({'x': x, 'h': h})
grouped = df.groupby('h')
df2 = grouped.size().reset_index().sort_values('h')
hs = df2['h']
res_h = []
res_x = []
i = (len(hs) - 1)
while (i >= 0):
h_i = hs[i]
xs = grouped.get_group(h_i).x.tolist... |
def extractAsadatranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('npc town building game', 'NPC Town-building Game', 'translated'), ('reader', 'reader', ... |
class VmMigrateSerializer(s.Serializer):
node = s.SlugRelatedField(slug_field='hostname', queryset=Node.objects, required=False)
root_zpool = s.CharField(max_length=64, required=False)
disk_zpools = DiskPoolDictField(required=False)
live = s.BooleanField(default=False)
def __init__(self, request, vm... |
def test_validation_custom_types():
def complex_args(rate: StrictFloat, steps: PositiveInt=10, log_level: constr(regex='(DEBUG|INFO|WARNING|ERROR)')='ERROR'):
return None
my_registry.complex = catalogue.create(my_registry.namespace, 'complex', entry_points=False)
my_registry.complex('complex.v1')(co... |
class BarcodeMatcher():
def __init__(self, barcode):
self.__barcode = barcode
def barcode(self):
return self.__barcode
def match(self, test_barcode, max_mismatches=0):
if test_barcode.startswith(self.__barcode):
return True
nmismatches = 0
try:
... |
class ServicePlanFixtureTestTracebackEntry(TracebackEntry):
def __init__(self, name, line_number, path, local_variables, fixture_source, test_source, raw_entry):
super(ServicePlanFixtureTestTracebackEntry, self).__init__(raw_entry)
self._name = name
self.lineno = (line_number - 1)
se... |
def parse_members(filepath: str) -> Set[str]:
with open(filepath, 'r') as filehandle:
filecontent = filehandle.read()
members = set()
for node in ast.parse(filecontent).body:
if (isinstance(node, ast.Import) or isinstance(node, ast.ImportFrom)):
members.update(((alias.asname or a... |
class Heartbeat(object):
def __init__(self, interval, send_heartbeat, timer=threading.Timer):
self.send_heartbeat = send_heartbeat
self.timer_impl = timer
self._lock = threading.Lock()
self._running = threading.Event()
self._timer = None
self._exceptions = None
... |
def test_parse_latlng() -> None:
bad = ['', 'aaa', '12', '1,2,3', '48,', '48,x', '4 8,8', '91,8', '-91,8', '48,-181', '48,181']
for s in bad:
with pytest.raises(ValueError):
staticmaps.parse_latlng(s)
good = ['48,8', ' 48 , 8 ', '-48,8', '+48,8', '48,-8', '48,+8', '48.123,8.456']
for... |
def bitread2bits(txt):
bits_ref = set()
for l in txt.split('\n'):
l = l.strip()
if (not l):
continue
m = re.match('bit_(.{8})_(.{3})_(.{2})', l)
addr = int(m.group(1), 16)
word = int(m.group(2), 10)
bit = int(m.group(3), 10)
bits_ref.add((addr,... |
class Flow_Add_6(base_tests.SimpleProtocol):
def runTest(self):
logging.info('Flow_Add_6 TEST BEGIN')
logging.info('Deleting all flows from switch')
delete_all_flows(self.controller)
sw = Switch()
self.assertTrue(sw.connect(self.controller), 'Failed to connect to switch')
... |
_op([AllocCursorA, IntA, NewExprA('buf_cursor'), NewExprA('buf_cursor')])
def resize_dim(proc, buf_cursor, dim_idx, size, offset):
stmt_c = buf_cursor._impl
(ir, fwd) = scheduling.DoResizeDim(stmt_c, dim_idx, size, offset)
return Procedure(ir, _provenance_eq_Procedure=proc, _forward=fwd) |
('Updater.last_required_reboot_performed', return_value=False)
('Updater.sdlog.error')
('Updater.sdlog.info')
def test_overall_update_status_reboot_not_done_previously(mocked_info, mocked_error, mocked_reboot_performed):
result = updater.overall_update_status(TEST_RESULTS_UPDATES)
assert (result == UpdateStatus... |
def paragraph(node: RenderTreeNode, context: RenderContext) -> str:
inline_node = node.children[0]
text = inline_node.render(context)
if context.do_wrap:
wrap_mode = context.options['mdformat']['wrap']
if isinstance(wrap_mode, int):
wrap_mode -= context.env['indent_width']
... |
def query_pfam_annotate(arguments):
(queries_pfams_group, queries_fasta, pfam_db, temp_dir, translate, pfam_file, cpu, data_path) = arguments
set_data_path(data_path)
aligned_pfams = None
(fasta_file, hmm_file) = filter_fasta_hmm_files(queries_pfams_group, queries_fasta, pfam_db, temp_dir)
if ((fast... |
class UltimateSpeedHandler(THBEventHandler):
interested = ['action_apply', 'choose_target', 'post_calcdistance']
def handle(self, evt_type, arg):
def is_card(card):
return (('skill' not in card.category) or ('treat_as' in card.category))
if (evt_type == 'post_calcdistance'):
... |
class OptionPlotoptionsAreasplineSonificationTracksMappingHighpass(Options):
def frequency(self) -> 'OptionPlotoptionsAreasplineSonificationTracksMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsAreasplineSonificationTracksMappingHighpassFrequency)
def resonance(self... |
def show_dependencies(reqs, python=None, *, dryrun=False):
if (not python):
python = sys.executable
print('dependencies:')
for req in reqs:
for c in '<=>;':
req = req.partition(c)[0]
if dryrun:
print(' ', req)
else:
print()
_get... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'ems-id'
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... |
def google_search(search: str, search_depth: int):
try:
res = requests.get((' + search))
res.raise_for_status()
except:
warning("There was a problem with this services's internet")
st.warning("There was a problem with this services's internet. \n If you got HT... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = None
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': {... |
def log_syslogd3_override_setting(data, fos):
vdom = data['vdom']
log_syslogd3_override_setting_data = data['log_syslogd3_override_setting']
filtered_data = underscore_to_hyphen(filter_log_syslogd3_override_setting_data(log_syslogd3_override_setting_data))
return fos.set('log.syslogd3', 'override-settin... |
def getHexToRgb(hex_color: str):
res = re.search('rgba\\(([0-9]*), ([0-9]*), ([0-9]*)', hex_color)
if (res is not None):
return [res.group(1), res.group(2), res.group(3)]
if (not hex_color.startswith('#')):
raise ValueError('Hexadecimal color should start with #')
if (not (len(hex_color)... |
def _check_scalar_array(obj, name, value):
if (value is None):
return None
arr = np.asarray(value)
assert (len(arr.shape) in [2, 3]), 'Scalar array must be 2 or 3 dimensional'
vd = obj.vector_data
if (vd is not None):
assert (vd.shape[:(- 1)] == arr.shape), ('Scalar array must match ... |
class OptionSeriesArcdiagramSonificationContexttracksMappingPan(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):
... |
(no_gui_test_assistant, 'No GuiTestAssistant')
class TestAboutDialog(unittest.TestCase, GuiTestAssistant):
def setUp(self):
GuiTestAssistant.setUp(self)
self.dialog = AboutDialog()
def tearDown(self):
if (self.dialog.control is not None):
with self.delete_widget(self.dialog.c... |
def search(payload, method='general'):
log.debug(('Searching with payload (%s): %s' % (method, repr(payload))))
if ((method == 'episode') and ('anime' in payload) and payload['anime']):
method = 'anime'
if (method == 'general'):
if ('query' in payload):
payload['title'] = payload... |
def get_textNqF0s(line, phids):
line = line.decode('utf-8').split()[1:]
texts = [phids['<']]
qF0s = [0.0]
for k in line:
if ('_' in k):
phone = k.split('_')[0]
texts.append(phids[phone])
qF0 = float(k.split('_')[1])
qF0s.append(qF0)
else:
... |
def check_all_variables(X: pd.DataFrame, variables: Variables) -> List[Union[(str, int)]]:
if isinstance(variables, (str, int)):
if (variables not in X.columns.to_list()):
raise KeyError(f'The variable {variables} is not in the dataframe.')
variables_ = [variables]
else:
if (... |
def populate_dot_thbattle():
res_path = _set_bootstrap_path()
os.system('rm -rf ~/.thbattle/{osx-eggs,src}')
os.system(('mkdir -p ~/.thbattle/osx-eggs && cd ~/.thbattle/osx-eggs && tar -xf %s' % os.path.join(res_path, 'osx-eggs.tar')))
os.system(('mkdir -p ~/.thbattle/src && cd ~/.thbattle/src && tar -x... |
class FunctionDataSourceTestCase(UnittestTools, unittest.TestCase):
def setUp(self):
self.myfunc = (lambda low, high: (linspace(low, high, 101) ** 2))
self.data_source = FunctionDataSource(func=self.myfunc)
def test_init_defaults(self):
data_source = FunctionDataSource()
assert_a... |
def format_running_time(runtime: int) -> str:
days = 0
hours = 0
minutes = 0
seconds = math.trunc(runtime)
if (seconds >= 60):
(minutes, seconds) = divmod(seconds, 60)
if (minutes >= 60):
(hours, minutes) = divmod(minutes, 60)
if (hours >= 24):
(days, hours) = divmod(... |
def read_fixture_file(path: (str | Path)) -> list[list[Any]]:
text = Path(path).read_text(encoding='utf-8')
tests = []
section = 0
last_pos = 0
lines = text.splitlines(keepends=True)
for i in range(len(lines)):
if (lines[i].rstrip() == '.'):
if (section == 0):
... |
def get_boundaries(is_jp: bool) -> Optional[list[int]]:
file_data = game_data_getter.get_file_latest('DataLocal', 'GamatotoExpedition.csv', is_jp)
if (file_data is None):
helper.error_text('Failed to get gamatoto xp requirements')
return None
boundaries = file_data.decode('utf-8').splitlines... |
('pyscf')
.parametrize('hbond_angles, prim_len_ref', ((True, 56), (False, 42)))
def test_run_geom_section_union(hbond_angles, prim_len_ref):
ref_energy = (- 160.)
def run_assert(run_dict, prim_len):
res = run_from_dict(run_dict)
geom = res.calced_geoms[0]
assert (geom.energy == pytest.ap... |
class DomainMetadata(models.Model):
domain = models.ForeignKey('pdns.Domain', blank=True, null=True)
kind = models.CharField(max_length=32, blank=True, null=True)
content = models.TextField(blank=True, null=True)
class Meta():
managed = False
db_table = 'domainmetadata'
def __unicode... |
.parametrize(['expr', 'value', 'typ', 'fs_type'], itertools.product(['f', '2.0*tanh(f) + cos(f) + sin(f)', '1.0/tanh(f) + 1.0/f'], [1, 10, (- 1), (- 10)], ['function', 'constant'], ['scalar', 'vector', 'tensor']))
def test_functions(mesh, expr, value, typ, fs_type):
if (typ == 'function'):
if (fs_type == 'v... |
class LocationFlatPage(models.Model):
menu = models.ForeignKey(LocationMenu, related_name='pages', help_text='Note: If there is only one page in the menu, it will be used as a top level nav item, and the menu name will not be used.')
flatpage = models.OneToOneField(FlatPage)
def slug(self):
url = se... |
class AccountBasedExpenseLineDetail(QuickbooksBaseObject):
class_dict = {'CustomerRef': Ref, 'AccountRef': Ref, 'TaxCodeRef': Ref, 'ClassRef': Ref, 'MarkupInfo': MarkupInfo}
def __init__(self):
super(AccountBasedExpenseLineDetail, self).__init__()
self.BillableStatus = None
self.TaxAmoun... |
class UPnPService(Service):
logger = get_logger('trinity.components.upnp.UPnPService')
def __init__(self, port: int, event_bus: EndpointAPI) -> None:
self.port = port
self.event_bus = event_bus
async def run(self) -> None:
while self.manager.is_running:
async for _ in eve... |
def setup_after_launch(cfg: CfgNode, output_dir: str, runner_class: Union[(None, str, Type[BaseRunner], Type[DefaultTask])]) -> Union[(None, BaseRunner, Type[DefaultTask])]:
create_dir_on_global_main_process(output_dir)
setup_loggers(output_dir)
log_system_info()
cfg.freeze()
maybe_override_output_d... |
class WriteFontInfoVersion3TestCase(unittest.TestCase):
def setUp(self):
self.tempDir = tempfile.mktemp()
os.mkdir(self.tempDir)
self.dstDir = os.path.join(self.tempDir, 'test.ufo')
def tearDown(self):
shutil.rmtree(self.tempDir)
def tearDownUFO(self):
if os.path.exis... |
class OptionSeriesDumbbellSonificationDefaultinstrumentoptionsMappingPan(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 SimulationTest(BasicTest):
def _setRelativePath(self, input_file):
self.scriptdir = os.path.dirname(input_file)
def remove_files(filelist):
for file in filelist:
if os.path.isfile(file):
os.remove(file)
def teardown_method(self):
extens = 'm'
... |
def build_train_graph(master_spec, hyperparam_config=None):
tf.logging.info('Building Graph...')
if (not hyperparam_config):
hyperparam_config = spec_pb2.GridPoint(learning_method='adam', learning_rate=0.0005, adam_beta1=0.9, adam_beta2=0.9, adam_eps=1e-05, decay_steps=128000, dropout_rate=0.8, gradient... |
class Idl(idl.Idl):
def __init__(self, session, schema):
if (not isinstance(schema, idl.SchemaHelper)):
schema = idl.SchemaHelper(schema_json=schema)
schema.register_all()
schema = schema.get_idl_schema()
self._events = []
self.tables = schema.tables
s... |
def acSubmitPseudo(session, dom):
pseudo = dom.getValue('Pseudo').strip()
room = session.room
if (not pseudo):
dom.alert('Pseudo. can not be empty !')
dom.setValue('Pseudo', '')
dom.focus('Pseudo')
elif room.handlePseudo(pseudo.upper()):
session.pseudo = pseudo
do... |
class SchemaManager(SingletonConfigurable):
schemaspaces: Dict[(str, 'Schemaspace')]
schemaspace_id_to_name: Dict[(str, str)]
schemaspace_schemasproviders: Dict[(str, Dict[(str, 'SchemasProvider')])]
schemaspace_schema_validators: Dict[(str, Dict[(str, Any)])]
def __init__(self, **kwargs):
s... |
def benchmark(fn: Callable, *args, num_iterations: int=10, **kwargs) -> Benchmark:
timer = Timer('fn(*args, **kwargs)', globals={'fn': fn, 'args': args, 'kwargs': kwargs})
times = timer.repeat(number=1, repeat=(num_iterations + 1))
return Benchmark(np.mean(times[1:]).item(), np.std(times[1:]).item()) |
class BsCard(Component):
css_classes = ['card']
name = 'Bootstrap Card'
str_repr = '<div {attrs}><div class="card-body">{sub_items}</div></div>'
dyn_repr = '{sub_item}'
def add_header(self, value):
title = self.page.web.std.div(value)
title.attr['class'].initialise(['card-header'])
... |
_router.get('/item/{item_uid}/chunk/{chunk_uid}/download/', dependencies=PERMISSIONS_READ)
def chunk_download(chunk_uid: str, collection: models.Collection=Depends(get_collection)):
chunk = get_object_or_404(collection.chunks, uid=chunk_uid)
filename = chunk.chunkFile.path
return sendfile(filename) |
def random_select(seed: bytes32) -> address:
select_val: wei_value = as_wei_value(as_num128(num256_mod(as_num256(seed), as_num256(self.total_deposits))), wei)
ind: num = 1
for i in range(15):
if (select_val <= self.validator_table[(ind * 2)].bal):
ind = (ind * 2)
else:
... |
def test_switch_no_empty_fallthough(task):
task.options.set('pattern-independent-restructuring.min_switch_case_number', 11)
(switch_variable, vertices) = _switch_no_empty_fallthrough(task)
PatternIndependentRestructuring().run(task)
assert (isinstance((seq_node := task.syntax_tree.root), SeqNode) and (l... |
def upgrade():
op.drop_index(op.f('ix_session_data'), table_name='session')
op.execute('ALTER TABLE session ALTER COLUMN data TYPE JSON USING data::JSON;')
op.drop_index(op.f('ix_config_config'), table_name='config')
op.execute('ALTER TABLE config ALTER COLUMN config TYPE JSON USING config::JSON;') |
.skipif((yaml is None), reason='needs yaml')
def test_yaml_file_handler(tmpdir, testconfig):
yaml_file = tmpdir.join('config.yaml')
yaml_file.write('\ndevelopment:\n DATABASE_URI: mysql://root:/posts\n\nproduction:\n DATABASE_URI: mysql://poor_user:poor_/poor_posts\n')
config = kaptan.Kaptan(handler='yaml... |
def update_or_create_camera_trace(patched_figure, trace_idx, cam_coords, wireframe_scale=0.5, linewidth=3, color='red', name='Camera'):
(x, y, z) = (cam_coords['x'], cam_coords['y'], cam_coords['z'])
if (trace_idx is None):
patched_figure['data'].append(go.Scatter3d(x=x, y=y, z=z, mode='lines', marker={... |
(autouse=True)
def no_cert_in_test(monkeypatch):
class MockESConfig(EvaluatorServerConfig):
def __init__(self, *args, **kwargs):
if ('use_token' not in kwargs):
kwargs['use_token'] = False
if ('generate_cert' not in kwargs):
kwargs['generate_cert'] = F... |
class OptionPlotoptionsColumnpyramidSonificationDefaultinstrumentoptionsMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsColumnpyramidSonificationDefaultinstrumentoptionsMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsColumnpyramidSonificationDefaultinst... |
class OptionSeriesPictorialStatesHoverMarker(Options):
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def enabledThreshold(self):
return self._config_get(2)
def enabledThreshold(self, num: float):
self._co... |
def _get_alembic_config(url):
from alembic.config import Config
current_dir = os.path.dirname(os.path.abspath(__file__))
package_dir = os.path.normpath(os.path.join(current_dir, '..'))
directory = os.path.join(package_dir, 'migrations')
config = Config(os.path.join(package_dir, 'alembic.ini'))
c... |
def create_ref_node(link_type, uri, text, tooltip):
innernode = nodes.inline(text, text)
if (link_type == 'ref'):
ref_node = addnodes.pending_xref(reftarget=unquote(uri), reftype='any', refdomain='', refexplicit=True, refwarn=True)
innernode['classes'] = ['xref', 'any']
else:
ref_nod... |
class Migration(migrations.Migration):
dependencies = [('gather', '0002_auto__1301')]
operations = [migrations.AlterField(model_name='event', name='attendees', field=models.ManyToManyField(related_name='events_attending', to=settings.AUTH_USER_MODEL, blank=True)), migrations.AlterField(model_name='event', name=... |
_type(OSPF_MSG_LS_UPD)
class OSPFLSUpd(OSPFMessage):
_PACK_STR = '!I'
_PACK_LEN = struct.calcsize(_PACK_STR)
_MIN_LEN = (OSPFMessage._HDR_LEN + _PACK_LEN)
def __init__(self, length=None, router_id='0.0.0.0', area_id='0.0.0.0', au_type=1, authentication=0, checksum=None, version=_VERSION, lsas=None):
... |
class PDFGraphicState():
def __init__(self):
self.linewidth = 0
self.linecap = None
self.linejoin = None
self.miterlimit = None
self.dash = None
self.intent = None
self.flatness = None
return
def copy(self):
obj = PDFGraphicState()
... |
class FeistelRFirstRounds():
def __new__(cls, guesses=_np.arange(64, dtype='uint8'), words=None, plaintext_tag='plaintext', key_tag='key'):
return _decorated_selection_function(_AttackSelectionFunctionWrapped, _first_round, expected_key_function=_first_key, words=words, guesses=guesses, target_tag=plaintext... |
def bindingQQ(request):
if (request.method == 'POST'):
openid = request.POST.get('openid')
figureurl_qq_1 = request.POST.get('figureurl_qq_1')
nickname = request.POST.get('nickname')
password = request.POST.get('password')
password1 = request.POST.get('password1')
ema... |
def _dbt_run_through_python(args: List[str], target_path: str, run_index: int, connection: Connection):
warnings.filterwarnings('ignore', category=DeprecationWarning, module='logbook')
from dbt.cli.main import dbtRunner
from dbt.contracts.results import RunExecutionResult
runner = dbtRunner()
run_re... |
class OptionPlotoptionsSolidgaugeSonificationContexttracksMappingTremolo(Options):
def depth(self) -> 'OptionPlotoptionsSolidgaugeSonificationContexttracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionPlotoptionsSolidgaugeSonificationContexttracksMappingTremoloDepth)
def speed(self) ... |
def generate(annotations_path, output_path, log_step=5000, force_uppercase=True, save_filename=False):
logging.info('Building a dataset from %s.', annotations_path)
logging.info('Output file: %s', output_path)
writer = tf.io.TFRecordWriter(output_path)
longest_label = ''
idx = 0
with open(annota... |
class OptionSeriesPyramid3dDataDragdrop(Options):
def draggableX(self):
return self._config_get(None)
def draggableX(self, flag: bool):
self._config(flag, js_type=False)
def draggableY(self):
return self._config_get(None)
def draggableY(self, flag: bool):
self._config(fla... |
def test_trace(filename, get_datetime, print_commands=False):
with open(filename) as trace_file:
sequence = parse_trace(trace_file, get_datetime)
errors = {'crash': 0, 'clash': 0}
counter = 0
start = time.time()
for (command, out) in sequence:
counter += 1
if print_commands:
... |
def update_request_body_for_consent_served_or_saved(db: Session, verified_provided_identity: Optional[ProvidedIdentity], fides_user_provided_identity: Optional[ProvidedIdentity], request: Request, original_request_data: Union[(PrivacyPreferencesRequest, RecordConsentServedRequest)], resource_type: Union[(Type[PrivacyPr... |
('ClippedLinear.v1')
def ClippedLinear(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, slope: float=1.0, offset: float=0.0, min_val: float=0.0, max_val: float=1.0) -> Model[(Floats2d, Floats2d)]:
... |
class Link(Sized):
def to_json(self) -> str:
encoder = JSONEncoder(sort_keys=True)
return encoder.encode(self)
def __len__(self) -> int:
return self.size
def displace(self, q: float) -> npt.NDArray[np.float64]:
raise NotImplementedError
def transform(self, q: float=0) -> ... |
('fides.api.service.masking.strategy.masking_strategy_aes_encrypt.encrypt')
def test_mask_gcm_happypath(mock_encrypt: Mock):
mock_encrypt.return_value = 'encrypted'
cache_secrets()
masked_value = AES_STRATEGY.mask(['value'], request_id)[0]
mock_encrypt.assert_called_with('value', b'y\xc5I\xd4\x92\xf6G\t... |
def test_ttlist_woff(capsys, tmpdir):
inpath = os.path.join('Tests', 'ttx', 'data', 'TestWOFF.woff')
fakeoutpath = tmpdir.join('TestWOFF.ttx')
options = ttx.Options([], 1)
options.listTables = True
options.flavor = 'woff'
ttx.ttList(inpath, str(fakeoutpath), options)
(out, err) = capsys.read... |
def test_score_diff_from_transaction():
good_holdings = {'good_id': 2}
currency_holdings = {'FET': 100}
utility_params = {'good_id': 20.0}
exchange_params = {'FET': 10.0}
ownership_state = OwnershipState()
ownership_state.set(amount_by_currency_id=currency_holdings, quantities_by_good_id=good_ho... |
class OptionYaxisLabels(Options):
def align(self):
return self._config_get(None)
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, js_type=False)
... |
def _validate_and_bolster_requested_submission_window(fy: int, quarter: Optional[int], period: Optional[int]) -> (int, Optional[int], Optional[int]):
if ((quarter is None) and (period is None)):
raise InvalidParameterException("Either 'period' or 'quarter' is required in filters.")
if ((quarter is not N... |
class Login(MethodView):
def post(self):
user_api = UserTable()
data = request.get_data()
data = json.loads(data.decode('UTF-8'))
username = data.get('username')
password = data.get('password')
if (not re_user.search(username)):
ret = {'code': 401, 'messag... |
def test_schema_overrides_hydra(monkeypatch: Any, tmpdir: Path) -> None:
monkeypatch.chdir('tests/test_apps/schema_overrides_hydra')
cmd = ['my_app.py', ('hydra.run.dir=' + str(tmpdir)), 'hydra.job.chdir=True']
(result, _err) = run_python_script(cmd)
assert (result == 'job_name: test, name: James Bond, ... |
def main():
try:
log_level = getattr(rospy, rospy.get_param(('/%s/log_level' % PROCESS_NAME), 'INFO'))
except Exception as e:
print(('Error while set the log level: %s\n->INFO level will be used!' % e))
log_level = rospy.INFO
rospy.init_node(PROCESS_NAME, log_level=log_level)
set... |
.django_db
def test_federal_account_list_success(client, monkeypatch, bureau_data, helpers):
helpers.mock_current_fiscal_year(monkeypatch)
resp = client.get(url.format(toptier_code='001', bureau_slug='test-bureau-1', query_params=f'?fiscal_year={helpers.get_mocked_current_fiscal_year()}'))
expected_result =... |
.parametrize('log_base, exp_age, exp_marks, learned_c', _params_test_automatic_find_variables)
def test_param_C_is_dict_user(log_base, exp_age, exp_marks, learned_c, df_vartypes):
transformer = LogCpTransformer(base=log_base, C={'Age': 19.0})
X = transformer.fit_transform(df_vartypes)
transf_df = df_vartype... |
def tts(model, text):
if use_cuda:
model = model.cuda()
model.encoder.eval()
model.postnet.eval()
sequence = np.array(text)
sequence = Variable(torch.from_numpy(sequence)).unsqueeze(0)
if use_cuda:
sequence = sequence.cuda()
(mel_outputs, linear_outputs, alignments) = model(s... |
def test_get_contributors_ranking_mbm_change_report():
contributor_field = 'Contributor'
commits_amount_field = 'Commits'
(jan, feb, dec) = (datetime(year=2020, month=1, day=1), datetime(year=2020, month=2, day=1), datetime(year=2020, month=12, day=1))
reports = [(jan, pd.DataFrame([{contributor_field: ... |
def normalise_font(font, padding=4):
DSIG_copy = copy.deepcopy(font['DSIG'])
del font['DSIG']
origFlavor = font.flavor
origRecalcBBoxes = font.recalcBBoxes
origRecalcTimestamp = font.recalcTimestamp
origLazy = font.lazy
font.flavor = None
font.recalcBBoxes = False
font.recalcTimestam... |
def test_remove_option(bus, config, mocker, tmpdir):
tmp_path = tmpdir.mkdir('tmp').join('tomate.config')
config.config_path = (lambda : tmp_path.strpath)
config.set('section', 'option', 'value')
subscriber = mocker.Mock()
bus.connect(Events.CONFIG_CHANGE, subscriber, weak=False)
config.remove('... |
def _get_available_ram_linux() -> int:
with open('/proc/meminfo') as f:
for line in f:
try:
(key, value) = line.split(':', 1)
except ValueError:
continue
suffix = ' kB\n'
if ((key == 'MemAvailable') and value.endswith(suffix)):
... |
def main():
data = load_iris()
X = normalize(data['data'])
y = data['target']
y = np.zeros((data['target'].shape[0], 3))
y[(np.arange(data['target'].shape[0]).astype('int'), data['target'].astype('int'))] = 1
(X_train, X_test, y_train, y_test) = train_test_split(X, y, test_size=0.33)
clf = M... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.