content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def remove_redundant_characters(str, char1, char2):
"""
remove substrings before and after two characters
exmaple:
input: '12@[123]57'. '[',']'
output: '[123]'
"""
left_index = str.find(char1)
right_index = str.find(char2)
result = str[left_index: (right_index +1)]
return result | 7e7dc284cd1ee4b8709bdc76b6ac864fb0dead8f | 698,513 |
def double(number):
"""
This function returns twice the value of a given number
"""
return number * 2 | 65a4bb13ecb45b37f0349f4be2f834f2fd23f813 | 698,514 |
def fund_nav_df_fillna(fund_nav_df):
"""
为 fund_nav_df 补充nav数据并记录错误日志
:param fund_nav_df:
:return:
"""
fund_nav_df.dropna(subset=['nav'], inplace=True)
fund_nav_df['nav_acc'] = fund_nav_df[['nav', 'nav_acc']].fillna(method='ffill', axis=1)['nav_acc']
return fund_nav_df | b61fdf7986c782a831bb9c97c190e161210ff925 | 698,515 |
def eliminate_duplicates(duplicated_iterable):
"""
对于包含重复元素且基于数组(可以通过下标访问)的可迭代对象,清除其重复元素并保持原顺序不变
@日期: 过去的某个时刻
@作者: 徐嘉辉
Args:
duplicated_iterable: 包含重复元素且基于数组(可以通过下标访问)的可迭代对象
Returns:
返回一个保持了原来元素顺序且去重完毕的列表
"""
return sorted(set(duplicated_iterable), key=duplicated_iterab... | ca86f37050ed6b1830c952bd76f5ac57a76eb149 | 698,516 |
def unique_dict_in_list(array):
"""Returns the unique dictionaries in the input list,
preserving the original order. Replaces ``unique_elements_in_list``
because `dict` is not hashable.
Parameters
----------
array: `List` [`dict`]
List of dictionaries.
Returns
-------
uniqu... | ef18d64c4a896321d57f984c0ede3e0e897c59f5 | 698,517 |
def merge(prevArtifacts, nextArtifacts):
"""Merge artifact lists with nextArtifacts masking prevArtifacts"""
artifactList = list(nextArtifacts.copy())
artifactList.extend(prevArtifacts)
merged = []
excludedNames = set()
for artifact in artifactList:
if artifact.name not in excludedName... | 089aaf140111b08a98e64118fde8f8a4fd413982 | 698,518 |
import os
def getpyfile(filename, split=os.path.splitext, exists=os.path.exists):
"""Return the .py file for a filename.
Resolves things like .pyo and .pyc files to the original .py. If *filename*
doesn't have a .py extension, it will be returned as-is.
:param filename: the path to a file.
:para... | fe004fd9f9d635a4c6538df1cc7fd48517e3d975 | 698,519 |
import argparse
def parse_arguments():
""" Must specify a directory path, a Clowder url and a service key"""
parser = argparse.ArgumentParser(description='Upload nested folders to clowder')
parser.add_argument('--path', required=True)
parser.add_argument('--host', required=True)
parser.add_argumen... | 5f2cd0a16ca5d9566dee67f42e1d99e58d8197b8 | 698,521 |
def circularArrayLoop( nums):
"""
:type nums: List[int]
:rtype: bool
"""
def move(i):
res = (i+nums[i])%len(nums)
return res
slow = move(0)
fast = move(slow)
while slow != fast:
slow = move(slow)
fast = move(move(fast))
fast = move(slow)
if fast ==... | bb25883c698abd0b7d9183799e9c4c866d342409 | 698,522 |
def _clean_str(value, strip_whitespace=True):
"""
Remove null values and whitespace, return a str
This fn is used in two places: in SACTrace.read, to sanitize strings for
SACTrace, and in sac_to_obspy_header, to sanitize strings for making a
Trace that the user may have manually added.
"""
... | 41b9f0a1388045b86d019464512a0253eb5d6523 | 698,523 |
import random
def createRandomGraph():
"""Creates a digraph with 7 randomly chosen integer nodes from 0 to 9 and
randomly chosen directed edges (between 10 and 20 edges)
"""
g = {}
n = random.sample([0,1,2,3,4,5,6,7,8,9], 7)
for i in n:
g[i] = []
edges = random.randint(10,20)
c... | e2ca213a594ad03c5df7a3231e7d246fe7fcb416 | 698,524 |
def ini_elec_levels(spc_dct_i, spc_info):
""" get initial elec levels
"""
if 'elec_levels' in spc_dct_i:
elec_levels = spc_dct_i['elec_levels']
else:
elec_levels = [[0., spc_info[2]]]
return elec_levels | 95a55a90c95466b2288799e4e24b3250c3afdd84 | 698,525 |
def check_for_factor(base, factor):
"""
This function should test if the
factor is a factor of base.
Factors are numbers you can multiply
together to get another number.
Return true if it is a factor or
false if it is not.
:param base:
:param factor:
:return:
"""
retur... | 6d20a7d2e2ec459e8307007adb332507d0078118 | 698,526 |
def has_access(user, users):
"""A list of users should look as follows: ['!deny', 'user1',
'user2'] This means that user1 and user2 have deny access. If we
have something longer such as ['!deny', 'user1', '!allow',
'user2'] then user2 has access but user1 does not have access. If
no keywords are fou... | 07d3f47cf3725002023d8c9e487e14280dabc2bf | 698,528 |
import subprocess
def check_dfs():
"""
This function checks if the dfs is running
"""
process = subprocess.Popen("jps", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = process.communicate()
results = str(stdout)
flag = 0
if results.find("NameNode") > -1:
... | 6f82750992a5b30322b8c1de12b94b44f7257efb | 698,529 |
def by_cities(sdat):
"""
this function determines from how often people fly from every city
:return: int[from moscow; from st pet.]
"""
borm = sdat.groupby(["Город вылета"]).size()
cities = []
for i in borm:
cities.append(i)
return cities | d5e438ea7f9d298ff879df479f250342cc02eff1 | 698,530 |
def isVowel(letter):
"""
isVowel checks whether a given letter is a vowel. For purposes of this
function, treat y as always a vowel, w never as a vowel.
letter should be a string containing a single letter
return "error" if the value of the parameter is not a single letter string,
return True, if the... | 5ba6917c80c4679a59580b8f3a05513d0904cd63 | 698,531 |
def fn_winkler(weight_jaro, pre_matches, pre_scale):
"""
Scale the standard Jaro metric by 'pre_scale' units per 'pre_matches'.
Note the warning in the docstring of jaro_winkler() regarding the scale.
"""
weight_jaro += pre_matches * pre_scale * (1.0 - weight_jaro)
assert weight_jaro <= 1.0
... | c938b932038e5344c19847555b70545d239cbb5a | 698,532 |
def isCCW(ring):
"""
Determines if a LinearRing is oriented counter-clockwise or not
"""
area = 0.0
for i in range(0,len(ring)-1):
p1 = ring[i]
p2 = ring[i+1]
area += (p1[1] * p2[0]) - (p1[0] * p2[1])
if area > 0:
return False
else:
return True | ef7b3ad88a3a5926896ab1c627b65f2e4e4dc47f | 698,533 |
def get_grant_key(grant_statement):
"""
Create the key from the grant statement.
The key will be used as the dictionnary key.
:param grant_statement: The grant statement
:return: The key
"""
splitted_statement = grant_statement.split()
grant_privilege = splitted_statement[1]
if "."... | 200b77d0988090628e013463bba5fe395dd76c00 | 698,534 |
def get_timediff(dataset,
start_time,
end_time):
"""
Usage: [arg1]:[Pandas DataFrame],[arg2]:[column-start_time],[arg3]:[column-end_time]
Returns: DataFrame with additional column [Duration in seconds]
"""
dataset['secs_diff_' + start_time + '_' + end_time] = (datas... | 8fff531201953cd637027c0b6ac76e9ae45dc380 | 698,535 |
def invert(d):
"""Dict of lists -> list of dicts."""
if d:
return [dict(zip(d, i)) for i in zip(*d.values())] | 1ac60d7c294e159836be3f6c83817ad7de4f7125 | 698,536 |
def get_format_style(deck) -> str:
""" Возвращает соответствующий класс стиля формата колоды """
matching = {0: 'unknown',
1: 'wild',
2: 'standard',
3: 'classic'}
return matching[deck.deck_format.numerical_designation] | 79fd7febf913deb684c5499768cdb11621952a6e | 698,537 |
def custom_filter(image):
"""
Allows the user to modify the image by multiplying each of the RGB values of each pixel by their input number.
"""
red_constant = float(input ("Multiply the R value of each pixel by: "))
green_constant = float(input ("Multiply the G value of each pixel by: "))
blue... | c1a23f13f7d5cdf49b7c9a4c1b9a84fa4cb56051 | 698,538 |
import json
def unpack_msrest_error(e):
"""Obtains full response text from an msrest error"""
op_err = None
try:
op_err = json.loads(e.response.text)
except (ValueError, TypeError):
op_err = e.response.text
if not op_err:
return str(e)
return op_err | f55b08443b0f97f967de837732159b82fd8b5a60 | 698,539 |
from datetime import datetime
def datetime_str_to_datetime(datetime_str):
"""
This converts the strings generated when matlab datetimes are written to a table to python datetime objects
"""
if len(datetime_str) == 24: # Check for milliseconds
return datetime.strptime(datetime_str, '%d-%b-%Y %H... | 84960880bccfb21bdb2dc1a15b0bd09ef358187c | 698,540 |
def mangle(prefix, name):
"""Make a unique identifier from the prefix and the name. The name
is allowed to start with $."""
if name.startswith('$'):
return '%sinternal_%s' % (prefix, name[1:])
else:
return '%s_%s' % (prefix, name) | 6d949e61a87c6667fdfb262376e476aea64bde4b | 698,541 |
def de_normalize_minmax(x_scale, x, min_r, max_r):
""" Transforms a min-max normalized and
scaled vector back to its un-normalized
form.
"""
x_t = [((i - min_r)/(max_r - min_r)) for i in x_scale]
x_inv = [(i*(max(x) - min(x)) + min(x)) for i in x_t]
return x_inv | d1a2bd2740552eae2c4bc0b94f2093de7ed03b70 | 698,542 |
import torch
def update_ntk_inv(ntk, ntk_inv, keep_indices):
""" A little bit faster implementation. Uses the fact that ntk is a symmetric matrix. """
S = set(keep_indices)
remove_indices = [i for i in range(ntk.shape[0]) if i not in S]
A12 = ntk[keep_indices][:, remove_indices]
A22 = ntk[remove_... | 26b62e0c1bca79643930ee822f34cfdd74e977fd | 698,543 |
import subprocess
import sys
def shell_cmd(cmd, alert_on_failure=True):
"""Execute shell command and return (ret-code, stdout, stderr)."""
print('SHELL > {}'.format(cmd))
proc = subprocess.Popen(cmd, shell=True, close_fds=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
... | 31299cd69991254ecbca2ecb314c55eb2d9b0544 | 698,544 |
def time_to_sec(time_str: str) -> int:
"""Convert time in string format to seconds.
Skipping seconds since sometimes the last column is truncated
for entries where >10 days.
"""
total_sec = 0
if '-' in time_str:
# parse out days
days, time_str = time_str.split('-')
total... | e08667cc35a3d85dc30ea3eb63e5d91f2ba99252 | 698,545 |
def get_string_value(value_format, vo):
"""Return a string from a value or object dictionary based on the value format."""
if "value" in vo:
return vo["value"]
elif value_format == "label":
# Label or CURIE (when no label)
return vo.get("label") or vo["id"]
elif value_format == "... | 0efaa0850a63076dd0334bc54f2c96e4f352d6ae | 698,546 |
def create_msearch_payload(host, st, mx=1):
"""
Create an M-SEARCH packet using the given parameters.
Returns a bytes object containing a valid M-SEARCH request.
:param host: The address (IP + port) that the M-SEARCH will be sent to. This is usually a multicast address.
:type host: str
:param ... | cb0da629716e992dd35a5b211f26cae3ad949dcb | 698,547 |
from pathlib import Path
def valid_folder(path_):
"""
Returns True if path_.match any of the conditions. False otherwise.
conditions assigned:
- "_*"
"""
# ignores dunders, __pycache__
conditions = (
"_*",
)
p = Path(path_)
return not(any(p.m... | a0ddff2667eea34d7b00e3aac8623e65140894f9 | 698,548 |
def _balance(target, weight):
"""Assume `cross_entropy(ignore_index=-100)`.
Args:
target (Tensor[H, W]): input tensor.
weight (Tensor[H, W]): probability of BG.
"""
negative_mask = target.eq(0)
limit = 3 + 3 * target.gt(0).sum().item()
if negative_mask.sum().item() > limit:
... | fd59351331319d10b89f70ef816fb9f922e61046 | 698,549 |
import requests
from bs4 import BeautifulSoup
def get_google_image_link(word):
"""
Function returns a url for the movie image in google search resoults
Returns second image as first is a search_url
:param word: search word
:return: url
"""
url = 'https://www.google.com/search?q=' + word + ... | 54b7e4626d0825dee6baaecc6a41ddb14c384797 | 698,550 |
def get_values_from_line(line):
"""Get values of an observation as a list from string,
splitted by semicolons.
Note 1: Ignore ';' inside \"...\". E.g. consider \"xxx;yyy\" as one value.
Note 2: Null string '' for NA values.
"""
raw_list = line.strip().split(';')
i = 0
values = []
whi... | 585c6c9484f6ad145f7265613dc189351cc2d556 | 698,551 |
import os
def find_basic_file(dir, adventure_name):
"""
Try to figure out which basic file belongs to this adventure.
Args:
dir: The directory where the adventure's EDX data files live, e.g., "C:/EDX/C/EAMONDX/E001"
adventure_name: The name of the adventure, e.g., "The Beginner's Cave"
... | 26761043299826286fab4dacd6092287f674866b | 698,552 |
import torch
def map2central(cell, coordinates, pbc):
"""Map atoms outside the unit cell into the cell using PBC.
Arguments:
cell (:class:`torch.Tensor`): tensor of shape (3, 3) of the three
vectors defining unit cell:
.. code-block:: python
tensor([[x1, y1, ... | 5ab75804efa182516ec4e99ec6707e65f205b842 | 698,553 |
def get_left_strip(chonk):
"""
Compute the left vertical strip of a 2D list.
"""
return [chonk[_i][0] for _i in range(len(chonk))] | dfc57a0776e5ab97a808a75170634fa6a072d9d3 | 698,554 |
def filter_waveforms(stream,f1,f2):
"""
Bandpass filter waveforms
INPUTS
stream - list of obspy streams, one for each station/channel combo, each 60 s long
f1 - lower bandpass limit in Hz
f2 - upper bandpass limit in Hz
OUTPUTS
stream - same list of streams, but filtered
""... | 6a563a987e50d668a164c7020449dd2ce5cf28a8 | 698,555 |
def _shift_num_right_by(num: int, digits: int) -> int:
"""Shift a number to the right by discarding some digits
We actually use string conversion here since division can provide
wrong results due to precision errors for very big numbers. e.g.:
6150000000000000000000000000000000000000000000000 // 1e27
... | ba459cb419ef19ac2884d8299d4f1a9213832fa3 | 698,556 |
import json
def js2str(js, sort_keys=True, indent=4):
"""Encode js to nicely formatted human readable string. (utf-8 encoding)
Usage::
>>> from weatherlab.lib.dataIO.js import js2str
>>> s = js2str({"a": 1, "b": 2})
>>> print(s)
{
"a": 1,
"b": 2
... | 17fac42012b5abae77a00083e183d851baaab5b3 | 698,557 |
def handle_extends(tail, line_index):
"""Handles an extends line in a snippet."""
if tail:
return 'extends', ([p.strip() for p in tail.split(',')],)
else:
return 'error', ("'extends' without file types", line_index) | 3b20cc5719d123e36db954c5ffc4537df64f268a | 698,560 |
import os
import codecs
def get_lines_of_cha_files(path):
"""
Gets the lines in the cha files in the given path
:param path: The path that is looked at, this includes the subfolders
:return: a list of cha files with the lines
"""
results = []
for file in os.listdir(path):
with cod... | 6c9fdb90d5f59d5cdd4aa47d7c43b707839ce998 | 698,561 |
def entryID(entry):
"""Try to make an unique ID for entry."""
id = None
if entry.get('guidislink', None):
id = entry.get('id', None)
if id is None:
id = entry.get('link', None)
if id is None:
raise Exception
return id | f1ca161d60db7197e8b51f40585d74690a00c004 | 698,562 |
import torch
def repackage_hidden(h):
"""Wraps hidden states in new Tensors,
to detach them from their history."""
if isinstance(h, torch.Tensor):
return h.detach()
else:
return tuple(repackage_hidden(v) for v in h) | b435d7537e4418d3877db55077285d35a24e46b3 | 698,563 |
def minus(evaluator, ast, state):
"""Evaluates "-expr"."""
return -evaluator.eval_ast(ast["expr"], state) | bf945c368e84d3badd7a90bfce74cb3c89b6890a | 698,564 |
def angle_M(M_r: float, n: float, t_r: float, t: float) -> float:
"""
M = Mr + n * (t - tr)
:param M_r: mean anomaly at tr
:type M_r: float
:param n: mean movement
:type n: float
:param t_r: reference time
:type t_r: float
:param t: time
:type t: float
:return: mean anomaly ... | c99e5dacffea44fa7fadfaebaf6ce734eea81e16 | 698,565 |
from typing import Union
from typing import Dict
import torch
def convert_double_to_float(data: Union[Dict, torch.Tensor]):
"""
Utility function to convert double tensors to float tensors in nested dictionary with Tensors
"""
if type(data) is torch.Tensor and data.dtype == torch.float64:
retur... | 737edbb9625b6cc1dbce425f7e8df8e06cb80410 | 698,566 |
import re
def is_transaction_expired_exception(e):
"""
Checks if exception occurred for an expired transaction
:type e: :py:class:`botocore.exceptions.ClientError`
:param e: The ClientError caught.
:rtype: bool
:return: True if the exception denote that a transaction has expired. False other... | c836521a7137b61ad8443157824ca5da59de65e3 | 698,567 |
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Experimenting Trackers with SORT')
parser.add_argument('--NoDisplay', dest='display', help='Disables online display of tracker output (slow)',action='store_false')
parser.add_argument('--dlib',... | 3ff5d05f2a800a5338c2ac386d0ae78610b285d3 | 698,568 |
def get_legal_moves_lshift(size, mask, player, blank, shift_size):
"""
左シフトで石が置ける場所を取得
"""
tmp = mask & (player << shift_size)
for _ in range(size-3):
tmp |= mask & (tmp << shift_size)
return blank & (tmp << shift_size) | 42a259f21b2ae1c0c57007f939e5e7e935761b88 | 698,569 |
def parse_int(sin):
"""A version of int but fail-safe"""
return int(sin) if sin.isdigit() else -99 | 204cbcb01b6df1bbdd09af318fdfe90feb5fe68f | 698,570 |
def check_read(read):
"""
a callback function for pysam.count function, returns true if the read should be included in the count
:param read: the read to check
:return: True of False whether the read should be included in the count
"""
return read.is_proper_pair | 1bc80c9156bdeb0bc34b2724da8d0147a435b3dd | 698,571 |
def createAggregatedTestCase(doc, parent_node, testclass_name):
"""
Create a node which represents a single aggregated testcase.
Aggregated testcase sums the result of all test cases that
belong to the speified classname. If one of these test cases
fails, the aggregated test case's status is set to ... | a6cfaa405464a09e76d3e4840f99a3d5ff9a87b1 | 698,572 |
def makeToUnicodeCMap(fontname, subset):
"""Creates a ToUnicode CMap for a given subset. See Adobe
_PDF_Reference (ISBN 0-201-75839-3) for more information."""
cmap = [
"/CIDInit /ProcSet findresource begin",
"12 dict begin",
"begincmap",
"/CIDSystemInfo",
"<< /Regis... | dbcb57eddcaa63373da63a90cd937f6d9e4cb835 | 698,573 |
import pandas
def ReadData():
"""Reads data about cannabis transactions.
http://zmjones.com/static/data/mj-clean.csv
returns: DataFrame
"""
transactions = pandas.read_csv('mj-clean.csv', parse_dates=[5])
return transactions | 2652635ae2ed765bc9465706866c017ea171383f | 698,574 |
from typing import List
import subprocess
def run_command(cmd: List[str]) -> str:
"""Execute a command in the shell.
Args:
cmd: :obj:`List[str]`. The command with its arguments to execute.
Returns:
The standard output of the command.
Raises:
:obj:`OSError`: if the standard e... | 5e4025b232c87e52608ea394c782bae0039d15d5 | 698,575 |
def create_dict(**kwargs):
"""Create a dict only with values that exists so we avoid send keys with
None values
"""
return {k: v for k, v in kwargs.items() if v} | 0abd94a4ec3a84685635affbe038d9b513287f6e | 698,576 |
def hospitalized_case(I, AGE_DATA):
""" Calculated hospitalization cases"""
AGE_DATA['Snapshot_hospitalized'] = round(AGE_DATA['Proportion_DE_2020'] *
I *
AGE_DATA['Hospitalization Rate'])
no_h = AGE_DATA['Sna... | 9876bd1e6420b0e12db3ef4300d25fb84931b759 | 698,577 |
def enable_cdc(client):
"""Utility method to enable Change Data Capture for Contact change events in an org.
Args:
client (:py:class:`simple_salesforce.Salesforce`): Salesforce client
Returns:
(:obj:`str`) Event channel Id
"""
payload = {
"FullName": "ChangeEvents_ContactCh... | 2c7bc57f33e83029caea542db9daeaa81f6661cc | 698,579 |
def extract_first_appearance(string, type_, last_possible):
"""Extract the first appearance of the character in manga or anime
Note: the complete list of manga_chapters and anime_episodes seems
incorrect on Hokuto Renkitōza.
Parameters
----------
string : str
entire appearances string ... | baee950b7f3f0cbba2f3dee2e136f7d63b737489 | 698,581 |
def get(key: str, dic, default=None):
"""Gets key even from not a dictionary."""
try:
return dict(dic).get(key, default)
except TypeError:
return default | 5302868de0b6b4a94bded35654d6a9ad215d867e | 698,582 |
import argparse
def get_arguments():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description="Code for domain adaptation (DA) training")
parser.add_argument('--cfg', type=str, default=None,
help='optional config file', )
parser.add_argument("--random-... | c1d52553350100ae8a9722d95a88fd87b7af62af | 698,583 |
import yaml
def load_config_from_yaml(filename='fsm.yaml'):
"""
Returns the current fsm configuration dictionary, loaded from file.
:return: a dict.
"""
yaml_file = open(filename, 'r')
yaml_dict = yaml.safe_load(yaml_file.read())
return yaml_dict | e1ff03a8fcc2a77288d8971cd76fd17e7a30f65a | 698,584 |
import torch
def atanh(x, eps=1e-2):
"""
The inverse hyperbolic tangent function, missing in pytorch.
:param x: a tensor or a Variable
:param eps: used to enhance numeric stability
:return: :math:`\\tanh^{-1}{x}`, of the same type as ``x``
"""
x = x * (1 - eps)
return 0.5 * torch.log(... | 27b0e8de0eeceb44d739f686ca22d616bc8f75de | 698,585 |
def index_names_from_symbol(symbol):
"""
Return the domain names of a GAMS symbol,
except ['*'] cases are replaced by the name of the symbol
and ['*',..,'*'] cases are replaced with ['index_0',..'index_n']
"""
index_names = list(symbol.domains_as_strings)
if index_names == ["*"]:
return [symbol.name]
... | dc4acc473eaf13d18f553abd722384bf4fe3115a | 698,586 |
from pathlib import Path
import json
def read_description(filename):
"""Read the description from .zenodo.json file."""
with Path(filename).open() as file:
info = json.load(file)
return info['description'] | 0568aa956f3b0c3f5be4ba75ea8e6b98e08c469e | 698,588 |
import argparse
def parsing():
"""
Parse arguments
"""
descr = "Superimpose all .pdb conformations onto the provided template"
descr_pdbDir = "Directory containing conformation ensemble"
descr_templatePath = "Template onto which superimpose the conformation " \
"ensemble"
parser =... | 45e96831e82adf04fd974631a303418db42fc09a | 698,589 |
import zipfile
import os
def zip_file(dir, filename):
"""
Add the contents of dir to zipfile.
:param dir: str
:param filename: str (the name of the zip file)
:return: None
"""
zp = zipfile.ZipFile(filename, "w")
for i in os.walk(dir, followlinks=True):
for fp in i[2]:
... | 23fa15682bd1e0917830139ef0848fddee36dbd0 | 698,590 |
def cocktail_shaker_sort(list_: list) -> list:
"""Returns a sorted list, by cocktail shaker sort method
:param list_: The list to be sorted
:type list_: list
:rtype: list
:return: Sorted list, by cocktail shaker sort method
"""
higher = len(list_) - 1
lower = 0
Flag = False
wh... | 5a5214100859f95a34fd6f89786f5b93dad426ce | 698,592 |
from bs4 import BeautifulSoup
import requests
import re
def getProductInfo(link):
"""
gets a random item link and looks for item_name,
item_price and item_main_image
returns all three infos as string
"""
req = requests.get(link)
soup = BeautifulSoup(req.text, 'html.parser')
# get im... | b1d1a2fc28db46fbc506865a9c5a470408680ba0 | 698,593 |
import os
def GetEnvInt(variable):
"""Returns the environment variable value as an integer."""
return int(os.getenv(variable) or 0) | dc87a87318efe816fdb1f0a96b4e14ea226d7a5d | 698,594 |
def convertBoolean(value: bool):
"""Convert Python bool to JS boolean.
Args:
value (bool): True/False
"""
if value:
jvalue = "true"
else:
jvalue = "false"
return jvalue | d9f3f58eed31f960050df25b5a8ec69fad5f8754 | 698,595 |
def a_or_an(word):
"""Naively returns "a word" or "an word" depending on the word."""
if len(word) > 0:
if word[0] in 'aeiouAEIOU':
return 'an'
else:
return 'a'
else:
return 'a' | 45f53fbc100511364d56c06b4030055f7671ff3e | 698,597 |
def find_earliest_start(t_goal, deltas):
"""Find the earliest start time with an active range reaching t_goal.
Example
-------
t_goal == 5
delta[t_goal - 1] == 3
We first take a guess...
|√-2|√-1| √ |
<------3
* ... Case 1 (e.g. deltas = [4, 4, 3, 3, 3]): guess DO... | f2716df58b8986a016dd79943b43959554a1786b | 698,598 |
def to_numbers(line, dictionary):
"""
Turn a nature language sentence string to a list of numbers.
:param line:
:param dictionary:
:return:
"""
return [dictionary[string] for string in line.split()] | 754cd8e10fda44a53e06a57cabb8f4663548c5e1 | 698,599 |
import importlib
def get_func(func_name):
"""Helper to return a function object by name. func_name must identify a
function in this module or the path to a function relative to the base
'modeling' module.
"""
if func_name == '':
return None
try:
parts = func_name.split('.')
... | da95b0933ce60cd55049c13ef198eba4d9d0b0ee | 698,600 |
import os
def _add_travis_info(capabilities):
"""
"""
capabilities['tunnel-identifier'] = os.getenv('TRAVIS_JOB_NUMBER')
capabilities['build'] = os.getenv('TRAVIS_BUILD_NUMBER')
capabilities['tags'] = [os.getenv('TRAVIS_PYTHON_VERSION'), 'CI']
return capabilities | c47d4c6f4524b7e1e6c01c0b5186ef1f4dd5fb88 | 698,601 |
def cica_const_ratio(ambient_co2, const):
"""ci/ca is constant."""
"""Return ci = intercellular CO2 concentration, kg/m^3."""
return const * ambient_co2 | 418f5172def68cede271767943a3af5817ccfe62 | 698,602 |
def MTFfreq(MTFpos, MTF, modulation=0.2):
""" Return the frequency for the requested modulation height. """
mtf_freq = 0
for f in range(len(MTFpos)):
if MTF[f] < modulation:
if f > 0:
# Linear interpolation:
x0 = MTFpos[f-1]
x1 = MTFpos[f]... | fadec075afaffa405ef4135f714be6e2bceb71c7 | 698,603 |
import codecs
def countsyll(instring):
"""This function counts the number of characters in a tamil string
This is done by ignoring the vowel additions. If one uses the len
function, the sample string has a length of 17 - but there are actually
only 11 characters"""
s = codecs.utf_8_enc... | 3340eb844014c2c53661f9ea278dd38eff8e8a33 | 698,604 |
def infer_relationship(coeff: float, ibs0: float, ibs2: float) -> str:
"""
Inferres relashionship labels based on the kin coefficient
and ibs0 and ibs2 values.
"""
result = 'ambiguous'
if coeff < 0.1:
result = 'unrelated'
elif 0.1 <= coeff < 0.38:
result = 'below_first_degree... | c24ab30a4a9d06ef552abe728f78d8081f40e87f | 698,605 |
def allStudentsMajoringIn(thisMajor,listOfStudents):
"""
return a list of the students with the major, thisMajor
>>> majorToLNames("MATH",[Student("MARY","KAY","MATH"), Student("FRED","CRUZ","HISTORY"), Student("CHRIS","GAUCHO","UNDEC")])
[Student(fName='MARY',lName='KAY',major="MATH")]
>>>
""... | ad32dfd68b2daa4aa3e46ff8563e4575bd940336 | 698,606 |
def float_to_string(f):
""" this prints a number with a certain number of digits after the point,
while removing trailing zeros.
"""
num_digits = 6 # we want to print 6 digits after the zero
g = f
while abs(g) > 1.0:
g *= 0.1
num_digits += 1
format_str = '%.{0}g'.format(num_... | 41ad07eb610044ae54a201ebc77c20e2b647da3a | 698,607 |
import os
import tempfile
def is_path_sibling_creatable(pathname: str) -> bool:
"""
`True` if the current user has sufficient permissions to create **siblings**
(i.e., arbitrary files in the parent directory) of the passed pathname;
`False` otherwise.
"""
# Parent directory of the passed path.... | 6558cbcc6d3a16f1e0eea207bd09557a66ec400c | 698,608 |
def flatten(iterable):
"""
Extracts nested file items from path
to single iter.
"""
return iterable
# Os walk with absolute path returns
# non-nested
#
# return [item for it in iterable for item in it] | c0b53c44c12a9307c62ce8cb54d5214b2648388f | 698,609 |
def bounding_box(ptlist):
"""
Returns the bounding box for the list of points, in the form
(x1, y1, x2, y2), where (x1, y1) is the top left of the box and
(x2, y2) is the bottom right of the box.
"""
xs = [pt[0] for pt in ptlist]
ys = [pt[1] for pt in ptlist]
return (min(xs), max(ys), ma... | cd27b3e5783ee7dd8c5960389079b32768516e4d | 698,611 |
def goodreads(soup):
"""
Read the book titles from the image alt text.
"""
tags = soup.find_all(lambda x: x.next_element.name ==
'img' and '/book/show/' in x.get('href', ''))
titles = set(map(lambda x: x.img.get('alt').strip(), tags))
return titles | b2385a8778711661f7ead88cc9357663dce38e32 | 698,612 |
def is_good(filename: str, force: bool = False) -> bool:
"""
Verify whether a file is good or not, i.e., it does not need
any shape or illumination modification. By default a file is
good if it is a pdf.
Parameters
----------
filename
The file name.
force
Wether to forc... | acaee589288db3eb48bd7bc89dc21c0a7d75822c | 698,613 |
def patched_repo_get_default_identity(original_repo_get_default_identity):
""" Allow to run without valid identity """
def patched_function():
try:
return original_repo_get_default_identity()
except: # pylint: disable=W0702
return ("Git User", "git@localhost")
return... | 99049874102efbec318b4ba0f23e7a8732695665 | 698,616 |
def discovery(request):
"""
defined in Core API Specification 7
:type request: pyramid.request.Request
:rtype: dict
"""
resp = request.response
resp.content = """\
<XRDS xmlns="xri://$xrds">
<XRD xmlns:simple="http://xrds-simple.net/core/1.0" xmlns="xri://$XRD*($v*2.0)" version="2.0">
... | c8ffad72903ab13298fc71f150f20c2e7dd47136 | 698,617 |
import platform
def is_windows():
"""是否Windows操作系统"""
return 'Windows' in platform.system() | 5d0820d442668ad42fbc3253664be8a67f508159 | 698,620 |
import re
def all_whitespace(string):
""" all_whitespace(string : str) -> bool
>>> all_whitespace(' ')
True
Returns True if a string has only whitespace.
"""
return re.search('^[ \t]*(\r|\n|$)', string) | 766b92da0b6e91fbcd05eed408cb5651cdf42b4e | 698,622 |
import copy
import uuid
import collections
def deep_copy(item_original):
"""Return a recursive deep-copy of item where each copy has a new ID."""
item = copy.copy(item_original)
item._id = uuid.uuid4().hex
if hasattr(item, '_children') and len(item._children) > 0:
children_new = collections.Or... | 83c8ee5dd620e30a518391752905ba1966d27aa4 | 698,623 |
import sys
def use_sys_args():
""" Parse the command line arguments using sys.args. """
# There are 2 possible ways to achieve the result in one line.
# One using a map:
# return sum(list(map(int, sys.argv[1:])))
# or using a list comprehension.
return sum([int(i) for i in sys.argv[1:]])
... | 790b50332755d5a35637fa7ab9f33b41a89fc32f | 698,624 |
import os
import json
def diff_location():
"""
:params none
Returns the non-repeated address co-ordinates
"""
loc = input('Enter facebook archive extracted location: ')
if not os.path.isdir(loc):
print("The provided location doesn't seem to be right")
exit(1)
... | b1ef5e3c4fd85351b45de5d33e54458f626333d2 | 698,625 |
import os
def get_files():
"""Get a list of files/folders in the cwd"""
return os.listdir(os.getcwd()) | 4888620176a33a3ad97b49af7e532fd4f53bf8e3 | 698,626 |
import os
import imp
def find_module(modname):
"""Finds and returns a module in the local dist/checkout.
"""
modpath = os.path.join(
os.path.dirname(os.path.dirname(__file__)), "Lib")
return imp.load_module(modname, *imp.find_module(modname, [modpath])) | ef308748c969889459abaef511bbf071d0ab6fe9 | 698,627 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.