code stringlengths 281 23.7M |
|---|
class Canvas(QLabel):
mode = 'rectangle'
primary_color = QColor(Qt.black)
secondary_color = None
primary_color_updated = pyqtSignal(str)
secondary_color_updated = pyqtSignal(str)
config = {'size': 1, 'fill': True, 'font': QFont('Times'), 'fontsize': 12, 'bold': False, 'italic': False, 'underline... |
def get_bar():
return bar.Bar([widget.GroupBox(font=font, fontsize=fontsize, active=foreground, urgent_border=alert, padding=0, borderwidth=3, margin_x=3, margin_y=0), widget.Sep(), widget.CurrentLayout(**font_params), widget.Sep(), widget.WindowName(**font_params), Metrics(**font_params), widget.Systray(icon_size=... |
class Migration(migrations.Migration):
dependencies = [('domain', '0008_meta')]
operations = [migrations.RemoveField(model_name='condition', name='attribute_entity'), migrations.RemoveField(model_name='condition', name='source_attribute'), migrations.RemoveField(model_name='condition', name='target_option'), mi... |
def save_model(path, epoch, model, optimizer=None):
if isinstance(model, torch.nn.DataParallel):
state_dict = model.module.state_dict()
else:
state_dict = model.state_dict()
data = {'epoch': epoch, 'state_dict': state_dict}
if (not (optimizer is None)):
data['optimizer'] = optimi... |
class TimelapseFramesExperiment(Experiment):
def get_model_name(self):
exp_name = 'TLF'
exp_name += '_{}'.format(self.dataset.display_name)
exp_name += '_{}'.format(self.arch_params['model_arch'])
exp_name += '_nprev{}'.format(self.combined_data_params['n_prev_frames'])
exp_n... |
def test_complete_headers(test_model_01):
headers = swmmio.utils.text.get_inp_sections_details(test_model_01.inp.path)
print(list(headers.keys()))
sections_in_inp = ['TITLE', 'OPTIONS', 'EVAPORATION', 'RAINGAGES', 'SUBCATCHMENTS', 'SUBAREAS', 'INFILTRATION', 'JUNCTIONS', 'OUTFALLS', 'STORAGE', 'CONDUITS', '... |
def get_feed_items(count=10):
return Item.objects.filter(status='active', activated_at__lte=datetime.datetime.now(), activated_at__gte=(datetime.datetime.now() - datetime.timedelta(days=90))).exclude(section=None).prefetch_related('issue', 'section', 'tags').order_by('-created_at', '-related_to_date')[:count] |
class EggInfoWithJS(egg_info):
def run(self) -> None:
static_path = os.path.join(NAME, STATIC_FOLDER)
if (os.path.exists(static_path) or ('READTHEDOCS' in os.environ)):
pass
else:
js_path = 'sqllineagejs'
use_shell = (True if (platform.system() == 'Windows... |
def test_a_decorated_singleton_is_shared_among_child_injectors():
parent_injector = Injector()
child_injector_1 = parent_injector.create_child_injector()
child_injector_2 = parent_injector.create_child_injector()
assert (child_injector_1.get(SingletonB) is child_injector_2.get(SingletonB)) |
class TestSeSolve():
H0 = ((0.2 * np.pi) * qutip.sigmaz())
H1 = (np.pi * qutip.sigmax())
tlist = np.linspace(0, 20, 200)
args = {'alpha': 0.5}
w_a = 0.35
a = 0.5
.parametrize(['unitary_op'], [pytest.param(None, id='state'), pytest.param(qutip.qeye(2), id='unitary')])
.parametrize(['H', '... |
class Post():
id: strawberry.ID
author: BlogPostAuthor
title: str = strawberry.field(resolver=make_localized_resolver('title'))
slug: str = strawberry.field(resolver=make_localized_resolver('slug'))
excerpt: str = strawberry.field(resolver=make_localized_resolver('excerpt'))
content: str = straw... |
def _get_density_and_strength_from_npz(npz):
l_density = []
l_strength = []
for word in npz:
if _is_bar_word(word):
l_density.append(_get_density(word))
l_strength.append(([0] * 16))
elif _is_beat_word(word):
(strength, tick) = _get_strength_and_tick(word)... |
def animate(callback_val):
global prev_time
global updates_per_sec
global world
counter_decay = 0
if animating:
num_steps = get_num_timesteps()
curr_time = get_curr_time()
time_elapsed = (curr_time - prev_time)
prev_time = curr_time
timestep = ((- update_times... |
class MaskRCNNFPNFeatureExtractor(nn.Module):
def __init__(self, cfg):
super(MaskRCNNFPNFeatureExtractor, self).__init__()
resolution = cfg.MODEL.ROI_MASK_HEAD.POOLER_RESOLUTION
scales = cfg.MODEL.ROI_MASK_HEAD.POOLER_SCALES
sampling_ratio = cfg.MODEL.ROI_MASK_HEAD.POOLER_SAMPLING_RA... |
class BoosterInfo():
def __init__(self, itemID, state=None, sideEffects=None):
self.itemID = itemID
self.state = state
self.sideEffects = sideEffects
def fromBooster(cls, booster):
if (booster is None):
return None
info = cls(itemID=booster.itemID, state=boost... |
def test(venv_client):
assert (venv_client.get('/users/1').status_code == 404)
nickname = str(uuid.uuid4())
r = venv_client.post('/users', json=dict(name=nickname))
r.raise_for_status()
r = r.json()
assert (venv_client.get('/users/{}'.format(r['id'])).json()['nickname'] == nickname) |
def test_ket2dm():
N = 5
ket = qutip.coherent(N, 2)
bra = ket.dag()
oper = qutip.ket2dm(ket)
oper_from_bra = qutip.ket2dm(bra)
assert (qutip.expect(oper, ket) == pytest.approx(1.0))
assert qutip.isoper(oper)
assert (oper == (ket * bra))
assert (oper == oper_from_bra)
with pytest.... |
def export_graph(nodes):
node_representations = []
wn_ids_to_synsets = {synset.wn_id: synset for synset in nodes}
wn_ids = set(wn_ids_to_synsets.keys())
if (len(wn_ids) != len(nodes)):
raise ValueError('Duplicate WordNet IDs in the same graph')
for wn_id in sorted(wn_ids):
synset = w... |
def create_pickup_database(game_enum: RandovaniaGame):
pickup_categories = {'weapon': PickupCategory(name='weapon', long_name='Weapon', hint_details=('a ', 'weapon'), hinted_as_major=True), 'ammo-based': PickupCategory(name='ammo-based', long_name='Ammo-Based', hint_details=('an ', 'ammo-based item'), hinted_as_maj... |
def main(_):
with tf.Graph().as_default():
(images, labels) = utils.prepare_testdata(FLAGS.dataset_dir, FLAGS.batch_size)
(logits, _) = network.inference(images, FLAGS.num_classes, for_training=False, feature_name=FLAGS.feature_name)
top_1_op = tf.nn.in_top_k(logits, labels, 1)
top_5... |
def RegisterSignalsFor(model):
eventName = 'events::db::{}'.format(GetPathFromClass(model))
eventsDict = {}
for event in events:
eventsDict[event] = '{}::{}'.format(eventName, event)
def pre_save_hook(sender, instance, *args, **kwargs):
if (instance.id is None):
Dispatcher.Di... |
class XAUDIO2_PERFORMANCE_DATA(ctypes.Structure):
_fields_ = [('AudioCyclesSinceLastQuery', c_uint64), ('TotalCyclesSinceLastQuery', c_uint64), ('MinimumCyclesPerQuantum', UINT32), ('MaximumCyclesPerQuantum', UINT32), ('MemoryUsageInBytes', UINT32), ('CurrentLatencyInSamples', UINT32), ('GlitchesSinceEngineStarted'... |
def test_charclass_union() -> None:
assert ((parse('[ab]') | parse('[bc]')).reduce() == parse('[abc]'))
assert ((parse('[ab]') | parse('[^bc]')).reduce() == parse('[^c]'))
assert ((parse('[^ab]') | parse('[bc]')).reduce() == parse('[^a]'))
assert ((parse('[^ab]') | parse('[^bc]')).reduce() == parse('[^b... |
class ExamplesTests(TestCasePlus):
def test_run_glue(self):
stream_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f'''
run_glue.py
--model_name_or_path distilbert-base-uncased
... |
class TestParameterize():
def test_idfn_marker(self, pytester: Pytester) -> None:
pytester.makepyfile("\n import pytest\n\n def idfn(param):\n if param == 0:\n return 'spam'\n elif param == 1:\n return 'ham'\n ... |
def convert_pytorch_checkpoint_to_tf(model: BertModel, ckpt_dir: str, model_name: str):
tensors_to_transpose = ('dense.weight', 'attention.self.query', 'attention.self.key', 'attention.self.value')
var_map = (('layer.', 'layer_'), ('word_embeddings.weight', 'word_embeddings'), ('position_embeddings.weight', 'po... |
class Migration(migrations.Migration):
initial = True
dependencies = [('conferences', '0011_auto__2340')]
operations = [migrations.CreateModel(name='Event', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', model_utils.fields.AutoCreatedFi... |
def test_bsmgrid(tmpdir):
spec = "dataarg: {workdir}\ndataopts:\n pathbase: {pathbase}\n subinits:\n signals:\n run_points_0: siginputs/sigpoint0\n run_points_1: siginputs/sigpoint1\n run_points_2: siginputs/sigpoint2\n data: datainputs\n backgrounds:\n run_bkgs_0: bkginputs/bkg_sample_0\n ... |
def read_setup_file(filename):
from distutils.sysconfig import parse_makefile, expand_makefile_vars, _variable_rx
from distutils.text_file import TextFile
from distutils.util import split_quoted
vars = parse_makefile(filename)
file = TextFile(filename, strip_comments=1, skip_blanks=1, join_lines=1, ... |
def Saveddata():
print('Building Saveddata')
from eos.saveddata.ship import Ship
from eos.saveddata.fit import Fit
from eos.saveddata.character import Character
from eos.saveddata.module import Module
from eos.const import FittingModuleState
from eos.saveddata.citadel import Citadel
from... |
def get_gt_bnd(gt):
gt = (gt > 0).astype(np.uint8).copy()
bnd = np.zeros_like(gt).astype(np.uint8)
for i in range(gt.shape[0]):
_mask = gt[i]
for j in range(1, (_mask.max() + 1)):
_gt = (_mask == j).astype(np.uint8).copy()
_gt_dil = dilation(_gt, disk(2))
... |
def main():
opts = TrainOptions().parse()
os.makedirs(opts.exp_dir, exist_ok=True)
opts_dict = vars(opts)
pprint.pprint(opts_dict)
with open(os.path.join(opts.exp_dir, 'opt.json'), 'w') as f:
json.dump(opts_dict, f, indent=4, sort_keys=True)
coach = Coach(opts)
coach.train() |
class Html():
def __init__(self, html_file, prompt_file_fullpath):
self.html_file_name = html_file
self.prompt_file_fullpath = prompt_file_fullpath
self.f = None
self.init_html()
def init_html(self):
self.f = open(self.html_file_name, 'w')
self.write('<!DOCTYPE ht... |
def process(datas, dataset, mode):
res = []
for data in datas:
res.append(process_one(data))
if (not os.path.exists('./loss/{}/word/'.format(dataset))):
os.makedirs('./loss/{}/word/'.format(dataset))
with open('./loss/{}/word/{}_loss.json'.format(dataset, mode), 'w') as file_obj:
... |
.parametrize('rng', [np.random.RandomState(123), np.random.default_rng(123)])
def test_GeneratorSharedVariable(rng):
s_rng_default = shared(rng)
s_rng_True = shared(rng, borrow=True)
s_rng_False = shared(rng, borrow=False)
assert (s_rng_default.container.storage[0] is not rng)
assert (s_rng_False.co... |
_grad()
def calculate_fid_given_paths(paths, img_size=256, batch_size=50, real_loader=None, real_mu=None, real_cov=None):
print(('Calculating FID given paths %s and %s...' % (paths[0], paths[1])))
device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
inception = InceptionV3().eval().to(dev... |
def gen_rr_src01_template(num_nops_src0, num_nops_src1, num_nops_dest, reg_src0, reg_src1, inst, src0, src1, result):
return '\n\n # Move src0 value into register\n csrr {reg_src0}, mngr2proc < {src0}\n {nops_src0}\n\n # Move src1 value into register\n csrr {reg_src1}, mngr2proc < {src1}\n {nops_s... |
class GINEConvLayer(nn.Module):
def __init__(self, dim_in, dim_out, dropout, residual):
super().__init__()
self.dim_in = dim_in
self.dim_out = dim_out
self.dropout = dropout
self.residual = residual
gin_nn = nn.Sequential(pyg_nn.Linear(dim_in, dim_out), nn.ReLU(), pyg... |
class TrainOptions():
def __init__(self):
self.parser = ArgumentParser()
self.initialize()
def initialize(self):
self.parser.add_argument('--exp_dir', type=str, help='Path to experiment output directory')
self.parser.add_argument('--dataset_type', default='ffhq_encode', type=str,... |
def parse_file(file_name):
prot_dict = {}
with open(file_name) as csvfile:
text = csv.reader(csvfile)
next(text, None)
for row in text:
prot_dict[row[4]] = list()
csvfile.seek(0)
next(text, None)
for row in text:
prot_dict[row[4]].append(in... |
class GetChatAdminsWithInviteLinks():
async def get_chat_admins_with_invite_links(self: 'pyrogram.Client', chat_id: Union[(int, str)]):
r = (await self.invoke(raw.functions.messages.GetAdminsWithInvites(peer=(await self.resolve_peer(chat_id)))))
users = {i.id: i for i in r.users}
return type... |
class AdaptiveDiffusionPipeline():
def __init__(self, estimator, student, teacher):
self.estimator = estimator
self.score_percentiles = None
self.student = student
self.teacher = teacher
def calc_score_percentiles(self, file_path, n_samples, num_inference_steps_student, prompts_p... |
class DropEmAndF1(object):
def __init__(self) -> None:
self._total_em = 0.0
self._total_f1 = 0.0
self._count = 0
def __call__(self, prediction: Union[(str, List)], ground_truths: List):
ground_truth_answer_strings = [answer_json_to_strings(annotation)[0] for annotation in ground_... |
class TolerantPullParser(_AbstractParser, sgmllib.SGMLParser):
def __init__(self, *args, **kwds):
sgmllib.SGMLParser.__init__(self)
_AbstractParser.__init__(self, *args, **kwds)
def unknown_starttag(self, tag, attrs):
attrs = self.unescape_attrs(attrs)
self._tokenstack.append(Tok... |
class proc_t(ctypes.Structure):
class lck_spin_t(ctypes.Structure):
_fields_ = (('opaque', (ctypes.c_ulong * 10)),)
_fields_ = (('p_list', list_entry), ('p_pid', ctypes.c_int32), ('task', POINTER64), ('p_pptr', POINTER64), ('p_ppid', ctypes.c_int32), ('p_pgrpid', ctypes.c_int32), ('p_uid', ctypes.c_uint... |
class Effect2143(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Target Painter')), 'signatureRadiusBonus', ship.getModifiedItemAttr('shipBonusMC2'), skill='Minmatar Cruiser', **kwargs) |
class CommunityManagersTest(TestCase):
def test_post_manager(self):
private_post = Post.objects.create(content='private post', media_type=Post.MEDIA_TEXT, status=Post.STATUS_PRIVATE)
public_post = Post.objects.create(content='public post', media_type=Post.MEDIA_TEXT, status=Post.STATUS_PUBLIC)
... |
def define_G(input_nc, output_nc, ngf, which_model_netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]):
netG = None
norm_layer = get_norm_layer(norm_type=norm)
if (which_model_netG == 'resnet_9blocks'):
netG = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=no... |
class FileItemObject(ops.data.DszObject):
def __init__(self, dszpath='', cmdid=None, parent=None, debug=False):
self.dszparent = parent
self.opsclass = fileitem
self.update(dszpath, cmdid, debug)
def update(self, dszpath='', cmdid=None, debug=False):
self.filehash = []
fo... |
def mean_tour_len_edges(x_edges_values, y_pred_edges):
y = F.softmax(y_pred_edges, dim=(- 1))
y = y.argmax(dim=3)
tour_lens = ((y.float() * x_edges_values.float()).sum(dim=1).sum(dim=1) / 2)
mean_tour_len = (tour_lens.sum().to(dtype=torch.float).item() / tour_lens.numel())
return mean_tour_len |
class TokenNetworkState(State):
address: TokenNetworkAddress
token_address: TokenAddress
channelidentifiers_to_channels: Dict[(ChannelID, NettingChannelState)] = field(repr=False, default_factory=dict)
partneraddresses_to_channelidentifiers: Dict[(Address, List[ChannelID])] = field(repr=False, default_f... |
class GuiToggleBoosterStatesCommand(wx.Command):
def __init__(self, fitID, mainPosition, positions):
wx.Command.__init__(self, True, 'Toggle Booster States')
self.internalHistory = InternalCommandHistory()
self.fitID = fitID
self.mainPosition = mainPosition
self.positions = p... |
def test_get_children() -> None:
func_node = extract_node('def func[T]() -> T: ...')
func_children = tuple(func_node.get_children())
assert isinstance(func_children[2], TypeVar)
class_node = extract_node('class MyClass[T]: ...')
class_children = tuple(class_node.get_children())
assert isinstance... |
class MainWindow(QMainWindow, Ui_MainWindow):
isFullScreen = False
isHideMenuBar = False
def __init__(self, parent=None):
super(MainWindow, self).__init__()
self.setupUi(self)
self.app = parent
self.settings = QSettings(zapzap.__appname__, zapzap.__appname__)
self.scd... |
def preceding_text(pattern):
try:
return _preceding_text_cache[pattern]
except KeyError:
pass
m = re.compile(pattern)
def _preceding_text():
app = get_app()
return bool(m.match(app.current_buffer.document.current_line_before_cursor))
condition = Condition(_preceding_t... |
class IntRangeTest(object):
def test_valid_range(self):
int_range = inputs.int_range(1, 5)
assert (int_range(3) == 3)
def test_inclusive_range(self):
int_range = inputs.int_range(1, 5)
assert (int_range(5) == 5)
def test_lower(self):
int_range = inputs.int_range(0, 5)... |
def GetData(url):
try:
r = requests.get(url, headers=headers, timeout=5)
r.encoding = 'utf-8'
return (r.status_code, r.text)
except (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError):
return ('Timeout', 'Timeout') |
class ArgSortOp(Op):
__props__ = ('kind', 'order')
def __init__(self, kind, order=None):
self.kind = kind
self.order = order
def __str__(self):
return (self.__class__.__name__ + f'{{{self.kind}, {self.order}}}')
def make_node(self, input, axis=(- 1)):
input = as_tensor_va... |
def perm_entropy(x, order=3, delay=1, normalize=False):
if isinstance(delay, (list, np.ndarray, range)):
return np.mean([perm_entropy(x, order=order, delay=d, normalize=normalize) for d in delay])
x = np.array(x)
ran_order = range(order)
hashmult = np.power(order, ran_order)
assert (delay > ... |
def print_asm(asm_code):
asm_code_list = asm_code
if isinstance(asm_code, str):
asm_code_list = [asm_code]
asm_list = []
for asm_seq in asm_code_list:
asm_list.extend(asm_seq.splitlines())
prev_blank_line = False
for asm in asm_list:
if (asm.strip() == ''):
if... |
class HP6633A(HP6632A):
def __init__(self, adapter, name='Hewlett Packard HP6633A', **kwargs):
super().__init__(adapter, name, **kwargs)
current_values = [0, limits['HP6633A']['Cur_lim']]
OVP_values = [0, limits['HP6633A']['OVP_lim']]
voltage_values = [0, limits['HP6633A']['Volt_lim']] |
def get_files(path, relative_to='fairseq'):
all_files = []
for (root, _dirs, files) in os.walk(path, followlinks=True):
root = os.path.relpath(root, relative_to)
for file in files:
if file.endswith('.pyc'):
continue
all_files.append(os.path.join(root, file... |
class Exclusive(ContextDecorator):
_locks = {}
_locks_creation_lock = threading.Lock()
def __init__(self, wrapped):
self._wrapped = wrapped
def get_lock(self):
_id = id(self._wrapped)
with Exclusive._locks_creation_lock:
if (not (_id in Exclusive._locks)):
... |
def decode_raiden_event_to_internal(abi: ABI, chain_id: ChainID, log_event: LogReceipt) -> DecodedEvent:
decoded_event = decode_event(abi, log_event)
if (not decoded_event):
raise UnknownRaidenEventType()
data = dict(decoded_event)
args = dict(decoded_event['args'])
data['args'] = args
d... |
class PornovkaCz(BaseDownloader):
__name__ = 'PornovkaCz'
__type__ = 'downloader'
__version__ = '0.02'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True)]
__description__ = 'Pornovka.cz downloader plugin'
__license__ = 'GPLv3'
__authors__ = [(... |
class SpanEntityScore(object):
def __init__(self, id2label):
self.id2label = id2label
self.reset()
def reset(self):
self.origins = []
self.founds = []
self.rights = []
def compute(self, origin, found, right):
recall = (0 if (origin == 0) else (right / origin))... |
def apply_transformation(x_source, x_transformation, output_shape, conditioning_input_shape, transform_name, flow_indexing='xy', color_transform_type='WB'):
n_dims = (len(conditioning_input_shape) - 1)
transformation_shape = x_transformation.get_shape().as_list()[1:]
x_transformation = Reshape(transformatio... |
_start_docstrings('The bare Cvt Model transformer outputting raw hidden-states without any specific head on top.', CVT_START_DOCSTRING)
class CvtModel(CvtPreTrainedModel):
def __init__(self, config, add_pooling_layer=True):
super().__init__(config)
self.config = config
self.encoder = CvtEnco... |
class transform(ctypes.Array):
_length_ = 7
_shape_ = (7,)
_type_ = ctypes.c_float
def __init__(self, p=(0.0, 0.0, 0.0), q=(0.0, 0.0, 0.0, 1.0)):
self[0:3] = vec3(*p)
self[3:7] = quat(*q)
def p(self):
return self[0:3]
def q(self):
return self[3:7] |
('a font having {vertAlign_state} vertical alignment')
def given_a_font_having_vertAlign_state(context, vertAlign_state):
style_name = {'inherited': 'Normal', 'subscript': 'Subscript', 'superscript': 'Superscript'}[vertAlign_state]
document = Document(test_docx('txt-font-props'))
context.font = document.sty... |
def test_cmd_error_throws_with_save_true_executable_not_found():
cmd = get_cmd('tests/testfiles/cmds/xxx', 'tests\\testfiles\\cmds\\xxx')
with pytest.raises(FileNotFoundError) as err:
context = Context({'cmd': {'run': cmd, 'save': True}})
pypyr.steps.cmd.run_step(context)
assert ('cmdOut' no... |
class AUC(BaseMetric):
def __init__(self, label_name):
self._label_name = label_name
def eval(self, predict, labels_map):
label = labels_map[self._label_name]
if ((np.sum(label) == 0) or (np.sum(label) == label.size)):
return MetricResult(result=float('nan'))
else:
... |
def add_action(name=None, location='\\', action_type='Execute', **kwargs):
logging.debug('Adding an action to the task...')
save_definition = False
if kwargs.get('task_definition', False):
task_definition = kwargs.get('task_definition')
else:
save_definition = True
if (not name):... |
class AnsiState(object):
def __init__(self, bold=False, inverse=False, color='white', background='black', backgroundbold=False):
self.bold = bold
self.inverse = inverse
self.color = color
self.background = background
self.backgroundbold = backgroundbold
trtable = {'black'... |
def get_image_paths_from_dir(fdir):
flist = os.listdir(fdir)
flist.sort()
image_paths = []
for i in range(0, len(flist)):
fpath = os.path.join(fdir, flist[i])
if os.path.isdir(fpath):
image_paths.extend(get_image_paths_from_dir(fpath))
else:
image_paths.ap... |
class TestOrderFactory(unittest.TestCase):
def setUpClass(cls):
cls.ticker = BloombergTicker('AAPL US Equity')
cls.crypto_ticker = BinanceTicker('BTC', 'BUSD')
cls.current_portfolio_value = 1000.0
cls.share_price = 10.0
position = Mock(spec=Position)
position.quantity... |
class COW():
def basepages(self, offset, length):
basepages = []
basepages.append(((offset - (offset % 4096)), (offset % 4096), (4096 - (offset % 4096))))
length -= (4096 - (offset % 4096))
offset += 4096
while (length >= 4096):
basepages.append((offset, 0, 4096))... |
class Delete(_base_nodes.AssignTypeNode, _base_nodes.Statement):
_astroid_fields = ('targets',)
def __init__(self, lineno: int, col_offset: int, parent: NodeNG, *, end_lineno: (int | None), end_col_offset: (int | None)) -> None:
self.targets: list[NodeNG] = []
super().__init__(lineno=lineno, col... |
class _PositionFactory():
def parse_position(element):
if element.findall('WorldPosition'):
return WorldPosition.parse(element)
elif element.findall('RelativeWorldPosition'):
return RelativeWorldPosition.parse(element)
elif element.findall('RelativeObjectPosition'):
... |
class TestBatchProcess(CommandTest):
def test_batch_commands(self):
self.call(batchprocess.CmdBatchCommands(), 'example_batch_cmds', 'Running Batch-command processor - Automatic mode for example_batch_cmds')
confirm = building.CmdDestroy.confirm
building.CmdDestroy.confirm = False
se... |
class FixedWordEmbedder(WordEmbedder):
def __init__(self, vec_name: str, word_vec_init_scale: float=0.05, learn_unk: bool=True, keep_probs: float=1, keep_word: float=1, shrink_embed: bool=False, cpu=False):
self.keep_word = keep_word
self.keep_probs = keep_probs
self.word_vec_init_scale = wo... |
def make_data_sampler(dataset, shuffle, distributed):
if distributed:
return samplers.DistributedSampler(dataset, shuffle=shuffle)
if shuffle:
sampler = torch.utils.data.sampler.RandomSampler(dataset)
else:
sampler = torch.utils.data.sampler.SequentialSampler(dataset)
return samp... |
def add_input_options(command):
def add_option(*args, **kwargs):
click.option(*args, **kwargs)(command)
add_option('--in', '-i', 'in_format', type=click.Choice(['smi', 'smi.gz']), help="Input structuture format (one of 'smi', 'smi.gz'). If not specified, use the filename extension or default to 'smi'.")... |
def datafiles_retrivedatabundle(config):
tutorial = config['tutorial']
countries = config['countries']
config_enable = config['enable']
config_bundles = load_databundle_config(config['databundles'])
bundles_to_download = get_best_bundles(countries, config_bundles, tutorial, config_enable)
listou... |
.parametrize(['dev', 'lines'], [(False, [f'a==1.2.3 ; {MARKER_PY27.union(MARKER_PY36_38)}']), (True, [f'a==1.2.3 ; {MARKER_PY27.union(MARKER_PY36_38).union(MARKER_PY36)}', f'b==4.5.6 ; {MARKER_PY}'])])
def test_exporter_can_export_requirements_txt_with_nested_packages_and_markers_any(tmp_path: Path, poetry: Poetry, dev... |
def enable_sanitized_heap(ql, fault_rate=0):
heap = QlSanitizedMemoryHeap(ql, ql.os.heap, fault_rate=fault_rate)
heap.oob_handler = (lambda *args: my_abort(f'Out-of-bounds read detected'))
heap.bo_handler = (lambda *args: my_abort(f'Buffer overflow/underflow detected'))
heap.bad_free_handler = (lambda *... |
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1, linear=False):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(dim, n... |
def get_qroam_cost(data_size: int, bitsize: int, adjoint: bool=False) -> Tuple[(int, int)]:
if adjoint:
k = (0.5 * np.log2(data_size))
value = (lambda k: ((data_size / (2 ** k)) + (2 ** k)))
else:
k = (0.5 * np.log2((data_size / bitsize)))
assert (k >= 0)
value = (lambda ... |
def validate_pathname_binary_tuple(data: Tuple[(str, IOBase)]):
if (not isinstance(data, tuple)):
raise TypeError(f'pathname binary data should be tuple type, but it is type {type(data)}')
if (len(data) != 2):
raise TypeError(f'pathname binary stream tuple length should be 2, but got {len(data)}... |
def test_mouse_release_event_when_scale_action(view, item):
view.scene.addItem(item)
event = MagicMock()
event.scenePos.return_value = QtCore.QPointF(20, 90)
item.scale_active = True
item.event_direction = (QtCore.QPointF(1, 1) / math.sqrt(2))
item.event_anchor = QtCore.QPointF(100, 80)
item... |
class Registry(object):
def __init__(self, name):
self._name = name
self._module_dict = dict()
def __repr__(self):
format_str = (self.__class__.__name__ + '(name={}, items={})'.format(self._name, list(self._module_dict.keys())))
return format_str
def name(self):
retur... |
class ScdocLexer(RegexLexer):
name = 'scdoc'
url = '
aliases = ['scdoc', 'scd']
filenames = ['*.scd', '*.scdoc']
version_added = '2.5'
flags = re.MULTILINE
tokens = {'root': [('^(;.+\\n)', bygroups(Comment)), ('^(#)([^#].+\\n)', bygroups(Generic.Heading, Text)), ('^(#{2})(.+\\n)', bygroups(G... |
def auth_handler() -> Tuple[(str, bool)]:
num = user_input[0]
input_thread = Thread(target=get_auth_code, args=(user_input,))
input_thread.daemon = True
input_thread.start()
for _ in range(120):
sleep(1)
if user_input[0]:
num = user_input[0]
user_input[0] = No... |
(cc=STDCALL, params={'SystemRoutineName': PUNICODE_STRING})
def hook_MmGetSystemRoutineAddress(ql: Qiling, address: int, params):
SystemRoutineName = params['SystemRoutineName']
routine_name = (SystemRoutineName and utils.read_punicode_string(ql, SystemRoutineName))
if routine_name:
for dll_name in ... |
class EquivalentRectangularIndex():
def __init__(self, gdf, areas=None, perimeters=None):
self.gdf = gdf
if (perimeters is None):
perimeters = gdf.geometry.length
elif isinstance(perimeters, str):
perimeters = gdf[perimeters]
self.perimeters = perimeters
... |
class InputFeedRNNDecoder(RNNDecoderBase):
def _run_forward_pass(self, tgt, memory_bank, memory_lengths=None):
input_feed = self.state['input_feed'].squeeze(0)
(input_feed_batch, _) = input_feed.size()
(_, tgt_batch, _) = tgt.size()
aeq(tgt_batch, input_feed_batch)
dec_outs =... |
def test_track_iter_progress():
out = StringIO()
ret = []
for num in mmcv.track_iter_progress([1, 2, 3], bar_width=3, file=out):
ret.append(sleep_1s(num))
assert (out.getvalue() == '[ ] 0/3, elapsed: 0s, ETA:\r[> ] 1/3, 1.0 task/s, elapsed: 1s, ETA: 2s\r[>> ] 2/3, 1.0 task/s, elapsed: 2s,... |
class FusedEmbeddingCollection(EmbeddingCollectionInterface, FusedOptimizerModule):
def __init__(self, tables: List[EmbeddingConfig], optimizer_type: Type[torch.optim.Optimizer], optimizer_kwargs: Dict[(str, Any)], device: Optional[torch.device]=None, need_indices: bool=False, location: Optional[EmbeddingLocation]=... |
class SingleFileConstraint(ValidationConstraint):
def __init__(self, error_message=None):
error_message = (error_message or _('$label can only accept a single file'))
super().__init__(error_message=error_message)
def validate_input(self, unparsed_input):
if (not (len(unparsed_input) <= 1... |
def run(train_path, test_path):
height = int(get_option('image', 'height'))
width = int(get_option('image', 'width'))
classes = int(get_option('image', 'classes'))
epochs = int(get_option('train', 'epochs'))
batch_size = int(get_option('train', 'batch_size'))
save_path = get_option('model', 'sav... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.