content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import subprocess
def repo_fixture(tmpdir):
"""
repo/
├── .git/
├── bar/
│ └── bar.txt
└── foo/
└── foo.txt
"""
root = (tmpdir / "repo").mkdir()
with root.as_cwd():
subprocess.call(["git", "init", "-q"])
(root / "foo").mkdir()
(root / "foo" / "foo... | cff3bdfae2d82fce042c34a48f3dfdb6e023bae6 | 683,964 |
import importlib
def decode(source, decoder, *args, **kwargs):
"""
import and execute a file or string decoder on a certain class
"""
decoder = importlib.import_module("."+decoder,'pyodec.files')
return decoder.decoder.decode(source, *args, **kwargs) | 00da115734542ab0d9409921fc1cac6f39cd7979 | 683,965 |
def get_users_preferred_timezone(user, service):
"""
Determines the users preferred timezone by checking what timezone they use for their primary google calendar
:param user: Django User object for the user whose calendar is being accessed
:return: A string representation of the timezone:
- "E... | 3d5efdf3ad3bfe8acc68bf014d46e0fd83d492e5 | 683,967 |
import os
def get_filenames(filepath):
"""
Function used to get all of the file names in the specified directory.
Arguments:
filepath -- String specifying the root directory
Return:
dataFiles -- Dictionary with keys as file name and value as file path
"""
dataFiles = {}
... | 02ce075e4c4ee7010d38ed6d5f5210cf23338b6d | 683,968 |
def odd(number):
"""Returns `True` if `number` is odd. `False` otherwise.
:param number: number to check if it is odd.
"""
try:
int(number)
except:
return False
else:
return int(number) & 0x1 == 1 | cc4fa4547769e3bcb4ddcfecee0d504f90ba0551 | 683,969 |
def set_rollout_horizon(rollout_schedule, current_timesteps):
""" Linearly change the """
min_length, max_length, min_timesteps, max_timesteps = (rollout_schedule.min_length,
rollout_schedule.max_length,
... | 566af44f987b26dcda44045826ed0e53d32ccfc1 | 683,970 |
def split_string(command:str, character:str):
"""
Split incoming command on a character
args:
command: string that's the command.
character: the character on which the command should be split.
Returns:
Array with at least length 2 containing the split command.
"""
... | fba0813cd318ffe3729399d5c4c87934b688f881 | 683,972 |
def offset_stopword(rank, nb_lemmas_in_stopwords):
"""Offset word frequency rankings by a small amount to take into account the missing ranks from ignored stopwords"""
return max(1, rank - nb_lemmas_in_stopwords) | 322e00f8836efcfc4c10e26ca1a06325217118ce | 683,973 |
def compute_loss(criterion, outputs, labels, batch_size):
"""
Helper function to compute the loss. Since this is a pixel-wise
prediction task we need to reshape the output and ground truth
tensors into a 2D tensor before passing it in to the loss criterion.
Args:
criterion: pytorch loss criter... | 328053eefe13bcf54f374bd7ee6bbfb2d097c1b9 | 683,974 |
def poly_smooth(x: float, n: float = 3) -> float:
"""Polynomial easing of a variable in range [0, 1].
Args:
x (float): variable to be smoothed
n (float, optional): polynomial degree. Defaults to 3.
Returns:
float: _description_
"""
if x > 1:
return 1
if x < 0:
... | a97defff3ea2cadb5842dd014fea5d77d621407d | 683,975 |
import re
def del_tokens_len_one(text: str) -> str:
"""Delete tokens with length = 1.
This is kind of a basic stopword filtering.
"""
text = re.sub('(\s)\w(\s)',' ',text)
return text | 1d36830fc5fb5e7b4e5efb8e86135711f08a1ee2 | 683,976 |
from typing import Callable
from typing import Iterable
from typing import Tuple
from typing import List
def split(predicate: Callable, iterable: Iterable) -> Tuple[List, List]:
"""
Splits the iterable into two list depending on the result of predicate.
Parameters
----------
predicate: Callable
... | 50f65b7022c7beab456825f3da6806470610f9d9 | 683,977 |
import subprocess
def get_diff():
"""
Get git diff
:return:
>>> get_diff()
''
"""
cmd_str = 'git diff'
exitcode, diff_str = subprocess.getstatusoutput(cmd_str)
if exitcode != 0:
diff_str = ''
return diff_str | 0e7ae4bd94bba0595405df67b7910e4b8ade751e | 683,979 |
def merge_dicts(dict_list: list) -> dict:
"""
merging dicts from dict_list to one dict. If dicts from dict_list have same keys pass KeyError
"""
result: dict = {}
for d in dict_list:
if len(set(d.keys()) & set(result.keys())) > 0:
raise KeyError(rf'keys_consts have same keys: {se... | ce65fd42822d31f1a6107c35a1dff5b20dac4779 | 683,980 |
def segment_by_tag(sequences, tags):
"""Segment string sequence by it's tags.
Args:
sequences: A two dimension source string list
tags: A two dimension tag string list
Returns:
A list of segmented string.
"""
results = []
for seq, tag in zip(sequences, tags):
if... | c40ec3b8801f05f317fa2556dbc046421d583bb1 | 683,981 |
from typing import List
def _entity_report(entity_name: str, messages: List[str]) -> List[str]:
""" Serializes the messages of a given entity to the Report
It generates a list that translates as:
+ entity
+ message one
+ message two"""
return [f' + {entity_name}'] + [f' + {message}'... | 5eb7ad0a648054ec5ef5e126a95fda357fadead8 | 683,983 |
def make_preterminal(label, word):
"""returns a preterminal node with label for word"""
return [label, word] | ebf5858eb1704434a10524696ebdb73f72fbb982 | 683,984 |
import functools
def handle_errors(_func=None, *, error_callback=None, error_message=None, stacktrace=True):
"""
handle_errors(func)
handle errors using a callback function or show a message
"""
def decorator_handle_errors(func):
@functools.wraps(func)
def wrapper_handl... | e47f372652a99ba8ab050b767dd78dc13b8c82d5 | 683,985 |
from typing import List
from typing import Union
def insertion_sort(arr : List , simulation : bool = False) -> List:
""" Insertion Sort
Complexity: O(n^2)
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller th... | 3af5023714f125c091a54a5c5dfb53d48d978df3 | 683,986 |
def mon_append_ok(L, e):
""" list[alpha] * alpha -> list[alpha]
retourne la liste L avec l'élément e à la fin. """
return L + [e] | 6cc6c02c8cf0629e32a2239679bc6bfc28226021 | 683,987 |
def isVariable(name, dataset):
"""
Determines if given string is an existing variable name for a variable in dataset.
This helper function returns True if the given name is a valid name of a variable
in the Tecplot file, False otherwise.
Arguments:
name -- the string that we are testin... | 764f357b71c120e72290a38f54ad639ebed5cc3f | 683,988 |
def fgrep(text, term, window=25, with_idx=False, reverse=False):
"""Search a string for a given term. If found, print it with some context.
Similar to `grep -C 1 term text`. `fgrep` is short for faux grep.
Parameters
----------
text: str
Text to search.
term: str
Term to look fo... | 8c8cc20ba6cfeba6006671e1b160a740179ef0ce | 683,989 |
def last_mentioned():
"""
Method reads csv file to keep track of last mentioned, in order to search from this value onwards for new mentions.
:return: Returns Latest mentioned user ID.
"""
with open('last_mentioned.csv', 'r') as f:
data = f.read()
data = data.split('\n')
return d... | 6b4bce6481a0572f0824881b677a7bcd69d733e6 | 683,990 |
def matrix_to_string(
matrix, row_headers=None, col_headers=None, fmtfun=lambda x: str(int(x))
):
"""Takes a 2D matrix (as nested list) and returns a string.
Parameters
----------
matrix :
row_headers :
(Default value = None)
col_headers :
(Default value = None)
fmtfu... | e35c6bc61e9e14965407f5ed5a9fe5f52953f64d | 683,991 |
import re
def fix_gitlab_links(base_url, text):
"""
Fixes gitlab upload links that are relative and makes them absolute
"""
matches = re.findall('(\[[^]]*\]\s*\((/[^)]+)\))', text)
for (replace_string, link) in matches:
new_string = replace_string.replace(link, base_url + link)
t... | 2a101b899ed8d02d725539faf773ddd2ada6daea | 683,992 |
def get_objlist(*, galaxy_catalog, survey, star_catalog=None, noise=None):
"""
get the objlist and shifts, possibly combining the galaxy catalog
with a star catalog
Parameters
----------
galaxy_catalog: catalog
e.g. WLDeblendGalaxyCatalog
survey: descwl Survey
For the approp... | b71f8fcbebc9fa2aba00e92848882669d658b275 | 683,993 |
def ClassFactory(base, extend, fixPrivateAttrs=True):
""" Возвращает новый класс, являющийся суб-классом от `base` и цепочки `extend`. """
extend=(base,)+tuple(extend) if extend else ()
name='_'.join(cls.__name__ for cls in extend)
extend=tuple(reversed(extend))
attrs={}
if fixPrivateAttrs:
# фи... | 2b9ef1ee1742e53516bf2169d293bb147c97857a | 683,994 |
import math
def tax_rec(income):
"""
A more advanced implementation that uses recursion
"""
payable = 0
if income > 40000:
payable = 0.4 * (income - 40000) + tax_rec(40000)
elif income > 10000:
payable = 0.2 * (income - 10000)
return math.floor(payable) | 6a03a29e4831db187a9f0551cc8d1d6bab68bbb1 | 683,995 |
import json
def load_json(filepath):
"""load params, whicch is stored in json format.
Args:
filepath (str): filepath to save args
Returns (dict or list): params
"""
with open(filepath, 'r') as f:
params = json.load(f)
return params | 9c28fbf4a708c87869617aebc16018779d577c20 | 683,996 |
import os
import re
def get_relative_path(base_folder, folder, filename):
"""
Return the relative path based on a base folder.
:param str base_folder: base folder calculate the relative path from.
:param str folder: The folder where the file is saved.
:param str filnemane: Filename of the file
... | 9825a5f822601c178e21c619236e955716201b36 | 683,998 |
import re
def clean_newline(text: str) -> str:
"""Filter newlines.
Arguments:
text:
The text to be filtered.
Returns:
The filtered text.
"""
return re.sub("\n", "", text) | c229f59fe862b4120653f6df7c7dd8c20ab8090b | 683,999 |
import copy
def thrift_to_dict(thrift_inst, update_func=None):
"""convert thrift instance into a dict in strings
:param thrift_inst: a thrift instance
:param update_func: transformation function to update dict value of
thrift object. It is optional.
:return dict: dict with at... | 9fd9febdbb0752e4bf6b7696d84fc074369d7406 | 684,000 |
def subclasstree(cls):
"""Return dictionary whose first key is the class and whose
value is a dict mapping each of its subclasses to their
subclass trees recursively.
"""
classtree = {cls: {}}
for subclass in type.__subclasses__(cls): # long version allows type
classtree[cls].update(sub... | 0c2b9cb05c1f97a92266dd15fb905e54a2588f5a | 684,001 |
def generateAngles(molecule, bonds):
"""
Generate angles form the bonds list
Parameters
----------
molecule : RDkit molecule
RDkit molecule
bonds : list
Bonds index list
Returns
-------
angles : list
Index angles atoms list
"""
angles = []
for ... | 4c460a55cf6fb82bd6c1c5be460bdb840a20f47a | 684,002 |
def sum_reduce(iter, params):
"""
Sums the values for each key.
This is a convenience function for performing a basic sum in the reduce.
"""
buf = {}
for key, value in iter:
buf[key] = buf.get(key, 0) + value
return buf.items() | f848ea3c37778a63ad7b96bd489afd8b0112ba80 | 684,003 |
def _totalUniqueWords(dataset, index):
"""
Given a dataset, compute the total number of unique words at the given index.
GIVEN:
dataset (list) list of lists, where each sublist is a document
index (int) index in dataset to count unique words
RETURN:
unique_words (int... | 25b834edd233e6c2f2c78f8f51e3baf08ab963d2 | 684,004 |
from typing import Dict
from typing import List
def get_parents(class_name: str, parent_mapping: Dict[str, List[str]]) -> List[str]:
"""
Recursively resolve all parents (ancestry) of class_name
:param class_name: class to resolve
:param parent_mapping: mapping of class_name -> parents
:return: Lis... | c7d4f757274e92fce06438047da35480f07eee94 | 684,005 |
import re
def matching(value, pattern, casesensitive=True):
"""
Filter that performs a regex match
:param value: Input source
:type value: str
:param pattern: Regex Pattern to be matched
:return: True if matches. False otherwise
:rtype: bool
"""
flags = re.I if not casesensitive e... | 2a54309730cd320e39d69db30a13e8cfead0524b | 684,007 |
def collate_fn(batch):
"""Pack batch"""
return tuple(batch) | f5bf743106933194440b0c35fe7c7c3d570cc468 | 684,008 |
import six
def get_members(group):
"""Get a list of member resources managed by the specified group.
Sort the list of instances first by created_time then by name.
"""
resources = []
if group.nested():
resources = [r for r in six.itervalues(group.nested())
if r.status... | a4925f1597faa3b149d60ae0f1b293a331a3fbd0 | 684,009 |
import random
def random_char():
"""
Random human-readable char
"""
return chr(random.randint(32, 126)) | 7d1d86aed7e41640b7eece97b766c08ce3512f55 | 684,010 |
def get_albums(tracks):
"""
Returns a dict where:
key: album_id
value: list of track ids
"""
albums = {}
for _,row in tracks.iterrows():
album = row['album'][1:-1]
if album != '' and album != 'None':
if album in albums:
albums[a... | b4d56f1f75574b58f121d65e92a2e25d0febb2ec | 684,011 |
def cat(*args):
"""
Flatten lists and concatenate strings in them.
"""
return "\n".join(type(arg) == list and cat(*arg) or str(arg) for arg in args) | 70afd77d73c93abfa4c4613c974370b4e5ae2659 | 684,012 |
import re
def has_spdx_text_in_analysed_file(scanned_file_content):
"""Returns true if the file analysed by ScanCode contains SPDX identifier."""
return bool(re.findall("SPDX-License-Identifier:?", scanned_file_content)) | 2987ae45598bf911fbd85eddfec639d82aadcbe5 | 684,013 |
def clamp_tensor(tensor, minimum, maximum):
"""
Supports sparse and dense tensors.
Returns a tensor with values clamped between the provided minimum and maximum,
without modifying the original tensor.
"""
if tensor.is_sparse:
coalesced_tensor = tensor.coalesce()
coalesced_tensor... | fe0c1c3b4fcc7ec057354e8cbf9cfdd58a514752 | 684,014 |
def _set_power_cap_callback(cb):
""" Manage the command line options """
def _cb(ctx, param, value):
nids = []
for x in value:
# Handle nid ranges here
nids = [int(m.strip()) for m in x.split(',')]
if cb:
return cb(ctx, param, nids)
return nids... | 50bd1e6485ca8330d55138a4804bc95d0ac98ae4 | 684,015 |
def rreplace(a, b, string):
""" Replaces the tail of the string.
"""
if string.endswith(a):
return string[:len(string)-len(a)] + b
return string | 5a1525c9603625e2bdd8a83e80b77e1a36deb9f1 | 684,016 |
def extract_picard_stats(path):
"""
Extract relevant information from picard wgs or size stats file.
This is assumed to be for a single sample and that there will only be
two lines in the "METRICS CLASS" section, which is the only section we'll
extract.
No effort is made to convert strings to nu... | 8e8cec2b05a97817ece098635b875081a4fd89c8 | 684,017 |
def canAcceptVassal(masterTeam, vassalTeam, bAtWar):
"""
Returns True if <vassalTeam> can become a vassal of <masterTeam>.
Pass True for <bAtWar> to test for capitulation and False to test for peaceful vassalage.
"""
if masterTeam.getID() == vassalTeam.getID():
return False
if masterTeam.isAVassal() or vassal... | 11b19e0b533608c971f01eff9615499485bf779a | 684,018 |
def unpack_bytes(word):
"""Unpacks a 32 bit word into 4 signed byte length values."""
def as_8bit_signed(val):
val = val & 0xff
return val if val < 128 else val - 256
return (as_8bit_signed(word),
as_8bit_signed(word >> 8),
as_8bit_signed(word >> 16),
as_8... | dc00ff14bebcc72f90511fdfe641086674a3245f | 684,019 |
import signal
def suspend_to_background_supported():
"""
Returns `True` when the Python implementation supports
suspend-to-background. This is typically `False' on Windows systems.
"""
return hasattr(signal, 'SIGTSTP') | 5d6bca4b0008ec6e7769fb86c812fa70b77f60e5 | 684,021 |
def lowerBound(sortedCollection, item, key=lambda x: x):
"""
Given a sorted collection, perform binary search to find element x for which
the following holds: item > key(x) and the value key(x) is the largest.
Returns index of such an element.
"""
lo = 0
hi = len(sortedCollection)
while ... | f74b44492180953c434e03a0b832444a7775fc52 | 684,023 |
import torch
def get_topk_class(probability, top_k):
"""
select top k class according probability for multi-label classification
:param probability: Tensor of (batch_size, class_size), probability
:param topk: int, number of selected classes
:returns: Tensor of long (batch_size, cl... | 21b6fda6f1704f9d3c324c51b6dd48a297f1b834 | 684,024 |
def gt_pseudophase(g):
"""
Return pseudophased genotype call.
Parameters
----------
g : str
Genotype call.
Returns
-------
str
Pseudophased genotype call.
Examples
--------
>>> from fuc import pyvcf
>>> pyvcf.pseudophase('0/1')
'0|1'
>>> pyvcf.... | de5478d09fa3f9955f48a5a6af5187b315431871 | 684,025 |
def get_users(user_file_path):
"""read usernames from file."""
user_file = open(user_file_path)
users = user_file.readlines()
user_file.close()
return users | ca98a42685d59f8d44f4b30139a0c1d4ac86c76e | 684,026 |
def transform( event, settings ):
"""
Takes a pipeline event and transforms it to pipeline event containing
an array of payloads
"""
adapters = settings.adapters()
payloads = []
for index in range( 0, len( adapters ) ):
outputter = settings.outputters[ index ]
if not output... | cbec1b2d684531a0ec98496e9875589b730b7c29 | 684,027 |
def esc_seq(n, s):
"""Escape sequence. Call sys.stdout.write() to apply."""
return '\033]{};{}\007'.format(n, s) | 10b9f83960e395103be12a213556db77b63d2d89 | 684,028 |
def patch_stdin_stdout(stdin, stdout):
"""Patch sys.stdout.write to ensure proper encoding."""
write_orig = stdout.write
read_orig = stdin.readline
async def decode_read():
"""Decode the input line."""
line = await read_orig()
return line.decode("UTF-8")
def encode_write(li... | 8fa9a92b9a3796925ee3492466fe494f4b8d4c6a | 684,029 |
def _strip_predicate(s):
"""Remove quotes and _rel suffix from predicate *s*"""
if s.startswith('"') and s.endswith('"'):
s = s[1:-1]
elif s.startswith("'"):
s = s[1:]
if s[-4:].lower() == '_rel':
s = s[:-4]
return s | a3f2399ada296d69612f8403d5cfce8b2cc91c80 | 684,030 |
def get_first_peak_dist(ds):
"""
the peak closest to satellite from GLAH14
"""
# closet to satellite = smallest distance
return ds.gaussian_fit_dist.min(dim="n_gaussian_peaks") | 8b67e8e10b21f63eb98920cb370cd495ac88b80f | 684,031 |
import math
def cosine_annealing_lr(
iteration: int,
num_iterations: int,
initial_lr: float,
final_lr: float,
):
"""
Cosine annealing NO restarts
Args:
iteration: current iteration
num_iterations: total number of iterations of coine lr
initial_lr: learning rate to ... | 40a69f2a6495afe6e49447065993f16d19eb42b2 | 684,032 |
def loadObject(name):
"""Load and return the object referenced by <name> ==
some.module[:some.attr].
"""
module, attrs = name.split(':')
attrs = attrs.split('.')
obj = __import__(module, globals(), globals(), ['__name__'])
for attr in attrs:
obj = getattr(obj, attr)
return obj | 2709b159d414d1baebbadd11fc5afc80cd074b53 | 684,033 |
import sys
def _processFixPythonInterpreter(aPositionalArgs, dKeywordArgs):
"""
If the "executable" is a python script, insert the python interpreter at
the head of the argument list so that it will work on systems which doesn't
support hash-bang scripts.
"""
asArgs = dKeywordArgs.get('args')... | 7fc38914f11805da40349258c2a3f7b673fb47f5 | 684,034 |
def get_deaths(j):
""" Get names from json response """
return [i['text'].split(',')[0] for i in j['data']['Deaths']] | 295b7072ecb3c373c7058fb01658d9a1308d7127 | 684,036 |
from typing import Union
def expand_fine_modality_questions(
answer: str, matched_word: str, modality: Union[None, str]
):
"""Create new questions for fine modality task with given information.
Args:
answer: Original answer to the question
matched_word: The keyword which labeled the origi... | 485f989103847f1bd0ae233bb8132544f15dc820 | 684,037 |
def add(x, y):
"""Add funtion"""
return x + y | b5e2e4d1036b0b94614d8d887be9f27c40ee3ec5 | 684,038 |
import re
def tex(s_data):
"""Purify (La)TeX input."""
def _strip_comment(text_data):
index = text_data.find("%")
if index == -1:
return text_data
return text_data[:index]
pattern = re.compile(r"(\\\w+)")
def _strip_commands(text_data):
def _replace_fn(mat... | d844d814a110f2bf91c0dbbd4a9ed08654cac496 | 684,039 |
def _parse_volumes_param(volumes):
"""Parse volumes details for Docker containers from blueprint
Takes in a list of dicts that contains Docker volume info and
transforms them into docker-py compliant (unflattened) data structures.
Look for the `volumes` parameters under the `run` method on
[this pa... | cf5e608bdb44583e320d9f3928283504e80b9647 | 684,040 |
from typing import Dict
from typing import Optional
def role_has_tag(role: Dict, key: str, value: Optional[str] = None) -> bool:
"""
Checks a role dictionary and determine of the role has the specified tag. If `value` is passed,
This function will only return true if the tag's value matches the `value` va... | 086410b2c8fbf4b2fb0d5be44d9a5196181a4e6d | 684,041 |
import tempfile
def get_tempdir():
"""
Gets the current tempdir for the module.
"""
return tempfile.gettempdir() | fd6342597a81bde85aeda0fe9c16623e8b980cb6 | 684,042 |
def get_datasets(datasets=''):
"""Gets the list of dataset names.
Args:
datasets: A string of comma separated dataset names.
Returns:
A list of dataset names.
"""
return [d.strip() for d in datasets.split(',')] | a0b520348978de25df2bfdefd123200a2f3d1145 | 684,043 |
import functools
def synchronized(obj):
"""
This function has two purposes:
1. Decorate a function that automatically synchronizes access to the object
passed as the first argument (usually `self`, for member methods)
2. Synchronize access to the object, used in a `with`-statement.
Note that you can ... | 29622cbef04c0da4a6e4921898d6c3f818888de0 | 684,044 |
import logging
def _set_root_logger(loglevel=logging.INFO):
""" Setup the root logger.
Parameters
----------
loglevel: int, optional
The log level to set the root logger to. Default :attr:`logging.INFO`
Returns
-------
:class:`logging.Logger`
The root logger for Faceswap
... | bc4d36685d271500fcda7a3743790976a6aa2f6a | 684,045 |
def _recurse_binary_exponentiation(num, power):
"""
Recursively calculate num**power quickly (via binary exponentiation).
Helper function. We did parameter checks before so that we don't have to
do them inside every recursive call.
"""
if power == 1:
return num
num_squared = n... | 96e2e95952c84078bcb211229496eb348110f720 | 684,046 |
def lower_columns(data, categorical_columns):
""" import dataset and lower columns name
Args:
data: pd.Dataframe
Returns:
data_lower: pd.Dataframe
"""
data.columns = map(str.lower, data.columns)
data[categorical_columns] = data[categorical_columns].apply(lambda x: x.str.lower())... | d6024e67ec75c6c976f95170eca8c171c4eb0595 | 684,048 |
def get_centroids(km):
"""km: K-Means model object
"""
# The cluster each point or observation belongs to
cluster_labels = km.labels_
# The means of the points in each cluster (centroids)
centroids = km.cluster_centers_
return cluster_labels, centroids | 57a2be9a93ab1b26fc5826d1bc8b8eb324a2fe60 | 684,049 |
from datetime import datetime
def today(tz=None) -> datetime:
"""get datetime of today (no time info)"""
now = datetime.now(tz)
return datetime(year=now.year, month=now.month, day=now.day) | e8e921c74c92e17ffdbdc029c04905072ada7687 | 684,050 |
import os
def getScriptname():
""" Return the scriptname part of the URL ("/path/to/my.cgi"). """
return os.environ.get('SCRIPT_NAME', '') | 3a2e3dbe9a4e2f2181913c5950370f6b8f3d7fe3 | 684,051 |
def _GetGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.healthChecks, 'Get',
client.messages.ComputeHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project... | b81e33e663c8939831ca055fcf143e1d9d1ab96c | 684,052 |
import six
def exact_filter(query, model, filters):
"""Applies exact match filtering to a query.
Returns the updated query. Modifies filters argument to remove
filters consumed.
:param query: query to apply filters to
:param model: model object the query applies to, for IN-style
... | b02748c0b46dfd03eca9de65d08ebace57baa8a2 | 684,053 |
def filter_dose_by_individual_species(doses, species):
"""Filter out relevent doses by the species name
If it does find doses with the specific species name, it returns a list of these.
If it doesn't find any doses with the specific species name, it returns None.
:param doses: A list of dose objects
... | 125e0dbfe9f9a81ff6597c8e7db932dfb8b3d209 | 684,054 |
def smooth(reading, factor, previous):
"""
apply smoothing function
::
smoothed = k*raw + (1-k)*previous
"""
if previous is None:
value = reading
else:
value = factor * previous + (1 - factor) * reading
return value | 78500996821a576287e38311804b889f28cdeea6 | 684,056 |
import math
def get_len_in_bytes(value: int) -> int:
"""
Returns minimum length in bytes to dump integer number
"""
return math.ceil(len("{0:0x}".format(value)) / 2) | 533b3b4edbe97efe703a6ad69cd52f86e8bd335d | 684,057 |
def get_key_lst_by_value(aim_value, data_dct: dict) -> list:
"""根据字典value值获取key值"""
key_lst = []
for key, value in data_dct.items():
if value == aim_value:
key_lst.append(key)
return key_lst | 81343651efde44af9007e1632926ae63c321a835 | 684,058 |
def coef(name, value, idx=0):
"""
Return a dict that represents a new coefficient.
:param name : int or sequence of int, optional, default: 1
Shape of the new notation, e.g., ``(2, 3)`` or ``2``.
:param value : number, vector with the same shape as `shape`, optional, default: None
The u... | 68cc5b2058e9662c19f58b02994cb108a97c7048 | 684,059 |
def check_bit(val, n):
""" Returns the value of the n-th (0 index) bit in given number """
try:
if val & 2**n:
return 1
else:
return 0
except TypeError:
return -1 | 1c889ce569a4d5ed4236cb95c8ad700ad1aa4c20 | 684,060 |
def check_legacy_headers(headers, legacy_headers):
"""Gather values from old headers."""
for legacy_header in legacy_headers:
try:
value = headers[legacy_header.lower()]
return value.split(',')[-1].strip()
except KeyError:
pass
return None | 5c1e81911a70857a1bdd5c123934dc34f974a38d | 684,062 |
def getAccurateFocalLengths(imageSize, focalLength, sensorSize):
"""
Parameters: image size x,y (pixels), focalLength (mili meters), sensorSize x,y (meters)
Focal length listed on the image exif is unitless...
We need focal length in pixels / meters.
Therefore, we scale the exif focal length b... | 8dd408e9c4a5ce9df4d1c6c440484310d86c4089 | 684,063 |
import base64
def base_64_encode(key, secret):
"""encodes key and secret in base 64 for the auth credential"""
conversion_string = "{}:{}".format(key, secret).encode('ascii')
auth_credential = base64.b64encode(conversion_string)
auth_credential = auth_credential.decode()
return auth_credential | cf75ebc44e4232715029e3d0315d6609436d8bb6 | 684,064 |
from pathlib import Path
def get_or_create_path(path_string, parents=True):
""" Get path object from string, create if non-existing"""
p = Path(path_string)
if not p.exists():
p.mkdir(parents=parents)
return p | fbfaccb60374fbbb67d7ae3ee242d455d2e3863c | 684,065 |
from typing import Counter
def bleu_stats(hypothesis, reference):
"""Compute statistics for BLEU."""
stats = []
stats.append(len(hypothesis))
stats.append(len(reference))
for n in range(1, 5):
s_ngrams = Counter(
[tuple(hypothesis[i:i + n]) for i in range(len(hypothesis) + 1 - ... | 6fc1e6fb52731b628fe69b2c26b7f2490da00e6a | 684,066 |
import argparse
import math
def get_regression_parser():
"""Return ArgumentParser object for regression."""
parser = argparse.ArgumentParser(add_help=False)
# Important/mandatory arguments
parser.add_argument(
"--target", type=str, required=True, help="Protein target to fit to."
)
par... | 1c0f9ab93acc9d4826a5bf028c5cea522908e294 | 684,068 |
def no_duplicates(seq):
""" Remove all duplicates from a sequence and preserve its order """
# source: https://www.peterbe.com/plog/uniqifiers-benchmark
# Author: Dave Kirby
# Order preserving
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)] | 47596bb28bf4634ff9c76a8b50f76e4301960447 | 684,069 |
def evaluate(prize, init_choice, change_choice):
"""
计算两种情况下的获奖概率
"""
init_win = sum(prize == init_choice)
change_win = sum(prize == change_choice)
return init_win, change_win | 9ced1dae7ca86ff3a929741792e8937741f3ceac | 684,070 |
def get_us_states():
"""Provides a list of all US states
Returns
-------
[list]
[Return all United States in a list]
"""
raw_states = """
Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Haw... | 8230cedee90efac7334bae37be26d4c82c11dad0 | 684,071 |
import os
import stat
def is_hard_link(filename):
"""Check if hardlink"""
file_stat = os.stat(filename)
if not stat.S_ISLNK(file_stat.st_mode):
return False
linkname = os.path.realpath(filename)
link_file_stat = os.stat(linkname)
return file_stat[stat.ST_DEV] == link_file_stat[stat.ST_... | 119d5151c12bb740268ccbe9e688a596816eadd0 | 684,072 |
import os
def abspath(*path):
"""A method to determine absolute path for a given relative path to the
directory where this .py script is located"""
this_dir = os.path.dirname(os.path.abspath(__file__))
return os.path.abspath(os.path.join(this_dir, *path)) | 5cf612daa16d1913e77d55d2450e3fde33f71a07 | 684,073 |
import secrets
def draft_conv_key() -> str:
"""
Create reference for a draft conversation.
"""
return secrets.token_hex(10) | 03d8b9c5dbc8530c25ee7b9d86bbcb185ad0d87a | 684,074 |
def area_triangle(length, breadth):
"""
Calculate the area of a triangle
>>> area_triangle(10,10)
50.0
"""
return 1 / 2 * length * breadth | 0916438810421d1890aaf92d417d05037884bd65 | 684,075 |
def _errmsg(argname, ltd, errmsgExtra=''):
"""Construct an error message.
argname, string, the argument name.
ltd, string, description of the legal types.
errmsgExtra, string, text to append to error mssage.
Returns: string, the error message.
"""
if errmsgExtra:
errmsgExtra = '\n' ... | de4072600a2624fa4ce0d4c213bc60d822143c41 | 684,076 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.