content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def getdaydate(Occurrence: str = 'Second', DayOfWeek: str = 'Tuesday', Month: int = date.today().month, Year: int = date.today().year): """ Overivew: return the date for occurrence of a day of the week Description: function returns the date for a giving day of the week and occurrence of givi...
75a1b4ed52b46a3f5414d5ff04166c45e0b206c0
3,612,432
from typing import Match def equalsOp(template, rule, propertyList): """ Process EQUALS operators """ matches = [] for prop in propertyList: actualValue = getProperty(prop, rule) if actualValue.strip() != str(rule.value).strip(): path = prop['Path'] path = path + r...
659b55db4a12ab362afae13b7c895ee2830ad528
3,612,433
def scaling_factor(context, ruler, rulerWidth): """ :type context: HackedContext """ rulerElement = context.driver.simple_find(ruler) rulerPixels = rulerElement.size['width'] scaleFactor = float(rulerPixels) / float(rulerWidth) return scaleFactor
5af9410879566b36a7a4d734c633d62cdcbddb7e
3,612,434
def to_bytes(string, encoding="utf-8"): """ Converts the given object to binary object, bytes (Py3) or str (Py2). :param string: The string like object to convert to bytes :type string: ``object`` :param encoding: The encoding to encode the string with. :type encoding: ``str`` :returns: The...
0285af78a56997994d3613322897be728f17ec0d
3,612,436
def makeVBClass(cls, init=None): """Returns the text of a VB class file wrapping the specified class If provided, then the init parameter is used as the initializer for the class so that you can link to the real Python object """ vb = [] # Build up as list and then .join it later # # Get t...
a773665ebe2a5d67e350ecd2a90cbe5a93bfe514
3,612,437
from ooiservices.app.uframe.status_tools import get_uid_digests, uid_digests_cache_update def new_compile_assets(data, compile_all=False): """ Process list of asset dictionaries from uframe; transform into (ooi-ui-services) list of asset dictionaries. """ info = False # Log missing vocab it...
6540b1ba7568fc72c65d124cf0c03c01b21f0d8f
3,612,438
def quat_delta(dalpha): """ Form quaternion from small angle rotation vector dalpha """ half_norm = 0.5 * norm(dalpha) scalar = cos(half_norm) vector = sinc(half_norm) * 0.5 * dalpha dqw = scalar dqx, dqy, dqz = vector dq = np.array([dqw, dqx, dqy, dqz]) return dq
37c09c6a141db169f479ed9f98e8537ba72d3bf9
3,612,439
def cluster_main_stats(sparkdf, src="src", dst="dst", cluster_id_colname="cluster_id"): """calculate diameter / transitivity(GCC) / triangle clustering coefficient LCC / square clustering coeff Args: sparkdf: imput edgelist Spark DataFrame src: src column name dst: dst c...
60d006d6a9a58442dd072dea67e853b98d0f2a18
3,612,440
from tensorflow.keras.models import load_model, Model def build_keras_model_front_v2(path_to_keras_model, idx_to_target_w = -1): """ idx_to_target_w = to which layer (default = -1 (the last one)) - 1 """ idx = 0 loaded_model = load_model(path_to_keras_model) front_layers = loaded_model.layers[:idx_to_target_w...
195339116ae3137fbd26f52d3adf48ea857e030e
3,612,443
def center_margin_bb(bb, img_bounds, margin=0.25): """create new bounding box with input margin""" bb_size = ([bb[0, 2] - bb[0, 0], bb[0, 3] - bb[0, 1]]) margins = (np.max(bb_size) * (1 + margin) - bb_size) / 2 bb_new = np.zeros_like(bb) bb_new[0, 0] = np.maximum(bb[0, 0] - margins[0], 0) bb_ne...
03c1f1fe5200bc0a57ee777acc9a065ccb73a5dd
3,612,444
def multi_fidelity_optimize( vocs, evaluate_f, budget=1, processes=1, base_cost=1.0, **kwargs ): """ Multi-fidelity optimization using Bayesian optimization This optimization algorithm attempts to reduce the computational cost of optimizing a scalar function through the use of many low-cost approxi...
ce431c258204ebcf916f65218c5b0c9c1cbe0707
3,612,445
def unique_filename(filename, upload_id): """Replace filename with upload_id, preserving file extension if any. Args: filename (str): Original filename upload_id (str): Unique upload ID Returns: str: An upload_id based filename """ if "." in filename: return "."...
04602532627d8557436c27f2e7d8165f638ed155
3,612,448
def parse_object(*args): """ 将查询到的结果转换为需要的结构 :param args: :return: """ results = [] for cond in args: result = {'OPEN_ID': cond.OPEN_ID, 'OBJECT_ID': cond.OBJECT_ID, 'OBJECT_NAME': cond.OBJECT_NAME, 'OBJECT_CLASS': cond.OBJECT_CLA...
be4bd26cca7dd50ed7ba66d814c0d3326d42ab73
3,612,449
def filter_ec2(tagName, ec2Name, env): """Filter EC2 Instances by Tag""" ec2_list = [] ec2 = boto3.client('ec2', region_name=env.get('region')) instances = ec2.describe_instances( Filters=[ { 'Name': tagName, 'Values': [ec2Name] } ]...
17f084b8c65b1ed0844cce939e2356e377c880a2
3,612,450
def do_roll(u): """ Actually do a 'roll' and updating global (secret) z """ global z z = [update(val) for val in z] r = [(((z[i] - 1) * x_coe[i] + u[i]) % 14) + 1 for i in range(NUM_CARDS)] return r
0ba2e23befc99efc1d9ca1a0337e868800d3b857
3,612,451
def pseudo_nm_tmatrix(markovian_tmatrix, stateA, stateB): """Obtain a pseudo non-Markovian transition matrix from a Markovian transiton matrix The pseudo Markovian matrix has a shape of (2 n_states, 2 n_states) """ check_tmatrix(markovian_tmatrix) n_states = len(markovian_tmatrix) # pseudo no...
4ac69b686694b822127d2a989b47e1d993f35122
3,612,452
def translate(img, x, y): """ Translates the given image. :param x: distance to translate in the positive x-direction :param y: distance to translate in the positive y-direction :returns: the translated image as an numpy array """ M = np.float32([[1, 0, x], [0, 1, y]]) return cv2.warpAffine(img.reshape(28,28),...
4209839032d8b0b2dce9557c0ad1b1a5b9317df2
3,612,453
def get_parent(graph, loc=None, exp=None, attr=None): """ Query syntax at start of expression: .. Selects the parent of the current node :param graph: (sub)graph instance to search :param loc: path location identifier :type loc: :py:str :param exp: expression to query for in...
3ab6ed2775feec96c9a14c7036609a10e3c59bd1
3,612,454
def htmlstriptags(*args): """ .. function:: htmlstriptags(str, default_tag_conversion) Strips the html tags of input. It also converts "<br>" tags to new lines. If a default_tag_conversion is provided then tags that would have been erased are converted to *default_tag_conversion*. Examples: >...
ed38d269f53a4665ab2f8983958f5ba5b787a87f
3,612,456
def rtc_runner(rtc): """ :type rtc: pbcommand.models.ResolvedToolContract :return: """ return gather_run_main(chunk_json=rtc.task.input_files[0], chunk_key=Constants.CHUNK_KEY, gathered_fn=rtc.task.output_files[0], ln_n...
04aacffbabf99befd67ff80c0e27e531dacb50ae
3,612,457
from typing import Iterable def check_and_prepare_sources(source): """ Check source type and return source(s) as a list :param source: single source or list of sources :return: list of sources based on provided source(s) """ source_ok = True if isinstance(source, Iterable)...
c7f2a104c2eca06040a0d67304170b9433247655
3,612,458
import ctypes def streamBurst(handle, numAddresses, aScanList, scanRate, numScans): """Initializes a stream burst and collects data. This function combines eStreamStart, eStreamRead, and eStreamStop, as well as some other device initialization. Args: handle: A valid handle to an open device. ...
495f34a89a54b5e69e428b29169f96f005f0740f
3,612,459
import traceback import requests def get_server_logs(hostname, instance_id): """ Get server logs for specified host and instance. """ host = get_host_by_hostname(hostname) if not host: return None if host['uri']: try: r = requests.get("%s/servers/%s/logs" % (host['...
b76777d90d01963bc8c67885cf9411a12428648a
3,612,460
def __to_pplot(p): """ Change Particle to pplot so that crossing 0-degree line can be plotted. Parameters ---------- p: Particle A given Lagrangian particle. Returns ------- re: tuple of particle and cross0 Particle after LON being modified and whether it crosses 0-degr...
ad343758e137cf6e6b3bd9ec8264c4833857807f
3,612,461
def ror (endv, iv): """ This capital budgeting function computes the rate of return on an investment for one period only. iv = initial investment value endv = total value at the end of the period Example: ror(100000, 129,500) """ return (endv - iv)/iv
43a1339d45725a5e04fd809a6cfb708b6b49b829
3,612,462
import torch def cov(x): """ https://en.wikipedia.org/wiki/Covariance_matrix """ E_x = x.mean(dim=1) x = x - E_x[:, None] return torch.mm(x, x.T) / (x.size(1) - 1)
ff4c5d3f90569f8c1a2d9a1ea9679079fb72b681
3,612,463
def ParseOptions(argv, docstring, extra_opts="", extra_long_opts=(), extra_option_handler=None): """Parse the options in argv and return any arguments that aren't flags. docstring is the calling module's docstring, to be displayed for errors and -h. extra_opts ...
dc0f5574f2ba4d442cbbaca702f14b3ca1d90668
3,612,464
def one_configuration_row(): """ ConfigurationRow """ return [ ConfigurationRow( id=100, name="Product 1: Feature 1", product="testproduct1", features='{"feature1": 1}', license_servers=["flexlm:127.0.0.1:2345"], license_ser...
ddb8af6adc76cca4954d75fffe2b45b8f7a69140
3,612,467
def atan(x, f=None): """ Computes trigonometric inverse tangent, element-wise. The inverse of tan, so that if y = tan(x) then x = arctan(y). :param x: Input array. :type x: array :param f: Machine learning framework. Inferred from inputs if None. :type f: ml_framework, optional :return:...
d1ced7d17c22fc5a60e7db71d9e0fab81be3bfb1
3,612,468
def butter(cutoff, fs, btype="low", order=4): """Return Butterworth filter coefficients. See scipy.signal.butter for a more thorough documentation. Parameters ---------- cutoff : array Cutoff frequency, e.g. roughly speaking, the frequency at which the filter acts. Units should be s...
febbdf7ecf7146c265d773edb1c4c9fbf39afef7
3,612,469
def is_dimensionless(quantity_or_unit: QuantityOrUnit) -> bool: """ Check wheter a quantity or unit is dimensionless. Parameters ---------- quantity_or_unit : QuantityOrUnit A quantity or a unit Returns ------- bool Whether the quanti...
eebc6c2edf02d370b3b14b7c936b223b1aa70dcb
3,612,470
def count_lines(filename): """Returns the number of lines of the file :obj:`filename`.""" with tf.io.gfile.GFile(filename, mode="rb") as f: i = 0 for i, _ in enumerate(f): pass return i + 1
5dea14a967299c8343756093588bd46d3e186207
3,612,471
def _build_transformer(gin_function): """ Makes a session and a default graph, loads the simple graph into it, and then calls gin_function(session) to build the :py:obj:`TFInputGraph` object. Return the :py:obj:`TFTransformer` created from it. """ graph = tf.Graph() with tf.Session(graph=gra...
a0b98c5d6b00206cc683e4a8e8405421f047d18e
3,612,472
def forecast_starter(seq, past, dim_in): """prepares the staring vector for RNN forecast :param seq: the sequence from which the beggining is used as the forcast starter :param past: the number of considered steps in the past :param dim_in: the dimensionality of the data fed to the network :returns: starter inpu...
8cd572afead804d1900cedcb5dcecbe2e468ee7a
3,612,473
def _get_single_osc(centers, powers, bws, osc_low, osc_high): """ Searches for an oscillations of specified frequency band. Returns a single oscillation in that band. Helper function for osc_per_vertex in MegSubj. Parameters ---------- centers : 1d array Vector of oscillation centers. ...
04691f21ca1721b9008d312f1283c0885f147564
3,612,474
def list_property_flags(flags): """Return list of PROPERTY_FLAG strings from flag number.""" return [k for k, v in Lucam.PROP_FLAG.items() if v & flags]
13b42c94aace2d678ff524fea5587fd12526f079
3,612,475
from typing import List from typing import Type import re def union_func_name(prefix: str, union_args: List[Type]) -> str: """ Generate a function name that contains all union types * `prefix` prefix to distinguish between serializing and deserializing * `union_args`: type arguments of a Union >...
a8f1201bccee0cdc35db5e9861538fb6c7210f0d
3,612,476
def create_line(data): """ Convenience function to create a new line chart with the right args """ return Line(data, x='year', y=countries, legend=True, width=1400, height=300, ylabel='Energy use per capita', palette=['purple', 'green', 'blue', 'pink'])
930b52784a00aacd3d0e2fa981801821358af49f
3,612,477
import time def slow_subtractor(a, b): """Return a minus b.""" time.sleep(5) return a - b
6420ad990ef3d7ebbe6f43832ae306a49a65f971
3,612,478
def _convert_image(data, mask=None): """ Convert the input data to a float64 (double) `numpy.ndarray`, required for input to `skimage.measure.moments` and `skimage.measure.moments_central`. The input ``data`` is copied unless it already has that `numpy.dtype`. If ``mask`` is input, then ma...
1f472dcb697bb6936445ebefd31ae6813731a433
3,612,479
import torch def concatenate_list_of_dict(list_of_dict) -> dict: """ Concatenate dictionary with the same set of keys Args: list_of_dict: list of dictionary to concatenate Returns: output_dict: the concatenated dictionary """ # check that all dictionaries have the same set of...
e38837d9e55cc17715bf988b585c3f4f371f7398
3,612,480
def get_task(request): """ 取出所有任务类型信息 :param request: :return: """ try: res = Task.objects.get_task(1) # 调用search_host接口 return res # 返回json数据 except Exception as e: return_dic = { "result": F...
64000dd312dd428fd03c665e6317339891eab9c6
3,612,481
import math def degrees(input): """Convertir a grados Función para convertir una entrada en radianes a grados. Args: input(Number): valor real Returns: Number """ return (180*input)/math.pi
30377bb8c135dcc8fab2d23ee3703c89f5d772cb
3,612,482
import random async def getrolenamed(role: str, guild: discord.Guild, create: bool = False, exact: bool = True): """ Returns a role inside a Guild based on a given name. :param role: The role to be gathered. -> str :param guild: The guild to retrieve the role from. -> discord.Guild :param create: ...
6744b0857f0bd4ea91d65e897c748d07aecacb76
3,612,484
def get_head_commit(current_branch=None): """Gets the commit hash of HEAD in the given branch. Args: current_branch: String; containing the name of a branch. Defaults to None and in this case is replaced by a call to get_current_branch. Returns: 40 hexadecimal characters contai...
c369d8be82e32bce5f5c0f14094078c50b75e6c2
3,612,485
from typing import Set from typing import OrderedDict def _collect_format_strings(zones_map: ZonesMap) -> IndexMap: """Collect the 'formats' field and return a map of indexes.""" short_formats: Set[str] = set() for zone_name, eras in zones_map.items(): for era in eras: format = era['fo...
9be77be17e8b0fea4e9be9610f81173cd7b63858
3,612,486
def lognormal(a, f): """ A lognormal distribution Parameters ---------- a : ndarray(3) * a[0] : the natural logarithm of the Gaussian amplitude * a[1] : the natural logarithm of the center of the Gaussian * a[2] : the width of the Gaussian in units of natural logarithm o...
ff64280e6e3a6955b9c80528eda127517f2e4ab9
3,612,487
def init_pose(pred_Rs, init_pose, weights=None): """ Should stay close to initial weights pred_Rs is N x 24 x 3 x 3 init_pose is 72D, need to conver to Rodrigues """ init_Rs = batch_rodrigues(tf.reshape(init_pose, [-1, 3])) init_Rs = tf.reshape(init_Rs, [-1, 24, 3, 3]) RRt = tf.matmul(in...
f63a2c78d40416d19e4caa95c54f4a1bceccbd48
3,612,488
from typing import List import glob def get_manifest_list(manifests_dir: str) -> List[str]: """Get a list of manifest files from the manifest directory.""" yml_endings = ["yml", "yaml"] manifest_list = [] for yml_ending in yml_endings: manifest_list += glob.glob(f"{manifests_dir}/**/*.{yml_en...
0dc951cf08870c639735e24b048a41fb7ab6ea52
3,612,492
def render(root: MdastNode) -> str: """Convert MDAST to CommonMark compliant HTML.""" return MdastToHtmlTransform()(root)
37a0859b1ac6a7d9e984c4c3f9fe5a466dae38cf
3,612,494
def interpolateNDMinTimeLinear(x0, x1, vmax, amax): """interpolateNDMinTimeLinear(doubleVector x0, doubleVector x1, doubleVector vmax, doubleVector amax)""" return _motionplanning.interpolateNDMinTimeLinear(x0, x1, vmax, amax)
7ee459f1f55be0d0c9db2cbdeb7a4fbf919aadc2
3,612,495
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up config entry.""" def get_sensor_description(type_string: str): if (description := SENSOR_TYPES_DICT.get(type_string)) is None: return Binary...
c274bf74f58d3a403bfaf5876e13b4b915addf29
3,612,496
def slack_channel_lookup_error(err): """'None' or 'Multiple' results were found during a ``one()`` query for :class:`jackalope.database.models.SlackChannel``. """ current_app.logger.exception(err) return err.message, 404
03ee30a9f6bfb0124fcb9a8a587d14921f7b4032
3,612,497
def actor_lookup_email(api_user, email): """ Lookup an actor based on an email address, useful for determining if an email address is available PARAMETERS: email - email alias RETURNS: actor_ref """ query = Relation.gql("WHERE target = :1 AND relation = 'email'", email) for rel_...
3984d4eb18147b163ed1aa8702c84fc13f3a2474
3,612,498
def load_user(user_id): """ Loads current user data --- """ return User.query.filter_by(id=user_id).first()
9427193ac8fae1554a10d89356959bb20ccafbf4
3,612,499
def load_image(raw_path): """ Function loads images from a list of file paths into ndarrays Params: ------- raw_paths (str) -- Paths to the image files """ # Iterate through each path in list, load image, and store in an array start = raw_path.find(FOLDER) suffix = raw_path[start:] img_path = DATA_DIR + '/...
c4dcd1896406c12f0914c8507c8a465cddbf2c18
3,612,501
def hp_qloguniform(min, max, q): """ Quantized log uniform (base 10) distribution with a quantum of q, bounded by min and max. Returns a value like round(exp(uniform(low, high)) / q) * q. :param min: Exponent of the minimum value in base 10 (e.g., -4 for 0.0001). :param max: Exponent of the maximum va...
b6d250e29f63c6bf5d621c88e408c85b9446d505
3,612,503
def display_account(): """ function to display existing account """ return User.display_account()
80e77505df1c663028228e1282dd96e70b93e29c
3,612,504
def mols_to_pngs(mols, basename="test"): """Helper to write RDKit mols to png files.""" filenames = [] for i, mol in enumerate(mols): filename = "BACE_%s%d.png" % (basename, i) Draw.MolToFile(mol, filename) filenames.append(filename) return filenames
7fa9079a083a396acdac9c784b085bf6824528d7
3,612,505
def create_game(): """Post a new game result to the database.""" game = validate_game_submission(request.headers, request.json) db.session.add(game) db.session.commit() print("New game: %s " % str(game)) return jsonify(game.to_dict()), 201
5468c35556c2976134c7b0ac857d4832e51f7d24
3,612,506
def rep1(arg): """ Matches one or more occurrences of 'arg'. """ assert isinstance(arg, ContentModel) arg.quant = ContentModel.QUANT_PLUS return arg
69147eaac824a5d53832d3b5233fb845f42a52d4
3,612,507
import re def _search_host(host=None, domain=None, username=None, password=None, **kwargs): """Find invalid customer routes received by host.""" result = [] driver = napalm.get_network_driver("ios") try: with driver(hostname="{}.{}".format(host, domain), us...
42b784b334435d24ff39aa53099ac3ab6c416deb
3,612,508
import scipy def wilcoxon(x,y): """ One-sided wilcoxon sign-rank test. p-value is small if \EE x >> \EE y. """ d = np.array(x)-np.array(y) d = np.compress(np.not_equal(d,0), d, axis=-1) n = len(d) inds = np.argsort(np.abs(d)) sign_diff = np.sign(d) W = np.sum([sign_diff[inds[...
e839bb205a294f2227b0dc400351921bc289d982
3,612,509
from typing import Iterable from typing import Sequence def bucket( nodes: Iterable[BaseNode], contraction_order: Sequence[network_components.CopyNode] ) -> Iterable[BaseNode]: """Contract given nodes exploiting copy tensors. This is based on the Bucket-Elimination-based algorithm described in `arXiv:q...
be5f2e1683886a5a09118df6e0316148fcd37be8
3,612,510
def contains_charset(s: str) -> bool: """Judge if given str is a valid charset name, return a boolean. The str could be charset name like 'utf-8' and the code page number like '65001'. Letter case ignored.""" return EncodingInfo._all_charsets_lower_cased_name.__contains__(s.lower())
57637e0161ac9b8a0a043dfd10ead799f95eec44
3,612,511
def prioritize_file_types(k): """ Give a proper priority to certain file types when sorting """ # BN databases should always go first if k.endswith('.bndb'): return 0 # Definition files matter more than raw files if any(k.endswith(e) for e in ('.def', '.idt')): return 5 return 10
97bb9f0257c81d0640c45961c8fd68fe2e1eaee2
3,612,512
def cvar_importance_sampling_biasing_density(pdf, function, beta, VaR, tau, x): """ Evalute the biasing density used to compute CVaR of the variable Y=f(X), for some function f, vector X and scalar Y. The PDF of the biasing density is q(x) = [ beta/alpha p(x) if f(x)>=VaR [ (1-b...
8ad888bf1445fd4666385938b1f2e1125e30eeb2
3,612,513
import numbers def transforms_treeleaffeaturizer( data, predictor_model, output_data=None, model=None, suffix=None, label_permutation_seed=0, **params): """ **Description** Trains a tree ensemble, or loads it from a file, then maps a numeric ...
e28f90be69a862a058f802abb46b16c0e77e0497
3,612,516
from sage.functions.other import imag_part def _sympysage_im(self): """ EXAMPLES:: sage: from sympy import Symbol, im sage: assert imag_part(x)._sympy_() == im(Symbol('x')) sage: assert imag_part(x) == im(Symbol('x'))._sage_() """ return imag_part(self.args[0]._sage_())
5dd609581d542205676acbe038e38c47eaa3828a
3,612,517
async def fetch(url: str, session: network.Session) -> Comment: """ Asynchronously fetch a single comment to a deviation. Args: url: The URL to a comment. session: A session to use for requesting data. Returns: A single comment. Raises: BadCommentPageError: If inst...
0f941ffa7f08897aa3ba9d34876597a3bcc2dc0b
3,612,518
from typing import Optional from typing import Iterable from typing import Any def updater_fields( fields: Optional[Iterable[str]] = None, null_fields: Optional[Iterable[str]] = None, updater_flag_preffix="update_", **kwargs: Any, ) -> dict[str, Any]: """ Prepares the specified fields in **kwa...
2f205aa8c94522a3cb82e63f3bbcb45df7fe11cf
3,612,519
def reduce_angle(angle: Real) -> float: """ Move angle in radians to range (-π, π] """ if -PI < angle <= PI: return angle n = angle / TWOPI n = ceil(n) if n < 0 else floor(n) return angle - n * TWOPI
8f02b1deba4ad729f4db20fc36b14bd7093773a2
3,612,520
def getATR(reader): """Return the ATR of the card inserted into the reader.""" connection = reader.createConnection() atr = "" try: connection.connect() atr = smartcard.util.toHexString(connection.getATR()) connection.disconnect() except smartcard.Exceptions.NoCardException: ...
3a690d1a4ddc9e8af70865511b76bab251984c7d
3,612,521
def create_cnn_model(size_output=None, tf_print=False): """ create keras model with convolution layers of MobileNet and added fully connected layers on to top :param size_output: number of nodes in the output layer :param tf_print: True/False to print :return: keras model object """ if s...
67fd4b7ddef1cfd444993aa8a17a5ae13822f141
3,612,522
def get_vertex_ids(g, my_query, my_query_annot_field, row_or_col): """ Extract vertices with the values in my_query in my_query_annot_field. If row_or_col is "row", my_query will only be searched for in row vertices. If row_or_col is "col", my_query will only be searched for in column vertices. If row_o...
dc93142c4a7b33e950a8f238647809964bb288b0
3,612,523
def data_preparation_fr(country_attributes,reversed_dates=True): """ Creates an sorted dictionary of dates, new cases and tests for the French Covid-19 data Parameters ---------- country_attributes : dict A dictionary containing country attributes reversed_dates : bool A boolean...
a8e333185294dec5bed3238da3b08550f4cb8dbd
3,612,524
import types import ast def get_segment_from_frame(caller_frame: types.FrameType, segment_type, return_locs=False) -> str: """Get a segment of a given type from a frame. *NOTE*: All this is rather hacky and should be changed as soon as python 3.11 becomes widely available as then it will be possible to g...
3cf1c461611e5583ca588c0fbd326889e8d3d747
3,612,525
def distribute_mpi_all(dimension, mpi_comm=MPI.COMM_WORLD): """ Computes the start indexes and bin sizes of all splits to distribute computations across an MPI communicator. Parameters ---------- dimension : int the size of the array to be distributed mpi_comm : mpi4py.MPI.Comm, opt...
a5a1c404460927ff15e1026e29bbc07330ebea1f
3,612,526
def gradient_cmap(colors, nsteps=256, bounds=None): """Return a colormap that interpolates between a set of colors. Ported from HIPS-LIB plotting functions [https://github.com/HIPS/hips-lib] """ ncolors = len(colors) # assert colors.shape[1] == 3 if bounds is None: bounds = np.linspace(...
01cf002e041b90abc90e1400fcc03b6375cdc4e5
3,612,527
def confounder_ppca(X, latent_dim, holdout_portion): """ Function to estimate a substitute confounder using PPCA. Adopted from the deconfounder_tutorial.ipynb https://github.com/blei-lab/deconfounder_tutorial Args: X: A numpy array or pandas dataframe of the original covariates d...
70a31c1942ce3db50a95b0eae781493c6d4ab77e
3,612,529
from typing import Tuple import shutil def create_job(user_folder: str, user_id: str, upload_file: str) -> Tuple[str, str, str]: """Upload several files and check they are properly created - utils method.""" file_service.setup_jobs_result_folder(user_id=user_id, job_id='test-job') job_run_folder = join(us...
be02f87bdab1a2ba256a68c9d37f8f05c2728884
3,612,530
def get_vserver(svm_cx, vserver_name): """ Return vserver information. :return: vserver object if vserver found None if vserver is not found :rtype: object/None """ vserver_info = netapp_utils.zapi.NaElement('vserver-get-iter') query_details = netapp_utils.zapi.NaElement.cre...
ae5972ea2c3ba354b9ee4589633b53839a0399b7
3,612,531
def saveData(dataset={}, filepath= 'defaultFilePath'): """ Saves the 'DATA' component of a dataset as an ascii file in XAYAcore graph format. """ return xayacore.writeGraph(dataset['DATA'], filepath)
3d73f492014861f2b3b488a638285813bdeca31a
3,612,532
def _move_cols_to_front(data: pd.DataFrame, column_count: int = 1) -> pd.DataFrame: """ Move N columns from end to front of DataFrame. Parameters ---------- data : pd.DataFrame The input DataFrame column_count : int, optional The number of columns to move (the default is 1) ...
ee03bbfa24d06aab1a6f2d5c987a2e11c58cdafd
3,612,533
def qual_vector(qual=None, capBQ=45, minBQ=0.25): """convert the base call quality score to related values for different genotypes http://emea.support.illumina.com/bulletins/2016/04/fastq-files-explained.html https://linkinghub.elsevier.com/retrieve/pii/S0002-9297(12)00478-8 @Note The parameter "q...
42f8f4f3c038aa11a96683983cb220f710617e8b
3,612,534
def load_runner( tag: t.Union[str, Tag], *, predict_fn_name: str = "predict", device_id: str = "CPU:0", predict_kwargs: t.Optional[t.Dict[str, t.Any]] = None, resource_quota: t.Union[None, t.Dict[str, t.Any]] = None, batch_options: t.Union[None, t.Dict[str, t.Any]] = None, model_store: "...
1d7a8b4c12990d33c2d7d99d05c3843f35476ee0
3,612,535
def random_uuid() -> str: """description of random_uuid""" return str(uuid4())
b23c6a9f180f757af6a484ba91a0d9b6a820dc3d
3,612,536
def _parse_see_args(dev_id, data): """Parse the payload location parameters, into the format see expects.""" kwargs = { 'gps': (data[ATTR_LATITUDE], data[ATTR_LONGITUDE]), 'dev_id': dev_id } if ATTR_GPS_ACCURACY in data: kwargs[ATTR_GPS_ACCURACY] = data[ATTR_GPS_ACCURACY] if...
fb159ef6dee3a42ae433262382d5ddca87c7bf6b
3,612,537
def _updateStartTimes(srow, delayDF, temkey): """ Update the starttimes to reflect the values trimed in alignement """ statsdict = srow.Stats sdo = srow.Stats for key in sdo.keys(): temtemkey = temkey.loc[temkey.NAME == key].iloc[0] delaysamps = delayDF[delayDF.Events == key].ilo...
b72754a57eae43442b9f0f2df796b7128c36ee8b
3,612,538
def playlist_detail(playlist_id, limit=1000): """ 根据歌单id获取歌单的详情 Args: playlist_id: limit:最大歌曲数为1000 """ for i in range(retry_times): try: base_url = 'http://music.163.com/api/playlist/detail?id=%s&limit=%s' % (playlist_id, limit) res = requests.get(ba...
ea7c5e747186bef78e8346255ffbf4b41c85909f
3,612,539
def checksum(s, m): """Create a checksum for a string of characters, modulo m""" # note, I *think* it's possible to have unicode chars in # a twitter handle. That makes it a bit interesting. # We don't handle unicode yet, just ASCII total = 0 for ch in s: # no non-printable ASCII chars, including space...
836e0f36ed3d87db8d3f2420230eb4f3f5d4d94c
3,612,540
def vol_std(data): """ Return standard deviation across voxels for 4D array `data` Parameters ---------- data : 4D array 4D array from FMRI run with last axis indexing volumes. Call the shape of this array (M, N, P, T) where T is the number of volumes. Returns ------- std_...
64a031026d609ca759634308e1f70c4c24c34cb9
3,612,542
def parse_component_arg(parser, storage: Storage, component: str): """Wrapper around parse_storage_component() to parse CLI arguments into patch elements""" try: component = parse_storage_component(storage, component) except ValueError: parser.error(f"invalid component: {component}") if ...
f3e4764354c5c5f1c6e0574259cc5fce963d1a2b
3,612,543
from typing import ChainMap def parse_flags(flags={}, preset="", **other) -> "int": """ Optimised for "parse_flags(**settings)" use-case, returns a flags integer suitable for view.add_regions. """ preset = presets[preset].get("flags", {}) orsum_flags = 0 for flag_name, active in ChainMap(flags, preset, dict....
8a1dac9dd330ab583a0a16a42c78d7a4c7360ccd
3,612,544
def _get_uniprot_id(agent): """Get the Uniprot ID for an agent, looking up in HGNC if necessary. If the Uniprot ID is a list then return the first ID by default. """ up_id = agent.db_refs.get('UP') hgnc_id = agent.db_refs.get('HGNC') if up_id is None: if hgnc_id is None: # I...
f59b19f86a2d8d48fa271f64892ec7453c98ec9e
3,612,546
def adv_rk2(y, t, dt, scratch1, scratch2): """Advance the solution one step using the 2nd order R-K method""" n = len(y) scratch1 = rhs(y, t) for i in range(n): scratch2[i] = y[i] + dt*scratch1[i] t2 = t + dt scratch2 = rhs(scratch2, t2) for i in range(n): y[i] = y[i] + 0.5*d...
3ee8051c08fcdb78715a20e0a6e90334e6054ac6
3,612,547
from pathlib import Path def retrieve_token() -> str: """Retrieves token from BEARER_TOKEN_PATH""" bearer_file_path = Path(BEARER_TOKEN_PATH) if not bearer_file_path.is_file(): with login_lock: if not bearer_file_path.is_file(): return login() with bearer_file_path....
c6982f74f7ba716bb9d2d9481ce0c22a237f3e82
3,612,551
def classification_phi_gradient(input_to_class, data): """ This is about a very simple model: there's an input layer, and a softmax output layer. There are no hidden layers, and no biases. This returns the gradient of phi (a.k.a. negative the loss) for the <input_to_class> matrix. <input_to_class> is a ...
4762e8d69f4473c1a0089cd2263a9b2dc0a1b508
3,612,552
import urllib def getData(stops): """Retrieves data from the MTA's realtime feed, then creates a train object for each train described in the feed and stores each train object in a master list. """ feed = gtfs_realtime_pb2.FeedMessage() response = urllib.urlopen('http://datamine.mta.info/mta_esi.p...
aae39c253b24d7df00cb4f981fc7d0263dfe8088
3,612,553
def ringing(img2d, alpha=0.5, noiseSize=0, noiseValue=2, clip=True, seed=None): """ https://bavc.github.io/avaa/artifacts/ringing.html :param img2d: 2d image :param alpha: float, reconstruction quality (0-1) optimal values for tv ringing modeling is 0.3-0.99 :param noiseSize: float, noise size (0-1...
2b7db2383eba12c20b0701d7a126c4e91066bee7
3,612,554