content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import torch def splitTensor(inputTensor,shardSize,locX,locY): """ Divides an input tensor into sub-tensors at given locations. The locations determine the top left corners of the sub-tensors. If the locations exceed the input tensor's boundaries, it is padded with zeros. """ ...
b4ca78ea2c2e90fb9f5503abb298564f7426b4e6
681,583
import ipaddress def calc_prefix(arg, addresses): """Calculates the prefix for the list of addresses. Creates the prefix from arg if one is supplied, otherwise computes the prefix from the addresses. """ # This can throw an exception if they supplied an invalid netmask. if arg: ...
6ed123dfa15c312ff31899a63451daaa540516bb
681,584
def cmd(command: str) -> str: # same as exe """Added for consistency with ghau.update.python. Useful for building the command to place in the reboot parameter of :class:`ghau.update.Update`. This is the recommended way to reboot using a command, as it adds an argument ghau detects to stop update loops. ...
a088d4390a0e184ed4ad23610e13fd4c4717ee83
681,585
def matchSlackUserNameByFullName(users, full_name): """Compare salck username with github user full name.""" if full_name: for user in users: if isinstance(user, dict) and user.get('real_name', '').strip().lower() == full_name.strip().lower(): return user.get('name') retu...
88153b9b84a301639446039172ff965e5cab20a9
681,586
def color_hex_to_dec_tuple(color): """Converts a color from hexadecimal to decimal tuple, color can be in the following formats: 3-digit RGB, 4-digit ARGB, 6-digit RGB and 8-digit ARGB. """ assert len(color) in [3, 4, 6, 8] if len(color) in [3, 4]: color = "".join([c*2 for c in color]) ...
70089c50afa569327d10413b1e0693697194988f
681,588
def property_accessors(property_type, name): """Generate the property accessor functions.""" return (f' @Property({property_type})\n' f' def {name}(self):\n' f' return self._{name}\n\n' f' @{name}.setter\n' f' def {name}(self, value):\n' ...
3e98228300b41a7d68ea96906fde4f38c65f18d6
681,589
import os def check_exitcode(exitcode_file_path): """ Return exitcode of application, which is stored in the exitcode_file_path """ exitcode = -1 if os.path.isfile(exitcode_file_path): try: f = open(exitcode_file_path, "rb") exitcode = int(f.read()) f.close() os.remove(exitcode...
6c8e6bba46cd2f8ae6bbe59a47d18af0a46fa371
681,590
def in_position(in_string, in_set): """ Returns: List of int String Index Positions in Set. """ return list(map(lambda char:in_set.find(char), in_string))[::-1]
7acc120e974a898dd185283e1be2999eba4fff2b
681,591
def fill_row(condition_val, data_rows, df_bayes, condition_name): """ Parameters ---------- condition_val: Current value of condition_name to look up in df_bayes data_rows: rows to fill with corresponding entries from df_bayes (will be concated later) df_bayes: dataframe to fill from condit...
1c49e48170dd9796edcec21a8f26ef2be50f1773
681,592
def msg(m, ctx): """Check if the message is in the same channel, and is by the same author.""" return m.channel == ctx.channel and m.author == ctx.author
38c4f72bb69c8e491dc9d8816060347e9bbac1b2
681,593
def cleanup(df): """Input the complete data and remove very bad listings in the output.""" # we should calculate the winners we dropped. f1 = df[(df.instock == 1) & (df.isfeaturedmerchant == 1)] f1 = f1.drop(['instock', 'isfeaturedmerchant'], axis=1) # those offers suck too f1 = f1[(f1.shipping_...
2133d0722b73e5bec79ac3fa1193e2e44fc9bf68
681,595
import torch def all_or_none_accuracy(preds, targets, dim=-1): """ Gets the accuracy of the predicted sequence. :param preds: model predictions :param targets: the true targets :param dim: dimension to operate over :returns: scalar value for all-or-none accuracy :rtype: float32 """ p...
4e46720996a383b601f7de332945182971f53988
681,596
def _calc_cr(r_jp, r_j, r_jm, vel): """ Calculates cr value used in superbee advection scheme """ eps = 1e-20 # prevent division by 0 if abs(r_j) < eps: fac = eps else: fac = r_j if vel > 0: return r_jm / fac else: return r_jp / fac
ffa5fd3a9aecd9b4dbda265842427014e34ca547
681,597
def get_ee_points(offsets, ee_pos, ee_rot): """ Helper method for computing the end effector points given a position, rotation matrix, and offsets for each of the ee points. Args: offsets: N x 3 array where N is the number of points. ee_pos: 1 x 3 array of the end effector position. ...
d7903638720102c6d4e3b3664301f09ba10029df
681,599
def medium(): """Medium GridWorld Returns ------- :obj:`str` name double :obj:`list` of `int` layout :obj:`int` scale """ name = "Medium" layout = [[3, 0, 0, 0, 0], [1, 1, 1, 1, 0], [0, 0, 0, 0, 0], [0, 1, 1, 1, 1], ...
7db9c36f3029d2d849a64603166d28f68b5f4846
681,600
def times_insertion(): """ :return: """ vart1 = input('how many times website must by open? ') return int(vart1)
8c33be91f33e01dc35a50ff1b62358d888500557
681,601
import math def get_observation_data(observation, t): """ Get observation data at t. """ vars = ['Foil', 'Fw', 'Fs', 'Fa', 'Fb', 'Fc', 'Fh', 'Fg', 'Wt', 'discharge', 'DO2', 'T', 'O2', 'pressure'] # convert to pH from H+ concentration pH = observation.pH.y[t] pH = -math.log(pH) / math.log(1...
7e85f2ce3db3e37228118d7c852f1740168268ef
681,602
from warnings import warn def cat(*args, **kwargs): """Return a string containing the concatenation of any files given as `args`.""" s = str() for f in args: if not f.exists(): warn(f'File {f.name} does not exist.') else: try: s += f.read_text() ...
0ade1dce245b7495ec0026a0663cc592e31861b8
681,603
def list2str(list): """Given a list return a string""" return "[" + ", ".join([str(x) for x in list]) + "]"
28b76e149f8d456ba3b9ecf610d2c780796d76d5
681,605
def num_cooperators(population): """Get the number of cooperators in the population""" return population['Coop'].sum()
fb61a4100a0fc72b5cdd45b3500a4c4f35e09c75
681,606
def int_or_zero(s): """ >>> int_or_zero('') 0 >>> int_or_zero('10') 10 """ return 0 if not s else int(s)
5615432033d88be8183ab502719730e93dc7d078
681,608
def get_url_stripped(uri): """ :param uri: <uri> or uri :return: uri """ uri_stripped = uri.strip() if uri_stripped[0] == "<": uri_stripped = uri_stripped[1:] if uri_stripped[-1] == ">": uri_stripped = uri_stripped[:-1] return uri_stripped
e0ee162de04059b4ddfdbe6bf52add85e49e876b
681,609
def soil_variable(WLM, WUM, WDM, WU, WL, WD, S0, SM): """ Analyze the inputs for soil water to make sure that the input variables are of consistence. """ if WU > WUM: WL = WL + WU - WUM WU = WUM if WL > WLM: WD = WD + WL - WLM WL = WLM if WD > WDM: WD = WDM...
7613f49451d85762be6564ee912e508b90e4b3b0
681,610
def split_company_name_notes(name): """Return two strings, the first representing the company name, and the other representing the (optional) notes.""" name = name.strip() notes = u'' if name.endswith(')'): fpidx = name.find('(') if fpidx != -1: notes = name[fpidx:] ...
4848d5f56420fe6da2c8ad62a43a4ab31b23baba
681,611
def read_cleaned(file): """ Function to extract photometric data from "cleaned" '_phot_cleaned.dat' style sedbys file. - file is a pathlib.Path object """ wvlen, band, lamFlam, elamFlam, flamFlam, beam, odate, ref = [],[],[],[],[],[],[],[] with open(file, 'r') as f_in: for line i...
efb11d774e4ac4e3def199d480c80be9b4ca5402
681,612
def get_enabled_services(environment, roles_data): """Build list of enabled services :param environment: Heat environment for deployment :param roles_data: Roles file data used to filter services :returns: set of resource types representing enabled services """ enabled_services = set() para...
886a05ffbea6ab489fc056409990205ec20cc137
681,613
def test_asyncio_request_response(connection, receiver): """ Test request/response messaging pattern with coroutine callbacks """ async def endpoint_handler(message): return message.payload + "-pong" connection.register_async_endpoint(endpoint_handler, "test.asyncio.request") connectio...
5c055e5a2b41a8170cd21062fff22c8e95f4ac15
681,615
import random def stat_check(stat1, stat2): """ Checks if stat1 wins over stat2 in competitive stat check. """ roll1 = random.randrange(stat1) roll2 = random.randrange(stat2) return roll1 >= roll2
64b96fad051d20c182dfbf719403590951f1b13c
681,616
def artists_to_mpd_format(artists): """ Format track artists for output to MPD client. :param artists: the artists :type track: array of :class:`mopidy.models.Artist` :rtype: string """ artists = list(artists) artists.sort(key=lambda a: a.name) return ', '.join([a.name for a in arti...
b96c191e58af39485fe9e5d8d5b4eb444ba55367
681,617
def flatten_substitution_choices(subs_choices): """ For a given dict {expr: (expr1, expr2)} returns a list of all possible substitution arising from choosing to subs expr by expr1 or expr2. """ subs_choices = subs_choices.copy() if not subs_choices: return [{}] result = [] expr ...
2661b657aac723c67df409aadc78b4eae6c86dd5
681,618
def plane_wave_coefficient(degree, wave_number_k): """ Computes plane wave coefficient :math:`c_{n}^{pw}` """ return (1 / (1j * wave_number_k)) \ * pow(-1j, degree) \ * (2 * degree + 1) / (degree * (degree + 1))
cfef00949677c8893ff74f8b206fe18a4606290b
681,619
from typing import Any def cmp(a: Any, b: Any) -> int: """ Restores the useful `cmp` function previously in Python 2. - Implemented according to [What's New in Python 3.0](https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons). Args: a: An object. b: An object. Retu...
782eef5699c5f0bc55ba57d494ef69a1737a6c78
681,620
def sixtoeight(intuple): """Given four base 64 (6-bit) digits... it returns three 8 bit digits that represent the same value. If length of intuple != 4, or any digits are > 63, it returns None. **NOTE** Not quite the reverse of the sixbit function.""" if len(intuple) != 4: return None for e...
bb6203d07c1cf1df1015bae48c918c9b478e7367
681,621
def forbidden_view(message, request): """Get JSON response for a 403 status code.""" request.response.status = 403 return {'message': str(message), 'status': 403}
0b8b70dff047823c6ba11a4d8f01efb2757efb2d
681,622
def polygon_area(vertices): """Calculate the area of the vertices described by the sequence of vertices. Thanks to Darel Rex Finley: http://alienryderflex.com/polygon_area/ """ area = 0.0 X = [float(vertex[0]) for vertex in vertices] Y = [float(vertex[1]) for vertex in vertices] j = len(ver...
225c56f36e842fe6d557cf5b42670425388b2e09
681,623
def normal_diffusion(times, diffusion_coefficient, dimensions=2): """Models the relationship between mean squared displacement and time during a normal (Brownian) diffusion process. During normal diffusion the mean squared displacement increases linearly with time according to the Einstein relation. ""...
b09b183b381a81d168e4f138245be02ee1ae9a39
681,624
def wisdom_of_the_crowd(nmin_nmax): """Aplica a sabedoria das massas, gerando o valor predito para o dia Args: nmin_nmax (tuple): Tupla com os valores mínimos e máximos Returns: int: Valor médio estimado para o dia corrente """ return int((nmin_nmax[0] + nmin_nmax[1]) / 2)
2ce10c372047042f0e1d2be1f9a4eaf94e6cfe8f
681,625
import re def check_mac(mac_address, capital_letters=True): """ Check mac address is valid. Either format of 52:54:00:AE:E3:41, or 52-54-00-AE-E3-41 """ if capital_letters: regex = r'^([0-9A-F]{2}[:]){5}([0-9A-F]{2})$' else: regex = r'^([0-9a-f]{2}[:]){5}([0-9a-f]{2})$' ...
38a574f9d888267f5a74d2a70ed353ed0e6fdc5e
681,626
def get_tdlinfo (typ, c): """TDL for a type (extracted by python)""" c.execute("""SELECT src, line, tdl, docstring FROM tdl WHERE typ=?""", (typ,)) return c.fetchall()
bf11030ef46eb1fcc6a8c2c9faaacfa19ce78278
681,627
def electrolyte_diffusivity_Valoen2005(c_e, T): """ Diffusivity of LiPF6 in EC:DMC as a function of ion concentration, from [1] (eqn 14) References ---------- .. [1] Valøen, Lars Ole, and Jan N. Reimers. "Transport properties of LiPF6-based Li-ion battery electrolytes." Journal of The Electroch...
0becd5997ae29ee40a1e2fa38f66386476a706e6
681,628
def pascal_voc_palette(num_cls=None): """ Generates the PASCAL Visual Object Classes (PASCAL VOC) data-set color palette. Data-Set URL: http://host.robots.ox.ac.uk/pascal/VOC/ . Original source taken from: https://gluon-cv.mxnet.io/_modules/gluoncv/utils/viz/segmentation.html . `num_cls`: t...
4859082ad0a02a4bbc7715bcabd01774758c214d
681,629
def index(): """ this is a root dir of my server :return: str """ return "This is root!!!!"
77fb96b51f23755511446e650aa65c6c6e970029
681,630
def get_stream_digest_data(digest): """ Process deployment digest for stream. """ try: # Process deployment information for stream. latitude = None longitude = None depth = None water_depth = None if digest and digest is not None: latitude = digest...
1c8415c8637592de15f0476aa124bff9b795b22d
681,631
import re def split_on_phrase_rgx(sentences, doc, rgx, threshold=250): """ Split sentence on phrase regex :param sentences: :param doc: :param rgx: :param threshold: :return: """ splits = [] for sent in sentences: matches = re.findall(rgx, sent.text) if len(se...
9138746af2a5161bea60ebd4a69aaa8289b2006c
681,632
def R(units): """Universal molar gas constant, R Parameters ---------- units : str Units for R. Supported units ============= =============================================== ============ Unit Description Value ...
485ccef1da6e865406420955b024f479356674de
681,633
import torch def compute_pdist_matrix(batch, p=2.0): """ Computes the matrix of pairwise distances w.r.t. p-norm :param batch: torch.Tensor, input vectors :param p: float, norm parameter, such that ||x||p = (sum_i |x_i|^p)^(1/p) :return: torch.Tensor, matrix A such that A_ij = ||batch[i] - bat...
ae997a59c7e208fca4dc80ee1f7865320edeff86
681,634
import typing def remove_repeats(strings: typing.List[str]) -> typing.List[str]: """ remove repeated words and sentences Arguments: strings (typing.List[str]): input strings. Returns: strings (typing.List[str]): output strings. """ out = [] for s in strings: words = s.s...
003eddbf47b653d0313c35d31506246966a05803
681,635
import socket import struct def get_ip_mreqn_struct(multicast_address, interface_address, interface_name): """ Set up a mreqn struct to define the interface we want to bind to """ # See https://github.com/torvalds/linux/blob/866ba84ea30f94838251f74becf3cfe3c2d5c0f9/include/uapi/linux/in.h#L168 ip_...
69f3e41986d89ec0ee14ff1e1b9a27450761543e
681,636
def _get_id(mf, url=None): """ get the uid of the mf object Args: mf: python dictionary of some microformats object url: optional URL to use in case no uid or url in mf Return: string containing the id or None """ props = mf['properties'] if 'uid' in props: return props['uid'][0] elif 'url' in props:...
51ecd4f77161dec47fbed1faa395c68b2698491d
681,637
def run_generator(generator, consume=False): """Run generator. """ if consume: for item in generator: pass return return next(generator)
14bf88c363c9e6049cafcb1a425c7acb5035472c
681,638
def vertices_for_patches(vertices, patches): """Compiles the set of vertices for the list of patches only read from an Amira HyperSurface file :param vertices: a sequence of vertices (see `ahds <http://ahds.readthedocs.io/en/latest/>`_ package) :type vertices: ``ahds.data_stream.VerticesDataStream`` ...
16e5115d1c1ef7f2e9000a646ff6da30582c7410
681,640
import argparse def parseArguments(): """ Parse the command-line options :returns: object -- Object containing the options passed """ desc = "Program that fixes RMSD symmetries of a PELE report file."\ "Control file is a JSON file that contains \"resname\", \"native\", "\ ...
e42acc90dda5b28ec181cb76e70ff525d749e091
681,641
import os import gc def ls_file(path): """ list the directory of path """ try: if path=="": data=os.listdir() directory={'/':data} return directory else : data=os.listdir(path) directory={path:data} return director...
c08d1a7d4566427c5be7907e0b235225e520e858
681,642
def get_worksheet_names(workbook): """ Gets the names of all the worksheets of the current workbook. :param workbook: Current workbook to manipulate. :return: A list of all the worksheets' names of the current workbook. """ return workbook.sheetnames
738423827f9fe4b1a016a31e032fc389d23ccc68
681,643
import time def is_task_successful(task, retry=10 , interval=5): """ Method to check the task state. :param task: VMware task. :param retry(int): Number of Retries. :param interval(int): Interval between each retry. :return: bool( """ while retry > 0: task_status = str(task.inf...
efc31efd20a5a77fab50862971ab132d068f02a7
681,644
def cropRegion(coord, topCrop=0, bottomCrop=0, leftCrop=0, rightCrop=0): """crops a region defined by two coordinates""" w = coord[1][0]-coord[0][0] # x2 - x1 h = coord[1][1]-coord[0][1] # y2 - y1 y1 = coord[0][1] + topCrop * h # y1 = y1 + topCrop * h y2 = coord[1][1] - bottomCrop * h # y2 = y...
75f84021d9a4cc9f8fd6ad00595d442636609aec
681,645
import torch def binary_acc(y_pred, y): """Calculates model accuracy Arguments: y_pred {torch.Tensor} -- Output of model between 0 and 1 y {torch.Tensor} -- labels/target values Returns: [torch.Tensor] -- accuracy """ y_pred_tag = torch.round(y_pred) correct_r...
81099841fa75b8302bbc9c4044e62b8ca01a5828
681,646
def cvode_stats_to_dict(path: str) -> dict: """ Converts a Delphin integrator_cvode_stats file into a dict. :param path: path to folder :return: converted tsv dict """ file_obj = open(path + '/integrator_cvode_stats.tsv', 'r') lines = file_obj.readlines() file_obj.close() tsv_dict...
39b5e78d142b8ad01f5cdd55130c1e05673eab17
681,647
def validate_bid_activation(request, **kwargs): """ validate bid activation(patch status to 'pending') """ # check if it administrator bacause he can do everything if request.authenticated_role == 'Administrator': return True # check if it is valid two-phase commit new_status =...
054cdfa6871a2d7203366e20c70d3db4d0997e31
681,648
def water_palette(): """Water palette for external use.""" return [[0, 0, 0], [0, 0, 255]]
1f2eb6b4246b9aa1d8130a1b58ea1eef54dc6188
681,649
from typing import OrderedDict def evaluate_boolean_filters(isovar_result, filter_flags): """ Helper function used by apply_filters. Parameters ---------- isovar_result : IsovarResult filter_flags : list of str Every element should be a boolean property of IsovarResult or "no...
562ab37267d834e33cd1afd2edc43d79c4cd5a64
681,650
def _scale_col_to_target(col, target, metric_func): """ Scale a column's values so that in aggregate they match some metric, for example, mean, median, or sum. Parameters ---------- col : pandas.Series target : number metric_func : callable Must accept a Series and return a numb...
3d7465d29917b133bc8cbaa56924bb2f08782a10
681,651
def ofxRemovePluginAliasExclusion(fullOfxEffectName:list): """ ofxRemovePluginAliasExclusion(fullOfxEffectName) -> None Remove an ofx plugin alias exclusion that was previously added with . Example: nuke.ofxRemovePluginAliasExclusion('OFXuk.co.thefoundry.noisetools.denoise_v100') @param fullOfxEffec...
a108b3c5f1b1752007e89fc7325bbef06f229362
681,652
def _get_token(azure_credentials): """Use an Azure credential to get a token from the Kusto service.""" TOKEN_URL = "https://kusto.kusto.windows.net/" token = azure_credentials.get_token(TOKEN_URL).token return token
750929efb8451e15cdb89ee5c5a466e456ccb596
681,653
def binlogs_to_backup(cursor, last_binlog=None): """ Finds list of binlogs to copy. It will return the binlogs from the last to the current one (excluding it). :param cursor: MySQL cursor :param last_binlog: Name of the last copied binlog. :return: list of binlogs to backup. :rtype: list ...
227ab73ece3df209f53cdd061c54f524cc5943b1
681,654
def performanceCalculator(count, avg, std, maxv, countref, avgref, stdref, maxvref): """ =========================================================================== Performance calculator function =========================================================================== Calculate performance bas...
92f98baa720f19a1e6f5dbcdb610b38036c49c6c
681,655
import torch def weighted_mean_rule_func(predictions: torch.Tensor, weights: torch.Tensor, *_) -> torch.Tensor: """ Mean the predictions of different classifier outputs with classifier weights. Args: predictions: outputs of the base models weights: a one-dimens...
b88bf7cc162adc1b968a34dca0380f7686ae875d
681,657
def set_val_if_dict( dct, key, val ): """ Set the { ... `key`:`val` ... } only if `dct` is a dictionary """ try: dct[ key ] = val return True except (TypeError, KeyError): return False
abeef6e3039b206ac661c9abc8e7403c7b0a9e50
681,658
def all_unique(seq): """Returns whether all the elements in the sequence ``seq`` are unique. >>> all_unique(()) True >>> all_unique((1, 2, 3)) True >>> all_unique((1, 1, 2)) False Creates a set, so the elements of the sequence must be hashable (and are compared ...
4c848a71d7f67b5b13b4cc051bc18d468e9baf54
681,659
import torch from typing import Optional def weighted_average( x: torch.Tensor, weights: Optional[torch.Tensor] = None, dim=None ) -> torch.Tensor: """ Computes the weighted average of a given tensor across a given dim, masking values associated with weight zero, meaning instead of `nan * 0 = nan`...
e2422c4b4f1de49b4273b2d9704fd38495a337e3
681,660
def check_sudoku(sudoku): """ Funktion zur Überprüfung einer Sudoku-Lösung auf Korrektheit. Als Eingabe an die Funktion wird die Sudoku-Lösung in Form einer Liste von Listen übergeben. Die Funktion gibt als Ergebnis einen Wahrheitswert zurück. """ # Prüfe Zeilen # Gehe jede Zeile durch for ...
5d39cd4ab1bc3116bc745cf10cc68a7b00dde533
681,661
import re def _is_pull_request_base_branch_match(pull_request: dict, base_branch: str) -> bool: """ Determine if the pull request represents a notification for a base branch we should consider. :param pull_request: Pull request section of payload to examine :type: :class:`~dict` :param base_branc...
30c7d0e495419ecd4eee6949d3d851de01192734
681,662
def get_contigous_borders(indices): """ helper function to derive contiguous borders from a list of indices Parameters ---------- indicies : all indices at which a certain thing occurs Returns ------- list of groups when the indices starts and ends (note: last element is t...
66c3dd37573e09763dde20f1428f1101341fefe1
681,663
import math def hsvToRGB(h, s, v): """Convert HSV color space to RGB color space @param h: Hue @param s: Saturation @param v: Value return (r, g, b) """ hi = math.floor(h / 60.0) % 6 f = (h / 60.0) - math.floor(h / 60.0) p = v * (1.0 - s) q = v * (1.0 - (f*s)) t = v * (1.0 - ((1.0 - f) * s)) D = {0...
7bb1d7268ba3c8b91adc4872521f75f8e699376e
681,664
def is_too_similar_for_axes(word1, word2): """ Checks if the words contain each other """ return word1 in word2 or word2 in word1
7156490dcaac3081fd44845ee6350906fd196f19
681,665
def dominance(solution_1, solution_2): """ Function that analyze solutions dominance. Parameters ----------- :param solution_1: Solution :param solution_2: Solution Returns --------- :return int If solution_1 dominates solution_2 -> return 1 :return -1 If soluti...
2b6b39e12afed85a9064cb36d0ecb9c3473bac61
681,666
from typing import List def _parse_csv(s: str) -> List[str]: """Return the values of a csv string. >>> _parse_csv("a,b,c") ['a', 'b', 'c'] >>> _parse_csv(" a, b ,c ") ['a', 'b', 'c'] >>> _parse_csv(" a,b,c ") ['a', 'b', 'c'] >>> _parse_csv(" a,") ['a'] >>> _parse_csv("a, ") ...
62c83f091e49fd75b30fe9cca46c2bf4175e959a
681,667
def dict_merge(a, b): """ Merge two dictionaries and return the result. :see http://stackoverflow.com/a/15836901 """ key = None try: if a is None or isinstance(a, str) or isinstance(a, bytes) \ or isinstance(a, int) or isinstance(a, float): # have primitives repl...
5fd6b68a9e4727229d020cc57469ecd815aad430
681,668
import builtins def replace_import(prefix, new_module): """Make import return a fake module Args: prefix: string at the beginning of the package name """ realimport = builtins.__import__ def my_import(name, *args, **kwargs): if name.startswith(prefix): return new_modu...
de244da8223103fd94d70c5da391a1da9d5230b2
681,669
def n_Linear(x, No): """The model function""" return No * (x)
7b4932114730d17059b3cdc2ac50f1c27edfb951
681,670
def _correct_registry_paths(registry_paths): """ parse_registry_path function recognizes the 'item' as the central element of the asset registry path. We require the 'namespace' to be the central one. Consequently, this function swaps them. :param list[dict] registry_paths: output of parse_registry_pat...
bedbb5bd6f0faee2fdee4318a339c0146166a348
681,671
import math def sph_kern2(r,h): """SPH kernel for h/2 < r < h""" return 2*(1-r/h)**3*8/math.pi/h**3
50b5302541c60aaac08f3669aaba945b86215b71
681,672
def _is_empty_two_way_keyword(data: dict) -> bool: """ 2way 키워드가 비워져 있는지 확인한다. :param data: 파라미터 :return: 비워져 있을때 True """ if data is None: return True try: _ = data['is2Way'] return False except KeyError: pass try: _ = data['twoWayInfo'] ...
8cdf1ad162d1e57c131030c9b4594c61855554f2
681,673
def get_antigen_name(qseqid): """ Get the antigen name from the BLASTN result query ID. The last item delimited by | characters is the antigen name for all antigens (H1, H2, serogroup) @type qseqid: str @param qseqid: BLASTN result query ID @return: antigen name """ if qseqid: ...
02f63245021a09cf02db27f34a5241070a5c8b3b
681,674
import requests def get_img_content(img_url): """ 函数功能:向服务器请求图片数据 参数: img_url:图片的链接地址 返回:图片的内容,即图片的二进制数据 """ header2 = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36' try: r = requests.get(img_url, headers...
1f00ddbfeddb5b2db8c0e57d9cf8ed96cb763087
681,675
def issues_to_link_to_for_organization_doc_template_values(url_root): """ Show documentation about issuesToLinkToForOrganization """ optional_query_parameter_list = [ { 'name': 'organization_we_vote_id', 'value': 'string', # boolean, integer, long, string 'de...
d6075f7d510b6acccb6c681dfca49f1bd7eab0d5
681,676
def wordFinder(string): """Takes a string and returns the number of times a word is repeated""" #begin init of function variables stringLower=string.lower() stringList=list(stringLower) stringList.insert(0,' ') stringList.append(' ') spaceList=[] wordList=[] charList=[] repeat=0 ...
9b061bb1034e8d864d9e243f5a5d7b131cdb2e86
681,677
import os def get_rank(): """ Returns the rank of current process group Rank is a unique identifier assigned to each process within a distributed process group. They are always consecutive integers ranging from 0 to ``world_size``. Returns: The rank of the process group """ ...
c84950bb4bd172ca31b639a17f371a25ff6c66b7
681,678
def is_full_alphabet(c): """是否全角字母""" if isinstance(c, str): c = ord(c) return (0xFF21 <= c <= 0xFF3A) or (0xFF41 <= c <= 0xFF5A)
89e64c20eaa1a46ea19cf740c61bca4004816576
681,679
def normalize_matrix(transformer, matrix): """Normalize count matrix to scale down the impact of very frequent tokens :param transformer: A Sklearn TfidfTransformer object :param matrix: An array representing a term document matrix, output of CountVectorizer.fit_transform """ matrix_normalized ...
069f5c3878d0a795dcefd906ba5d03a3c333f5f2
681,680
def find_default_image(images): """Search the list of registered images for a defult image, if any. Return the image if found, otherwise None """ for img in images: if img['default']: print("The default image is currently: '%s'" % img['imagename']) return img return ...
a8ec40318973b5fe007186c21719c9e37f9d0970
681,681
import tempfile import zipfile def unpack_zip(zip_ffn): """ Unpacks zip file in temp directory Parameters: =========== zip_ffn: str Full filename to zip file Returns: ======== temp_dir: string Path to temp directory """ #build ...
95ee3c9d3f215fe91a949d6de3b296a63005d775
681,683
import os def project_centric_path(projroot: str, path: str) -> str: """Convert a CWD-relative path to a project-relative one.""" abspath = os.path.abspath(path) if abspath == projroot: return '.' projprefix = f'{projroot}/' if not abspath.startswith(projprefix): raise RuntimeError...
becf9779047d5803d5694c565b2e562841170b33
681,684
import os def StatFile(path): """ Stat the file, following the symlink. """ d = None try: d = os.stat(path) except: pass return d
6171bbeb5461f04e5ebba481ef3da3b3a3071590
681,686
import subprocess def get_lsb_release(): """Gets the os info through lsb_release. Returns: (distributor_id, description, release, codename) """ proc = subprocess.Popen(["lsb_release", "-i", "-d", "-r", "-c"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = proc.communicate...
dfe5c4c18ee6e46374e328945f978faf1695be36
681,687
def getlogin(): """Return the name of the user logged in on the controlling terminal of the process. For most purposes, it is more useful to use the environment variable :envvar:`LOGNAME` to find out who the user is, or ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently ...
440f4f214fdb9ebe703c4bb0b0aa4ea0acbdd2bf
681,688
def _colors(strKey): """ Function gives access to the RxCS console colors dictionary. The Function returns a proper console color formating string (ANSI colors) based on the key given to the function. |br| Available keys: 'PURPLE' 'BLUE' 'GREEN' 'YELLOW' 'RE...
90f09148ac709299d1666930e7c675595d04663f
681,689
def get_target_name(item): """Take a query record, split the name field, and return the target name.""" return item.file_location.split('/')[-2].split('_')[-1]
f1fce4b4886b68a845267e35eaab47111969548a
681,690
import torch def get_lr_scheduler(config, optimizer): """[summary] Args: config ([type]): [description] optimizer ([type]): [description] Raises: ValueError: [description] Returns: [type]: [description] """ scheduler_name = config.SOLVER.LR_SCHEDULER if s...
a47d896d517b3efee6731fd55694d1900d71439f
681,691
import torch def textTotensor(raw_text_iter,tokenizer, vocab): """Converts raw text into a flat Tensor.""" data = [torch.tensor(vocab(tokenizer(item)), dtype=torch.long) for item in raw_text_iter] return torch.cat(tuple(filter(lambda t: t.numel() > 0, data)))
6e683dcbc31c696cede7b2a5f8fbb8293e79d51f
681,692