ngram
listlengths
0
67.8k
[ "identifier.identify({'HTTP_AUTHORIZATION':'Basic %s' % credentials}) def test_pass(self): identifier = BasicAuthIdentifier() credentials = base64.standard_b64encode('foo:bar') identified_credentials", "with self.assertRaises(errors.IdentificationError): identifier.identify({'HTTP_AUTHORIZATION':'Basic \\x000'}) ...
[]
[ "* 626, warmup_ratio=0.9, # warmup 20 epochs. update_interval=update_interval, ), ] # optimizer optimizer", "training beta=1.2, gamma=0.5, eta=0.2, neigh_size=4, n_labels=3, t_eps=0.8), resizemix=dict(scope=(0.1, 0.8), use_alpha=True), samix=dict(mask_adjust=0, lam_margin=0.08), #", "EMA_W = (1 - m) * EMA_W + m...
[ "\\\"\" + filename + \"\\\" could not be found.\") self.Reader = InstrumentReader(filename) def", "= InstrumentReader(filename) def add_to_instr(self, Instr): \"\"\" Adds information from the McStas file to", "---------- filename (str) Filename of python file to be written \"\"\" if \"force\"", "mcstasscript....
[ "ITS DOCUMENTATION, EVEN # IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF", "University of California. All rights reserved. # # Permission is hereby granted, without", "# TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. import time, subprocess, optparse,", "time = [] hygiene_flag...
[ "or answer.title() == COUNTRIES_CAPITALS[key]: correct_answers += 1 print(\"Correct!\") else: print(\"Wrong!\") # Should we", "\"\"\"#################### Index: 1. Imports and Readme 2. Functions 3. Main 4. Testing ####################\"\"\"", "Main 4. Testing ####################\"\"\" ####################### ...
[ "'analysis_rhythm_rekordbox.json') analysis = dict() with click.progressbar(metadata_file.keys(), label=\"Converting...\") as metadata_keys: for key in metadata_keys:", "@click.command() @click.argument('dataset_path') def rekordbox_file_to_analysis_file(dataset_path): \"\"\" Read information from rekordbox_rhyth...
[ "\"\"\" Class representing a relationship between parts\"\"\" URL = 'part/related' @classmethod def add_related(cls,", "def getBomItems(self): \"\"\" Return the items required to make this part \"\"\" return", "the data to the server return api.post(cls.URL, data) class PartRelated(inventree.base.InventreeObjec...
[ "path.resolve.return_value = path special.resolve.return_value = special path_constructor.return_value = path # Register global static", "async def test_partialy_applied_handler(aiohttp_client): app = web.Application() async def handler(data, request): return web.Response(body=data) with", "r.release() r = awai...
[ "precision_macro, recall_macro, f1_micro, precision_micro, recall_micro, nmi, adjscore) ) fh.write('\\r\\n') fh.flush() fh.close() return acc,", "/ 2.0) q = np.transpose(np.transpose(q) / np.sum(q, axis=1)) return q def generate_unconflicted_data_index(emb, centers_emb,", "return np.argmax(yita, axis=1) def enc...
[ "value.id, } properties = PropertyObj.search([('name', '=', 'property_stock_journal'), ('company_id', '=', company.id)]) if properties: #", "value = self.env['account.journal'].search([('company_id', '=', company.id), ('code', '=', 'STJ'), ('type', '=', 'general')], limit=1) if", "in todo_list: account = getatt...
[ "# Squeeze batch dim # for key in blobs: # if key !=", "mini-batch of indices. Args: sampler (Sampler): Base sampler. batch_size (int): Size of mini-batch.", "torch._six import int_classes as _int_classes from core.config import cfg from roi_data.minibatch import get_minibatch", "type of \"list of ndarray\". ...
[ "it does not blow up, and stays somewhat close to a solution given", "when fit_intercept=False and # normalize=False ########################################################################### # # The R result was obtained", "precompute=False) rng = np.random.RandomState(0) X = rng.normal(0, 1, (100, 5)) X_copy...
[ "default_type application/octet-stream; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## #", "re.search('(?P<offset>[\\s\\n]*)#(?P<comment>.*)$', config, re.M) sharp_comment = re_sharp_comment.groupdict() parent_block.add_comment(Comment(sharp_comment['offset']...
[ "os.system(\"xcopy \" + source_dir + \" . /E /Y /H\") os.system('git pull origin", "os.system('git pull origin develop') os.system('git submodule update --init --force') ret = subprocess.call('\"%VS110COMNTOOLS%..\\IDE\\devenv.com\" \"build\\cocos2d-win32.vc2012.sln\"", "Config:' print ' Host:win7 x86' print ' ...
[ "from iris_sdk.models.base_resource import BaseData from iris_sdk.models.maps.ord.rate_center_search_order import \\ RateCenterSearchOrderMap class RateCenterSearchOrder(RateCenterSearchOrderMap, BaseData): pass", "#!/usr/bin/env python from iris_sdk.models.base_resource import BaseData from iris_sdk.models.maps....
[ "popSize, Iter) elif algo == \"SCA\": x = sca.SCA(getattr(benchmarks, function_name), lb, ub, dim,", "objectivefunc, Iterations) if Flag == False: # Faild to run at least one", "import optimizers.GA as ga import optimizers.HHO as hho import optimizers.SCA as sca import", "= ga.GA(getattr(benchmarks, function_...
[ "avro_type = fields.PYTHON_TYPE_TO_AVRO[primitive_type] assert {\"name\": name, \"type\": avro_type} == field.to_dict() @pytest.mark.parametrize(\"primitive_type\", fields.PYTHON_INMUTABLE_TYPES) def", "= \"a_field\" field = fields.Field(name, primitive_type, None) avro_type = [fields.NULL, fields.PYTHON_TYPE_TO_...
[ "problem.setStateInfo(\"/jointset/j0/q0/speed\", [-50, 50], 0) problem.setStateInfo(\"/jointset/j1/q1/value\", [-10, 10], 0) problem.setStateInfo(\"/jointset/j1/q1/speed\", [-50, 50], 0) problem.setControlInfo(\"/tau0\",", "predictedSolution.exportToStatesTable() statesTraj = osim.StatesTrajectory.createFromState...
[ "__init__(self): self.createTable() def createTable(self): ''' Creates A Table If it Doesnt Exist '''", "createTable(self): ''' Creates A Table If it Doesnt Exist ''' conn.execute(\"\"\"CREATE TABLE IF", "cursor = conn.cursor() def __init__(self): self.createTable() def createTable(self): ''' Creates A Table If...
[ "for v in vals] elif typename == 'TIME': vals = [None if v", "as pa message = pa.read_message(buf) rb = pa.read_record_batch(message, schema) return rb.to_pandas() def _parse_tdf_gpu(tdf):", "shared memory Parameters ---------- buf : pyarrow.Buffer Returns ------- schema : pyarrow.Schema \"\"\"", "[None if v ...
[ "self.variables = [index_variable] + [v for v in variables if v.id != index]", "not recognized as numeric or\" \" datetime\" % (self.id)) if self.entityset.time_type != time_type:", "= variable_id def set_secondary_time_index(self, secondary_time_index): for time_index, columns in secondary_time_index.items(): ...
[ "= urlparse(repo_url) return site_object.netloc def get_repo_name_from_http_url(repo_url): site_object = urlparse(repo_url) parsed_string = re.sub(r'\\.git$', '',", "predicate.search(repo_url) return match.group() def validate_protocol_exists(is_ssh, is_http): if not is_ssh and not is_http: err_message", "is_ss...
[ "True def release_capacity_send_remove_msg_to_old_segment(self, update_infos, l_segment): seg_path_id = l_segment.seg_path_id if not update_infos.has_key(seg_path_id): update_infos[seg_path_id] =", "= constants.NORMAL_MODE if current_mode == constants.CONGESTION_MODE: return constants.FINISHED_WITH_DEADLOCK else:...
[ "스위치가 꺼져 있으면 흑백, 켜져 있으면 색상 if s == 0: img[:] =", "= cv.getTrackbarPos('G', 'image') b = cv.getTrackbarPos('B', 'image') s = cv.getTrackbarPos(switch, 'image') # 스위치가", "numpy as np import cv2 as cv def nothing(x): pass # Create a", "r = cv.getTrackbarPos('R', 'image') g = cv.getTrackbarPos('G', 'image') b = c...
[ "takes around 20s pt1, pt2 = solve(29000000) print(\"Part 1:\", pt1) print(\"Part 2:\", pt2)", "range(1, int(n**0.5)+1, step) if not n % i))) def solve(target): house_count = 0", "# https://stackoverflow.com/questions/6800193/what-is-the-most-efficient-way-of-finding-all-the-factors-of-a-number-in-python def fa...
[ "Audience :: Developers\", \"License :: OSI Approved :: MIT License\", \"Natural Language ::", "import pathlib import setuptools def read(*args: str) -> str: file_path = pathlib.Path(__file__).parent.joinpath(*args) return", "Developers\", \"License :: OSI Approved :: MIT License\", \"Natural Language :: Englis...
[ "photos, blogs, tribes, wikis, tweets, bookmarks, swaps, locations and user-to-user messaging. In 0.5", "blogs, tribes, wikis, tweets, bookmarks, swaps, locations and user-to-user messaging. In 0.5 this", "site. It provides profiles, friends, photos, blogs, tribes, wikis, tweets, bookmarks, swaps, locations", ...
[ "from __future__ import unicode_literals from ralph.business.models import Venture, VentureRole def all_ventures(): yield '',", "import division from __future__ import print_function from __future__ import unicode_literals from ralph.business.models import", "yield ( v.id, \"%s[%s] %s\" % ( '\\u00A0' * 4 * v.pa...
[]
[ "user6.email = \"<EMAIL>\" user6.city_country = \"Singapore, SG\" user6.tags = \"Performer\" user6.about = ('Dancers", "awards for our photos. ' 'We will capture your ' 'memories in ways", "= \"Bar, Restaurant\" user5.about = ('Award winnning winebar with the best selection of", "user2.city_country = \"Singap...
[ "logs=None): super().on_epoch_end(epoch, logs) self._completed_epoch += 1 self.update_artifacts() should_save = False if self.epochs_since_last_save ==", "self._completed_epoch += 1 self.update_artifacts() should_save = False if self.epochs_since_last_save == 0: if self.save_best_only:", "self._workspace_path =...
[ "'labels') splits = {'train','test','valid'} files = os.listdir(in_img_dir) count = len(files) for f in", "splits = {'train','test','valid'} files = os.listdir(in_img_dir) count = len(files) for f in files:", "= os.path.join(output_dir, 'labels') splits = {'train','test','valid'} files = os.listdir(in_img_dir) ...
[ "as projector: projector.set_power('on') def mute_volume(self, mute): \"\"\"Mute (true) of unmute (false) media player.\"\"\"", "device.\"\"\" def __init__(self, host, port, name, encoding, password): \"\"\"Iinitialize the PJLink device.\"\"\" self._host", "= host self._port = port self._name = name self._passw...
[ "p[j]: j += 1 # continue elif s[i] != p[j] and j<n_p-1: j", "return True if __name__ == \"__main__\": ss = 'abbbbbc' p = 'a*' print(isMatch(ss,", "j = 0 i = -1 while i < n_s-1: i = i+", "'.' or s[i] == p[j]: j += 1 # continue elif s[i] !=", "s n_s = len(s) n_p = len(p) j = 0 i = -1", "True if __name__ == ...
[ "for user in extracted: self.user_set.add(user) class ACLRuleFactory(factory.django.DjangoModelFactory): class Meta: model = ACLRule name", "import User, Group, Permission from waliki.models import ACLRule, Page, Redirect class UserFactory(factory.django.DjangoModelFactory): username", "u'user{0}'.format(n)) pa...
[ "path_str = str(self.node_paths) self.setText(\"Parent {} to {}\".format(path_str, self.parent_node_path)) class AddAttribute(SetNodeAttributeData): \"\"\"Add an attribute", "inst_path, model, layer_path) def redo(self): super(LocalizeInstancePath, self).redo() self.setText(\"Localize instance path to {}\".format...
[ "import PdfFileWriter from frappe.utils.file_manager import save_file class ArbitrationAuthority(Document): pass def _get_sb(**kwargs): ''' call", "} }] def raise_200(answer): return ['200 OK', answer] @frappe.whitelist() def get_sammel_pdf(no_letterhead=1): frappe.enqueue(method=_get_sammel_pdf, queue='long',", ...
[ "None: self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def connect(self, host: str, port: int) -> Connection:", "socket.socket(socket.AF_INET, socket.SOCK_STREAM) def connect(self, host: str, port: int) -> Connection: self.__socket.connect((host, port)) return", "__init__(self) -> None: self._...
[ "= Gf.Vec3f(0, 0, 0) xform = UsdGeom.Xform.Define(stage, \"/Xform\") # direct subclass xformOpOrder =", "1, 1), (2, 2, 2)] pointsAsVec3fArr = Vt.Vec3fArray(pointsAsList) comp = UsdGeom.PointBased.ComputeExtent expectedExtent =", "(3,0,0)], # Test Curve with 2 widths [(0,0,0), (1,1,1), (2,1,1), (3,0,0)] # Test",...
[ "round_key = 'Round ' + str(round_num + 1) default_spread = [tournament_start_time + timedelta(minutes=game_num", "round_num)) time_df.loc[round_key, :] = match_time.strftime('%I:%M%p') return time_df else: \"\"\" # Given the algorithm,", "begins play one stagger count after you at the latest. \"\"\" for round_...
[ "int]], retargs=0) if itemid is None: return False # Check if the item", "thisitem: return False # Keep track of whether we found anything in case", "exists but has no location. Use `requisition` to fix this.\".format(NAME)) return False #", "USE OR OTHER DEALINGS # IN THE SOFTWARE. # ********** NAME = \"loca...
[ "in range(12): xgb_row.append(xgb_results[month][row_target_index]) rfr_row.append(rfr_results[month][row_target_index]) dtr_row.append(dtr_results[month][row_target_index]) plt.plot(data[month_dependant_variables].iloc[row_target_index], '-', label='scsb', color='blue', alpha=0.5) plt.plot(xgb_row, '-', label='xgb...
[ "Feature importance # MAGIC # MAGIC SHAP is a game-theoretic approach to explain", "\"title_without_stopwords\", \"text\", \"title\", \"type\", \"author\"] col_selector = ColumnSelector(supported_cols) # COMMAND ---------- # MAGIC", "nulls. # To enable SHAP to succeed, both the background data and examples", ...
[ "globals().update({k: getattr(module, k) for k in module.__all__}) __all__ += module.__all__ except AttributeError: continue", "is_pkg in pkgutil.walk_packages(__path__): module = importlib.import_module('.'+module_name,package=__name__) try: globals().update({k: getattr(module, k) for k in", "= [] for loader, ...
[ "X[idx], Y[idx] def add_to_grid(tiles, grid): for tile in tiles: grid[tile.pt1[0], tile.pt1[1]] = tile", "center_pts[:,0] Y = center_pts[:,1] if only_new_blocks: idx = (np.abs(X) + np.abs(Y) <= order)", "grid def enlarge_grid_deprec(grid, order): center_pts = [*grid] X_aztec, Y_aztec = aztec_grid(order) center_...
[ "np.sqrt((x - cell_grid_x) ** 2 + (y - cell_grid_y) ** 2) def get_distance_matrix_squared(cell_grid_x,", "- cell_grid_x) ** 2 + (y - cell_grid_y) ** 2) def get_distance_matrix_squared(cell_grid_x, cell_grid_y,", "import numpy as np def get_position_of_minimum(matrix): return np.unravel_index(np.nanargmin(matrix...
[]
[ "[] plugin = manager.QuantumManager.get_plugin() resource_name = 'qos_queue' collection_name = resource_name.replace('_', '-') + \"s\"", "softtabstop=4 # Copyright 2013 Nicira, Inc. # All Rights Reserved # # Licensed", "Unless required by applicable law or agreed to in writing, software # distributed", "'vali...
[ "to be added, please add an issue on the GitHub repo. \"\"\" from", "Numpy. To suggest more to be added, please add an issue on the", "contains all of the maths tools that you'd ever need for your AI", "be added, please add an issue on the GitHub repo. \"\"\" from easyneuron.math.distance", "your AI project...
[ "workingarea.close.call_count assert 0 == dispatcher.terminate.call_count obj.terminate() assert 1 == workingarea.open.call_count assert 0 ==", "= [1001, 1002] # runid package0 = mock.MagicMock(name='package0') package1 = mock.MagicMock(name='package1') assert 0", "sleep=0.01) ret.open() yield ret ret.close() #...
[ "License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "writing, software # distributed under the License is distributed on an \"AS IS\"", "OdlDhcpDriverTestCase(test_odl_dhcp_driver_base.OdlDhcpDriverTestBase): def setUp(self): super(OdlDhcpDriverTestCase, self).setUp() cfg.CONF.se...
[ "= [ ('users', '0001_initial'), ] operations = [ migrations.AlterField( model_name='users', name='site_key', field=models.CharField(blank=True, default='<KEY>',", "Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AlterField( model_name='users', name='site_ke...
[ "total_groups = Group.objects.all().count() total_applications = Application.objects.all().count() new_users = handler.get_new_user_counts( { \"new_users_last_24_hours\": timedelta(hours=24), \"new_users_last_7_days\":", "AdminDashboardView(APIView): permission_classes = (IsAdminUser,) @extend_schema( tags=[\"Adm...
[ "or EOFError: print(\"in except\") # s.close() # 關閉連線 socketThread.do_run = False # socketThread.join()", "s.recv(1024).decode(\"utf-8\") print(data) time.sleep(0.1) def inputJob(): while True: data = input() s.send(bytes(data, \"utf-8\")) time.sleep(0.1)", "time.sleep(0.1) except KeyboardInterrupt or EOFError:...
[ "assign if a specific type is not associated with an observable\", \"order\": 7", "\"string\", \"title\": \"URL Mapping\", \"description\": \"Indicator type to assign if a specific type", "a specific type is not associated with an observable\", \"order\": 11 }, \"notes\":", "\"title\": \"File\", \"description...
[ "delta = {'instances': 1, 'volumes': CONF.max_volumes_per_user + 1} self.assertRaises(exception.QuotaExceeded, self.driver.reserve, FAKE_TENANT1, resources, delta)", "= {'instances': 10, 'volumes': 2000, 'Fake_resource': 123} self.assertRaises(exception.QuotaResourceUnknown, self.driver.reserve, FAKE_TENANT1, res...
[ "from flask_restful import reqparse def retornar_parser(): parser = reqparse.RequestParser() parser.add_argument('sentenca', type=str, required=True) return", "flask_restful import reqparse def retornar_parser(): parser = reqparse.RequestParser() parser.add_argument('sentenca', type=str, required=True) return par...
[ "항공기', '소형 승용차', '버스', '트럭', '기차', '크레인', '다리', '정유탱크', '댐', '운동경기장', '헬리패드', '원형", "mmdet.apis import init_detector, inference_detector, show_result, draw_poly_detections import mmcv from mmcv import Config from", "'stadium', 'helipad', 'roundabout') CLASS_MAP = {k:v for k, v in zip(CLASS_NAMES_KR, CLASS_NAMES...
[ "dicoms.models import Subject from dicoms.models import Session from dicoms.models import Series admin.site.register(Session) admin.site.register(Subject)", "import Subject from dicoms.models import Session from dicoms.models import Series admin.site.register(Session) admin.site.register(Subject) admin.site.regis...
[ "for django-react-redux-jwt-base project. \"\"\" import os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"djangoreactredux.settings.dev\") from django.core.wsgi import get_wsgi_application from", "\"\"\" WSGI config for django-react-redux-jwt-base project. \"\"\" import os os.environ.setdefault(\"DJANGO_SETT...
[ "self.key_pattern: return True return bool(re.match(self.key_pattern, key)) def _qualified_key(self, key): \"\"\" Prepends the configured", "if self.auto_casting and (result is not None): result = jsonpickle.decode(result) return result def", "_qualified_key(self, key): \"\"\" Prepends the configured prefix to ...
[ "and the following disclaimer in the documentation # and/or other materials provided with", "# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR #", "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES", "AND FITNESS FOR A PARTICULAR PURPOSE ARE # DI...
[]
[ "for c in chain(*clauses))) def count_clauses(*clauses): total = 0 for subclauses in clauses:", "count_clauses(*clauses): total = 0 for subclauses in clauses: total += len(subclauses) return total", "total def unique_literals(*clauses): literals = set() for clause in chain(*clauses): literals.update((abs(l) for...
[ "self.parameters) simulation.Run() def tearDown(self): with KratosUnittest.WorkFolderScope(self.work_folder, __file__): KratosUtilities.DeleteFileIfExisting('sod_shock_tube_geom_coarse.time') def _CustomizeSimulationSettings(self): # Customize simulation", ": { \"check_variables\" : [\"DENSITY\",\"MOMENTUM_X\",\"...
[ ".cate_broadcast_comm_controller import CateBCommMAC from .cate_broadcast_comm_controller_full import CateBCommFMAC from .cate_broadcast_comm_controller_not_IB import CateBCommNIBMAC from .tar_comm_controller", "from .cate_broadcast_comm_controller import CateBCommMAC from .cate_broadcast_comm_controller_full imp...
[ "path): try: print(\"connect\") async for message in websocket: print(message) finally: USERS.remove(websocket) async def", "async def main(): async with websockets.serve(counter, \"localhost\", 5000): await asyncio.Future() # run forever", "asyncio import json import logging import websockets logging.basicConf...
[ "= conv_block(p3, n_filters*4,5,True) p4 = Conv3D(n_filters*8,kernel_size = (2,2,2) , strides = (2,2,2) ,", "(1,1,1) , padding = 'same')(u10); c10 = Dropout(dropout)(c10) c10 = add([c10,u10]); #c9 =", "conv_block(u9,n_filters*4,5,True) c9 = Dropout(dropout)(c9) u10 = Conv3DTranspose(n_filters,(2,2,2),strides = ...
[ "str = None img: str = None tag: str = None price: int", "class ActiveOffer(BaseModel): id: str = None title: str = None instruction: str =", "None title: str = None instruction: str = None instruction_html: str = None", "id: str = None title: str = None instruction: str = None instruction_html:", "= None t...
[ "name='bn2b_branch2b',is_training=False) .conv(1, 1, 256, 1, 1, biased=False, relu=False, name='res2b_branch2c') .batch_normalization(name='bn2b_branch2c',is_training=False,relu=False)) (self.feed('res2a_relu', 'bn2b_branch2c') .add(name='res2b')", "relu=False, name='res3c_branch2b') .batch_normalization(relu=Tru...
[ "_is_principal_tuple(principal): return [tuple(principal)] else: return _flatten(_process_principal(p) for p in principal) def _process_permission_set(ids, permission_set):", "LOGGER = logging.getLogger(__name__) _Context = collections.namedtuple(\"_Context\", [ \"session\", \"ids\", \"principal\", \"principal_fi...
[ "threading from concurrent.futures import ThreadPoolExecutor from service.train import do_train def thread_runner(thread_num, func, *args):", "<reponame>naetimus/bootcamp<filename>solutions/pic_search/webserver/src/service/theardpool.py import threading from concurrent.futures import ThreadPoolExecutor from servi...
[ "# dest='alpha', # help='try to get the version') # Execute parse_args() args =", "subcommand = parser.parse_args().cmd if args.version is True: print(f\"version: {__version__}\") exit(0) # if subcommand", "the build system') # parser.add_argument( # '-f', # '--file', # help='A readable file',", "__version__ ...
[ "R.json() PAGES = DATA[\"query\"][\"pages\"] for k, v in PAGES.items(): for l in v[\"links\"]:", "file is auto-generated. See modules.json and autogenerator.py for details #!/usr/bin/python3 \"\"\" get_links.py MediaWiki", "\"\"\" get_links.py MediaWiki API Demos Demo of `Links` module: Get all links on", "of...
[ "an xyz file to use as input to use_gen_template (if make_input is True).", "as script_file: sfw = script_file.write sfw('#!/bin/bash -l\\n\\n') sfw('#$ -pe omp {}\\n'.format(num_cores)) sfw('#$ -M", "copied into the next file) and a template file that should be the", "line is the number of atoms # continue #...
[ "if len(matrix.shape) > 1: matrix_list = [] for row in matrix: try: matrix_list.append(list(row))", "import pdb import numpy as np import pickle def listify_mat(matrix): matrix = np.array(matrix).astype(str)", "pdb.set_trace() return matrix_list else: return list(matrix) class Recorder(): def __init__(self): se...
[ "'state', 'zip', 'lng', 'lat'] mywriter=csv.writer(output) mywriter.writerow(header) for r in range(1000): mywriter.writerow([ fake.name(), fake.random_int(min=18,", "'street', 'city', 'state', 'zip', 'lng', 'lat'] mywriter=csv.writer(output) mywriter.writerow(header) for r in range(1000): mywriter.writerow([", ...
[ "# Generated by Django 2.2.4 on 2019-10-03 21:09 from django.db import migrations, models", "django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('ingreso', '0003_auto_20190907_2152'),", "on 2019-10-03 21:09 from django.db import migration...
[ "= tddft_iter(label='water', cd=dname) try: from pyscf.lib import misc libnao_gpu = misc.load_library(\"libnao_gpu\") td_gpu =", "self.assertTrue(hasattr(td, 'xvrt')) self.assertTrue(td.ksn2f.sum()==8.0) # water: O -- 6 electrons in the valence +", "valence + H2 -- 2 electrons self.assertEqual(td_gpu.xocc[0].sh...
[ "JSON', long_description=long_description, long_description_content_type='text/markdown', keywords='geometry gis osm parsing', author='<NAME>', author_email='<EMAIL>', url='https://github.com/aspectumapp/osm2geojson', packages=['osm2geojson'], include_package_data=True, install_requires=parse_requirements(\"require...
[ "(valor, registro[0])) if cursor.rowcount == 1: conexao.commit() print('Alteração gravada.') else: conexao.rollback() print('Alteração abortada.')", "= float(input('Novo valor: R$')) cursor.execute('UPDATE Precos SET preco = ? WHERE nome_produto =", "with sqlite3.connect('precos.db') as conexao: with closing(co...
[ "return self.__class__(self.vars,obj,le,eq) def build_solution(self,x,obj_value,status,duals): _vars = { var: v.item() for var,v in zip(self.vars,x)}", "= [] self.posts = [] def solve(self,p,config,x=None): for pre in self.pres: start =", "x,_,status,duals = solve(p_f32,x,config,fast=True) logger.debug(\"fast m...
[ "import numpy as np import cv2 def test_pad(): raw = dict( img=np.zeros((200, 401,", "pad(raw) print(r['img'].shape) cv2.imshow('draw', r['img']) cv2.waitKey() raw = dict( img=np.zeros((402, 401, 3), dtype=np.uint8) )", "gt_bboxes = np.array([[0, 0, 10, 9]]) result = dict(gt_bboxes=bboxes) fb = FilterBox((10, 1...
[ "self.aliases = aliases class FakeConfigurationSettings(object): def __init__(self, settings_name, base_config=None): self.base_config = base_config self.name", "test_ProjectSettingsFileMergeKwSection_ValidInputs_Success(mock_parse_json, fake_context, mock_json_map, additional_aliases, section_key, expected): tes...
[ "enum.auto() SUM_MAX_DEVIATION = enum.auto() def _generate_variables(solver, points, coeff_ranges, err_max, error_def): \"\"\"Create coefficient variables.", "tuples (x, y) coeff_ranges: A tuple of valid coefficient ranges, respresented as tuples", "definition.\"\"\" objective = solver.Objective() for variable ...
[ "parsed.package_dir)) # Convert build_dir to absolute path, relative to package_dir. parsed.build_dir = os.path.join(parsed.package_dir,", "as e: printerr('FAIL: Generating the Xcode project failed') printerr('Executing: %s' % ' '.join(e.cmd))", "in the toolchain rpaths_to_add = ['@executable_path/../lib/swift/...
[ "group id\", \"name\": \"Light group\", \"type\": \"LightGroup\", \"state\": {\"all_on\": False, \"any_on\": True}, \"action\":", "openpeerpower.components.scene import DOMAIN as SCENE_DOMAIN, SERVICE_TURN_ON from openpeerpower.const import ATTR_ENTITY_ID from .test_gateway import", "config_entry.data, \"/group...
[ "mailbot_config.getint(section, 'max_emails_per_protection_interval', fallback=50) NOTIFY_INTRUDER = mailbot_config.getboolean(section, 'notify_intruder', fallback=True) NOTIFY_ADMIN = mailbot_config.getboolean(section, 'notify_admin', fallback=False)", "/ 'hosts_config.ini') MAILBOT_TEMPLATE_CONFIG_PATH = str(te...
[ "2) + dec_hid_dim self.attn = nn.Linear(self.attn_in, attn_dim) def forward(self, decoder_hidden, encoder_outputs): src_len =", "= nn.Linear(self.attn_in, attn_dim) def forward(self, decoder_hidden, encoder_outputs): src_len = encoder_outputs.shape[0] repeated_decoder_hidden = decoder_hidden.unsqueeze(1).repeat(1...
[ "to send it to # loss function we want it to be (N,", "of shape (trg_len, batch_size, output_dim) but Cross Entropy Loss # doesn't take input", "encoder_net = Encoder( input_size_encoder, encoder_embedding_size, hidden_size, num_layers, enc_dropout ).to(device) decoder_net = Decoder( input_size_decoder,", "wa...
[ "class LightImitateMixin(Agent): \"\"\"Abstract class that handles passing expert trajectories alongside self-play sampling \"\"\"", "import Agent from parlai.core.message import Message from random import sample import pathlib path", "for i in range(len(utterances)): history = self.histories[i] history.append(...
[ "( ListNode, NodeType, convert_list_to_linked_list, ) def has_cycle(head: NodeType) -> bool: \"\"\" Args: head:", "from pytudes._2021.utils.linked_list import ( ListNode, NodeType, convert_list_to_linked_list, ) def has_cycle(head: NodeType) -> bool:", ">>> head.next = head >>> has_cycle(head) True >>> head = c...
[ "# conn.sendall(msg) break if __name__ == '__main__': input_port = int(sys.argv[1]) input_doc_root = sys.argv[2]", "200 req else: res = self.res_200 res += \"Last-Modified: {}\\r\\n\".format(time.ctime(os.stat(path).st_mtime)) with open(path, \"rb\")", "# mapping url, return 404 escape or absolute filename # ju...
[ "all metrics. From: https://github.com/pytorch/tnt/blob/master/torchnet/meter/meter.py \"\"\" def reset(self): pass def add(self): pass def value(self):", "class Metric(object): \"\"\"Base class for all metrics. From: https://github.com/pytorch/tnt/blob/master/torchnet/meter/meter.py \"\"\" def reset(self): pass"...
[ "git import Repo from pf_pweb_sourceman.common.console import console from pf_py_file.pfpf_file_util import PFPFFileUtil class GitRepoMan:", "class GitRepoMan: def get_repo_name_from_url(self, url: str): if not url: return None last_slash_index =", "def clone_or_pull_project(self, path, url, branch): repo_name ...
[ "= stdout_4.readlines() output_5 = stdout_5.readlines() remote_data_1 = { 'Hostname': '', 'IP': '', 'MAC':", "= stdout_6.readlines() data_ = [] filter_ = [] remote_data_2 = { 'Hostname': [],", "due to wrong username/password\".format(Hostname)) exit(1) except: print(\"Failed to connect to {} \".format(Hostname)...
[ "delete_latest_version_of_secret(self, path, mount_point=DEFAULT_MOUNT_POINT): \"\"\"Issue a soft delete of the secret's latest version at", "int :param cas_required: If true the key will require the cas parameter to", "str | unicode :return: The response of the request. :rtype: requests.Response \"\"\" params"...
[ "to connected device(s) import subprocess import sys answer = input(\"Install all vulkan examples", "time! (Y/N)\").lower() == 'y' if answer: BUILD_ARGUMENTS = \"\" for arg in sys.argv[1:]:", "this may take some time! (Y/N)\").lower() == 'y' if answer: BUILD_ARGUMENTS = \"\"", "\"-validation\" if subprocess.c...
[ "# Ahoughton generator and adapter test # 2016 problem = ahoughton_generator_2016.generate() ahoughton_renderer_2016.render_problem(problem) #", "DefaultProblemAdapter from adapters.crg import CRGProblemAdapter from adapters.ahoughton import AhoughtonAdapter import json def main():", "AhoughtonAdapter(), config...