ngram
listlengths
0
82k
[ "# Make sure to only set the hash after the", "central_atom_indices = sorted( map_to_atom_index[task.central_bond[i]] for i in (0, 1) )", "None: return task_id.decode() task_id = compute.delay(task_json=task.json()).id redis_connection.hset(\"qcgenerator:types\", task_id, task.type) #", "hits. canonical_molec...
[ ":param str state_start: Verb to describe operation start :param str", "to execute :param str state_start: Verb to describe operation start", "seq_snap.add(*build_instance_sequence(instance, OP_SS_D)) if OP_SS_C in instance.node.operations: seq_snap.add(*build_instance_sequence(instance, OP_SS_C)) # Init", ":...
[ "# Wait until sending file while not self._sending_file: pass #", "with parameters\") def threadfunc(worker_num, fpath): self._workers_active += 1 try: recver_socket", "return printerror(\"Couldn't access file due to permission error\") except timeout:", "path of the storage dir for received files. If storage...
[ "= is_training self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size =", "to next_input_ids next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) next_attn_mask = tf.cast(ids_tensor((self.batch_size,", "is a problem with the signature check. # Test passes", "passes for TFLEDMo...
[ "x: np.sin(np.pi*x)), ] enabled_act_functions = available_act_functions def get_measurements(self, weights, x,", "scores in x. Returns: softmax - softmax normalized in dim", "y_raw y_pred = np.argmax(y_raw, axis=-1) y_prob = softmax(y_raw, axis=-1) if", "np.abs(x)), ('cos', lambda x: np.cos(np.pi*x)), ('sin '...
[ "expected_data == imported_data def assert_many_records_match( expected: Sequence[TrackedModel], imported: Sequence[TrackedModel], ignore=frozenset(),", "from django.urls import reverse from freezegun import freeze_time from lxml", "def assert_many_records_match( expected: Sequence[TrackedModel], imported: Sequ...
[ "# 发送HTML邮件 # msg = MIMEText('<html><body><h1>Hello</h1>' + # '<p>send by", "'plain', 'utf-8') # 发送HTML邮件 # msg = MIMEText('<html><body><h1>Hello</h1>' + #", "把附件的内容读进来: mime.set_payload(f.read()) # 用Base64编码: encoders.encode_base64(mime) # 添加到MIMEMultipart: msg.attach(mime) msg['From'] =", "'</body></html>',...
[ "queue system installed. queue_resources = QueueWorkerResources( number_of_threads=1, number_of_gpus=1, preferred_gpu_toolkit=QueueWorkerResources.GPUToolkit.CUDA, per_thread_memory_limit=5", "a HPC resources with the LSF queue system installed. queue_resources", "\"module load cuda/10.1\"] calculation_backend ...
[ "repeat runtime test for _ in range(self.n_repeat_trials): observation = IDMAgents(", "iteration.time_point.time_s, ) observation.update_observation(iteration, next_iteration, buffer) profiler.stop() if self.display_results: logger.info(profiler.output_text(unicode=True, color=True))", "next_iteration = Simulat...
[ "tf.train.Checkpoint(model=agent) manager = tf.train.CheckpointManager(ckpt, load_path, max_to_keep=None) ckpt.restore(manager.latest_checkpoint) print(\"Restoring from {}\".format(manager.latest_checkpoint))", "in range(nb_rollout_steps): # Predict next action. action, q, _, _", "rank == 0 and logdir: if hasat...
[ "from PySide2.QtWidgets import * from PySide2.QtPrintSupport import QPrinter, QPrintDialog from", "def print_statement(self): printer = QPrinter() printer.setOutputFileName(os.path.join( os.environ.get('HOME'), '%s_%s.pdf' % (self._transaction.created_at.strftime('%Y%m%d'),", "from PySide2.QtCore import * from ...
[ "equal to other. \"\"\" # Check that the other is", "optional Which columns to read, with 0 being the first.", "isinstance(ret, YTArray): if inp.units.same_dimensions_as(ret.units): ret.in_units(inp.units) return ret def sanitize_units_add(this_object, other_object,", "expm1, log1p, sqrt, square, \\ reciproca...
[ "= serializers.SerializerMethodField() class Meta: model = Post fields = [", "image class PostListSerializer(serializers.ModelSerializer): url = post_detail_url user = serializers.SerializerMethodField() class", "'html', ] def get_html(self, obj): return obj.get_markdown() def get_user(self, obj):", "except: ...
[ "grid_number=1) self.oHelper.SetButton('Concluir') self.oHelper.SetButton('Fechar') self.oHelper.AssertTrue() @classmethod def tearDownClass(inst): inst.oHelper.TearDown() if __name__", "import unittest class GTPA036E(unittest.TestCase): @classmethod def setUpClass(inst): inst.oHelper = Webapp()", "\"T1\", \"D ...
[ "DjangoFilterBackend from django.http import HttpResponse,FileResponse,JsonResponse from rest_framework_jwt.authentication import JSONWebTokenAuthentication from", "from rest_framework.generics import ListAPIView from rest_framework.filters import SearchFilter, OrderingFilter from", "HttpResponse,FileResponse,J...
[ "def __init__(self, *args, **kwargs): super(HeartbeatCollector, self).__init__(*args, **kwargs) self.hostname = self.get_hostname()", "self.config: self.connection_timeout = int(self.config['netuitive_connection_timeout']) self.api = netuitive.Client(url=self.config['netuitive_url'], api_key=self.config['netuitiv...
[ "[exp2_Delta.min(), exp2_Delta.median(), exp2_Delta.std()]) stat2_Delta.index = [\"Best\", \"Median\", \"Std.\"] # find", "# print(\"{}.Hypervolume:\".format(market), # best2_Hypervolume[0], best2_Hypervolume[1]) # TODO: check error print(\"{}\\n----------------------------------------------\".format(market))", ...
[ "np.sqrt(cov(x, x, w) * cov(y, y, w)) print('Completed: Computed weighted", "int(lat.shape[0]),int(lon.shape[0]))) varyravel = np.reshape(vary.copy(), (int(vary.shape[0]*12.),levsq, int(lat.shape[0]),int(lon.shape[0]))) varx_dj = np.empty((int(varx.shape[0]-1),levsq, int(lat.shape[0]),int(lon.shape[0])))", "for...
[ "\"C\") as [vi, vj]: C[vi, vj] = B[vi, vj] +", "vi + 1, vj], (1, 1)) C[vi, vj] = Bb[0,", "\"C\" def test_compute_inline_under_loop(): sch = tir.Schedule(elementwise_under_loop, debug_mode=True) block_b = sch.get_block(\"B\")", "128], \"C\") as [vi, vj]: D[vi, vj] = B[vi, vj]", "D = tir.match_buffer(d, (128,...
[ "request, redirect import subprocess import tempfile import json import yaml", "\"%sjobs/%i\" % (request.url_root, self.jobid), \"log\": \"%sjobs/%i/log\" % (request.url_root, self.jobid), \"run\":", "= self.proc.communicate(self.inputobj) if self.proc.returncode == 0: outobj = yaml.load(self.stdoutdata, Loader...
[ "2: result = result << 1 = 0000_0000_0000_0000_0000_0000_0000_0100. n&1 =", "side if (i < 31) { // CATCH: for last", "binary as 0000_0000_0000_0000_0000_0000_0000_1101, the \"_\" is for readability), calling reverseBits(13)", "1 therefore result = result + 1 = = 0000_0000_0000_0000_0000_0000_0000_1011", "00...
[ "the last in the module, exactly as formatted: __version__ =", "be the last in the module, exactly as formatted: __version__", "*must* be the last in the module, exactly as formatted:", "information.\"\"\" # The following line *must* be the last in", "\"\"\"Version information.\"\"\" # The following line *m...
[ "PdfFileWriter import re range_pattern = re.compile(r'(\\d+)(\\.\\.|-)(\\d+)') comma_pattern = re.compile('\\d+(,\\d+)*') def", "\"usage examle:\\npython3 selective_merge_pdf.py file1.pdf 1-3 file2.pdf 3,4,10 file1.pdf 50\" assert(len(argv)", "groups = range_pattern.search(pages_str) if groups: start = int(grou...
[ "detected_vps, image_dims): \"\"\"Measures error in direction from center of detected", "VPs do not count against the score. Based on log", "/ height def vp_direction_error(ground_truth_vps, detected_vps, image_dims): \"\"\"Measures error in direction", "in the location of detected vanishing points. \"Missed\...
[ "replace=False) args.task_id = int(task_list[proc_id()]) _robots = [\"IIWA\", \"Jaco\", \"Kinova3\", \"Panda\"]", "type=int, default=-1) parser.add_argument('--task-id', type=int, default=-1) parser.add_argument('--hid', type=int, default=256) parser.add_argument('--l', type=int,", "default=0.02) parser.add_arg...
[ "f(): yield 1 g = f() res = g.next() assert", "object\") def test_throw_finishes_generator(self): def f(): yield 1 g = f()", "def f(): try: yield 1 v = (yield 2) except:", "set() def test_explicit_stop_iteration_unpackiterable(self): def f(): yield 1 raise StopIteration assert", "assert d['f'].x == 42 def t...
[ "with the same environment of VM' ) subparser.add_argument( '--disk-size', dest='disk_size',", "use latest hypervisor settings', ) subparser = subparsers.add_parser( 'delete', description=vm_delete.__doc__,", "any(isinstance(a, _SubParsersAction) for a in self._actions): return super(IGVMArgumentParser, self).f...
[ "dataset_path = os.path.join(base_path, dataset_name) processor = PROCESSORS[dataset_name.lower()]() train_dataset = processor.get_train_examples(dataset_path)", "18025 assert len(test_dataset) == 4928 assert test_dataset[0].text_a == \" |", "os.path import abspath, join root_dir = d(d(d(abspath(__file__)))) sy...
[ "syntax/format \", RESOURCE_NOT_AVAILABLE : \"Not available\", RESOURCE_ALLOCATE_FAILURE : \"Allocate failure\",", "0x1004 OPTION_NOT_SUPPORTED = 0x1005 OPTION_UNKNOWN_ERROR = 0x1FFF PARAMETER_INVALID = 0x2000", "0x4000 RESOURCE_ALLOCATE_FAILURE = 0x4001 RESOURCE_FULL = 0x4002 RESOURCE_OVERFLOW = 0x4003", "se...
[ "random class SUN397EncodableDataset(Dataset): \"\"\"SUN397 encodable dataset class\"\"\" def __init__(self, train=True):", "transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ])", "'data/SUN397/train/*/*.jpg' if train else 'data/SUN...
[ "All rights reserved. # See LICENSE.txt for complete terms. from", "= super(Location, self).to_dict() if self._XSI_TYPE: d[\"xsi:type\"] = self._XSI_TYPE return d", "= common_binding.LocationType _namespace = 'http://cybox.mitre.org/common-2' _XSI_TYPE = None # overridden", "fields.IdrefField(\"idref\") name ...
[ "pandas as pd import pysam import matplotlib matplotlib.use(\"agg\") import matplotlib.pyplot", "not None: softclips.append([clip_right, False, is_first_read]) if i == 10000000: break", "max(softclips) plt.plot([m, m], [0, 1.0], \":k\") plt.text(m, 1, \"max={}\".format(m), horizontalalignment=\"right\",", "fu...
[ "import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('rss_feeder_api', '0002_feed_subtitle'), ]", "), migrations.AlterModelOptions( name='feed', options={'ordering': ('-updated_at',), 'verbose_name': 'Feed', 'verbose_name_plural': 'Feeds'}, ),", "] operations = [ migrations.Alt...
[ "v2 has BN-ReLU before Pooling x = BatchNormalization()(x) x =", "res_block == 0: # first layer and first stage activation", "y = resnet_layer(inputs=y, num_filters=num_filters_in, conv_first=False) y = resnet_layer(inputs=y, num_filters=num_filters_out, kernel_size=1,", "dimensions activation (string): activ...
[ "'isSpouseOf'] RELS_TO_INFER = ['hasGrandParent', 'isGrandParentOf', 'hasGreatGrandParent', 'isGreatGrandParentOf', 'isUncleOf', 'hasUncle', 'isGreatUncleOf',", "{} graph['nodes'] = [] graph['edges'] = [] nodes = {}", "graph['nodes'] = [] graph['edges'] = [] nodes = {} q", "?obj . VALUES ?testPred { fhkb:isWi...
[ "\"kermit\", \"iss\": \"test-issuer\"}) self.assertEqual(channel.result[\"code\"], b\"200\", channel.result) self.assertEqual(channel.json_body[\"user_id\"], \"@kermit:test\") # An", "\"\"\"An unknown IdP should cause a 400\"\"\" channel = self.make_request(", "ApplicationService.NS_ALIASES: [], }, ) self.anoth...
[ "in range(5): publisher.publish(request) sleep(0.5) rclpy.shutdown() print(f'Delivery request submitted to {args.robot_type}')", "= args.dropoff for _ in range(5): publisher.publish(request) sleep(0.5) rclpy.shutdown() print(f'Delivery", "dispenser - parameters: [request_guid: xxx, target_guid:cssdbot, transpor...
[ "log.warning( f\"{route.endpoint} Has exceeded it's ratelimit ({lock.limit})! Reset in {lock.delta}", "logging.getLogger(logger_name) class GlobalLock: \"\"\"Manages the global ratelimit\"\"\" def __init__(self) ->", "\"\"\" if bucket_hash := self._endpoints.get(route.rl_bucket): # we have seen this", "import...
[ "= environ.get('SECRET_KEY') USER = environ.get('DB_USER') PASSWORD = environ.get('DB_PASSWORD') DB_NAME =", "False CSRF_ENABLED = True SECRET_KEY = environ.get('SECRET_KEY') USER = environ.get('DB_USER')", "= environ.get('DB_HOST') SQLALCHEMY_DATABASE_URI = f\"postgresql://{USER}:{PASSWORD}@{HOST}/{DB_NAME}\" ...
[ "the mnemonic seed must begin with this SEED_PREFIX = '01'", "return SEED_PREFIX_SW elif seed_type == '2fa': return SEED_PREFIX_2FA elif seed_type", "<filename>electrum/version.py ELECTRUM_VERSION = '4.1.5-radc' # version of the client package", "'4.1.5-radc' # version of the client package APK_VERSION = '4.1...
[ "torch import numpy as np import cv2 from lib.utils.visualize_utils import", "= p.forward(feat_dim) print(p1) def test_filp(cfg, tb_writer): cfg = copy.deepcopy(cfg) cfg['feature_maps']", "0') def _setup(self, cfg): num_feat = len(self._steps) for item in", "map size\"\"\" assert self._prior_cfg is not {} ret...
[ "s = str( self ) if IECore.FileSequence.fileNameValidator().match( s ) :", "isinstance( exampleValue, basestring ) : combiner = mostCommon if combiner", "child ) ) else : nonLeafPaths.append( child ) sequences =", "values ) / len( values ) def mostCommon( values )", "path ) : result = self.__basePathSeed.co...
[ "django.db import migrations class Migration(migrations.Migration): dependencies = [ ('reo', '0117_financialmodel_generator_fuel_escalation_pct'),", "= [ ('reo', '0117_financialmodel_generator_fuel_escalation_pct'), ('reo', '0120_auto_20210927_2046'), ('reo', '0121_auto_20211012_0305') ] operations", "from djan...
[ "\"by%sIsolationMVArun2v1DBnewDMwLT\") tau.idCI3hit = id3(tau, \"by%sCombinedIsolationDeltaBetaCorr3Hits\") tau.idAntiMu = tau.tauID(\"againstMuonLoose3\") + tau.tauID(\"againstMuonTight3\")", "alltaus: tau.associatedVertex = event.goodVertices[0] if len(event.goodVertices)>0 else event.vertices[0] tau.lepVeto ="...
[ "e - (b // a) * d, d) def modInvert(a,b):", "open(\"plaintext.txt\", \"r\") plain1 = plain1File.read().split(\"\\n\")[0] plain2 = plain2File.read().split(\"\\n\")[0] if plain1", "plain2: print(\"Dosyalar Özdeştir..\") else: print(\"Dosyalar özdeş değildir..\") n = int(input(\"Oluşturulmak", "işlemi yapılamz. ...
[ "as predecessors print networkx.descendants(self.networkx, e) # almost as child_to_parents def", "# write_to_dot def get_subgraph(self, envos=None): \"\"\"Given a list of ENVO", "* https://github.com/biolab/orange-bio * https://bitbucket.org/biolab/orange-bioinformatics To install: $ pip install Orange-Bioinfor...
[ "Possible values include: \"undefined\", \"false\", \"true\". :type result: str or", "to specify whether the fallback route is enabled. :type is_enabled:", "__init__( self, **kwargs ): super(ExportDevicesRequest, self).__init__(**kwargs) self.export_blob_container_uri = kwargs['export_blob_container_uri'] self....
[ "('aliases', ['alias1.yaml']), ('triggers', ['trigger1.yaml', 'cron1.yaml']), ('rules', ['rule1.yaml']), ('triggertypes', ['triggertype1.yaml']), ('executions',", "'path': '/v1/ruleenforcements/%s' % (enforcement_model.id), 'method': 'GET' }, # Action Executions", "{ 'path': '/v1/packs/index/health', 'method': ...
[ "assert len(r.json()[\"data\"][\"tensor\"][\"values\"]) == 1 r = rest_request_ambassador(\"myabtest\",None,API_AMBASSADOR) res = r.json()", "myabtest --imageA seldonio/mock_classifier:1.0 --imageB seldonio/mock_classifier:1.0 --oauthKey=oauth-key --oauthSecret=oauth-secret && ks apply", "k8s_utils import * def ...
[ "# proxy module from __future__ import absolute_import from envisage.safeweakref import", "<reponame>enthought/etsproxy # proxy module from __future__ import absolute_import from envisage.safeweakref", "proxy module from __future__ import absolute_import from envisage.safeweakref import *" ]
[ "models.ManyToManyField('Genre') class Author(models.Model): name = models.CharField(max_length=50) nationality = models.ForeignKey('Nation', null=True)", "name = models.CharField(max_length=50) nationality = models.ForeignKey('Nation', null=True) class Genre(models.Model): name", "= models.CharField(max_length...
[ "- keep_prob) * width**2 / dropblock_size**2 / (width - dropblock_size", "keepdims=True) else: ksize = [1, 1, dropblock_size, dropblock_size] block_pattern =", "C]) if data_format == 'channels_last' else tf.reshape(cam, [N, C, height,", "code from tensorpack.tfutils.tower import get_current_tower_context from...
[ "tree. # from rlstructures import logging from rlstructures.env_wrappers import GymEnv,", "import GymEnv, GymEnvInf from rlstructures.tools import weight_init import torch.nn as", "envs.append(e) return GymEnvInf(envs, seed) def create_agent(model, n_actions=1): return RecurrentAgent(model=model, n_actions=n_ac...
[ "alt import pydeck as pdk import os import glob from", "wc = WordCloud(background_color=\"white\", max_words=100, width=2000, height=800, colormap='tab20') wc.generate_from_frequencies(worte) return st.image(wc.to_array())", "gesamt: {relations.replace(',','.')}\") def systematik(): #Ranking der meistverwendete...
[ "processed. class NoParkingAvailableError(NoOverlapSpatialJoinError): def __init__(self, message): self.message = message class", "class NoOverlapSpatialJoinError(Exception): def __init__(self, message): self.message = message # msg:", "overlapping polygons representing geographic features # please how shapefil...
[ "port = 42 s_soket = socket(AF_INET, SOCK_DGRAM) s_soket.bind((ip, port)) print(\"\\nSunucu", "istemciAdres = s_soket.recvfrom(4096) dosyaIcerigi = s_soket.recvfrom(4096) if(os.path.exists(dosyaIsmi.decode(\"utf-8\")) == True): s_soket.sendto(bytes(\"aynisi", "True): dosya = open(dosyaIsmi.decode(\"utf-8\"), \"...
[ "custom_order = [ \"method\", \"url\", \"params\", \"headers\", \"cookies\", \"data\", \"json\",", "Dict]) -> Dict: \"\"\" convert extract list(v2) to dict(v3) Args:", "deprecated argument: --failfast\") args.pop(args.index(\"--failfast\")) # convert --report-file to --html if", "args: logger.warning( f\"gene...
[ "can click-drag a rectangular region to zoom. If you use", "scatter plot\" bg_color=\"lightgray\" #=============================================================================== # # Demo class that is", "bg_color=\"lightgray\" #=============================================================================== # #...
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "= 'ANY' SELENIUM_SERVER = None SELENIUM_PORT = 4444 BROWSER_WIDTH =", "# # Licensed under the Apache License, Version 2.0 (the", "configuration module of webstr selenium tests. This module provides configuration", "comp...
[ "__call__(self, population): chroms_to_mutate = random.sample( population, round(self.chrom_mut_chance * len(population))) for", "gen_mut_chance): self.chrom_mut_chance = chrom_mut_chance self.gen_mut_chance = gen_mut_chance def __call__(self, population):", "chrom in chroms_to_mutate: genes_to_mutate = random....
[ "for i in range(len(chars)): if (i + 1) % 20", "* [0] # For each lowercase letter in the list,", "displayCounts(counts) def createList(): \"\"\"Create a list of characters.\"\"\" # Create", "def createList(): \"\"\"Create a list of characters.\"\"\" # Create an", "counts = 26 * [0] # For each lowercase lett...
[ "you can use the ``Config`` API:: from ddtrace import config,", "To configure the Vertica integration globally you can use the", "# override the service and tracer to be used Pin.override(conn,", "missing_modules: from .patch import patch, unpatch __all__ = [patch, unpatch]", "use the ``patch`` function. No...
[ "/>', ] def __init__(self, data): datadriven.DataDrivenTestCase.__init__(self, data) self.data = data", "OpenIDServiceEndpoint.fromHTML('http://unused.url/', self.data) expected = [] self.failUnlessEqual(expected, actual) def pyUnitTests(): return", "self.data) expected = [] self.failUnlessEqual(expected, actua...
[ "TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) EMAIL_BACKEND", "= get_env_var('EMAIL_HOST_PASSWORD') EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL =", ") EMAIL_BACKEND = 'django.cor...
[ "# df[column_name].max()) if df[column_name].min() < 0 and df[column_name].max() <= 0:", "df.columns states = [] g.attr('node', shape='ellipse') for column_name in column_names:", "def generate_react_flow_chart_from_df(df): column_names = df.columns nodes = {} # Elipses", "edges.append([state, name1, 'one_way...
[ "os.path.exists( filename ) : old_month -= 1 # 調査用に+1してあるので、実際の値は、これにold_monthに-1したものとなる。 break", ": return None #df = pd.DataFrame({ # 'start': [None, None],", "os import json import datetime import pandas as pd from", "break labels.append( m_year + \"/\" + m_month ) fileNameList.append( filename", "base.C...
[ "n, m: (int(end.split(\".\")[n]) - int(start.split(\".\")[n])) * m return calc(0, 256", "(int(end.split(\".\")[n]) - int(start.split(\".\")[n])) * m return calc(0, 256 * 256", "- int(start.split(\".\")[n])) * m return calc(0, 256 * 256 *", "m return calc(0, 256 * 256 * 256) + calc(1,", "256 * 256 * 256) + c...
[ "a bug in adm feature passing scale into dwt_quant_step #", "= cls.get_scores_key('vifdiff_den_scale3') vifdiff_scale0_scores_key = cls.get_scores_key('vifdiff_scale0') vifdiff_scale1_scores_key = cls.get_scores_key('vifdiff_scale1') vifdiff_scale2_scores_key =", "val = None atom_feature_scores_dict[atom_featur...
[]
[ "by susy at 2019/11/8 \"\"\" from dao.dao import DataDao import", "# -*- coding: utf-8 -*- \"\"\" Created by susy at", "-*- coding: utf-8 -*- \"\"\" Created by susy at 2019/11/8", "from dao.models import PanAccounts from cfg import PAN_SERVICE, MASTER_ACCOUNT_ID class", "import pytz from dao.models import P...
[ "value, mask=None): if mask is not None: mask = mask.unsqueeze(1)", "= nn.Dropout(p=dropout) def forward(self, query, key, value, mask=None): if mask", "nn.Linear(d_model, d_model) self.dropout = nn.Dropout(p=dropout) def forward(self, query, key, value,", "2) for l, x in zip(self.linear_layers, (query, key, ...
[ "strategy == \"mh\": print(\"**** \", str(system), \" Job \", str(job),", "help='Suffix (chosen epoch, e.g. 1981)', required=True) parser.add_argument('-j', '--job', help='Job (0/1)',", "elif strategy == \"naive\": print(\"**** \", str(system), \" Job \",", "= argparse.ArgumentParser() parser.add_argument('-s...
[ "cdll lib = cdll.LoadLibrary(\"../target/release/libembed.dylib\") #=> for Mac #lib = cdll.LoadLibrary(\"../target/release/libembed.so\")", "# $ python embed.py from ctypes import cdll lib =", "lib = cdll.LoadLibrary(\"../target/release/libembed.dylib\") #=> for Mac #lib = cdll.LoadLibrary(\"../target/release/l...
[ "local_var_params: body_params = local_var_params['body'] if isinstance(request, SdkStreamRequest): body_params = request.get_file_stream()", "SdkStreamRequest): body_params = request.get_file_stream() response_headers = [] header_params['Content-Type'] = http_utils.select_header_content_type(", "the HTTP reque...
[ "= False, decreasing: bool = False, multi_spikes_threshold: float = .7,", "Improvement Objective'] = (self.diagnostics.loc[ self.iter - 1, 'Objective Function'] -", "after iteration Returns ------- \"\"\" if self.iter == 0: self.diagnostics", "= init_reweighting_prec self.init_reweighting_prec = init_reweight...
[ "g.serialize(format='trix') g3 = ConjunctiveGraph() from StringIO import StringIO g3.parse(StringIO(r), format='trix')", "r2 = URIRef('resource:2') label = URIRef('predicate:label') g1 = Graph(identifier =", "isinstance(q[3].identifier, URIRef): tg=Graph(store=g.store, identifier=q[3].identifier) else: # BNode,...
[ "print \"\\033[35mRevision Updated in the database as %d\\033[0m\" % checkout_revision", "updatelib_inst.updateDatabaseVersion(checkout_version) print \"\\033[35mVersion Updated in the database %s\\033[0m\" % checkout_version", "sinedon import dbupgrade, dbconfig import updatelib project_dbupgrade = dbupgrade.D...
[ "from fightchurn.listings.chap8.listing_8_2_logistic_regression import save_regression_summary, save_dataset_predictions def regression_cparam(data_set_path, C_param): X,y =", "from sklearn.linear_model import LogisticRegression from fightchurn.listings.chap8.listing_8_2_logistic_regression import prepare_data, s...
[ "3*6*16)) #%% [markdown] # ## ACP # Réduction de la", "l in clustering.kmeans_labels] plt.scatter(clustering.pca_reduction[:, 0], clustering.pca_reduction[:, 1], c = col)", "#%% from IPython.display import Image #%% for cl in range(0,19):", "# img = Tools.display_mosaic(image_array, nrow = 10) # fig =", "Zo...
[ "handler_error = logging.FileHandler(os.path.join(this_folder, error_log_file)) # set levels handler_info.setLevel(logging.INFO) handler_error.setLevel(logging.ERROR) #", "'%(message).180s', datefmt='%Y-%m-%d %H:%M:%S') format_error = \\ logging.Formatter( '%(asctime)s %(levelname)s '", "= logging.FileHandler(o...
[ "True, use_propensity = True, test_size = 0) uplift_model.best_params_net y_test, x_test,", "rmse_tolerance = .05 num_obs = 10000 param_grid = dict(num_nodes=[8], dropout=[.1],", "t) def test_prepare_data_optimized_loss_one_col_tmt(self): num_obs = 1000 y, x, t =", "= np.mean((optim_treatments_no_cuttoff_cat=...
[ "y0 = increment(x0) #y0 == 1 self.assertEqual(y0, 1) x1 =", "from example_module import COLORS, increment class ExampleTest(unittest.TestCase): \"\"\" #TODO \"\"\"", "#TODO \"\"\" def test_increment(self): x0 = 0 y0 = increment(x0)", "= 0 y0 = increment(x0) #y0 == 1 self.assertEqual(y0, 1)", "\"\"\" #TODO \...
[ "from django.utils.translation import ugettext as _ from desktop.auth import forms", "+ request.get_host() + '/login/oauth_authenticated/' })) if resp['status'] != '200': raise", "is_first_login_ever = first_login_ever() backend_names = get_backend_names() is_active_directory = 'LdapBackend' in", "exc_info=e)...
[ "= name def get_follow_list(self): return self.follow_list def set_follow_list(self, follow_list): self.follow_list", "== other.get_follow_list() \\ and self.intention == other.get_intention() and self.lane ==", "get_name(self): return self.name def set_name(self, name): self.name = name def", "= intention de...
[ "re.IGNORECASE) def get_url(url, headers=0, gid=0, sheet=None): parts = parse.urlparse(url) if", "headers = int(qs['headers'][-1]) if 'gid' in qs: gid = qs['gid'][-1]", "path = parts.path path = '/'.join((path.rstrip('/'), 'gviz/tq')) qs = parse.parse_qs(parts.query)", "from __future__ import division from __...
[ "len(boxes) == 0 and len(labels) == 0: boxes.append([0, 0, 2,", "self.coco[\"images\"][idx] ) img_path = Path(self.img_folder) / ann_info[\"file_name\"].replace(\".png\", \".jpg\") ann_path =", "= Image.open(img_path).convert(\"RGB\") w, h = img.size if \"segments_info\" in ann_info:", "# Instead of finding b...
[ "middle = left + (right - left) // 2 if", "equals to nth-item \"\"\" if len(array) <= index: return index", "search recursively here if left is None and right is", "0, len(array) - 1 if len(array) == 0: return None", "O(n) because you are returning the function continuously until index", "return middle el...
[ "b, c, dt)) RM.commit() def update_memory(self, a, b): cursor.execute('''UPDATE memory", "into memory (concept, location, person,DATE) values (?, ?, ?, ?)\",", "= ? WHERE concept = ? ''', (b, a)) RM.commit()", "from pattern.en import pprint from pattern.en import parsetree from pattern.en", "(b, a)) RM.comm...
[ "= bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = 10", "# to make the bad region transparent. This is the", "palette.set* lines, you will see # all the defaults; under", "palette.set_under('g', 1.0) palette.set_bad('b', 1.0) # Alternatively, we could use #", "range to which the regular palette color scale is ap...
[ "List, Dict from datetime import datetime class Authenticate(BaseModel): access_token: str", "typing import List, Dict from datetime import datetime class Authenticate(BaseModel):", "import List, Dict from datetime import datetime class Authenticate(BaseModel): access_token:", "validator, Field from typing im...
[ "\"dankmemes\", \"wholesomememes\", \"memes\", \"terriblefacebookmemes\", \"historymemes\", \"me_irl\", \"2meirl4meirl\", \"fellowkids\", \"tumblr\" ]", "requests.get(f\"https://api.reddit.com/r/{chosen_sub}/top.json?sort=top&t=day&limit=500\", headers={'User-agent': 'Super Bot 9000'}) r = r.json() boxed =", "r...
[ "Registry MultiSZ multi_sz = cli.get_reg_multi_sz(r'HKLM:\\SYSTEM\\CurrentControlSet\\control\\SecurePipeServers\\winreg\\allowedExactPaths', 'Machine') # Output Lines self.output", "[r'HKLM:\\SYSTEM\\CurrentControlSet\\control\\SecurePipeServers\\winreg\\allowedExactPaths', ('Machine=')] + multi_sz # Recommended...
[ "MikanException(Exception): \"\"\"Generic Mikan exception\"\"\" class ConversionError(MikanException, ValueError): \"\"\"Cannot convert a", "<reponame>dzzhvks94vd2/mikan class MikanException(Exception): \"\"\"Generic Mikan exception\"\"\" class ConversionError(MikanException, ValueError): \"\"\"Cannot", "class ...
[ "path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), p...
[ "def generate_docker_compose(host, conf_path, extra_vars, extra_vars_file): template = 'template/docker/compose/docker-compose.yml' ansible_arg =", "_to_backup(local_path) show_diff(local_path, backup_path) upload_conf_file(backup_path, host, container, conf_path, relative_to) restart_container(host, container)",...
[ "edit distance computes the cost it takes to get from", "len(source) m = len(target) D = {} # Initialization for", "j in range(0, m+1): D[0,j] = j for i in", "in range(1, m+1): if source[i-1] == target[j-1]: D[i,j] = D[i-1,", "i in range(0, n+1): D[i,0] = i for j in", "computes the cost it takes to get fr...
[ "outfile, threads=1, maxmatch=True): delta = f\"{outfile}.tmp.delta\" delta_1 = f\"{outfile}.tmp.1delta\" subprocess.check_output(f\"rm", ": new_record.POS + len(new_record.REF) ] ) if new_record.CHROM not in", "new_record.POS + len(new_record.REF) ] ) if new_record.CHROM not in vcf_records:", "os.unlink(delt...
[ "-> Dict[str, Any]: return asdict(self) @dataclass(frozen=True) class Contributor: name: str", "model for various reports\"\"\" @classmethod def key(cls: Type) -> str:", "def to_table(self) -> List[str]: return [ 'Pull requests:', '--------------', 'Open", "+ [f'{c.name.ljust(24)}{c.commit_count}' for c in se...
[ "datetime_string = self.get(datum, self.field_name) if isinstance(datetime_string, datetime.datetime): to_compare = datetime_string", "any((self.start, self.end)): return None query_params = dict() if self.start: query_params[\"{}__gte\".format(self.field_name)]", "if query_params: return queryset.filter(**quer...
[ "= reduction self.loss_weight = loss_weight if self.use_sigmoid: self.loss_function = binary_cross_entropy", "diff * diff / beta, diff - 0.5 * beta)", "0 diff = torch.abs(pred - target) loss = torch.where(diff <", "torch.nonzero(labels >= 1).squeeze() if inds.numel() > 0: bin_labels[inds, labels[inds] -", "...