ngram
listlengths
0
67.8k
[ "if path.endswith('/') and len(path) == 2: for v in self.list_dir(d + path[:-1]): yield", "= \"@%08x\" % (khash >> 32) _dir = self.get_dir(khash32) ret = [] if", "bucket)) def get_buckets_keys_count(store): \"\"\" return dict: buckets -> count \"\"\" st = {}", "get_buckets_keys_count(store): \"\"\" return dic...
[ "l1p1y l1p1y = l1p2y l1p2y = tmp l2p1x = line2[0][0] l2p1y = line2[0][1]", "False if l1p1y > l2p2y or l1p2y < l2p1y: return False return True", "= l2p1y l2p1y = l2p2y l2p2y = tmp # line2 rectangle is inside", "return True if l1p1x > l2p2x or l1p2x < l2p1x: return False if", "l2p2y = tmp # line2 rectangle is...
[ "= self.get_from() if from_clause is not None: rv = rv.select_from(from_clause) return rv.execution_options(loader=self) def", "= rv.outerjoin(from_clause, getattr(subloader, 'on_clause', None)) return rv def load(self, *column_names, **extras): if column_names:", "item) class ModelLoader(Loader): def __init__(...
[ "is None, returning data\") return \"data\" logging.debug(\"profile.get('curr_view', 'dummy') is %s\" % profile.get(\"curr_view\", \"data\"))", "to pass in the day, and # remove this interface. Extra credit: should", "newView): user = User.fromUUID(uuid) user.setClientSpecificProfileFields({'curr_view': newView...
[ "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,", "out.append( u\" * %s\" % (self.colorize(m.level, m.summary[\"en\"] % m.vars)) ) smsgs = [msg", "status on stderr with CLI? class BaseTextFormatter(Formatter): \"\"\" Base class for text formatters.\"\"\"", "if level == \"uri...
[ "scale_value(self, value): ''' (out_max - out_min)(value - in_min) f(x) = ----------------------------------- + out_min", "self._in_min ) / ( self._in_max - self._in_min )) + self._out_min # return ((", "= self.get_value() if update_led: self.set_rgb(_value) return self.scale_value(_value) # as float # # .........
[ "class Response: '' def close(): pass content = None def json(): pass text", "1.12.0 \"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.12.0', version='v1.12 on 2019-12-20', machine='ESP32 module (spiram)", "text = None def delete(): pass def get(): pass def head(): pass def", "def get(): pass def h...
[ "urlparse import urlparse def parse1(): p = re.compile(r\"/(?P<uid>\\d+)/(?P<mid>\\w+)\") o = urlparse(\"http://weibo.com/2827699110/yz62AlEjF\") m =", "p = re.compile(r\"/(?P<uid>\\d+)/(?P<mid>\\w+)\") o = urlparse(\"http://weibo.com/2827699110/yz62AlEjF\") m = p.search(o.path) print m.group('uid') print m.group...
[ "import Popup from kivy.properties import NumericProperty, ReferenceListProperty from kivy.uix.checkbox import CheckBox from kivy.core.window", "import matplotlib import datetime from TransactionBook.model.Filter import Filter from datetime import datetime from", "AnchorLayout() if option_init is None: option_i...
[ "bridge this turn. \"\"\" finished_cars = list() for c in self.cars: c.distance_on_bridge +=", "Bridge: \"\"\"Bridge class simulating the behaviour of bridge in simulation. On can set", "len(self.cars) > self.capacity def move_cars(self) -> List[Car]: \"\"\" Moves cars across the bridge", "= field(default_fac...
[ "self.config['main']['reporting_firmware_ver'], self.config['main']['uuid'], base_url)) elif contentPath == '/lineup_status.json': if self.hdhr_station_scan: returnJSON = templates['jsonLineupStatus'] else:", "enumerate(self.rmg_station_scans): if scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" de...
[ "context = {} # All resource paths end in .html. # Pick out", "from django.http import HttpResponse from django.template import loader @login_required(login_url=\"/login/\") def index(request): context =", "= loader.get_template(load_template) return HttpResponse(html_template.render(context, request)) except t...
[ "> 1 def convert_float_samples_to_int16(y): \"\"\"Convert floating-point numpy array of audio samples to int16.\"\"\"", "Is the given ndarray a multichannel spectrogram? :param samples: numpy ndarray :return: \"\"\"", "a multichannel spectrogram? :param samples: numpy ndarray :return: \"\"\" return len(spectrog...
[ "elif i == \"]\": if len(stack) < 1: print(False) exit() if stack[-1] ==", "stack.pop() else: print(False) exit() elif i == \"}\": if len(stack) < 1: print(False)", "1: print(False) exit() if stack[-1] == \"{\": stack.pop() else: print(False) exit() if len(stack)", "i == \"{\": stack.append(\"{\") elif i == \...
[ "data.get('slides'): for el in data.get('slides'): template = el.get('template') self.render(template=template, data=el, render_type='slide') @staticmethod def", "self.set_base_dirs() self.set_source_dirs() self.content = get_content(content_path) self.render_init_templates() if table_contents: self.render_table_...
[ "= \"encrypt\" subprocess.check_call(cmd_line) # Now we need to pass the encrypted-hsm startup option", "= node_factory.get_nodes(3) l1.fundwallet(10**6) # We should now have a transaction that gave us", "COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] == 4 # Simple test for", "decode['vin']: assert l1.da...
[ "is_unit_fraction=is_unit_fraction) df[cn.TRANSFER] = transfer dfs.append(df) if self._is_plot: plt.show() return pd.concat(dfs) def plotLine(self, transfer,", ":return pd.DataFrame: row=mutation, col=line, value is fraction \"\"\" if is_plot is None: is_plot", "plots nrows = 2 if (len(pairs) == 4) else 3 fig =...
[ "label in 3-dim(h,w,c) and in BGR fromat read from cv2 ''' h, w,", "KIND, either express or implied. # See the License for the specific language", "= open(train_file, \"r\") lines = [line[:-1] for line in train_text_file] for line in", "Unless required by applicable law or agreed to in writing, software # dis...
[ "= trainer.get_lr() train_meter = StopwatchMeter() train_meter.start() while lr > args.min_lr and epoch <=", "args.test_subset.split(','): scorer = score_test(args, trainer.get_model(), dataset, subset, beam, cuda_device=(0 if num_gpus > 0", "if num_gpus > 0 else None)) print('| Test on {} with beam={}: {}'.for...
[ "# Message sent. elif (command.startswith(\"sent,\")): m_id = command.split(\",\")[1] messages[m_id].sent(time) # Message processed. elif", "file>\") exit() messages = logTiming(sys.argv[1]) groups = groupByMsgType(messages) print() print(\"All messages:\") for key", "return groupByX(lambda x : x.getSource(), m...
[ "'\\n[' + error('ERROR') + '] schema of ' + str(e['url']) + ' is", "schemas = settings.SIMPLE_JSONSCHEMA for url, schema in schemas.items(): try: Draft4Validator.check_schema(schema) except SchemaError as", "except SchemaError as e: errors.append({ 'url': url, 'error': e, 'schema': json.dumps(schema, indent=4, ...
[ "right on right comb[:left.shape[0],:left.shape[1]] = left comb[:right.shape[0],left.shape[1]:] = right return comb def plotXY(data,size", "for our purposes. \"\"\" def resize(*args, **kwargs): return cv2.resize(*args, **kwargs) def moveWindow(*args,**kwargs): return", "= 0 P = [] for x,y in data: x = np.array(...
[ "that tag. tag_to_positions = defaultdict(set) for i, (token, tag) in enumerate(tagged_tokens): tag_to_positions[tag].add(i) #", "+= score tottrainscores = sum(trainscores) # det_tplsort() is for deterministic sorting; # the", "def extract_property(tokens, index): \"\"\"@return: The given token's text.\"\"\" re...
[ "+ xlnet_tokens_sub4 + xlnet_tokens_sub5 + [\"[SEP]\"] ) if len(tokens) > max_len: max_len =", "span_tokens[:length]: st = len(\" \".join(tokens[:idx])) + 1 if idx != 0 else 0", "= [] # span2 span2s = [] # span1 idx span1_idxs = []", "span_text, span_index): tokens = text.replace(\"\\n\", \" \").lower().split...
[ "= [] for i in range(len(self.tokens)): word = self.tokens[i] score = self.dictionary.get(word, 0)", "as data_file: self.dictionary = json.load(data_file) no_punctunation = re.sub(r\"[^a-zA-Z ]+\", \" \", self.text) self.tokens", "[\"no\", \"not\"]: word = \"not_\" + word score = -score if score <", "= [\"Sim...
[ "visit: # https://robodk.com/doc/en/PythonAPI/robolink.html from robolink import * # RoboDK API # JSON tools", "#OptimAxes_TEST[\"RefWeight_\" + str(i+1)] = (count+i) #OptimAxes_TEST[\"RefOn_\" + str(i+1)] = count % 2 #", "active: ToUpdate = {} ToUpdate[\"Active\"] = 1 json_str = json.dumps(json.dumps(ToUpdate)...
[ "\"\"\"E -> E ^ + T E -> T T -> T *", "self.assertSetEqual({'E', 'T', 'F'}, self.G.nonterminals) self.assertSetEqual({'+', '*', '(', ')', 'id', 'E', 'T', 'F'}, self.G.symbols)", "E ^ + T E -> T T -> T * F |", "-> T * F | F F -> ( E ) F ->", "E -> T T -> T * F | F F -> (", "id\"\"\", \"\"\"E -> E ^ + T E -...
[ "models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('elo_mean', models.IntegerField(default=0)), ('elo_diff', models.IntegerField(default=0)), ('result', models.CharField(max_length=40)), ('timecontrol', models.CharField(max_length=40)), ('timestamp',", "= True dependenci...
[ "1, key=world.Get_rank()) if world.Get_rank() < num_workers: if comm.Get_rank() == 0: x = torch.tensor([[0,", "@abort_on_exception def test_1(): worker_shape = [2, 2] world = MPI.COMM_WORLD num_workers = np.array(worker_shape).prod()", "comm=comm, worker_shape=worker_shape) e = torch.tensor([[0, 1], [2, 3]]) as...
[ "min_x = min(positions) max_x = max(positions) costs = {x: 0 for x in", "= abs(pos - crab) costs[pos] += ((distance * distance) + distance) // 2", "positions = [int(x) for x in infile.readline().strip().split(',')] min_x = min(positions) max_x = max(positions)", "def process(filename): with open(filename) as ...
[ "n def getFeatGene(x, firstOnly = False): # get gene if pd.isnull(x): return ''", "if firstOnly: return [n[1] for n in r][0] else: return [n[1] for n", "r][0] else: return [n[1] for n in r] def pd_filter(df, idx): # filters", "idx = [n for n in idx if n in df.index] return df.loc[idx,", "= [n for n in idx i...
[ "14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/random_title\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\")), (240, 240, 240), ElementsX + 95, ElementsY + 77,", "KIND, either express or implied. # See the License for the specific language", "Unless required by applicable law or agree...
[ "def getRawButton(self, num): return self._pressed[num] def press(self, num): self._pressed[num] = True def release(self,", "Toggle(joystick, 1, 0.1) assert toggleButton.off joystick.press(1) assert toggleButton.on joystick.release(1) joystick.press(1) joystick.release(1) assert toggleButton.on", "self._pressed...
[ "test cases for tflearn ''' import tensorflow.compat.v1 as tf import tflearn import unittest", "self.assertAlmostEqual( sess.run(tflearn.activation(x, 'tanh')), -0.2449, places=TestActivations.PLACES) # Case 5: lrelu_02 (callable) self.assertAlmostEqual( sess.run(tflearn.activation(x, lrelu_02)),", "sess.run(tf...
[ "an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "fab install-libs', shell=True, check=True) except: success = False reply = dict() reply['request_id'] =", "express or implied. See the License for the # spe...
[ "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "writing, software # distributed under the License is distributed on an \"AS IS\"", "edict({ 'task': 'NER', 'num_labels': 41, 'data_file': '', 'schema_file': None, 'finetune_ckpt': '', 'use_crf': False,", "'clue_benchmark': False, ...
[ "mdb_view: try: avb = ArticleViewedBy.objects.get(article=mdb_view['article'], user=mdb_view['user']) avb.viewed_at = mdb_view['viewed_at'] avb.save() except ArticleViewedBy.DoesNotExist: try:", "mdb_view = core_articleviewedby_mdb.posts.find_one_and_delete({}) while mdb_view: try: avb = ArticleViewedBy.objects.g...
[ "__init__(self, in_channels, out_channels, D=3): ResNetBase.__init__(self, in_channels, out_channels, D) def network_initialization(self, in_channels, out_channels, D):", "x): out = self.conv0p1s1(x) out = self.bn0(out) out_p1 = self.relu(out) out = self.conv1p1s2(out_p1)", "loss.item()) # Gradient loss.backwar...
[ "setuptools import setup setup( name='nginx-access-tailer', version='0.1', author='swfrench', url='https://github.com/swfrench/nginx-tailer', packages=['nginx_access_tailer',], license='BSD three-clause license', entry_points={", "version='0.1', author='swfrench', url='https://github.com/swfrench/nginx-tailer', p...
[ "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "writing, software # distributed under the License is distributed on an \"AS IS\"", "permissions and # limitations under the License. from .. import helpers from .", "}, \"exclusive\": false, \"name\": \"shared\" } } } \"\"\" def t...
[ "setuptools import find_packages, setup # allow setup.py to be run from any path", "#!/usr/bin/env python # -*- coding: utf-8 -* import os from setuptools import find_packages,", "utf-8 -* import os from setuptools import find_packages, setup # allow setup.py to", ":: Python :: 3', 'Programming Language :: Py...
[ "size=_max_receive_size): if self.on_read is not None: self.on_read() return self.receive_buffer.popleft() class ClientTests(unittest.TestCase): def setUp(self):", "is not None: self.on_read() return self.receive_buffer.popleft() class ClientTests(unittest.TestCase): def setUp(self): self.client = driver.Client(_...
[ "categorical_var = bank.select_dtypes(include = 'object') print(categorical_var) numerical_var = bank.select_dtypes(include = 'number') print(numerical_var) #", "# Import packages import numpy as np import pandas as pd from scipy.stats", "i in range(len(loan_terms)) if loan_term.value_counts().index[i] >= 25] #...
[ "build_design_matrices, PatsyError, Origin) def test_issue_11(): # Give a sensible error message for level", "try: build_design_matrices([info.design_info], new_data) except PatsyError as e: assert e.origin == Origin(formula, 0, 4)", "# This file is part of Patsy # Copyright (C) 2013 <NAME> <<EMAIL>>", "dmatr...
[ "'A' in image.mode: frame = image.convert('RGBA') elif image.mode == 'CMYK': frame = image.convert('RGB')", "image.seek(i) except EOFError: break frame = image if img_num is not None and", "an array with R, G, B columns palette = np.asarray(pil_image.getpalette()).reshape((256, 3)) # Not", "= 'I;16' mode_base...
[ "utf-8 -*- \"\"\" Linear chain of reactions. \"\"\" from __future__ import print_function, division", "/ (1 + S1 + S2); J2: S2 -> S3; (10 * S2", "0; S2 = 0; S3 = 0; S4 = 0; X0 = 10;", "X1 = 0; // Variable initialization: VM1 = 10; Keq1 = 10; h", "(10 * S3 - 2 * S4) / (1 + S3 + S4);", "(KS4 + S4); // Speci...
[ "UserUpdate from .transactions import Transaction, TransactionCreate, TransactionUpdate from .accounts import Account, AccountList, AccountSingle,", "from .transactions import Transaction, TransactionCreate, TransactionUpdate from .accounts import Account, AccountList, AccountSingle, AccountCreate,", "import Tr...
[ "def __init__(self): super.test(Bar, self).__init__() class InvalidSuperCall(Foo): def __init__(self): super(InvalidSuperCall.__class__, self).__init__() def method_accepting_cls(cls, self):", "cell found # (Exact exception would be 'RuntimeError: super(): __class__ cell not found')", "to *not* see a warning ab...
[ "labelencoder_X_6 = LabelEncoder() X[:, 6] = labelencoder_X_6.fit_transform(X[:, 6]) labelencoder_X_7 = LabelEncoder() X[:, 7]", "LabelEncoder() X[:, 7] = labelencoder_X_7.fit_transform(X[:, 7]) labelencoder_X_9 = LabelEncoder() X[:, 9] = labelencoder_X_9.fit_transform(X[:,", "LabelEncoder() X[:, 1] = labelenco...
[ "data output_test = gcn(C_test[:-1], X_test[:-1], e_test) guess_test = t.argmax(output_test, dim=1) if eval_type ==", "MAP_train, MRR_train, loss_train)) print(\"alpha/Tr/Ep %.2f/%d/%d. Val MAP/MRR %.16f/%.16f. Val loss %.16f.\" % (alpha,", "[6,6,2], nonlin2=\"selu\") elif no_layers == 1: gcn = ehf.EmbeddingKWG...
[ "_test_y = data[2][0], np.array(data[2][1]).reshape(len(data[2][1]), 1) return _train_x, _train_y, _val_x, _val_y, _test_x, _test_y if", "_test_x, _test_y = data[2][0], np.array(data[2][1]).reshape(len(data[2][1]), 1) return _train_x, _train_y, _val_x, _val_y, _test_x, _test_y", "import ELMClassifier from sklea...
[ "97), 200) print('bob:', bob.uid) # socket communication kdc_host, kdc_port = 'localhost', 9999 bob_host,", "msg: print(msg); sys.exit(1) # sock_with_kdc.shutdown(socket.SHUT_WR) # talk to bob try: sock_self = socket.socket(socket.AF_INET,", "bob.uid) # socket communication kdc_host, kdc_port = 'localhost', 999...
[ "taking_best: print(\"using best instead of latest\") model_path = os.path.join(config.out_dir, \"best_net.pytorch\") net.load_state_dict( torch.load(model_path, map_location=lambda", "as archs from proj.utils.cluster.general import config_to_str, get_opt, update_lr from proj.utils.cluster.baselines.triplets impo...
[ "nullable=False), sa.Column(\"created_at\", sa.DateTime(), nullable=True), sa.Column(\"updated_at\", sa.DateTime(), nullable=True), sa.ForeignKeyConstraint( [\"job_id\"], [\"jobs.id\"], ), sa.PrimaryKeyConstraint(\"id\"), )", "sa.DateTime(), nullable=True), sa.Column(\"updated_at\", sa.DateTime(), nullable=True),...
[ "def test_otpauth_url(self): url = urlparse(self.user_settings.otpauth_url) assert_equal(url.scheme, 'otpauth') assert_equal(url.netloc, 'totp') assert_equal(url.path, '/RDM:{}'.format(self.user.username)) assert_equal( parse_qs(url.query),", "can test it was changed back. self.user_settings.totp_drift = 1 self.u...
[ "class TransformWhileSampling(object): def __init__(self, transform): self.transform = transform def __call__(self, sample): x1 =", "as np from torchvision import transforms np.random.seed(1) class TransformWhileSampling(object): def __init__(self, transform): self.transform", "def __init__(self, transform): se...
[ "for pth in os.listdir(model_dir)] # if len(pths) <= 2: # return # os.system('rm", "import colored from .logger import get_logger def save_model(net, optim, scheduler, recorder, is_best=False): model_dir", "else epoch torch.save({ 'net': net.state_dict(), 'optim': optim.state_dict(), 'scheduler': scheduler.stat...
[ "import AppConfig #pragma: no cover class HexafuelOilAppConfig(AppConfig): #pragma: no cover name = 'hexafuel_oil_app'", "django.apps import AppConfig #pragma: no cover class HexafuelOilAppConfig(AppConfig): #pragma: no cover name =", "from django.apps import AppConfig #pragma: no cover class HexafuelOilAppConf...
[ "+= 1 elif value > minSuitability*0.1: vs_candidates += 1 total += value check.append(column+1)", "postings] postCompetencies = [lists[7:10] for lists in postings] postSecurity = [lists[10] for lists", "as f: #gives first column ie candidate a a=totalMatrix[:,[0]] #b = totalMatrix[:,[0]] #print(a)", "% tenpc_...
[ "re from setuptools import setup, find_packages ################################################################### NAME = \"pysyrenn\" PACKAGES = [", "OS Independent\", \"Programming Language :: Python\", \"Programming Language :: Python :: 2\", \"Programming", "script for PySyReNN. Adapted from: https://hynek...
[]
[ "import importlib def load(name, path): \"\"\"Load and initialize a module implemented as a", "path): \"\"\"Load and initialize a module implemented as a Python source file and", "imp import importlib def load(name, path): \"\"\"Load and initialize a module implemented as", "load(name, path): \"\"\"Load and i...
[ "width, there is nothing to # do if any(i[0] == [] for i", "dtype[key] if isinstance(key, slice): key = key.start if key is None or key", "if isinstance(key, slice): key = key.start if key is None or key ==", "dtype = s.in_ports[0].dtype out_type = s.out_ports[0].dtype slices = list( map( partial(index_to_sv_...
[ "= {} hold_thresh = 5 score_thresh = 0.001 x_axises, y_axises, mark_points, money =", ".add_xaxis(xaxis_data=x_axises) .add_yaxis( series_name=\"cur_money\", y_axis=money, is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), markline_opts=opts.MarkLineOpts( dat...
[]
[ "loss) if loss < best: best = loss best_t = epoch cnt_wait =", "None) loss = b_xent(logits, lbl) print('Loss:', loss) if loss < best: best =", "torch.nn as nn import networkx as nx import time from embed_methods.dgi.models import DGI,", "else: cnt_wait += 1 if cnt_wait == patience: print(\"epochs: \", epoch) ...
[ "if tag.name == f\"v{version}\": keep_trying = False # Tag now exists break if", "= parser.parse_args() # Make sure our cwd is the root of the repository", "parser.parse_args() # Make sure our cwd is the root of the repository os.chdir(os.path.abspath(os.path.join(THIS_FILE_DIRECTORY,", "keep_trying = True wh...
[ "loss_mz_to=1000.0) -> SpectrumType: \"\"\"Derive losses based on precursor mass. Parameters ---------- spectrum_in: Input", "---------- spectrum_in: Input spectrum. loss_mz_from: Minimum allowed m/z value for losses. Default is", "Add losses which are within given boundaries mask = numpy.where((losses_mz >= lo...
[ "name, content = item if \"type\" not in content: if \"$ref\" in content:", "{...}}) :return: The schema name \"\"\" name, content = item content = content[\"items\"]", "0, it is added to the schema name. :return: the corresponding schema name.", "and schema_dict. :param json_type: the type in jsonschema :ret...
[ "test_directory_pattern_filter(self): dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) # ## dpf =", "self.assertTrue(dpf(\"/fo...
[ "host.package('grafana').is_installed def test_service(host): \"\"\" Testing whether the service is running and enabled \"\"\"", "def test_package(host): \"\"\" check if packages are installed \"\"\" assert host.package('grafana').is_installed def test_service(host):", "testinfra.utils.ansible_runner.AnsibleRun...
[ "8) and (2.9 * 10**4 <= RayleighNbrOverallDiameter <= 2.3 * 10**5): nnInT =", "= self.cylinderDiameter + (2 * finRadius) self.ambAirTemp = ambAirTemp # degrees kelvin self.maxJunctionTemp", "class variables. NOTE: all models are based off of the finSpacing variable NOTE:", "+ (0.0154 * cdoD) - (0.0433 * cdoD*...
[]
[ "ownerWallet, idr): identity = Identity(identifier=idr) req = senderWallet.requestIdentity(identity, sender=senderWallet.defaultId) senderClient.submitReqs(req) def chk(): retrievedVerkey", "def checkAbbrVerkeySize(verkey): # A base58 encoding of 32 bytes string can be either", "def fetchFullVerkeyFromSovrin(lo...
[ "isinstance(sp.date, str) assert isinstance(sp.datetime, datetime.datetime) assert isinstance(sp.v_bary, float) assert isinstance(sp.wave_units, str) assert isinstance(sp.flux_units,", "isinstance(sp.raw_flux, np.ndarray) assert len(sp.raw_wave) == len(sp.raw_bary_wave) assert len(sp.raw_wave) == len(sp.raw_flux)...
[ "device: %s' % quote(device or '')) elif invalid_partition: raise ValueError('Invalid partition: %s' %", "directory :param devices: parent directory of the devices to be audited :param datadir:", ":param account: Account :param container: Container :param object: Object :param raw_digest: If True,", "if mount...
[ "_g_cache return _g_cache def buildCache(): vehiclesByLevel = {} vehiclesByTag = {'beast': set(),'sinai': set(),'patton':", "Embedded file name: scripts/common/dossiers2/custom/cache.py import nations from items import vehicles def getCache(): global", "scripts/common/dossiers2/custom/cache.py import nations fr...
[ "input_file + ' does not exist') sys.exit(1) input_code = open(input_file, 'r').read() if input_code[len(input_code)-1]", "''' parsed.append(p.slice) p[0] = TreeNode('assign_op', p[1], 'OPERATOR') return def p_IfStmt(p): '''IfStmt : IF", "SymbolTable() var_list = [] generated = {'temp': [], 'scope': ['scope_0']...
[ "0.2*green red = 0.1 + 0.8*red + green**3 green = 0.2 + 0.21*green", "(2560, 1440), \"1080p\": (1920, 1080), \"720p\": (1280, 720), \"480p\": (854, 480), \"360p\": (640,", "in range(max_iter): # cut_buf[i] *= 0.05**args.dt bg = (im < 0) im /=", "= [channel + random(channel.shape)*dither for channel in rgb] if...
[ "anyio.run(SubscribePacket.from_stream, stream) (topic, qos) = message.payload.topics[0] self.assertEqual(topic, 'a/b') self.assertEqual(qos, QOS_1) (topic, qos) =", "hbmqtt.mqtt.packet import PacketIdVariableHeader from hbmqtt.mqtt.constants import QOS_1, QOS_2 from hbmqtt.adapters import BufferAdapter class", ...
[ "logger.info(\"***** Running training *****\") logger.info(\" Num orig examples = %d\", len(train_examples)) logger.info(\" Num", "or n_gpu > 1: if args.local_rank != -1: raise NotImplementedError elif n_gpu >", "exists and is not empty.\") if args.gradient_accumulation_steps < 1: raise ValueError(\"Invalid gra...
[ "'max_timesteps': int(4e7), 'reward_floor': -20.7, 'reward_ceiling': 21.0, }, { 'env_id': 'QbertNoFrameskip-v4', 'trials': 2, 'max_timesteps':", "'max_timesteps': 6000000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ]) bandit_tasks = [] for n_arms", "-1000.0, 'reward_ceiling': 1000.0, }, ]) register_b...
[ "{} with open(fpath_conf_data) as f: for line in f: tokens = line.split() #", "(data was copied from website into txt file) - number of samples: we", "# Take files from all three data sets since we repartition anyway. fpaths", "#!/usr/bin/env python3 # Copyright 2020 <NAME> # # Licensed under the Apache Licen...
[ "auth_pk=request.data['auth_pk']): code = status.HTTP_201_CREATED post = Post.objects.latest(\"published\") data = PostSerializer(post).data else: code =", "'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentListView(request, post_pk, auth_pk=None): page_n...
[ "[[0.05, 0.1], [-0.9, 0.05]]]], 1, \"y\", [[[0.05, 0.1], [-0.9, 0.05]]], ('t','x','band')), ]) def", "= execute_array_element_process(index=5) assert ex.value.args[0] == \"The argument 'index' in process 'array_element' is invalid:", "xr import numpy as np sys.path.append(os.path.dirname(os.path.dirname(os.path...
[ "// or set enable_profile_use property to false. cc_defaults { name: \"skia_pgo\", pgo: {", "not s.endswith('.h')} dm_srcs = {s for s in dm_srcs if not s.endswith('.h')} nanobench_srcs", "= {s for s in srcs if not s.endswith('.h')} dm_srcs = {s for", "include directories. bp = string.Template('''// This file ...
[ "tag # value says 'type' instead of 'kind'. TAG_RAY_NODE_KIND = \"ray-node-type\" NODE_KIND_HEAD =", "multi # node type clusters. TAG_RAY_USER_NODE_TYPE = \"ray-user-node-type\" # Tag for autofilled node", "# Tag for user defined node types (e.g., m4xl_spot). This is used for", "for user defined node types (e...
[ "y)) for x in range(1, world.width - 1): borders_total_elevation += world.elevation_at((x, 0)) borders_total_elevation", "@staticmethod def _mean_elevation_at_borders(world): borders_total_elevation = 0.0 for y in range(world.height): borders_total_elevation += world.elevation_at((0,", "from worldengine.world i...
[ "net(inputs.cuda()) assert output.shape == (2, 1) # pretrained should be str or None", "assert output.shape == (2, 1) # pretrained should be str or None with", "import MaxFeature def test_max_feature(): # cpu conv2d = MaxFeature(16, 16, filter_type='conv2d') x1 =", "in_channels=3) net = build_component(cfg) n...
[ "'ssl_keyfile or other certificate-related inputs shall be defined Usage: Connection is activated not", "class Consumer: GROUP_ID = 'web_metrics_consumer' CLIENT_ID = 'website-monitoring-consumer-service' def __init__( self, *topics, **connection_kwargs", "**connection_kwargs ): \"\"\"Class for creating Kafka c...
[ "out = self.bn4(out) out = self.relu4(out) out = self.dpout(out) out = self.conv5(out) out", "= 64 # layer2 = build_resblock(filters_num[6], layer_dims[1], stride=2) # filters_num = 128 #", "self.bn2 = layers.BatchNormalization() ############################### 注意力机制 ############################### self.ca = Ch...
[ "Python 2 is even more evil, because it catches ALL exceptions. Therefore this", "without dependencies. \"\"\" import sys import contextlib import functools import re import os", "def next(self): \"\"\" Python 2 Compatibility \"\"\" return self.__next__() def __next__(self): if self.pushes:", "or some code in...
[ "1. Run Bioconductor Software package transition 2. Run Bioconductor Experiment Data package transition", "software packages Manual tasks which need to be done: 1. Copy over bare", "--> Git transition can be run in a sequential manner. It runs the", "logging.basicConfig(filename='transition.log', format='%(le...
[ "a sequence of keys derived from the function itself and the arguments passed", "async_creator) as value: return value def get_or_create_multi( self, keys, creator, expiration_time=None, should_cache_fn=None): \"\"\"Return", "or not. If it returns False, the value is still returned, but isn't", "region.get_or...
[ "Deze functie voert alle versies uit zodat deze vergeleken kunnen worden qua timing.", "= import_module(version) montecarlo.simulatie(100,50) #Deze waarden dienen enkel als test if __name__ == \"__main__\":", "-*- \"\"\" Module projectparallelprogrammeren.codesimulatie ==========================================...
[ "# the encrypted data can be generate with 'devscripts/generate_aes_testdata.py' class TestAES(unittest.TestCase): def setUp(self):", "encrypted, b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\") def test_decrypt_text(self): password = intlist_to_bytes(...
[ "https://github.com/Microsoft/Recommenders/tree/master/tests import papermill as pm import pytest import scrapbook as sb from utils_cv.common.data", "kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"keypoints\"].data) == len( nb_output.scraps[\"bboxes\"].data ...
[ "dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[10])", "for a batch size of 8 optimizer = dict(type='SGD', lr=0.0005, momentum=0.9, weight_decay=0.0001) optimizer_config", "[ '../retinanet_r50_fpn_1x_...
[]
[ "import os import pytest import pandas as pd import numpy as np from", "as pd import numpy as np from os import path from sklearn import", "from cognito.check import Check from cognito.table import Table import os import pytest import", "from cognito.table import Table import os import pytest import pandas as...