content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def prep_summary_for_merge(df, prepend_string): """ Prepend the specified string onto every column name of the dataframe. :param df: dataframe to alter the column names of. :param prepend_string: string to prpend to each column name. :return: dataframe with modified column names """ df2 = d...
cc4e365085ce37765525bed4eca79309e979ba93
607,187
import re def argo_safe_name(name): """Some names are to be used in the Argo YAML file. For example, the generateName and template name in https://github.com/argoproj/argo/blob/master/examples/hello-world.yaml. As Argo is to use the YAML as part of Kubernetes job description YAML, these names must...
e336d0153d92aa05e1bf77c99545805d502f591a
607,189
def dict_key_lookup(the_dict, key): """ Checks if the given key exists in given dict :param the_dict: :param key: :return: str """ return the_dict.get(key, '')
23e51b1a0a50352068788e6c222c9d0c156c7a6a
607,190
def none(graph, node): """Do-nothing filter function used to display an entire graph using :func:`draw`.""" return False
b81a6cb62be28b56c0c983bd60aa38029ba18195
607,192
def kronecker_product(matrices): """ Performs Kronecker product of a list of matrices. Args: - matrices (a list of matrices) Returns: - matrix - the result of kronecker_product of matrices """ if len(matrices) < 1: return RuntimeError('The input should be a list of matric...
f808a55270a5411279ba4d22ba7ead82661a6a91
607,193
def convert_dataframe(df, schema): """Convert dataframe via column renaming or functions that map rows to values. Parameters ---------- df : pd.DataFrame Original DataFrame for conversion schema : dict dict whose keys are strings and whose values are either strings or functions. ...
9d8e1c3665a61e6cddcb056c3a04fc1f31a566f8
607,195
def to_stitch_program(program: str, stitch_dsl): """ take a dreamcoder program and rewrite it into a stitch program using a stitch dsl, specifically: - rewrite #(...) to `fn_i` - rewrite lambda -> lam """ # rewrite in reverse order so that subinventions come later so we dont mangle by rewriting ...
dca563f269f6d36faedfe4ac1ab8e30c97e207a8
607,197
def _is_str(s): """ True iff s is a string (checks via duck typing). """ return hasattr(s, 'capitalize')
206530dd9eedef9e37db9266d6226f1007d50875
607,198
from typing import Dict from typing import Set def _extract_sub_qg_adj_map(qg_adj_map: Dict[str, Set[str]], allowed_qnode_keys: Set[str]) -> Dict[str, Set[str]]: """ This function extracts the node adjacency info for a "subgraph" of the query graph (represented by allowed_qnode_keys). Example of qg_adj_ma...
8571e1d41ee18433661f27a3a64d60438487aa83
607,202
import six def get_formula_from_symbol_list(_list, separator=""): """ Return a string with the formula obtained from the list of symbols. Examples: * ``[[1,'Ba'],[1,'Ti'],[3,'O']]`` will return ``'BaTiO3'`` * ``[[2, [ [1, 'Ba'], [1, 'Ti'] ] ]]`` will return ``'(BaTi)2'`` :param _list: a list ...
4b53b1fd5d39b3ebc6f5a87f9700cb3318d3401e
607,204
def apply_default_values(table, default_values): """ Iterate through a table and use the default values as defined in launcher.json for non-mandatory columns. This is required otherwise the payload would not be constructed correctly and the post would fail. For the remaining non-mandatory columns t...
9554f21abdfbdac76e75d3a9b156fff24895820d
607,208
import re def clean(s): """ Remove rare characters and change everything to lowercase """ # s = re.sub(r'[^\x00-\x7f]', r'', s) s = re.sub("[^a-zA-Z]+", ' ', s) # remove numbers return s.lower()
5b6b734c785eb94eb080b3373c311cc0393ad41f
607,211
def _popcnt(a: int) -> int: """Returns the Hamming weight of the given non-negative integer.""" t = 0 while a > 0: a &= a - 1 t += 1 return t
7711f17a43983ce09539169222f97424a2f8329d
607,212
from typing import Union from datetime import datetime def string_or_date(s: Union[str, datetime]): """Convert given datetime to IEX conforming string or return given string (YYYYMMDD)""" if isinstance(s, str): return s elif isinstance(s, datetime): return s.strftime('%Y%m%d') raise Ty...
7e2061f04c170e192bef4c129cec5667b835a112
607,213
def convert_vegref(list_of_vegrefs): """ This function converts the Vegrefs from the JSON file to fit the documentation for the vegrefs in the NVDB API. :param list_of_vegrefs: A list of strings containing the vegrefs :return converted_vegrefs: A list of the converted vegrefps """ converted_vegr...
79fe6a8fb8f9c027da29ab3635af12b3d0f2e3be
607,214
from typing import Dict def index_post() -> Dict[str, str]: """Exemplar POST endpoint for the API service. Simply returns a welcome message.""" return {"message": "Welcome to the Hippo diagnosis service!"}
295d5e8346cc44c0d74acdb8fad78c622be9a390
607,217
def _GetProcStatusField(pstatus, field): """Retrieves a field from the contents of a proc status file. @type pstatus: string @param pstatus: Contents of /proc/$pid/status @type field: string @param field: Name of field whose value should be returned @rtype: string """ for line in pstatus.splitlines():...
f273be9138020b0a97b0a562735f0d1a5f7734be
607,220
def convertYawToDegrees(yaw): """ Converts a yaw which is -180 to 180 to a compass heading between 0 and 360 Useful in particular for the yaw value that the NavX supplies :param yaw: Initial yaw between -180 and 180 :return: Degrees 0 to 360 """ if yaw == 0.0: return 0.0 if yaw >...
bb539dbb7e839531630675e64317e4ff423ced9d
607,223
def _get_m(mu, tof, s, _lambda): """Computes the m auxiliary variable. Parameters ---------- mu: float The gravitational parameter. tof: float The time of flight. s: float The semiperimeter of the orbit. _lambda: float The transfer angle parameter. Retur...
182e642f33cace9e9e40aa9fbcee0707135c1a4b
607,229
def init_sequential_planning_program() -> str: """Initialize an ASP sequential planning program with a minimized version of the sequential horizon meta-encoding as detailed in "plasp 3: Towards Effective ASP Planning" (Dimopoulos et al. 2018 - https://arxiv.org/pdf/1812.04491.pdf) and explicitly declared in...
bd5e05dfa477c3cff4ee2b152978cac05c9f9481
607,232
def getCUIDs(term): """ Gets all CUIDs for a given pronto Ontology object (from the xrefs) Args: term (pronto Ontology): Term from ontology to extract CUIDs for Returns: list of CUIDs """ cuids = [] if 'xref' in term.other: for xref in term.other['xref']: if xref.startswith('UMLS_CUI'): cuid = xre...
92f9fa82e0c88509758b4dd783ea8a5ba1ae61ea
607,233
def t_pulse(t_2, f_2, f, DM): """ Function for generating the time values of a pulse given the frequency values. Eq. 1 in FDMT paper. t_pulse, t_2 in s f_2, f in MHz DM in pc cm^-3 """ return t_2 + 4.148808*DM*((f/1000.)**(-2) - (f_2/1000.)**(-2))/1000.
12604a6ea9eb7a808eacb4fbeff972d5180c0429
607,236
def get_query_subreads_from_alns(alns): """Given a list of alignments, return a list of non-redundant query subreads""" return list(set([aln.query_name for aln in alns]))
9aee1c56fe2031ccd4921ef6c75a1985393a4dc4
607,237
def is_outlook_msg(content): """ Checks if the given content is a Outlook msg OLE file Args: content: Content to check Returns: bool: A flag the indicates if a file is a Outlook MSG file """ return type(content) == bytes and content.startswith( b"\xD0\xCF\x11\xE0\xA1\xB...
c71c2b1b90c2e44c9cb795f448284dd51259c434
607,242
def getcf(lambda_val , Re_theta): """ Computes the skin friction coefficient, cf Assumptions: None Source: None Inputs: lambda_val - thwaites separation criteria [unitless] Re_theta - Reynolds Number as a function of momentum thickness [unitless] Outputs...
4be19282ef14ce5cf13df750a5fcc3f585465475
607,243
def snowmelt_temperature_index(temperatures, temperature_cutoff=32.0, melt_rate_coeff=0.06): """Calculate the amount of snowmelt using a temperature index method, also called degree-day method. This method has its limitations as noted in the refe...
f283487fc54700c8b3da592f0b488bdc42856e93
607,244
from typing import BinaryIO from typing import Optional def get_location(reader: BinaryIO) -> Optional[str]: """Given a binary file-handle, try to extract the path/URL to the file.""" return ( getattr(reader, "name", None) or getattr(reader, "url", None) or getattr(reader, "geturl", la...
647790487e4ea39c2cce0c230acbe26003dd0b05
607,245
def build_response(content): """Builds bot response """ response = content response += "\n***\n^(I am a bot and I byte | [source](https://github.com/jasmaa/shiritori-bot))" return response
e99e730ae5a355db8aa9bcd45abc23d05bf648c0
607,246
def indicator(cond): """Compute indicator function: cond ? 1 : 0""" res = 1 if cond else 0 return res
ee836cc872e558288a4d7fe97303a96b27decd02
607,249
from typing import Dict from typing import Any import requests import json def get_person_by_id(id_number: int, auth_dict: Dict[str, Any]) -> Any: """ This function just fetches a person by the id number from coresignal. Args ------- id_number: int the coresignal id number. Should...
0eab682a03e12c95c5f80aaddf72ae82cdc1a4da
607,252
def min_distance(polygon, point): """ Return the minimum distance between a point and a polygon edge """ dist = polygon.exterior.distance(point) for interior in polygon.interiors: dist = min(dist, interior.distance(point)) return dist
b66afa5c15e156b9f9089e7d7a3bd6ea6f98b0f8
607,253
def hours_to_minutes(hours: str) -> int: """Converts hours to minutes""" return int(hours) * 60
84057d6ed73fc20f06fb69741eb2c8bca9628548
607,256
def _is_camel_case_abb(s, index): """Determine if the index ends at 'ABb', which is the start of a camel token. For example, with 'HTMLParser', this function detects 'LPa'.""" return (index >= 2 and s[index - 2].isupper() and s[index - 1].isupper() and s[index].islower())
9017a1e18b1b5adae4e678555cdd1c1cbf11eec6
607,270
def _get_cell_value(s, row, column): """Helper function to get value in 1-D array (s), given row and column""" return s[row * 3 + column]
566ecc4f13e30cdeb8077f32de05b43ef5805eeb
607,271
def reverse_transformation(text): """ Reverses a given string so that the first character becomes the last one """ return text[::-1]
5e5480e0866739342b9282ad077d4bfc2cf1f5f9
607,272
def format_size(size): """ Convert size to XB, XKB, XMB, XGB :param size: length value :return: string value with size unit """ units = ['B', 'KB', 'MB', 'GB'] unit = '' n = size old_n = n value = size for i in units: old_n = n x, y = divmod(n, 1024) i...
76ba4e17b899a412e7e32a9d24afc5b11dc5ad3a
607,275
def findRequiredNode(xmlNode, nodeTag): """ Find the required xml node @ In, xmlNode, xml.etree.ElementTree.Element, xml element node @ In, nodeTag, str, node tag that is used to find the node @ Out, subnode, xml.etree.ElementTree.Element, xml element node """ subnode = xmlNode.find(nodeTag) if ...
46b966cd4071ee58f6f07e1aedab47d438f1c7e2
607,278
import logging import copy def graph_directional_to_undirectional(graph): """ Convert a directional to an undirectional graph Returns a deep copy of the full graph with all directional edges duplicated as undirectional ones. Undirectional edges share the same data dictionary. In converting di...
045ad1f1a7d455ca05ffe50aa4fb117957cb4ed1
607,279
def read(filepath): """ Read the contents from a file. :param str filepath: path to the file to be read :return: file contents :rtype: str """ with open(filepath, 'r') as file_handle: content = file_handle.read() return content
4b64f79ec27aedf773ad06a50fe3187199947baa
607,285
def delete_cells_from_polydata(poly,id_list): """ Removes cells from VTK PolyData with their id numbers Args: poly: VTK PolyData id_list: python list of cell id numbers Returns: poly: VTK PolyData with cells removed """ poly.BuildLinks() for idx in id_list: p...
8ccc310d9c60865d30e7d940fb98845a53203147
607,289
def create_environment(**kwargs): """ Format args for AWS environment Writes argument pairs to an array {name, value} objects, which is what AWS wants for environment overrides. """ return [{'name': k, 'value': v} for k, v in kwargs.items()]
cc2458c164ed04b533d73c733d1fd4c2cbb93fdb
607,291
def update_params(old_params, new_params, check=False): """Update old_params with new_params. If check==False, this merely adds and overwrites the content of old_params. If check==True, this only allows updating of parameters that are already present in old_params. Parameters ---------- o...
57095ac1647e113eaf01bdf9a63f252d28f4d1d5
607,296
def json_api_patch(original, patch, recurse_on=set({})): """Patch a dictionary using the JSON API semantics. Patches are applied using the following algorithm: - patch is a dictionary representing a JSON object. JSON `null` values are represented by None). - For fields that are not in `recursive_...
d843470f12a11c497632b3608dca40f77b83d8a4
607,302
def dsfr_accordion_group(items: list) -> dict: """ Returns a group of accordion items. Takes a list of dicts as parameters (see the accordeon tag for the structure of these dicts.) **Tag name**:: dsfr_accordion_group **Usage**:: {% dsfr_accordion_group data_list %} """ retur...
ca1b459c159c4164b8f88013a6149cc242260e31
607,307
def tostr(input_string): """ Change a list of strings into a multiline string """ if isinstance(input_string, list): return '\n'.join([tostr(i) for i in input_string]) else: return str(input_string)
3856c9870c9c4a85e18927b91e2ac5b5696c9cc6
607,310
def convertTo8bits(currentSlice, npArrayMin, npArrayMax): """ Description: Converts the given slice into a 8-bit array Params: - currentSlice: 2D slice - npArrayMin: the minimum voxel value of the entire volume - npArrayMax: the maximum voxel value of the entire volume Returns: ...
39925075a37f2fd8c15e04ce32ac17d600de8d42
607,316
def crop_np_image(coordinates,img): """Copying a crop box portion from image Args: coordinates ((xmin,ymin,width,height)): coordinates for box img (np.ndarray): image Returns: cropt np image """ xmin,ymin,width,height=coordinates return img[ymin:ymin+height,xmin:xmin+wid...
4cbccd86c315468e0daf5e2ebf6bf00415470ee9
607,323
def create_bzip2(archive, compression, cmd, verbosity, interactive, filenames): """Create a BZIP2 archive.""" cmdlist = [cmd, 'a'] if not interactive: cmdlist.append('-y') cmdlist.extend(['-tbzip2', '-mx=9', '--', archive]) cmdlist.extend(filenames) return cmdlist
f63f10e034407e3a92e0177b039b22e44f221455
607,324
def merge_dicts(*source_dicts): """Create a new dictionary and merge sources into it.""" target = {} for source in source_dicts: target.update(source) return target
d1ad29b0999241ea41e26f52a17dbdf3b21ca8fb
607,325
def get_original_docker_name(tool_yml): """ Gets the original docker name from a tool CWL Parameters: ----------- tool_yml : dict Tool CWL from file Returns: -------- str: Original docker name """ try: orig_docker_image_name = tool_yml["hints"]["Dock...
f4de15713d6ba79d1d783fc9cf68b665ef647737
607,326
def set_phone_number_for_subscription(log, ad, subid, phone_num): """Set phone number for subscription Args: log: log object. ad: Android device object. subid: subscription id. phone_num: phone number string. Returns: True if success. """ try: ad.cfg...
0b97f9c3448e7f0339d5c7089f52f6d701181ff1
607,327
def normalise(lst, denoms): """Normalise a list of values by dividing by sum of list.""" return [lst[i] / denoms[i] for i in range(len(lst))]
0cabd0bdb01423000e0083fafddca68d178ec470
607,328
def grid_to_ciphertext(grid: list[list[str]]) -> str: """Return the ciphertext corresponding to the given grid. Preconditions: - grid != [] - grid[0] != [] - all({len(row1) == len(row2) for row1 in grid for row2 in grid}) """ # zip transposes an array: list(zip([1, 2], [3, 4], [...
95b8549652d242f992ebafcece33f836e32789fb
607,329
def lineup_by_date(df, date, team): """ Returns team's lineup for a given date as a dictionary. """ df = df[df.kickoff == date] df = df[df.team == team] forwards = df[df.position == "forward"].player.tolist() defenders = df[df.position == "defender"].player.tolist() g...
117f50b67a5cbc2519d32a3968900b57ec0e54f8
607,333
def index_axis(obj, i, a): """ Return obj indexed at i on axis a This is done manually to support both lists and numpy arrays """ if a == None: return obj elif a == 0: return obj[i] elif a == 1: return obj[:, i] else: raise NotImplementedError()
fbb5f06fadd762d5a54280470f5d6263706e647a
607,336
import operator import math def distance_kmer_vec(queryvec, targetvec): """Calculate the cosine similarity between two vectors Parameters ---------- queryvec, targetvec: `list` with floats corresponding to relative frequencies to compare Return ---------- cos_sim: `f...
da8eb1ffe05f4750de5e9a036cae27b22931201b
607,337
from typing import Tuple def get_position(handle: str) -> Tuple[int, int, int, int]: """Gets the window location and size of a given window. Returns a 4 element tuple containing the x and y position along with the width and height. """ return (0, 0, 100, 100)
f0fc0866456d6f7ff813e28bda4539b424d04488
607,349
import yaml def get_config(configfile): """Pulls YAML configuration from file and returns dict object""" with open(configfile) as _: return yaml.load(_, Loader=yaml.FullLoader)
77029e4285174a27b4f6fc7e67e85645a0ca6229
607,352
def convert_time_string_to_wolframalpha_query_url(time_string: str) -> str: """ Converts a time string to a Wolframalpha URL Returns: - The converted URL that links to the Wolframalpha query results """ formatted_query = time_string.replace(" ", "+") return f"https://www.wolframalpha.co...
4b2bada509232399bb0450313dcedc7726fef878
607,357
from typing import List import re def number2kansuuzi(tokens: List[str]) -> List[str]: """ >>> number2kansuuzi(['大引け', 'は', '147円', '高', 'の', '14000円']) ['大引け', 'は', '147円', '高', 'の', '1万4000円'] >>> number2kansuuzi(['10000円', '台']) ['1万円', '台'] """ def convert(token: str) -> str: i...
39175f36e755bac96d0e0f978e3d436efd499b51
607,359
import socket def _establish_socket_connection(ip, timeout, port=7777): """Establish socket connection to the LS372. Parameters ---------- ip : str IP address of the LS372 timeout : int timeout period for the socket connection in seconds port : int Port for the connect...
00932a2cf5f8e02e8176e8a379ac893eecac6dc6
607,361
def is_collinear(x1: float, y1: float , x2: float, y2: float, x3: float, y3: float) -> bool: """ Finds whether given three points are collinear. Parameters: x1, y1 : The x and y coordinates of first point x2, y2 : The x and y coordinates of second point ...
5d6ff4f8957fa11e533f83d213531a18c72756f2
607,362
def extract_date_from_iso8601(record, timestamp_key): """ Extract date from iso8601 timestamp """ return record[timestamp_key].split("T")[0]
f3d62d2c7f376f3c233ceeb840c1e2379f668836
607,363
import re def regstrip(string, char_to_remove=None): """Does the same thing as the strip() method using regex: - without 2nd argument it removes all the whitespace characters - 2nd argument provides possibility to remove custom characters, must be given as a string""" if char_to_remove: pattern = str('[' + c...
77f86d650325710c06b126eff482632a898092f7
607,364
def shquote(arg): """Quote an argument for later parsing by shlex.split()""" for c in '"', "'", "\\", "#": if c in arg: return repr(arg) if arg.split()!=[arg]: return repr(arg) return arg
543894d6bf98ae27000d0ee4241f908546d9722e
607,366
import itertools import math def euler85(target=2000000): """Solution for problem 85.""" # nb_rect(i, 1) = 1 (of size i) + 2 (of size i-1) + ... + i (of size 1) = i*(i+1)/2 # nb_rect(i, j) = nb_rect(i, 1) (of height j) + 2 * nb_rect(i, 1) (of height j-1) + ... + j * nb_rect(i, 1) (of height 1) # ...
fbbeffe77dba31a848ce3253c2c3cab4be047617
607,368
def mutator_show_noun_only(nocaption=False): """Mutate the image to show the noun only. Args: nocaption: [bool] If true, then do not display the caption, only consistently colored boxes for the noun. ..note:: To color boxes by track rather than noun, use `vipy.image.mutator_show_trackon...
2987f4e939835c92d129e37f0a787bb3deb7030d
607,369
async def hello(): """Returns a friendly greeting 👋""" return {'message': 'Hello user!'}
613bdadae5c6b4ebc70aedd443731ff4e1da1498
607,371
def urljoin(*paths: str) -> str: """Join together a set of url components.""" # urllib's urljoin has a few gotchas and doesn't handle multiple paths return "/".join(map(lambda path: path.strip("/"), paths))
6adfa42011bbe70a643a22bb9cc63261bef4fc8c
607,372
def decompose(num, bytes=3): """ Decompose the value *num* into a list of *bytes* 8-bit values. """ return [(num >> (i * 8)) & 0xFF for i in range(bytes)]
e4d302a20ec194dfa6e687cbd28ce1c9290a8eb2
607,375
def S_crop_values(_data_list, _max, _min): """ Returns a filtered data where values are discarded according to max, min limits. """ f_data = [] ds = len(_data_list) i = 0 while i < ds: if _data_list[i] >= _max: f_data.append(_max) elif _data_list[i] <= _min: ...
2e5eac918d16c9a25009d368308782fdb300eea0
607,376
from typing import Union from typing import Dict from typing import Any from typing import MutableMapping from typing import List from typing import Set def delete_keys_from_dict( dictionary: Union[Dict[Any, Any], MutableMapping], keys: Union[str, List[str], Set[str]] # type: ignore ) -> Dict[Any, Any]: """ ...
8d81b014be3cef7120e41ee3610462b9625566d6
607,378
def xor_encrypt(plaintext: str, key: int) -> str: """ Encrypt a plaintext into a hex-encoded ciphertext. Args: plaintext (str): The plaintext to encrypt key (int): The single-byte key Returns: str: The hex-encoded ciphertext """ return bytes(ord(c) ^ key for c in plaintext)...
e9ec3c4e52ac7b040083ef485af54b68e6b3015c
607,380
def print_num(n): """Print a number with proper formatting depending on int/float""" if float(n).is_integer(): return print(int(n)) else: return print(n)
bb5c22ab64b93709bb5e99fb746bc98a7757add4
607,384
def _on_batch_overridden(callback): """Check if on_batch_begin or on_batch_end were overridden If the method does not exist at all, it's not considered overridden. This is mostly for callbacks that are mocked. """ try: base_skorch_cls = next(cls for cls in callback.__class__.__mro__ ...
75907324990959789c2356202e39962717bb3ed7
607,387
import typing def _mode(path: str) -> typing.Literal["ab", "wb"]: """Extract the writing mode (overwrite or append) from a path spec""" if path.startswith("+"): return "ab" else: return "wb"
36d951915e9be168cb65c4913041f6c3f0e2ef0c
607,389
from pathlib import Path def generate_identified_filename(filename: Path, identifier: str) -> Path: """ Append a string-identifier at the end (before the extension, if any) to the provided filepath Args: filename: pathlib.Path The actual path object we would like to add an identifier suffix ...
7e06aa8ee4eb5daed488c119d4f9a014a1e74d97
607,391
def remove_duplicate_words(s): """ removes duplicate words from a string s: a string of words separated by spaces """ s = s.split() unique = [] for word in s: if word not in unique: unique.append(word) s = ' '.join(unique) return s
cac43d36a511fc65e7732a5eadcd5da4471f764f
607,396
def empty_list(*args): """ Returns an empty list, whatever the arguments. """ return []
c174fb33e57ae8b0e66eb85bf4589272f990a590
607,398
def insert_activity_classifier_attribute(log, classifier, force_activity_transition_insertion=False): """ Insert the specified classifier as additional event attribute in the log Parameters ----------- log Trace log classifier Event classifier force_activity_transition_inser...
3ef027fa386958b4862656a28f9e6d3e40c0bbd1
607,399
def short_to_long(arg: str) -> str: """Convert the short form of an argument to its long form.""" if arg == "-h": return "--help" elif arg == "-v": return "--version" elif arg == "-q": return "--quiet" else: return arg
34b73102d2a57a3e471b36da33d2c65d68e472bd
607,400
from pathlib import Path def read_final(path: Path) -> str: """ Repeatedly read the file until it is non-empty. Some notebook editors empty the source file before updating it. """ contents = '' while len(contents) == 0: with path.open() as file: contents = file.read() ...
e9a8951d7fd14ec881a567018277cd3fcbb989f1
607,403
def encode_datetime(dt): """Converts provided datetime object into ISO 8601/RFC3339-compliant string :param datetime.datetime dt: datetime object :return: string representation of dt :rtype: str """ s = dt.isoformat() if s.endswith('+00:00'): s = s[:-6] + 'Z' if dt.tzinfo is Non...
609daac917cccd4f42b96852352d412e8bde34ca
607,404
def find_l_context(tokens, i, n=5): """ Trouve et renvoie le contexte gauche d'un mot d'indice i dans la liste tokens Args: tokens (list): liste des tokens i (int): indice du mot pivot dans tokens n (int): longueur du contexte Returns: str: les n tokens à gauche du mo...
b338d61c7984a8b3405fb788d029a4f79e42ef42
607,405
import re def find_uptime(show_ver): """ Example: pynet-rtr1 uptime is 3 weeks, 1 day, 3 hours, 52 minutes """ match = re.search(r".* uptime is (.*)", show_ver) if match: return match.group(1) return ''
b8be152a6010156c274bbbca57c18b8383e84d27
607,407
def display_segments(image, image_draw, coordinates, image_height=1024, image_width=1024, segment_width=5): """ Draw segments between body parts according to predicted body part locations. Args: image: PIL Image The loaded image the coordinate predictions are inferred for im...
eb570a079f0244d4de2423a040e7ab6738a2309c
607,412
def rhonfw(re,alpha): """ NAME: rhonfw PURPOSE: Calculate the ratio of the NFW and soliton sections. USAGE: x = rhonfw(re,alpha) ARGUMENTS: alpha is a positive parameter, re is the transition radius. RETURNS: The value of the ratio of the sections. WRITTEN: Antonio Herr...
93f6357909640f87323acd44b49254d0d52afb2d
607,415
import json def GetErrorContent(error): """Returns the contents of an error returned by Google Compute APIs as a dictionary or None. """ if not error.resp.get('content-type', '').startswith('application/json'): return None return json.loads(error.content)
68b441fe01f8e7d5e099660a3e1c784729ee38ce
607,419
def read_cipher_alphabet(filename: str) -> str: """Reads the cipher text from text file Args: filename (str): the name of file containing cipher text Returns: str: the string consisting of the cipher text """ file_openend = open(filename) return file_openend.read()
921563a1565b7297a5a7fc3babdd72d3f5a08c2d
607,420
from typing import List from typing import Dict from typing import Any import requests def pinSearch( query: str, pinata_api_key: str, pinata_secret: str ) -> List[Dict[str, Any]]: """ Purpose: Query pins for data Args: query - the query str pinata_api_key - pinata api key ...
413422870a35a4fc438e53e376fe96f7a15fb0f5
607,424
import re def filter_lines(lines, pattern): """Returns `lines` minus any line matching `pattern`.""" if isinstance(lines, str): lines = lines.split('\n') regex = re.compile(pattern) lines = [line for line in lines if not regex.match(line)] return '\n'.join(lines)
00af1919d6f912d4c127048f6a5a5319edcb1098
607,426
def hsv_to_hex(h, s, v): """ >>> print(hsv_to_hex(0, 0, 0)) #000000 >>> print(hsv_to_hex(0, 0, 1)) #FFFFFF >>> print(hsv_to_hex(0, 1, 1)) #FF0000 >>> print(hsv_to_hex(120, 1, 1)) #00FF00 >>> print(hsv_to_hex(240, 1, 1)) #0000FF >>> print(hsv_to_hex(60, 1, 1)) #FFFF00 ...
8f33987dcd4d4d8f48c4087906e732e212c57cec
607,431
def swap_elements(arr, axis0, axis1, offset=0): """Swap elements within an list or tuple. Args: arr: List or tuple in which to swap elements. axis0: Index of first element to swap. axis1: Index of second element to swap. offset: Offsets for indices; defaults to 0. R...
18585bab77f8d3995fcf5ab68d52e05b3b1e706a
607,436
def polygon_area(polygon): """Calculates the area of an arbitrary polygon.""" area = 0.0 n = len(polygon) if n > 0: polygon -= polygon[0] for j, p1 in enumerate(polygon): p2 = polygon[(j+1) % n] area += p1[0] * p2[1] - p2[0] * p1[1] return 0.5 * area
2c7f858d5a19edac18f9572d6b469dbd6db67ab4
607,437
import re def is_family_url(url: str) -> bool: """Checks that a given URL points to a Pfam family page, e.g.: - http://pfam.xfam.org/family/PF16122 - http://pfam.xfam.org/family?acc=PF16122 - http://pfam.xfam.org/family/DIM URL with multiple slashes (e.g. http://pfam.xfam.org//family/PF1612...
efba93ed888de0eadb41641e38bfa309eb8d711e
607,438
def generic_print(expr): """Returns expr surrounded by newlines""" return "\n"+expr+"\n"
3906621091c632f4eb586fad8dd13c95747df481
607,440
def TypeOrVar(dart_type, comment=None): """Returns string for declaring something with |dart_type| in a context where if a type is omitted, 'var' must be used instead.""" if dart_type == 'dynamic': if comment: return 'var /*%s*/' % comment # e.g. var /*T*/ x; else: re...
ac333f4baa9ea6e2475c455e3241d806861e4e7f
607,442
def transitive_closure(mapping, start): """ Return all of the things you can get to by any number of applications of the mapping, starting at 'start'. """ result = set() to_check = [start] while to_check: this_one = to_check.pop() for item in mapping[this_one]: re...
e7d747f981a43d12f041f784eaa8aff2d370defc
607,444
import re def multireplace(tobereplaced, substitute): """ Returns replaced string given string and substitute map. Parameters ---------- tobereplaced : str String to execute replacements on. substitute : dict Substitute dictionary {value to find: value to replace}. Return...
a07eb4e72494dc84a83e0266eea8defaf24ebace
607,447
def _is_lt(series, value): """ Returns the index of rows from series where series < value. Parameters ---------- series : pandas.Series The data to be queried value : list-like The values to be tested Returns ------- index : pandas.index The index of series for...
757dc06b9c8b91619f2ac02d85c44d1d4b32a387
607,453