content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_table_13(): """表 13 玄関ポーチに設置された照明設備の人感センサーによる補正係数 Args: Returns: list: 表 13 玄関ポーチに設置された照明設備の人感センサーによる補正係数 """ table_13 = (0.9, 1.0) return table_13
91a89343800ad5e3c587371c91e7d256d9ed85a1
703,429
def find_left_anchor_index(fragment_info, fragments): """ Description: Use the fragment information to find which fragment is the left anchor :param fragment_info: [list[dict]] the list of fragment information :param fragments: [list] the list of fragments being searched :return: left_anchor_index: [int] the index location in the fragment list for the left anchor fragment """ for info in fragment_info: if len(info['left_matches']) == 0: left_anchor_index = fragments.index(info['anchor']) return left_anchor_index
502473f7fee00a5ccd1ed3d6cf5c938e8c4d2041
703,430
def get_all_preconditions(action_set): """ Returns a set of all preconditions for the actions in the given set """ all_precons = set() for a in action_set: all_precons.update(a.precondition) return all_precons
1697c2d013b07bbfc24ca6273d16523eb1d83acf
703,431
def f_line(x, m, b): """ Line fit with equation y = mx + b Parameters ---------- x : array x values m : float slope b : float y-intercept Returns ------- y : array y values """ y = m*x + b return y
daf437461c2e8723a824e4083794d1f6ea6b368b
703,432
def getDistance(sensor): """ Return the distance of an obstacle for a sensor. The value returned by the getValue() method of the distance sensors corresponds to a physical value (here we have a sonar, so it is the strength of the sonar ray). This function makes a conversion to a distance value in meters. """ return ((1000 - sensor.getValue()) / 1000) * 5
d00b1d201fb59939d2b8a2e57bfa35588780b6d5
703,433
def update_individual_metadata(ts): """Update individual metadata in ts object. Returns new list of individuals with updated metadata """ individuals = [] oldname = None i = 0 for ind in ts.individuals(): popindex = ts.nodes()[ind.nodes[0]].population popname = ts.population(popindex).metadata["name"] if oldname is not None and oldname != popname: i = 0 oldname = popname name = f"tsk_{ind.id}_{popname}_{i}" md = { "id": ind.id, "tskit_id": f"tsk_{ind.id}", "name": name, "popname": popname, "ind_index": i, "population": ts.population(popindex), "description": ( f"tskit_individual:tsk_{ind.id}, name:{name}, " f"population:{ts.population(popindex)}" ), "is_reference": False, } md["vcfheader"] = ( f"##<SAMPLE=<ID={md['tskit_id']},Name={md['name']}," f"Index={md['id']},Population={md['popname']}," f"Description=\"{md['population'].metadata['description']}\">" ) newind = ind.replace(metadata=md) individuals.append(newind) i = i + 1 return individuals
4cfaf24fc4e68203e8206163fcb0686ac9fd9692
703,434
import platform def mysql_config_path(): """ 根据平台查询mysql配置文件 :return: """ _platform = platform.system() print('当前平台为:{}'.format(_platform)) mysql_config = None if _platform == 'Darwin': mysql_config = "/Users/yuxiang/Documents/Developer/WeChat/baixiaotu-mini/sqlconfig.json" elif _platform == 'Linux': mysql_config = "/root/swift/baixiaotu.json" else: print('请设置mysql配置文件路径') print(mysql_config) return mysql_config
c24632e4262ea1cfb903492b5d261a8cd5cbcd8e
703,435
import numpy def index_to_position(index, nelx, nely): """ Convert the index of a element to the centroid of the element """ return numpy.array([(index % nelx)+.5, index/nelx+.5])
1402251581df9e346097dbd561ef5f782f18da1e
703,436
import os def get_api_key(api_file): """ Return an API key from the user's home directory """ with open('{_home}/.{_api_file}'.format(_home = os.path.expanduser('~'), _api_file = api_file)) as f: return f.read().replace('\n', '')
0819cfe693478b24a827d12b448ccd1ab274271e
703,437
import requests def get_function_fb_graph(): """Get call - facebook.""" return requests.get('http://graph.facebook.com')
38f790a006a3d8de981e66936e50b7be743e4d1b
703,438
import random def get_random_number_with_zero(min_num: int, max_num: int) -> str: """ Get a random number in range min_num - max_num of len max_num (padded with 0). @param min_num: the lowest number of the range in which the number should be generated @param max_num: the highest number of the range in which the number should be generated @return: A string like "00183" """ return str(random.randint(min_num, max_num)).zfill(len(str(max_num)))
bdc9f192286262566d2b2a87e8124abdf745ecbd
703,439
def raoult_liquido(fraccion_vapor, presion_vapor, presion): """Calcula la fraccion molar de liquido mediante la ec de Raoult""" return fraccion_vapor * presion / presion_vapor
bd15f53ee74ef3dc1925ee3da7133a9c3f455333
703,442
def implemented_motifs(): """ Returns ------- List strings of all implemented motif definitions """ return ['Sheet', 'Gamma', 'Herringbone', 'Sandwich']
63564c7e1b3e7e5f8f6b93354a3e268a79e9c5de
703,443
def left(direction): """rotates the direction counter-clockwise""" return (direction + 3) % 4
f8136385e5fec11bf26a97f77e336b04ce783571
703,444
def union(list1, list2): """Union of two lists, returns the elements that appear in one list OR the other. Args: list1 (list): A list of elements. list2 (list): A list of elements. Returns: result_list (list): A list with the union elements. Examples: >>> union([1,2,3], [2,3,4]) [1, 2, 3, 4] """ return list(set(list1) | set(list2))
983e96ceb4f4eeb2b4b2d96362a0977be0cb2222
703,445
import re def list_all_links_in_page(source: str): """Return all the urls in 'src' and 'href' tags in the source. Args: source: a strings containing the source code of a webpage. Returns: A list of all the 'src' and 'href' links in the source code of the webpage. """ return re.findall( r'src\s*=\s*"([^"]+)"', source, ) + re.findall( r'href\s*=\s*"([^"]+)"', source, )
f17f2ac2724fcfdd041e2ad001557a0565b51e00
703,446
def get_direction(source, destination): """Find the direction drone needs to move to get from src to dest.""" lat_diff = abs(source[0] - destination[0]) long_diff = abs(source[1] - destination[1]) if lat_diff > long_diff: if source[0] > destination[0]: return "S" else: return "N" else: if source[1] > destination[1]: return "W" else: return "E"
224a8df79cbafbcf1eed8df522ab7f58cc93598d
703,447
import sys def verifyPicklingCompatibility(otherPythonVersion): """ Check a provided python version string versus the present instance string for pickling safety. :param otherPythonVersion: other version string :return: True is safe, False otherwise """ if otherPythonVersion is None: return False sPyVer = otherPythonVersion.split('.') if len(sPyVer) < 3: return False try: major, minor = int(sPyVer[0]), int(sPyVer[1]) # We need both major and minor agreement for pickling compatibility return major == sys.version_info[0] and minor == sys.version_info[1] except Exception: return False
1b5e2a9cb350f8a223b78cfed0a1ebaddb9d346e
703,448
def are_close(col1, col2): """This function used to compare values of collections with numeric data """ if len(col1) != len(col2): raise ValueError("Different size of input collections") result = [] for x, y in zip(col1, col2): result.append(abs(abs(x) - abs(y)) < 0.4) r = True for c in result: r = r & c return r
72896f522a5fc7cb9f4f96e873c14797009877fe
703,449
def identity(*args, **kwargs): """ An identity function used as a default task to test the timing of. """ return args, kwargs
472808f6b5260569538f26513f24ffcb1bd88c4d
703,450
def list_merger_list0(*lists): """Picks leading list, discards everything else""" return lists[0]
c571adb593de991f633a28b086e61fa7888cbc7e
703,451
def cmp(a,b): """3-way comparison like the cmp operator in perl""" if a is None: a = '' if b is None: b = '' return (a > b) - (a < b)
97c5a33e9161196119abbc323841be0b1cfdda14
703,452
import base64 import os def generate_random_string(length): """Generates a random string of the specified length. Args: length: int. Length of the string to be generated. Returns: str. Random string of specified length. """ return base64.urlsafe_b64encode(os.urandom(length))
10f22582cbe17ac0a4a41b52a8691e12036593d2
703,453
def create_logdir(method, weight, label, rd): """ Directory to save training logs, weights, biases, etc.""" return "bigan/train_logs/mnist/{}/{}/{}/{}".format(weight, method, label, rd)
4b4edcc9c0c36720e76013a6fb0faf1b49472bc0
703,454
import re def camel_case_to_title_case(camel_case_string): """ Turn Camel Case string into Title Case string in which first characters of all the words are capitalized. :param camel_case_string: Camel Case string :return: Title Case string """ if not isinstance(camel_case_string, str): return None title_case = re.sub('([^-])([A-Z][a-z-]+)', r'\1 \2', camel_case_string)\ .title() return title_case
bcc40753a8672355519741f5aec64c262431d582
703,456
def pmr_corr(vlos, r, d): """ Correction on radial proper motion due to apparent contraction/expansion of the cluster. Parameters ---------- vlos : float Line of sight velocity, in km/s. r : array_like, float Projected radius, in degrees. d : float Cluster distance from the Sun, in kpc. Returns ------- pmr : array_like, float Correction in the radial component of the proper motion, in mas/yr. """ r = r * 60 # Equation 4 from Bianchini et al. 2018. pmr = -6.1363 * 1e-5 * vlos * r / d return pmr
c9136c5ae33e89d6f57b936b92c23001fd30ccfa
703,457
def get_min_corner(sparse_voxel): """ Voxel should either be a schematic, a list of ((x, y, z), (block_id, ?)) objects or a list of coordinates. Returns the minimum corner of the bounding box around the voxel. """ if len(sparse_voxel) == 0: return [0, 0, 0] # A schematic if len(sparse_voxel[0]) == 2 and len(sparse_voxel[0][0]) == 3 and len(sparse_voxel[0][1]) == 2: x, y, z = list(zip(*list(zip(*sparse_voxel))[0])) # A list or coordinates elif len(sparse_voxel[0]) == 3: x, y, z = list(zip(*sparse_voxel)) else: raise Exception("Unknown schematic format") return min(x), min(y), min(z)
371b25b795a1a2ffeb0fc3724f01f1a329f917ae
703,458
def ExtractListsFromVertices(vertexProp, g): """ Method to extract the lists at each vertex of a vertex property, vertexProp, belonging to a graph, g, and to return a list of lists, where each sub-list is a list of values from each vertex :param vertexProp: :param g: :return: """ # Make a list to hold lists from each vertex varList = list() # Iterate thru each vertex and extract list associated with vertexProp for ii in range(g.num_vertices()): varList.append(vertexProp[g.vertex(ii)]) return varList
fd10e9285f9382511a526468e41e8a516a6f50bd
703,459
def is_palindrome_letters_only(str): """ Confirm Palindrome, even when string contains non-alphabet letters and ignore capitalization. casefold() method, which was introduced in Python 3.3, could be used instead of this older method, which converts to lower(). """ i = 0 j = hi = len(str) - 1 while i < j: # This type of logic appears in partition. # Find alpha characters and compare while not str[i].isalpha(): i += 1 if i == hi: break while not str[j].isalpha(): j -= 1 if j == 0: break if str[i].lower() != str[j].lower(): return False i += 1 j -= 1 return True
5f95add0ecf3fbe31af2b9cd0e27aac36b2c3985
703,460
from typing import Any def validate_delta(delta: Any) -> float: """Make sure that delta is in a reasonable range Args: delta (Any): Delta hyperparameter Raises: ValueError: Delta must be in [0,1]. Returns: float: delta """ if (delta > 1) | (delta < 0): raise ValueError("The delta values must be in [0,1]") return delta
1fd3084c047724a14df753e792b8500a103a34c0
703,461
import numpy as np def molpos_1Dbin(data,bins,diameter): """Creates a 1D histogram from X,Y location data of a single tracked molecule over time Args: data (pandas dataframe): time series 2D location data of a tracked molecule bins (int): # of rectangular bins to discretize cell with (bins are equidistant on x-axis) diameter (float): diameter of simulated cell Returns: TYPE: List """ pos=np.linspace(-diameter/2,diameter/2,bins+1) speciesNum = int(data.shape[1]/2) data_hist1D_total = np.zeros(bins) print(speciesNum) for i in range(speciesNum): data_hist1D = np.histogram(data.loc[:,1],bins=pos)[0] data_hist1D_total += data_hist1D return data_hist1D_total #for chunk in pd.read_csv(datapath,header=None,chunksize=10**6): #Chunk size 10^6 runtime: 72.68, chunk size 10^7 runtime: 72.29 #data_hist += np.histogram(chunk.loc[:,1],bins=pos)[0]
fbc05b9c14d82c19f62ae30ec1d05b7e314b57e8
703,463
def build_authenticate_header(realm=''): """Optional WWW-Authenticate header (401 error)""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
74c2e4e4188b608120f241aadb20d8480ac84008
703,464
def decorator_with_default_params(real_decorator, args, kwargs, default_args=None, default_kwargs=None): """ This function makes it easy to build a parametrized decorator, having a default value. Construct your decorator like this: >>> def decorator(*d_args, **d_kwargs): # d_args with d like decorator ... def function_processor(function, *args, **kwargs): ... print("additional_args", args, kwargs) ... # just do stuff here with the function, or with the args. ... return function ... return decorator_with_default_params(function_processor, d_args, d_kwargs, default_args=["I am a default argument, used if you don't provide args"]) so you can use that decorator: >>> @decorator # will fall back to the default value. ... @decorator("hey") # with parameter(s). ... @decorator(key="value") # with parameter(s). ... def foobar() ... pass ... foobar = decorator(foobar) # use default value # same as @decorator ... foobar = decorator(foobar, "hey") # with parameter(s) # same as @decorator("hey") ... foobar = decorator(foobar, key="value") # with parameter(s) # same as @decorator(key="value") :param real_decorator: The function whitch gets a function, and *args. Must return the function again. :param default_args_list: arguments which will be provided to the real_decorator, if @decorator is used without params :param args: :param kwargs: :return: """ if default_args is None: default_args = [] if default_kwargs is None: default_kwargs = {} if args is not None and len(args) > 0 and callable(args[0]): func = args[0] if len(args) == 1: # @admin or func = admin(func) if kwargs is None or len(kwargs) == 0: # no arguments/kwargs return real_decorator(func, *default_args, **default_kwargs) # func = arg[0] else: # has kwargs return real_decorator(*args, **kwargs) # args contains func. # end if else: # test = admin(test, param) return real_decorator(*args, **kwargs) # end if else: # @admin(param) if args is None or len(args) == 0: # you don't provide a function at all. if kwargs is None or len(kwargs) == 0: args = default_args kwargs = default_kwargs # end if # end if elif args[0] == Ellipsis: # so you can insert callables, after Ellipsis as first argument. args = args[1:] # end if def real_decorator_param_provider(func): return real_decorator(func, *args, **kwargs) # end def return real_decorator_param_provider
63e38bbdaea3483250db7281908a0053e072e866
703,465
import json import copy def get_args(request, required_args): """ Helper function to get arguments for an HTTP request Currently takes args from the top level keys of a json object or www-form-urlencoded for backwards compatability. Returns a tuple (error, args) where if error is non-null, the requesat is malformed. Otherwise, args contains the parameters passed. """ args = None if ( request.requestHeaders.hasHeader('Content-Type') and request.requestHeaders.getRawHeaders('Content-Type')[0].startswith('application/json') ): try: args = json.load(request.content) except ValueError: request.setResponseCode(400) return {'errcode': 'M_BAD_JSON', 'error': 'Malformed JSON'}, None # If we didn't get anything from that, try the request args # (riot-web's usage of the ed25519 sign servlet currently involves # sending the params in the query string with a json body of 'null') if args is None: args = copy.copy(request.args) # Twisted supplies everything as an array because it's valid to # supply the same params multiple times with www-form-urlencoded # params. This make it incompatible with the json object though, # so we need to convert one of them. Since this is the # backwards-compat option, we convert this one. for k, v in args.items(): if isinstance(v, list) and len(v) == 1: args[k] = v[0] missing = [] for a in required_args: if a not in args: missing.append(a) if len(missing) > 0: request.setResponseCode(400) msg = "Missing parameters: "+(",".join(missing)) return {'errcode': 'M_MISSING_PARAMS', 'error': msg}, None return None, args
b44e058590945211ca410005a5be2405b4756ca4
703,466
def find_most_sim(mesh, doc_id, top_n=10): """Find documents most similar to the given document.""" doc = mesh.doc_cache[doc_id] results = [] doc_conc = list(map(lambda x: x[1], mesh.graph.out_edges(doc_id))) for other_doc in mesh.doc_cache.values(): if other_doc._.id != doc_id: other_doc_conc = list(map(lambda x: x[1], mesh.graph.out_edges(other_doc._.id))) inter = [conc for conc in doc_conc if conc in other_doc_conc] results.append( { "id": other_doc._.id, "sim": doc.similarity(other_doc), "related": inter, "title": other_doc._.title, } ) results.sort(key=lambda x: x["sim"], reverse=True) return results[: min(len(results) - 1, top_n)]
2eef0091bebb7dd8f4aa1a186020aafb6eefca7c
703,467
def determine_header_length(trf_contents: bytes) -> int: """Returns the header length of a TRF file Determined through brute force reverse engineering only. Not based upon official documentation. Parameters ---------- trf_contents : bytes Returns ------- header_length : int The length of the TRF header, prior to the table portion of the TRF file. """ column_end = b"\t\xdc\x00\xe8\t\xdc\x00\xe9\t\xdc\x00\xea\t\xdc\x00\xeb\t\xdc\x00" header_length = trf_contents.index(column_end) + len(column_end) # test = trf_contents.split(b"\t") # row_skips = 6 # i = next(i for i, item in enumerate(test[row_skips::]) if len(item) > 3) + row_skips # header_length_old_method = len(b"\t".join(test[0:i])) + 3 # if header_length_old_method != header_length: # raise ValueError("Inconsistent header length determination") return header_length
e8aa5110691e877c34f208af5bd508f0f5ec4760
703,469
import re def _join_lines(source): """Remove Fortran line continuations""" return re.sub(r'[\t ]*&[\t ]*[\r\n]+[\t ]*&[\t ]*', ' ', source)
9caa3b6f470a96a7b473f3cce12f57d3787e91dd
703,470
def format(t): """ function to format the stopwatch time to A:BC.D Returns: the formatted six character string """ A = t/600 t = t - A * 600 # this round function isn't needed when t is an integer CD = round(t/10.0, 1) B = "" if CD < 10.0: B = "0" return str(A) + ":" + str(B) + str(CD)
ad6dc72f0d6b090cf4d94d27e1f0560c58a9f42d
703,471
import requests def get_kalliope_bijlage(path, session): """ Perform the API-call to get a poststuk-uit bijlage. :param path: url of the api endpoint that we want to fetch :param session: a Kalliope session, as returned by open_kalliope_api_session() :returns: buffer with bijlage """ r = session.get(path) if r.status_code == requests.codes.ok: return r.content else: raise requests.\ exceptions.HTTPError('Failed to get Kalliope poststuk bijlage (statuscode {})'.format(r.status_code))
b2a126b8e33bab50b1e2aa122645d7a45d6dfea9
703,472
def filter_by_book_style(bibtexs, book_style): """Returns bibtex objects of the selected book type. Args: bibtexs (list of core.models.Bibtex): queryset of Bibtex. book_style (str): book style key (e.g. JOUNRAL) Returns: list of Bibtex objectsxs """ return [bib for bib in bibtexs if bib.bib_type_key == book_style]
ca3b46772930a6f6e28b6fc0ee4d175ee8d69c3c
703,474
import torch def attributions(scores: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: """Error analysis for antecedent scoring ## Inputs - `scores`: `(batch_size, max_antecedent_number)`-shaped float tensor. The first dimension might be padded with `-float("-inf")` or approximations (such as `1e-32`) when a mention has less than ` max_antecedent_number` antecedent candidates. - `targets`: `(batch_size, max_antecedent_number)`-shaped byte tensor mask with `true` for the correct antecedents. """ targets = targets.to(torch.bool) _, highest_scores_indices = torch.max(scores, dim=-1) sys_new = highest_scores_indices.eq(0) gold_new = targets.narrow(-1, 0, 1).squeeze() true_new = gold_new.logical_and(sys_new) false_new = gold_new.logical_not().logical_and(sys_new) false_link = gold_new.logical_and(sys_new.logical_not()) argmax_mask = torch.nn.functional.one_hot( highest_scores_indices, num_classes=scores.size(-1) ).to(torch.bool) correct = targets.masked_select(argmax_mask) correct_link = correct.logical_and(true_new.logical_not()) wrong_link = correct.logical_or(false_new).logical_or(false_link).logical_not() outpt = torch.stack((true_new, false_new, correct_link, false_link, wrong_link)) outpt = outpt.sum(dim=-1) return outpt
6ce0c443d6e344bfc84565f8f901984904216194
703,476
def square_quad_f(x, a, matrix): """ Compute the square of the quadratic function. Parameters ---------- x : 1-D array Point in which the square of the quadratic is to be evaluated. minimizer : 1-D array Minimizer of the square of the quadratic function. matrix : 2-D array Positive definite matrix. Returns ------- func_val : float Square of the quadratic function at x. """ func_val = ((x - a).T @ matrix @ (x - a)) ** 2 return func_val
1ff7aafd5d4259bfccd110d4f2880071b8fad18a
703,477
import random def random_val(index, tune_params): """return a random value for a parameter""" key = list(tune_params.keys())[index] return random.choice(tune_params[key])
1cf7ba9d1a3ff651f946a8013e338d62f4fec3ab
703,478
def git_version_specifier(refspec, branch, commit, tag): """ Return the minimal set of specifiers that the user input reduces to, in a dict of variables for Ansible. :param refspec: provided refspec like 'pull/1/head' :param branch: provided branch like 'master' :param commit: provided commit SHA like '2cbd73cbd5aacc965ecfa480fa90164a85191489' :param tag: provided tag like 'v1.3.0-rc2' :return: minimal set of specifiers in a dict using Ansible keys """ if commit: return {'origin_ci_sync_version': commit} if tag: return {'origin_ci_sync_version': tag} if branch and not refspec: return {'origin_ci_sync_version': branch} if branch and refspec: return { 'origin_ci_sync_version': branch, 'origin_ci_sync_refspec': refspec + ':' + branch, }
9b723b44f3bad03a74b78a10153f4d6120202fc6
703,479
import socket def receive_bytes(socket: socket.socket, buffer_size: int) -> str: """ Receives the specified number of bytes from the specified socket @param socket - the socket from which to receive @param buffer_size - the number of bytes to receive @return - string """ receiver_buffer: bytes = b'' while len(receiver_buffer) < buffer_size: if not (t := socket.recv(buffer_size)): break receiver_buffer += t return receiver_buffer.decode('utf-8')
bb28fa45641596a02f6e325e3a62ccc51c9f9905
703,480
def convert_archive_posts(archive_posts): """Convert a list of SQL post rows to the format used for display within the post archive.""" converted_archive = []; current_year = "" current_month = "" for post in archive_posts: # If the posts created year is not the current year being parsed, push that year. if post["created_year"] != current_year: current_year = post["created_year"] converted_archive.append({"year": current_year, "months": []}) months = converted_archive[len(converted_archive) - 1]["months"] # If the posts created month is not the current month being parsed, push that month. if post["created_month"] != current_month: current_month = post["created_month"] months.append({"month": current_month, "posts": []}) posts = months[len(months) - 1]["posts"] posts.append({"title": post["title"], "link": post["link"]}) return converted_archive
1572d6105c4ed217f67021ebd7c9a3f1058a7617
703,482
def _get_search_text(keywords): """Get search text.""" search_text = ' '.join(['"{}"'.format(keyword) for keyword in keywords]) search_text = search_text.replace(':', ' ') search_text = search_text.replace('=', ' ') return search_text
cabb5d9ca5b5faf3d9287261aab0cd01df21a680
703,483
def readnext(x): """x is a list""" if len(x) == 0: return False else: return x.pop(0)
dd27ad3c8f750ef3e6df640fd710a0469b0839d0
703,484
def coding_problem_19(house_costs): """ A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost while ensuring that no two neighboring houses are of the same color. Given an N by K matrix where the nth row and kth column represents the cost to build the nth house with kth color, return the minimum cost. Example: >>> house_size = [1, 2, 4, 2] # size of the house >>> color_cost = [1, 2, 4] # cost of paint for each color >>> house_costs = [[cc * hs for cc in color_cost] for hs in house_size] # 4 houses, 3 colors >>> coding_problem_19(house_costs) # [1,2,4,2] . [1,2,1,2] == 1*1 + 2*2 + 1*4 + 2*2 == 13 13 Notes: this is dynamic programming in disguise. We assign a color to each house in order, and keep track of the minimum cost associated with each choice of color. These costs are the minimum over all possible permutation in which the last added house is of a particular color. """ best_costs = [0] * len(house_costs[0]) for color_costs in house_costs: # color_costs are those paid to paint last added house with a certain color best_costs = [color_costs[i] + min(best_costs[:i] + best_costs[i + 1:]) for i in range(len(best_costs))] return min(best_costs)
f9d8b33f449d7a2f87118be3e4d894988b781476
703,486
import requests def requests_get(url): """Make a get request using requests package. Args: url (str): url to do the request Raises: ConnectionError: If a RequestException occurred. Returns: response (str): the response from the get request """ try: r = requests.get(url) except requests.exceptions.RequestException: raise ConnectionError return r
a438d211e6b5bf78af56783b5d22c85961a2d563
703,487
def _join_dicts(*dicts): """ joins dictionaries together, while checking for key conflicts """ key_pool = set() for _d in dicts: new_keys = set(_d.keys()) a = key_pool.intersection(new_keys) if key_pool.intersection(new_keys) != set(): assert False, "ERROR: dicts to be joined have overlapping keys. Common hint: Have you specified your scheme dicts properly?" else: key_pool.update(new_keys) ret = {} for _d in dicts: ret.update(_d) return ret
2dee7a6f6a89d310d6a58e35d14c57e8ddb5b804
703,488
def cases_vs_deaths(df): """Checks that death count is no more than case count.""" return (df['deaths'] <= df['cases']).all()
994ae93fb23090de50fc4069342487d0d8e621ed
703,489
import os def list_files_in_dir(dir_path): """ List out files only from a target directory path. """ if not os.path.isdir(dir_path): raise ValueError('`dir_path` must be a directory.') return iter(f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)))
c502799d34ba5fd1a89a574cfb78d722e6ce4a8c
703,490
import re def add_pronom_link_for_puids(text): """If text is a PUID, add a link to the PRONOM website""" PUID_REGEX = r"fmt\/[0-9]+|x\-fmt\/[0-9]+" # regex to match fmt/# or x-fmt/# if re.match(PUID_REGEX, text) is not None: return '<a href="https://nationalarchives.gov.uk/PRONOM/{}" target="_blank">{}</a>'.format( text, text ) return text
5fdc9c15895dfd75be54ad0258e66625462204a2
703,491
def convert(df_column): """ Converts a DataFrame column to list """ data_list = [] for element in df_column: data_list.append(element) return data_list
6cd0f9b445573892612e01e0e3e25eb32d658be4
703,492
from typing import Mapping from typing import Any import textwrap def format_nested_dicts(value: Mapping[str, Mapping[str, Any]]) -> str: """ Format a mapping from string keys to sub-mappings. """ rows = [] if not value: rows.append("(empty)") else: for outer_key, outer_value in value.items(): if isinstance(outer_value, dict): if outer_value: rows.append(f"+ {outer_key}") inner_rows = format_nested_dicts(outer_value) rows.append(textwrap.indent(inner_rows, prefix=" ")) else: rows.append(f"+ {outer_key}: (empty)") else: if outer_value is None: rows.append(f"- {outer_key}: (null)") else: rows.append(f"- {outer_key}: {outer_value}") return "\n".join(rows)
79d029a062f0e2545265ecdf5d8cdacb271c40c2
703,493
import random def shuffle_string(s): """ Shuffle a string. """ if s is None: return None else: return ''.join(random.sample(s, len(s)))
25d109f11737b60cecf391fd955f2df4366de7e6
703,494
def get_rule_full_description(tool_name, rule_id, test_name, issue_dict): """ Constructs a full description for the rule :param tool_name: :param rule_id: :param test_name: :param issue_dict: :return: """ issue_text = issue_dict.get("issue_text", "") # Extract just the first line alone if issue_text: issue_text = issue_text.split("\n")[0] if not issue_text.endswith("."): issue_text = issue_text + "." return issue_text
546dcb5ce2cbc22db652b3df2bf95f07118611cf
703,495
import itertools def check_length(seed, random, query_words, key_max): """ Google limits searches to 32 words, so we need to make sure we won't be generating anything longer Need to consider - number of words in seed - number of words in random phrase - number of words in the lists from the query Will raise exception if there are too many words Args: seed: the seed for segment 1 random: the random query string for segment 0 query_words: object with key=name of dimension, value=list of keywords to use in query key_max: the maximum number of words (32 in Google's case) Returns: bool: True for correct number of words, False for too many """ all_query_words = " ".join(list(itertools.chain.from_iterable(query_words))).split(' ') total_words = len(seed.split(" ")) + len(random.split(" ")) + len(all_query_words) if total_words <= key_max: return True else: message = "The maximum number of keywords is:", key_max, "\nYou have:", total_words raise Exception(message)
14871b468454f324223673a0c57941ea9e63341a
703,496
def is_string(val): """ Is the supplied value a string or unicode string? See: https://stackoverflow.com/a/33699705/324122 """ return isinstance(val, (str, u"".__class__))
99b082ec080f261a7485a4e8e608b7350997cf18
703,497
from datetime import datetime def time_string(): """ Generate a string of numbers generated from now time (UTC). """ # UTC time up to microseconds time_str = datetime.utcnow().strftime("%Y%m%d%H%M%S") return time_str
c7258004db459563a1d229119b6148584cc72584
703,498
def colorvsn1(studydata, column, context): """Please convert numeric codes of 0 and 99 to the text strings they represent.""" return column.mask(column == 0, 'No').mask(column > 90, "Don't Know")
3f05a3a78d1368e6116fa52366079c22dd183bc3
703,499
def score(hand): """ Compute the maximal score for a Yahtzee hand according to the upper section of the Yahtzee score card. hand: full yahtzee hand Returns an integer score """ max_score = 0 sorted_hand_list = sorted(list(set(hand))) for i_mem in sorted_hand_list: temp_score = 0 for j_mem in list(hand): if i_mem == j_mem: temp_score += i_mem if temp_score > max_score: max_score = temp_score return max_score
b1fae3c67793a96b040f8abae41514bef2c5b89c
703,500
def context_get(stack, name): """ Find and return a name from a ContextStack instance. """ return stack.get(name)
a5a9a50c54e8f0f685e0cf21991e5c71aee0c3d6
703,501
import os def test_vars(env_vars): """Method to identify the active and inactive environment variables for a specific conda environment test_vars ========= This method is used to get the active and inactive environment variables for a specific conda environment created by ggd. Parameters: ----------- 1) env_vars: (list) The list of environment variables to check for activity Return: +++++++ 1) (list) A list of the active environment variables 2) (list) A list of the inactive environment variables """ active_vars = [] inactive_vars = [] for env_var in env_vars: if env_var in os.environ and os.environ[env_var] == env_vars[env_var]: active_vars.append(env_var) else: inactive_vars.append(env_var) return active_vars, inactive_vars
f24f2b18c028984ab1dd4e11832a39fcba48d946
703,502
def tree_names (tree): """Get the top-level names in a tree (including files and directories).""" return [x[0] for x in list(tree.keys()) + tree[None] if x is not None]
12a5522974671f3ab81f3a1ee8e8c4db77785bd3
703,504
def fixed_width_repr_of_int(value, width, pad_left=True): """ Format the given integer and ensure the result string is of the given width. The string will be padded space on the left if the number is small or replaced as a string of asterisks if the number is too big. :param int value: An integer number to format :param int width: The result string must have the exact width :return: A string representation of the given integer. """ ret = '{:{pad_dir}{width}d}'.format(value, pad_dir='>' if pad_left else '>', width=width) return '*' * width if len(ret) > width else ret
adb212746dd081112ec1de2c4ea8745d2601c055
703,505
def _getCompiledName(fldName, clsName): """Return mangled fldName if necessary, else no change.""" # If fldName starts with 2 underscores and does *not* end with 2 underscores... if fldName[:2] == '__' and fldName[-2:] != '__': return "_%s%s" % (clsName, fldName) else: return fldName
91285b7c54e001d807850c66ac74521e55d05ca4
703,506
def ConvertListToCSVString(csv_list): """Helper to convert a list to a csv string.""" return ','.join(str(s) for s in csv_list)
547311ceac094211d47d0cc667d54b2a3e697f4e
703,508
def min_distance_bottom_up(word1: str, word2: str) -> int: """ >>> min_distance_bottom_up("intention", "execution") 5 >>> min_distance_bottom_up("intention", "") 9 >>> min_distance_bottom_up("", "") 0 """ m = len(word1) n = len(word2) dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0: # first string is empty dp[i][j] = j elif j == 0: # second string is empty dp[i][j] = i elif ( word1[i - 1] == word2[j - 1] ): # last character of both substing is equal dp[i][j] = dp[i - 1][j - 1] else: insert = dp[i][j - 1] delete = dp[i - 1][j] replace = dp[i - 1][j - 1] dp[i][j] = 1 + min(insert, delete, replace) return dp[m][n]
8cd87ffe877aa24d5b1fa36ce1d3b96efb7b4e1e
703,510
def periodize_filter_fourier(h_f, nperiods=1, aggregation='sum'): """ Computes a periodization of a filter provided in the Fourier domain. Parameters ---------- h_f : array_like complex numpy array of shape (N*n_periods,) n_periods: int, optional Number of periods which should be used to periodize aggregation: str['sum', 'mean'], optional 'sum' will multiply subsampled time-domain signal by subsampling factor to conserve energy during scattering (rather not double-account for it since we already subsample after convolving). 'mean' will only subsample the input. Returns ------- v_f : array_like complex numpy array of size (N,), which is a periodization of h_f as described in the formula: v_f[k] = sum_{i=0}^{n_periods - 1} h_f[i * N + k] References ---------- This is a modification of https://github.com/kymatio/kymatio/blob/master/kymatio/scattering1d/ filter_bank.py Kymatio, (C) 2018-present. The Kymatio developers. """ N = h_f.shape[0] // nperiods h_f_re = h_f.reshape(nperiods, N) v_f = (h_f_re.sum(axis=0) if aggregation == 'sum' else h_f_re.mean(axis=0)) v_f = v_f if h_f.ndim == 1 else v_f[:, None] # preserve dim return v_f
f9a2845dcf40eedce9d46faba506f1c1358ce6a5
703,511
def quick_sort(data): """To sort data as an increase order by divide and conquer method.""" def q_sort(left_index, right_index): """Do quicksort recursively.""" if right_index <= left_index: return # Sort sub partition. part = partition(left_index, right_index) # Handle left-side. q_sort(left_index, part - 1) # Handle right-side. q_sort(part + 1, right_index) def partition(low_index, high_index): """Do partition by quicksort method.""" # Set pivot. pivot, pivot_index = data[high_index], high_index high_index -= 1 while low_index <= high_index: while data[low_index] < pivot: low_index += 1 while data[high_index] > pivot: high_index -= 1 if low_index < high_index: data[low_index], data[high_index] = data[high_index], data[low_index] low_index, high_index = low_index + 1, high_index - 1 data[low_index], data[pivot_index] = data[pivot_index], data[low_index] return low_index # Call quick sort main function. return q_sort(0, len(data) - 1)
e8c530b6da3f705b08279eb213d03bd54820f4a4
703,512
def slope_id(csv_name): """ Extract an integer slope parameter from the filename. :param csv_name: The name of a csv file of the form NWS-<SLP>-0.5.csv :return: int(<SLP>) """ return int(csv_name.split("-")[1])
1ae34f1e5cc91fdc3aaff9a78e1ba26962475625
703,513
def minbox(points): """Returns the minimal bounding box necessary to contain points Args: points (tuple, list, set): ((0,0), (40, 55), (66, 22)) Returns: dict: {ulx, uly, lrx, lry} Example: >>> minbox((0, 0), (40, 55), (66,22)) {'ulx': 0, 'uly': 55, 'lrx': 66, 'lry': 0} """ x, y = [point[0] for point in points], [point[1] for point in points] return {'ulx': min(x), 'lrx': max(x), 'lry': min(y), 'uly': max(y)}
d8b11d40b52886f290d28f3434b17d2b9641c4fb
703,514
import csv def write_csv(history, filename): """ Write Letterboxd format CSV """ if history: with open(filename, 'w', encoding='utf8') as fil: writer = csv.DictWriter(fil, list(history[0].keys())) writer.writeheader() writer.writerows(history) return True return False
66ab2c9734c5d50b59d1aaff2dd62a4fffcfe0ec
703,515
def apply_regression(df, w): """ Apply regression for different classifiers. @param df pandas dataframe; @param w dict[classifier: list of weights]; @return df with appended result. """ # get input if 'state' in df.columns: x = df.drop('state', axis=1).to_numpy(dtype='float64') else: x = df.to_numpy(dtype='float64') # initialize result new = df.copy() for classifier, wi in w.items(): # evaluate output y = x@wi # append output new[f'lms_{classifier}'] = y return new
1fb5fd9f4b297cd024e405dc5d9209213d28ff0d
703,516
import sys def parse_acc_table(infile): """Parsing tab-delim accession table (genome_name<tab>accession) """ if infile == '-': inF = sys.stdin else: inF = open(infile) tbl = [] for line in inF: line = line.rstrip().split('\t') tbl.append(line) return tbl
568aaeb0d6dd4158b1f6e6c59c709c9996948a69
703,517
def get_lambda_cloud_watch_func_name(stackname, asg_name, instanceId): """ Generate the name of the cloud watch metrics as a function of the ASG name and the instance id. :param stackname: :param asg_name: :param instanceId: :return: str """ name = asg_name + '-cwm-' + str(instanceId) return name[-63:len(name)]
893abaf60684cbf9d72774d6f5bb2c4351744290
703,518
def secondary_training_status_changed(current_job_description, prev_job_description): """Returns true if training job's secondary status message has changed. Args: current_job_description: Current job description, returned from DescribeTrainingJob call. prev_job_description: Previous job description, returned from DescribeTrainingJob call. Returns: boolean: Whether the secondary status message of a training job changed or not. """ current_secondary_status_transitions = current_job_description.get("SecondaryStatusTransitions") if ( current_secondary_status_transitions is None or len(current_secondary_status_transitions) == 0 ): return False prev_job_secondary_status_transitions = ( prev_job_description.get("SecondaryStatusTransitions") if prev_job_description is not None else None ) last_message = ( prev_job_secondary_status_transitions[-1]["StatusMessage"] if prev_job_secondary_status_transitions is not None and len(prev_job_secondary_status_transitions) > 0 else "" ) message = current_job_description["SecondaryStatusTransitions"][-1]["StatusMessage"] return message != last_message
b1d1a83cccb8cf84fa678345bcf7b3f6531aa2c5
703,519
def string_concat(str1, str2): """Concatenates two strings.""" return str1 + str2
5b6d842fca2d3623d33341d9bba4e4a76ec29e15
703,520
def remove_spaces(input_text, main_rnd_generator=None, settings=None): """Removes spaces. main_rnd_generator argument is listed only for compatibility purposes. >>> remove_spaces("I love carrots") 'Ilovecarrots' """ return input_text.replace(" ", "")
a9ba3bcca4a4ff1610d52271562e053f25815618
703,521
from typing import List from typing import Counter import heapq def top_k_frequent_pq(nums: List[int], k: int) -> List[int]: """Given a list of numbers, return the the top k most frequent numbers. Solved using priority queue approach. Example: nums: [1, 1, 1, 2, 2, 3], k=2 output: [1, 2] 1. Get the counts of each items, and turn them into tuples. 2. Put the counts on a heap, popping the min off if the heap is > k 3. Now we have a heap of size k with the largest elements (Note: We ensure k < n by checking at the start to get the times below.) Time: O(n log k): Where n is len(nums) Space: O(n+k): Where n is len(nums) n for the counts, and k for the heap """ if k == len(nums): return nums # Build a hashmap of frequencies O(n) counts = Counter(nums) # Build the heap of size k O(n log k) heap = [] for num, frequency in counts.items(): # O(n) heapq.heappush(heap, (frequency, num)) # O(k) if len(heap) > k: heapq.heappop(heap) # Get the elements in the heap O(k) return [element[1] for element in heap]
4d30bd7e11a087be1a23f9db5c8af7f78c083a5f
703,522
def monthFormat(month: int) -> str: """Formats a (zero-based) month number as a full month name, according to the current locale. For example: monthFormat(0) -> "January".""" months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ] return months[month % 12]
cb675f547d9beec0751d8252e99b5c025b8fd291
703,524
def build_fnln_contact(individual_contact): """ Expected parameter format for individual_contact ('My Name', '[email protected]') Sample output: {'email': '[email protected]', 'name': 'My Name'} """ return { "email": individual_contact[-1], "name": individual_contact[0] }
54080191320cfeb425de0f765f10e29726405d0d
703,525
import numpy as np def shortcut( sn ) : """ For a given snana.SuperNova object sn, quickly convert the posterior probabilities computed using the 'mid' class fractions prior into the posterior probabilities you get when adopting the 'galsnid' prior. NOTE: we do not account for redshift dependence here, so this only works exactly if we have a known spec-z !!! NOT FUNCTIONAL !!! """ return(0) k = sn.bayesNormFactor priorIa = np.mean( sn.ClassSim.Ia.priorModel ) priorIbc = np.mean( sn.ClassSim.Ibc.priorModel ) priorII = np.mean( sn.ClassSim.II.priorModel ) priorIaNew, priorIbcNew, priorIINew = pClassMorph( sn.HOST_TYPE, priorIa=priorIa, priorIbc=priorIbc, priorII=priorII ) kNew = ( (priorIaNew/priorIa) * sn.PIa + (priorIbcNew/priorIbc) * sn.PIbc + (priorIINew/priorII) * sn.PII ) PIaNew = priorIaNew * sn.likeIa.sum() / kNew PIbcNew = priorIbcNew * sn.likeIbc.sum() / kNew PIINew = priorIINew * sn.likeII.sum() / kNew return( PIaNew, PIbcNew , PIINew )
adca461ca14c941e8f6a69193f796b78f5dc25dd
703,526
def extract_img(size, in_tensor): """ Args: size (int): size of crop in_tensor (tensor): tensor to be cropped """ dim1, dim2 = in_tensor.size()[2:] in_tensor = in_tensor[:, :, int((dim1-size)/2):int((dim1+size)/2), int((dim2-size)/2):int((dim2+size)/2)] return in_tensor
5c167c88aa7c65ca06f46d2795dbcd2af38db71e
703,527
import math import copy def plan_cartesian_path_lin(move_arm, wpose, length, alpha, z_start, cs): """ :type move_arm: class 'moveit_commander.move_group.MoveGroupCommander' :type length: float :type alpha: float """ move_arm.set_start_state(cs) waypoints = [] wpose.position.x += length*math.cos(alpha) wpose.position.y += length*math.sin(alpha) waypoints.append(copy.deepcopy(wpose)) (plan, fraction) = move_arm.compute_cartesian_path( waypoints, # waypoints to follow 0.01, # end effector follow step (meters) 0.0) # jump threshold return plan, fraction
e064ff6239fd7bb6b29d4c210ef94956219b5165
703,528
from numpy import asarray, mean def r_precision(r): """Score is precision after all relevant documents have been retrieved Relevance is binary (nonzero is relevant). >>> r = [0, 0, 1] >>> r_precision(r) 0.33333333333333331 >>> r = [0, 1, 0] >>> r_precision(r) 0.5 >>> r = [1, 0, 0] >>> r_precision(r) 1.0 Args: r: Relevance scores (list or numpy) in rank order (first element is the first item) Returns: R Precision """ r = asarray(r) != 0 z = r.nonzero()[0] if not z.size: return 0. return mean(r[:z[-1] + 1])
37467e1e02284e16a82a3dad6e0e5c14a0afcad3
703,530
import functools def accepts(*types): """ Checks argument types. """ def decorator(f): assert len(types) == f.__code__.co_argcount @functools.wraps(f) def wrapper(*args, **kwds): for (a, t) in zip(args, types): assert isinstance(a, t), "The input argument %r must be of type <%s>" % (a,t) return f(*args, **kwds) wrapper.__name__ = f.__name__ return wrapper return decorator
26dd256b466659400898972eea0a19391433be87
703,531
def pass_down(L,L1,map): """map maps L into L1.Populate L1 with values in L""" ## print len(L),len(L1),len(map),max(map) ## print sumsize(L) ## print sumsize(L1) for j in range(len(map)): if L[j] == -1: continue assert L1[map[j]] == -1 or L1[map[j]] == L[j], 'L1=%d, L = %d'%(L1[map[j]],L[j]) L1[map[j]] = max(L[j],L1[map[j]]) return L1
6896de91a37a29d1f0e360f410d83065b7434fc7
703,532
def parse_correctness_stats(filename): """ Parse the results returned from get_Correctness.sh """ results = [] stats_file = open(filename, 'r') line = stats_file.readline() while not line.startswith('Reference:'): line = stats_file.readline() # Add Reference bases. results.append(line.strip().split()[1]) # Add the genome bases. line = stats_file.readline() results.append(line.strip().split()[1]) line = stats_file.readline() while not line.startswith('N50:'): line = stats_file.readline() # Add N50. results.append(line.split()[1]) line = stats_file.readline() while not line.startswith('Missing Reference'): line = stats_file.readline() # Missing reference bases. results.append(line.strip().split(' ')[3].split('(')[0]) line = stats_file.readline() while not line.startswith('Avg Idy:'): line = stats_file.readline() # Add Avg Idy. results.append(line.strip().split(' ')[2]) # Add SNPs. line = stats_file.readline() results.append(line.strip().split(' ')[1]) # Add Indels > 5bp. line = stats_file.readline() line = stats_file.readline() results.append(line.strip().split(' ')[3]) # Add Inversions. line = stats_file.readline() results.append(line.strip().split(' ')[1]) # Add Relocations. line = stats_file.readline() results.append(line.strip().split(' ')[1]) # Add translocations. line = stats_file.readline() results.append(line.strip().split(' ')[1]) line = stats_file.readline() while not line.startswith('N50:'): line = stats_file.readline() # Add Corrected N50. results.append(line.strip().split()[1]) stats_file.close() return results
8ac0ff9307169726597bd6bce632560faaed6b3b
703,533
import os def _simple_execution(cmd): """ Shell simple execution Return only exit status (0 : Good) """ return os.system(cmd)
5024f01e82f5da218cc4c6ec4a3c2086b588939c
703,534
def whereSubseq(conditionFunc, seq, length, overlap=False): """ >>> a = [1, 3, 2, 3, 2] >>> b = [1, 2] >>> whereSubseq(lambda seq: seq == b, a, 2) [] >>> c = [3, 2] >>> whereSubseq(lambda seq: seq == c, a, 2) [1, 3] >>> whereSubseq(lambda seq: sum(seq) < 8, a, 3) [0] >>> whereSubseq(lambda seq: sum(seq) < 8, a, 3, overlap=True) [0, 2] """ if (conditionFunc is None) or (seq is None): return [] if (length < 1) or (len(seq) < length): return [] end = len(seq) - length + 1 allIdxs = [] if overlap: for i in range(end): subSeq = seq[i:(i + length)] if conditionFunc(subSeq): allIdxs.append(i) else: i = 0 while i < end: subSeq = seq[i:(i + length)] if conditionFunc(subSeq): allIdxs.append(i) i += length # skip possible overlaps else: i += 1 return allIdxs
f25ded43f91b4ecc05fa28e81095996f4d036418
703,535
import math def bearing(lat1: float, lon1: float, lat2: float, lon2: float) -> float: """Calculate bearing from lat1/lon2 to lat2/lon2 Arguments: lat1 {float} -- Start latitude lon1 {float} -- Start longitude lat2 {float} -- End latitude lon2 {float} -- End longitude Returns: float -- bearing in degrees """ rlat1 = math.radians(lat1) rlat2 = math.radians(lat2) rlon1 = math.radians(lon1) rlon2 = math.radians(lon2) dlon = math.radians(lon2-lon1) b = math.atan2(math.sin(dlon)*math.cos(rlat2),math.cos(rlat1)*math.sin(rlat2)-math.sin(rlat1)*math.cos(rlat2)*math.cos(dlon)) # bearing calc bd = math.degrees(b) br,bn = divmod(bd+360,360) # the bearing remainder and final bearing return bn
9148bc2726247cedf8a7de7279dac47316f2864f
703,536
def get_title(reg_doc): """ Extract the title of the regulation. """ parent = reg_doc.xpath('//PART/HD')[0] title = parent.text return title
744759addf0cea3ba6cc3dadad05d535b66b20d6
703,537
import random import requests def get_rising_submissions(subreddit): """Connects to the Reddit API and queries the top rising submission from the specified subreddit. Parameters ---------- subreddit : str The name of the subreddit without forward slashes. Returns ------- tuple A tuple containing a formatted message and an image url. """ endpoint = random.choice(['top','rising']) url = f"https://www.reddit.com/r/{subreddit}/{endpoint}.json?limit=1" headers = {"User-Agent": "Reddit Rising Checker v1.0"} with requests.get(url, headers=headers) as response: data = response.json()["data"]["children"] # Iterate over all the children. for item in data: item_data = item["data"] # We will collect only the fields we are interested in. title = item_data["title"] permalink = "https://reddit.com" + item_data["permalink"] author = item_data["author"] score = item_data["score"] image_url = item_data["url"] # Compose a Markdown message using string formatting. message = f"[{title}]({permalink})\nby **{author}**\n**{score:,}** points" return (message, image_url)
115edc8986acdefbb232218d237bcba7320db9a0
703,538
def E_float2(y, _): """Numerically stable implementation of Muller's recurrence.""" return 8 - 15/y
4e8801465994afcb554e048897ec1ff903385bbe
703,539
def compute_packet_csum(pkt): """Computes the checksum for the given GDB packet""" csum = 0 for x in pkt: csum += x csum = csum & 0xFF return csum
29eef2afd1b33ab80013ce7fcd46c3b11c9f639b
703,540
def new_headers() -> list: """Return list of new headers with clean names.""" return [ "date", "Rohs FB1", "Rohs FB2", "Rohs gesamt", "TS Rohschlamm", "Rohs TS Fracht", "Rohs oTS Fracht", "Faulschlamm Menge FB1", "Faulschlamm Menge FB2", "Faulschlamm Menge", "Temperatur FB1", "Temperatur FB2", "Faulschlamm pH Wert FB1", "Faulschlamm pH Wert FB2", "Faulbehaelter Faulzeit", "TS Faulschlamm", "Faulschlamm TS Fracht", "Faulbehaelter Feststoffbelastung", "GV Faulschlamm", "Faulschlamm oTS Fracht", "Kofermentation Bioabfaelle", # To be predicted. "Faulgas Menge FB1", "Faulgas Menge FB2", ]
c81c38e8521f159f0bbf29b3a32adeaa13d4c38f
703,541
import hashlib import io def calc_file_md5(filepath, chunk_size=None): """ Calculate a file's md5 checksum. Use the specified chunk_size for IO or the default 256KB :param filepath: :param chunk_size: :return: """ if chunk_size is None: chunk_size = 256 * 1024 md5sum = hashlib.md5() with io.open(filepath, 'r+b') as f: datachunk = f.read(chunk_size) while datachunk is not None and len(datachunk) > 0: md5sum.update(datachunk) datachunk = f.read(chunk_size) return md5sum.hexdigest()
8f391ade85a5b69ca63d8adb3eff6ff6af7a08e3
703,542