content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import re def replace_emoticons_with_tags(tweet): """ Replaces emoticons in a tweet with tags. INPUT: tweet: original tweet as a string OUTPU: tweet with emoticons replaced """ hearts = set(['<3', '❤']) happy_faces = set([ ':)', ":')", '=)', ':-)', ':]', ":']", '=]...
bec8829ce963da7759db87e1bbb320227bc6ad7a
643,783
def message_filter(msg): """Return True if the message cannot be considered as a repeat.""" if msg == '' or '--' in msg or 'List:\n' in msg: return True return False
d194bad3971abe733666a6546f07f0fc6cb5359a
643,784
import time def hours_offset(): """ Generate the numerical hour offset for the timezone relative to UTC. """ return {'timezone_hours_offset': time.strftime('%z')}
ea51077ba72c56ab2aae8f7abf2bb6f6d7123218
643,785
from typing import Iterable def get_velocity_range_y(target: Iterable[int]) -> Iterable[int]: """Get the y-velocity range to reach the `target`""" target_minimum = min(target) min_velocity = target_minimum max_velocity = abs(target_minimum) - 1 return range(min_velocity, max_velocity + 1)
a605db113141afa2abe14d729db5ee082867f2ce
643,786
import re def split_hname(hname): """split a hierarchical name (hname) into parts. double '/' is used to escape the '/'. and is transformed into a into single '/' e.g. hname = "network/network-fd02:://64" => ["network", "network-fd02::/64"] :param str hname: hierarchical name ...
bb88dd2164a37c42a109332f6d62a85d2d009198
643,787
def get_distances(clusters): """Extract distances as intermediate values between 2 clusters""" clusters_ext = list(clusters) clusters_ext.insert(0, str(0)) distances = [] for idx, _ in enumerate(clusters_ext[:-1]): clst_0 = float(clusters_ext[idx]) clst_1 = float(clusters_ext[idx + ...
fe97fe9d65ec4b4021e670a042f59cab7df79314
643,788
def _get_dependencies_in_namespace(msg_desc, namespace): """Return all message dependencies in the given namespace.""" dependencies = [] for key in msg_desc.message_dependencies: if key.startswith(namespace): dependencies.append(key) return dependencies
1d1369c068fcc3c71c7081532030f9503a4755b9
643,789
def esc(s): """ Escapes a string to prevent html injection Returns a string with special HTML characters replaced. Used to sanitize output to prevent XSS. We looked at alternatives but there wasn't anything of an appropriate scope that we could find. In the long-term this should be repla...
c94d0a5638019e23ee9f71dfb198031f6032d7c8
643,790
def word_tokenizer(text): """ Dataset is already tokenized """ return text.split(" ")
fc1e44f69fcdd5b704af592c7f7e7010119410df
643,791
import re def validar_cpf(cpf): """Rotina para validação do CPF - Cadastro Nacional de Pessoa Física. :Return: True or False :Parameters: - 'cpf': CPF to be validate. """ # Limpando o cpf if not cpf.isdigit(): cpf = re.sub('[^0-9]', '', cpf) if len(cpf) != 11 or cpf == c...
db9852d534c9894c50dcdb1ee709ef6ff27f7699
643,792
import re def process_string_and_remove_tags(raw_string: str): """Removes tags and converts newlines to match ace offsets alignment""" raw_string = raw_string.replace('\r\n', '\n') return re.sub(r'<[\s\S]*?>', '', raw_string)
a4e82ad0728519b5646be767e60f8dfa7be760ef
643,793
import os def parse_list_arg(l): """Return a list of line values if it's a file or a list of values if it is a string""" if os.path.isfile(l): f = open(l, 'r', encoding='utf-8') return [line.strip("\n").split()[0] for line in f] else: return [el for el in l.split(" ")]
ccaafe5380342c029d0342d734612afde51e5745
643,794
import typing def RgbToInt(rgb: typing.Tuple[int, int, int]): # -> int: """Converts a RGB tuple to a integer color value :param rgb: :class:`tuple[int,int,int]` RGB tuple :param no: :class:`tuple[int,int,int]` RGB tuple :returns: :class:`int` The integer color value. """...
06aae5fc8bbb5c658179a5fe3acf673accb4599e
643,795
from datetime import datetime def get_str_dt_use_timestamp(nt, mill=1000): """ 从时间戳中获得日期 """ dt = datetime.fromtimestamp(float(nt) / mill) return dt.strftime("%Y-%m-%d %H:%M:%S")
f83499c020b1634373afd475a8ac702dcfa84e13
643,796
from typing import Any def get_client_region(client: Any) -> str: """Get the region from a boto3 client. Args: client: The client to get the region from. Returns: AWS region string. """ return client._client_config.region_name
1b6d0810d7376bd5ef8ea59d7ae700c39a89e610
643,799
def _compute_depth_recursively(event): """Return the depth of the current event. The depth is the largest number of possible successive descend into the children field. Args: event (json): Json representing the current event. Returns: The depth of the current event. """ if event['c...
e36fde83e787406892f686fc4278e8e25ef68fe4
643,800
import random import string def random_pass(length=20): """Generate a random string of letters and digits """ return "".join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
e23d82e8c4328e07bb57c7aab4be8817f73f25d5
643,801
import re def read_urls(filename): """Returns a list of the puzzle urls from the given log file, extracting the hostname from the filename itself. Screens out duplicate urls and returns the urls sorted into increasing order.""" # NOTE: Hostname not longer exists hostName = 'http://'+ filename...
56226030bc9a0ec33d416a8cb62d20cd79c75196
643,802
def problem_8_3(data): """ Write a method that returns all subsets of a set. Complexity: O(2^n) """ def subsets(s): """ Returns a list of sets given the input set. """ if len(s) == 0: return [set()] head = s.pop() subs = subsets(s) out = subs[:] ...
5a5a2ca7aa8bac3b50bd85355ece7bca04389244
643,803
def namedtuple_to_dict(data): """ Converts a namedtuple to a dictionary with the top-level key being the class name. """ return {type(data).__name__.lower(): dict(data._asdict())}
fcbc01c822932636f30a41e1f2870528e14865ea
643,804
import math def prime_sieve(num: int) -> list[int]: """ Returns a list with all prime numbers up to n. >>> prime_sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] >>> prime_sieve(25) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> prime_sieve(10) [2, 3, 5, 7] >>> prime_sieve...
5ff2708fb92387ac671b54829ff4710fcf7ac2a8
643,805
def get_yonetoku_relationship(energies): """ Returns the Yonetoku relationship for a given set of energies. The original paper scaled L_iso by 10^52 so undo that here :param energies: :return: """ return 1e52*(2.34e-5)*energies**2
c8f84cc84802f5db969c8c6314d5924a3e56d88c
643,806
def shipDown(self): """ Returns True if alien bolt collides with ship and removes bolt from _bolts""" for bolt in self._bolts: if self._ship is not None and self._animator is None: if self._ship.collides(bolt): # Sound(self._soundList[0]).play() self._bolts.re...
1de376d7d4343068ffb6ea8b65d8382291d1c895
643,807
def get_prediction(data,model): """ Predict the class of a given data point. """ severity = ["Fatal injury", "Serious Injury", "Slight Injury"] pred = model.predict(data) return severity[pred[0]-1]
7b455a3472c8d43512708b46f756d6ec369dcdc1
643,808
import wave def read_audio(path): """ Read the audio from path into a wave_read object. Parameters ---------- path : string Specifies path of the audio file. Returns ------- wave_reader : class : 'wave.Wave_read' wave_params : class : 'wave._wave_params' """ wave...
0b91aac08e2e0520c90ffa1360cc32aa82665900
643,809
import base64 def py_base64(s): """ """ return base64.b64encode(s.encode('utf-8'))
8b615e45b9aef79a883dda49595a5f67cc08fd71
643,810
def ask_question(question, not_done): """Method to ask the user a simple yes or no question""" while not_done: answer = input("\n[?] {} ['yes' or 'no']: ".format(question)) if answer[0].lower() == "y": break if answer[0].lower() == "n": not_done = False ...
bc8a661fa2c301b652d98d6eae01c7ff03cce6c5
643,811
def _depth_first_select(rectangles): """Find a rectangle of minimum area for bisection.""" min_area, j = None, None for i, (_, (u, v), (s, t), _, _, _, _) in enumerate(rectangles): area = (s - u)*(t - v) if min_area is None or area < min_area: min_area, j = area, i return ...
b305602422fbfd293e673e5ba762f1235a83c374
643,812
def _optimize_movement_list(movements): """ Optimize the movements list) Parameters ---------- movements : list The list of movements to optimize Returns ------- movements_optimized : list The list of movements optimized Cases ----- 1- [A , A ] or [...
ad1f8d3ce45056cd89cf6e3839ef13b72f262f02
643,813
def add_char_padding(sent_list, dictionary): """ args sent_list: [batch_size, seq_len, token_len, char_id] dictionary: Dictionary return char_list: [batch_size*seq_len, token_len, char_id] """ batch_size = len(sent_list) max_seq_len = max([len(sent) for sent in sent_list]) max_t...
0e303d35a988bc5467ab6d7f962f172ebe6490b6
643,814
import copy def calculateTileCountUpToTier(tierSizeInTiles): """ The function caclulate the tileCount up to the top tier Arguments: tileSizeInTiles {Array} Return: {Array} """ tileCountUpToTier = [0] tmp_tierSizeInTiles = copy.copy(tierSizeInTiles) tmp_tierSizeInTiles.reverse() ...
55d53c900605850da9da627a27bfff803fb0f49f
643,815
def locus_generator(start, stop, length, n, f): """Generate index positions Parameters ---------- start : int A starting or minimum index stop : int The largest possible index length : int The length of a substring to extract n : int The number of indices to ...
ade11318c4f05a20e780087177ad69c7f9aed8f9
643,816
from sys import version def buildHeader(width): """Generate the header string.""" header = str(version) + "/" + str(width) + "/" return header
8c810a17928cdcd1253faa6f04b672e212f348dc
643,817
def get_gRNAs(db): """get gRNAs :param db: ultra or g_ultra list :return: set object with sequences as elements """ hold = [] for j in range(len(db)): hold.append(db[j].split(',')[0]) hold_set = set(hold) return hold_set
3f99e6a8af52e678dd77a72634e314968c5bd46c
643,818
def pcircle(self, xcentr="", ycentr="", xlrad="", **kwargs): """Creates an annotation circle (GUI). APDL Command: /PCIRCLE Parameters ---------- xcentr Circle X center location (-1.0 < X < 2.0). ycentr Circle Y center location (-1.0 < Y < 1.0). xlrad Circle radius...
beed27a0eb54159272c6f448036cfba3a6d8d05d
643,819
def html_strip(text): """ Strips html markup from text """ mark = 0 markstart = 0 markend = 0 index = 0 occur = 0 for i in text: if i == "<": try: if text[index+1] != " ": mark = 1 markstart = index ...
62ef2549e4f2f000846c3855e8d1534e3276ebc2
643,820
import socket def find_open_port(): """Bind to an ephemeral port, force it into the TIME_WAIT state, and unbind it. This means that further ephemeral port alloctions won't pick this "reserved" port, but subprocesses can still bind to it explicitly, given that they use SO_REUSEADDR. By defaul...
b69b3338575e21dbf27651098c0ae7c168ab3f86
643,822
import math def floor(value): """Rounds a number down to the nearest whole number.""" return math.floor(value)
ae79c659bbdb157c2d79e7bb7ba1747ef19ada1c
643,823
from typing import Union from typing import List from typing import Optional def sync_get_ami_arch_from_processor_arches(processor_arches: Union[str, List[str]]) -> str: """Maps a processor architecture to the equivalent AMI architecture""" if not isinstance(processor_arches, list): processor_arches = [ proce...
7ac10a6050d116e99a396e7f7d2cc6545124adf8
643,825
def massage(depender, components, packages): """ @param depender: A DependerData object @param components: Component names, in either package/component format, or just "naked" (hopefully unique) components. @param packages: Package names, which expand into their constituent components. @return A set of al...
bbc3138c23cb9d6f3bb39a83dde31cca3b88805e
643,827
def build_feature_dict(opt): """Make mapping of feature option to feature index.""" feature_dict = {} if opt['use_in_question']: feature_dict['in_question'] = len(feature_dict) feature_dict['in_question_uncased'] = len(feature_dict) if opt['use_tf']: feature_dict['tf'] = len(feat...
2b2d4c34637a3709766cf8f8cfc3df5b6910d8b3
643,828
import argparse import os import multiprocessing def get_args(): """Init argparser and return the args from cli.""" parser = argparse.ArgumentParser() parser.add_argument( "-c", "--config", help="the config file", type=str, default=os.getcwd() + os.sep + "judge.conf...
73b4ba6c4f3d2fc31da45e1ae2b0b763b3a3f60e
643,829
import math def to_degree7(r): """ Convert radians to 'degrees' with a 0-7 scale. :param r: :return: direction in 7-value degrees """ return round(r * 4 / math.pi)
832a5bac58114f2b121cf0bd5dc92bc124ad3381
643,830
import operator def ParseIpRanges(messages, ip_ranges): """Parse a dict of IP ranges into AdvertisedPrefix objects. Args: messages: API messages holder. ip_ranges: A dict of IP ranges of the form ip_range=description, where ip_range is a CIDR-formatted IP and description is an optional ...
67421829f0451859e940de282b84230e4252d58c
643,831
def iscellular(kit_name): """ Determine if a kit is a cellular kit or a WiFi kit based on kit name. :param kit_name: Name of the kit the LTE-M name is only used in prototype kits """ return "CELLULAR" in kit_name.upper() or "LTE-M" in kit_name
151430128f348866e58fc4d3c41ecbf6a4d69a2f
643,832
import os def get_jpeg_data_files_paths(): """ Returns the input file folders path :return: list of strings The input file paths as list [train_jpeg_dir, test_jpeg_dir, test_jpeg_additional, train_csv_file] """ data_root_folder = os.path.abspath("../input/") train_jpeg_dir = os.path....
c5e996feeb4f180350b99f2ef9817d66e5a4476d
643,833
def radix_sort(alist): """基数排序 radix_sort 耗时:439 毫秒 """ # 记录正在对哪一位进行排序,最低位为个位 i = 0 # 最大值的位数 max_num = max(alist) j = len(str(max_num)) while i < j: # 建立桶数组,数字为0-9,所以建10个桶 bucket_list = [[] for i in range(10)] # 按位数的大小分别装进不同的桶里 for num in alist: ...
08114e67bcfd4d4195cdedfc73bc13dbf23dd225
643,834
def parentheses(n, count_open=0, count_close=0, item_str="", ret=[]): """ Return all parentheses with n length :param n: number :param count_open: number :param count_close: number :param item_str: string :param ret: list :return: """ if count_close == int(n): ret.append(...
a5cd6b7b4087fb3cf119634f7a9fd500994891c6
643,835
def no_args_help_message(): """! @brief Returns a help message if no arguments were presented. @return The "no arguments" help message. """ message = "**** Execution Terminated ****\n" message += "No Options were provided. Please use Options with PyPalEx.\n" message += "Examples:\n" mes...
d93756164ad9f2aca2dda73c6bb609f9ad2617dd
643,836
def rb_epc(fit, rb_pattern): """Take the rb fit data and convert it into EPC (error per Clifford) Args: fit (dict): dictionary of the fit quantities (A, alpha, B) with the keys 'qn' where n is the qubit and subkeys 'fit', e.g. {'q0':{'fit': [1, 0, 0.9], 'fiterr': [0, 0, 0]}}} ...
74bcf29747cfe5522ff5f6085fc0a8b71c48569f
643,837
def get_string_range(float_range, x_buffer=0, y_buffer=0): """ Buffer is for the possible interface between pixel-node-registered and gridline-node-registered files :param float_range: list, [w, e, s, n] :type float_range: list :param x_buffer: possible interface between pixel-node-registered etc. ...
c146d96f154cfa615d6f304b74feb62d880d069c
643,838
import ntpath import posixpath def MakeZipPath(os_path, isdir, iswindows): """Changes a path into zipfile format. # doctest doesn't seem to honor r'' strings, so the backslashes need to be # escaped. >>> MakeZipPath(r'C:\\users\\foobar\\blah', False, True) 'users/foobar/blah' >>> MakeZipPath('/tmp/tmpfoo...
175070384239c751a6662a4f46133f0dad69d84f
643,839
def bytes_from_str( size_str ): """ Given a string description of directory size, return float bytes. Supports B, K, M, G, T suffixes. B can be ommitted. """ unit_conversions = { char: 1024**power for ( power, char ) in enumerate( [ "B", "K", "M", "G", "T" ] ) } try: coeff = unit_convers...
43c0abdf513ebb60ed486f1a8c9a8143d4dbcf0e
643,840
def test_function_arbitrary_arguments(): """任意的参数列表""" # 当出现 **name 的最后一个正式形参时,它将接收一个字典,其中包含除与正式形参对应的关键字参数外的所有关键字参数。 # 这可以与 *name 的形式参数结合使用,该形式参数接收一个包含形式参数列表之外的位置参数的元组。 # (*name 必须出现在 **name之前。)例如,如果我们这样定义一个函数: def test_function(first_param, *arguments): """这个函数通过“arguments”元组和关键字字典接受它的参数。"...
9ce82646148165876ae80b6045ea6e8b1a126857
643,841
import functools def _str_table_result(cols, rows): """Turn a Civis Query result into a readable table.""" str_rows = [['' if _v is None else _v for _v in row] for row in rows] # Determine the maximum width of each column. # First find the width of each element in each row, then find the max # wid...
397c71590d630d61a7204c1098191de5ff433f56
643,842
def gather_dictBK(Dinit, Dmodified, index, D0, D1, D2, D3, D4, D5): """ Gather the Boundaries Actions Performances dictionary to use it in Electre Tri :param Dinit: Initial dictionary containing the form of the gathered dictionary. :param Dmodified: Modified dictionary to be included in gathe...
3bc6ba80ee81f42c953d4a4320c5391fa2a064f2
643,843
def getNodeValue(dom, nodename): """ get 'myname' from a xml structure like this one when you call this method with 'name': <?xml version="1.0" encoding="UTF-8" ?> <root> <name>myname</name> </root> """ return dom.getElementsByTagName(nodename).item(0).firstChild.nodeValue
77b49ce418ba82d1f4f42b81b62f35d38978d9a7
643,844
def get_recipients(connection, search_term, search_pattern="CONTAINS_ANY_WORD", offset=0, limit=-1, enabled_status='ALL'): """Get information for a set of recipients. Args: connection(object): MicroStrategy connection object returned by `connection.Connection()`. ...
cfc1bf8e62395ef63aa36c97d4ab280d9851584b
643,845
def bin_centers(bins): """ Centers of histogram bins to plothistograms as lines :param bins: Bins limits. :return: Centers of bins. """ return bins[:-1] + (bins[1:] - bins[:-1]) / 2.0
e30c67efcb8e2249d23aebe73f1bff4894ed9b4d
643,846
def get_max_row_column(train, val, test): """Returns the total number of rows, columns from train, validation and test arrays in COO form.""" r = max(max(train[:, 0]), max(val[:, 0]), max(test[:, 0])).astype(int) + 1 c = max(max(train[:, 1]), max(val[:, 1]), max(test[:, 1])).astype(int) + 1 return r, c
43f07cc68f5b4dcee2503ffb0d704ad599407efd
643,847
def is_string(ins): """Convenience wrapper""" if ins.is_cstr(): return True return False
2dd0540f7aa2aaf15279fc105e02eaca57bb6e8c
643,848
import sys import ctypes def to_hwnd(pycobject): """ Convenience method to get a Windows Handle from a PySide WinID Based on http://srinikom.github.io/pyside-bz-archive/523.html @return A value equivalent to a void* that represents the Windows handle if one exists; None otherwise. """ if type...
174c4ca0d4b91c17c01cdb8df209ff2cbf7df4eb
643,849
def residualSumOfSquares(xs,ys,func): """Return the residual sum of squares.""" return sum([(func(xs[i])-ys[i])**2 for i in range(len(xs))])
c513c0100a4076ccf8a2de580a6af5caeb9cd373
643,850
import re def get(tags=[]): """Compile requirements by tag from conda's environment.yml file.""" with open("environment.yml", "r") as f: conda_env_yml = f.readlines() pip_idx = conda_env_yml.index(" - pip:\n") requirements = conda_env_yml[pip_idx + 1 :] if tags: r...
69d3651523fc2d93512d56e070a7bd421de3e3c5
643,851
def http_handle_GET(request_string): """Given a http requst return a response Both request and response are unicode strings with platform standard line endings. """ print('request: ' + request_string) assert not isinstance(request_string, bytes) contents = '' try: with open(req...
1cea68defaa96476a487b05c119a7ebb288a8881
643,852
from typing import Iterable def _get_common_letters(box_id1: str, box_id2: str) -> str: """Returns common letters in the box ids Arguments: box_id1 {String} box_id2 {String} Returns: [String] """ # I can iterate through both the string and find out the diff in one iteration...
8e20830b951d1876d523c51448ec7a3f9c55d250
643,854
def _reGroupDict(d, newgr): """Regroup keys in the d dictionary in subdictionaries, based on the scheme in the newgr dictionary. E.g.: in the newgr, an entry 'LD label': ('laserdisc', 'label') tells the _reGroupDict() function to take the entry with label 'LD label' (as received from the sql databas...
eed4344c415dbb12cdceb8edb54ef2a1fbc369d2
643,855
def code_parser(text): """ Arguments: INPUT: - ``s``:sage code, may or may not start with "sage:" OUTPUT: - string -- rst text EXAMPLES (not used for unit test, see http://groups.google.com/group/sage-devel/browse_thread/thread/d82cb049ac102f3a) : from sage_sws2rst.worksh...
36035be91fc0e9e277398f70f9da25491b6e0aa0
643,856
import time def date_to_TS(date, form='%Y-%m-%d %H:%M:%S'): """ Use your local time-zone to convert date in specific format to timestamp. Parameters ---------- date : str A date to convert. form : str (default '%Y-%m-%d %H:%M:%S') Time format. Returns ------- TS :...
de1e5223cce8a55566f4e0657482f1ee08e6b30d
643,858
def sqlite_list_text(elements): """Return text to create a repr of a python list.""" return "'[' || %s || ']'" % "|| ', ' ||".join(elements)
f50766d680269d61814d679e635143f799a14294
643,859
import re def extract_url(input_string): """Extracts a URL from a blob of text. Params: - input_string: (type: string) string to parse. Returns: - result: (type: string) extracted URL. """ if input_string: url_search = re.search( r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&...
0e7b7ee68ed7e5b40777c613e109db226eee58d3
643,860
import torch def get_device(): """ Return a CUDA device, if available, or a standard CPU device otherwise """ return torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
61bc8d58b7982b84dc56f8f027769f2198babdfb
643,863
def is_gzip(filepath): """ Convert packed PFile UID to standard DICOM UID. Parameters ---------- uid : str packed PFile UID as a string Returns ------- uid : str unpacked PFile UID as string """ with open(filepath, 'rb') as fp: compressed = (fp.read(2) =...
ab227de7f5086939b18ed7f14ccacbb314e0f152
643,864
def get_unmatched_part(abbr: str, text: str): """ Returns a part of `abbr` that wasn’t directly matched against `str`. For example, if abbreviation `poas` is matched against `position`, the unmatched part will be `as` since `a` wasn’t found in string stream """ last_pos = 0 for i, ch in enum...
042273ca8ac9c50eebeed2e519b78406ff70b26b
643,865
def create_output_header(data_type, species_list, biomet_var_list=[]): """ A helper function to create the header for output data frame. Parameters ---------- data_type : str The type of output dataframe * 'flux' - flux data * 'diag' - curve fitting diagnostics species_l...
7ae280b59433a39ac2244ee9ee5306e1676818cd
643,866
import json import argparse def load_config(): """Load configuration values from configuration file and from options passed into script execution""" # Read in configuration file for default values with open("config.json", "r") as config_file: config_dict = json.load(config_file) # Read i...
c1e61e374c9ae88ddbbab68ecbc2457a4914e9f8
643,867
def split_sections(diff): """ takes a git diff and breaks it up into sections :param diff: a diff piped from git :return: a list of sections """ sections = [] section = '' for line in diff.splitlines(): line = line.strip() if line.startswith('@@'): if section...
26a79be87a1695135be267012f0ad1552a9c2680
643,868
def list_to_string(list, separator=", "): """Returns a new string created by converting each items in `list` to a new string, where each word is separated by `separator`. :param list: list of iterable items to covert to a string. :param separator: character to use as a separator between the list items....
e32e1307585ac63816833ae58333ee3b38ac9dcd
643,870
def calculate_fpl(household_size, annual_income): """Calculate income as a percentage of the Federal Poverty Level.""" fpl = 4160 * int(household_size) + 7610 return float(annual_income) / fpl * 100
6928c6c8ac6dd6fe0a94efa75ec838237213831e
643,871
def make_css(): """ Add the web page CSS - see The Woork Handbook (A. Lupetti). """ ## The CSS string to return. s = ''' /* ----------------------- */ /* STANDARD HTML TAG RESET */ /* ----------------------- */ body, h1, h2, h3, p, ul, li, form { border:0; margin:0px; padding:0px; } ...
7102eb1d9638e554bbd81ba6146e4b259cf0e25b
643,872
import re import pathlib def get_thread_siblings_list(): """ Returns a list of 2-element integer tuples representing pairs of hyperthreading cores. """ path = "/sys/devices/system/cpu/cpu*/topology/thread_siblings_list" thread_siblings_list = [] pattern = re.compile(r"(\d+)\D(\d+)") fo...
39d30a0ed4d518a481d7abd969ca0a517d5fe1a7
643,873
def assert_equal(other, obj, msg=None): """ Fail if the two objects are unequal as determined by the '==' operator. from functools import * from amara.lib.util import * f = partial(assert_equal, u'', msg="POW!") print (f(''),) # -> '' """ if not obj == other: raise Assertion...
0bd440bd60b5807fc6524e0bd12bbb823d0c6043
643,874
def generate_height_map_quad(x, z, vertex_start, uv_start, x_step_size,z_step_size, uv_step_size, height_uv_step_size): """store xyz and 4 uv coordinates per vertex""" vertices = [] vertex = vertex_start + [x * x_step_size, 0, -z * z_step_size] uv = uv_start + [x * uv_step_size, 0, x * height_uv_step_si...
b1195f6f256917e3555177e6919b55c835508ceb
643,875
def zero_module(module): """ Zero out the parameters of a module and return it. """ for p in module.parameters(): p.detach().zero_() return module
005ff5799a2ddcf5b93e9e12e1dce9372c1c5e9b
643,876
def executeJSONRPC(jsonrpccommand): """ Execute an JSONRPC command. :param str jsonrpccommand: string - jsonrpc command to execute. :returns: jsonrpc return string :rtype: str List of commands: http://kodi.wiki/?title=JSON-RPC_API example:: response = xbmc.executeJSONRPC('{ "json...
5b6ddc15b31920f1572c7e86be1ae74d4fa0a2b7
643,878
def has_unexpected_subset_keys(expected_keys, minimum_keys, actual_keys, name): """Returns an error if unexpected keys are present or expected keys are missing. Accepts optional keys. This is important to catch typos. """ actual_keys = frozenset(actual_keys) superfluous = actual_keys - expected_keys m...
8372d512c34eb4a6555ced0781fa67585f0cf676
643,879
def hasNan(self) -> bool: """Returns whether this Tensor has any nan values at all.""" return (self != self).sum() > 0
9dc8d4c5f0a327e5c8c20916eaa4ead51f859645
643,880
def factorial( *, number: int, ) -> int: """Recursive Factorial Function Args: number (int): number Returns: int: factorial of the number """ if number <= 1: return 1 return number * factorial(number=number - 1)
0ab7323ebd6bd9df7a72a3b26abeddc46e8a5a37
643,881
def seat_position(boarding_pass): """Get seat position from boarding pass code.""" row_code = boarding_pass[:7].replace('F','0').replace('B','1') col_code = boarding_pass[7:].replace('L','0').replace('R','1') row = int(row_code,2) col = int(col_code,2) return {'row': row, 'column': col, 'id': ro...
f5841d96331ff1cc41c23b221c7485cce70b6a8c
643,884
from typing import Iterable def norm1(x: Iterable[int]) -> int: """ Returns the manhattan distance (1-norm) of x """ return sum(map(abs, x))
04dea3fb08401ca6d9bf4cc759410c5e370248d7
643,885
def create_alarm_dialog(context, request, alarm_form=None, redirect_location=None, modal_size='medium', metric_unit_mapping=None): """Create alarm dialog page.""" redirect_location = redirect_location or request.route_path('cloudwatch_alarms') return dict( alarm_form=alarm_fo...
8f8756c5e2e9ea0e9f1f1d95fde0e99c40062b24
643,886
def print_cutoffs(cutoffs): """Print cutoff counts.""" lines = [] for key, val in sorted(cutoffs.items()): lines.append(f' {key}: {val}') return '\n'.join(lines)
41f21dde5c1aae6c330df339e64cf120b137c7bc
643,887
def ints_to_string(ch): """Converts int arrays to strings of lowercase letters. Args: ch (int array): The int array to be converted Returns: A string of lowercase characters. """ return ''.join([chr(c+97) for c in ch])
3e6e11597e48de464b8db997351d8570f24314bc
643,889
def _get_row(i, counts): """Returns table row data. """ return [ i.label_index, counts.get(i.label_index.strip(), 0), i.label_tp_elapsed, str(i.ts_start).split(" ")[1], "--" if not i.ts_end else str(i.ts_end).split(" ")[1], i.step_label if i.step_label el...
0f4c766c905ef3cb38842ac0ac2f33d368419a8d
643,890
def getlink(tag): """ Get the hyperlink and title from a tag. Return None tuple if there isn't a link. """ if not tag or isinstance(tag, str): return None, None if "href" not in tag.attrs: return None, None return tag["href"], tag["title"]
85af70a2b219b0c90f91f9dce2eaf9dc69cba2ee
643,891
from typing import Tuple def __parse_gav(full_artifact_path: str, root="/") -> Tuple[str, str, str]: """Parse maven groupId, artifactId and version from a standard path in a local maven repo. e.g: org/apache/maven/plugin/maven-plugin-plugin/1.0.0/maven-plugin-plugin-1.0.0.pom -> (org.apache.maven.plugin, ...
bb8a30f77a2e0fd9dff2b67cce85ede601b36a6d
643,892
def getTimestamps(data): """ Get the time stamps for each position :param data: JSON Object :return: Array of timestamps """ timestamps = data['time'] return timestamps
7ecfc32b80cfd1967b80090d02fb5db1da03ccaf
643,893
import math def update_alg_squarert(score): """Change the score by taking the square root.""" return math.sqrt(score)
aa1a91ddbff1537244275bb170c6cc97b190a8f9
643,894
def nida_y_tobaco7(studydata, column, context): """Please recode 1 as 2, 2 as 3, and 6 as 4.""" return column.replace({ 1: 2, 2: 3, 6: 4, })
0e17c4622bd4d0414a3396bcc339a68d1c5c0613
643,895
def find_all_indexes(text, pattern, first=False): """Return a list of starting indexes of all occurrences of pattern in text, or an empty list if not found. Best and worst case are O(n * m) because it goes to the end no matter what. Could consider improving by checking when theres less than m chars in ...
73e5bd464aee91f9f87ba194aa97565b8f543b98
643,896