content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def trustRegion(f,grad,hess,subprob,x0,r0,rmax=2.,eta=1./16,gtol=1e-5): """Implement the trust regions method. Parameters: f : callable function object The objective function to minimize. g : callable function object The gradient (or approximate gradient) of the ob...
dfa3fecfff0c85e4594ed955c04fbad302b9c7b1
3,607,300
import inspect def _filter_module_all(path, root, children): """Filters module children based on the "__all__" arrtibute. Args: path: API to this symbol root: The object children: A list of (name, object) pairs. Returns: `children` filtered to respect __all__ """ del path if not (inspect...
9cbc86a6a0321722910fb2f48b8857d5d6488511
3,607,301
def meanValue(arg): """ return the mean value of the argument over its domain :param arg: function :type arg: `escript.Data` :return: mean value :rtype: ``float`` or ``numpy.ndarray`` """ fs=arg.getFunctionSpace() d=fs.getDomain() if fs == escore.Solution(d) or fs == escore.Cont...
699e6af31272f1e1224b17027fe7c85740112277
3,607,302
def ratio_shimenreservoir_to_shimenagrichannel(): """ Real Name: Ratio ShiMenReservoir To ShiMenAgriChannel Original Eqn: Sum Allocation ShiMenReservoir To ShiMenAgriChannel/Sum Allcation From ShiMenReservoir Units: m3/m3 Limits: (None, None) Type: component """ return sum_allocation_s...
e00eb525d5388965377ff5336e15b7830ba09e11
3,607,303
from datetime import datetime def get_object_storage_class_v2(s3_locs, extra_info=False, **kwargs): """ Return the storage class and restoring status of an s3_loc If "extra_info", return a dictionary including creation date, last modified date, and size """ #assert type(s3_locs) == type([]) f...
0aec67e7bb2726a27e6aff54e0eaf659cb1df46f
3,607,304
def contains_pattern(input: str, pattern: str) -> bool: """Check if the `input` contains all signals of the given `pattern`""" assert len(input) >= len(pattern) return all([p in input for p in pattern])
0fd2b5d35145fe21f855358c061995e04ad695a9
3,607,305
def is_CyclotomicField(x): """ Return True if x is a cyclotomic field, i.e., of the special cyclotomic field class. This function does not return True for a number field that just happens to be isomorphic to a cyclotomic field. EXAMPLES:: sage: from sage.rings.number_field.number_field...
2c7d7a10cb15aac1a0e3600986a2fe4a8b83472b
3,607,306
import json def TestActiveTwitterToken(handle): """ Check whether the Twitter token details are valid. """ try: twitterQuery = ( "https://api.twitter.com/1.1/users/show.json?" + "screen_name=" + handle ) T_response, json_string = client.request(twitterQuery) ...
7d6010aa4c629524b57975e73b42198e361a69c8
3,607,307
def verify_no_deny_list_words(file_contents, file_location): """Verify no segments of the file are in the list of denied words.""" error_count = 0 segments = file_contents.split('/') for word in segments: if word in DENY_LIST: logger.error(f"Word '%s' in %s is not allowed.", word, fi...
23a330b480243b6c123f5c329d0b92b88bfec1c1
3,607,308
import pkg_resources import requests from datetime import datetime import json def get_commodity_recent_data(commodity, as_json=False, order='ascending', interval='Daily'): """ This function retrieves recent historical data from the introduced commodity from Investing.com, which will be returned as a :obj...
b48e573c0857d098b86b676cbb0f9b1452f159f9
3,607,309
def _prune_dict_null_str(dictionary): """ Prune the "None" or emptry string values from dictionary items """ for key, value in list(dictionary.items()): if value is None or str(value) == "": del dictionary[key] if isinstance(value, dict): dictionary[key] = _prune...
c6e408f3b3a3d2bafc77fdb1c106bd5ea3a27dbb
3,607,310
import warnings def sample_chain( num_results, current_state, previous_kernel_results=None, kernel=None, num_burnin_steps=0, num_steps_between_results=0, trace_fn=lambda current_state, kernel_results: kernel_results, return_final_kernel_results=False, parallel_iterations=10, na...
75d7c75ae562f0f494dc8348dea0007696cb059b
3,607,311
def d_sigmoid(x): """ Derivative for sigmoid used for gradient calculation """ y = sigmoid(x) return y * (1. - y)
fe2a8ab8debf22bab349a65bfd29cea5a3e0e90d
3,607,312
import requests def get_interacting_proteins_string(protein, num_results=25): """ @Param protein: The name of the protein that you want to generate a list of interacting proteins for. @Param num_results (default=25): The number of interacting proteins that you want to get. @Return: ...
816498d9ecb7bf144bbced55a173fd6da8a5fff4
3,607,313
def add_fill_zone_rounded_rectangle(topleft, bottomright, corner_radius, N=10, layer="F.Cu", linestart=' '): """ Add fill zone In KiCad, click Place > Zone, then right click inside a zone > :param topleft: :param bottomright: :param min_thickness: :param linestart: :return: """ ...
640b49af89c71a249a0020a924e63997cfcf1295
3,607,314
def count_punc(text): """ Count the number of punctuations within the text. Parameters ---------- text : str piece of text to analyze Returns ------- integer the number of punctuations Examples -------- >>> count_punc("Hello, World!") 2 >>> coun...
e08b1973ef693c0fb12608d6303c2c054c6030ae
3,607,315
from typing import Collection from typing import Tuple from typing import List def decode_access_list( access_list: Collection[Tuple[bytes, Collection[bytes]]] ) -> List[Tuple[bytes, Tuple[int, ...]]]: """Decode an access list into friendly Python types""" work_list = [] if not access_list or len(acc...
18d24f3a6f2b8c88ff47383e8586588a00d15905
3,607,316
def exception_to_http_code(exc: Exception) -> int: """Returns a HTTP error code from an exception object. Args: exc (Exception): Exception object Returns: int: Error code """ return exception_type_to_http_code(type(exc).__name__)
2d146bae0303495b7e3578ac3cce31d2409e7621
3,607,317
def doIBDTW(SSMA, SSMB, NThreads = 8, Verbose = False): """ Do isometry blind dynamic time warping between two self-similarity matrices :param SSMA: MXM self-similarity matrix :param SSMB: NxN self-similarity matrix :param NThreads: How many threads to use in parallelization of row compu...
228b284a024ffb49a458e15930ccb5b8213dd303
3,607,318
def lxml_stringify_children(node): """ Returns XML contents of the node :param node: :return: """ return (node.text if node.text is not None else '') + \ ''.join((etree.tostring(child, encoding='unicode') for child in node))
7a2f59565719d90469d6e74c15bfe9e99622b1be
3,607,319
import pickle def grab_training_data(shuffle: bool = False, direc: str = 'data/training/movie_reviews_data.pkl') -> tuple[list]: """ Opens the reviews stored in the pickle file. If shuffle is true that means that we should get the data ready by running shuffle_training_Data """ with open(dir...
c23b36c7571c8d152164f111503caf1f42d5682d
3,607,320
import os import re def skey(a): """ Complex sorting hack: elki > elki-core > elki-* > others """ a = os.path.basename(a) if re.search(r"^elki-[0-9]", a): return (-10, a) if re.search(r"^elki-core-", a): return (-5, a) if re.search(r"^elki-", a): return (-1, a) return (0, a)
f5bc3aceaf018e699b1979fa4eba603a6ea89750
3,607,321
import powerlaw as pl def best_power_law_fit(S, resolution=400, percentile_min=10, percentile_max=99, sigma_threshold=0.05): """Returns best-fitting powerlaw.Distribution object of the data. The built-in optimization routine for the powerlaw package often fails to find the best/most-reasonable fit. This ...
832901a58ca43c6b26e89121f05a92b0b00f574b
3,607,322
def beta_cal(v_command): """βを計算""" # 元論文(アッカーマン) z = np.arctan(tan(v_command[1, 0]) / 2) ## ドリフト有りモデル #lr = 0.2 #L = 0.4 #z = np.arctan(lr / L * tan(v_command[1, 0])) return z
98f3e2ffee92ccdc7bb5b1af8a4fb3a214d61f48
3,607,323
from typing import List from typing import Dict import torch def load_examples( examples: List[Dict[str, torch.Tensor]], tokenizer: RecconSpanExtractionTokenizer, max_seq_length: int = 512, doc_stride: int = 512, max_query_length: int = 512, evaluate: bool = False, output_examples: bool = ...
b13779e187af16863454bf70af987b59c3b02dfb
3,607,324
import types import numpy import pandas def sdc_pandas_series_binop(self, other, level=None, fill_value=None, axis=0): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.binop Limitations ----------- Parameters ``level`...
a608e4ab123fec08f1ae71fd5a4b733d1a5efb5e
3,607,325
def intersectionOfMaskSets(setOne, setTwo): """ from set two from set one :param setOne: :param setTwo: :return: @type setOne: list of dict @type setOne: list of dict """ result = [] for itemOne in setOne: for posTwo in range(len(setTwo)): itemTwo = setTwo[pos...
1acbb21d5cdf94e77f18692b966c7a9cfa45c002
3,607,326
import click def service_option(**attrs): """A --service option for commands.""" kwargs = dict( metavar='SERVICE', required=False, help='Service name.' ) kwargs.update(attrs) option = click.option( '--service', **kwargs ) return option
67e858589117701c5f9f8f375c67803cf9c1a2e9
3,607,327
import logging def return_json(func): """ A decorator that serializes the output to JSON before returning to the web client. """ def convert_to_json(self, *args, **kwargs): return_val = func(self, *args, **kwargs) try: return render_json(utils.to_json(return_val)) except ...
0dc968e49f1914bfbb827169fbea12039a0783a0
3,607,328
import os def EnvArray(): """Returns an env variable array from the os.environ map object.""" return map(lambda k,v: k+"="+v, os.environ.keys(), os.environ.values())
c9b14dcb26a299db597ea35435de7eee2dca703e
3,607,329
def recursive_fibonacci(i, seq=None): """Recursive solution""" if seq is None: seq = [0, 1] if i > len(seq): seq.append(seq[-1] + seq[-2]) return recursive_fibonacci(i, seq) return i, seq[i - 1], seq[:i]
385cac4df9ca3a47ed2968a27601a07cd80e9908
3,607,330
def count_distinct(n): """ Count distinct divisors. >>> count_distinct(180) # 180 = (2*2)*(3*3)*5 3 """ return len(set(get_divisors(n)))
74573c40f36618578e54990400c44062e035faea
3,607,331
def detect_greenthread_environment() -> str: """ Detect the current environment: eventlet, or gevent, or '' for default """ global _greenthread_environment if _greenthread_environment is None: _greenthread_environment = _detect_greenthread_environment() return _greenthread_environment
65b6143c1608fd350e281e1ccfbbbcb69317ebfa
3,607,332
def get_ell_cfft(nx, dx, ny=None, dy=None): """ returns the wavenumber l = \sqrt(lx**2 + ly**2) for each Fourier mode """ lx, ly = get_lxly_cfft(nx, dx) return np.sqrt(lx**2 + ly**2)
e9979df5e278eea286931b96dce541475f4d7f03
3,607,333
def check_dkim(msg_bytes, fromAddr, logger): """ :param msg_bytes: bytes :param fromAddr: str :param logger: logger :return: bool Validate the message (passed as a byte sequence, as that's what the dkimpy library wants). """ d = dkim.DKIM(msg_bytes, logger=logger) valid_dkim = d.ver...
40d392a9726eb30f1c8136d7161245c4f539024c
3,607,334
def reinstate_endpoint(cpid, old_endpoint, next_hop_ips, proc_alias=PROC_ALIAS): """ Re-instate and endpoint that has been removed. :param hostname: The hostname this endpoint resides in :param cpid: The PID of the namespace to operate in. :param old_endpoint: The old endpoint...
f00f7b0887079f962613feb11e271bd99f48d0d5
3,607,335
def main(*argv): """Do the thing""" (prog, argv) = argparsing.grok_argv(argv) argparser = argparsing.setup_argparse(prog=prog, description=DESCRIPTION) _add_arguments(argparser) args = argparser.parse_args(argv) with open(args.version_file, "r") as version_file: current_version = _get_v...
236c5ce71c201a33b19d6d45b75ee86dfd08b708
3,607,336
def ticks_to_distance(ticks: int) -> Real: """ Convert encoder ticks into distance [cm]. :param ticks: Number of encoder ticks. :return: Distance that number of ticks represents [cm]. """ return ticks * WHEEL_CM_PER_TICK
3f288ee6cbcf9cd89379b68a5e7c639485c411f8
3,607,337
def with_podcasts(feeds, update=False): """Looks up podcast associated with result. Adds new podcasts if they are not already in the database""" podcasts = Podcast.objects.filter(rss__in=[f.url for f in feeds]).in_bulk( field_name="rss" ) new_podcasts = [] for feed in feeds: feed....
c35448adf541f97856e2eb43f42157e3f6f4ed65
3,607,338
def load_all_prem_types(country): """ Collate the matrices of different location types for a given country :param country: str Name of the requested country """ matrices = {} for sheet_type in ("all_locations", "home", "other_locations", "school", "work"): matrices[sheet_type] =...
75aef412acc63215dabf2e96d25642809a9d4f84
3,607,339
def SLInt32(name): """signed, little endian 32-bit integer""" return FormatField(name, "<", "l")
ef87be8a1d397dc9daa94b6175ac71c28c498d6e
3,607,340
def team_manager(request, aid): """Manage team members.""" alert = get_object_or_404(Alert, pk=aid) perms = alert.permissions(request.user) student = _student(alert) vitals = student['student'] team = [m.user for m in alert.team.all() if m.status] matrix = [] for c in alert.category.all(...
c29621137ec3ec1c0f9d9b17acf11e6c3d940839
3,607,341
def inception_score(images, num_batches=None): """IS function from tfc Args: images: must be 4-D tensor, ranges from [0, 255] num_batches: Number of batches to split `generated_images` in to in order to efficiently run them through the classifier network. """ batches = images.shape[0] if ...
be241dce6bc538457bcd2670bb3632b8e2d0177b
3,607,342
def build_get200_model_a400_invalid_request( **kwargs # type: Any ): # type: (...) -> HttpRequest """Send a 200 response with invalid payload {'statusCodeInvalid': '400'}. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :ret...
cf524efb45add25daf08718ce0d9508f60af7c40
3,607,343
def get_identifiers_url(db_name, db_id): """Return an identifiers.org URL for a given database name and ID. Parameters ---------- db_name : str An internal database name: HGNC, UP, CHEBI, etc. db_id : str An identifier in the given database. Returns ------- url : str ...
2889bba2519240af5f088c7d126c378d5019cb39
3,607,344
def addSimpleUserFolder(self,REQUEST=None): """Add a SimpleUserFolder to a container as acl_users""" ob=SimpleUserFolder() self._setObject('acl_users', ob) if REQUEST is not None: return self.manage_main(self,REQUEST)
35cc73b8b8182cddf844ab0873979a68f38acb7e
3,607,345
import collections def fol_language(): """Makes a first-order logic language. This has: * Predicate symbols p1, ..., p9, q1, ..., r9. * Constant symbols a1, ..., a9, b1, ..., c9. * Variable symbols x1, ..., x9, y1, ..., z9. Returns: Instance of `Language`. """ def make_symbols(start): ...
0cf4460412ad8cce3d428e60a116cb5d5ecbcb6d
3,607,346
def is_youtube(url: str) -> bool: """Test whether the given URL belongs to one of the recognized YouTube domains.""" host = urlparse(url.strip()).netloc for domain in domains: if host == domain or host.endswith('.' + domain): return True return False
980b420095d52142fe29919bf80ad73127191a1f
3,607,347
def tv_emulator(ev, x, y): """ This emulates a tv-based device, like the OUYA. """ if ev.type == pygame.MOUSEBUTTONDOWN: return None, x, y elif ev.type == pygame.MOUSEBUTTONUP: return None, x, y elif ev.type == pygame.MOUSEMOTION: return None, x, y elif ev.type == py...
724fc758fd16a3c62eab73f783ae5a9b897cdeb6
3,607,348
def mean_f(center, width, sun_range=1., model="STIS"): """Returns the solar F averaged over the bandpass of a "boxcar" filter, given its center and full width. F is defined such that pi*F is the solar flux density. Input: center the center of the bandpass in microns. width ...
a898f76e0f6f0f45cc150ea20567a0762a47cbe0
3,607,349
def strToRange(s): """ Convert string to range """ return [int(i) for i in s.split(',')]
970a3a76d72187808aecafecbdcf35ca21e5f781
3,607,350
def read(filepath): """Reads in the file at the specified location""" hdulist = pyfits.open(filepath) hdulist.verify('silentfix') fits_comment = hdulist[0].header.get_comment() # PyFITS 2.x if len(fits_comment) > 0 and isinstance(fits_comment[0], basestring): comments = [val fo...
81e49f2a93cb24e88c3edf50853ddab3d1490d38
3,607,351
def get_pr_info(lst_lbl, lst_scr): """ calculate PR info; """ rc_pt = np.linspace(0, 1, 1001) rc_pt[0] = 1e-16 prs = [] aps = [] for lbl, scr in zip(lst_lbl, lst_scr): pr, rc, _ = precision_recall_curve(y_true=lbl, probas_pred=scr) aps.append(average_precision_score(y_tru...
72c8e3902c222b30f0efa48fb2a21426dce66691
3,607,352
def nbest_oracle_eval(nbest, n=None): """Return the evaluation object of the best sentence in the nbest list.""" return nbest.oracle_hyp(n=n).eval_
fe7641f6ccbaae7d85f620f4772e3a8b506880f5
3,607,353
from typing import Optional from typing import Iterator from typing import Tuple import sys import attr from typing import Union import math from typing import Deque import inspect from typing import cast def format_task_tree( task: Optional[trio.lowlevel.Task] = None, prefix: str = "", *, color: bool = False ) -...
ef3266fd0d8fe05db4c766f64571e644134d6c25
3,607,354
def _prepare_visible_key_name_for_adapting_to_fe(key_name, key_to_parent_map): """Prepare single key for adapting to frontend. Returns: Dictionary representation of the field that can be handled by the next adaptation method like adapt_non_recursive(), e.g.: { 'field': 'gt_n...
8c66edf19abd9ed43ebd2a34191d3131b105b4ee
3,607,355
def max_pool_forward_reshape(x, pool_param): """ A fast implementation of the forward pass for the max pooling layer that uses some clever reshaping. This can only be used for square pooling regions that tile the input. """ N, C, H, W = x.shape pool_height, pool_width = pool_param['pool_height'], pool_param['po...
3e95afaf9793197d7eebfc0beb1661a74d63c648
3,607,356
import pkg_resources def get_package_location(package): """Return physical location of a package""" try: info = pkg_resources.get_distribution(package) location = info.location except pkg_resources.DistributionNotFound as err: logger.error("package provided (%s) not installed." % p...
1a3dbe1d2425192a67bd3b7b0ed0f22522ee34ad
3,607,357
def rot_euler(v, xyz): """ Rotate vector v (or array of vectors) by the euler angles xyz https://stackoverflow.com/questions/6802577/python-rotation-of-3d-vector :param v: :param xyz: euler angels; tuple of length 3 :return: """ for theta, axis in zip(xyz, np.eye(3)): v = np.dot(np.array(v), expm(np.cross(np...
2bba71264907d7bc8b792b8f380bdb4825807ca9
3,607,358
def box_to_unit_interval_np(arr, space): """ Rescale array values from Box space to the unit interval. This is essentially just min-max scaling: .. math:: x\\ \\mapsto\\ \\frac{x-x_\\text{low}}{x_\\text{high}-x_\\text{low}} Parameters ---------- arr : nd array A numpy ar...
a0650024abc7e6624470d6e0adceb6e2c5425637
3,607,359
from typing import Dict import subprocess def gpu_memory_mb() -> Dict[int, int]: """ Get the current GPU memory usage. Based on https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/4 # Returns `Dict[int, int]` Keys are device ids as integers. Values are memory us...
657f3589ef3a8be1266808c1042972fb7c9d9bdb
3,607,360
def NINJA_data_to_hoft(fname, TDlen=-1, scaleT=1., scaleH=1., Fp=1., Fc=0.): """ Function to read in data in the NINJA format, i.e. t_i h+(t_i) hx(t_i) and convert it to a REAL8TimeSeries holding the observed h(t) = Fp*h+(t) + Fc*hx(t) If TDlen == -1 (default), do not zero-pad the returned ...
81a95e22f735c8f8637cdfbcfcb4727fc881d0c4
3,607,361
from sys import prefix def si_format(value, precision=1, format_str=u'{value} {prefix}', exp_format_str=u'{value}e{expof10}', trailing_zeroes=False): """ Format value to string with SI prefix, using the specified precision. Parameters ---------- value : int, float Input valu...
900fc93a7927944b17aa56e164b0750d30ba920a
3,607,362
def reaction_class_from_data(class_typ, class_spin, class_radrad, class_isc): """ Build a full-class description including the following useful descriptors of the reaction class: typ: type of reaction (e.g., abstraction, addition, migration) spin: whethe...
7ab3b7713c252e4dc3f2f9410d0021f24141a901
3,607,363
def get_day_average_price(fsym, tsym, e='all', try_conversion=True, avg_type='HourVWAP', utc_hour_diff=0): """ Get the current days average price of a currency pair. Args: fsym: FROM symbol. tsym: TO symbol. e: Default returns average price across all excha...
5d5467b056bb6bba10f861d183b3feb380180a5c
3,607,364
import pytato.utils as utils from typing import Union def logical_or(x1: ArrayOrScalar, x2: ArrayOrScalar) -> Union[Array, bool]: """ Returns the element-wise logical OR of *x1* and *x2*. """ # https://github.com/python/mypy/issues/3186 return utils.broadcast_binary_op(x1, x2, ...
5bb60a559231f563d9cf63103fbe56bd26f761c7
3,607,365
def avoir(self): """Make a black and white image of the IR 10.8um channel (320m). Modeled after mpop.instruments.viirs.ir108 """ self.check_channels("M15") data = self["M15"].data range = (-65 + C0, 35 + C0) img = geo_image.GeoImage((data, data, data), self...
83e66a248a8fac381351cdfc6dad6c077284fb3d
3,607,366
import os def finalize_packages_list_as_files(wd: str, pip_tmp_dir: str, files: list): """[summary] Args: wd (str): the lambda python project working directory files (list): [description] """ global _globals logger.info( "starting package finalization as zip in({}) for: {}...
0cfcd8809904958ad53d65d4314a1fec4b6765a1
3,607,367
def build_auth_url(additional_scopes=[], client_id=''): """Create the OAuth URL for the user-approved scopes.""" user_scopes = ['Read & modify playback.'] + additional_scopes scopes = [] for scope in AUTH_SCOPES_MAPPING: if scope['name'] in user_scopes: scopes += scope['scopes'] ...
9231ff04da4f3289ad0e59baac6b7328fa4201c9
3,607,368
import pickle def get_one_hot_encodings(filepath='../data/one-hot.pkl'): """ Gets the one_hot encodings of the verses of the Quran, along with mappings of characters to ints :param filepath: the filepath to the one_hot encoding pickled file :return: """ with open(filepath, 'rb') as one_hot_qur...
f255ba44018ae1d38694ba12ad9e733ac4fb433f
3,607,369
import inspect def has_self_parameter(func): """ Checks whether the given func has a self parameter. :param func: The func to be checked. :return: True if the func has the self parameter. """ func_args = inspect.getargspec(func).args return len(func_args) > 0 and func_args[0] == 'self'
24a1157f87190cbcb19d77f13f018141dfc25ebc
3,607,370
def foo(update: Update, context: CallbackContext) -> int: """Dumb foo func.""" # TODO: временная заглушка update.message.reply_text( 'Временно недоступно', reply_markup=ReplyKeyboardMarkup( keyboard=[ ['Создать игру', 'Вступить в игру', 'Мои игры'], ...
5147f6f725bd4fc8678fe6f22a3283cb009835aa
3,607,371
def otherline_from_line(line_dict, filing_number, line_sequence, is_amended, filer_id): """ http://initd.org/psycopg/docs/extras.html#hstore-data-type """ try: # Some lines have illegal transaction ids -- longer than 20 characters. Truncate those. line_dict['transaction_id'] = line_dict[...
2afe0981de5102d80307bdaa99fae0b42ef90c88
3,607,372
def create_qc(qubits): """Creation of the quantum circuit and registers where the circuit will be implemented. Args: qubits (int): number of qubits used for the unary basis. Returns: q (list): quantum register encoding the asset's price in the unary bases. ancilla (int): qubit that ...
9a50a8e8032e34b9828015c7420806bbe22d16d7
3,607,373
def unique_slug_generator(instance, new_slug=None): """ This is for a Django project and it assumes your instance has a model with a slug field and a title character (char) field. """ if new_slug is not None: slug = new_slug else: slug = slugify(instance.name) if slug in DO...
c01f490d2065b6b5a3897fad9b5394b570fb1dd2
3,607,374
def classifier(density): """Classify rocks with secret algorithm.""" if density <= 0: raise ValueError('Density cannot be zero or negative.') elif density >= 2750: return 'granite' elif density >= 2400: return 'sandstone' else: return 'not a rock'
17eaba4ec43effb7bdb90432fddd55c6f2bf163a
3,607,375
import os import time def SubmitSlurmJob(datapath, outpath, scriptfile, debugfile):#{{{ """Submit job to the Slurm queue """ loginfo("Entering SubmitSlurmJob()", debugfile) rmsg = "" os.chdir(outpath) cmd = ['sbatch', scriptfile] cmdline = " ".join(cmd) loginfo("cmdline: %s\n\n"%(cmdli...
7285e393a0409b83a41eec32e5b244ccdbd14bc1
3,607,376
import pickle def errors(model, Xtest, burnin=500, MC=None, plot=False, thinning=1, returnE=False, loadDict=False): """ """ #xbins = np.linspace(np.min(model.x), np.max(model.x), 200) ybins = np.linspace(np.min(model.y)*1.2, np.max(model.y)*1.2, 500) #Xgrid, Ygrid = np.meshgrid(xbins, ybins) ...
6ac39cb4933cfbe1c4512c200632a87fc93a2799
3,607,377
def draw_masks(ax, img, masks, color=None, with_edge=True, alpha=0.8): """Draw masks on the image and their edges on the axes. Args: ax (matplotlib.Axes): The input axes. img (ndarray): The image with the shape of (3, h, w). masks (ndarray): The masks with the shape of (n, h, w). ...
c343d90ac6d41b5e73cee9d81c5f5b62152d8cfa
3,607,378
from typing import Union from typing import Optional from typing import List def get_operand_or_result( op: Operation, arg_def_idx: int, previous_var_args: int, is_operand: bool ) -> Union[SSAValue, Optional[SSAValue], List[SSAValue]]: """ Get an operand or a result. In the case of a varia...
d0681303641c4c17eb110230fa91f7379bac9b23
3,607,379
def add_noise(prj, ratio=0.05): """ Adds Gaussian noise with zero mean and a given standard deviation as a ratio of the maximum value in data. Parameters ---------- prj : ndarray 3D stack of projection images. The first dimension is projection axis, second and third dimensions a...
b3bc95ae15fd9602ac7126737d5a6818e00463f1
3,607,380
def delete(cm_id, caller_id, user_id): """ Deletes User. For technical and legal reasons only inactive User may be deleted. Other users may only be blocked. @clmview_admin_clm @param_post{user_id,int} id of the User to delete """ user = User.get(user_id) if user.last_login_date or user...
cd80eab295a93f11117f3cf21a20f76d2102c58d
3,607,381
import tqdm import os def load_point_cloud(filename, use_colors=True): """Load point cloud and labels for given dataset Parameters ---------- filename : str Name of the dataset for loading. point_cloud : pypcs.PointCloud Class representing thee point cloud use_colors : bool ...
4f4c38e857d94f2df062d7d5f4439c2310232c08
3,607,382
def get_label(Z, V): """ Transforms Z_arr into the desired form. Also works if data set is not contiguous. """ xlim = Z.shape[0] dict_labels = dict(zip(range(V), range(V))) for i in range(xlim): Z1 = int(Z[i,0]) Z2 = int(Z[i,1]) Z[i,0] = min(dict_labels[Z1], dict_lab...
e51d21a7f3be8a99bc09e309b944ca0478eb8f69
3,607,383
def _decode_and_random_crop(image_bytes: tf.Tensor, image_size: int) -> tf.Tensor: """Make a random crop of image_size.""" bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]) image = _distorted_bounding_box_crop( image_bytes, bbox, min_object_c...
8d3cd868e413d5c1df70dae1162c00e670c1ce39
3,607,384
def read_csv(path_or_buf=None, *args, **kwargs): """ A convenience wrapper for _read_multi() that uses pd.read_csv as the read function. """ return _read_multi( read_function=pd.read_csv, path_or_buf=path_or_buf, *args, **kwargs )
204fb8cd1327be486be52b0b9e2b654eebba37b1
3,607,385
def get_sale_invoice_rows(*args, **kwargs): """ 获取列表 :param args: :param kwargs: :return: """ return db_instance.get_rows(SASaleInvoice, *args, **kwargs)
8f8b927e3d45b126d8dcbac3b4feaf8d35ae284f
3,607,386
def table_description(): """Handle Mysql/Pg vs Sqlite""" # django's mysql/pg introspection.get_table_description tries to select * # from table and fails during initial migrations from scratch. # sqlite does not have this failure, so we can use the API. # For not-sqlite, query information-schema dir...
aaad99b2b2718f5c56e2a0671ae4f5dbfffa94e0
3,607,387
def vap_internalenergy(temp,pres): """Calculate water vapour internal energy. Calculate the specific internal energy of water vapour using the IAPWS-97 formulation. :arg float temp: Temperature in K. :arg float pres: Pressure in Pa. :returns: Internal energy in J/kg. """ g = va...
732d4d12d54ee7a5c4c135791b54219a8b485809
3,607,388
def flatten(lst): """Flatten a nested list lst""" return [i for subl in lst for i in subl]
5835f05ca6b098c096fdb2bbface034a3c3bee26
3,607,389
import pathlib def exists_in_experiment_filestore(path: pathlib.Path) -> bool: """Returns True if |path| exists in the experiment_filestore.""" return filestore_utils.ls(exp_path.filestore(path), must_exist=False).retcode == 0
0896439b0fdd411600a9bcddf59f4714a1d194ca
3,607,390
import random def extract_words(text, word_count): """ Extract a list of words from a text in sequential order. :param text: source text, tokenized :param word_count: number of words to return :return: list list of words """ text_length = len(text) if word_count > text_length: ...
f84f8b4148380d6c6e29dc0742e42481dda2d11a
3,607,391
def process_observation_data(station): """ This function processes the observation data using baseline correction and rotation (if needed) """ # Validate inputs if len(station) != 3: print("[ERROR]: Expecting 3 components!") return False # Reorder components if needed so tha...
daeb79e88ad3b5f0159ad2660b513b5a8f36c257
3,607,392
def subproc_captured_object(*cmds, envs=None): """ Runs a subprocess, capturing the output. Returns an instance of CommandPipeline representing the completed command. """ return xonsh.procs.specs.run_subproc(cmds, captured="object", envs=envs)
01c8bfe1c6a62428b0ac2574d337632108719848
3,607,393
def numeratorC(weight, y_exp, y_pred): """ finds the sums Ti*Pi*wi over the channels. """ return weight*K.sum(K.flatten(y_exp)*K.flatten(y_pred))
c0cd2de21a4268418c2b1e6a9585a7365c0519b3
3,607,394
import os def _find_in_path(path, file): """Find a file in a given path string.""" for p in path.split(os.pathsep): candidate = os.path.join(p, file) if (os.path.exists(os.path.join(p, file))): return candidate return False
297ab3d91aabca5a979e45ea2b1a2595f05fedd6
3,607,395
import xmlrpc def start_vm(client, session, vm, params): """Start a virtual machine. The virtual machine is created if it does not exists.""" if vm['state'] == 'active': return { 'changed': False, 'vm_id': vm['id'], 'actions': [] } actions = [] if vm['state'] is None: vm['id'] = creat...
9cce62511016cba8ddca59a024f8929e1d4c4ad0
3,607,396
def deser(val): """ Deserialize from a string representation of an long integer to the python representation of a long integer. :param val: The string representation of the long integer. :return: The long integer. """ if isinstance(val, str): _val = val.encode("utf-8") else: ...
0a8e486f2cea255c495820f91fa01911b0df4ad3
3,607,397
from typing import List from typing import Optional def get_site_scene( self, connected_sites: List[ConnectedSite] = None, # connected_site_metadata: None, # connected_sites_to_draw, connected_sites_not_drawn: List[ConnectedSite] = None, hide_incomplete_edges: bool = False, incomplete_edge...
ea3ea3caabf253c3d04182b70c5ac47f96b926b4
3,607,398
import json def create_registry(registrydata): """ POST /registries :param registry: :return: """ request_inputs = anchore_engine.services.common.do_request_prep(request, default_params={}) user_auth = request_inputs['auth'] method = request_inputs['method'] bodycontent = request_...
ddc95f57d1e4f46485119b33d88114933b56f65f
3,607,399