ngram
listlengths
0
67.8k
[ "DO THIS c = cnx.cursor() c.execute(\"SELECT * FROM {name} WHERE aa=%s\".format( name=db_parameters['name']) %", "\"(aa INT, bb STRING)\".format( name=db_parameters['name'])) cnx.cursor().execute( \"INSERT INTO {name} VALUES(%s, %s)\".format( name=db_parameters['name']), (1,", "TABLE {name} \" \"(aa INT, bb STR...
[ "is likely to appear in this context.''' raise NotImplementedError() def entropy(self, text): '''Evaluate", "def probability(self, word, context): '''Evaluate the probability of this word in this context.'''", "# URL: <http://nltk.sf.net> # For license information, see LICENSE.TXT class ModelI(object): \"\"\" A...
[ "String, create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base POSTGRES_CONNECTION_STRING =", "Integer, String, create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base POST...
[ "# light field at the ccd plane T1 = np.array([[1, 0, -dCCD *", "3, 0], [0, 1, 0, -dCCD * 2 / 3], [0, 0, 1,", "use internal data still in development\") else: if not isinstance(data_files, str): raise ValueError(\"{}", "to use internal data still in development\") else: if not isinstance(destination_folder, s...
[ "import Vector3 # def quaternion_to_euler(quaternion): # \"\"\"Convert Quaternion to Euler Angles # quaternion:", "KIND, either express or implied. # See the License for the specific language", "p in traj.points: # v_list.append(quaternion_to_euler(p.pose.orientation).z) # return v_list[0: len(s_arr)] # def plo...
[ "'name': 'email'})) class Meta: model = User fields = (\"email\", \"full_name\", \"username\", \"<PASSWORD>\",", "= forms.CharField(label=\"Username\", max_length=16, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'})) password = forms.CharField(label=\"Password\", max_length=16, widget=f...
[ "that some people actually pay for # I once had a short freelance", "better way to put it is that covariance is the measure of the", "end=datetime.datetime(2014, 1, 1)) JPM = pd.io.data.get_data_yahoo('JPM', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) SBUX", "print( corComp.head()...
[ "test(): while 1: img1=cv2.imread('captured car1.jpg') print(\"{}\".format(img1.shape)) print(\"{}\".format(img1)) cv2.imshow('asd',img1) cv2.waitKey(1) t1 = threading.Thread(target=test) t1.start()", "import cv2 import numpy as np import threading def test(): while 1: img1=cv2.imread('captured", "numpy as np i...
[ "Unless required by applicable law or agreed to in writing, software # distributed", "metric_def in metric_defs: if metric_def: metrics = self._filter_metrics(element_metrics, metric_def) metric_values.append(self._sum_metric_values(metrics)) else: # In", "host) def get_host_cpu_info(self): if not self._host_cp...
[ "type=click.Path(exists=True), help=\"Path to puzzle data.\") def cli(day: int, puzzle: int, input: str): filename", "metavar=\"<1..31>\", help=\"Day you want to select.\") @click.option('-p', '--puzzle', required=True, type=click.IntRange(1, 2), metavar=\"<1|2>\", help=\"Puzzle", "{puzzle} for day {day} not im...
[ "[ 9.68525639e-01, 5.69699633e-01, 2.61721488e-01], [ 9.70204593e-01, 5.75028270e-01, 2.58325424e-01], [ 9.71835007e-01, 5.80382015e-01, 2.54931256e-01], [", "[ 1.71573925e-01, 1.97063415e-02, 5.80805890e-01], [ 1.78950212e-01, 1.92522243e-02, 5.84054243e-01], [ 1.86212958e-01, 1.88029767e-02, 5.87227661e-01], ["...
[ "d * np.sin(theta_hat_L) y_hat_end_R = y_hat_start + d * np.sin(theta_hat_R) plt.plot([x_start, x_end], [y_start,", "+ d * np.cos(theta_hat_L) x_hat_end_R = x_hat_start + d * np.cos(theta_hat_R) y_hat_start =", "PI / 2 theta_BR = theta_B - PI / 2 x_BL = xB", "= 2 x_start = x y_start = y x_end = x + L", "Fro...
[ "nullable=False, comment=\"评论用户的 ID\") post_id = Column(Integer, nullable=False, comment=\"Post 文章的 ID\") content = Column(Text,", "post_id = Column(Integer, nullable=False, comment=\"Post 文章的 ID\") content = Column(Text, nullable=False, comment=\"用户的评论\") create_time", ") user_id = Column(Integer, nullable=Fal...
[ "if platform_version is None: platform_version = 'LATEST' return self.boto.run_task( cluster=cluster, taskDefinition=task_definition, count=count, startedBy=started_by,", "msg = 'At least one subnet (--subnet) and one security ' \\ 'group", "DiffAction(EcsAction): def __init__(self, client): super(DiffAction, s...
[ "v): return not set(self.g.neighbors(u)).intersection(set(self.g.neighbors(v))) def count_local_bridges(self): monochromatic, bichromatic = 0, 0 for (u,", "actual counts\"\"\" def __init__(self, n, p, q, seed=0): self.n = n self.p =", "self.q = q self.g = nx.generators.community.stochastic_block_model( [int(sel...
[ "_op_mixin.Op(_op_mixin.OP_IDENTITY, children) else: host.op = _op_mixin.Op(_op_mixin.OP_ADD, children) # HACK: This duplicates BloomNode._expand, essentially.", "_normalize_state( exit_node: 'bloom_node.BloomNode', index: Union[Iterable, anagram_iter.AnagramIter]) -> _AnagramState: if isinstance(index, _AnagramS...
[ "expand=None): if not expand: params = None elif expand == True: params =", "user_id=None): if user_id is None: user_id = self.token.user_id return self.get_json(urls.galaxy(\"user\", user_id)) def galaxy_friends(self,", "self.get_json( urls.galaxy(\"product\", game_id), params=params, authorized=False) def gal...
[ "['biopython', 'numpy', 'pandas'] setup(name='stacksPairwise', version='0.0.0', description='Calculate pairwise divergence (pairwise pi) from Stacks `samples.fa`", "# The directory containing this file HERE = pathlib.Path(__file__).parent # The text of", "pathlib.Path(__file__).parent # The text of the README f...
[ "import sys args = sys.argv[1:] os.system('python -O -m spanningtree.csv_experiment_statistics ' + ' '.join(args))", "/usr/bin/env python import os import sys args = sys.argv[1:] os.system('python -O -m spanningtree.csv_experiment_statistics", "os import sys args = sys.argv[1:] os.system('python -O -m spanningt...
[ "import ( ObjectNavThorPPOExperimentConfig, ) class ObjectNavThorDaggerThenPPOExperimentConfig(ObjectNavThorPPOExperimentConfig): \"\"\"A simple object navigation experiment in THOR.", "lr = 2.5e-4 num_mini_batch = 2 if not torch.cuda.is_available() else 6 update_repeats =", "use_gae=use_gae, gae_lambda=gae_lam...
[ "PSSM cluster ID. target_file : pandas DataFrame PSSM profile. Returns ------- Name :", "of core peptide chain. Returns ------- shuffled_scores : list List of scores for", "matrix, substrate_shuffling_matrix, module_shuffling_matrix, cpu, iterat): \"\"\" Calculating scores. Parameters ---------- variant_seq : l...
[ "-> Optional[Token]: value = get_value(expr=expr.value) if value is UNKNOWN: return None return Token(value=value,", "@get_returns.register(*TOKENS.YIELD) def handle_yield(expr) -> Optional[Token]: value = get_value(expr=expr.value) if value is UNKNOWN: return", "-> bool: for expr in traverse(body=body): if isi...
[ "16], 16: [11, 12, 15, 17], 17: [11, 12, 16, 18], 18: [13,", "\\ { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 4],", "2, 14] } # 22 edges ibm20AustinTokyo_c_to_tars = \\ { 0: [1, 5],", "17], 13: [7, 8, 12, 14, 18, 19], 14: [9, 13, 18, 19],", "=\\ { 0: [1, 2], 1: [2], 2: [], 3: [2, 4], 4:", "6, 7], 2: [1, 3, 6, 7],...
[ "quantity = sum([b['quantity'] for b in self.asks if b['price'] == self.ask_price]) filled =", "leftavg = avg(left) rightavg = avg(right) if rightavg > leftavg: return 1 elif", "= sum(bestBids.values()) compositBidQ = min(bestBidsQ.values()) compositAsk = sum(bestAsks.values()) compositAskQ = min(bestAsksQ.valu...
[ "hdl-diagram:: ../../../examples/basic/_output_bus.v :type: netlistsvg :align: center :module: top \"\"\" from os import path", "center :module: top **Output1** ``wire0`` feedthough from ``inst_2_1`` .. hdl-diagram:: ../../../examples/basic/_output_wire.v :type: netlistsvg", "cable0 = next(top.get_cables(\"wire...
[ "on canvas. Defaults to None. Raises: workflow_exceptions.ToolNotAvailable: indicates that provided string does not", "\"\"\" tool = self._get_tool_by_id(tool_id) tool.config = data return tool def set_tool_coordinates( self, tool_id:", "passed tool ID(s) exist in the current workflow and returns the list of", ...
[ "= ( \"Welcome to fundraising for the Triple Crown for Heart!\" ) #", "through # used in paypal.py:process_paypal() confirmation_email_closing = ( '.\\n\\nFor all donations over $20,", "to your friends telling them ' 'about your ride.' '\\nDon\\'t forget to include", "fundraiser for a previous campaign, pleas...
[ "def test_live_page_update_signal_receivers(): assert len(live_page_update.receivers) == 0 @override_settings( WAGTAIL_LIVE_PUBLISHER=\"tests.testapp.publishers.DummyWebsocketPublisher\" ) def test_live_page_update_signal_receivers_websocket(): app_config =", "WAGTAIL_LIVE_PUBLISHER=\"tests.testapp.publishers.Dum...
[ "= QGraphicsItem.ItemPositionChange DEVICECACHE = QGraphicsItem.DeviceCoordinateCache SELECTABLE = QGraphicsItem.ItemIsSelectable MOVEABLE = QGraphicsItem.ItemIsMovable FOCUSABLE =", "grass = QColor(111, 178, 68, 255) forest = QColor(69, 149, 62, 255) peacock", "QColor(55, 52, 144, 255) deep_blue = QColor(15, 8...
[ "# driver.find_element_by_xpath(\"//button[@onclick='fnSearch();']\").click() driver.find_elements_by_xpath(\"//*[contains(text(), '5기_B반_Java(1)')]\")[0].click() driver.find_element_by_xpath(\"//span[@class='file-name']\").click() driver.switch_to.window(driver.window_handles[1]) print(driver.find_elements_by_xpat...
[ "+ dataThree return data # dataStr 为爬虫数据字符串 dataStr = outputData() # 1. 将", "= StringIO() f.write('Python-100') str = f.getvalue() # 读取写入的内容 print('写入内存中的字符串为:%s' %str) f.write('\\n') # 追加内容", "'我是 1 号爬虫数据\\n' dataTwo = '我是 2 号爬虫数据\\n' dataThree = '我是 3 号爬虫数据'", "in dataIO.readlines(): print(data.strip('\\n')...
[ "[\"balsheet\", \"--filepath=temp/data2.csv\"] args = docopt(cli.__doc__, argv=argv) self.assertTrue(args[\"balsheet\"]) self.assertEqual(args[\"--filepath\"], \"temp/data2.csv\") def test_balsheet_with_levels_default(self): argv =", "self.assertEqual(args[\"--levels\"], \"2\") def test_balsheet_with_date_default...
[ "class Ejderha(Yaratik): def Ates_puskurtme(self): print('ates puskurtum!') class Zombie(Yaratik): def Isirmak(self): print('Isirdim simdi!') enemy", "ejderha.move_left() ejderha.Ates_puskurtme() # Zombie is called the (child class), inherits from Yaratik (parent", "print('ates puskurtum!') class Zombie(Yaratik...
[ "\"\"\" import numpy as np import pandas as pd from sklearn.neighbors import NearestNeighbors", "= d A[i, i0] = d # by symmetry return A def sparse_affinity_graph(X):", "= dist # by symmetry return A def laplacian_graph(X, mode='affinity', knn=3, eta=0.01, sigma=2.5):", "algorithm='ball_tree').fit(X) distance...
[ "classes will fail isinstance checks # even though they are \"the same\"). _COMMANDS", "modname, mod in zip(self.__all__, _COMMANDS): setattr(self, modname, mod) _patch_our_attrs() def _check_recipes_cfg_consistency(recipe_deps): \"\"\"Checks all", "subcommands shouldn't use; everything from this point on # sho...
[ "an numpy array to be sorted out for top-k components. k: k most", "positive mean value, negative mean value and zero value. Args: data: an flattened", "data is sparse and flattened mean_topk = np.mean(np.abs(data)) out_ = np.where(data > 0.0,", "create table for idx, u_value in enumerate(unique_value_array):...
[ "self._port = RasterPort(\"test\", uses=[\"invar\"]) super().__init__() c = Component() assert c.get_x(\"invar\") == approx(np.array([3.0, 5.0,", "return (3.0,) class Component(GridMixIn): def __init__(self): self._port = RasterPort(\"test\", uses=[\"invar\"]) super().__init__() c =", "__init__(self): self._por...
[ "= load_log_sp(mylog) correctlog_sp = load_log_sp(correctlog) for (i, ((nb1, sp1), (nb2, sp2))) in enumerate(zip(mylog_sp,", "spidx = line.find(\"SP:\") endidx = line.find(' ', spidx) data.append((line[0:4], line[spidx+3:endidx])) return data if", "= sys.argv[2] mylog_sp = load_log_sp(mylog) correctlog_sp = loa...
[ "each hidden layer.') parser.add_argument('--epochs', default=50, type=int, help='Number of epochs to train.') parser.add_argument('--dropout', nargs='+',", "mlflow.log_param('one_hot_columns', one_hot_columns) mlflow.log_param('numeric_columns', numeric_columns) # Not using these yet mlflow.log_param('epochs', e...
[ "= skeleton warn( \"Skeleton representations contained some unknown treenode->connector relation IDs:\\n\\t\" \"\\n\\t\".join(sorted(warnings)) )", "within the first skeleton set will be used in the model. Parameters ----------", "Parameters ---------- skeleton_ids : array-like Skeletons whose NeuroML to return...
[ "ExternalWriter def register_external_writer(external_writer: ExternalWriter) -> None: create = find_external_writer_create(external_writer.type) if create is None:", "from watchmen_meta.common import ask_meta_storage, ask_snowflake_generator from watchmen_meta.system import ExternalWriterService as ExternalWrite...
[ "a nota da seugundo nota ')) peso2 = float(input('Digite o peso da segundo", "o peso da segundo nota ')) media = (nota1/peso1+nota2/peso2)/2 print('A média das duas", "<reponame>AlbertoAlfredo/exercicios-cursos nota1 = float(input('Digite a nota da primeira nota ')) peso1 = float(input('Digite", "segundo nota...
[ "Class/attribute at the given import path. Raises ------ ImportError If the path does", "getattr(module, class_name) except AttributeError as error: raise ImportError( f\"Module '{module_path}' does not define", "name and returns the class/attribute. Parameters ---------- path: str Dotted module path to", "ra...
[ "\"prefs\", \"prev\", \"param\", \"premul\", \"quad\", \"quads\", \"quat\", \"quats\", \"recalc\", \"recalcs\", \"refl\", \"sce\", \"sel\",", "\"pierson\", # Pierson-Moskowitz \"preetham\", \"prewitt\", \"ramer\", # Ramer-Douglas-Peucker \"runge\", \"sobol\", \"verlet\", \"wilkie\", \"worley\",", "\"viewport\",...
[ "= prediction.detach() * scale target = (target) * scale return F.mse_loss(prediction, target) class", "n=target.size(0) ) if verbose and e % 100 == 0: print(\"Epoch {}, {},", "self.mean = np.mean(ytrain) self.std = np.std(ytrain) if self.encoding_type is not None: _xtrain =", "def accuracy_mse(prediction, ta...
[ "realpath from os import uname import glob import sh class LibX264Recipe(Recipe): version =", "arch): with current_directory(self.get_build_dir(arch.arch)): env = self.get_recipe_env(arch) configure = sh.Command('./configure') shprint(configure, '--cross-prefix=arm-linux-androideabi-', '--host=arm-linux', '--disa...
[ "_winreg import * else: import winreg from winreg import * def get(skey,name,root=HKEY_CURRENT_USER,returnType=True): '''", "r = OpenKey(root,skey,0,KEY_SET_VALUE) if not py.isint(type): if py.isint(value):type=4 if py.istr(value):type=1 if py.isbyte(value):type=3 #TODO", "''' from qgb.Win import reg reg.get(r'...
[ "key, password) self.assertIsInstance(pkey, cls) pkey = IndexHandler.get_specific_pkey(cls, 'x'+key, None) self.assertIsNone(pkey) with self.assertRaises(paramiko.PasswordRequiredException): pkey", "def test_get_pkey_obj_with_plain_key(self): fname = 'test_ed25519.key' cls = paramiko.Ed25519Key key = read_file(ma...
[ "= self.setup_view(self.view, request) self.assertEqual(view.get_statuses(), []) @override_settings(NOTIFICATIONS_ACTIONS={'2': 'bar'}) def test_get_status_invalid_config(self): request = RequestFactory().get('{}?statuses=1'.format(self.url_path)) view", "self.get_view_with_get_querystring('is_pending').queryset_...
[ "ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse", "elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut", "adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "culpa qui officia deserunt mollit anim id est laborum....
[ "from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^image/$', views.add_image, name='upload_image'),", "views.profile_update, name='update'), url(r'^comment/(?P<image_id>\\d+)', views.comment, name='comment'), url(r'^search/', views.search_results, name = 'search_results'), url(r'^f...
[ "enrichment def get_enrichment_percent(enrichment: str) -> int: if enrichment == 'Cream Cheese': return 10", "returns multiplied spoon units from teaspoon fraction input, 3 tsp = 1 tbsp", "'Oolong') # default possible teaspoon values list for flour = 500, 3 tsp", "== extract2: return False e1 = extract1.split...
[ "response.json() self.assertEqual(response_data[\"domain\"], \"the.posthog.com\") self.assertEqual(response_data[\"verified_at\"], None) self.assertEqual(response_data[\"jit_provisioning_enabled\"], False) self.assertRegex(response_data[\"verification_challenge\"], r\"[0-9A-Za-z_-]{32}\") instance = OrganizationDom...
[ "import matplotlib.pyplot as plt from os import listdir from tensorflow.keras.callbacks import ModelCheckpoint dataDir", "# print(\"inputs shape = \", inputs.shape) print(np.shape(targets[:, 1, :, :].flatten())) maxvel = np.amax(np.sqrt(targets[:,", "\"./data/trainSmallFA/\" files = listdir(dataDir) files.sort(...
[ "reply_to_question(brain_response_question) self._log.info(\"REPLY to question: {}\".format(reply)) else: brain_response_statement = app.brain.update(utterance, reason_types=True) # Searches for", "and Response # Make sure to not execute the response here, but just", "return the response function return 1.0, la...
[ "== \"blog\": return redirect(url_for('content.blog', slug=posturl)) return redirect(url_for('home.content', slug=url_name)) # Duplicate entry except Exception", "slug=posturl)) return redirect(url_for('home.content', slug=posturl)) else: if form.validate_on_submit(): url_name = slugify(form.title.data) content =...
[ "None: \"\"\"Test we handle invalid auth.\"\"\" result = await hass.config_entries.flow.async_init( DOMAIN, context={\"source\": config_entries.SOURCE_USER}", "context={\"source\": config_entries.SOURCE_USER} ) assert result[\"type\"] == RESULT_TYPE_FORM assert result[\"errors\"] is None with patch(\"airthings.ge...
[ "mask = GT < args.maxdisp mask.detach_() # loss = F.smooth_l1_loss(pred[mask], GT[mask], size_average=True) loss", "numpy as np def GERF_loss(GT, pred, args): # mask = (GT < args.maxdisp)", "cv2 as cv import numpy as np def GERF_loss(GT, pred, args): # mask", "if count == 0: count = 1 return torch.sum(torch.s...
[ "np_array = face_recognition.load_image_file(image) # Find face locations locations = face_recognition.face_locations(np_array) # Create face", "image data np_array = face_recognition.load_image_file(image) # Find face locations locations = face_recognition.face_locations(np_array) #", "right - left, 'height': ...
[ "setuptools import setup setup(name='rblod', version='2021.1', description='Pymor support for RBLOD', author='<NAME>', author_email='<EMAIL>', license='MIT', packages=['rblod'])", "Licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) # Authors: # <NAME> # <NAME> #", "Efficient Two-Scal...
[ "Fix T_ncdm or m_ncdm \"m_nu\" : 0.02 } # EUCLID values z_table =", "if type(fcst.fisher)==type(None): fcst.gen_pm() fcst.gen_fisher( fisher_order=[ 'omega_b', 'omega_cdm', 'n_s', 'A_s', 'tau_reio', 'h', 'N_ncdm', 'M_ncdm',", "# Fix T_ncdm or m_ncdm \"m_nu\" : 0.02 } # EUCLID values z_table", "'omega_b', 'ome...
[ "\"128\", \"256\", \"512\", \"1024\", \"2048\"] for dim in dims: os.system( f\"perf stat -e", "if __name__ == \"__main__\": dims = [\"32\", \"64\", \"128\", \"256\", \"512\", \"1024\", \"2048\"]", "\"512\", \"1024\", \"2048\"] for dim in dims: os.system( f\"perf stat -e r11 -x,", "== \"__main__\": dims = [\"3...
[ "the query language in some default cases. :return: The display_name of this QueryResultRowTypeSummary.", ":type unit: str :param display_name: The value to assign to the display_name property", "__repr__(self): return formatted_flat_dict(self) def __eq__(self, other): if other is None: return False return", ...
[ "import re import time import random import argparse import torch from transformers import", "truncation=True, padding=True, max_length=max_length, return_tensors='pt', ).input_ids input_ids_len = input_ids.shape[1] assert input_ids_len < max_length with", "0 terminals_pos = [pos for pos in [find_re(completion,...
[ "self.assertEqual(Rover(0, 0, 'E'), final_pos) def test_rover_runner_goes_off_gird_east(self): grid = small_mars_with_one_rover_empty_commands.grid rover = Rover(1, 1,", "Rover(1, 1, \"N\") tss = m.get_mocked_turn_command_selector_turn_right_from_north_command_only() mss = m.get_mocked_move_command_selector_north...
[ "num_workers=4,shuffle=True): normalize = tfs.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) transforms = tfs.Compose([ tfs.RandomResizedCrop(crop_size),", "self.optimize_times = [0] optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), weight_decay=self.weight_decay...
[ "a와 합쳐 ‘아인'으로 적는다. \"\"\" self.assert_examples({ # u'Nha Trang': u'냐짱', # u'<NAME>': u'호찌민',", "뒤따르는 모음과 합쳐서 한 음절로 적는다. \"\"\" self.assert_examples({ 'yên': '옌', 'Nguyên': '응우옌', })", "u'핫꽌호', 'Quôc': '꾸옥', 'Quyên': '꾸옌', }) def test_3rd(self): \"\"\"제3항 y는 뒤따르는 모음과 합쳐서", "test_3rd(self): \"\"\"제3항 y는 뒤따르는 모음...
[ "self.tan = Tan() def test_call(self): self.assertEqual(self.tan(0), 0) def test_eq(self): self.assertEqual(self.tan, Tan()) def test_get_derivative(self):", "1) class CosTester(unittest.TestCase): def setUp(self): self.cos = Cos() def test_call(self): self.assertEqual(self.cos(0), 1) def", "def test_get_deriva...
[ "< letters[0] or target >= letters[-1]: return letters[0] left, right = 0, len(letters)", "while left < right: mid = left + (right - left) // 2", "letters = [\"c\", \"f\", \"j\"] target = \"a\" print(f\"Input: letters = {letters}, target", "[\"c\", \"f\", \"j\"] target = \"a\" print(f\"Input: letters = {lette...
[ "T_State from nonebot.adapters import Bot, Event from nonebot.log import logger from .config import", "anti_cpdaily_check_routine cpdaily = on_command('cpdaily') scheduler = nonebot.require(\"nonebot_plugin_apscheduler\").scheduler async def one_shot_routine(): scheduler.remove_job('anti_cpdaily_oneshot') await a...
[ "functions, methods, classes and modules is shown # in this example: import matplotlib", "np import matplotlib.pyplot as plt import matplotlib.ticker as ticker # Fixing random state", "plt.show() ############################################################################# # # ------------ # # References # \"\"...
[ "= units[index] while size_by_bytes > 1000: index = index + 1 unit =", "ValueError): # pass return False # def url_check(url: str): # url = url.lower()", "is not None: if type(val) is str: result[key] = parse.unquote(val) else: result[key] =", "wrong url %s !' % url) # return url # if len(data) ==", "+ '?' ...
[ "as np from something import Top i = 0 while i < 10:", "something import Top i = 0 while i < 10: a = np.ndarray((10,4))", "i = 0 while i < 10: a = np.ndarray((10,4)) b = np.ones((10,", "Top i = 0 while i < 10: a = np.ndarray((10,4)) b =", "0 while i < 10: a = np.ndarray((10,4)) b = np.ones((10, Top)) i", ...
[ "type. \"\"\" mapper = FloatMapper({\"field\": 1}) mapper.is_valid() assert mapper.data[\"field\"] == 1.0 mapper =", "test we check success convert to float type. \"\"\" mapper = FloatMapper({\"field\": 1})", "mapper = FloatMapper({\"field\": 0}) mapper.is_valid() assert mapper.data[\"field\"] == 0.0 def test_w...
[ "# build list of name files to try and load usgpth = os.path.join(\"..\",", "in files: if name.endswith(\".nam\"): usg_files.append(os.path.join(path, name)) # def test_load_usg(): for fusg in usg_files:", "write it back out def load_model(namfile, model_ws): m = flopy.modflow.Modflow.load( namfile, model_ws=mo...
[ "str: if os.path.isdir(string): return string raise ArgumentTypeError( 'Directory does not exist: \"{}\"'.format(os.path.abspath(string))) class", "self.add_argument(*args, **kwargs, type=DirType) def arg_file(self, *args: Any, mode: str = 'r', **kwargs: Any)", "self.add_argument(*args, **kwargs, action='store_...
[ "Target # Blame X.509... class SequenceOfTargets(core.SequenceOf): _child_spec = Targets class AttrSpec(core.SequenceOf): _child_spec =", "agree with what we export ext_map = x509.ExtensionId._map ext_specs = x509.Extension._oid_specs ext_map['172.16.17.325'] =", "x509.GeneralName, {'explicit': 1}), ('target_ce...
[ "import random def test_delete_some_group(app): if len(app.group.get_group_list()) <= 1: app.group.add_new_group(Group(name='test')) old_list = app.group.get_group_list() index", "new_list = app.group.get_group_list() assert len(old_list) - 1 == len(new_list) del old_list[index] assert old_list", "model.group i...
[ "'{}data/weightAP-{}.pkl'.format(baseDir,featType) print 'Results saved in ',savename with open(savename,'r') as f: ap = pickle.load(f)", "np.mean(ap) savename = '{}data/weightAP-{}.pkl'.format(baseDir,featType) print 'Results saved in ',savename with open(savename,'w') as f:", "',savename with open(savename,'w...
[ "<filename>python/csv/csv_dict_writer.py import csv def csv_dict_writer(path, headers, data): with open(path, 'w', newline='') as csvfile:", "records.pop(0) list_of_dicts = [] for row in records: my_dict = dict(zip(headers, row)) list_of_dicts.append(my_dict)", "Python Interviews,<NAME>,Packt Publishing,2018,97...
[ "got 'int'\\)\" with pytest.raises(Exception, match=expected_err_msg): verify_products(maker, maker.acquire()) def test_supports_config(): expected_err_msg = ( \"An", "error occurred while processing the parameter 'conflicting_types':\\n\" + \"The specified type 'int' conflicts", "+ \" - 'b' of type 'str'\" ) w...
[ "= self.embedding(samples) x = x.unsqueeze(1) x = [self.relu(conv(x)).squeeze(3) for conv in self.convolutions] x", "(K, self.embedding_dim)) for K in self.filter_sizes]) self.dropout = nn.Dropout(0.3) def get_output_length(self): return len(self.filter_sizes)", "= nn.ModuleList( [nn.Conv2d(1, self.conv_out_cha...
[ "element does not include voice or staff elements. Duration values should always be", "elements are required to coordinate multiple voices in one part, including music on", "Duration from musicscore.musicxml.types.complextypes.complextype import ComplexType class ComplexTypeBackup(ComplexType): \"\"\" The backu...
[ "= collections.defaultdict(list) for idx, label in enumerate(km_model.labels_): clustering[label].append(idx) print(clustering) kmini_model = kmini.fit(X_train) print(\"For", "in tokens] # return only tokens with size over 1 if len(tokens) >", "preprocessed_text = \" \".join(tokens) return preprocessed_text ret...
[ "action_error_sum[action_name]['p2'].update(np.mean(dist) * num, num) else: for i in range(num): end_index = action[i].find(' ')", "- min_value)) + min_value def mpjpe_cal(predicted, target): assert predicted.shape == target.shape return torch.mean(torch.norm(predicted", "data_threshold, model, model_name): # i...
[ "self.s2t.recognize(audio_input, model=self.k_st2_model) result = loads(str(result)) result = result[\"result\"][\"results\"][0][\"alternatives\"][0]['transcript'] except Exception: return False, \"I", "url=self.k_t2s_url) def read(self, string: str): return self.t2s.synthesize( string, voice=self.k_t2s_voice, ac...
[ "_is_reboot = arg + \"-r\" else: _is_reboot = arg + \"-h\" time_to_shutdown =", "import run def perform_shutdown(body): arg = \"\" if body[\"reboot\"]: _is_reboot = arg +", "_is_reboot = arg + \"-h\" time_to_shutdown = str(body['timeToShutdown']) result = run([\"/sbin/shutdown\", _is_reboot, time_to_shutdown])"...
[ "# Generated by Django 2.1.7 on 2019-02-23 23:45 from django.db import migrations class", "import migrations class Migration(migrations.Migration): dependencies = [ ('torrents', '0010_auto_20190223_0326'), ] operations = [", "2.1.7 on 2019-02-23 23:45 from django.db import migrations class Migration(migrations....
[ "tg, phrases as phr, finance as fin, utils, glossary, bots, gcp, sed, db)", "as kb, telegram as tg, phrases as phr, finance as fin, utils, glossary,", "from . import (emoji as emj, keyboards as kb, telegram as tg, phrases", "as emj, keyboards as kb, telegram as tg, phrases as phr, finance as", "keyboards as...
[ "import Category class PossibleAnswerSerializer(serializers.ModelSerializer): class Meta: model = PossibleAnswer fields = ( 'id',", "= serializers.StringRelatedField(many=True) class Meta: model = Question fields = ( 'id', 'question', 'category',", ":mod:`question.serializers` -- serializers \"\"\" from rest_fr...
[ "# Created: Sat May 16 17:05:43 2015 # by: PyQt5 UI code generator", "QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate(\"Dialog\", \"Dialog\")) self.lb_image.setText(_translate(\"Dialog\", \"Image Label\")) self.btn_save.setText(_translate(\"Dialog\", \"Save it\")) from widgets.ImageLabel import...
[ "functions\"\"\" return self.__system_management_key @lazy_property def user(self): \"\"\"`dict` - The user associated with this", "user_id: Display all keys belonging to `user_id` :type user_id: int. :returns: `list` -", "Identifies if the key can be used for DCM system management functions\"\"\" return", "s...
[ "5} my_dict = {'name': 'Jose', 'age': 90} another_dict = {1: 15, 2: 75,", "my_dict = {'name': 'Jose', 'age': 90} another_dict = {1: 15, 2: 75, 3:", "3: 150} lottery_players = [ { 'name': 'Rolf', 'numbers': (13, 45, 66, 23,", "'numbers': (14, 56, 80, 23, 22) } ] universities = [ { 'name':", "'age': 90} anoth...
[ "-> psdaq/control_gui/ \"\"\" import logging logger = logging.getLogger(__name__) from PyQt5.QtWidgets import QTableView, QVBoxLayout,", "QStandardItem(\"itemA %d %d\"%(row,col)) item.setIcon(icon.icon_table) item.setCheckable(True) self._si_model.setItem(row,col,item) if col==2: item.setIcon(icon.icon_folder_clo...
[ "embeddable]\" elif self.embed: flags = \" [embeddable]\" elif self.parse: flags = \" [displayable]\"", "name, load_as=None): load_as = load_as or name if hasattr(mod, name): v = getattr(mod,", "= \"%s_%s\" % (major, minor) else: modname = major mod = self.find_module(modname) ext", "= None if not mod and mod...
[ "'https://adminrest.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'adminrest' @classmethod def new_instance(cls, service_name: str = DEFAULT_SERVICE_NAME, ) ->", "None: _dict['includes'] = self.includes return _dict def _to_dict(self): \"\"\"Return a json dictionary representing", "if 'headers' in kwargs: headers.updat...
[ "output == ''' Assessment Value: 59999.969999999994 Property Tax: 383.999808 ''' def test_bmi(): assert", "@should_print def test_sales_tax_5_95(output): functions.sales_tax(5.95) assert output == \"\"\" Purchase Amount: 5.95 State Sales", "test_bmi(): assert functions.bmi(160, 67) == approx(25.05680552) assert...
[]
[ "# coding=utf-8 from __future__ import unicode_literals from .base import BasePlugin class TextPlugin(BasePlugin): ext", "<reponame>beshrkayali/content-io # coding=utf-8 from __future__ import unicode_literals from .base import BasePlugin class TextPlugin(BasePlugin):", "coding=utf-8 from __future__ import unic...
[ "<<EMAIL>> # - <NAME> <<EMAIL>> # Year: 2020 # Description: Generates game configurations.", "\"\"\" for p in procs: try: p.kill() except ProcessLookupError: pass PLAYING_AIs = [", "signal(SIGCHLD, signal_handler) boards_played = 0 try: for board_definition in board_definitions(): boards_played += 1", "1 run_...