ngram
listlengths
0
67.8k
[ "raise TypeError(\"Expected Tensor, but received type of x: {}\".format( type(x))) dtype = x.dtype", "paddle.static import Variable from ..fluid.framework import _in_legacy_dygraph, in_dygraph_mode __all__ = [] def _complex_to_real_dtype(dtype):", "x (Tensor): The input tensor. Returns: bool: True if the data t...
[ "a 'date' key\"\"\" def __init__(self, key, message): self.key = key self.message = message", "def __str__(self): return str(self.message) class NonObjectReleaseError(OCDSMergeError, TypeError): \"\"\"Raised when a release is not", "class NullDateValueError(OCDSMergeError, TypeError): \"\"\"Raised when a releas...
[ "is list: self.config[element[1]] = element[0][0] elif (\"SYN\" in str(element[0])) or (\"FF\" in str(element[0])):", "in self.capaRAW[1]: self.state[self.config[code]] = 0 for code in self.capaRAW[3]: self.state[self.config[code]] = 0 print(\"waiting", "buttons.append(int(i)) for i in holder2: buttons.append(i...
[ "2000) sensor.set_auto_gain(False) # must turn this off to prevent image washout... sensor.set_auto_whitebal(False) #", "Camera. import sensor, image, time, math sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.VGA) # High Res! sensor.set_windowing((640,", "can run at the full 6...
[ "<reponame>devaslooper/Code-Overflow n=int(input(\"Enter number \")) fact=1 for i in range(1,n+1): fact=fact*i print(\"Factorial is \",fact)" ]
[ "<reponame>thiagofreitascarneiro/Curso-de-Python---Curso-em-Video import time # O * é para desempacotar o paramêtro. Permite atribuir", "para desempacotar o paramêtro. Permite atribuir inumeros parametros. def maior(* num): contador =", "in num: contador = contador + 1 print(f'{v} ', end='', flush=True) time.sl...
[ "be 3-dimensional.\"): values = torch.rand((100,), device=device) first_idxs = torch.tensor([0, 80], dtype=torch.int64, device=device) padded_to_packed(values,", "True values_packed = padded_to_packed( values, mesh_to_faces_packed_first_idx, num_faces_per_mesh.sum().item() ) values_packed_torch = TestPackedToPadd...
[ "roi1] roi_wrong_1 = (123, 345) roi_wrong_2 = [123, 456] roi_wrong_3 = [[123, 345],", "geotiff._prase_header_string(in_str) assert out_dict['tie_point'] == (368090.77975000005, 3956071.13823) def test_prase_header_string_nodata(): out_dict = geotiff._prase_header_string(\"* 42113 gdal_nodata", "[np.asarray([97....
[ "\"\"\"Gets the address_line2 of this ItemLocation. # noqa: E501 The second line of", "title=\\\"Limited Release\\\" alt=\\\"Limited Release\\\" />(Limited Release)</a> The Marketplace Insights API provides the ability", "@address_line2.setter def address_line2(self, address_line2): \"\"\"Sets the address_line2...
[ "100 data.sort(key=lambda x: x[1]/x[2], reverse=True) profit=0 ans=[] i=0 while i<n: if data[i][2]<=bag: bag-=data[i][2]", "Knapsack wt = [40,50,30,10,10,40,30] pro = [30,20,20,25,5,35,15] n = len(wt) data = [", "= 100 data.sort(key=lambda x: x[1]/x[2], reverse=True) profit=0 ans=[] i=0 while i<n: if data[i][2]...
[ "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "writing, software # distributed under the License is distributed on an \"AS IS\"", "#!/usr/bin/env python # -*- python -*- #BEGIN_LEGAL # #Copyright (c) 2019 Intel Corporation", "One can look for # those with SSE2MMX and SSSE3MMX ...
[ "details.id == target_group.id, u'Expected the `details` response to match the requested target group.'", "return type `TargetGroup`.' assert details.id == target_group.id, u'Expected the `details` response to match", "not return type `TargetGroup`.' assert edited_group.id == target_group.id, u'Expected the edi...
[ "``True``, the time index is the center of the STFT kernel. Default value", "in the shape of (batch, freq_bins, timesteps)\" # Initializing Random Phase rand_phase =", "to ``n_fft//4``. window : str The windowing function for STFT. It uses ``scipy.signal.get_window``,", "be controlled by ``fmin`` and ``fmax``...
[ "return val def test_dataloader(self): test = DataLoader(self.test, batch_size=self.batch_size, num_workers=self.num_workers, shuffle=False) return test class", "test = DataLoader(self.test, batch_size=self.batch_size, num_workers=self.num_workers, shuffle=False) return test class Base(pl.LightningModule): def __...
[ "== LAST_RESET_UPTIME and self.attribute_value is not None ): value = cast(float, self.attribute_value) if", "\"rollerEnergy\"): BlockAttributeDescription( name=\"Energy\", unit=ENERGY_KILO_WATT_HOUR, value=lambda value: round(value / 60 / 1000, 2), device_class=sensor.DEVICE_CLASS_ENERGY,", "), (\"sensor\", \"...
[ "smaller size for testing QUERY_KWARGS['GET']['facet_size']['default'] = 3 QUERY_KWARGS['GET']['facet_size']['max'] = 5 QUERY_KWARGS['POST']['q']['jsoninput'] = True", "# User Input Control # ***************************************************************************** # use a smaller size for testing", "Query ...
[ "except FileNotFoundError: logger.error(f\"ERROR: Image file '{img}' is missing\") except UnidentifiedImageError: logger.error(f\"ERROR: Image file", "part in Part.objects.exclude(image=None): try: self.rebuild_thumbnail(part) except (OperationalError, ProgrammingError): logger.error(\"ERROR: Database read error....
[ "twice def hex_to_rgb(hex: str) -> tuple: \"\"\" Args: hex (str): \"\"\" return tuple(int(hex.lstrip(\"#\")[i", "= requests.get(carbon_url) b = BytesIO(r.content) await ctx.send(file=discord.File(fp=b, filename=\"code.png\")) async def setup(bot): await bot.add_cog(Carbon(bot))", "themes, controls, languages, f...
[ "or URL import spotipy_twisted import sys import pprint if len(sys.argv) > 1: urn", "import pprint if len(sys.argv) > 1: urn = sys.argv[1] else: urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu'", "1: urn = sys.argv[1] else: urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu' sp = spotipy_twisted.Spotify() artist =", "...
[ "<filename>examples/mcp3xxx_mcp3002_single_ended_simpletest.py import busio import digitalio import board import adafruit_mcp3xxx.mcp3002 as MCP from adafruit_mcp3xxx.analog_in", "AnalogIn(mcp, MCP.P0) print(\"Raw ADC Value: \", chan.value) print(\"ADC Voltage: \" + str(chan.voltage) +", "import adafruit_mcp3xx...
[ "' 'csv.gz txt.gz tbl.bz ' 'dat.gz'), priority=1) def tabular_data(path, **kwargs): from glue.core.data_factories.astropy_table import", "astropy_tabular_data from glue.core.data_factories.pandas import pandas_read_table for fac in [astropy_tabular_data, pandas_read_table]: try: return fac(path,", "'dat.gz'), p...
[ "= 10 template_name = \"code_doc/authors/author_list.html\" context_object_name = \"authors\" model = Author def detail_author(request,", "from django.http import Http404 from django.views.generic.edit import UpdateView from django.views.generic import ListView, View", "ListView, View from django.contrib.auth.d...
[ "soc_sloc += driver_sloc #print(\"{}: {}\".format(cmp_str, driver_sloc)) if arch not in soc_sloc_by_arch: soc_sloc_by_arch[arch] =", "driver_sloc = avg_sloc_by_arch[arch] soc_sloc += driver_sloc #print(\"{}: {}\".format(cmp_str, driver_sloc)) if arch not in", "DRIVER_NAME_TO_SLOC else: print(\"Error: no SLOC fi...
[ "y = batch if self.lr_decay: self.tokens += (y >= 0).sum() # number of", "trainer.optimizers[0] _, y = batch if self.lr_decay: self.tokens += (y >= 0).sum() #", "max(0.1, 0.5 * (1.0 + math.cos(math.pi * progress))) lr = self.learning_rate * lr_mult", "self.final_tokens = final_tokens self.lr_decay = lr_decay ...
[ "if any were set results['tag'] = set(parse_list(result.group('tags'))) # Prepare our Asset Object results['asset']", "in this configuration file to our list self._cached_servers.extend( cfg_plugin.servers(asset=asset)) # We no longer", "files marked to be in STRICT mode are treated as being in ALWAYS", "{}.'...
[ "startupinfo def popen_ffmpeg(inner_args): cmd = [ 'ffmpeg', *inner_args, # logging '-loglevel', ffmpeg_loglevel, '-hide_banner',", "'win32' in str(sys.platform).lower() SUBPROCESS_ARGS = {} if IS_WIN32: startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags =", "AV_LOG_DEBUG = \"debug\" ffmpeg_loglevel = A...
[]
[ "if x_pos < min_x: continue if x_pos > max_x: break b_above_x, b_below_x =", "= min(z_min, np.min(veh_surf[\"z\"])), max(z_max, np.max(veh_surf[\"z\"])) x_min, x_max = x_min - settings[\"voxel_size\"], x_max +", "veh_surf['nodes'][:, 1] veh_surf[\"z\"] = veh_surf['nodes'][:, 2] return veh_surf def find_occupied...
[ "''' # CODE ======================================================================== import zlib import random from hashlib import sha1 from", "counter in range(len(pad)): operated=int(pad[counter])^locker[counter] holder.append(operated) return holder def encrypt(user_input,passphrase): compressed=zlib.compress(...
[ "pyfire.errors ~~~~~~~~~~~~~~~~~~~~~~ Holds the global used base errors :copyright: 2011 by the pyfire", ":license: BSD, see LICENSE for more details. \"\"\" import xml.etree.ElementTree as ET class", "via XMPP Protocol to peer \"\"\" def __init__(self, error_element, error_namespace, error_name=None): self.err...
[ "my_position[1]['x'] and my_position[0]['y'] < my_position[1]['y']: return 'up' else: return 'down' def getHealth(gamedata): pass", "'none': choice = random.choice(options) #remove opposite direction if current_direction == 'up': options.remove('down') if", "Status.getMyDirection(gamedata) #first go if current_...
[ "total < 30 or total >= 160 else: return total < 160 or", "* 40 if master_only or mates: if bullet: return total < 30 or", "= nps[-20:] # print(info) best = EngineMove(info[0][\"pv\"][0], info[0][\"score\"].pov(winner)) second = EngineMove(info[1][\"pv\"][0], info[1][\"score\"].pov(winner)) if", "limit: chess...
[ "= datetime.now() if n.hour == 6 and (n.minute-(n.minute%5)) == 15: return morning.main() time.sleep(300", "if n.hour == 6 and (n.minute-(n.minute%5)) == 15: return morning.main() time.sleep(300 - (time.mktime(datetime.now().timetuple())-a))", "a = time.mktime(datetime.now().timetuple()) n = datetime.now() if n...
[ "samcli.commands.validate.lib.exceptions import InvalidSamDocumentException from samcli.commands.local.lib.exceptions import OverridesNotWellDefinedError class TestCli(TestCase): def setUp(self): self.template =", "as context: self.call_cli() msg = str(context.exception) expected = \"bad env vars\" self.assertEqu...
[ "\"\"\"Whether it returns correct df when input is correct\"\"\" # Returns correct df", "True) self.assertEquals(Getter(table_name=IndicatorType, df_flag=True, param_list={\"name\": \"abcd\"}).get_data() .equals( Converter(obj_list=list(IndicatorType.objects.filter(**{\"name\": \"abcd\"}))).to_df() ), True) def t...
[ "governing permissions and limitations under the License. \"\"\" import json import logging import", "'SSDHead': return False if not cfg.model.bbox_head.anchor_generator.type == 'SSDAnchorGeneratorClustered': return False return True @staticmethod", "in widths: n_clust += len(w) if isinstance(w, (list, tuple)) ...
[ "set() files.update(complexity.keys()) files.update(duplicate_const_strings.keys()) result = [] for f in files: result.append({ 'filename': f,", "in which to keep track of the complixities # for each file files", "= {} # Build an array containing the number of potentially duplicated #", "array of complexities...
[ "'SyntaxError: invalid syntax' return [wanted], line_nr def test_default_except_error_postition(): # For this error the", "+', [(1, 3), (2, 3)]), ('x + 2', []), ('[\\n', [(2, 0)]), ('[\\ndef", "that are oddly enough not SyntaxErrors. wanted = 'SyntaxError: (value error) ' +", "assert False, \"The piece of cod...
[ "src, None, modifier=modifier) step += 1 elif line[0].isupper(): dst = Coords(int(line[2]), RANKNUM[line[3]]) yield", "1 elif line[0].isupper(): dst = Coords(int(line[2]), RANKNUM[line[3]]) yield Move(color[step & 1], dst, None,", "= PROMOTE else: modifier = None yield Move(color[step & 1], dst, src, None,", ...
[ "tx_hash = utils.send_transaction(func, 0, private_key) return tx_hash @main.command() @click.option( '--private-key', callback=utils.check_account, help='The privat", "oracles to work with Ether dollar\" pass @main.command() @click.option('--ether-price', type=float, help=\"The ether price", "Ether dollar\" pa...
[ "return local def with_machine_rule(cls): old_init = cls.__init__ def new_init(self, config): if \"machine\" not", "if machine_type == \"local\": self.machine = get_local_machine() self.files_to_copy = None elif machine_type ==", "ParamikoMachine(host, user=user, password=password) return rem @_once def get_rem...
[ "<reponame>legna7/Python<gh_stars>0 salario = float(input('digite o seu salario: ')) aumento = (salario + (salario", "o seu salario: ')) aumento = (salario + (salario * 15)/100 if salario", "seu salario: ')) aumento = (salario + (salario * 15)/100 if salario <=", "aumento = (salario + (salario * 15)/100 if sa...
[ "self.assertTrue(len(t) > 0) self.assertTrue('git' not in (x['id'] for x in t)) t =", "x.get('id') == '1']) == 1) def test_git(self): with app.app_context(): t = get_tree(\"git/HEAD\") self.assertTrue(t", "def test_tree(self): with app.app_context(): t = get_tree() self.assertTrue(len(t) > 0) self.assertTrue('g...
[ "login endpoint. Will return a fresh access token and # a refresh token", "not actually verify a password in this endpoint. @app.route(\"/refresh\", methods=[\"POST\"]) @jwt_refresh_token_required async def", "# As we just verified their username and password, we are # going", "login(): username = (await requ...
[ "__all__ = 'AnyDict' AnyDict = Dict[str, Any] # pragma: no mutate datetime_or_str =", "datetime from typing import Any, Dict, Union __all__ = 'AnyDict' AnyDict = Dict[str,", "Union __all__ = 'AnyDict' AnyDict = Dict[str, Any] # pragma: no mutate datetime_or_str", "import datetime from typing import Any, Dict,...
[ "from keras.models import save_model, load_model from sklearn.preprocessing import StandardScaler, MinMaxScaler, Normalizer if __name__", "keras.layers import Input, Dense from keras.models import Model from keras.models import save_model, load_model", "model.compile(optimizer=sgd ,loss='mse') model.fit(x_,y_, ...
[ "CheerLightsEffect(canvas) # Must check before and after in case it changes during the", "effect = CheerLightsEffect(canvas) # Must check before and after in case it changes", "# Mock the hardware layer to avoid errors. from ledshimdemo.canvas import Canvas from", "canvas = Canvas(self.TEST_CANVAS_SIZE) effec...
[ "np.zeros((num_images, *shape)) out_dict[k][i] = v return out_dict def generate_image(cells, shape, max_dist=5): thetas =", "out_dict = {name: np.zeros(shape) for name, dclass in zip(data_list[0].names, data_list[0].dclasses) if dclass !=", "num_images)).astype(int) nums = nums[nums > 0] assert sum(nums) < len(...
[ "self._value = settings[\"value\"] @property def id(self): return self._id @property def value(self): return self._value", "<filename>epiphancloud/models/settings.py class DeviceSettings: def __init__(self, settings): self._id = settings[\"id\"] self._title = settings[\"title\"] self._type", "= settings[\"id\"]...
[ "with one or two horns on its nose\") else: print(\"That word must not", "on its nose\") else: print(\"That word must not exist. This dictionary is very", "if word == \"a\": print(\"one; any\") elif word == \"apple\": print(\"familiar, round fleshy", "\"a\": print(\"one; any\") elif word == \"apple\": print(\...
[ "= list(map(int, input())) sum = 0 for i in range(len(num)): sum = sum", "= int(input()) num = list(map(int, input())) sum = 0 for i in range(len(num)):", "cnt = int(input()) num = list(map(int, input())) sum = 0 for i in", "int(input()) num = list(map(int, input())) sum = 0 for i in range(len(num)): sum", ...
[ "in a second keywords = ['testing', 'logging', 'example'], # arbitrary keywords classifiers =", "above version = '0.1', description = 'Kubernetes resource discovery toolkit', author = '<NAME>',", "author = '<NAME>', author_email = '<EMAIL>', url = 'https://github.com/sdnhub/kube-navi', # use the URL", "url = ...
[ "permissions and limitations # under the License. # import ast from typing import", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "if MetricTypeProto.DATASET == metric_meta_proto.metric_type: metric_type = MetricType.DATASET else: metric_type = MetricType.MODEL return MetricMet...
[ "moduels.component.NormalValue import 常量 from moduels.component.SponsorDialog import SponsorDialog import os, webbrowser class Tab_Help(QWidget): 状态栏消息", "self.tipButton.setMaximumHeight(100) def openHelpDocument(self): try: if 常量.系统平台 == 'Darwin': import shlex os.system(\"open \" +", "Signal from moduels.compo...
[ "except InvalidPasswordException as e: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail={ \"code\": ErrorCode.REGISTER_INVALID_PASSWORD, \"reason\": e.reason, },", "app.common.user import ErrorCode, run_handler from app.users.user import ( CreateUserProtocol, InvalidPasswordException, UserAlre...
[ "HSV color model, instead of the saturation plane, as we do here. Args:", "representation of the dense optical flow in RGB format Ref: https://github.com/philferriere/tfoptflow/blob/33e8a701e34c8ce061f17297d40619afbd459ade/tfoptflow/optflow.py \"\"\" hsv", "0, 255, cv2.NORM_MINMAX) else: hsv[..., 1] = flow_magn...
[ "1.66 ming = 10 ratr = 2 speed = 8 leafcount = 0", "= 2 speed = 8 leafcount = 0 total = 0 for i", "8 leafcount = 0 total = 0 for i in range(0, int(imWidth/speed)): for", "= Image.open(args.fname) RGB = im.convert('RGB') imWidth, imHeight = im.size ratg = 1.2 ratgb", "i in range(0, int(imWidth/speed)): for j...
[ "endMsecs)) parseStats(cluster['name'], capacityStats['dataPointVec'][0], 'capacity') parseStats(cluster['name'], consumedStats['dataPointVec'][0], 'consumed') parseStats(cluster['name'], dataInStats['dataPointVec'][0], 'dataIn') parseStats(cluster['name'], dataWrittenStats['dataPointVec'][0], 'dataWritten')", "=...
[ "n_neighbors = 5; # better to have this at the start of the", "# 10重 skf = StratifiedKFold(y,kfold) skfind = [None] * len(skf) cnt = 0", "= ind[0] # print ind l = serial imgs = [] for rank", "# roughly 2.5 secs # Testing y_predict = [] tic = time.time() y_predict", "= train_index cnt += 1 list_fams = n cach...
[ "\"XCLAIM\", \"key\": \"mystream\", \"group\": \"mygroup\", \"consumer\": \"Alice\", \"millisecond\": \"3600000\", \"stream_id\": \"1526569498055-0\", \"force\": \"FORCE\",", "\"XTRIM\", \"key\": \"mystream\", \"maxlen\": \"MAXLEN\", \"count\": \"2\"}, ) judge_command( \" XTRIM mystream MAXLEN", "\"XRANGE somes...
[ "= fixture.read() response_mock = self.make_mock(json_response) self.make_test(response_mock) def test_determine_names(self): \"\"\"To run this test you'll", "= determine_names('name-with-an-error') def test_find_forks(self): sent_args = { 'per_page': 99, 'start_page': 3 } url", "'https://github.com/frost-nzcr4...
[ "LOG.debug(\"gw_port_host missing from router: %s\", self.router['id']) return host def internal_network_added(self, port): super(DvrRouter, self).internal_network_added(port)", "LOG.exception(_LE('DVR: removed snat failed')) def get_gw_port_host(self): host = self.router.get('gw_port_host') if not host: LOG.debu...
[ "class PerformanceWarning(SiderWarning, RuntimeWarning): \"\"\"The category for warnings about performance worries. Operations that warn", "this base class.\"\"\" class PerformanceWarning(SiderWarning, RuntimeWarning): \"\"\"The category for warnings about performance worries.", "custom warning category classes...
[ "($search: String) { User(search: $search) { id name html_about: about(asHtml: true) about avatar", "avatar { large } bannerImage siteUrl stats { watchedTime chaptersRead } } }", "} } \"\"\" MEDIA_BY_ID = \"\"\" query ($id: Int, $type: MediaType) { Media(id:", "{ large } bannerImage siteUrl stats { watchedTim...
[ "all_names: if name.endswith(suffix): suite.addTest(unittest.makeSuite(all_names[name], \"test\")) return suite if __name__ == '__main__': runner =", "sandbox.chainop as chainop class BasicChainTest (unittest.TestCase): def testBasicChain(self): double = lambda x: x", "= lambda x: x ** 2 self.assertEqual([2**31...
[ "= \"data/local/trpo-pendulum\" np.random.seed(42) # Clean up existing logs os.system(\"rm -rf {}\".format(log_dir)) with logger.session(log_dir):", "= GaussianMLPPolicy( observation_space=env.observation_space, action_space=env.action_space, env_spec=env.spec, hidden_sizes=(64, 64), hidden_nonlinearity=chainer.f...
[ "root = self._root.find(tag) attrib = root.attrib if attrib.get('part', 'False').lower() == 'true': self._part_tag(root) return", "= str_ self._root = et.parse(xml).getroot() self.re = '' self.data = [] def select(self,", "class RegexEngine: def __init__(self, xml, str_): \"\"\"加载正则表。正则表为xml :param xml: 正则表的位置 ...
[ "monitor=\"val_acc\")], \"verbose\": False, \"validation_split\": 0.33, }, A dictionary to hold epochs, callbacks, verbose,", "default=\"categorical_crossentropy\" A loss function used when compiling the neural network. pretrained : bool,", "more typechecking self.network.compile( loss=self.loss, optimizer=self...
[ "cmap = plt.get_cmap(\"Oranges\") N = 12 width = (2 * np.pi) / N", "Default colors equally spaced on [0,1]: if z is None: z = np.linspace(0.0,", "segments = make_segments(x, y) lc = mcoll.LineCollection(segments, array=z, cmap=cmap, norm=norm, linewidth=linewidth, alpha=alpha, zorder=zorder)", "norm=norm, lin...
[ "LoginRequiredMixin, PermissionRequiredMixin): permission_required = 'accounts.view_account' raise_exception = True def post(self, request, pk, *args,", "return redirect(\"home\") else: messages.warning(request, 'There is an issue with your login processes') return", "login as auth_login from django.contrib.aut...
[ "enc_param = [int(cv2.IMWRITE_JPEG_QUALITY), 40] _, im = await loop.run_in_executor(threadpool, lambda: cv2.imencode('.jpg', im, enc_param))", "= await queue.get() im = np.frombuffer(im, dtype=np.uint8) im = await loop.run_in_executor(threadpool, lambda: cv2.imdecode(im,", "except asyncio.CancelledError: await ...
[ "typing import List from Giveme5W1H.extractor.root import path from Giveme5W1H.extractor.tools.util import bytes_2_human_readable class KeyValueCache(object):", "+ str(value)) self.persist() self._lock.release() def get(self, key): \"\"\" Read cache entries :param key:", "[value, str(time.time())] def _unpack(s...
[ "len(word)] token_tgt = [nsst.tokenization_tgt[word] if word in nsst.tokenization_tgt else 0 for word in", "= NSST.NSST() nsst.load(args.nsst_file) args.nsst = nsst # open files src_file = open(args.src_lang, 'r')", "in args.nsst_file or k[0] == -1) ), key=lambda x: x[2], reverse=True)[0] n_res =", "in token_...
[ "Define functionts def mean(data): return sum(data) / len(data) def stddev(data, size): sum =", "len(data) def stddev(data, size): sum = 0 for i in range(size): sum =", "data size = int(input()) numbers = list(map(int, input().split())) # Get standard deviation print(round(stddev(numbers,", "range(size): sum ...
[ "<reponame>jmsevillam/Herramientas-Computacionales-UniAndes def decode(word1,word2,code): if len(word1)==1: code+=word1+word2 return code else: code+=word1[0]+word2[0] return decode(word1[1:],word2[1:],code) Alice='Ti", "else: code+=word1[0]+word2[0] return decode(word1[1:],word2[1:],code) Alice='Ti rga eoe esg o...
[ ") from pychron.database.adapters.power_calibration_adapter import PowerCalibrationAdapter from pychron.paths import paths from pychron.graph.graph import Graph", "KIND, either express or implied. # See the License for the specific language", "self._get_calibration_path() self.info(\"saving calibration to {}\"....
[ "fetch the list of candidate games from the game history # we need", "to be submitted to maximin maximin_list.append(these_probs) #print(\"maximin_list:\", maximin_list) # send the list of", "if candidate_games != False: # this is the list of games that match", "for the next move recommended_move = maximin(ma...
[ "interval, times): for cnt in range(times): time.sleep(interval) print(\" -- %s: %s\" % (thread_name,", "2, 6)) except: print(\"Error: 无法启动线程\") # 主线程无限等待 while 1: pass @staticmethod def demo(args=[]):", "6)) except: print(\"Error: 无法启动线程\") # 主线程无限等待 while 1: pass @staticmethod def demo(args=[]): RawThreadDemo...
[ "= \"connection_density\" EVAL_NUM_EPOCHS = \"evaluate_every_number_of_epochs\" EVAL_NUM_EXAMPLES = \"evaluate_on_number_of_examples\" INTENT_CLASSIFICATION = \"intent_classification\" ENTITY_RECOGNITION =", "= \"maximum_negative_similarity\" USE_MAX_NEG_SIM = \"use_maximum_negative_similarity\" SCALE_LOSS = \"sc...
[ "self.adjust = adjust self.angle = None def calcAngle(self, distances): long_distance = distances[self.long_point_index] short_distance", "self.points = {0: 0, 45: 0, 90: 0, 135: 0, 180: 0, 225:", "lines[self.left_point_index] mline = lines[self.mid_point_index] rline = lines[self.right_point_index] dlong1 = di...
[ "['EscalationPolicy'], 'spaceone.monitoring.interface.grpc.v1.event_rule': ['EventRule'], 'spaceone.monitoring.interface.grpc.v1.webhook': ['Webhook'], 'spaceone.monitoring.interface.grpc.v1.maintenance_window': ['MaintenanceWindow'], 'spaceone.monitoring.interface.grpc.v1.alert': ['Alert'], 'spaceone.monitoring.in...
[ "toys = models.ManyToManyField(Toy, through='PlayedWith') class PlayedWith(models.Model): child = models.ForeignKey(Child) toy = models.ForeignKey(Toy) date", "object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey() class AwardNote(models.Model)...
[ "= np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2) dst = cv2.perspectiveTransform(pts,M) img2 = cv2.polylines(img2,[np.int32(dst)],True,255,3, cv2.LINE_AA) else: print(\"Not", "SIFT kp1, des1 = sift.detectAndCompute(img1,None) kp2, des2 = sift.detectAndCompute(img2,None) FLANN_INDEX_KDTREE = 0 ind...
[ "relevant_data) / (ideal - nadir) distance = distance.max(axis=1) distance_order = np.argsort(distance) best =", "12: \"12\", }, className=\"text-center mt-5\", ), ], className=\"mr-3 ml-3 mb-2 mt-2\", ), dbc.FormGroup(", "preference\", \"value\": \"both\", }, ], id=\"os-choice\", value=\"both\", inline=True, #...
[ "in class annotations by removing the need to write lambda functions. \"\"\" return", "JSON data. Example: >>> @sprop.a # sprop annotations are needed to tell the", "out. >>> class Baz(object): pass >>> def __init__(self, a, b, c): >>> self.a", "sprops = pd.class_sprops.get(cls,{}) # [name] cprops = pd.class_...
[ "to a resolution of {1} to create standard sized patches.\\n\".format(config[\"trainingset_patchsize\"], resolution_model), \"One of", "path_model, overlap_value, config, resolution_model, acquired_resolution = None, verbosity_level=0): ''' Segment the image located", "that resolution.\\n\".format(round(psm * m...
[ "low d assert close_enough(approx_95CI_lower, bs_95CI_lower, count_error) assert close_enough(approx_95CI_upper, bs_95CI_upper, count_error) assert close_enough(h_testing.d, (m2", "/ sig, h_testing.correction) print (\"lower: approx, bootstrap\", approx_95CI_lower, bs_95CI_lower) print (\"upper: approx, bootstrap...
[ "path from . import views urlpatterns = [ path('', views.Records, name =\"fRec\"), ]", "import path from . import views urlpatterns = [ path('', views.Records, name =\"fRec\"),", "django.urls import path from . import views urlpatterns = [ path('', views.Records, name", "from django.urls import path from . im...
[ "make_tempdir from spacy import util from thinc.api import Config TRAIN_DATA = [ (\"I'm", "@layers = \"reduce_mean.v1\" [components.transformer] factory = \"transformer\" \"\"\" # Xfail this until the", "spacy.util import make_tempdir from spacy import util from thinc.api import Config TRAIN_DATA =", "up. @py...
[ "run(self): await asyncio.sleep(1) print(\"Insert command: \") action_creator = ActionCreator() while True: input_data =", "\") action_creator = ActionCreator() while True: input_data = await input(\"~> \") if not", "config, *args, **kwargs): self.action_queue = action_queue self.config = config async def run(s...
[ "global_step, sample_rate=fs) except Exception as e: warn(str(e)) pass def save_states(global_step, writer, mel_outputs, linear_outputs,", "hparams.masked_loss_weight > 0: # decoder output domain mask decoder_target_mask = sequence_mask( target_lengths /", "torch.autograd import Variable from torch import nn fr...
[ "screen.blit(write(\"Loading index... %fs\" % (time.time() - start)), (0,0)) pygame.display.flip() with open(os.path.join(imgdir, \"index.tsv\")) as", "= pygame.font.Font(\"Futura.ttc\", font_size) return fonts[font_size] def write(text, colour = font_colour, font_size = 40):", "(255, 0, 0), rect, 2) capture = ...
[ "pydocstyle D400. ======= Resolwe ======= Open source enterprise dataflow engine in Django. \"\"\"", "<reponame>plojyon/resolwe<gh_stars>10-100 \"\"\".. Ignore pydocstyle D400. ======= Resolwe ======= Open source enterprise dataflow engine", "from resolwe.__about__ import ( # noqa: F401 __author__, __copyright_...
[ "sample dates # %% df_tmp = pd.DataFrame(df['file_name'].resample('1D').count()) df_tmp['count'] = df_tmp['file_name'] del df_tmp['file_name'] df_tmp['rac']", "x=df_tmp['count'], hue=df_tmp['rac'], orient='h') plt.draw() # %% df_melt = pd.melt(df, value_vars=['rac'], value_name='ractopamine') plt.figure(figsize=(...
[ "code. \"\"\" # return Competition return Competition def update_competition(self, competition): \"\"\" Retrieve data", "the most recent fixtures and results for the supplied competition code. \"\"\" return", "results. Returns ------- Competition A Competition object with the most recent fixtures and", "the s...
[ "Exception(\"No files found to convert\") subprocess.call(\"mkdir -p %s\" % HTML_DIR, shell=True) pool.map(create_rst, candidate_files)", "Pool(processes=4) candidate_files = [f for f in EXAMPLE_GLOB] if not candidate_files: raise Exception(\"No", "you see once you click into a grid cell on the pydeck gallery",...
[ "rotations # inertial frame: located at the origin (waist), but aligned with the", "[None] for i in range(0,3): if vector[i] == 0 or vector[i] == 1:", "= nb_bodies*[None] # waist Dg[0] = sp.Matrix([sp.Symbol('L_1_6'), sp.Symbol('L_2_6'), sp.Symbol('L_3_6')]) # right leg Dg[1]", "{}'.format(get_string_enum(joi...
[ "required=True, help=\"can be defined in days, hours, minutes (for example 5d or 12h", "minutes (for example 5d or 12h or 30m).\") parser.add_argument(\"-o\", \"--output\", help=\"Output file\") args", "misp_key, misp_verifycert import argparse import os import json # Usage for pipe masters:", "'w') as f: f.w...
[ "+ bank_account_urls + footer_item_urls)), # Extensions url(r'^menu/', include(menu_urls)), url(r'^shipping/', include(shipping_urls)), url(r'^style-guide/', core_views.styleguide, name='styleguide'),", "as product_urls from .search.urls import urlpatterns as search_urls from .shipping.urls import urlpatterns as"...
[ "FRN args = trainer.train_parser() with open('../../../../config.yml', 'r') as f: temp = yaml.safe_load(f) data_path", "trainer, frn_train from datasets import dataloaders from models.FRN import FRN args = trainer.train_parser()", "os.path.abspath(temp['data_path']) fewshot_path = os.path.join(data_path,'CUB_fe...