code stringlengths 281 23.7M |
|---|
_page.route('/table/save_settings', methods=['POST'])
def save():
res = check_uuid(all_data['uuid'], request.json['uuid'])
if (res != None):
return jsonify(res)
if ('condition' in request.json):
condition = request.json['condition']
all_data['filter_condition'].update(condition)
... |
class TestUCSPoperties(util.ColorAsserts, unittest.TestCase):
def test_u(self):
c = Color('color(--ucs 0.51332 0.92781 1.076)')
self.assertEqual(c['u'], 0.51332)
c['u'] = 0.2
self.assertEqual(c['u'], 0.2)
def test_v(self):
c = Color('color(--ucs 0.51332 0.92781 1.076)')
... |
.parametrize('degree', range(1, 4))
def test_right_inverse(mesh, degree):
V = FunctionSpace(mesh, 'DG', degree)
u = TrialFunction(V)
v = TestFunction(V)
form = (inner(u, v) * dx)
A = Tensor(form)
Result = assemble((A * A.inv))
nnode = V.node_count
assert ((Result.M.values - np.identity(n... |
_ns.after_request
def after_request(response):
request = flask.request
status = response.status_code
prefix = 'Webhook ({}) '.format(status)
if ((request.content_length is not None) and (request.content_length >= (100 * 1024))):
app.logger.info((prefix + 'large content: %d bytes'), request.conte... |
def send_email_notification():
time.sleep(20)
while True:
try:
schedule = get_value('config.property', 'SMTP', 'email_schedule')
records = email_db.db.email.find({})
for data in records:
notification = data['email_notification']
scan_id... |
def audio_converter(audio_file: BufferedReader, export_format: str='wav', frame_rate: Union[(int, None)]=None, channels: Union[(int, None)]=None):
file_extension = audio_file.name.split('.')[(- 1)]
audio_out: AudioSegment = AudioSegment.from_file(audio_file, format=file_extension)
if frame_rate:
aud... |
(('src', 'passthrough', 'expected'), [param({'_target_': 'tests.instantiate.Tree', 'value': 1, 'left': {'_target_': 'tests.instantiate.Tree', 'value': 21}}, {}, Tree(value=1, left=Tree(value=21)), id='default'), param({'_target_': 'tests.instantiate.Tree', '_recursive_': True, 'value': 1, 'left': {'_target_': 'tests.in... |
class CellStyle(object):
def __init__(self):
self.style_elements = {}
self.format_function = None
def set(self, key, value):
self.style_elements[key] = value
def css(self):
style = ''
for key in self.style_elements:
style += ('%s: %s;' % (key, self.style_e... |
def add_style(svgfile, style, replace=False):
if (style == '-'):
style = '/dev/stdin'
(root, ext) = os.path.splitext(style)
if ((ext == '.css') or (root == '/dev/stdin')):
with open(style, encoding='utf-8') as f:
style = replace_comments(f.read())
try:
svg = etree.par... |
def clean_nones(value: dict[(str, Any)]) -> dict[(str, Any)]:
if isinstance(value, list):
return [clean_nones(x) for x in value if (x is not None)]
if isinstance(value, dict):
return {key: clean_nones(val) for (key, val) in value.items() if (val is not None)}
return value |
class Plugin(plugin.PluginProto):
PLUGIN_ID = 523
PLUGIN_NAME = 'Communication - Jami DringCtrl (EXPERIMENTAL)'
PLUGIN_VALUENAME1 = 'State'
PLUGIN_VALUENAME2 = 'Status'
PLUGIN_VALUENAME3 = 'Peer'
PLUGIN_VALUENAME4 = 'Text'
def __init__(self, taskindex):
plugin.PluginProto.__init__(se... |
class Test_auth(unittest.TestCase):
def setUp(self):
self.nxt = 0
self.size = 4
self.spi = 256
self.seq = 1
self.data = b'!\xd3\xa9\\_\xfdM\x18F"\xb9\xf8'
self.auth = ipv6.auth(self.nxt, self.size, self.spi, self.seq, self.data)
self.form = '!BB2xII12s'
... |
class TakeUntil(Op):
__slots__ = ('_notifier',)
def __init__(self, notifier, source=None):
Op.__init__(self, source)
self._notifier = notifier
notifier.connect(self._on_notifier, self.on_source_error, self.on_source_done)
def _on_notifier(self, *args):
self.on_source_done(sel... |
class CartpoleEnv(mujoco_env.MujocoEnv, utils.EzPickle):
PENDULUM_LENGTH = 0.6
def __init__(self):
utils.EzPickle.__init__(self)
dir_path = os.path.dirname(os.path.realpath(__file__))
mujoco_env.MujocoEnv.__init__(self, ('%s/assets/cartpole.xml' % dir_path), 2)
def step(self, a):
... |
def fever(n: int):
import os
import json
path = os.path.join(os.path.expanduser('~'), '.cache', 'lmql', 'datasets', 'fever.json')
if (not os.path.exists(path)):
os.makedirs(os.path.join(os.path.expanduser('~'), '.cache', 'lmql', 'datasets'), exist_ok=True)
url = '
subprocess.run(... |
class RedisTransportClientCore(RedisTransportCore):
protocol_version = attr.ib(default=ProtocolVersion.VERSION_3, converter=_convert_protocol_version)
def is_server(self):
return False
def _get_metric_name(self, name):
return 'client.transport.redis_gateway.{name}'.format(name=name) |
def extractDwrfTL(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
tagmap = [('the world is fun as it became a death game', "The World Has Become a Death Game and It's Fun", 'transl... |
class PromptTemplateRegistry():
def __init__(self) -> None:
self.registry = defaultdict(dict)
def register(self, prompt_template, language: str='en', is_default=False, model_names: List[str]=None) -> None:
scene_name = prompt_template.template_scene
if (not scene_name):
raise... |
class lift(_coconut_base_callable):
__slots__ = ('func',)
def __new__(cls, func, *func_args, **func_kwargs):
self = _coconut.super(_coconut_lift, cls).__new__(cls)
self.func = func
if (func_args or func_kwargs):
self = self(*func_args, **func_kwargs)
return self
d... |
((detect_target().name() == 'rocm'), 'Not supported by ROCM.')
(((detect_target().name() == 'cuda') and (int(detect_target()._arch) < 80)), 'Not supported by CUDA < SM80.')
class ConvBiasActFewChannelsTestCase(unittest.TestCase):
def _test_conv_bias_relu_few_channels(self, HH=224, WW=224, CI=4, CO=64, batch=1, copy... |
class Migration(migrations.Migration):
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('core', '0010_auto__2140')]
operations = [migrations.CreateModel(name='Subscription', fields=[('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('cr... |
class group_add(group_mod):
version = 5
type = 15
command = 0
def __init__(self, xid=None, group_type=None, group_id=None, buckets=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (group_type != None):
self.group_type = group_ty... |
class Cpe(Base):
__tablename__ = 'cpes'
cpe_id = Column(String(), primary_key=True)
vendor = Column(String())
product = Column(String())
version = Column(String())
update = Column(String())
cves = relationship(Association, back_populates='cpe')
def __repr__(self) -> str:
return f... |
def rescaleHalflife(prior, scale=1.0):
(alpha, beta, t) = prior
oldHalflife = modelToPercentileDecay(prior)
dt = (oldHalflife / t)
logDenominator = betaln(alpha, beta)
logm2 = (betaln((alpha + (2 * dt)), beta) - logDenominator)
m2 = np.exp(logm2)
newAlphaBeta = ((1 / ((8 * m2) - 2)) - 0.5)
... |
class ClickSettings(Settings):
absolute_params = {'angle': 5.0}
relative_params = {'depth': 3.0, 'bottom_radius': 0.1}
def edgeObjects(self, boxes, chars: str='cC', add: bool=True):
edges = [ClickConnector(boxes, self), ClickEdge(boxes, self)]
return self._edgeObjects(edges, boxes, chars, ad... |
.skip('These tests take a very long time to compute')
.parametrize('sz', [32, 30, 31, 29, 28])
def test_grad_odd_size_j2(sz):
x = torch.randn(1, 3, sz, sz, requires_grad=True, dtype=torch.double, device=dev)
scat = ScatLayerj2(biort='near_sym_a', qshift='qshift_a').to(dev)
scat = scat.to(torch.double)
g... |
class URLFetcherTest(SimpleTestCase):
def setUp(self):
get_reversed_hashed_files.cache_clear()
def test_default(self):
url = '
with mock.patch('weasyprint.default_url_fetcher') as url_fetcher:
django_url_fetcher(url)
url_fetcher.assert_called_once_with(url)
ur... |
def setup():
print('')
global port, mc
plist = list(serial.tools.list_ports.comports())
idx = 1
for port in plist:
print('{} : {}'.format(idx, port))
idx += 1
_in = input('\nPlease input 1 - {} to choice:'.format((idx - 1)))
port = str(plist[(int(_in) - 1)]).split(' - ')[0].s... |
.external
.parametrize('generate_type, generate_target', [('systems', 'aws'), ('systems', 'okta'), ('datasets', 'db'), ('datasets', 'bigquery'), ('datasets', 'dynamodb')])
def test_generate_failure(test_config: FidesConfig, generate_type: str, generate_target: str, test_client: TestClient) -> None:
data = {'organiz... |
_flyte_cli.command('list-launch-plan-versions', cls=_FlyteSubCommand)
_project_option
_domain_option
_optional_name_option
_host_option
_insecure_option
_token_option
_limit_option
_show_all_option
_filter_option
_sort_by_option
_optional_urns_only_option
def list_launch_plan_versions(project, domain, name, host, insec... |
class IBCCoreConnectionRestClientTestCase(TestCase):
REST_CLIENT = IBCCoreConnectionRestClient
def make_clients(self, response_content: Dict) -> Tuple[(MockRestClient, IBCCoreConnectionRestClient)]:
mock_client = MockRestClient(json_encode(response_content).encode('utf-8'))
rest_client = self.RE... |
class OptionPlotoptionsArcdiagramSonificationDefaultinstrumentoptionsMappingVolume(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, t... |
class AdminIntegrationTest(SearchTestBase):
def setUp(self):
super(AdminIntegrationTest, self).setUp()
self.user = User(username='foo', is_staff=True, is_superuser=True)
self.user.set_password('bar')
self.user.save()
(('django.contrib.admin' in settings.INSTALLED_APPS), 'Django a... |
class SingleTestRun(EnsembleExperiment):
def __init__(self, simulation_arguments: SingleTestRunArguments, config: ErtConfig, storage: StorageAccessor, id_: UUID):
local_queue_config = config.queue_config.create_local_copy()
super().__init__(simulation_arguments, config, storage, local_queue_config, ... |
class OptionPlotoptionsAreasplineSonificationContexttracksMappingNoteduration(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: ... |
def test_save_as_move_external_files_to_project_folder(create_test_data, create_maya_env, trash_bin):
data = create_test_data
maya_env = create_maya_env
new_texture_file = pm.nt.File()
local_file_full_path = os.path.join(tempfile.gettempdir(), 'temp.png')
with open(local_file_full_path, 'w'):
... |
class TlsSubscriptionResponseAttributesAllOf(ModelNormal):
allowed_values = {('state',): {'PENDING': 'pending', 'PROCESSING': 'processing', 'ISSUED': 'issued', 'RENEWING': 'renewing', 'FAILED': 'failed'}}
validations = {}
_property
def additional_properties_type():
return (bool, date, datetime, ... |
class OptionPlotoptionsAreaSonificationContexttracksMappingPlaydelay(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 Article_CommentSerializer(serializers.ModelSerializer):
user = UserSerializer()
add_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', required=False, read_only=True)
articlecommentreply_set = ArticleCommentReplySerializer1(many=True, read_only=True)
class Meta():
model = Article... |
.plugin('snakes.nets')
def extend(module):
class PetriNet(module.PetriNet):
def __init__(self, name, **args):
self._hello = args.pop('hello', 'Hello from %s')
module.PetriNet.__init__(self, name, **args)
def hello(self):
print((self._hello % self.name))
return... |
(max_examples=10)
.filterwarnings('ignore::UserWarning')
.filterwarnings('ignore::RuntimeWarning')
.filterwarnings('ignore::ert.config.ConfigWarning')
(config_generators(use_eclbase=st.just(True)))
def test_that_enkf_obs_keys_are_ordered(tmp_path_factory, config_generator):
with config_generator(tmp_path_factory) a... |
.django_db
def test_match_from_code_filter_only(client, monkeypatch, elasticsearch_award_index, subaward_with_tas):
_setup_es(client, monkeypatch, elasticsearch_award_index)
resp = query_by_treasury_account_components_subaward(client, {'require': [_agency_path(BASIC_TAS)]}, None)
assert (resp.json()['result... |
class CustomFormOptionList(ResourceList):
def query(self, view_kwargs):
query_ = self.session.query(CustomFormOptions)
if view_kwargs.get('custom_form_id'):
query_ = self.session.query(CustomFormOptions).filter((getattr(CustomFormOptions, 'custom_form_id') == view_kwargs['custom_form_id'... |
def extractImperator(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, postfix=po... |
class UserTokenAPIView(RetrieveDestroyAPIView):
lookup_field = 'key'
serializer_class = TokenSerializer
queryset = Token.objects.all()
def filter_queryset(self, queryset):
return queryset.filter(user=self.request.user)
def retrieve(self, request, key, *args, **kwargs):
if (key == 'cu... |
def run_near_to_far(mesh, DG0, W):
velocity = as_vector((0.0, 1.0, 0.0))
u0 = project(velocity, W)
xs = SpatialCoordinate(mesh)
inflowexpr = conditional(And((real(xs[2]) > 0.33), (real(xs[2]) < 0.67)), 1.0, 0.5)
inflow = Function(DG0)
inflow.interpolate(inflowexpr)
n = FacetNormal(mesh)
... |
def extractLaoshutranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name,... |
def extractGrasstranslatesBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PGS', 'Peerless Genius System', 'translated'), ('dkfod', 'Devil King from the Otherworldly... |
def format_bulk_insert_list_column_sql(cursor, load_objects, type):
keys = load_objects[0][type].keys()
columns = ['"{}"'.format(key) for key in load_objects[0][type].keys()]
values = [[format_value_for_sql(load_object[type][key], cursor) for key in keys] for load_object in load_objects]
col_string = '(... |
class NibeClimate(NibeEntity, ClimateEntity):
def __init__(self, system: NibeSystem, climate: ClimateSystem, parameters: set[(ParameterId | None)]):
parameters |= {PARAM_PUMP_SPEED_HEATING_MEDIUM}
super().__init__(system, parameters)
self._climate = climate
self._status = 'DONE'
... |
class OptionSeriesArearangeSonificationContexttracksMappingHighpass(Options):
def frequency(self) -> 'OptionSeriesArearangeSonificationContexttracksMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionSeriesArearangeSonificationContexttracksMappingHighpassFrequency)
def resonance(s... |
class ReducedOutputsMeanSquaredError(tf.keras.losses.Loss):
def __init__(self, reduction=tf.keras.losses.Reduction.AUTO, name='reduced_outputs_mean_squared_error'):
super(ReducedOutputsMeanSquaredError, self).__init__(reduction=reduction, name=name)
def call(self, y_true, y_pred):
y_pred = tf.co... |
class OptionSeriesErrorbarSonificationTracksMappingLowpassFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
def activate_clade(tree_id):
(tid, subtree) = get_tid(tree_id)
tree_data = app.trees[int(tid)]
node = tree_data.tree[subtree]
tree_data.active.clades.results.add(node)
for n in node.descendants():
tree_data.active.clades.results.discard(n)
results = tree_data.active.clades.results
pa... |
_set_msg_type(ofproto.OFPT_PORT_MOD)
class OFPPortMod(MsgBase):
_TYPE = {'ascii': ['hw_addr']}
def __init__(self, datapath, port_no=0, hw_addr='00:00:00:00:00:00', config=0, mask=0, properties=None):
super(OFPPortMod, self).__init__(datapath)
self.port_no = port_no
self.hw_addr = hw_addr... |
class RateLimitV1Test(AmbassadorTest):
target: ServiceType
def init(self):
self.target = HTTP()
self.rls = RLSGRPC()
def config(self) -> Generator[(Union[(str, Tuple[(Node, str)])], None, None)]:
(yield (self.target, self.format('\n---\napiVersion: getambassador.io/v3alpha1\nkind: Ma... |
def gen_function(func_attrs, exec_cond_template, dim_info_dict, gemm_flag, extra_code='', ndims=2, extra_shape_template=EXTRA_SHAPE_TEMPLATE, problem_args_template=PROBLEM_ARGS_TEMPLATE, extra_header_template=EXTRA_HEADER_TEMPLATE, input_addr_calculator='', output_addr_calculator=''):
func_name = func_attrs['name']... |
def bump_version(cfg: Config, package: Package, hydra_root: str) -> None:
if (package.version_type == VersionType.SETUP):
ver_file = ((Path(hydra_root) / package.path) / 'setup.py')
bump_version_in_file(cfg, package.name, ver_file)
elif (package.version_type == VersionType.FILE):
ver_fil... |
.parametrize(('degree', 'family', 'expected_convergence'), [(1, 'CG', 1.8), (2, 'CG', 2.6), (3, 'CG', 3.8), (0, 'DG', 0.8), (1, 'DG', 1.8), (2, 'DG', 2.8)])
def test_convergence(degree, family, expected_convergence):
l2_diff = np.array([run_test(x, degree, family) for x in range(2, 5)])
conv = np.log2((l2_diff[... |
class TestFuzzTHBattle2v2(object):
def testFuzzTHBattle2v2(self):
env = Environ()
t = EventTap()
me = gevent.getcurrent()
def fail_crash(g):
e = Exception('GAME CRASH')
e.__cause__ = g.runner.exception
gevent.kill(me, e)
return g
... |
class BigQueryAgent(AgentBase):
def __init__(self):
super().__init__(task_type='bigquery_query_job_task', asynchronous=False)
def create(self, context: grpc.ServicerContext, output_prefix: str, task_template: TaskTemplate, inputs: Optional[LiteralMap]=None) -> CreateTaskResponse:
job_config = No... |
def amazon_receipt_parser_formatter(pages: List[dict]) -> ReceiptParserDataClass:
extracted_data = []
for page in pages:
for receipt in (page.get('ExpenseDocuments') or []):
summary = {}
currencies = {}
for field in (receipt.get('SummaryFields') or []):
... |
class ItemsBoxRec():
def from_records(records: List[dict], column: Any, title: str=None, color: str=None, icons=None) -> list:
if (title is None):
title = column
result = {}
if callable(title):
for rec in records:
result[rec[column]] = {'title': title(... |
class ChartMultiBar(ChartBar):
def dom(self) -> JsNvd3.JsNvd3MultiBar:
if (self._dom is None):
self._dom = JsNvd3.JsNvd3MultiBar(page=self.page, js_code=self.js_code, component=self)
return self._dom
def colors(self, hex_values: list):
(line_colors, bg_colors) = ([], [])
... |
class OptionPlotoptionsFunnel3dZones(Options):
def className(self):
return self._config_get(None)
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get(None)
def color(self, text: str):
self._config(text, js_type=False)... |
def test_adding_tolerations():
config = '\ndeployment:\n enabled: true\ndaemonset:\n tolerations:\n - key: "key1"\n operator: "Equal"\n value: "value1"\n effect: "NoExecute"\n tolerationSeconds: 3600\n'
r = helm_template(config)
assert (r['daemonset'][name]['spec']['template']['spec']['tolera... |
def find(search_list, value):
low = 0
high = (len(search_list) - 1)
while (low <= high):
middle = ((low + high) // 2)
if (search_list[middle] > value):
high = (middle - 1)
elif (search_list[middle] < value):
low = (middle + 1)
else:
return ... |
class KeyValueCache(DataclassAsTuple):
key: Tensor
value: Tensor
def filter_batch_items(self, mask: Tensor) -> 'KeyValueCache':
if (mask.ndim != 1):
raise ValueError(f'Cache mask must be a 1D tensor, has {mask.ndim} dimensions.')
if (mask.size(0) != self.key.size(0)):
... |
def pytorch_to_torchscript_wrapper(model: Model):
shim = model.shims[0]
if (not isinstance(shim, PyTorchShim)):
raise ValueError('Expected PyTorchShim when converting a PyTorch wrapper')
convert_inputs = model.attrs['convert_inputs']
convert_outputs = model.attrs['convert_outputs']
pytorch_m... |
def get_websocket_user(websocket: WebSocket, ticket_model: t.Optional[TicketInner]=Depends(load_websocket_ticket)):
if (ticket_model is None):
return None
user_queryset = get_user_queryset(User.objects.all(), CallbackContext(websocket.path_params))
return user_queryset.get(id=ticket_model.user) |
class Compose(Bijector):
def __init__(self, bijectors: Sequence[flowtorch.Lazy], *, shape: torch.Size, context_shape: Optional[torch.Size]=None):
assert (len(bijectors) > 0)
super().__init__(None, shape=shape, context_shape=context_shape)
self.bijectors = torch.nn.ModuleList()
for bi... |
def ArgsGeneralWrapper(f):
def decorated(request: gradio.Request, cookies, max_length, llm_model, txt, txt2, top_p, temperature, chatbot, history, system_prompt, plugin_advanced_arg, *args):
txt_passon = txt
if ((txt == '') and (txt2 != '')):
txt_passon = txt2
cookies.update({'to... |
def extractSouzoukaiHomeBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('nidome murabito', 'Nidome no Jinsei wa Zettai, Shiawase ni! ~Murabito ni Tensei shitan dakedo, Kond... |
class OptionPlotoptionsVariwide(Options):
def accessibility(self) -> 'OptionPlotoptionsVariwideAccessibility':
return self._config_sub_data('accessibility', OptionPlotoptionsVariwideAccessibility)
def allowPointSelect(self):
return self._config_get(False)
def allowPointSelect(self, flag: boo... |
class RemoveQueuedItemAfterPlayed(widgets.CheckPreference, widgets.CheckConditional):
default = False
name = 'queue/remove_item_after_played'
condition_preference_name = 'queue/remove_item_when_played'
def __init__(self, preferences, widget):
widgets.CheckPreference.__init__(self, preferences, w... |
class BasicTransformerBlock(nn.Module):
def __init__(self, dim, n_heads, d_head, dropout=0.0, context_dim=None, gated_ff=True, checkpoint=True):
super().__init__()
self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout)
self.ff = FeedForward(dim, dropout=d... |
def test_wf1_compile_time_constant_vars():
def t1(a: int) -> typing.NamedTuple('OutputsBC', t1_int_output=int, c=str):
return ((a + 2), 'world')
def t2(a: str, b: str) -> str:
return (b + a)
def my_wf(a: int, b: str) -> (int, str):
(x, y) = t1(a=a)
d = t2(a='This is my way', ... |
class BKZReduction(object):
def __init__(self, A):
if isinstance(A, GSO.Mat):
L = None
M = A
A = M.B
elif isinstance(A, LLL.Reduction):
L = A
M = L.M
A = M.B
elif isinstance(A, IntegerMatrix):
L = None
... |
def extractWtitranslationBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ((item['tags'] == []) and item['title'].startswith('Chapter ')):
return buildReleaseMessageW... |
def test_autodiff():
geom = geom_from_library('h2o.xyz', coord_type='redund')
print(geom)
B_ref = geom.internal.B
print(B_ref)
sg = autodiff.stretch_grad
bg = autodiff.bend_grad
auto_funcs = {2: sg, 3: bg}
int_ = geom.internal
ref_funcs = {2: int_.calc_stretch, 3: int_.calc_bend}
... |
class NetworkSimulator():
def __init__(self, latency=50):
self.agents = []
self.latency_distribution_sample = transform(normal_distribution(latency, ((latency * 2) // 5)), (lambda x: max(x, 0)))
self.time = 0
self.objqueue = {}
self.peers = {}
self.reliability = 0.9
... |
class OptionSeriesPolygonStatesHover(Options):
def animation(self) -> 'OptionSeriesPolygonStatesHoverAnimation':
return self._config_sub_data('animation', OptionSeriesPolygonStatesHoverAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._co... |
def test_format_dict_error():
with pytest.raises(ValueError) as exc_info:
apply_formatters_to_dict({'myfield': int}, {'myfield': 'a'})
with pytest.raises(ValueError) as exc_info:
eth_utils.apply_formatters_to_dict({'myfield': int}, {'myfield': 'a'})
assert ('myfield' in str(exc_info.value)) |
_parameters()
(name='true_positive', expected_result='fail', drop_failure_percent_threshold=5, metric_value=25)
(name='false_positive', expected_result='fail', drop_failure_percent_threshold=None, metric_value=29)
(name='true_negative', expected_result='pass', drop_failure_percent_threshold=5, metric_value=29)
def test... |
class crypto_base(object):
__key = None
__is_tcp = None
def __init__(self, is_tcp=False):
self.__is_tcp = is_tcp
self.__key = None
def key(self):
return self.__key
def is_tcp(self):
return self.__is_tcp
def set_key(self, key: str):
key = calc_str_md5(key)
... |
_ns.route('/<username>/<coprname>/update_chroot/<chrootname>/', methods=['POST'])
_ns.route('/g/<group_name>/<coprname>/update_chroot/<chrootname>/', methods=['POST'])
_required
_with_copr
def chroot_update(copr, chrootname):
chroot_name = chrootname
form = forms.ChrootForm()
chroot = ComplexLogic.get_copr_... |
.parametrize('lang', set((lang for lang in Mnemonic.list_languages() if (lang not in ('japanese', 'korean', 'chinese_simplified', 'chinese_traditional')))))
def test_expand(lang):
m = Mnemonic(lang)
words = m.generate()
for word in words.split(' '):
norm_word = normalize_string(word)
for siz... |
class DistanceDecimeters(DistanceValue):
def __init__(self, decimeters):
self.decimeters = decimeters
def __str__(self):
return (str(self.decimeters) + 'dm')
def __mul__(self, other):
assert isinstance(other, (float, int)), '{} can only be multiplied by an int or float'.format(self)
... |
class _CRG(Module):
def __init__(self, platform, sys_clk_freq):
self.rst = Signal()
self.clock_domains.cd_sys = ClockDomain()
self.clock_domains.cd_sys4x = ClockDomain(reset_less=True)
self.clock_domains.cd_sys4x_dqs = ClockDomain(reset_less=True)
self.clock_domains.cd_idelay... |
class AggregationDialogues(Dialogues, ABC):
END_STATES = frozenset({AggregationDialogue.EndState.SUCCESSFUL, AggregationDialogue.EndState.FAILED})
_keep_terminal_state_dialogues = False
def __init__(self, self_address: Address, role_from_first_message: Callable[([Message, Address], Dialogue.Role)], dialogue... |
def backprop_reduce_mean(d_means, lengths, *, threads_per_block=128, num_blocks=128):
_is_float_array(d_means)
B = len(lengths)
T = int(lengths.sum())
O = d_means.shape[1]
_check_lengths(lengths, T)
out = _alloc((T, O), dtype=d_means.dtype, zeros=False)
if (d_means.dtype == 'float32'):
... |
class OptionSeriesHistogramSonificationContexttracksMappingPan(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):
s... |
def test_task_get_overrides_with_command_environment_and_secrets(task_definition):
task_definition.set_commands(webserver='/usr/bin/python script.py')
task_definition.set_environment((('webserver', 'foo', 'baz'),))
task_definition.set_secrets((('webserver', 'bar', 'qux'),))
overrides = task_definition.g... |
def test_database_url_escape():
u = DatabaseURL(f"postgresql://username:{quote('[password')}/mydatabase")
assert (u.username == 'username')
assert (u.password == '[password')
assert (u.userinfo == f"username:{quote('[password')}".encode('utf-8'))
u2 = DatabaseURL(u)
assert (u2.password == '[pass... |
class OptionSeriesPolygonLabelStyle(Options):
def fontSize(self):
return self._config_get('0.8em')
def fontSize(self, num: float):
self._config(num, js_type=False)
def fontWeight(self):
return self._config_get('bold')
def fontWeight(self, text: str):
self._config(text, js... |
class TestSetup(TestBase):
def setUp(self):
self.tmpdir = tempfile.TemporaryDirectory(prefix='fract4d_')
import sys
if (sys.platform[:6] == 'darwin'):
self.userConfig = fractconfig.DarwinConfig('')
else:
self.userConfig = fractconfig.T('')
self.userCon... |
def run_and_assert(command, communicate=True):
print(f'Running command {command}')
output = subprocess.Popen(command, stdout=subprocess.PIPE)
if communicate:
(stdout, stderr) = output.communicate()
print('STDOUT', (stdout.decode('utf-8') if (stdout is not None) else None))
print('STD... |
class RestStatsApi(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION, ofproto_v1_2.OFP_VERSION, ofproto_v1_3.OFP_VERSION, ofproto_v1_4.OFP_VERSION, ofproto_v1_5.OFP_VERSION]
_CONTEXTS = {'dpset': dpset.DPSet, 'wsgi': WSGIApplication}
def __init__(self, *args, **kwargs):
super(RestStatsAp... |
(post_delete, sender=Post)
def decrease_posts_count_after_post_deletion(sender, instance, **kwargs):
if (not instance.approved):
return
try:
assert (instance.poster_id is not None)
poster = User.objects.get(pk=instance.poster_id)
except AssertionError:
return
except Objec... |
class MetaMapping():
_mappings = {'D:displayname': ('name', None, None)}
def _reverse_mapping(cls, mappings):
mappings.update({i[1][0]: (i[0], i[1][1], i[1][2]) for i in mappings.items()})
def _mapping_get(self, key):
return self.__class__._mappings.get(key, (key, None, None))
def map_ge... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.