content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def key_set(d): """A set of all the keys of a dict.""" return set(d.iterkeys())
e5e6ad8d1ad25003689d5a1135c2bd9919ae7729
694,563
def gimmick(message): """Detect if a message is the result of a gib gimmick.""" if message is None: return False if message.lower().count("oob") > 3: return True if message.lower().count("ob") > 4: return True if message.isupper(): return True return False
91f8ffa77e8ddddeb7b7de2b39809b964ffb502b
694,564
import yaml def load_yaml(data): """Parse a unicode string containing yaml. This calls ``yaml.load(data)`` but makes sure unicode is handled correctly. See :func:`yaml.load`. :raises yaml.YAMLError: if parsing fails""" class MyLoader(yaml.SafeLoader): def construct_yaml_str(self, node): # Override the default string handling function # to always return unicode objects return self.construct_scalar(node) MyLoader.add_constructor( 'tag:yaml.org,2002:str', MyLoader.construct_yaml_str) return yaml.load(data, Loader=MyLoader)
f55e144582707d603d263066ef3555049d2ea377
694,568
from typing import Dict from typing import List def process_group_mappings( group_mapping_config: Dict[str, dict], sso_attributes: dict, groups: List[str] ): """Processes the groups from the mapping rule config into discourse compatible formats Args: group_mapping_config (Dict[str, dict]): Predefined mapping rules for the keycloak group tree { "<group_name>": { "name": "<group name in discourse>", "isMod": false, "isAdmin": false }, ... } sso_attributes (dict): SSO Attributes as they will be processed by the bridge groups (List[str]): List of groups from the userinfo endpoint """ grps = list() for group in groups: mapping_rule = group_mapping_config.get(group) if mapping_rule is None: continue if mapping_rule.get("isAdmin", False): sso_attributes["admin"] = "true" elif mapping_rule.get("isMod", False): sso_attributes["moderator"] = "true" else: grps.append(mapping_rule["name"]) # Make sure the mod and admin privileges are pinned to false to trigger permission reset on group change. for priv in ["admin", "moderator"]: if priv not in sso_attributes: sso_attributes[priv] = "false" sso_attributes["groups"] = ",".join(grps) return sso_attributes
53643ab55607837ce04ce4a7a3637b558780fd08
694,573
def get_literal_type(value): """Get the data type :param value: The data :return: The data type as a string :rtype: str """ return type(value).__name__
ed0fe2541f2439f98be14345bc622c9d49b3165b
694,575
import yaml def parsed_site_config(site_config_yml): """Fixture that returns the parsed contents of the example site config YAML file in the resource directory""" return yaml.load(site_config_yml, Loader=yaml.SafeLoader)
71c692dc80cb631d813bf9e53d98b0e1cd9e5a9d
694,576
import inspect import six def _GetArgSpecFnInfo(fn): """Gives information pertaining to computing the ArgSpec of fn. Determines if the first arg is supplied automatically when fn is called. This arg will be supplied automatically if fn is a bound method or a class with an __init__ method. Also returns the function who's ArgSpec should be used for determining the calling parameters for fn. This may be different from fn itself if fn is a class with an __init__ method. Args: fn: The function or class of interest. Returns: A tuple with the following two items: fn: The function to use for determing the arg spec of this function. skip_arg: Whether the first argument will be supplied automatically, and hence should be skipped when supplying args from a Fire command. """ skip_arg = False if inspect.isclass(fn): # If the function is a class, we try to use it's init method. skip_arg = True if six.PY2 and hasattr(fn, '__init__'): fn = fn.__init__ else: # If the function is a bound method, we skip the `self` argument. is_method = inspect.ismethod(fn) skip_arg = is_method and fn.__self__ is not None return fn, skip_arg
939d7e0a5f49f317d881638fd77be26f379f5e9a
694,579
def gradezero(evtdata): """ Only accept counts with GRADE==0. Parameters ---------- evtdata: FITS data class This should be an hdu.data structure from a NuSTAR FITS file. Returns ------- goodinds: iterable Index of evtdata that passes the filtering. """ # Grade filter grade_filter = ( evtdata['GRADE'] == 0) inds = (grade_filter).nonzero() goodinds = inds[0] return goodinds
370bbf16b25d9543b7e485f0e366b709d6261dfb
694,584
def exists_db(connection, name): """Check whether a database exists. :param connection: A connection :param name: The name of the database :returns: Whether the db exists :rtype: bool """ exists = connection.execute("SELECT 1 FROM pg_database WHERE datname = {}".format(name)).first() connection.execute("COMMIT") return exists is not None
2a729b85cbf9e9cdc30970bcaa4258a7ff8a97fb
694,586
def _ggm_qcondwait_whitt_ds3(cs2): """ Return the approximate E(V^3)/(EV)^2 where V is a service time; based on either a hyperexponential or Erlang distribution. Used in approximation of conditional wait time CDF (conditional on W>0). Whitt refers to conditional wait as D in his paper: See Whitt, Ward. "Approximations for the GI/G/m queue" Production and Operations Management 2, 2 (Spring 1993): 114-161. This is Equation 4.3 on p146. Note that there is a typo in the original paper in which the first term for Case 1 is shown as cubed, whereas it should be squared. This can be confirmed by seeing Eq 51 in Whitt's paper on the QNA (Bell Systems Technical Journal, Nov 1983). Parameters ---------- cs2 : float squared coefficient of variation for service time distribution Returns ------- float mean wait time in queue """ if cs2 >= 1: ds3 = 3.0 * cs2 * (1.0 + cs2) else: ds3 = (2 * cs2 + 1.0) * (cs2 + 1.0) return ds3
fb6f4cadafeae2f3cb29200a4ae3402a0317c63a
694,587
import re import click def validate_mfa_device_name(ctx, param, value): """Validates a virtual MFA device name.""" try: if not all([re.match(r"[\w+=/:,.@-]+", value), 9 <= len(value) <= 256]): raise ValueError(value) return value except ValueError: click.echo('Invalid device name given, only ASCII characters and + = / : , . @ - are allowed with a length ' 'between 9 and 256 with no spaces.') value = click.prompt(param.name) return validate_mfa_device_name(ctx, param, value)
be3801383ebe2e4c2aed42b2e29601987dffc283
694,591
import json def write_to_json_file(obj, filename): """ Write on file filename the object in JSON format :param obj: object to be written on the JSON file :param filename: filename to be used to store the obj :return: success (bool) """ f = open(filename, "w") try: json.dump(obj, f) success = True except: success = False finally: f.close() return success
c074e379c51b0cc3468f812552ee3176e64eda51
694,597
def orbital_eccentricity(t: float) -> float: """ Calculate the eccentricity of earth's orbit around the sun. Parameters: t (float): The time in Julian Centuries (36525 days) since J2000.0 Returns: float: The earth's orbital eccentricity at the given time """ # t must be in the range from year 1901 thru year 2099 if (t < -0.99 or 1.00 < t): raise ValueError("t must be beteween -0.99 and 1.00: " + str(t)) return -0.0000001267 * pow(t, 2) - 0.000042037 * t + 0.016708634
d971c059259c875b00041a7cd558af628af1df09
694,598
def tagsAssoPerson(cnx,person,domain): """ Function to determine tags related to a person in the given domain :param cnx: connection object :param person: user with whom the tags are associated :param domain: domain id of the desired topic :return: list of tags associated with the user """ cursor = cnx.cursor() cursor2 = cnx.cursor() # procedure to determine user tags associated with domain cursor.callproc('associated_tags',[person, domain]) result = [] for result1 in cursor.stored_results(): for row in result1.fetchall(): getTag="select tag_details from tags where tagId='"+str(row[0])+"'" cursor2.execute(getTag) tagName = cursor2.fetchone() result.append(tagName[0]) if result: return result return ["None Found"]
188363fdee34a1ccbc94941e5fdb60dcbc529b3a
694,601
def type_prefix(typ) -> bytes: """ Return the prefix string for the given type. The prefix determine the type of the expected object. """ return b'o'
852d5802e912d0efd685e99c581e11670674d23e
694,602
def update_grad_w(grad, grad_old, grad_new): """Update the global gradient for W Parameters ---------- grad: theano tensor The global gradient grad_old: theano tensor The previous value of the local gradient grad_new: theano tensor The new version of the local gradient Returns ------- grad: theano tensor New value of the global gradient """ return grad - grad_old + grad_new
74015b8987fa7af0bc6bbb4d9de3d96c1d83b5d8
694,608
def product(list): """ Returns a product of a List :param list: :return: """ prod = 1 for e in list: prod = prod * e return prod
900ff8b30be04a0f6e440fa47ece772846c890e3
694,609
def map_indices_py(arr): """ Returns a dictionary with (element, index) pairs for each element in the given array/list """ return dict([(x, i) for i, x in enumerate(arr)])
d045d57ec95be50f2c1ab3f46e22b93ab3568637
694,611
import requests def _download_collection(url): """ Download all pages in a paginated mgnify data collection This returns a single structure with all entries appended to result['data'] """ result = {'data': []} while url is not None: resp = requests.get(url, params={'page_size': 100}).json() result['data'] += resp['data'] url = resp['links']['next'] return result
31c5af3480a40f0cc700cfb81235cca7ab094469
694,616
def has_function(faker, key): """ helper function to check if a method is available on an object""" return hasattr(faker, key)
c57020222be5f7a336f2773a2e80a85c4eac867f
694,619
def outlierStats(outlier_list): """Takes a list of outliers and computes the mean and standard deviation""" try: outlierMean = outlier_list.mean() outlierStdev = outlier_list.std() return outlierMean, outlierStdev except TypeError : explanation = "Cannot compute statistics on a list of non-numerical elements." return explanation
98aeec98faa3eff4ce576e9ad4a3331f54d7a25d
694,620
def gcd(x, y): """greatest common divisor of x and y""" while y: x, y = y, x % y return x
211d6aeab23734a944a606b2a744bd4ab682a166
694,623
def _encode_for_display(text): """ Encodes strings so they can display as ASCII in a Windows terminal window. This function also encodes strings for processing by xml.etree.ElementTree functions. Returns an ASCII-encoded version of the text. Unicode characters are converted to ASCII placeholders (for example, "?"). """ return text.encode('ascii', errors="backslashreplace").decode('utf-8')
59fa895204b764a105f0cc73f87f252c64e62871
694,624
def d_theta_parabolic(C, k, clk): """ A downwards concave parabola of form: f(x) = -c(x)(x - a) Here: C -> x k -> c clk -> a """ return -1 * k * C * (C - clk)
ac520d33bf11ba20e1a2f72d298a2a496ec00ca7
694,625
def get_blueprints(bot, base): """Gets the blueprints associated with the given base. Also returns whether or not the command is a shortcut. If the base is not found in the commands dictionary, returns (None, None) """ try: command = bot.commands[base] is_shortcut = base in command.shortcut.bases return (command.blueprints, is_shortcut) except KeyError: return (None, None)
48b7a5bad96f64825cfe6178711d8714514d5bad
694,626
def is_good_response(res, content_type='html'): """ Returns True if the response seems to be Content type (default html), False otherwise. """ content_type = res.headers['Content-Type'].lower() return (res.status_code == 200 and content_type is not None and content_type.find(content_type) > -1)
d48ad85a7f8790be6e037d978e84756fa7091689
694,628
def can_infer(num_sensed_blocked: int, num_confirmed_blocked: int, num_sensed_unblocked: int, num_confirmed_unblocked: int): """ check whether we can infer or not from the current set of variables :param num_sensed_blocked: number of sensed blocks :param num_confirmed_blocked: number of confirmed blocks :param num_sensed_unblocked: number of sensed unblocks :param num_confirmed_unblocked: number confirmed unblocks :return: True if we can infer anything otherwise False """ # Check precondition assert (num_sensed_blocked >= num_confirmed_blocked) and (num_sensed_unblocked >= num_confirmed_unblocked) # Condition whether we can infer or not if ((num_sensed_blocked == num_confirmed_blocked) and (num_sensed_unblocked > num_confirmed_unblocked)) or \ ((num_sensed_unblocked == num_confirmed_unblocked) and (num_sensed_blocked > num_confirmed_blocked)): return True return False
49eea4125ffb970c89f223afd21e3e7dd3c870d7
694,630
def get_contacts(filename): """ Return two lists names, emails containing names and email addresses read from a file specified by filename. """ names = [] emails = [] lineofdata = [] # print(names) # print(emails) with open(filename, mode='r', encoding='utf-8') as contacts_file: for a_contact in contacts_file: # print(a_contact) lineofdata = a_contact.split() # print(lineofdata) # print(len(lineofdata)) # print(lineofdata[0]) # print(lineofdata[1]) names.append(lineofdata[0]) emails.append(lineofdata[1]) # print("names are ", names) # print(emails) return names, emails
e3f3b862fca1e290c2b353ba440913479e1265c9
694,631
def _int32_to_bytes(i): # NOTE: This course is done on a Mac which is little-endian """Convert an integer to four bytes in little-endian format.""" # &: Bitwise 'and' # >>: Right shift return bytes((i & 0xff, i >> 8 & 0xff, i >> 16 & 0xff, i >> 24 & 0xff))
61606a87d7f074117637b3a322dcded43a514cd0
694,632
import math def calculateCents(referenceScale, newScale): """Takes two arrays of frequencies and calculates the cents difference. Returns 8 values in a list.""" centsList = [] for i in range(len(referenceScale)): ratio = newScale[i] / referenceScale[i] cents = round(((math.log(ratio) / math.log(2)) * 1200), 2) centsList.append(cents) return centsList
94796baa067806b2a15fd536798adf84f5360901
694,635
def usage(err=''): """ Prints the Usage() statement for the program """ m = '%s\n' %err m += ' Default usage is to seach the Scan the currect directory for PE checkpoints.\n' m += ' It will look for linked CRs in a peer directory' m += ' create_pe_load \n' return m
3b9e7b34eb7b1072f02f0678dd505961bdf9aa39
694,636
def is_float(n: str) -> bool: """ Checks if a string is a valid float Parameters ---------- n: str The string to check. Returns ------- bool """ try: float(n) return True except ValueError: return False
dcbcdaafc857f69bcc3b9cf728a230088adf84b7
694,638
import zipfile import pathlib async def make_zip_archive( input_directory_path: str, output_file_path: str, ) -> dict: """ Creates zip file of a directory. Parameters ---------- input_directory_path : str Path to directory to be archived output_file_path : str Path where the output archive should be saved (should include file name) Returns ------- dict Path to the output zip file """ with zipfile.ZipFile(output_file_path, "w") as zip: for file in pathlib.Path(input_directory_path).rglob("*"): zip.write(file, file.name) return {"output_path": output_file_path}
a27729eeec533e6978047268e62b644d3ce9a038
694,639
def flowDiff(graph1, graph2): """ Return the difference between the flows of two graphs. Parameters ---------- graph1: netwrorkx obj graph2: networkx obj Returns ------- a dictionary with name od edge and diff in flows. graph1-graph2 """ flowDiff_ = {} for edge in graph1.edges(): flow1 = graph1[edge[0]][edge[1]]['flow'] flow2 = graph2[edge[0]][edge[1]]['flow'] flowDiff_[edge] = flow1-flow2 return flowDiff_
65d7392607b01f935dd6fe2e282083530a3513d3
694,640
def tryint(s): """ try casting s to an int. if exception occurs, return s unchanged """ try: return int(s) except ValueError: return s
8a4b221a2930494a631dcd23544176d47f4ef6e0
694,646
import mimetypes def guess_mimetype(resource_path): """ Guesses the mimetype of a given resource. Args: resource_path: the path to a given resource. Returns: The mimetype string. """ mime = mimetypes.guess_type(resource_path)[0] if mime is None: return "application/octet-stream" return mime
66f2554387966028a4ab1cf1bf3715878b3dc246
694,648
def hex_8bit(value): """Converts 8bit value into bytearray. args: 8bit value returns: bytearray of size 1 """ if value > 0xff or value < 0: raise Exception('Sar file 8bit value %s out of range' % value) return value.to_bytes(1, 'little')
597ecb6c9a499c7a5959f1f8ddd7300b78b06e9a
694,649
def lower(s): """ Returns the string `s` converted to lowercase. """ return s.lower()
e953cb79ee371128952a6ad7a0b7c91afc08c8b6
694,651
def episode_title(self): """Return episode title.""" return self.media_metadata.get("subtitle")
94b5be128e44334efe5f3c141e0b9dbc1bc10c3d
694,654
def weed_out_short_notes(pairs, **kwargs): """Remove notes from pairs whose duration are smaller than the threshold""" duration_threshold = kwargs.get('duration_threshold', 0.25) return [(n, d) for (n, d) in pairs if d > duration_threshold]
de9caea78313e4f8d77c16ed17ae885d4bed9e33
694,657
def datetime_format(datetime_obj, fmtstring = '%Y-%m-%d'): """ A function to string format a datetime.datetime object. """ return datetime_obj.strftime(fmtstring)
a64ce81cb28c59489bff3d57751feebb818e04c5
694,658
def start_ea(obj): """ Return start ea for supplied object. :param obj: Object to retrieve start ea. :return: start ea. """ if not obj: return None try: return obj.startEA except AttributeError: return obj.start_ea
fc00c290d493ec762f165c6ff657716c8218fab3
694,660
def has_tx_succeeded(tx_receipt): """ We check tx has succeeded by reading the `status` on the `tx_receipt` More info: https://docs.pantheon.pegasys.tech/en/latest/Reference/JSON-RPC-API-Objects/#transaction-receipt-object """ status = tx_receipt.get("status", None) if status == 1: return True return False
3b9e54efd1b269a835b4829adeca7afe7cfe51a9
694,661
def derive_nums_from_text(comments, regex): """Given a string, derive all related case nums using given regexes""" return set(int(num) for num in regex.findall(comments) if num)
76d1a69acefaeba64a9be9763f15f2da24652bea
694,662
def _evaluate_cubic_spline_derivative_one(x, y, r, t): """Evaluate one point on the first derivative of the cubic spline. Parameters: x : rank-1 np.array of np.float64, length 2 data x coordinates y : rank-1 np.array of np.float64, length 2 data y coordinates r : rank-1 np.array of np.float64, length 2 corresponding elements of output of solve_coeffs() for your data t : float point where to evaluate. Must be between the given x values. Returns: s : float Value of the derivative at the point t. """ h = x[1] - x[0] a = -2 * ( y[1] - y[0] ) + ( r[0] + r[1] ) * h b = 3 * ( y[1] - y[0] ) - ( 2*r[0] + r[1] ) * h c = r[0] * h lt = (t - x[0]) / h # 0..1 return ((3*a*lt + 2*b) * lt + c)/h
ef9aa1454c412f2ec66a112d367b5171d9de4e35
694,666
import pickle def get_challenges_for_user_id(database, user_id, ctf_channel_id): """ Fetch a list of all challenges a user is working on for a given CTF. Return a list of matching Challenge objects. """ ctfs = pickle.load(open(database, "rb")) ctf = ctfs[ctf_channel_id] challenges = [] for challenge in ctf.challenges: if user_id in challenge.players: challenges.append(challenge) return challenges
bd2c048ca88aad630bfe9fda7c37924cf93c611b
694,667
def make_gmm_unaries(X, fg_gmm, bg_gmm): """ Make unaries by log probability under GMM. Take X: data in N x K ndarray where N is no. samples and K is no. features fg_gmm, bg_gmm: fitted sklearn.mixture.gmm Give fg_unary, bg_unary: log probabilities under the fg and bg gmms resp. """ fg_un, _ = fg_gmm.score_samples(X) bg_un, _ = bg_gmm.score_samples(X) return fg_un, bg_un
d69b942d465262736c3d209be7e2de9a4ce2cf4b
694,669
def d(value: bytes) -> str: """ Decode a bytestring for interpolating into an error message. """ return value.decode(errors="backslashreplace")
5b37b195cc5a462c8eb665b0fd77cbe823f57e00
694,672
def impact_seq(impact_list): """String together all selected impacts in impact_list.""" impact_string = '' connector = '-' for impact in impact_list: impact_string += connector + impact.iname.strip() return impact_string
335a879c17e263690744c947b11be872c5ccf663
694,673
def url_to_path(url: str): """ Convert URL to path """ return url.replace("://", "___").replace(".", "__").replace("/", "_")
518fa3647d53838a9f7a68e175778f191cc82896
694,677
import requests def verify_physionet_credentials(username, password): """Returns True if the username and password are valid for the physionet.org website.""" url = "https://physionet.org/works/MIMICIIIClinicalDatabase/files/" r = requests.get(url, auth=(username, password)) return True if r.status_code == 200 else False
2821de8abf6cb1d0f9363bbb0440f9a1ae65bc99
694,680
def _find_start_entry(line, n): """Find the starting character for entry ``n`` in a space delimited ``line`` (PRIVATE). n is counted starting with 1. The n=1 field by definition begins at the first character. Returns ------- starting character : str The starting character for entry ``n``. """ # This function is used by replace_entry if n == 1: return 0 # Special case # Count the number of fields by counting spaces c = 1 leng = len(line) # Initialize variables according to whether the first character # is a space or a character if line[0] == " ": infield = False field = 0 else: infield = True field = 1 while c < leng and field < n: if infield: if line[c] == " " and line[c - 1] != " ": infield = False else: if line[c] != " ": infield = True field += 1 c += 1 return c - 1
60b609b099bae2aa6e891008a1e49c7083c6de32
694,681
def startswith_whitespace(text): """Check if text starts with a whitespace If text is not a string return False """ if not isinstance(text, str): return False return text[:1].isspace()
4c1acdfea37fc1ffdcde13fb6c68567489d91b30
694,683
def triplet(n): """Find the Pythagorean triplet who's sum equals a given number.""" for c in range(n - 3, 1, -1): for b in range(c - 1, 1, -1): a = (c**2 - b**2)**.5 if a + b + c == n: return [c, b, int(a)] return False
0f4121ac169d8830a776f4fb44d9716077288cb8
694,689
def tlv_file_xml_mapped(tlv_data_xml_mapped, tmp_path): """Return the path to an mapped XML file containing the test tree.""" path = tmp_path / "expected_mapped.xml" path.write_bytes(tlv_data_xml_mapped) return path
314a0a55112259940b6dcbd7d72beb69da400134
694,698
def bissexto(ano): """Verifica se um ano é bissexto. Retorna True se ano for bissexto ou False caso contrário. Definição de ano bissexto: Um ano é bissexto se for divisível por 400 ou então se for divisível por 4 e, ao mesmo tempo, não for divisível por 100. """ return ano % 400 == 0 or ano % 4 == 0 and ano % 100 != 0
388880697cdebe9c29b8815edb99b9fda80a2210
694,701
import re def find_all(item, items, regex=False, regex_flags=None): """ Finds the indexes and values for all values matching a given item. :param item: the value (or pattern) to match/find. :param items: an iterable of items to match against. :param regex: If True, item will be treated as a regex pattern. :param regex_flags: Optional flags for re.search(). :return: an iterable of (index, value) tuples. >>> find_all('own',['Is', 'that', 'your', 'own', 'brown', 'cow']) [(3, 'own')] >>> find_all('own',['Is', 'that', 'your', 'own', 'brown', 'cow'], regex=True) [(3, 'own'), (4, 'brown')] >>> find_all('^own$',['Is', 'that', 'your', 'own', 'brown', 'cow'], regex=True) [(3, 'own')] >>> find_all('ow',['How', 'now', 'brown', 'cow']) [] >>> find_all('ow$',['How', 'now', 'brown', 'cow'], regex=True) [(0, 'How'), (1, 'now'), (3, 'cow')] >>> find_all('[a-z]ow(?![\w])',['How', 'now', 'brown', 'cow'], regex=True) [(1, 'now'), (3, 'cow')] >>> find_all('(?<!\w)[a-z]ow',['How', 'now', 'brown', 'cow'], regex=True, regex_flags=re.IGNORECASE) [(0, 'How'), (1, 'now'), (3, 'cow')] >>> find_all('(?<=\w)[a-z]ow',['How', 'now', 'brown', 'cow'], regex=True, regex_flags=re.IGNORECASE) [(2, 'brown')] """ if regex: flags = regex_flags or 0 return [(index, value) for index, value in enumerate(items) if re.search(item, value, flags=flags)] else: return [(index, value) for index, value in enumerate(items) if value == item]
bf9e78ef94261c0ee88162e6a1be85a8cdb1dd54
694,703
def mark_doc(doc, wids, mark=None, pos=None): """ Given a list of words and a set of word positions, mark the words in those positions. :param list doc: a list of words (strings) :param set wids: the positions of the words to be marked :param string mark: a string that sets the mark that will be applied to each of the selected words :param string pos: can be one of {"prefix", "suffix"} :return: the marked list of words """ if mark is None: mark = "NEG" if pos is None: pos = "suffix" marked_doc = [] for i, tok in enumerate(doc): if i in wids: if pos == "prefix": word = mark + "_" + tok else: word = tok + "_" + mark marked_doc.append(word) else: marked_doc.append(tok) return marked_doc
481fb2d4ca8828181288d776c6f4b73e82f0443a
694,706
def unknown_char(char_name, id_ep): """Transforms character name into unknown version.""" if "#unknown#" in char_name:#trick when re-processing already processed files return char_name return f"{char_name}#unknown#{id_ep}"
061683efd275335e58129225fe4bc9dabc044c9b
694,707
def _copy_list(seq): """Recursively copy a list of lists""" def copy_items(seq): for item in seq: if isinstance(item, list): yield list(copy_items(item)) else: yield item return list(copy_items(seq))
2e179ed338bf9b5417772509ca27a84608c240d9
694,708
def calculate_occlusion(ray, obj, light, objects): """ Calculate if there is an object between the light and object Args: ray: A ray starting in the hit point with direction to the light obj: The object where the hit point is light: A source of light to calculate if it's occluded objects: The objects in the scene Returns: bool: If there is an occlusion or not """ # Check for occlusion # 1. Shoot ray from point to light # 2. Check collision with other objects # 3. If there is one between the hit point and the light, there is occlusion light_distance = light.get_distance(ray.pr) for other_obj in objects: if other_obj == obj: continue shadow_t = ray.intersect(other_obj) if 0 < shadow_t <= light_distance: return True return False
c15acf785f8baf72da64307380cd36d7de6b6ef8
694,713
def get_integer(dictionary, key): """Gets value of a key in the dictionary as a integer. Args: dictionary (dict): A dictionary. key (str): A key in the dictionary. Returns: A integer, if the value can be converted to integer. Otherwise None. """ val = dictionary.get(key) try: return int(val) except ValueError: return None
503f168ff6ecac637fde28dae3c6fc33554b5e26
694,715
from typing import Tuple def left(x: int, y: int) -> Tuple[int, int]: """Move one step to the left""" return x - 1, y
ad16a27149980c532a72970fade1b09843168a82
694,716
import re def extract_bonds_and_angle_info(force_field): """ Given a force field files, extracts the values use for equilibrium bond lengths and angles. """ info = {"bonds":{}, "angles": {}} bond_regex = r"^(.{2}-.{2})\s+\S+\w+\s+(\S+)" angle_regex = r"^(.{2}-.{2}-.{2})\s+\S+\w+\s+(\S+)" with open(force_field, "r") as f: text = f.read() # Extract bond info matches = re.finditer(bond_regex, text, re.MULTILINE) for m in matches: atoms = m.group(1) length = m.group(2) info["bonds"][atoms] = float(length) # Extract angle info matches = re.finditer(angle_regex, text, re.MULTILINE) for m in matches: atoms = m.group(1) angle = m.group(2) info["angles"][atoms] = float(angle) return info
ee314b68f9e2dfecb3b94c4493594adc30668d3e
694,717
def ymd2jd(year, month, day): """ Converts a year, month, and day to a Julian Date. This function uses an algorithm from the book "Practical Astronomy with your Calculator" by Peter Duffet-Smith (Page 7) Parameters ---------- year : int A Gregorian year month : int A Gregorian month day : int A Gregorian day Returns ------- jd : float A Julian Date computed from the input year, month, and day. """ if month == 1 or month == 2: yprime = year - 1 mprime = month + 12 else: yprime = year mprime = month if year > 1582 or (year == 1582 and (month >= 10 and day >= 15)): A = int(yprime / 100) B = 2 - A + int(A / 4.0) else: B = 0 if yprime < 0: C = int((365.25 * yprime) - 0.75) else: C = int(365.25 * yprime) D = int(30.6001 * (mprime + 1)) return B + C + D + day + 1720994.5 #def ymd2weekday(year, month, day): """ Returns the day of the week for the specified year, month, and day """ jd = ymd2jd(year, month, day) A = (jd + 1.5) / 7.0 return dayNames[round((A - int(A)) * 7.0)]
7f93c1eef14d3e75764329748d4646e41ba6fea9
694,718
def _get_default_var_dicts_planetos(dataset): """ Returns dictionary mapping PlanetOS variable names to OpenOA variable names for a particular dataset Args: dataset (:obj:`string`): Dataset name ("merra2" or "era5") Returns: :obj:`dict`: Dictionary mapping reanalysis variable names from PlanetOS to standard OpenOA variable names """ dataset = dataset.lower().strip() if dataset == "merra2": var_dict = {"U50M": "u_ms", "V50M": "v_ms", "T2M": "temperature_K", "PS": "surf_pres_Pa"} elif dataset == "era5": var_dict = { "eastward_wind_at_100_metres": "u_ms", "northward_wind_at_100_metres": "v_ms", "air_temperature_at_2_metres": "temperature_K", "surface_air_pressure": "surf_pres_Pa", } else: raise ValueError('Invalid dataset name. Currently, "merra2" and "era5" are supported.') return var_dict
b93e2b5655003ea81900e013d3c24545baae690c
694,722
from typing import Union from typing import List from typing import Any from typing import Dict def convert_to_schema(schema: Union[List[Any], Dict[str, Any], Any]) -> Dict[str, Any]: """Recursively convert a json-like object to OpenAPI example response.""" if isinstance(schema, list): return { "type": "array", "items": convert_to_schema(schema[0] if len(schema) > 0 else "???"), } if isinstance(schema, dict): return { "type": "object", "properties": {str(key): convert_to_schema(value) for key, value in schema.items()}, } return { "type": "string", "default": str(schema), }
dbb5010b50f81bb86d668850b70631cad34c9407
694,723
def match_any_re(regex_list, value): """Given a list of pre-compiled regular expressions, return the first match object. Return None if there's no Match""" for regex in regex_list: match = regex.fullmatch(value) if match: return match.groupdict()
fcb1ce9530ac990dd1048eb62883adcf9a06ab6a
694,730
def get_album_from_html(self, html): """Scrapes the html parameter to get the album name of the song on a Genius page""" parse = html.findAll("span") album = '' for i in range(len(parse)): if parse[i].text == 'Album': i += 1 album = parse[i].text.strip() break return album
a7cf940227dfd2dd9f2c7fe44073ef02489e6db1
694,734
def identity(mask): """ This is identity function that can be used as an argument of functions :func:`set_encoder` and :func:`set_decoder`. :param mask: input mask :type mask: numpy.ndarray :return: the same mask :rtype: numpy.ndarray Example: .. code-block:: python ACDC.set_encoder(ACDC.identity) ACDC.set_decoder(ACDC.identity) """ return mask
b2082ffb09501a393776e3a1b960b4b532f3e465
694,735
import json async def assert_api_post_response(cli, path: str, payload: object = None, status: int = 200, expected_body: object = None): """ Perform a POST request with the provided http cli to the provided path with the payload, asserts that the status and data received are correct. Expectation is that the API returns text/plain format json. Parameters ---------- cli : aiohttp cli aiohttp test client path : str url path to perform POST request to payload : object (default None) the payload to be sent with the POST request, as json. status : int (default 200) http status code to expect from response expected_body : object An object to assert the api response against. Returns ------- Object or None returns the body of the api response if no data was provided to assert against, otherwise returns None """ response = await cli.post(path, json=payload) assert response.status == status body = json.loads(await response.text()) if expected_body: assert body == expected_body else: return body
a09185ff957446ce99cb1bcd93d5699890b72b52
694,736
def diffangles(a1, a2): """ Difference between two angles in 0-360 degrees. :param a1: angle 1 :param a2: angle 2 :return: difference """ return 180 - abs(abs(a1 - a2) - 180)
8f17b4f1bdd822082b552aa14907bcdb4b185a4f
694,737
def split_fqn(title): """ Split fully qualified name (title) in name and parent title """ fqn = title.split('/') if len(fqn) > 1: name = fqn.pop() return (name, '/'.join(fqn)) else: return (title, None)
5595cbc5bf312f4eedf1987925ed08ae0f840087
694,741
def make_dict_from_csv(fn): """ convert listing of partial permutations with multiplicity into dict input file should have one line for each "type" of ballot - first entry is number of ballots of this type - successive entries are ranked candidates (no non-votes or repeats) - all candidates are comma-separated """ d = dict() for x in open(fn,'r'): line = x.rstrip().split(',') lbl = '_'.join(line[1:]) if lbl not in d.keys(): d[lbl] = int(line[0]) else: d[lbl] += int(line[0]) # print("%d -- %s" % (int(line[0]),lbl)) return d
2ca1dd45b7d92f036462753c5016983eea66dcd4
694,742
def _replace_special_characters(str_special_chars): """ Replaces special characters in a string with their percent-encoded counterparts ':' -> '%3A' '/' -> '%2F' ',' -> '%2C' (e.g. "1/1/9" -> "1%2F1%2F9") :param str_special_chars: string in which to substitute characters :return: new string with characters replaced by their percent-encoded counterparts """ str_percents = str_special_chars.replace(":", "%3A").replace("/", "%2F").replace( ",", "%2C") return str_percents
c488f10cd817673e853fce1651d6444e2fa2a97b
694,744
def bit_or(evaluator, ast, state): """Evaluates "left | right".""" res = evaluator.eval_ast(ast["left"], state) | evaluator.eval_ast(ast["right"], state) return res
c16ad4fd4daccf2d0f05785b7cc4032ff1b78c18
694,747
def is_snapshot_task_running(vm): """Return True if a PUT/POST/DELETE snapshot task is running for a VM""" snap_tasks = vm.get_tasks(match_dict={'view': 'vm_snapshot'}) snap_tasks.update(vm.get_tasks(match_dict={'view': 'vm_snapshot_list'})) return any(t.get('method', '').upper() in ('POST', 'PUT', 'DELETE') for t in snap_tasks.values())
26088c4583d35e5d9b069b7f5046301f5e127feb
694,750
from typing import Dict from typing import Any from typing import List def get_region_sizes(settings: Dict[str, Any]) -> List[int]: """ Compute size of each layer in network specified by `settings`. """ dim = settings["num_tasks"] + settings["obs_dim"] region_sizes = [] for region in range(settings["num_layers"]): if region == 0: region_size = settings["hidden_size"] * (dim + 1) elif region == settings["num_layers"] - 1: region_size = dim * (settings["hidden_size"] + 1) else: region_size = settings["hidden_size"] ** 2 + settings["hidden_size"] region_sizes.append(region_size) return region_sizes
c8a1880ff67bdf3bc2658162cd6827927e9c4737
694,752
def get_classification_task(graphs): """ Given the original data, determines if the task as hand is a node or graph classification task :return: str either 'graph' or 'node' """ if isinstance(graphs, list): # We're working with a model for graph classification return "graph" else: return "node"
e64620b31e68631d883e8e3d635d2147fe85cf78
694,753
import unicodedata def code_points(text, normalize=None): """Return the sequence of unicode code points as integers If normalize is not None, first apply one of the unicode normalization schemes: NFC, NFD, NFKC, NFKD. More details on normalization schemes in: https://docs.python.org/3/library/unicodedata.html#unicodedata.normalize """ if normalize is not None: text = unicodedata.normalize(normalize, text) return [ord(c) for c in text]
a01d39b2272803b75e567d190858301db9eb9251
694,754
def find_unique_name(name, names, inc_format='{name}{count:03}', sanity_count=9999999): """ Finds a unique name in a given set of names :param name: str, name to search for in the scene :param names: list<str>, set of strings to check for a unique name :param inc_format: str, used to increment the name :param sanity_count: int, used to prevent infinite search loop. Increment if needed (default=9999999) """ count = 0 ret = name while ret in names: count += 1 ret = inc_format.format(name=name, count=count) if sanity_count and count > sanity_count: raise Exception('Unable to find a unique name in {} tries, try a different format.'.format(sanity_count)) return ret
6b48426df7340f88f657097bfa8d35e32cd790f6
694,756
def get_nextupsegs(graph_r, upsegs): """Get adjacent upsegs for a list of segments as a single flat list. Parameters ---------- graph_r : dict Dictionary of upstream routing connections. (keys=segments, values=adjacent upstream segments) upsegs : list List of segments Returns ------- nextupsegs : list Flat list of next segments upstream from upsegs """ nextupsegs = set() for s in upsegs: nextupsegs.update(graph_r.get(s, {})) #nextupsegs.update(graph_r[s]) return nextupsegs
cc38dd78bd0af8cce2c0a96106bea58d1e9d0b17
694,757
def build_texts_from_gems(keens): """ Collects available text from each gem inside each keen in a list and returns it :param keens: dict of iid: keen_iid :return: texts: dict of iid: list of strings with text collected from each gem. """ texts = {} for keen in keens.values(): for gem in keen.gems: sents = [gem.text, gem.link_title, gem.link_description] sents = [s for s in sents if s] # filters empty sentences if sents: texts[gem.gem_id] = sents return texts
b9b94f4a1035f03746bd3b18755c02b19a97b27b
694,759
def filterResultsByRunsetFolder(runSets, form): """ Filters out results that don't have the specified runsetFolder name """ ret = [] for runset in runSets: if runset.runsetFolder == form['runset'].value: ret.append(runset) return ret
a9416fa8f96aa2dc370c23260f65bfb53114e09a
694,760
import csv def read_list( csvFile ): """Returns a list which has been stored as a csv file""" with open( csvFile ) as csvFile: reader = csv.reader( csvFile, quotechar='|' ) out = [ ] for row in reader: out += row return out
9fcb5b01496b39915e0169d0a19efc91a779aaf1
694,762
def find_net(table_coordinates): """ Finding net coordinates, taking avg of x1 and x4 (mid points of table) """ top_x = table_coordinates[1][0] bottom_x = table_coordinates[4][0] avg = int((top_x+bottom_x)/2) return avg
e8d8821977362c641be0ca7621802e774caf5adf
694,771
def clamp(v, lo, hi): """Return v clamped to range [lo, hi]. >>> clamp(1, 2, 3) 2 >>> clamp(4, 0, 1) 1 >>> clamp(6, 5, 8) 6 """ assert lo <= hi if v < lo: return lo elif v > hi: return hi else: return v
5b2213be8f7ce24bfb3addb6c3ff436a62ff1dbd
694,776
def collatz_sequence(seed): """Given seed generates Collatz sequence""" sequence = [seed] counter = seed # pylint: disable=misplaced-comparison-constant while 1 != counter: # pylint: disable=misplaced-comparison-constant counter = (int(counter/2) if 0 == counter%2 else 3*counter+1) sequence.append(counter) return sequence
37195042d6feae7d9ea26ebfea8c35a9436c8c11
694,777
import csv def loadFlags(file): """Takes in a filename/path and reads the data stored in the file. If it is a single column of data returns a 1D list, if it is multiple columns of data returns a 2D list. Note the first line is skipped as it assumes these are column labels. """ with open(file) as fstrm: data = csv.reader(fstrm) vals = list(data) if all([len(val)==1 for val in vals]): data = [val[0] for val in vals[1:]] else: data = vals[1:] return data
cfd48269ed94b47dfd2c12e6a7f66f8106253f15
694,779
def fopen(ref): """ Open a file and return a list of lines. """ return [i.split() for i in open(ref).readlines()]
689d74d626de2a84a1a28f219c634f3eb043ec76
694,783
import colorsys def hsl_to_rgb(hue, saturation, lightness): """Takes a colour in HSL format and produces an RGB string in the form #RRGGBB. :param hue: The Hue value (between 0 and 360). :param saturation: The Saturation value (between 0 and 100). :param lightness: The Lightness value (between 0 and 100). :raises ValueError: if any of the three parameters are outside their \ bounds.""" if not isinstance(hue, int) and not isinstance(hue, float): raise TypeError("hue must be numeric, not '%s'" % hue) if not isinstance(saturation, int) and not isinstance(saturation, float): raise TypeError("saturation must be numeric, not '%s'" % saturation) if not isinstance(lightness, int) and not isinstance(lightness, float): raise TypeError("lightness must be numeric, not '%s'" % lightness) if not (0 <= hue <= 360): raise ValueError("hue must be between 0 and 360, not '%s'" % str(hue)) if not (0 <= saturation <= 100): raise ValueError( "saturation must be between 0 and 100, not '%s'" % str(saturation) ) if not (0 <= lightness <= 100): raise ValueError( "lightness must be between 0 and 100, not '%s'" % str(lightness) ) r, g, b = colorsys.hls_to_rgb(hue / 360, lightness / 100, saturation / 100) return ("#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255))).upper()
a7d0ab91bc01c04f2ecf5afa8255f639e5758a6c
694,785
def is_overlapping(segment_time, previous_segments): """ Checks if the time of a segment overlaps with the times of existing segments. Arguments: segment_time -- a tuple of (segment_start, segment_end) for the new segment previous_segments -- a list of tuples of (segment_start, segment_end) for the existing segments Returns: True if the time segment overlaps with any of the existing segments, False otherwise """ segment_start, segment_end = segment_time # Step 1: Initialize overlap as a "False" flag. (≈ 1 line) overlap = False # Step 2: loop over the previous_segments start and end times. # Compare start/end times and set the flag to True if there is an overlap (≈ 3 lines) for previous_start, previous_end in previous_segments: if segment_start <= previous_end and segment_end >= previous_start: overlap = True return overlap
27b817a76829eb7eba63d3fd22376e4164a7bf39
694,786
def gir_merge_dicts(user, default): """Girschik's dict merge from F-RCNN python implementation""" if isinstance(user, dict) and isinstance(default, dict): for k, v in default.items(): if k not in user: user[k] = v else: user[k] = gir_merge_dicts(user[k], v) return user
49196cc305c8acb454d9d3d8d9b6ddbabd67dff8
694,790
import json def ler_arquivo(local: str) -> list: """ Essa função serve para ler um arquivo JSON e devolver um dicionário :param local: str, local onde se encontra o arquivo JSON :return: list, lista de dicionário com os dados do arquivo JSON """ with open(local, encoding='UTF-8') as arquivo: return json.loads(arquivo.read())
02f4f9460ad359939c120f605657bca6cf905a60
694,791
import re def get_derived_table(view_list): """ This function extracts the derived table clause from a view file, if it exists. :param view_list: view file broken down list :type view_list: list :return: a list of the derived table clause for a view file """ derived_list = [] for line in view_list: line_list = list(filter(None, line.split(' '))) derived_list.append(line_list) end_of_derived_table = sum([bool(re.search('dimension', s) or re.search('parameter', s) or re.search('measure', s)) for s in line_list]) if end_of_derived_table > 0: break return derived_list[1:-1]
1fe5546f387037ec393f8f4cfc4e86c09e9d74c3
694,792
import typing import ipaddress def format_address(address: typing.Optional[tuple]) -> str: """ This function accepts IPv4/IPv6 tuples and returns the formatted address string with port number """ if address is None: return "<no address>" try: host = ipaddress.ip_address(address[0]) if host.is_unspecified: return "*:{}".format(address[1]) if isinstance(host, ipaddress.IPv4Address): return "{}:{}".format(str(host), address[1]) # If IPv6 is mapped to IPv4 elif host.ipv4_mapped: return "{}:{}".format(str(host.ipv4_mapped), address[1]) return "[{}]:{}".format(str(host), address[1]) except ValueError: return "{}:{}".format(address[0], address[1])
28c735fd60f69f8bb0f038b136fc9b8d1b938a91
694,795
import json def refundCardTransactionPayload(amount, reason, merchant_refund_reference, refund_time): """ Function for constructing payload for refundCardTransaction API call. Note: All parameters are of type String unless otherwise stated below. :param amount: Integer - Amount to be refunded :param reason: Reason for refund :param merchant_refund_reference: A reference specified by the merchant to identify the refund. This field must be unique per refund. :param refund_time: Date and time of the request. Format - YYYY-MM-DD HH:mm:ss :return: JSON payload for API call """ payload_py = { "amount": amount, "reason": reason, "merchant_refund_reference": merchant_refund_reference, "refund_time": refund_time } payload_json = json.dumps(payload_py) return payload_json
6c54a5177acf1d79bc1d06e709ca9a81ffb6c9b7
694,797
def round_to(x, base=1, prec=2): """ Round to nearest base with precision. :param x: (scalar) - value to be rounded from :param base: (scalar) - value to be rounded to :param prec: (int) - number of decimal points :return rounded_val: (scalar) - rounded value """ try: return round(base * round(float(x) / base), prec) except: print('Unable to round to') return x
d8c041a99d948458ced6942f037592da225fa9e4
694,798
def select_sort(inputlist): """ 简单选择排序 :param inputlist: a list of number :return: the ascending list """ length = len(inputlist) for i in range(length): minimum = i for j in range(i, length): if inputlist[j] < inputlist[minimum]: minimum = j inputlist[i], inputlist[minimum] = inputlist[minimum], inputlist[i] return inputlist
c6163f0d7c0b5048c067d6f8d0adfd08bfb02728
694,799
def definir_orden_builtin(a: str, b: str, c: str) -> str: """Devuelve tres palabras en orden alfabético de izquierda a derecha. :param a: Primera palabra. :a type: str :param b: Segunda palabra. :b type: str :param c: Tercera palabra. :c type: str :return: Las tres palabras en orden alfabético de izquierda a derecha. :rtype: str """ return ", ".join(sorted([a, b, c], key=str.lower))
7cb1a5916a2917b942121de52020c7323c695ba8
694,800