code stringlengths 281 23.7M |
|---|
def target_loss(sess, target_lstm, data_loader):
nll = []
data_loader.reset_pointer()
for it in range(data_loader.num_batch):
batch = data_loader.next_batch()
g_loss = sess.run(target_lstm.pretrain_loss, {target_lstm.x: batch})
nll.append(g_loss)
return np.mean(nll) |
def coord_map_from_to(top_from, top_to):
def collect_bottoms(top):
bottoms = top.fn.inputs
if (top.fn.type_name == 'Crop'):
bottoms = bottoms[:1]
return bottoms
from_maps = {top_from: (None, 1, 0)}
frontier = {top_from}
while frontier:
top = frontier.pop()
... |
def vector_to_amplitudes(cc_or_eom, vec, kshift=0):
expected_vs = vector_size(cc_or_eom, kshift)
if (expected_vs != len(vec)):
raise ValueError('The size of the vector passed {:d} should be exactly {:d}'.format(len(vec), expected_vs))
itr = iter_12(cc_or_eom, kshift)
nocc = cc_or_eom.nocc
nm... |
class UserAgentMiddleware(Middleware):
def __init__(self, sdk_version):
sys_info = '{0}; {1}'.format(_platform.system(), _platform.machine())
python_ver = _platform.python_version()
user_agent = 'QiniuPython/{0} ({1}; ) Python/{2}'.format(sdk_version, sys_info, python_ver)
self.user_... |
class TestTryStar(TestNameCheckVisitorBase):
_before((3, 11))
def test_eg_types(self):
self.assert_passes('\n from typing import assert_type\n\n def capybara():\n try:\n pass\n except* ValueError as eg:\n assert_ty... |
def test_invalid_usage_old():
with raises(NotImplementedError):
sys.argv = shlex.split('visualqc -u {} -i {} -o {} --vis_type labels_contour'.format(fs_dir, id_list, out_dir))
cli_run()
with raises(NotImplementedError):
sys.argv = shlex.split('visualqc -f {} -i {} -o {} --outlier_method ... |
def is_iambic(phrase):
meter = ''
for word in phrase.split():
word = word.strip().strip(string.punctuation).lower()
try:
phones_list = pronouncing.phones_for_word(word)
stresses = pronouncing.stresses(phones_list[0])
if (len(stresses) == 1):
if... |
def hard_example_mining(dist_mat, labels, return_inds=False):
assert (len(dist_mat.size()) == 2)
assert (dist_mat.size(0) == dist_mat.size(1))
N = dist_mat.size(0)
is_pos = labels.expand(N, N).eq(labels.expand(N, N).t())
is_neg = labels.expand(N, N).ne(labels.expand(N, N).t())
(dist_ap, relative... |
class GetMinstServingHtmlHandler(webBase.BaseHandler):
def get(self):
arr = np.arange(30)
image_array = []
for idx in arr:
out_file = (out_dir % ('%05d' % idx))
print(out_file)
image_array.append(out_file)
self.render('minst_serving.html', image_ar... |
def test_imported_module_var_inferable3() -> None:
mod3 = parse(textwrap.dedent("\n from top3.mod import __dunder_var__ as v\n __dunder_var__ = ['w'] + v\n "), module_name='top')
parse("__dunder_var__ = ['v']", module_name='top3.mod')
w_val = mod3.body[(- 1)].value
i_w_val = next(w_val.infer())... |
def autodoc_process_bases(app, name, obj, option, bases: list):
for (idx, base) in enumerate(bases):
base = str(base)
if base.startswith('typing.AbstractAsyncContextManager'):
bases[idx] = ':class:`contextlib.AbstractAsyncContextManager`'
continue
if ('StringEnum' in ... |
class TreeWindowBase(QMdiSubWindow):
def __init__(self, parent=None):
super(TreeWindowBase, self).__init__(parent)
self.model = None
self.find_bar = None
self.view = QTreeView()
self.view.setSelectionMode(QAbstractItemView.ContiguousSelection)
self.view.CopyCellsToCli... |
class XBOGExchangeCalendar(TradingCalendar):
name = 'XBOG'
tz = timezone('America/New_York')
open_times = ((None, time(9, 31)),)
close_times = ((None, time(16)),)
def regular_holidays(self):
return HolidayCalendar([NewYearsDay, Epiphany, StJosephsDay, MaundyThursday, GoodFriday, LabourDay, M... |
class RandomDropout(nn.Module):
def __init__(self, p=0.5, inplace=False):
super(RandomDropout, self).__init__()
self.p = p
self.inplace = inplace
def forward(self, X):
theta = torch.Tensor(1).uniform_(0, self.p)[0]
return pt_utils.feature_dropout_no_scaling(X, theta, self... |
def frames2video(frame_dir, video_file, fps=30, fourcc='XVID', filename_tmpl='{:06d}.jpg', start=0, end=0, show_progress=True):
if (end == 0):
ext = filename_tmpl.split('.')[(- 1)]
end = len([name for name in scandir(frame_dir, ext)])
first_file = osp.join(frame_dir, filename_tmpl.format(start))... |
def get_portfoliodiversification_solution(rho: np.ndarray, n: int, q: int, result: MinimumEigensolverResult) -> np.ndarray:
del rho, q
v = result.eigenstate
if isinstance(v, StateFn):
v = v.to_matrix()
N = ((n ** 2) + n)
index_value = [x for x in range(len(v)) if (v[x] == max(v))][0]
str... |
_module()
class X3DHead(BaseHead):
def __init__(self, num_classes, in_channels, loss_cls=dict(type='CrossEntropyLoss'), spatial_type='avg', dropout_ratio=0.5, init_std=0.01, fc1_bias=False):
super().__init__(num_classes, in_channels, loss_cls)
self.spatial_type = spatial_type
self.dropout_ra... |
class KerasRegressor(BaseWrapper):
def predict(self, x, **kwargs):
kwargs = self.filter_sk_params(Sequential.predict, kwargs)
return np.squeeze(self.model.predict(x, **kwargs))
def score(self, x, y, **kwargs):
kwargs = self.filter_sk_params(Sequential.evaluate, kwargs)
loss = sel... |
def get_video_links():
response = requests.get(SITEMAP_URL)
soup = bs4.BeautifulSoup(response.content, 'lxml')
one_year_ago = (datetime.datetime.now() - datetime.timedelta(days=365)).date()
links = set()
for url in soup.find_all('url'):
loc = url.find('loc').string
path = urllib.pars... |
class CustomStatsView(BaseView):
('/', methods=['GET'])
def index(self):
return self.render('stats.html', stats=get_stats())
def is_accessible(self):
return current_user.is_authenticated
def inaccessible_callback(self, name, **kwargs):
return redirect(url_for('admin.login_view', ... |
def test_uninstall_suffix(pipx_temp_env):
name = 'pbr'
suffix = '_a'
executable_path = (constants.LOCAL_BIN_DIR / app_name(f'{name}{suffix}'))
assert (not run_pipx_cli(['install', PKG[name]['spec'], f'--suffix={suffix}']))
assert executable_path.exists()
assert (not run_pipx_cli(['uninstall', f'... |
def args_parse():
parser = argparse.ArgumentParser(description='FCGEC preprocess params')
base_args = ArgumentGroup(parser, 'base', 'Base Settings')
base_args.add_arg('mode', str, 'normal', 'STG Mode')
base_args.add_arg('out_uuid', bool, True, 'Output UUID in test file')
base_args.add_arg('err_only'... |
def download_file(url, local_filename):
if (not (' in url)):
f = urlopen(url)
with open(local_filename, 'wb') as lf:
lf.write(f.read())
else:
h = ({} if (not ('YADAGE_INIT_TOKEN' in os.environ)) else {'PRIVATE-TOKEN': os.environ['YADAGE_INIT_TOKEN']})
r = requests.get... |
def train_transform(rotation_range=45):
return A.Compose([A.Perspective(pad_mode=cv2.BORDER_CONSTANT, p=0.5), A.ShiftScaleRotate(shift_limit=0.0, scale_limit=0.1, rotate_limit=rotation_range, interpolation=1, border_mode=cv2.BORDER_CONSTANT, value=0, mask_value=0, always_apply=False, p=0.5), A.RandomBrightnessContr... |
class MultiLingualInput():
en: str = ''
it: str = ''
def clean(self, languages: list[str]) -> 'MultiLingualInput':
new_input = MultiLingualInput()
for lang in ('it', 'en'):
if (lang in languages):
value = getattr(self, lang)
setattr(new_input, lang... |
def get_anonymous_replacement_value(keyword, current_value=None, replacement_strategy=None):
vr = get_baseline_keyword_vr_dict()[keyword]
if (vr == 'CS'):
logging.warning('Keyword %s has Value Representation CS and may require special processing to avoid breaking DICOM conformance or interoperability', ... |
class MonitoredMemcacheConnection():
def __init__(self, context_name: str, server_span: Span, pooled_client: PooledClient):
self.context_name = context_name
self.server_span = server_span
self.pooled_client = pooled_client
_prom_instrument
def close(self) -> None:
with self._... |
def _is_all_proxies(collection):
if isinstance(collection, dict):
collection = list(collection.values())
if all((isinstance(elem, Proxy) for elem in collection)):
return True
if any((isinstance(elem, Proxy) for elem in collection)):
raise ValueError('Collection has mixed proxies and ... |
def test_order_marks(item_names_for):
tests_content = '\n import pytest\n\n .order(-1)\n def test_1(): pass\n\n .order(-2)\n def test_2(): pass\n\n .order(1)\n def test_3(): pass\n '
assert (item_names_for(tests_content) == ['test_3', 'test_2', 'test_1']) |
class _CloudStorage(BaseStorageV2):
def __init__(self, context, connection_class, connect_kwargs, upload_params, storage_path, bucket_name, access_key=None, secret_key=None):
super(_CloudStorage, self).__init__()
self.minimum_chunk_size = ((5 * 1024) * 1024)
self.maximum_chunk_size = None
... |
def check_singleton(cand_mol, ctr_node, nei_nodes):
rings = [node for node in (nei_nodes + [ctr_node]) if (node.mol.GetNumAtoms() > 2)]
singletons = [node for node in (nei_nodes + [ctr_node]) if (node.mol.GetNumAtoms() == 1)]
if ((len(singletons) > 0) or (len(rings) == 0)):
return True
n_leaf2_a... |
class SearchVisitor(ExtendedTraverserVisitor):
def __init__(self, line: int, column: int, end_line: int, end_column: int) -> None:
self.line = line
self.column = column
self.end_line = end_line
self.end_column = end_column
self.result: (Expression | None) = None
def visit... |
class Inform7Lexer(RegexLexer):
name = 'Inform 7'
url = '
aliases = ['inform7', 'i7']
filenames = ['*.ni', '*.i7x']
version_added = '2.0'
flags = (re.MULTILINE | re.DOTALL)
_dash = Inform6Lexer._dash
_dquote = Inform6Lexer._dquote
_newline = Inform6Lexer._newline
_start = ('\\A|(... |
class FusedLeakyReLUFunction(Function):
def forward(ctx, input, bias, negative_slope, scale):
empty = input.new_empty(0)
ctx.bias = (bias is not None)
if (bias is None):
bias = empty
out = fused.fused_bias_act(input, bias, empty, 3, 0, negative_slope, scale)
ctx.s... |
def gen_standalone(lark_inst, output=None, out=sys.stdout, compress=False):
if (output is None):
output = partial(print, file=out)
import pickle, zlib, base64
def compressed_output(obj):
s = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
c = zlib.compress(s)
output(repr(base64.b6... |
class RaftInfo(BaseModel, extra='forbid'):
term: int = Field(..., description='Raft divides time into terms of arbitrary length, each beginning with an election. If a candidate wins the election, it remains the leader for the rest of the term. The term number increases monotonically. Each server stores the current ... |
class SlotSelect(discord.ui.Select):
view: ScrimsView
def __init__(self, slots: T.List[ReservedSlot]):
_options = []
for _ in slots:
_options.append(discord.SelectOption(label=f'Slot {_.num}', description=f"Team: {_.team_name} ({(_.leader or 'No leader')})", value=_.id.__str__(), emo... |
def create_continuous_contract(df, resolution='1T'):
def _merge_contracts(m1, m2):
if (m1 is None):
return m2
try:
roll_date = m1['expiry'].unique()[(- 1)]
except Exception as e:
combined = m1.merge(m2, left_index=True, right_index=True)
m_high... |
class TestOptions(BaseOptions):
def initialize(self):
BaseOptions.initialize(self)
self.parser.add_argument('--ntest', type=int, default=float('inf'), help='# of test examples.')
self.parser.add_argument('--results_dir', type=str, default='./results/', help='saves results here.')
sel... |
class BeitFeatureExtractor(FeatureExtractionMixin, ImageFeatureExtractionMixin):
model_input_names = ['pixel_values']
def __init__(self, do_resize=True, size=256, resample=Image.BICUBIC, do_center_crop=True, crop_size=224, do_normalize=True, image_mean=None, image_std=None, reduce_labels=False, **kwargs):
... |
def handle_withdraw(token_network_state: TokenNetworkState, state_change: ContractReceiveChannelWithdraw, block_number: BlockNumber, block_hash: BlockHash, pseudo_random_generator: random.Random) -> TransitionResult:
return subdispatch_to_channel_by_id(token_network_state=token_network_state, state_change=state_cha... |
def recover_closest_standard(feature_matrix_all, image_paths, save_path, n_image_samples=10, n_closest=3):
image_paths = np.array([x[0] for x in image_paths])
sample_idxs = np.random.choice(np.arange(len(feature_matrix_all)), n_image_samples)
faiss_search_index = faiss.IndexFlatL2(feature_matrix_all.shape[(... |
class Transaction(object):
_types(asset=Asset)
def __init__(self, asset, amount, dt, price, order_id):
self.asset = asset
self.amount = amount
self.dt = dt
self.price = price
self.order_id = order_id
self.type = DATASOURCE_TYPE.TRANSACTION
def __getitem__(self... |
def run_eval(load_model, load_sess, filename, sample_num_file, hparams, flag):
with open(sample_num_file, 'r') as f:
sample_num = int(f.readlines()[0].strip())
load_sess.run(load_model.iterator.initializer, feed_dict={load_model.filenames: [filename]})
preds = []
labels = []
while True:
... |
_fixtures(WebFixture, DataTableFixture)
def test_layout_for_contained_table(web_fixture, data_table_fixture):
layout = TableLayout(heading_theme='light')
data_table = DataTable(web_fixture.view, data_table_fixture.columns, data_table_fixture.data, 'my_css_id', table_layout=layout)
assert (data_table.table.l... |
def main():
try:
examples = DPMSExamples()
print('Initial state')
examples.print_dpms()
print('Setting random timeouts')
examples.set_random_timeouts()
examples.print_dpms()
print('The next example will turn-off your screen, press Ctrl-C to cancel.')
t... |
def save_model(model, dirpath):
if os.path.exists(dirpath):
if (os.path.exists(os.path.join(dirpath, 'config.json')) and os.path.isfile(os.path.join(dirpath, 'config.json'))):
os.remove(os.path.join(dirpath, 'config.json'))
if (os.path.exists(os.path.join(dirpath, 'pytorch_model.bin')) a... |
def _add_runpip(subparsers, venv_completer: VenvCompleter, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser('runpip', help='Run pip in an existing pipx-managed Virtual Environment', description='Run pip in an existing pipx-managed Virtual Environment', parents=[shared_parser])
p.add_ar... |
class MultiplayerMembership(BaseModel):
user: User = peewee.ForeignKeyField(User, backref='sessions')
user_id: int
session: MultiplayerSession = peewee.ForeignKeyField(MultiplayerSession, backref='members')
session_id: int
admin: bool = peewee.BooleanField(default=False)
ready: bool = peewee.Boo... |
class EfficientNetBackbone(object):
def __init__(self, cfgs):
self.cfgs = cfgs
self.MEAN_RGB = [(0.485 * 255), (0.456 * 255), (0.406 * 255)]
self.STDDEV_RGB = [(0.229 * 255), (0.224 * 255), (0.225 * 255)]
self._DEFAULT_BLOCKS_ARGS = ['r1_k3_s11_e1_i32_o16_se0.25', 'r2_k3_s22_e6_i16_o... |
class STSBenchmarkFinetune(SICKEval):
def __init__(self, task_path, seed=1111):
logging.debug('\n\n***** Transfer task : STSBenchmark*****\n\n')
self.seed = seed
train = self.loadFile(os.path.join(task_path, 'sts-train.csv'))
dev = self.loadFile(os.path.join(task_path, 'sts-dev.csv')... |
def load_score_files(args):
if args.all_shards:
shard_ids = list(range(args.num_shards))
else:
shard_ids = [args.shard_id]
gen_output_lst = []
bitext1_lst = []
bitext2_lst = []
lm_res1_lst = []
for shard_id in shard_ids:
using_nbest = (args.nbest_list is not None)
... |
def prepare_build_wheel_files(build_directory, config_settings):
shutil.copy('pyproject.toml', build_directory)
for pyfile in glob('*.py'):
shutil.copy(pyfile, build_directory)
for distinfo in glob('*.dist-info'):
shutil.copytree(distinfo, pjoin(build_directory, distinfo)) |
class SawyerPlateSlideBackV2Policy(Policy):
_fully_parsed
def _parse_obs(obs):
return {'hand_pos': obs[:3], 'unused_1': obs[3], 'puck_pos': obs[4:7], 'unused_2': obs[7:]}
def get_action(self, obs):
o_d = self._parse_obs(obs)
action = Action({'delta_pos': np.arange(3), 'grab_effort': ... |
class OutgoingViewFull(StatsView):
name = 'outgoingViewFull'
def __init__(self, parent):
StatsView.__init__(self)
self.parent = parent
self._cachedValues = []
def getHeaderText(self, fit):
return _t('Remote Reps')
def getTextExtentW(self, text):
(width, height) = ... |
def is_extension_class(cdef: ClassDef) -> bool:
if any((((not is_trait_decorator(d)) and (not is_dataclass_decorator(d)) and (not get_mypyc_attr_call(d))) for d in cdef.decorators)):
return False
if cdef.info.typeddict_type:
return False
if cdef.info.is_named_tuple:
return False
... |
.parametrize('page', ['stylesheet/simple.html', 'stylesheet/simple_bg_set_red.html'])
def test_set_delayed(stylesheet_tester, page):
stylesheet_tester.js.load(page)
stylesheet_tester.init_stylesheet('none.css')
stylesheet_tester.set_css('body {background-color: rgb(0, 255, 0);}')
stylesheet_tester.check... |
class NvidiaSensors(base.ThreadPoolText):
defaults = [('format', '{temp}C', 'Display string format. Three options available: ``{temp}`` - temperature, ``{fan_speed}`` and ``{perf}`` - performance level'), ('foreground_alert', 'ff0000', 'Foreground colour alert'), ('gpu_bus_id', '', "GPU's Bus ID, ex: ``01:00.0``. ... |
class Blosc2(Codec):
codec_id = 'imagecodecs_blosc2'
def __init__(self, level=None, compressor=None, typesize=None, blocksize=None, shuffle=None, numthreads=None):
self.level = level
self.compressor = compressor
self.typesize = typesize
self.blocksize = blocksize
self.shu... |
class RDN(nn.Module):
def __init__(self, args):
super(RDN, self).__init__()
r = args.scale[0]
G0 = args.G0
kSize = args.RDNkSize
(self.D, C, G) = {'A': (20, 6, 32), 'B': (16, 8, 64)}[args.RDNconfig]
self.SFENet1 = nn.Conv2d(args.n_colors, G0, kSize, padding=((kSize - ... |
class NormPQ(object):
def __init__(self, n_percentile, quantize, true_norm=False, verbose=True, method='kmeans', recover='quantize'):
self.M = 2
(self.n_percentile, self.true_norm, self.verbose) = (n_percentile, true_norm, verbose)
self.method = method
self.recover = recover
... |
def focal_loss(alpha: Optional[Sequence]=None, gamma: float=0.0, reduction: str='mean', ignore_index: int=(- 100), device='cpu', dtype=torch.float32) -> FocalLoss:
if (alpha is not None):
if (not isinstance(alpha, Tensor)):
alpha = torch.tensor(alpha)
alpha = alpha.to(device=device, dtyp... |
class _TestSequenceMeta(type):
def __new__(mcs, name, bases, tests):
parent_path = (Path(__file__).parent.parent / 'docs')
cwd = os.getcwd()
os.chdir(parent_path)
for p in filter((lambda x: (x.suffix == '.rst')), parent_path.iterdir()):
with open(p, 'r', encoding='utf8') ... |
class SpeakerVoucher(TimeStampedModel):
class VoucherType(models.TextChoices):
SPEAKER = ('speaker', _('Speaker'))
CO_SPEAKER = ('co_speaker', _('Co-Speaker'))
conference = models.ForeignKey(Conference, on_delete=models.PROTECT, verbose_name=_('conference'), related_name='+')
user = models.F... |
class Input():
def __init__(self, parameter, **kwargs):
super().__init__(**kwargs)
self._parameter = None
self.set_parameter(parameter)
def set_parameter(self, parameter):
self._parameter = parameter
if parameter.is_set():
self.setValue(parameter.value)
... |
class UserDetailsPluginsList(PluginsList):
template_name = 'plugins/user.html'
def get_filtered_queryset(self, qs):
user = get_object_or_404(User, username=self.kwargs['username'])
return qs.filter((Q(created_by=user) | Q(owners=user)))
def get_context_data(self, **kwargs):
user = ge... |
class Metadata(pkg_resources.EmptyProvider):
def __init__(self, *pairs):
self.metadata = dict(pairs)
def has_metadata(self, name):
return (name in self.metadata)
def get_metadata(self, name):
return self.metadata[name]
def get_metadata_lines(self, name):
return pkg_resour... |
.parametrize('delete', [True, False])
.parametrize('stylesheet_param', [True, False])
.parametrize('update', [True, False])
.parametrize('changed_option', ['colors.hints.fg', 'colors.hints.bg'])
def test_set_register_stylesheet(delete, stylesheet_param, update, changed_option, qtbot, config_stub, caplog):
config_st... |
class DeactivateButtonEvent(DefaultScript):
def at_script_creation(self):
self.key = 'deactivate_button'
self.desc = 'Deactivate red button temporarily'
self.interval = 21
self.start_delay = True
self.persistent = True
self.repeats = 1
def at_start(self):
... |
def insert_deepcopy(fgraph, wrapped_inputs, wrapped_outputs):
assert (len(wrapped_inputs) == len(fgraph.inputs))
assert (len(wrapped_outputs) == len(fgraph.outputs))
reason = 'insert_deepcopy'
updated_fgraph_inputs = {fgraph_i for (i, fgraph_i) in zip(wrapped_inputs, fgraph.inputs) if getattr(i, 'update... |
class SpatialSegmentSmoothness(object):
def __init__(self, n_chans, n_dims, warped_contours_layer_output=None, lambda_i=1.0):
self.n_dims = n_dims
self.warped_contours_layer_output = warped_contours_layer_output
self.lambda_i = lambda_i
def compute_loss(self, y_true, y_pred):
los... |
class FakeDataset(object):
def __init__(self, info, attrs, dims=None):
for (var_name, var_data) in list(info.items()):
if isinstance(var_data, np.ndarray):
info[var_name] = xr.DataArray(var_data)
self.info = info
self.attrs = attrs
self.dims = (dims or {})... |
class EFI_LOADED_IMAGE_PROTOCOL(STRUCT):
_pack_ = 8
_fields_ = [('Revision', UINT32), ('ParentHandle', EFI_HANDLE), ('SystemTable', PTR(EFI_SYSTEM_TABLE)), ('DeviceHandle', EFI_HANDLE), ('FilePath', PTR(EFI_DEVICE_PATH_PROTOCOL)), ('Reserved', PTR(VOID)), ('LoadOptionsSize', UINT32), ('LoadOptions', PTR(VOID)),... |
class GradCam(Explainer):
def __init__(self, gnn_model_path):
super(GradCam, self).__init__(gnn_model_path)
def explain_graph(self, graph, model=None, draw_graph=0, vis_ratio=0.2):
if (model == None):
model = self.model
edge_attr = Variable(graph.edge_attr, requires_grad=True... |
class AverageMeter(object):
def __init__(self, name, fmt=':f', summary_type=Summary.AVERAGE):
self.name = name
self.fmt = fmt
self.summary_type = summary_type
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
d... |
def test_resampling_nan_function(verbose=True, *args, **kwargs):
from radis import get_residual
from radis.test.utils import getTestFile
from radis.tools.database import load_spec
plot = True
s = load_spec(getTestFile('CO_Tgas1500K_mole_fraction0.01.spec'), binary=True).crop(2170, 2180, 'cm-1')
... |
class Completion(BaseModel):
id: str
object: str
created: int
model: str
choices: List[TextChoice]
usage: Optional[Usage]
def create(cls, model: str, prompt: str, use_prompt_format: bool=True, max_tokens: Optional[int]=16, temperature: Optional[float]=1.0, top_p: Optional[float]=1.0, stream:... |
class JumpToMarketItem(ContextMenuSingle):
def __init__(self):
self.mainFrame = gui.mainFrame.MainFrame.getInstance()
def display(self, callingWindow, srcContext, mainItem):
validContexts = ('marketItemMisc', 'fittingModule', 'fittingCharge', 'droneItem', 'implantItem', 'boosterItem', 'projected... |
class KarrasVePipeline(DiffusionPipeline):
unet: UNet2DModel
scheduler: KarrasVeScheduler
def __init__(self, unet, scheduler):
super().__init__()
scheduler = scheduler.set_format('pt')
self.register_modules(unet=unet, scheduler=scheduler)
_grad()
def __call__(self, batch_size... |
class HashtagTests(RaveberryTest):
def test_empty(self) -> None:
self.assertFalse(Tag.objects.exists())
def _get_random_hashtag(self) -> str:
html = self.client.get(reverse('musiq')).content
soup = BeautifulSoup(html, 'html.parser')
hashtag = soup.find('span', id='hashtag-text')
... |
class CocoTasksGT(Dataset):
def __init__(self, task_number: int, set_name: str):
assert (task_number in TASK_NUMBERS)
assert (set_name in ['train'])
self.len_lambda = 60
self.task_number = task_number
self.set_name = set_name
self.only_relevant = False
self.an... |
def asizeof(*objs, **opts):
(t, p, x) = _objs_opts_x(asizeof, objs, **opts)
_asizer.reset(**p)
if t:
if x:
_asizer.exclude_objs(t)
s = _asizer.asizeof(*t)
_asizer.print_stats(objs=t, opts=opts)
_asizer._clear()
else:
s = 0
return s |
def test_foldl_memory_consumption():
x = shared(np.asarray(np.random.uniform(size=(10,)), dtype=config.floatX))
(o, _) = foldl((lambda v, acc: (acc + v)), x, pt.constant(np.asarray(0.0, dtype=config.floatX)))
mode = FAST_RUN
mode = mode.excluding('inplace')
f0 = function([], o, mode=mode)
(input... |
class PyramidPooling(Module):
def __init__(self, in_channels, norm_layer, up_kwargs):
super(PyramidPooling, self).__init__()
self.pool1 = AdaptiveAvgPool2d(1)
self.pool2 = AdaptiveAvgPool2d(2)
self.pool3 = AdaptiveAvgPool2d(3)
self.pool4 = AdaptiveAvgPool2d(6)
out_cha... |
def _offline_song_suggestions(query: str) -> List[SuggestionResult]:
results: List[SuggestionResult] = []
terms = query.split()
song_results: Iterable[Mapping[(str, Any)]]
if settings.DEBUG:
matching_songs = ArchivedSong.objects.prefetch_related('queries')
for term in terms:
... |
def is_pipeline_test(test_case):
if (not _run_pipeline_tests):
return unittest.skip('test is pipeline test')(test_case)
else:
try:
import pytest
except ImportError:
return test_case
else:
return pytest.mark.is_pipeline_test()(test_case) |
class ScreenMode():
width = None
height = None
depth = None
rate = None
def __init__(self, screen):
self.screen = screen
def __repr__(self):
return f'{self.__class__.__name__}(width={self.width!r}, height={self.height!r}, depth={self.depth!r}, rate={self.rate})' |
.supported(only_if=(lambda backend: backend.dh_supported()), skip_message='DH not supported')
class TestDHSerialization():
.skip_fips(reason='non-FIPS parameters')
def test_dh_public_key(self, backend):
data = load_vectors_from_file(os.path.join('asymmetric', 'DH', 'dhkey.pem'), (lambda pemfile: pemfile... |
class TFControl():
def __init__(self, k=0.0, n0=0.0, n1=0.0, d0=0.0, d1=0.0, Ts=0.01, limit=1.0):
self.k = k
self.n0 = n0
self.n1 = n1
self.d0 = d0
self.d1 = d1
self.Ts = Ts
self.limit = limit
self.y = 0.0
self.u = 0.0
self.y_delay_1 = ... |
def init(disp, _info):
disp.extension_add_method('display', 'dpms_get_version', get_version)
disp.extension_add_method('display', 'dpms_capable', capable)
disp.extension_add_method('display', 'dpms_get_timeouts', get_timeouts)
disp.extension_add_method('display', 'dpms_set_timeouts', set_timeouts)
d... |
def get_canonical_path(project, resource, offset):
pymod = project.get_pymodule(resource)
pyname = evaluate.eval_location(pymod, offset)
(defmod, lineno) = pyname.get_definition_location()
if (not defmod):
return None
scope = defmod.get_scope().get_inner_scope_for_line(lineno)
names = []... |
def loadAWSInstanceProfiles(neo4j_session, data_path, account_name):
logger.info("[*] Loading AWS Role Instance Profiles into neo4j instance for AWS account '%s'", account_name)
ingest_role_instance_profiles = 'merge (instanceprofile:AWSInstanceProfile {Arn:$Arn}) \n\t\t\t\t\t\t\t\t\ton match set \n\t\t\t\t\t\t... |
class OSISAFL3NCFileHandler(NetCDF4FileHandler):
def _get_ease_grid(self):
from pyresample import create_area_def
proj4str = self['Lambert_Azimuthal_Grid/attr/proj4_string']
x_size = self['/dimension/xc']
y_size = self['/dimension/yc']
p_lowerleft_lat = self['lat'].values[((y... |
def fmt_item(x, l):
if isinstance(x, np.ndarray):
assert (x.ndim == 0)
x = x.item()
if isinstance(x, (float, np.float32, np.float64)):
v = abs(x)
if (((v < 0.0001) or (v > 10000.0)) and (v > 0)):
rep = ('%7.2e' % x)
else:
rep = ('%7.5f' % x)
el... |
def component(function: Callable[(..., (((ComponentType | VdomDict) | str) | None))]) -> Callable[(..., Component)]:
sig = inspect.signature(function)
if (('key' in sig.parameters) and (sig.parameters['key'].kind in (inspect.Parameter.KEYWORD_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD))):
msg = f"Com... |
def main(argv: List[str]):
args = parse_args(argv)
rank = int(os.environ['LOCAL_RANK'])
print('Running with args', args)
if torch.cuda.is_available():
device: torch.device = torch.device(f'cuda:{rank}')
backend = 'nccl'
torch.cuda.set_device(device)
else:
device: torc... |
class IPCCommandInterface(CommandInterface):
def __init__(self, ipc_client: ipc.Client):
self._client = ipc_client
def execute(self, call: CommandGraphCall, args: tuple, kwargs: dict) -> Any:
(status, result) = self._client.send((call.parent.selectors, call.name, args, kwargs))
if (statu... |
def check_frame_wise(cur_path, init_dirname, new_dirname):
new_path = os.path.join(cur_path, new_dirname)
pre_path = os.path.join(cur_path, init_dirname)
for dirname in os.listdir(pre_path):
print(dirname)
if (('.' in dirname) or (dirname == 'list_cvt_v1')):
continue
init... |
def autofill(args):
if (not args.task_name):
args.task_name = os.path.basename(os.getcwd())
if (not args.log_file):
if os.path.exists('./exps/logs'):
args.log_file = './exps/logs/{}_at-{}.log'.format(args.task_name, socket.gethostname())
else:
args.log_file = '.{}... |
def printHelp():
print('{} [OPTIONS] inputJson outputImg'.format(os.path.basename(sys.argv[0])))
print('')
print('Reads labels as polygons in JSON format and converts them to label images,')
print('where each pixel has an ID that represents the ground truth label.')
print('')
print('Options:')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.