content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import struct
import lzma
def decompress_lzma(data: bytes) -> bytes:
"""decompresses lzma-compressed data
:param data: compressed data
:type data: bytes
:raises _lzma.LZMAError: Compressed data ended before the end-of-stream marker was reached
:return: uncompressed data
:rtype: bytes
"""
... | 247c3d59d45f3f140d4f2c36a7500ff8a51e45b0 | 706,567 |
def get_case_number(caselist):
"""Get line number from file caselist."""
num = 0
with open(caselist, 'r') as casefile:
for line in casefile:
if line.strip().startswith('#') is False:
num = num + 1
return num | b1366d8e4a0e2c08da5265502d2dd2d72bf95c19 | 706,568 |
def _parseList(s):
"""Validation function. Parse a comma-separated list of strings."""
return [item.strip() for item in s.split(",")] | 5bf9ac50a44a18cc4798ed616532130890803bac | 706,569 |
def splitDataSet(dataSet, index, value):
"""
划分数据集,取出index对应的值为value的数据
dataSet: 待划分的数据集
index: 划分数据集的特征
value: 需要返回的特征的值
"""
retDataSet = []
for featVec in dataSet:
if featVec[index] == value:
reducedFeatVec = featVec[:index]
reducedFeatVec.extend(fe... | 814a54fe13d832e69d8df32af52d882d4a15c4ba | 706,570 |
def in_skill_product_response(handler_input):
"""Get the In-skill product response from monetization service."""
""" # type: (HandlerInput) -> Union[InSkillProductsResponse, Error] """
locale = handler_input.request_envelope.request.locale
ms = handler_input.service_client_factory.get_monetization_servi... | 9452ac1498ff0e6601df9fc419df0cfdd6b9171e | 706,572 |
def stat_mtime(stat):
"""Returns the mtime field from the results returned by os.stat()."""
return stat[8] | 1f7fec9a54a97bb63141d63db706b2885913dadb | 706,573 |
def calc_very_restricted_wage_distribution(df):
"""Compute per-period mean and std of wages for agents under two choice restrictions."""
return (
df.query("Policy == 'veryrestricted' and Choice == 'a' or Choice == 'b'")
.groupby(["Period"])["Wage"]
.describe()[["mean", "std"]]
) | 3ca8a2f0061e456a3158b4ee8a128a5a7439af3f | 706,574 |
def msort(liste, indice):
"""
This function sorts a vector regarding values of the indice 'indice'
Indice start from 0
"""
tmp = [[tbl[indice]]+[tbl] for tbl in liste]
tmp.sort()
liste = [cl[1] for cl in tmp]
del tmp
return liste | 7f4caff9a74f4d118877e335513e68ecd54986d8 | 706,576 |
def _Net_forward(self, blobs=None, start=None, end=None, **kwargs):
"""
Forward pass: prepare inputs and run the net forward.
Take
blobs: list of blobs to return in addition to output blobs.
kwargs: Keys are input blob names and values are blob ndarrays.
For formatting inputs for Caffe,... | 790baa0fc8529e3cad45bd8236060bad591ab4a4 | 706,577 |
import os
def MakeCommandName(name):
"""adds '.exe' if on Windows"""
if os.name == 'nt':
return name + '.exe'
return name | 39aba823ee6de6fb6d550dd7bfbdaf310010278b | 706,579 |
import os
def is_path_parent(possible_parent, *paths):
"""
Return True if a path is the parent of another, False otherwise.
Multiple paths to test can be specified in which case all
specified test paths must be under the parent in order to
return True.
"""
def abs_path_trailing(pth):
... | 23ae7ab4cf2aaf4935613501a5344cf811313e7b | 706,580 |
def cmpversion(a, b):
"""Compare versions the way chrome does."""
def split_version(v):
"""Get major/minor of version."""
if '.' in v:
return v.split('.', 1)
if '_' in v:
return v.split('_', 1)
return (v, '0')
a_maj, a_min = split_version(a)
b_maj, b_min = split_version(b)
if a_maj... | 226191f2a72d4cb65198ddcb779b130b7a524034 | 706,581 |
from datetime import datetime
def create_nav_btn(soup,date,text):
"""
Helper functions for month_calendar, generates a navigation button
for calendar
:param soup: BeautifulSoup parser of document
:param date: Date to create nav button
:param text: Text for button
"""
nav_th = soup.new... | 6f49e5173980a9da01e4d92e2f5adfeb73a4a4d0 | 706,582 |
import re
def parse_name(content):
"""
Finds the name of the man page.
"""
# Create regular expression
name_regex = re.compile(r"^([\w\.-]*)")
# Get name of manual page
just_name = name_regex.search(content)
name_str = ""
if just_name is not None:
name_str = just_name.... | c3a1f32beb96d39d4490681bf90d54115597ffe5 | 706,584 |
def albanian_input_normal(field, text):
"""
Prepare a string from one of the query fields for subsequent
processing: replace common shortcuts with valid Albanian characters.
"""
if field not in ('wf', 'lex', 'lex2', 'trans_ru', 'trans_ru2'):
return text
text = text.replace('ё', 'ë')
... | 6bd4e7a1e764feada04ae5e95465fb4d7cbb29fb | 706,585 |
import re
def extract_share_id_from_url(public_base_url: str) -> str:
"""
Extracts the Airtable share id from the provided URL.
:param public_base_url: The URL where the share id must be extracted from.
:raises ValueError: If the provided URL doesn't match the publicly shared
Airtable URL.
... | 5aad99b5bf022a2b957f10fcb09793188051340c | 706,586 |
def adjust_learning_rate(optimizer, epoch, args):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
if args.lr_policy == 'decay':
lr = args.lr * (args.lr_decay ** epoch)
elif args.lr_policy == 'poly':
interval = len([x for x in args.lr_custom_step if epoch >= x])
... | c247c81a90476e737ff54c2a7ca45f5c42dccd38 | 706,587 |
def find_file_start(chunks, pos):
"""Find a chunk before the one specified which is not a file block."""
pos = pos - 1
while pos > 0:
if chunks[pos][0] != 0x100 and chunks[pos][0] != 0x102:
# This is not a block
return pos
else:
pos = pos - 1
return pos | b0fb280a847dea3cd589d59863888d1087d4982f | 706,588 |
def get_all_ann_index(self):
""" Retrieves all annotation ids """
return list(self.ann_infos.keys()) | 4375c9dbc14bf50575c8a5e42ce0ae8749820dfb | 706,589 |
def get_pairs(l, k):
"""
Given a list L of N unique positive integers, returns the count of the total pairs of numbers
whose difference is K. First, each integer is stored into a dictionary along with its frequency.
Then, for each integer I in the input list, the presence of the integer I+K is checked w... | 90fd199c75431c1d20076cea04358b3ca5872810 | 706,590 |
def get_quoted_text(text):
"""Method used to get quoted text.
If body/title text contains a quote, the first quote is considered as the text.
:param text: The replyable text
:return: The first quote in the text. If no quotes are found, then the entire text is returned
"""
lines = text.split('\n... | 3ac1801edcaf16af45d118918cb548f41d9a08fb | 706,591 |
def get_username_for_os(os):
"""Return username for a given os."""
usernames = {"alinux2": "ec2-user", "centos7": "centos", "ubuntu1804": "ubuntu", "ubuntu2004": "ubuntu"}
return usernames.get(os) | 579ebfa4e76b6660d28afcc010419f32d74aa98c | 706,592 |
from typing import List
def is_negative_spec(*specs: List[List[str]]) -> bool:
""" Checks for negative values in a variable number of spec lists
Each spec list can have multiple strings. Each string within each
list will be searched for a '-' sign.
"""
for specset in specs:
if spe... | 216e6db2e63a657ac95a31896b9b61329a10a3db | 706,593 |
def loadEvents(fname):
"""
Reads a file that consists of first column of unix timestamps
followed by arbitrary string, one per line. Outputs as dictionary.
Also keeps track of min and max time seen in global mint,maxt
"""
events = []
ws = open(fname, 'r').read().splitlines()
events = []
for w in ws:
... | 495dbd5d47892b953c139b27b1f20dd9854ea29a | 706,594 |
from datetime import datetime
import json
import hashlib
def map_aircraft_to_record(aircrafts, message_now, device_id):
"""
Maps the `aircraft` entity to a BigQuery record and its unique id.
Returns `(unique_ids, records)`
"""
def copy_data(aircraft):
result = {
'hex': aircraft.get('hex'),
'... | d423b87e2018486de076cc94a719038c53c54602 | 706,596 |
def sub(xs, ys):
"""
Computes xs - ys, such that elements in xs that occur in ys are removed.
@param xs: list
@param ys: list
@return: xs - ys
"""
return [x for x in xs if x not in ys] | 8911bb2c79919cae88463a95521cf051828038e8 | 706,597 |
def input_fn(request_body, request_content_type):
"""
An input_fn that loads the pickled tensor by the inference server of SageMaker.
The function deserialize the inference request, then the predict_fn get invoked.
Does preprocessing and returns a tensor representation of the source sentence
ready t... | 62d45e188d5537eaa566bd4b90bdb8abc7626621 | 706,598 |
def get_colors(k):
"""
Return k colors in a list. We choose from 7 different colors.
If k > 7 we choose colors more than once.
"""
base_colors = ['b', 'r', 'g', 'c', 'm', 'y', 'k']
colors = []
index = 1
for i in range(0, k):
if index % (len(base_colors) + 1) == 0:
in... | 6c4a38eb394254f57d8be9fca47e0b44f51f5f04 | 706,599 |
import argparse
def _parse_args() -> argparse.Namespace:
"""Parses and returns the command line arguments."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('in_json',
type=argparse.FileType('r'),
help='The JSON file containing a ... | 108f2ab7d962fa31a99158997f832f46b8b8d6f8 | 706,600 |
def get_channels(posts):
"""
<summary> Returns post channel (twitter/facebook)</summary>
<param name="posts" type="list"> List of posts </param>
<returns> String "twitter" or "facebook" </returns>
"""
channel = []
for i in range(0, len(posts['post_id'])):
if len(posts['post_text'][i... | 2bd67d13079ce115263ac46856d8a708f461cb7e | 706,601 |
def ConvertToTypeEnum(type_enum, airflow_executor_type):
"""Converts airflow executor type string to enum.
Args:
type_enum: AirflowExecutorTypeValueValuesEnum, executor type enum value.
airflow_executor_type: string, executor type string value.
Returns:
AirflowExecutorTypeValueValuesEnum: the execut... | 04162b04719031ba6b96d981a7ffe8a82691bc31 | 706,602 |
import os
import pkgutil
def get_data(cfg, working_dir, global_parameters, res_incl=None, res_excl=None):
"""Reads experimental measurements"""
exp_type = global_parameters['experiment_type']
path = os.path.dirname(__file__)
pkgs = [
modname
for _, modname, ispkg in pkgutil.iter_modu... | 826314fe99b6ba6dc408c7b0109536ae5fdc0acb | 706,603 |
def index(web):
"""The web.request.params is a dictionary,
pointing to falcon.Request directly."""
name = web.request.params["name"]
return f"Hello {name}!\n" | b717ac60d42b8161ed27f7e4156d8a5a03aea803 | 706,604 |
def _parseLocalVariables(line):
"""Accepts a single line in Emacs local variable declaration format and
returns a dict of all the variables {name: value}.
Raises ValueError if 'line' is in the wrong format.
See http://www.gnu.org/software/emacs/manual/html_node/File-Variables.html
"""
paren = '... | 39dc5130f47589e111e4b894cf293d446ac0eac0 | 706,605 |
def __clean_datetime_value(datetime_string):
"""Given"""
if datetime_string is None:
return datetime_string
if isinstance(datetime_string, str):
x = datetime_string.replace("T", " ")
return x.replace("Z", "")
raise TypeError("Expected datetime_string to be of type string (or No... | 77afef31056365a47ea821de7a4979cb061920dc | 706,606 |
import os
def create_folder(path):
"""
Creates a folder if not already exists
Args:
:param path: The folder to be created
Returns
:return: True if folder was newly created, false if folder already exists
"""
if not os.path.exists(path):
os.makedirs(path)
return... | 9b6cfaed256001aa15c15cb535fce54ddcf20bc8 | 706,607 |
def is_member(musicians, musician_name):
"""Return true if named musician is in musician list;
otherwise return false.
Parameters:
musicians (list): list of musicians and their instruments
musician_name (str): musician name
Returns:
bool: True if match is made; otherwise False.... | 6ef5b9bbccb17d9b97a85e3af7789e059829184b | 706,608 |
def _to_sequence(x):
"""shape batch of images for input into GPT2 model"""
x = x.view(x.shape[0], -1) # flatten images into sequences
x = x.transpose(0, 1).contiguous() # to shape [seq len, batch]
return x | bb3b0bb478c924b520bf7bf991a028cf8aaea25f | 706,609 |
def combine_per_choice(*args):
"""
Combines two or more per-choice analytics results into one.
"""
args = list(args)
result = args.pop()
new_weight = None
new_averages = None
while args:
other = args.pop()
for key in other:
if key not in result:
result[key] = other[key]
else:... | 63e482a60b521744c94d80b0b8a740ff74f4b197 | 706,610 |
import string
def prepare_input(dirty: str) -> str:
"""
Prepare the plaintext by up-casing it
and separating repeated letters with X's
"""
dirty = "".join([c.upper() for c in dirty if c in string.ascii_letters])
clean = ""
if len(dirty) < 2:
return dirty
for i in range(len(d... | 5c55ba770e024b459d483fd168978437b8d48c21 | 706,611 |
def get_signed_value(bit_vector):
"""
This function will generate the signed value for a given bit list
bit_vector : list of bits
"""
signed_value = 0
for i in sorted(bit_vector.keys()):
if i == 0:
signed_value = int(bit_vector[i])
else:
signed_... | 6b2b9a968576256738f396eeefba844561e2d2c7 | 706,613 |
from typing import List
import sys
def _clean_sys_argv(pipeline: str) -> List[str]:
"""Values in sys.argv that are not valid option values in Where
"""
reserved_opts = {pipeline, "label", "id", "only_for_rundate", "session", "stage", "station", "writers"}
return [o for o in sys.argv[1:] if o.startswit... | 551f4fdca5d7cc276b03943f3679cc2eff8ce89e | 706,614 |
def get_number_from_user_input(prompt: str, min_value: int, max_value: int) -> int:
"""gets a int integer from user input"""
# input loop
user_input = None
while user_input is None or user_input < min_value or user_input > max_value:
raw_input = input(prompt + f" ({min_value}-{max_value})? ")
... | c9df4ac604b3bf8f0f9c2a35added1f23e88048e | 706,615 |
def process_domain_assoc(url, domain_map):
"""
Replace domain name with a more fitting tag for that domain.
User defined. Mapping comes from provided config file
Mapping in yml file is as follows:
tag:
- url to map to tag
- ...
A small example domain_assoc.yml is included
"... | 29c0f81a4959d97cd91f839cbe511eb46872b5ec | 706,616 |
import random
def shuffled(iterable):
"""Randomly shuffle a copy of iterable."""
items = list(iterable)
random.shuffle(items)
return items | cd554d4a31e042dc1d2b4c7b246528a5184d558e | 706,617 |
def parse_discontinuous_phrase(phrase: str) -> str:
"""
Transform discontinuous phrase into a regular expression. Discontinuity is
interpreted as taking place at any whitespace outside of terms grouped by
parentheses. That is, the whitespace indicates that anything can be in between
the left side an... | 58fe394a08931e7e79afc00b9bb0e8e9981f3c81 | 706,618 |
def name_standard(name):
""" return the Standard version of the input word
:param name: the name that should be standard
:return name: the standard form of word
"""
reponse_name = name[0].upper() + name[1:].lower()
return reponse_name | 65273cafaaa9aceb803877c2071dc043a0d598eb | 706,619 |
def getChildElementsListWithTagAttribValueMatch(parent, tag, attrib, value):
"""
This method takes a parent element as input and finds all the sub elements (children)
containing specified tag and an attribute with the specified value.
Returns a list of child elements.
Arguments:
parent = paren... | cae87e6548190ad0a675019b397eeb88289533ee | 706,620 |
def not_numbers():
"""Non-numbers for (i)count."""
return [None, [1, 2], {-3, 4}, (6, 9.7)] | 31f935916c8463f6192d0b2770c1034ee70a4fc5 | 706,621 |
def default_validate(social_account):
"""
Функция по-умолчанию для ONESOCIAL_VALIDATE_FUNC. Ничего не делает.
"""
return None | 634382dbfe64eeed38225f8dca7e16105c40f7c2 | 706,622 |
def recursive_dict_of_lists(d, helper=None, prev_key=None):
"""
Builds dictionary of lists by recursively traversing a JSON-like
structure.
Arguments:
d (dict): JSON-like dictionary.
prev_key (str): Prefix used to create dictionary keys like: prefix_key.
Passed by recursive ... | c615582febbd043adae6788585d004aabf1ac7e3 | 706,623 |
def same_shape(shape1, shape2):
"""
Checks if two shapes are the same
Parameters
----------
shape1 : tuple
First shape
shape2 : tuple
Second shape
Returns
-------
flag : bool
True if both shapes are the same (same length and dimensions)
"""
if len(shap... | 9452f7973e510532cee587f2bf49a146fb8cc46e | 706,624 |
from typing import List
from typing import Any
def reorder(list_1: List[Any]) -> List[Any]:
"""This function takes a list and returns it in sorted order"""
new_list: list = []
for ele in list_1:
new_list.append(ele)
temp = new_list.index(ele)
while temp > 0:
if new_li... | 2e7dad8fa138b1a9a140deab4223eea4a09cdf91 | 706,625 |
def is_extended_markdown(view):
"""True if the view contains 'Markdown Extended'
syntax'ed text.
"""
return view.settings().get("syntax").endswith(
"Markdown Extended.sublime-syntax") | 5c870fd277910f6fa48f2b8ae0dfd304fdbddff0 | 706,626 |
def start_end_epoch(graph):
"""
Start epoch of graph.
:return: (start epoch, end epoch).
"""
start = 0
end = 0
for e in graph.edges_iter():
for _, p in graph[e[0]][e[1]].items():
end = max(end, p['etime_epoch_secs'])
if start == 0:
start = p['s... | 724726ec83d3a98539eed859ec584c6f1adb8567 | 706,627 |
def is_point_in_rect(point, rect):
"""Checks whether is coordinate point inside the rectangle or not.
Rectangle is defined by bounding box.
:type point: list
:param point: testing coordinate point
:type rect: list
:param rect: bounding box
:rtype: boolean
:return: boolean check result
"""
x0, y0,... | d0c7a64138899f4e50b42dc75ea6030616d4dfec | 706,628 |
from os.path import expanduser
def parse_pgpass(hostname='scidb2.nersc.gov', username='desidev_admin'):
"""Read a ``~/.pgpass`` file.
Parameters
----------
hostname : :class:`str`, optional
Database hostname.
username : :class:`str`, optional
Database username.
Returns
--... | 929b705fa8a753f773321e47c73d096ffb4bd171 | 706,629 |
def convert_timestamp(ts):
"""Converts the timestamp to a format suitable for Billing.
Examples of a good timestamp for startTime, endTime, and eventTime:
'2016-05-20T00:00:00Z'
Note the trailing 'Z'. Python does not add the 'Z' so we tack it on
ourselves.
"""
return ts.isoformat() + 'Z... | 6b8d19671cbeab69c398508fa942e36689802cdd | 706,630 |
import re
def address_split(address, env=None):
"""The address_split() function splits an address into its four
components. Address strings are on the form
detector-detectorID|device-deviceID, where the detectors must be in
dir(xtc.DetInfo.Detector) and device must be in
(xtc.DetInfo.Device).
@param addr... | c5d362c7fc6121d64ec6a660bcdb7a9b4b532553 | 706,632 |
def can_create_election(user_id, user_info):
""" for now, just let it be"""
return True | 06c8290b41b38a840b7826173fd65130d38260a7 | 706,633 |
def boolean(input):
"""Convert the given input to a boolean value.
Intelligently handles boolean and non-string values, returning
as-is and passing to the bool builtin respectively.
This process is case-insensitive.
Acceptable values:
True
* yes
* y
* ... | 09c09206d5487bf02e3271403e2ba67358e1d148 | 706,634 |
def create_provisioned_product_name(account_name: str) -> str:
"""
Replaces all space characters in an Account Name with hyphens,
also removes all trailing and leading whitespace
"""
return account_name.strip().replace(" ", "-") | 743e7438f421d5d42c071d27d1b0fa2a816a9b4d | 706,635 |
def release_branch_name(config):
"""
build expected release branch name from current config
"""
branch_name = "{0}{1}".format(
config.gitflow_release_prefix(),
config.package_version()
)
return branch_name | 0d97c515aca8412882c8b260405a63d20b4b0f63 | 706,636 |
def torch2numpy(data):
""" Transfer data from the torch tensor (on CPU) to the numpy array (on CPU). """
return data.numpy() | c7ca4123743c4f054d809f0e307a4de079b0af10 | 706,637 |
def edges_to_adj_list(edges):
"""
Transforms a set of edges in an adjacency list (represented as a dictiornary)
For UNDIRECTED graphs, i.e. if v2 in adj_list[v1], then v1 in adj_list[v2]
INPUT:
- edges : a set or list of edges
OUTPUT:
- adj_list: a dictionary with the vertices as ... | 683f10e9a0a9b8a29d63b276b2e550ebe8287a05 | 706,638 |
def default_mutable_arguments():
"""Explore default mutable arguments, which are a dangerous game in themselves.
Why do mutable default arguments suffer from this apparent problem? A function's
default values are evaluated at the point of function definition in the defining
scope. In particular, we can ... | a58a8c2807e29af68d501aa5ad4b33ad1aa80252 | 706,639 |
def get_user_messages(user, index=0, number=0):
"""
返回指定user按时间倒序的从index索引开始的number个message
"""
if not user or user.is_anonymous or index < 0 or number < 0:
return tuple()
# noinspection PyBroadException
try:
if index == 0 and number == 0:
all_message = user.messa... | bb0c499e5ca8ec650d2ebca12852d2345733e882 | 706,640 |
import argparse
from pathlib import Path
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description="Map gleason data to standard format.")
parser.add_argument("-d", "--data_path", type=Path, help="Path to folder with the data.", required=True)
parser.add_argument("-n... | 0a1a1cb404d74c48d550642e31399410d1bd13c3 | 706,641 |
def read_simplest_expandable(expparams, config):
"""
Read expandable parameters from config file of the type `param_1`.
Parameters
----------
expparams : dict, dict.keys, set, or alike
The parameter names that should be considered as expandable.
Usually, this is a module subdictiona... | 4e2068e4a6cbca050da6a33a24b5fb0d2477e4e3 | 706,642 |
def _hexsplit(string):
""" Split a hex string into 8-bit/2-hex-character groupings separated by spaces"""
return ' '.join([string[i:i+2] for i in range(0, len(string), 2)]) | 672e475edeaafaa08254845e620b0a771b294fa8 | 706,643 |
from typing import List
def hello_world(cities: List[str] = ["Berlin", "Paris"]) -> bool:
"""
Hello world function.
Arguments:
- cities: List of cities in which 'hello world' is posted.
Return:
- success: Whether or not function completed successfully.
"""
try:
[print("Hello... | a24f0f47c9b44c97f46524d354fff0ed9a735fe3 | 706,644 |
import os
def makeFolder(path):
"""Build a folder.
Args:
path (str): Folder path.
Returns:
bool: Creation status.
"""
if(not os.path.isdir(path)):
try:
os.makedirs(path)
except OSError as error:
print("Directory %s can't be created (%s)" % ... | 4bd1535fb3ffc69f5638b6cfbeaf90a1ccbdf2f9 | 706,645 |
def team_to_repos(api, no_repos, organization):
"""Create a team_to_repos mapping for use in _add_repos_to_teams, anc create
each team and repo. Return the team_to_repos mapping.
"""
num_teams = 10
# arrange
team_names = ["team-{}".format(i) for i in range(num_teams)]
repo_names = ["some-rep... | 390da146c3f96c554f9194f8551a066eec535533 | 706,646 |
import struct
def padandsplit(message):
"""
returns a two-dimensional array X[i][j] of 32-bit integers, where j ranges
from 0 to 16.
First pads the message to length in bytes is congruent to 56 (mod 64),
by first adding a byte 0x80, and then padding with 0x00 bytes until the
message length is ... | ea06a3fc91e19ed0dbea6ddcc2ee6d554fb5a40f | 706,647 |
def extract_coords(filename):
"""Extract J2000 coordinates from filename or filepath
Parameters
----------
filename : str
name or path of file
Returns
-------
str
J2000 coordinates
"""
# in case path is entered as argument
filename = filename.split("/")[-1] if ... | 57f0ca79223116caa770a1dbea2eda84df146855 | 706,648 |
def _parse_multi_header(headers):
"""
Parse out and return the data necessary for generating ZipkinAttrs.
Returns a dict with the following keys:
'trace_id': str or None
'span_id': str or None
'parent_span_id': str or None
'sampled_str': ... | 2ac3d0cbee196385e970bcc85827c1a467b5bb3b | 706,649 |
def brand_profitsharing_order_query(self, transaction_id, out_order_no, sub_mchid):
"""查询连锁品牌分账结果
:param transaction_id: 微信支付订单号,示例值:'4208450740201411110007820472'
:param out_order_no: 商户分账单号,只能是数字、大小写字母_-|*@,示例值:'P20150806125346'
:param sub_mchid: 子商户的商户号,由微信支付生成并下发。示例值:'1900000109'
"""
if sub_... | cb1af072f2b4f94f632817baff6cdfea66110873 | 706,650 |
def get_controller_from_module(module, cname):
"""
Extract classes that inherit from BaseController
"""
if hasattr(module, '__controller__'):
controller_classname = module.__controller__
else:
controller_classname = cname[0].upper() + cname[1:].lower() + 'Controller'
controller_c... | b450105f6ec38a03fe461c5d9c07c4652da0efd3 | 706,651 |
def get_ogheader(blob, url=None):
"""extract Open Graph markup into a dict
The OG header section is delimited by a line of only `---`.
Note that the page title is not provided as Open Graph metadata if
the image metadata is not specified.
"""
found = False
ogheader = dict()
for line in... | 4edd7c5545ddef241ee2bfd5e316e47a336aaa3f | 706,652 |
import time
import os
def get_log_filename(log_directory, device_name, name_prefix=""):
"""Returns the full path of log filename using the information provided.
Args:
log_directory (path): to where the log file should be created.
device_name (str): to use in the log filename
name_prefix (str): ... | 48c0540c9717e54ab4389a2c9f6a5e31696c4595 | 706,653 |
import re
def condense_colors(svg):
"""Condense colors by using hexadecimal abbreviations where possible.
Consider using an abstract, general approach instead of hard-coding.
"""
svg = re.sub('#000000', '#000', svg)
svg = re.sub('#ff0000', '#f00', svg)
svg = re.sub('#00ff00', '#0f0', svg)
... | 413f1d7c69a52384fc21ee6f8eda6f2a63833e66 | 706,654 |
def rgb(r=0, g=0, b=0, mode='RGB'):
"""
Convert **r**, **g**, **b** values to a `string`.
:param r: red part
:param g: green part
:param b: blue part
:param string mode: ``'RGB | %'``
:rtype: string
========= =============================================================
mode ... | 563b8fe8273ce4534567687df01cebe79b9f58dc | 706,655 |
def load_csv_translations(fname, pfx=''):
"""
Load translations from a tab-delimited file. Add prefix
to the keys. Return a dictionary.
"""
translations = {}
with open(fname, 'r', encoding='utf-8-sig') as fIn:
for line in fIn:
line = line.strip('\r\n ')
if len(lin... | e8b4707fe5eeb0f0f4f4859bd9a5f2272387a022 | 706,656 |
def refines_constraints(storage, constraints):
"""
Determines whether with the storage as basis for the substitution map there is a substitution that can be performed
on the constraints, therefore refining them.
:param storage: The storage basis for the substitution map
:param constraints: The const... | de82087c41d95240ee9d15bd51810b7c5594ef0f | 706,657 |
def normalize(data, train_split):
""" Get the standard score of the data.
:param data: data set
:param train_split: number of training samples
:return: normalized data, mean, std
"""
mean = data[:train_split].mean(axis=0)
std = data[:train_split].std(axis=0)
return (data - mean) / std,... | cfc45ac5bd6ae7a30169253a1ae3ed64c1bd1118 | 706,659 |
def get_type_dict(kb_path, dstc2=False):
"""
Specifically, we augment the vocabulary with some special words, one for each of the KB entity types
For each type, the corresponding type word is added to the candidate representation if a word is found that appears
1) as a KB entity of that type,
""... | cd35054505c429cc1ad17eabe1cafb1aa6b38a1f | 706,660 |
def merge_dicts(iphonecontrollers, ipadcontrollers):
"""Add ipad controllers to the iphone controllers dict, but never overwrite a custom controller with None!"""
all_controllers = iphonecontrollers.copy()
for identifier, customclass in ipadcontrollers.items():
if all_controllers.get(identifier) is ... | 10638e775d6578e2553ff5b2b47aff8a17051c7e | 706,661 |
def perimRect(length,width):
"""
Compute perimiter of rectangle
>>> perimRect(2,3)
10
>>> perimRect(4, 2.5)
13.0
>>> perimRect(3, 3)
12
>>>
"""
return 2*(length+width) | 50fdd92430352f443d313d0931bab50ad5617622 | 706,662 |
def add_vary_callback_if_cookie(*varies):
"""Add vary: cookie header to all session responses.
Prevent downstream web serves to accidentally cache session set-cookie reponses,
potentially resulting to session leakage.
"""
def inner(request, response):
vary = set(response.vary if response.va... | ee7949f8c6ba1c11784b2c460e3c9dd962473412 | 706,665 |
def simple_list(li):
"""
takes in a list li
returns a sorted list without doubles
"""
return sorted(set(li)) | 1e36f15cea4be4b403f0a9795a2924c08b2cb262 | 706,666 |
import json
def write_json(object_list, metadata,num_frames, out_file = None):
"""
"""
classes = ["person","bicycle","car","motorbike","NA","bus","train","truck"]
# metadata = {
# "camera_id": camera_id,
# "start_time":start_time,
# "num_frames":num_frames,
# ... | 8b224af4edbd31570a432a8c551e95cd7a002818 | 706,667 |
import copy
def _clean_root(tool_xml):
"""XSD assumes macros have been expanded, so remove them."""
clean_tool_xml = copy.deepcopy(tool_xml)
to_remove = []
for macros_el in clean_tool_xml.getroot().findall("macros"):
to_remove.append(macros_el)
for macros_el in to_remove:
clean_too... | 9df0980265b26a2de1c88d2999f10cd5d1421e0b | 706,668 |
import json
import zlib
import base64
def convert_gz_json_type(value):
"""Provide an ArgumentParser type function to unmarshal a b64 gz JSON string.
"""
return json.loads(zlib.decompress(base64.b64decode(value))) | 1cf0300f40c8367b9129f230a7fef0c9b89ba012 | 706,669 |
import string
import random
def get_random_string(length: int) -> str:
"""
Returns a random string starting with a lower-case letter.
Later parts can contain numbers, lower- and uppercase letters.
Note: Random Seed should be set somewhere in the program!
:param length: How long the required strin... | 6cf20ce7d158ac158ffa49cac427c396cfd840db | 706,671 |
def factorial(n):
"""
Return n! - the factorial of n.
>>> factorial(1)
1
>>> factorial(0)
1
>>> factorial(3)
6
"""
if n<=0:
return 0
elif n==1:
return 1
else:
return n*factorial(n-1) | da5bc6f68375c7db03b7b2bdac1fec2b476ba563 | 706,672 |
def get_ffmpeg_folder():
# type: () -> str
"""
Returns the path to the folder containing the ffmpeg executable
:return:
"""
return 'C:/ffmpeg/bin' | 4708eec64ff56b72f7b1b9cc7f5ee7916f6310bd | 706,673 |
def create_bag_of_vocabulary_words():
"""
Form the array of words which can be conceived during the game.
This words are stored in hangman/vocabulary.txt
"""
words_array = []
file_object = open("./hangman/vocabulary.txt")
for line in file_object:
for word in line.split():
... | e3aadad2575e28b19b83158eb2127437c8aada89 | 706,674 |
def clean_cells(nb_node):
"""Delete any outputs and resets cell count."""
for cell in nb_node['cells']:
if 'code' == cell['cell_type']:
if 'outputs' in cell:
cell['outputs'] = []
if 'execution_count' in cell:
cell['execution_count'] = None
ret... | 67dce7ecc3590143730f943d3eb07ae7df9d8145 | 706,675 |
def test_f32(heavydb):
"""If UDF name ends with an underscore, expect strange behaviour. For
instance, defining
@heavydb('f32(f32)', 'f32(f64)')
def f32_(x): return x+4.5
the query `select f32_(0.0E0))` fails but not when defining
@heavydb('f32(f64)', 'f32(f32)')
def f32_(x): retu... | 157560cc90e3f869d84198eeb26896a76157eb39 | 706,676 |
def deprecated_func_docstring(foo=None):
"""DEPRECATED. Deprecated function."""
return foo | f9c996c4f3735ed2767f0bbb139b1494e2a0fa39 | 706,677 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.