content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def safe_hasattr(item: object, member: str) -> bool:
"""Safe version of ``hasattr()``."""
try:
# some sketchy implementation (like paste.registry) of
# __getattr__ cause hasattr() to throw an error.
return hasattr(item, member)
except Exception:
return False | 3aa60eb3cb454ca737414f0ecf2099afe43a82ae | 674,660 |
def mirror_distance_vector(scd_scaled_dists):
"""
Function to take a binned list of scaled scd distances on [0,1] and
mirror the right half to result in a binned list on [0,0.5], which is ~twice
as deep per bin and has half as many bins.
Params:
------
scd_scaled_dists: list of sca... | 605980fd42d3429d901aac41f2520bee801e71a6 | 674,661 |
import fnmatch
def _get_pprint_include_names(table):
"""Get the set of names to show in pprint from the table pprint_include_names
and pprint_exclude_names attributes.
These may be fnmatch unix-style globs.
"""
def get_matches(name_globs, default):
match_names = set()
if name_glob... | a642ec20192f4dfedda293105dc83978b5ba20d2 | 674,662 |
def _recall(conf_mat):
"""
Compute the recall score, i.e. the ratio of true positives to true positives and false negatives.
Answers the question: "Which share of the pixels that are actually slum was identified by the model as such?"
:param conf_mat: Confusion matrix produced by conf_mat().
:retu... | d28d9b63106fb5bba83fbc45f009258716eb9cab | 674,663 |
def recursive_lookup(dict_object, keys):
"""
Given a dict object and list of keys, nest into those keys.
Raises KeyError if the path isn't found.
>>> recursive_lookup({'foo': 1}, ['foo'])
1
>>> recursive_lookup({'foo': {'bar': 1}}, ['foo'])
{'bar': 1}
>>> recursive_lookup({'foo': {'bar':... | 485a398649640fce5cfe370e8a28f13f5540ca18 | 674,664 |
import os
def get_file_size(path):
"""Returns the file in MB
param path: absolute pathname of the file
"""
return os.stat(path).st_size / (1000.0 * 1000.0) | 9a1f28b9288a546782d9688fa0a2d3981ec67b28 | 674,665 |
import re
def educateDashesOldSchoolInverted(str):
"""
Parameter: String.
Returns: The string, with each instance of "--" translated to
an em-dash HTML entity, and each "---" translated to
an en-dash HTML entity. Two reasons why: First, unlike the
en- and em-dash syntax... | 58e80b5f2aa181acc75f9ce0a254416782cf93e9 | 674,666 |
from typing import Dict
from typing import Any
from typing import Literal
from typing import Optional
from typing import Union
from typing import List
def _check_for_override(
systematic: Dict[str, Any], template: Literal["Up", "Down"], option: str
) -> Optional[Union[str, List[str]]]:
"""Returns an override ... | 85cfbde0e2de2083b1ee378994ee388365750d6e | 674,667 |
def encrpyt(answer):
"""
This program encrpyt the answer to dash
:param answer: str, the final answer
:return encrpyted: str, the dashed answer
"""
encrpyted = ''
for ch in answer:
encrpyted += '-'
return encrpyted | 5457d6e38151eb92fa3e54d078bfc0e9cc327c98 | 674,668 |
def _convert_3dlut_from_cube_to_3dl(lut, grid_num):
"""
cube形式(R -> G -> B 順で増加) のデータを
3dl形式(B -> G -> R) に変換
Parameters
----------
lut : array_like
3DLUT data with cube format.
grid_num : int
grid number of the 3dlut.
Returns
-------
array_like
3DLUT da... | c5ff50db865ea1bf6ce4770f912b14280876cab4 | 674,670 |
import os
from pathlib import Path
def resolve_relative_path(absolute_path, relative_path):
"""Given a path and a path that is relative to it, return the full path.
Args:
absolute_path (str): An absolute path.
relative_path (str): A path relative to the absolute path.
Returns:
Th... | 10a038df61cdfaf391a7cea2092ab4cf013e44e2 | 674,671 |
def get_table_id(current_page, objects_per_page, loop_counter):
"""
Calculate correct id for table in project page. This function is used only for pagination purposes.
"""
return ((current_page - 1) * objects_per_page) + loop_counter | 36d12d316940b5982abb4bc89369c3df5e8a42b6 | 674,672 |
def _recur_serialize_metaset(value):
"""Transform a MetaSet to a JSON serializable value"""
try:
return {k: _recur_serialize_metaset(v) for k, v in value.items()}
except AttributeError:
return list(value) | b9408e04b7968aff372ec70ef1bf66184b659987 | 674,673 |
import os
import re
def _strip_win32_incompat(string, BAD='\:*?;"<>|'):
"""Strip Win32-incompatible characters from a Windows or Unix path."""
if os.name == "nt":
BAD += "/"
if not string:
return string
new = "".join(map(lambda s: (s in BAD and "_") or s, string))
parts = new.sp... | cc69b56ddc4d4147b950055547c0b242484b9f1f | 674,674 |
def timekey_to_timepoint(timekey):
"""
Return the timepoint it corresponds to. Assumes are of form "xxxxt00_rep..."
"""
timestring = timekey.split("_")[0].split("t")[-1]
if timestring == "05":
return 0.5
else:
return eval(timestring) | 659c1ecfaa6df6661db76387b1eb0f86cf1b9378 | 674,675 |
def get_kp_labels(bands_node, kpoints_node=None):
"""
Get Kpoint labels with their x-positions in matplotlib compatible format.
A KpointsData node can optionally be given to fall back to if no labels
are found on the BandsData node. The caller is responsible for ensuring
the nodes match. This shou... | decd7c5f0a027fa975b7bdab692548f3c0c7d05a | 674,676 |
def IndexOfMin(inputList):
"""
Return the index of the min value in the supplied list
"""
assert(len(inputList) > 0)
index = 0
minVal = inputList[0]
for i, val in enumerate(inputList[1:]):
if val < minVal:
minVal = val
index = i + 1
return index | 0f2ca9bdf78755aaf71eddc3ca2a5683af095dc5 | 674,677 |
def filter_profile(data, profile):
"""
Take a dataframe after it has been processed by merge_data, and a profile
and returns a filtered dataframe of players with that profile. Valid profiles
are 'long_inaccurate', 'long_accurate', 'short_inaccurate', 'short_inaccurate'.
"""
player_aggregates = d... | e60ff7d862f2635538094299977ac08655073bf8 | 674,678 |
def is_valid_as_number(as_number):
"""check as-number is valid"""
if as_number.isdigit():
if int(as_number) > 4294967295 or int(as_number) < 1:
return False
return True
else:
if as_number.find('.') != -1:
number_list = as_number.split('.')
if len(... | 4d902a9911b450680e32cc5e73fce0f86bd2ca0d | 674,679 |
def find_matches_scripts(name, scripts):
"""
This function ...
:param name:
:param scripts:
:return:
"""
# Get a list of the script names that match the first command line argument, if there is one
if "/" in name:
matches = []
dir_name = name.split("/")[0]
scri... | 5655a2107d913b0c16471705a5eb304dabdb3307 | 674,680 |
def mat_like_array(start, end, step=1):
"""
Generate a matlab-like array start:end
Subtract 1 from start to account for 0-indexing
"""
return list(range(start-1, end, step)) | ce69ee207a543ade6c52e119682e4e5387266d71 | 674,681 |
def rotate(pos, vel, matrix):
"""
Rotate.
Applies the rotation `matrix` to a set of particles positions `pos` and
velocities `vel`
Parameters
----------
pos : `np.ndarray`, shape = (N_part, 3)
Positions of particles
vel : `np.ndarray`, shape = (N_part, 3)
Velocities of ... | d701380c86d0217be8d6ea297cf1678ca0d2d4d5 | 674,683 |
def GetParamfileName(pfPattern, tmplBase, dn=0, scn=0, tn=0, cpdn=0):
"""
パラメータファイル名の展開
[in] pfPattern パラメータファイル名パターン
[in] tmplBase テンプレートファイルベース名
[in] dn ワークディレクトリ通番
[in] scn サブケース通番
[in] tn テンプレートファイル番号
[in] cpdn 単一ディレクトリ内サブケース番号
戻り値 -> 真偽値
"""
paramfile = pfPattern
... | 108b747c0c79613f7856787f78642bf85efa6faa | 674,684 |
from typing import Tuple
from typing import List
import os
def get_list_of_uuids(
lab_name: str,
results_directory: str,
shared_dir_name: str = 'shared') -> Tuple[List, str]:
"""
For a given lab_name, which corresponds with a directory (containing multiple results files), it
return... | 99ebbbb64e6da07c00a9ea5f3dabab5ec3f8df4f | 674,685 |
def generate_public(private, generator, modulus):
"""Calculates the public Diffie-Hellman key given g, p, and the private key"""
return pow(generator, private, modulus) | 9b6a4ec6cb858c248719a96f45a45638759100a1 | 674,686 |
import base64
def custom_jinja2_filter(string):
"""encodes a string using base64 schema"""
return base64.b64encode(string.encode("UTF-8")).decode("UTF-8") | 50e25472b44ea62cd7f8d1996454441889120e2b | 674,687 |
def line_search(
func,
x_0,
d_x,
expected_improvement,
y_0=None,
accept_ratio=0.1,
backtrack_ratio=0.8,
max_backtracks=15,
atol=1e-7,
):
"""Perform a linesearch on func with start x_0 and direction d_x."""
# pylint:disable=too-many-arguments
if y_0 is None:
y_0 = ... | 51e0fa822a7b397aff8c0e3b693322e5ee463995 | 674,688 |
def union(self_k_v, others_k_v, func, self_is_source):
"""
Parameters
----------
self_k_v: [(k,v)]
others_k_v: [(k,v)]
func: deal with the self and other's value
self_is_source: boolean
Returns
-------
"""
self_keys = self_k_v.keys()
for k, v in others_k_v.items():
... | e6d6010ec4eca96321241fb8f38967b58bbd699d | 674,689 |
def assume_role_response_to_session_kwargs(assume_role_resp):
"""Convert assume role response to kwargs for boto3.Session
Also useful for creating AWS credentials file.
"""
return dict(aws_access_key_id=assume_role_resp['Credentials']['AccessKeyId'],
aws_secret_access_key=assume_role_r... | 08bcf3ba302229330708a3d827770ab5b206afdc | 674,690 |
def join_ints(*ints):
"""Given a list of ints, return a underscore separated strings with them.
>>> join_ints(1, 2, 3)
'1_2_3'
"""
return '_'.join(map(str, ints)) | e0fe79ac05e5473df319b76ddb22ffec3b06442c | 674,691 |
def affects_transaction(func):
"""
mark a method as write (affecting state of transaction) for transaction log
"""
setattr(func, 'affects_transaction', True)
return func | bd88ae970ce2d23714e061ac1e9b209e2e05b992 | 674,692 |
import math
def make_multiple(x, number):
""" Increases x to be the smallest multiple of number """
return int(math.ceil(float(x) / float(number)) * number) | 7b25e08beb911b5868e704274c0b36d4bd6449be | 674,693 |
def zones2list(zones, type="power"):
"""Convert zones Strava response into a list
Parameters
----------
zones : dict
Strava API zones response
type : {"power", "heart_rate"}
Returns
-------
y : list
Zones boundaries with left edge set to -1 and right to 10000
"""
... | 19e70764b7c4cb1098c586cdb56aeb83518a2bb9 | 674,694 |
def retrieve_commands(commands):
"""
Retrieve context needed for a set of commit actions
"""
config_commands = commands['config']
support_commit = commands.get('support_commit')
config_verify = commands['config_verification']
return (config_commands, support_commit, config_verify) | c85f69f24581004033eb83d2d0177533c82c6bdf | 674,695 |
def is_list_unique(list_of_cards):
"""
Checks if list members are unique
:param list_of_cards:
:return:
"""
salonga = False
buffer = list(set(list_of_cards))
if len(buffer) == len(list_of_cards):
salonga = True
return salonga | f3d5642753bbf4b2b8adb48ac02d913cc12bcb10 | 674,697 |
from typing import OrderedDict
def extract_submodule_config(configs, path):
"""Extract a submodule config given its path, from a git_config configs dict.
Looks for a matching submodule path, not submodule name.
"""
name = None
for key, value in configs.items():
if not key.startswith("subm... | eff7a984232e134bc73a89d634b8983c5d69a060 | 674,698 |
import re
def RemoveFrameShiftsFromAlignment(row_ali, col_ali, gap_char="-"):
"""remove frame shifts in an alignment.
Frameshifts are gaps are 1, 2, 4, or 5 residues long.
>>> RemoveFrameShiftsFromAlignment("ABC-EFG", "AB-DEFG")
('ABEFG', 'ABEFG')
Arguments
---------
row_ali : string
... | 851b6e9e963b468656da6f4daf1213d403ca0d99 | 674,699 |
def get_artella_python_folder():
"""
Returns folder where Artella stores Python scripts
:return: str
"""
return None | 97f2e6833ed222e495ea689e1fca8546cda9aa0e | 674,700 |
def remove_nan(values):
"""
Replaces all 'nan' value in a list with '0'
"""
for i in range(len(values)):
for j in range(len(values[i])):
if str(values[i][j]) == 'nan':
values[i][j] = 0
return values | 162ad5442a951e48acc510d6896b732a7cac3d3c | 674,701 |
def get_predicates():
"""Get predicates and entities provided by the API
:return: JSON with biolink entities
"""
openpredict_predicates = {
"disease": {
"drug": [
"treated_by"
]
}
}
return openpredict_predicates | 526bd0c486787a103f23b6b563579fbe2d94c93b | 674,702 |
async def headers_middleware(req, handler):
"""
Middleware that adds the current version of the API to the response.
"""
resp = await handler(req)
resp.headers["X-Virtool-Version"] = req.app["version"]
resp.headers["Server"] = "Virtool"
return resp | 2c12a6644aafc1dcd2ef49ff5aead805b10cdc80 | 674,703 |
def loantovalue(purchaseprice, financedamount):
"""Return ratio of financed amount to purchase price.
:param purchaseprice: Contract price of property.
:type purchaseprice: double
:param financedamount: Amount of money borrowed.
:type financedamount: double
:return: double
"""
return f... | 5a88a690823a23607efc77a7fe0e6d7de48cef75 | 674,704 |
def squeeze(array):
"""Return array contents if array contains only one element.
Otherwise, return the full array.
"""
if len(array) == 1:
array = array[0]
return array | 738319557582597805d1f184d30d2ec3e13e9288 | 674,705 |
def to_label(name, capitalize=True):
"""Converts `name` into label by replacing underscores by spaces. If
`capitalize` is ``True`` (default) then the first letter of the label is
capitalized."""
label = name.replace("_", " ")
if capitalize:
label = label.capitalize()
return label | fa030cd9ec337684f624e0df8295e82f7f6dc16b | 674,706 |
def MAR(z, Mh):
"""
Equation 9 from McBride et al. (2009).
..note:: This is the *median* MAH, not the mean.
"""
return 24.1 * (Mh / 1e12)**1.094 * (1. + 1.75 * z) * (1. + z)**1.5 | f2c6cd5b01be2b91aef88b3ee9c763dbcbc0333d | 674,707 |
from functools import reduce
from typing import cast
def cast_schema(df, schema):
"""Enforce the schema on the data frame.
Args:
df (DataFrame): The dataframe.
schema (list): The simple schema to be applied.
Returns:
A data frame converted to the schema.
"""
spark_schema ... | 1a8412a2a3a363589c18f09e672145e94a020aab | 674,708 |
import collections
def _count_plans(computed_relations):
"""Count occurrences of subexpressions across a set of computed relations.
:param computed_relations: a set of computed relations
:return: count of sub-plan occurrence indexed by plan
"""
counts = collections.Counter()
for computed_rela... | 41cae2a596542009940ae0bbdc3e424819e819c0 | 674,709 |
import os
import platform
def get_self_peak_vmm_kb():
"""
Attempt to get the peak virtual memory by looking into the /proc/self/status
Note that this accounts for the peak virtual memory of just the current
process, not the sum of the current process and all its children.
Returns
-------
... | 88d19749ec56d562611db2f1e3847c0128fea459 | 674,711 |
def compare_pbp_matchup(pbp, matchup):
"""Get the differences in scores between play-by-play and matchup DataFrames.
Arguments:
pbp -- name of the play-by-play DataFrame
matchup -- name of the matchup DataFrame
"""
periods = [
pbp.loc[(pbp["id"] == game) & (pbp["period"] == period)].ind... | cb49726a0bc7787102b0091b9745f7e269d5c095 | 674,712 |
def get_social_auths_for_user(user, provider=None):
"""Get UserSocialAuths for given `user`
Filter by specific `provider` if set
Returns a QuerySet of UserSocialAuth objects
"""
social_users = user.social_auth
if provider is None:
social_users = social_users.all()
else:
soc... | 1c7346aedf9795e94bc86b23d84ec73380b28561 | 674,714 |
import argparse
def parse_arguments():
"""
Argument parser configuration.
"""
parser = argparse.ArgumentParser()
parser.add_argument('--log_dir', type=str, default="logs", help="Log directory to store tensorboard summary and model checkpoints")
parser.add_argument('--epochs', type=int, defaul... | 1302588fb1c32ded18678e7dbd5a117c6f7a098f | 674,715 |
import os
def get_download_dir():
"""Get the absolute path to the download directory.
Returns
-------
dirname : str
Path to the download directory
"""
default_dir = os.path.join(os.path.expanduser('~'), '.dgl')
dirname = os.environ.get('DGL_DOWNLOAD_DIR', default_dir)
if not o... | be7e0f4390837149747317960682dbc9767f25aa | 674,716 |
def convert_to_int(value):
"""Attempts to convert a string or a number < value > to an int. If unsuccessful or an
exception is encountered returns the < value > unchanged. Note that this function will return
True for boolean values, faux string boolean values (e.g., "true"), "NaN", exponential
notation,... | afd4a95c3d3df4711e6ac74cb67db911629e40cc | 674,717 |
def abtest(*abtests):
"""Select a (list of) abtest(s)."""
vabtest = [t for t in abtests]
return {"abtest": vabtest} | 2daae4df4cc3cebcf8764acd8f1be37e324f95f9 | 674,719 |
def get_sub_series(sub_cats):
""" Gets the series IDs of all the subseries that are in UTC time
associated with a given load balancing station """
series = []
for category in sub_cats['category']['childseries']:
if "UTC time" in category['name']:
series.append(category['series_id'])
... | 6af4dd8ba22fc39ae75af417ed86e331620db648 | 674,720 |
def lag_changed(current_status, name, min_links):
""" Determines if a modifiable link aggregation group attribute has been modified. """
return (name and name != current_status['lagName']) or (min_links and min_links != current_status['minimumLinks']) | b9442a85affe16cc87901eba23a1c427708178e3 | 674,721 |
from datetime import datetime
import os
def get_file_metadata(url, file_location, gcs_url):
"""Takes a file path and the original URL used to download the data and retrieves metadata on the file.
Args:
url: A string containing the original url used to download the data file.
file_location: A ... | a3a791162e8fe8ac47e7eb449e0723c641341a81 | 674,722 |
from typing import List
def two_sum(nums: List[int], target: int) -> List[int]:
"""
https://leetcode.com/problems/two-sum/
:param nums: list of integers
:param target: expected sum
:return: list of two index of the two integers that when summed are equals to target
:raises: ValueError when com... | 6d4f19e69ec6180afddd3cd67a708429cea70e4f | 674,723 |
import string
import random
def password_gen(length):
"""
generate random password
"""
letters = string.ascii_lowercase
result = ''.join((random.sample(letters, length)))
auto_gen_password= result
return auto_gen_password | e277e2058d0cbb15947702cea1d9f86046b98b07 | 674,724 |
def get_xml_declaration():
"""Return the XML declaration entity <?xml ...>."""
return '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n' | 56b598c2c39eb2bc67bc89f9ecc0934c38c14f00 | 674,726 |
import requests
def is_successful(result):
"""
result could either be a boolean or the response object.
"""
if isinstance(result, requests.models.Response):
return int(result.status_code / 100) == 2
else:
return result | f5d867c16cc10c909e5722c39696299bb2d23dd5 | 674,727 |
from typing import Union
from pathlib import Path
def guess_format(filename: Union[str, Path]):
"""
Guess the output format from a given filename and return the corrected format.
Any names not in the dict get passed through.
"""
extension = str(filename).rsplit(".", 1)[-1].lower()
format_map ... | b5eb01e9cd2a294b31c5194a73fe3f0d3e6b3efc | 674,729 |
def TD2hours(td):
"""
convert a timedelta to integer hours
"""
return td.days*24 + td.seconds/3600.0 + td.microseconds/3600000.0 | 4891d007f4057b8d056536bf30f76e0b43c50153 | 674,730 |
def decode_file_line(dwarfinfo, address):
""" Get the source code line associated with an PC address"""
# Go over all the line programs in the DWARF information, looking for
# one that describes the given address.
for CU in dwarfinfo.iter_CUs():
# First, look at line programs to find the file/l... | 7899e575d75633b4a133389c13fba41b111af2da | 674,731 |
def sub(num1, num2):
"""
Subtract two numbers
"""
return num1 - num2 | f5e0b2e47302c50f79f1ba8a3d3bc6dffa8054c6 | 674,732 |
import numpy
def accelerate_hessian(p, x_mat, g_vectors, eye_mat, s, num_class, d):
"""
accelerate the process of compute hessian
compute H^-1 * g
"""
p_vectors = numpy.zeros((num_class, d, 1))
for i in range(num_class):
p_i = p[i].reshape(s, 1)
p_i = p_i - numpy.power(p_i, 2)
... | 794a3adb2e49d7fc2f92303788938058f114f7dc | 674,733 |
import re
def remove_links(text: str) -> str:
"""
Removes links from a text.
Args:
text (:obj:`str`):
Text to process.
Returns:
:obj:`str`:
Text without links.
"""
# add empty character between two paragraph html tags to make processing easier
te... | 75bde7a53ccbcbc3007fde66f3573df457ecbda9 | 674,735 |
def sum_list(node):
"""
Given a Python list, sum its values recursively.
"""
if node is None:
return 0
return node.value + sum_list(node.next) | 375cad754750b5aaa60c1877193d4c6cd8033c37 | 674,736 |
from typing import List
def _validate_counts(counts: List[int]) -> bool:
"""
Validates the counts parameter.
Parameters
----------
counts : List[integers]
A list of counts.
Raises
------
TypeError
The ``counts`` parameter is not a list or one of the elements of this
... | a87095d1df60e75801ed81485a3223b8a3e6a8ea | 674,737 |
def simplify_headers(headers: list[str]) -> list[str]:
"""Simplify the headers for the data to be more readable
The header names are fusions between the first and second header line
in the OpenCravat input. This function removes the parts of the header
names that are useless. In short, it keeps only th... | 924d86d0e3359862fd2616ce38dae81599b3d4cc | 674,738 |
def get_max_width(text_array):
"""Get the maximum width of a bunch of rows of text."""
width = 0
# Figure out the maximum width
for row in text_array:
if len(row) > width:
width = len(row)
return width | 9fae5e9a6d634c641e8920fff4700db67e6cc895 | 674,739 |
def mel2hz(mel):
"""Convert a value in Hertz to Mels
Parameters
----------
hz : number of array
value in Hz, can be an array
Returns:
--------
_ : number of array
value in Mels, same type as the input.
"""
return 700 * (10 ** (mel / 2595.0) - 1) | fede0b4779e712ed2bd76c549f0ac675c924e436 | 674,740 |
import torch
def generate_proposals(anchors, offsets, method="YOLO"):
"""
Generate all proposals from anchors given offsets.
@Params:
-------
anchors (tensor):
Tensor of shape [B, A, H', W', 4] returned by `generate_anchors()`. Anchors are
parameterized by the coordinates (x_tl, y... | 133cfd328b38fffe7cbcb0bcae33e7af5d0c1c98 | 674,741 |
import re
def syntax_highlight(msg):
"""
Inserts HTML `<span>` elements into a string, for symbol/word styling.
Args:
msg : (str) A message.
"""
msg.replace("<", "&;lt")
msg.replace(">", "&;gt")
font_size = 16.0 / len(msg)
msg = re.sub('([!()"%])', '<span class="dark">\\1</s... | 13058f16b69c58af77fee230f574cfdc825517dd | 674,743 |
import os
def _FindGsUtil():
"""Looks for depot_tools and returns the absolute path to gsutil.py."""
for path in os.environ['PATH'].split(os.pathsep):
path = os.path.abspath(path)
git_cl = os.path.join(path, 'git_cl.py')
gs_util = os.path.join(path, 'gsutil.py')
if os.path.exists(git_cl) and os.pa... | 65c555ebb5cc9278fa60f929fadc84c77da82d0f | 674,744 |
def create_mapping(dict_times):
"""
If times are not integers transform each one of them to a unique integer of its own.
"""
keys = list(dict_times.keys())
mapping = {}
for i in range(len(keys)):
mapping.update({keys[i]: i})
return mapping | 9720a63d1b938f009193519ca94330e6eb078078 | 674,745 |
import os
def create_image_label_mapping(glob_image, encoded_y, label_df):
""" returns a dictionary X_train(image_path to open while writing image), Y_label
to be unpacked for writing into TFRecord """
image_labels = dict()
for image in glob_image:
image_idx = int(os.path.basename(
... | dc7d4cc25d4ac99580290d5c6b68cb00db690cb6 | 674,746 |
def getinfo(args, data):
"""
预计
:param args: [('20191121056', '73901'), ('20191121057', '80705'),
:param data: 0~9
:return: [('002', '86440', '|1对', '1'), ('006', '58336', '|1对', '1'),
"""
result_true = 0
result_error = 0
result_count = 0
result_list = []
... | 2debf79fade050a71bb791e82014469ac944ceeb | 674,747 |
def traitement_colonnes_zeit(df_messung):
"""
Retire les colonnes inutlies de la df (Zeit)
"""
for column_name in df_messung.columns:
if 'Zeit' in column_name:
del df_messung[column_name]
return df_messung | 5de7f5d14668d09cf3b2d45bf190eb5c81d0d44e | 674,748 |
def constrain(value, lowest, highest):
"""Test whether `value` is within the range `(highest, lowest)`.
Return `value` if it is inside the range, otherwise return
`highest` if the value is *above* the range or `lowest` it the value
is *below* the range.
>>> constrain(-1, 2, 5)
2
>>> constra... | 197668ebd855a79db217991788105b49860664ed | 674,749 |
from typing import List
from typing import Any
def async_results(i: List[Any]):
"""Just a dummy function to get the results of the mapped async functions
param i: List containing results
:type i: List[Any]"""
return i[1] | fb54669991a229d857956ef0271a13988c5c1934 | 674,750 |
def graph_place_text(work):
"""Get place text for graph
Default: return place acronym
"""
if getattr(work, "place", None) is not None:
return work.place.acronym | 9d63b00a4d3ac3f39a08570ee6863772b5967c1f | 674,751 |
def first(mention):
""" Compute the first token of a mention.
Args:
mention (Mention): A mention.
Returns:
The tuple ('first', TOKEN), where TOKEN is the (lowercased) first
token of the mention.
"""
return "first", mention.attributes["tokens"][0].lower() | 7cd0bc412d7b59fa26b2981b3d0c1a0c1465c0dc | 674,753 |
from typing import Optional
def ask_employee_id() -> Optional[int]:
"""
Fetch the Employee ID from the user.
"""
try:
return int(input('Enter the Employee ID: '))
except Exception:
return None | deb1bcf9ea233c31106ca431943113310188dc81 | 674,754 |
def _get_nested_sorted_probs(
new_variables_order_outer, new_variables_order_inner, old_variable_order, old_assign_probs
):
"""
Reorder variables to a new order (and sort assignments) and then convert the probs dictionary to a hierarchical
dictionary with certain variables (or rather their correspon... | ed88eed91670d8e36aae94776dd9634958baf235 | 674,755 |
import optparse
def standalone():
"""Set up for running as main."""
parser = optparse.OptionParser()
add = parser.add_option
add(
"-i",
"--install",
action="store_true",
dest="i",
default=False,
help="compile and install the newly created file. "
... | a942d75827cb090c73d90fd12852e09d0b4665aa | 674,756 |
def convert_velocity(val, old_scale="km/h", new_scale="m/s"):
"""
Convert from a velocity scale to another one among km/h, and m/s.
Parameters
----------
val: float or int
Value of the velocity to be converted expressed in the original scale.
old_scale: str
Original scale from ... | 6a38ac70090f14a4a0d3989ce5a1a884067afd77 | 674,757 |
def Set_AxText(ax,text_string,pos='uc',ftdic=None,color='k',**kwargs):
"""
Purpose: add a text to axes. pos can be['lc','uc','ll','ul','lr','ur'],
when it's a tuple, indicating relative position.
Parameters:
-----------
Default values:
lc: 0.5, 0.05
ouc: 0.5, 1.02
uc: 0.5, 0.9... | 46df8de34fffbd7c582eb12719c89672d8892665 | 674,758 |
import calendar
def get_month_dispatch_intervals(year, month):
"""Get all dispatch interval IDs for a given month"""
days = range(1, calendar.monthrange(year, month)[1] + 1)
intervals = range(1, 289)
return [f'{year}{month:02}{d:02}{i:03}' for d in days for i in intervals] | 543337d356313471abda6493e9b23a8057fb1f9a | 674,759 |
from pkg_resources import iter_entry_points
def mock_iter_entry_points_factory(data, mocked_group):
"""Create a mock iter_entry_points function."""
def entrypoints(group, name=None):
if group == mocked_group:
for entrypoint in data:
yield entrypoint
else:
... | 6062ff151661d6523f3e3eb26928e905052b26e9 | 674,760 |
def isprime(number):
"""
Check if a number is a prime number
number:
The number to check
"""
if number == 1:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True | ea644071a80ed9d467d025cfd6261783abb688c5 | 674,761 |
def input_number(message):
"""
Returns user input if its valid.
"""
while True:
try:
input_value = int(input(message))
return input_value
except ValueError:
print('Input must be a number!')
continue | a2c0ef444ed1389d342050e88e211197dc53e233 | 674,762 |
def import_class_by_path(class_path):
"""Import a class by its <module>.<name> path.
Args:
class_path: <module>.<name> for a class.
Returns:
Class object for the given class_path.
"""
classname = class_path.split('.')[-1]
modulename = '.'.join(class_path.split('.')[0:-1])
mod = __import__(module... | a03ba0e25b70328ec7cc2ac044ed165ca30cfdf7 | 674,763 |
def get_pk_int(view):
"""
必须转为int否则不等于request.user.id, int必须有值安全起见设默认值0
"""
return int(view.kwargs.get('pk', 0)) | 2ffe6dc04e94ed362bc6b8fa08c3a04fe5a9d94e | 674,764 |
def avg(l):
"""Returns the average of a list of numbers."""
if not l:
return None
return sum(l)/len(l) | 1d3ad50753796374dd73008dc1d3eb95432780c1 | 674,766 |
import typing
import re
import logging
def read_accounts_csv(input_file: typing.IO) -> typing.Dict:
"""
Parses contents from the CSV file containing the accounts and email addreses.
Returns:
A dictionary where the key is account ID and value is email address.
"""
account_re = re.compile(r... | 4e4a8d49b6ec832753752b640fda6e0ae432ca57 | 674,767 |
import re
def clean_str(text: str) -> str:
"""
Args:
text: A unicode string
Returns:
str: lowercased, sans punctuation, non-English letters
"""
RE_PREPROCESS = r'\W+|\d+'
text = re.sub(
RE_PREPROCESS,
' ',
text.lower()
)
text = re.sub(r"[^A-Za-z0... | d716c66d77ba73335f19d345879fa59f42277774 | 674,769 |
def common_suffix(l):
"""
Return common suffix of the stings
>>> common_suffix(['dabc', '1abc'])
'abc'
"""
commons = []
for i in range(min(len(s) for s in l)):
common = l[0][-i-1]
for c in l[1:]:
if c[-i-1] != common:
return ''.join(reverse... | 8634ed160c3503dd8ac31bbb66505f5f18d9f908 | 674,770 |
def op_signum(x):
"""Returns the sign of this mathematical object."""
if isinstance(x, list):
return [op_signum(a) for a in x]
else:
m = abs(x)
if m:
x /= m
return x | 13c0eba48091fb660e174b25e3fd7c8b05409557 | 674,771 |
def NetworkSetSFANodeClass(sfa_node_class, network):
"""Replaces the field sfa_node_class of all layers with a specific node class.
This function is useful, for example, to transform an SFA network into a PCA network. """
for i, layer in enumerate(network.layers):
layer.sfa_node_class = sfa_node_cl... | e40b8be605c9b3f838298cd7c647194a0963a49f | 674,772 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.