code stringlengths 281 23.7M |
|---|
class InteriorWall(Wall):
name: str
material: str
def __init__(self, material: str):
super().__init__(material)
self.name = f'Interior wall made out of {material}'
def setName(self, name: str) -> None:
self.name = name
def __str__(self) -> str:
return self.name
de... |
class CallInfo():
def __init__(self, function_name, args, keywords, args_arg, keywords_arg, implicit_arg, constructor):
self.function_name = function_name
self.args = args
self.keywords = keywords
self.args_arg = args_arg
self.keywords_arg = keywords_arg
self.implicit... |
class representation():
def __init__(self, x, smiles=None):
if (smiles is not None):
self.smiles = []
for (i, smile) in enumerate(smiles):
if smile.endswith('.smi'):
smile = smile[:(- 4)]
self.smiles.append(smile)
else:
... |
def parse_opts(treestr, category_index=None):
dash_depth = 0
opt_list = treestr.split('\n')
kept_opts = []
if (category_index != None):
if (not is_category(treestr, category_index)):
return True
dash_depth = (dashcount(opt_list[category_index]) + 1)
opt_list = opt_lis... |
class Ui_Form(object):
def setupUi(self, Form):
if (not Form.objectName()):
Form.setObjectName(u'Form')
Form.resize(470, 466)
self.model1_choose = QGroupBox(Form)
self.model1_choose.setObjectName(u'model1_choose')
self.model1_choose.setGeometry(QRect(30, 10, 371, ... |
def run_iterative_averaging(seed, num_nodes, failure_prob, max_iterations, averaging_algo, target_precision=None):
np.random.seed(seed)
weights = np.random.normal(0, 1, num_nodes).astype(np.float64)
history = np.zeros(((max_iterations + 1),), dtype=np.float64)
iter_num = 0
history[iter_num] = cur_pr... |
class DummyOAuth2Test(OAuth2Test):
backend_path = 'social_core.tests.backends.test_dummy.DummyOAuth2'
user_data_url = '
expected_username = 'foobar'
access_token_body = json.dumps({'access_token': 'foobar', 'token_type': 'bearer'})
user_data_body = json.dumps({'id': 1, 'username': 'foobar', 'url': '... |
def test_initial_file_object(rgb_file_object):
with FilePath(rgb_file_object) as vsifile:
with vsifile.open() as src:
assert (src.driver == 'GTiff')
assert (src.count == 3)
assert (src.dtypes == ('uint8', 'uint8', 'uint8'))
assert (src.read().shape == (3, 718,... |
def tilt_mask(size, tilt_ang1, tilt_ang2=None, tilt_axis=1, light_axis=2, sphere_mask=True):
assert (tilt_axis != light_axis)
if (tilt_ang2 is None):
tilt_ang2 = float(N.abs(tilt_ang1))
tilt_ang1 = (- tilt_ang2)
else:
assert (tilt_ang1 < 0)
assert (tilt_ang2 > 0)
tilt_ang... |
class CSGameExporter(GameExporter):
_busy: bool = False
def is_busy(self) -> bool:
return self._busy
def export_can_be_aborted(self) -> bool:
return False
def _before_export(self):
assert (not self._busy)
self._busy = True
def _after_export(self):
self._busy =... |
class GrafanaOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.grafana.GrafanaOAuth2'
user_data_url = '
access_token_body = json.dumps({'access_token': 'foobar', 'token_type': 'bearer'})
user_data_body = json.dumps({'login': 'fooboy', 'email': '', 'name': 'Foo Bar'})
expected_username = '... |
_on_posix
def test_run_shell_raise_on_fail():
assert (run_shell('true') == (None, None, 0))
assert (run_shell('true', raise_on_fail=False) == (None, None, 0))
with pytest.raises(subprocess.CalledProcessError):
run_shell('false')
assert (run_shell('false', raise_on_fail=False) == (None, None, 1)) |
def test_diff_newline_at_end(pytester: Pytester) -> None:
pytester.makepyfile("\n def test_diff():\n assert 'asdf' == 'asdf\\n'\n ")
result = pytester.runpytest()
result.stdout.fnmatch_lines("\n *assert 'asdf' == 'asdf\\n'\n * - asdf\n * ? -\n * + asdf... |
class SEModule(nn.Module):
def __init__(self, channels, reduction):
super(SEModule, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc1 = nn.Conv2d(channels, (channels // reduction), kernel_size=1, padding=0, bias=False)
self.relu = nn.ReLU(inplace=True)
self.fc... |
def _module_name_from_path(path: Path, root: Path) -> str:
path = path.with_suffix('')
try:
relative_path = path.relative_to(root)
except ValueError:
path_parts = path.parts[1:]
else:
path_parts = relative_path.parts
if ((len(path_parts) >= 2) and (path_parts[(- 1)] == '__ini... |
def make_support(question, source='wiki40b', method='dense', n_results=10):
if (source == 'none'):
(support_doc, hit_lst) = (' <P> '.join(['' for _ in range(11)]).strip(), [])
elif (method == 'dense'):
(support_doc, hit_lst) = query_qa_dense_index(question, qar_model, qar_tokenizer, passages, gp... |
def blend(first, second, coefficient=0.5):
(first, second) = (color_to_rgb(first), color_to_rgb(second))
r = int(((coefficient * first.R) + ((1 - coefficient) * second.R)))
g = int(((coefficient * first.G) + ((1 - coefficient) * second.G)))
b = int(((coefficient * first.B) + ((1 - coefficient) * second.... |
class CachingFileBackend(SimpleFileBackend):
def __init__(self, config: 'Configuration', cache_manager: t.Optional[CacheManager]=None):
super().__init__(config)
self.cache_manager = (cache_manager or CacheManager())
def add_package(self, filename: str, stream: t.BinaryIO) -> None:
super(... |
def plot_distribution(*distributions, states=None, label=None, figsize=(9, 3), fig=None, ax=None, lineplot_threshold=64, title='State distribution', y_label='Pr(state)', validate=True, labels=None, **kwargs):
if (validate and (not all((np.allclose(d.sum(), 1, rtol=0.0001) for d in distributions)))):
raise V... |
def topkp_decoding(inp_ids, attn_mask, model, tokenizer):
topkp_output = model.generate(input_ids=inp_ids, attention_mask=attn_mask, max_length=256, do_sample=True, top_k=40, top_p=0.8, num_return_sequences=3, no_repeat_ngram_size=2, early_stopping=True)
Questions = [tokenizer.decode(out, skip_special_tokens=Tr... |
def test_shell_command_completion_does_path_completion_when_after_command(cmd2_app, request):
test_dir = os.path.dirname(request.module.__file__)
text = os.path.join(test_dir, 'conftest')
line = 'shell cat {}'.format(text)
endidx = len(line)
begidx = (endidx - len(text))
first_match = complete_t... |
def get_args_parser():
parser = argparse.ArgumentParser('Set transformer detector', add_help=False)
parser.add_argument('--lr', default=0.0001, type=float)
parser.add_argument('--lr_backbone', default=1e-05, type=float)
parser.add_argument('--batch_size', default=2, type=int)
parser.add_argument('--... |
class EventQueue():
def __init__(self):
self.__data = []
def put(self, item):
if (item is not None):
heapq.heappush(self.__data, item)
def put_all(self, iterable):
for item in iterable:
heapq.heappush(self.__data, item)
def get(self):
return heapq.... |
def extract_tw_template():
with open('templates.txt', 'r') as f:
room_intro_templ = {}
phrase_replace = {}
objects_replace = {}
room_desc_templ = {}
d_templ = {}
for (line_index, line) in enumerate(f):
if (line_index in range(2, 30)):
room_... |
class TestDuration(unittest.TestCase):
def test_wav(self):
actual = file_info.duration(INPUT_FILE)
expected = 10.0
self.assertEqual(expected, actual)
def test_wav_pathlib(self):
actual = file_info.duration(Path(INPUT_FILE))
expected = 10.0
self.assertEqual(expecte... |
def time_offset_finder(min_switch_ind, final_i_index, i_time, m_time):
assert (type(min_switch_ind) == int), 'min_switch_ind should be an int.'
assert (type(final_i_index) == int), 'final_i_index should be an int.'
assert (type(i_time) == list), 'i_time should be a list.'
assert (type(m_time) == list), ... |
class Worker(object):
def __init__(self):
self._sched = BackgroundScheduler()
self._operations = []
self._stop = Event()
self._terminated = Event()
self._raven_client = None
if (app.config.get('EXCEPTION_LOG_TYPE', 'FakeSentry') == 'Sentry'):
worker_name =... |
class Extension(Converter):
async def convert(self, ctx: Context, argument: str) -> str:
if ((argument == '*') or (argument == '**')):
return argument
argument = argument.lower()
if (argument in bot_instance.all_extensions):
return argument
if ((qualified_arg ... |
_dtype_float_test(only64=True, additional_kwargs={'clss': [IntegrationModule, IntegrationNNModule]})
def test_quad(dtype, device, clss):
torch.manual_seed(100)
random.seed(100)
nr = 2
fwd_options = {'method': 'leggauss', 'n': 100}
a = torch.nn.Parameter(torch.rand((nr,), dtype=dtype, device=device).... |
class Solution(object):
def mergeTrees(self, t1, t2):
if (t1 is None):
return t2
if (t2 is None):
return t1
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1 |
(frozen=False)
class CollaborationState():
optimizer_step: int
samples_accumulated: int
target_batch_size: int
num_peers: int
num_clients: int
eta_next_step: float
next_fetch_time: float
def ready_for_step(self):
return ((self.samples_accumulated >= self.target_batch_size) or (ge... |
class BaseParameterisedDistribution(nn.Module, metaclass=abc.ABCMeta):
def update(self, *input, **kwargs) -> T:
raise NotImplementedError
def forward(self, *input, **kwargs):
num_samples = kwargs.pop('num_samples', 1)
self.update(*input, **kwargs)
if self.training:
re... |
def run(nsis=False, ace=False, pdfjs=True, legacy_pdfjs=False, fancy_dmg=False, pdfjs_version=None, dicts=False, gh_token=None):
if nsis:
download_nsis_plugins()
if pdfjs:
update_pdfjs(pdfjs_version, legacy=legacy_pdfjs, gh_token=gh_token)
if ace:
update_ace()
if fancy_dmg:
... |
class Key(BasePathMixin):
tag = ext_x_key
def __init__(self, method, base_uri, uri=None, iv=None, keyformat=None, keyformatversions=None):
self.method = method
self.uri = uri
self.iv = iv
self.keyformat = keyformat
self.keyformatversions = keyformatversions
self.b... |
def build_progress_bar(args, iterator, epoch: Optional[int]=None, prefix: Optional[str]=None, default: str='tqdm', no_progress_bar: str='none'):
if getattr(args, 'no_progress_bar', False):
default = no_progress_bar
if (getattr(args, 'distributed_rank', 0) == 0):
tensorboard_logdir = getattr(args... |
def _get_elts(arg, context):
def is_iterable(n):
return isinstance(n, (nodes.List, nodes.Tuple, nodes.Set))
try:
inferred = next(arg.infer(context))
except (InferenceError, StopIteration) as exc:
raise UseInferenceDefault from exc
if isinstance(inferred, nodes.Dict):
item... |
class TestReproducibility(unittest.TestCase):
def _test_reproducibility(self, name, extra_flags=None):
if (extra_flags is None):
extra_flags = []
with tempfile.TemporaryDirectory(name) as data_dir:
with contextlib.redirect_stdout(StringIO()):
test_binaries.cre... |
class Conv2d(nn.Conv2d, Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True):
super(Conv2d, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias)
def forward(self, x, params=None, episode=None)... |
class EvaluationPlan():
def __init__(self, metrics: Iterable[SupportsMetricCompute], validators: Optional[Iterable[SupportsMetricValidate]]=None, composite_metrics: Optional[Iterable[SupportsCompositeMetricCompute]]=None, intervention_validators: Optional[List[str]]=None):
self.metrics = metrics
sel... |
def createEditor(parent, filename=None):
if (filename is None):
global newFileCounter
newFileCounter += 1
editor = PyzoEditor(parent)
editor.document().setModified(True)
editor.removeTrailingWS = True
editor._name = '<tmp {}>'.format(newFileCounter)
else:
... |
def _upgrade_package(venv: Venv, package_name: str, pip_args: List[str], is_main_package: bool, force: bool, upgrading_all: bool) -> int:
package_metadata = venv.package_metadata[package_name]
if (package_metadata.package_or_url is None):
raise PipxError(f'Internal Error: package {package_name} has corr... |
def checkSuccess(vmObject, actionData):
retVal = False
if (('SUCCESS_TYPE' in actionData) and ('SUCCESS_METRIC' in actionData)):
if (actionData['SUCCESS_TYPE'] == 'PROCESS'):
retVal = sampleLib.checkForProcess(vmObject, actionData['SUCCESS_METRIC'])
else:
print('NO SUCCESS_TYPE O... |
def main(pepno='426'):
print(('Comparing PEP %s version sort to setuptools.' % pepno))
(projects, public) = get_projects(VERSION_CACHE)
print()
Analysis('release versions', public, releases_only=True).print_report()
print()
Analysis('public versions', public).print_report()
print()
Analy... |
class FairseqDropout(nn.Module):
def __init__(self, p, module_name=None):
super().__init__()
self.p = p
self.module_name = module_name
self.apply_during_inference = False
def forward(self, x, inplace: bool=False):
if (self.training or self.apply_during_inference):
... |
def test_columns_no_desc(vuln_data):
columns_format = format.ColumnsFormat(False)
expected_columns = 'Name Version ID Fix Versions\n---- ------- ------ \nfoo 1.0 VULN-0 1.1,1.4\nfoo 1.0 VULN-1 1.0\nbar 0.1 VULN-2'
assert (columns_format.format(vuln_data, list()) == expected_columns) |
class ResNetHead(nn.Module):
def __init__(self, block_module, stages, num_groups=1, width_per_group=64, stride_in_1x1=True, stride_init=None, res2_out_channels=256, dilation=1):
super(ResNetHead, self).__init__()
stage2_relative_factor = (2 ** (stages[0].index - 1))
stage2_bottleneck_channel... |
def parse_col(toks, start_idx, tables_with_alias, schema, default_tables=None):
tok = toks[start_idx]
if (tok == '*'):
return ((start_idx + 1), schema.idMap[tok])
if ('.' in tok):
(alias, col) = tok.split('.')
key = ((tables_with_alias[alias] + '.') + col)
return ((start_idx ... |
_required
def new_template(request, orgslugname=None):
pytitionuser = get_session_user(request)
ctx = {'user': pytitionuser}
if orgslugname:
redirection = 'org_new_template'
try:
org = Organization.objects.get(slugname=orgslugname)
ctx['org'] = org
except Orga... |
def parse_args():
parser = argparse.ArgumentParser(description='AB3DMOT')
parser.add_argument('--det_name', type=str, default='pointrcnn', help='we provide pointrcnn on KITTI, megvii for nuScenes')
parser.add_argument('--dataset', type=str, default='KITTI', help='nuScenes, KITTI')
parser.add_argument('-... |
def _write_image_series(metric_file, relative_image_report_dir, series):
for (image_id, metric) in series.iteritems():
relative_image_report_path = _image_report_path(relative_image_report_dir, image_id)
metric_file.write(('<a href="%s">%s</a>: %f, \n' % (relative_image_report_path, image_id, metric... |
def test_tonality():
duration = 60.0
fs = 10025.0
samples = int((fs * duration))
times = (np.arange(samples) / fs)
signal = Signal(np.sin((((2.0 * np.pi) * 1000.0) * times)), fs)
tonality = Tonality(signal, signal.fs)
tonality.spectrum
tonality.plot_spectrum()
tonality.frequency_reso... |
def parse_ace_2004(tokenizer: Tokenizer) -> None:
output_dir_path = 'data/ace2004/'
os.makedirs(output_dir_path, mode=493, exist_ok=True)
output_file_list = ['ace2004.train', 'ace2004.dev', 'ace2004.test']
for (split_info_file, output_file) in zip(SPLIT_INFO_FILE_LIST, output_file_list):
output_... |
def get_rel_pos_cls(cfg: MaxxVitTransformerCfg, window_size):
rel_pos_cls = None
if (cfg.rel_pos_type == 'mlp'):
rel_pos_cls = partial(RelPosMlp, window_size=window_size, hidden_dim=cfg.rel_pos_dim)
elif (cfg.rel_pos_type == 'bias'):
rel_pos_cls = partial(RelPosBias, window_size=window_size)... |
class MeanShift(nn.Conv2d):
def __init__(self, rgb_range, rgb_mean=(0.4488, 0.4371, 0.404), rgb_std=(1.0, 1.0, 1.0), sign=(- 1)):
super(MeanShift, self).__init__(3, 3, kernel_size=1)
std = torch.Tensor(rgb_std)
self.weight.data = (torch.eye(3).view(3, 3, 1, 1) / std.view(3, 1, 1, 1))
... |
(eq=False, hash=False, slots=True)
class ParkingLot():
_parked: OrderedDict[(Task, None)] = attr.ib(factory=OrderedDict, init=False)
def __len__(self) -> int:
return len(self._parked)
def __bool__(self) -> bool:
return bool(self._parked)
_core.enable_ki_protection
async def park(self... |
class Migration(migrations.Migration):
dependencies = [('tasks', '0028_data_migration')]
operations = [migrations.AlterField(model_name='task', name='sites', field=models.ManyToManyField(blank=True, help_text='The sites this task belongs to (in a multi site setup).', to='sites.Site', verbose_name='Sites'))] |
def init_logger(filename, level='INFO'):
formatter = logging.Formatter('[ %(levelname)s : %(asctime)s ] - %(message)s')
logger = logging.getLogger(((__name__ + '.') + filename))
logger.setLevel(getattr(logging, level))
filehandler = logging.FileHandler(filename)
filehandler.setFormatter(formatter)
... |
class Browser():
def __init__(self, window, handle, browser, parent):
self.window = window
self.handle = handle
self.browser = browser
self.parent = parent
self.text_select = window.text_select
self.uid = window.uid
self.loaded = window.events.loaded
s... |
class ZoneRecordDal(object):
def list_zone_header():
zones = DnsHeader.query.all()
results = [zone.zone_name for zone in zones if (not zone.zone_name.endswith('.IN-ADDR.ARPA'))]
return sorted(results)
def list_zone_ttl():
pattern = re.compile('\\$TTL\\s+(\\d+)\\s?')
zone_... |
def set_session(user_info, session=flask.session, permanent=True):
session.permanent = bool(permanent)
session.update({'authenticated': True, 'id': user_info['id'], 'name': user_info['name'], 'role': user_info['role'], 'perms': user_info['permission'], 'template': user_info['template']})
return session |
def test_project_label_promotion(gl, group):
_id = uuid.uuid4().hex
data = {'name': f'test-project-{_id}', 'namespace_id': group.id}
project = gl.projects.create(data)
label_name = 'promoteme'
promoted_label = project.labels.create({'name': label_name, 'color': '#112233'})
promoted_label.promote... |
class BaseRequest(ABC):
session: ClientSession
log = logging.getLogger('aiosnow.request')
def __init__(self, api_url: str, session: ClientSession, fields: dict=None, headers: dict=None, params: dict=None, resolve: bool=False):
self.api_url = api_url
self.session = session
self.fields... |
_model
def hardcorenas_e(pretrained=False, **kwargs):
arch_def = [['ds_r1_k3_s1_e1_c16_nre'], ['ir_r1_k5_s2_e3_c24_nre_se0.25', 'ir_r1_k5_s1_e3_c24_nre_se0.25'], ['ir_r1_k5_s2_e6_c40_nre_se0.25', 'ir_r1_k5_s1_e4_c40_nre_se0.25', 'ir_r1_k5_s1_e4_c40_nre_se0.25', 'ir_r1_k3_s1_e3_c40_nre_se0.25'], ['ir_r1_k5_s2_e4_c80... |
def set_default(default_zone=None, connection_retries=None, connection_pool=None, connection_timeout=None, default_rs_host=None, default_uc_host=None, default_rsf_host=None, default_api_host=None, default_upload_threshold=None, default_query_region_host=None, default_query_region_backup_hosts=None, default_backup_hosts... |
class KwsTimeWeight(_lexicographic_weight.KwsTimeWeight):
def __new__(cls, *args):
if (len(args) == 0):
return _lexicographic_weight.KwsTimeWeight()
if (len(args) == 1):
if (isinstance(args[0], tuple) and (len(args[0]) == 2)):
args = args[0]
else:
... |
.django_db
.parametrize('site_name', ['site1', 'site2'])
def test_clear_site_cache_check_site_cache_size(site_name: str, settings) -> None:
assert (len(site_models.SITE_CACHE) == 0)
site = Site.objects.create(domain='foo.com', name=site_name)
settings.SITE_ID = site.id
assert (Site.objects.get_current()... |
class VGMF_Fusion(nn.Module):
def __init__(self, opt={}):
super(VGMF_Fusion, self).__init__()
self.gate = nn.Linear(1024, opt['embed']['embed_dim'])
def forward(self, sv, kv):
sv = l2norm(sv, dim=(- 1))
kv = l2norm(kv, dim=(- 1))
sw_s = F.sigmoid(self.gate(torch.cat([sv, ... |
class GenericEnv(VirtualEnv):
def __init__(self, path: Path, base: (Path | None)=None, child_env: (Env | None)=None) -> None:
self._child_env = child_env
super().__init__(path, base=base)
def find_executables(self) -> None:
patterns = [('python*', 'pip*')]
if self._child_env:
... |
class GlobalAttentionGeneral(nn.Module):
def __init__(self, idf, cdf):
super(GlobalAttentionGeneral, self).__init__()
self.sm = nn.Softmax()
self.mask = None
def applyMask(self, mask):
self.mask = mask
def forward(self, input, context_key, content_value):
(ih, iw) = (... |
def get_project_dependency_packages(locker: Locker, project_requires: list[Dependency], root_package_name: NormalizedName, project_python_marker: (BaseMarker | None)=None, extras: Collection[NormalizedName]=()) -> Iterator[DependencyPackage]:
if (project_python_marker is not None):
marked_requires: list[Dep... |
def _format_replace(replace: Optional[ReplaceTypes]=None) -> dict[(Variable, Variable)]:
items: dict[(Variable, Variable)]
if isinstance(replace, dict):
items = cast(dict[(Variable, Variable)], replace)
elif isinstance(replace, Iterable):
items = dict(replace)
elif (replace is None):
... |
class ArgKindsPlugin(Plugin):
def get_function_hook(self, fullname: str) -> (Callable[([FunctionContext], Type)] | None):
if ('func' in fullname):
return extract_arg_kinds_from_function
return None
def get_method_hook(self, fullname: str) -> (Callable[([MethodContext], Type)] | None)... |
class UserDBHandler(BaseHandler):
.authenticated
async def get(self, userid):
adminflg = False
user = (await self.db.user.get(userid, fields=('role',)))
if (user and (user['role'] == 'admin')):
adminflg = True
(await self.render('DB_manage.html', userid=userid, adminf... |
class DetectionNetworkBase(object):
def __init__(self, cfgs, is_training):
self.cfgs = cfgs
self.base_network_name = cfgs.NET_NAME
self.is_training = is_training
self.batch_size = (cfgs.BATCH_SIZE if is_training else 1)
if (cfgs.METHOD == 'H'):
self.num_anchors_pe... |
class TestSpiderDev170(unittest.TestCase):
(ONE_TEST_TIMEOUT)
def test_spider_dev(self):
split_name = 'dev'
i_query = 170
db_id = get_db_id(split_name, i_query)
(rdf_graph, schema) = get_graph_and_schema(split_name, db_id)
sql_query = get_sql_query(split_name, i_query)
... |
class ChocolateBoiler():
__empty: bool
__boiled: bool
__uniqueInstance = None
def __init__(self):
self.__empty = True
self.__boiled = False
def getInstance():
if (ChocolateBoiler.__uniqueInstance == None):
print('Creating unique instance of Chocolate Boiler')
... |
def skip_until(src: str, pos: Pos, expect: str, *, error_on: FrozenSet[str], error_on_eof: bool) -> Pos:
try:
new_pos = src.index(expect, pos)
except ValueError:
new_pos = len(src)
if error_on_eof:
raise suffixed_err(src, new_pos, f'Expected {expect!r}') from None
if (not... |
class FilericeCom(XFSDownloader):
__name__ = 'FilericeCom'
__type__ = 'downloader'
__version__ = '0.01'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('fallback', 'bool', 'Fallback t... |
class XFixes():
selection_mask = ((SelectionEventMask.SetSelectionOwner | SelectionEventMask.SelectionClientClose) | SelectionEventMask.SelectionWindowDestroy)
def __init__(self, conn):
self.conn = conn
self.ext = conn.conn(xcffib.xfixes.key)
self.ext.QueryVersion(xcffib.xfixes.MAJOR_VER... |
def get_reference_facial_points(output_size=None, inner_padding_factor=0.0, outer_padding=(0, 0), default_square=False):
tmp_5pts = np.array(REFERENCE_FACIAL_POINTS)
tmp_crop_size = np.array(DEFAULT_CROP_SIZE)
if default_square:
size_diff = (max(tmp_crop_size) - tmp_crop_size)
tmp_5pts += (s... |
class CartPoleEnv(gym.Env):
metadata = {'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': 50}
def __init__(self):
self.gravity = 9.8
self.masscart = 1.0
self.masspole = 0.1
self.total_mass = (self.masspole + self.masscart)
self.length = 0.5
self.p... |
class ScenePlot(Plot2D):
def __init__(self, scene, **kwargs):
Plot2D.__init__(self, scene, **kwargs)
self.components_available = {'displacement': {'name': 'LOS Displacement', 'eval': (lambda sc: sc.displacement)}, 'theta': {'name': 'LOS Theta', 'eval': (lambda sc: sc.theta)}, 'phi': {'name': 'LOS Ph... |
def get_sents_qa_num(file_path, mode):
sents = []
with open(file_path, 'r') as f:
for line in f.readlines():
line = line.strip()
tmp_sum = []
line = line.split('')[:(- 1)]
if (mode == 'final'):
for i in range(int((len(line) / 2))):
... |
class PFMarketPref(PreferenceView):
def __init__(self):
self.priceSettings = MarketPriceSettings.getInstance()
def populatePanel(self, panel):
self.title = _t('Market & Prices')
self.mainFrame = gui.mainFrame.MainFrame.getInstance()
self.sFit = Fit.getInstance()
helpCurso... |
class InceptionB(nn.Module):
def __init__(self):
super(InceptionB, self).__init__()
self.branch0 = BasicConv2d(1024, 384, kernel_size=1, stride=1)
self.branch1 = nn.Sequential(BasicConv2d(1024, 192, kernel_size=1, stride=1), BasicConv2d(192, 224, kernel_size=(1, 7), stride=1, padding=(0, 3))... |
class OggOpus(OggFileType):
_Info = OggOpusInfo
_Tags = OggOpusVComment
_Error = OggOpusHeaderError
_mimes = ['audio/ogg', 'audio/ogg; codecs=opus']
info = None
tags = None
def score(filename, fileobj, header):
return (header.startswith(b'OggS') * (b'OpusHead' in header)) |
def make_dataframe(spark_context, spark_session):
data = [{'id': 1, 'ts': '2016-04-11 11:31:11', 'feature1': 200, 'feature2': 200, 'nonfeature': 0}, {'id': 1, 'ts': '2016-04-11 11:44:12', 'feature1': 300, 'feature2': 300, 'nonfeature': 0}, {'id': 1, 'ts': '2016-04-11 11:46:24', 'feature1': 300, 'feature2': 400, 'no... |
class KnownValues(unittest.TestCase):
def test_n3_diffuse(self):
cell = make_test_cell.test_cell_n3_diffuse()
nmp = [1, 1, 2]
ehf2 = kmf.e_tot
self.assertAlmostEqual(ehf2, (- 6.), 6)
ecc2 = mycc.e_corr
self.assertAlmostEqual(ecc2, (- 0.), 6)
eom = EOMIP(mycc)
... |
def create_metrics_puller():
try:
while True:
KOA_LOGGER.debug('[puller] collecting new samples')
KOA_CONFIG.load_rbac_auth_token()
k8s_usage = K8sUsage()
k8s_usage.extract_namespaces_and_initialize_usage(pull_k8s('/api/v1/namespaces'))
k8s_usage.e... |
def create_datasets_and_loaders(args, model_config, neptune=None):
input_config = resolve_input_config(args, model_config=model_config)
(dataset_train, dataset_eval) = create_dataset(args.dataset, args.root, args.ann_name)
labeler = None
if (not args.bench_labeler):
labeler = AnchorLabeler(Ancho... |
def get_quay_user_from_federated_login_name(username):
results = FederatedLogin.select().where(FederatedLogin.metadata_json.contains(username))
user_id = None
for result in results:
if (json.loads(result.metadata_json).get('service_username') == username):
user_id = result.user_id
re... |
def get_test_sequences() -> dict[(str, TestSequence)]:
filter_list1_deny_dict = {'name': 'testname', 'list_type': 0, 'guild_pings': [], 'filter_dm': True, 'dm_pings': [], 'remove_context': False, 'bypass_roles': [], 'enabled': True, 'dm_content': '', 'dm_embed': '', 'infraction_type': 'NONE', 'infraction_reason': '... |
class up_res(nn.Module):
def __init__(self, up_in_ch, up_out_ch, cat_in_ch, cat_out_ch, if_convt=False):
super(up_res, self).__init__()
self.if_convt = if_convt
if self.if_convt:
self.up = nn.ConvTranspose2d(up_in_ch, up_out_ch, 2, stride=2)
else:
self.up = nn... |
class _ProcessMemoryInfo(object):
pagesize = PAGESIZE
def __init__(self) -> None:
self.pid = getpid()
self.rss = 0
self.vsz = 0
self.pagefaults = 0
self.os_specific = []
self.data_segment = 0
self.code_segment = 0
self.shared_segment = 0
se... |
def make_validate_dict(item: feedparser.FeedParserDict) -> dict:
_ = item.get('published_parsed', None)
if _:
published_at = datetime.fromtimestamp(mktime(_))
else:
published_at = datetime.now()
try:
result = {'title': item.title, 'description': item.summary, 'link': item.link, '... |
class InstallWizard(BaseWizard, Widget):
__events__ = ('on_wizard_complete',)
def on_wizard_complete(self, storage, db):
pass
def waiting_dialog(self, task, msg, on_finished=None):
def target():
try:
task()
except Exception as err:
self... |
class OfflineHost(github.Host):
def __init__(self, *args, network, **kwargs):
super().__init__(*args, **kwargs)
self._network = network
async def get(self, client, url):
return self._network[('GET', url)]
async def post(self, client, url, payload):
expected = self._network[('... |
def restore_previous_ratings(qcw):
incomplete_list = list(qcw.id_list)
prev_done = []
(ratings_file, backup_name_ratings) = get_ratings_path_info(qcw)
if pexists(ratings_file):
(ratings, notes) = load_ratings_csv(ratings_file)
prev_done = set(ratings.keys())
incomplete_list = lis... |
def Generate(n_max: int=10):
n_controls = []
t_count = []
for n in range(2, (n_max + 2)):
n_controls.append(n)
gate = MultiAnd(cvs=((1,) * n))
op = gate.on_registers(**get_named_qubits(gate.signature))
c = t_complexity(op)
t_count.append(c.t)
return (n_controls, t... |
def expand_stream_args(mode):
def wrap(f):
def g(*args, **kwargs):
stream = kwargs.pop('stream', None)
filename = kwargs.get('filename', None)
if (mode != 'r'):
filename = kwargs.pop('filename', None)
string = kwargs.pop('string', None)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.