content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_urls_keywords_thread(urls, keywords):
"""
get_urls_keywords_thread(urls, keywords)
:param urls:
:param keywords:
:return:
"""
urls_keywords = []
for url in urls:
for keyword in keywords:
if keyword in url:
urls_keywords.append(url)
return u... | 6b3d1017b767e450fa3db02fe377c32c036daf1d | 663,078 |
import multiprocessing
def parmap(f, X, nprocs=multiprocessing.cpu_count()):
"""
Parallel map implementation adapted from http://stackoverflow.com/questions/3288595/multiprocessing-using-pool-map-on-a-function-defined-in-a-class
"""
def func_wrap(f, q_in, q_out):
while True:
i, x ... | d1e21ede71f73a103ed20b3f700b9d26fdc42b98 | 663,079 |
import requests
def get_comment_content(goods_id, score, page, pageSize):
"""获取商品评论"""
url = "https://club.jd.com/comment/productPageComments.action"
headers = {
"Host": "club.jd.com",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0",
"... | 190927665f361fb13cf3026a6ee85d53a5120a25 | 663,080 |
def generate_plus_grid_isls(output_filename_isls, n_orbits, n_sats_per_orbit, isl_shift, idx_offset=0):
"""
Generate plus grid ISL file.
:param output_filename_isls Output filename
:param n_orbits: Number of orbits
:param n_sats_per_orbit: Number of satellites per orbit
... | c1da59a15ed7dd7dc769380c65ec5e96d41fd748 | 663,081 |
def empty(l):
"""Retourne True ssi la liste est vide"""
return len(l) == 0 | 7132cef8ce279306e898a1535d7794f92a12328d | 663,082 |
def unique_list(list):
"""
Returns a unique version of a list
:param list: Input list
:return: Unique list
"""
new_list = []
for i in list:
if i not in new_list:
new_list.append(i)
return new_list | f04b2714b4c0c9c0ec8de10cf87167a696859969 | 663,083 |
def calculate_comment_to_code_ratio(production_code_metrics, test_code_metrics):
"""Calculate the ratio between the comments and the lines of code."""
lines_of_code = production_code_metrics["SUM"]["code"] + test_code_metrics["SUM"]["code"]
comment_lines = production_code_metrics["SUM"]["comment"] + test_c... | 48d7b991ecf19ebd7e97c2da3987abf7d2c8face | 663,085 |
import os
def _FileToModuleName(filename):
"""Returns the module name corresponding to a filename."""
_, lib, suffix = filename.partition('$PYTHON_LIB/')
if lib:
module = suffix
else:
module = filename
module = os.path.normpath(module)
if '.py' in module:
module = module.rpartition('.py')[0]
... | db9472cb89353f9a9eb6c6cc183c3cf2b363d84b | 663,086 |
def lowercase_first_letter(s: str) -> str:
"""
Given a string, returns that string with a lowercase first letter
"""
if s:
return s[0].lower() + s[1:]
return s | e57810ec93482950c3e6563d1f9adbca732217e4 | 663,087 |
import re
def find_num(txt):
""" Find first match to any number in a given txt """
p = r'[\d]+[.,\d]+|[\d]*[.][\d]+|[\d]+'
lst_nums = re.findall(p, txt)
# if not match, then return the original string
if not lst_nums:
return txt
else:
# if some matches here, just pick the firs... | 1fad83149b4703aa7cc576f7b604e03113f3004c | 663,088 |
import argparse
def get_local_predict_args():
"""
Defines the command line arguments necessary to kick off an extraction session
:return: the command line arguments provided from stdin
"""
parser = argparse.ArgumentParser()
parser.add_argument("-mt", "--model_type", help="Choose a model type: ... | 422edd95088b96d80206991de99a29e7e2656851 | 663,089 |
import operator
def SortedByCompletion(requests):
"""Returns the requests, sorted by completion time."""
return sorted(requests, key=operator.attrgetter('timestamp')) | ec30ed7f09bdc43efccc5bda5b0d70bf81e6232e | 663,090 |
import numpy
def area_info(area_cube, mask, selected_region):
"""Determine the area of the ocean and land."""
areas_dict = {}
regions = ['ocean', 'land']
regions.remove(selected_region)
area_cube.data = numpy.ma.asarray(area_cube.data)
area_cube.data.mask = mask
areas_dict["area_" + sel... | 99beeadb901986f9f1cb07708f9a62ca5d5aa155 | 663,091 |
def get_huffman_codes(node, huffman_codes):
"""Creates a dict of chars and their cooresponding Huffman Codes.
Args:
node: A HuffmanNode object to find all Huffman Codes for the leaves
under it
huffman_codes: A dict to store the generated Huffman Codes
Returns:
huffman_c... | 454a97dec2bdf6bc9fcc4e6c7c26cdef7a072d89 | 663,092 |
def _h_n_linear_geometry(bond_distance: float, n_hydrogens: int):
# coverage: ignore
"""Create a geometry of evenly-spaced hydrogen atoms along the Z-axis
appropriate for consumption by MolecularData."""
return [('H', (0, 0, i * bond_distance)) for i in range(n_hydrogens)] | f30d7008f64f586b952e552890cc29bb87c0544c | 663,093 |
def split_alignments_by_chrom(alignments_file, get_temp_path):
"""Split an alignments file into several files, one per chromosome.
get_temp_path is a function that returns a new temporary file path.
Returns a dictionary, {chrom_name: alignmentfile_path}."""
paths = {}
cur_chrom = None
output_p... | 6aa2a7caf200b15cdcefc855a779d59982b03e1f | 663,094 |
def admin_can_edit_paste(user, paste):
"""Can the user using admin permission to edit the paste?"""
return user.has_perm('core.change_paste') and user.has_perm(
'core.delete_paste'
) | 44b5c83efac30ec9e71dcaa0104217e7327c84b0 | 663,095 |
import argparse
def main(args=None):
"""Console script for {{cookiecutter.project_slug}}."""
parser = argparse.ArgumentParser(description='Command line executable for {{cookiecutter.project_slug}}.')
args = parser.parse_args()
return 0 | 5c1d4532d9a19872b67e65a34ec491a135d3353a | 663,096 |
def generate_occluder_pole_position_x(
wall_x_position: float,
wall_x_scale: float,
sideways_left: bool
) -> float:
"""Generate and return the X position for a sideways occluder's pole object
using the given properties."""
if sideways_left:
return -3 + wall_x_position - wall_x_scale / 2
... | 4d31538547bb59b7b4115f772886d61b6e695e4b | 663,097 |
def govukify(html):
"""
A method to add govuk classes to vanilla HTML
Params
------
html : str
a string of html
"""
html = html.replace("<p", '<p class="govuk-body"')
html = html.replace("<h1", '<h1 class="govuk-heading-xl"')
html = html.replace("<h2", '<h2 class="govuk-head... | 6393886fc878885bfd9f4af4864bd2d5e157559a | 663,099 |
def fix_wifi_csv(header: bytes, rows_list: list, file_name: str):
""" Fixing wifi requires inserting the same timestamp on EVERY ROW.
The wifi file has its timestamp in the filename. """
time_stamp = file_name.rsplit("/", 1)[-1][:-4].encode()
# the last row is a new line, have to slice.
for row in ... | 03f8d23464c495201820c4dff0539c78bcbccc71 | 663,100 |
def repr(obj):
"""Default implementation of `__repr__()` for user-defined classes.
Simply uses the object's `str()` representation and adds the object's memory address at the
end (which is often times useful to check if two references point to the same object).
"""
return "<{!s} @{:x}>".format(obj,... | a26083b4b78a0150ebd4fb60aa7c2eb3fa49dfe9 | 663,102 |
def merge(ll, rl):
"""Merge given two lists while sorting the items in them together
:param ll: List one (left list)
:param rl: List two (right list)
:returns: Sorted, merged list
"""
res = []
while len(ll) != 0 and len(rl) != 0:
if ll[0] < rl[0]:
res.append(ll.pop(0))
... | 0b88eea3733d0ac2739faff57b36faf6841d0446 | 663,103 |
def seqs_lengths(seqs):
""" Helper method to return length for all seqs"""
N = {}
for seq in seqs:
N[seq] = seqs[seq].N
return N | 8e7dd23f1a69b50bfea23f8788cc2f4f9bfef0be | 663,104 |
import json
def CommentToJSON(comment):
"""
Converts a Comment object into a JSON-compatible dictionary.
Return None on failure.
"""
if not comment:
return None
if not comment.author_json:
return None
# Used to fetch updated author representation to attach to a comment
... | 3b170775eee35f1426d7cf51b0205f7d3f7d83a1 | 663,105 |
import hashlib
def MD4(s):
"""
@summary: compute the md4 sum
@param s: {str} input data
@return: {str} MD4(s)
"""
return hashlib.new('md4', s).digest() | fb071415aecc30d3869209744befea6a51066c75 | 663,106 |
def scaleTimeAxis(time=0):
""" Calculates time axis scaling factor
:returns:
A float, X-axis (time) number of data points
"""
return 2000//(10**(time)) | c8c66779eb7720a0e87ba402ec22542e6e4cc4cc | 663,107 |
def replace_none(params):
"""replace_none"""
if params == "None":
return None
if isinstance(params, dict):
for key, value in params.items():
params[key] = replace_none(value)
if key == "split_char" and isinstance(value, str):
try:
v... | bd6572b27bb3efb9e55f6be188e745660d56e302 | 663,108 |
def dot(A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
M = 1000000007
m = len(A)
n = len(B[0])
d = len(B)
result = [[0 for j in range(n)] for i in range(m)]
for i in range(m):
for j in range(n):
for k in range(d):... | a5b8843b78835f0a0c64bda8c813736f35b283d9 | 663,109 |
import functools
import operator
def factorial(n):
""" Factorial of a number.
>>> factorial(0)
1
>>> factorial(1)
1
>>> factorial(5)
120
>>> factorial(10)
3628800
"""
# Handle 0 as a special case
if n == 0:
return 1
# この階乗の実装は再帰呼び出しを避けているので OK だ。
# なお... | bcf8c286d986ad3c3cdb6fab80e655437e570488 | 663,110 |
def prep_reply_text(screen_name, text):
"""Replies have to contain the original tweeter's screen_name"""
if screen_name in text:
return text
else:
if "@" in screen_name:
return screen_name + " " + text
else:
return "@{} {}".format(screen_name, text) | 683fec84971e4350dcbb97483602c73a51b0fb35 | 663,111 |
import math
def h_euclidean(board):
"""
Euclidean Distance It is the distance between the current cell and the
goal cell using the distance formula
"""
h = 0
for i in range(board.width):
for j in range(board.height):
if (board.tiles[i][j]):
(goal_x, goal_y) ... | 1be0607c730d589ef382aeb8433540215354815f | 663,112 |
def evaluate_probabilities(data):
"""Calculate accuracy of logistic regression model
Args:
data (pandas.DataFrame): dataframe with nudge success and probability
Returns:
int: accuracy in percentage
"""
check = round(data['probability']) == data['outcome']
correct = sum(check)
... | f8953f6fe3a934bdaea25f83828b9a9709e59974 | 663,113 |
def contains(needle, haystack) -> bool:
"""
A syntactic sugar for the following:
>>> for item in haystack:
>>> if needle == item:
>>> return True
>>> return False
Note that this is very like Python's in operator, however it's not quite same, since
in doesn't involve the __e... | 05f8ca8be7b6d9aa694d8863e122850f2a399e81 | 663,114 |
def startup_cost_by_st_rule(mod, g, tmp, BIN_OR_LIN, Bin_or_Lin):
"""
Startup costs are applied in each timepoint based on the amount of capacity
(in MW) that is started up in that timepoint for a given startup type and
the startup cost parameter for that startup type. We take the sum across
all sta... | 54937dda0d67e5f4808af2fb2da47a0e06c5781e | 663,115 |
def community_kwargs_from_role(role):
"""Parses community id and role from role name."""
args = role.name.split(':')
if args[0] != 'community' or len(args) != 3:
return None
return dict(
id_=args[1],
role=args[2]
) | 4ce927f8c647190e7f1c5a2c7f875fd24c52b3c5 | 663,116 |
def find_path_timestamp(path):
"""Returns the timestamp of a path.
Timestamp of a path is considered to be the minimum timestamp contained in path.
:param path: A path represented as a sequence of edges in the form of four-tuples.
(source, target, key, timestamp)
"""
return min([e[3] f... | 5dc4f944525db1c64853ff43afa7645f84ab7b0e | 663,117 |
def CO2_scrubber_rating(report, index):
"""
Determine the CO2 scrubber rating value.
:param report: list of read binary numbers
:return: CO2 scrubber rating
"""
ones = 0
zeros = 0
if len(report) == 1:
return report[0]
for number in report:
if int(number[index]):
... | bfcc3e3ef8c536df233c8aac64d5132883ef4206 | 663,119 |
import torch
def get_lengths_from_binary_sequence_mask(mask: torch.Tensor):
"""
Compute sequence lengths for each batch element in a tensor using a
binary mask.
Parameters
----------
mask : torch.Tensor, required.
A 2D binary mask of shape (batch_size, sequence_length) to
calcu... | f590d08ae8649a1ba9aaa2da70de377d0b397e4c | 663,120 |
def _f_p_r_lcs(llcs, m, n):
"""
Computes the LCS-based F-measure score
Source: http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Args:
llcs: Length of LCS
m: number of words in reference summary
n: number of words in candidate summary... | 93700f51169b4c081b53412e133fc173392c3ea3 | 663,121 |
def build_response_html_app_info(response, language):
"""
Stringifying the application information, for output in a html file, with the response_id and applicant name contact info as
paragraphs (<p>)
"""
stringified_app_info = f"<p><b> Response ID:</b> {response.id}</p> <p><b>Full name:</b> {r... | 1dc73d0688c35c4e01011a706f50a97a6c737b92 | 663,122 |
def date_formats(request):
"""
date_formats
"""
return {
'date_format_long': 'l j F Y',
} | 2796d0063d0283a0792021c6716ffb96a6ab81e4 | 663,123 |
def flatten_frames(array):
"""
Flattens array of shape [frames, height, width] into array of shape [frames, height*width]
Parameters
----------
array : np.array
(frames, height, width)
Returns
-------
np.array
flattened array (frames, height, width)
"""
_, heig... | 6f1d3de5d6987ad46dca6de04647f5c2eab1f5cb | 663,124 |
def check_valid_coors(coords):
"""Check if the given coords of the polygon are valid
Parameters
----------
coords : numpy array
a list of coordinates, shape = (8,)
Returns
------
bool
whether all coordinates are valid or not
"""
for i in coords:
if i < 0:
... | 0ad092cb34d3d2a51e5708e2ac60a6332eeb67e3 | 663,125 |
def LIS_by_one_starting_index(seq):
"""
Return the index in a sorted seq at which the longest increasing subsequence, that increases by a difference of one, starts.
For example: seq = (1, 5, 6, 9, 10, 11, 12, 39, 40)
returns 3 because 9, 10, 12 starts at 3
"""
assert seq
index = candidate_in... | 39e615871d681e0848d2dbf97b0106bb8c1c6af8 | 663,126 |
import configparser
def _get_api_key() -> str:
"""
Retrieves the ADSBexchange API key from secrets.conf
"""
config = configparser.ConfigParser()
config.read("secrets.conf")
return config.get("adsbexchange", "key") | f0d01ba6acbab1cf1768b555365735313057d135 | 663,127 |
import os
def path_contains(parent_path, child_path):
"""Check a path contains another path.
>>> path_contains("a/b", "a/b")
True
>>> path_contains("a/b", "a/b/")
True
>>> path_contains("a/b", "a/b/c")
True
>>> path_contains("a/b", "c")
False
>>> path_contains("a/b", "c/b")
... | b2f75d66f4a7f43edf33bd6a489bacf5880b1a03 | 663,128 |
def getKeys(dictionary, sorted=True):
""" Gets the keys of a dictionary """
keys = []
for key, value in dictionary.iteritems():
keys.append(key)
return keys | 03ecc99b4d8fe1d7dfc3ed2879c0355e7fccf290 | 663,129 |
def removeNoneValues(dict):
""" If value = None in key/value pair, the pair is removed.
Python >3
Args:
dict: dictionary
Returns:
dictionary
"""
return {k:v for k,v in dict.items() if v is not None} | 0ef51c71e8b41e61dc7928db5393d959dc9a0f69 | 663,132 |
import hashlib
def CalcMD5(filepath, encoding='utf-8'):
"""
计算文件MD5
:param filepath:
:return:
"""
with open(filepath, 'rb', encoding=encoding) as f:
md5obj = hashlib.md5()
md5obj.update(f.read())
hash = md5obj.hexdigest()
return hash | d4219db1870b2b05f6987a25b39505618844f518 | 663,135 |
def subsampling(sequence, sampling_factor=5):
"""
Args:
sequence: data sequence [n_samples, n_features]
sampling_factor: sub-sampling factor
Returns:
sequence: sub-sampled data sequence [n_samples/sampling_factor, n_features]
"""
sequence = sequence[::sampling_factor]
... | ffdb254890525b7500852867359fdfd64869d485 | 663,137 |
def union(interval1, interval2):
"""
Given [0, 4] and [1, 10] returns [0, 10]
Given [0, 4] and [8, 10] returns False
"""
if interval1[0] <= interval2[0] <= interval1[1]:
start = interval1[0]
end = interval1[1] if interval2[1] <= interval1[1] else interval2[1]
elif interval1[0] <= interval2[1] <= int... | b62354d8740820127771c7ae8df41ea3624e5ae1 | 663,138 |
import argparse
import sys
def getparser():
"""Gets program's parser."""
parser = argparse.ArgumentParser(
prog='run', description='Client for Bloodhound server.')
parser.add_argument('url', help='The URL of the server.')
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
... | 59ca402186f830647e43d441896b49dfb80d0522 | 663,139 |
import os
def get_fout_py(module_name):
"""Given a module name, return the name of the corresponding Python file."""
fout_py = "{MODULE}.py".format(MODULE=module_name)
if os.path.isfile(fout_py):
os.remove(fout_py)
return fout_py | 5684ffdfe58ca69367299f017e40867dbf238c76 | 663,141 |
def _get_local_explanation_row(explainer, evaluation_examples, i, batch_size):
"""Return the local explanation for the sliced evaluation_examples.
:param explainer: The explainer used to create local explanations.
:type explainer: BaseExplainer
:param evaluation_examples: The evaluation examples.
:... | b17f88b7f03d0ff40772102a88afc4449fee8035 | 663,142 |
def get_addons(objects):
"""Return tuple of required addons for a given sequence of objects."""
required = {}
def _required_addons(objs):
for addon in objs:
if addon not in required:
if addon.required_addons:
_required_addons(addon.required_addons)
... | b2fb3450e07b0882fc8760d53691b6e14613baf8 | 663,143 |
from dateutil import tz
def _naive_time_offset(timestamp, reference):
"""
Returns the offset (in seconds) between the given datetime objects, but
assumes that both are in the same time zone.
"""
if reference.tzinfo != tz.tzutc():
reference = reference.replace(tzinfo=tz.tzutc())
return ... | 293e8fb68e2af63791c9b2e57cbd6681d941030b | 663,144 |
def search_dict(list, key, value):
"""
dictの配列から指定された値を持つdictを取得する。
"""
for d in list:
if key in d and d[key] == value:
return d
return None | ed3048c01e9b2853d572ca09af24a5665a2907b8 | 663,145 |
from pathlib import Path
def remove_temp(TEMP: Path) -> None:
"""Deletes folder with affix "temp" along all its contents.
Parameters:
TEMP: Path - Directory to delete
Returns:
None
"""
assert TEMP.name.endswith("temp"), f"Directory does not seem temporary"
for file in TEMP.iterdir():... | 1e23db83b4107a5cbb46cad2c3938bb3c30d4269 | 663,146 |
def big_letters(sequence_of_sequences):
"""
Returns a new STRING that contains all the upper-case letters
in the subsequences of the given sequence that are strings,
in the order that they appear in the subsequences.
For example, if the argument is:
[(3, 1, 4), # not... | 6df221024d634579b10cd8b05772a488cd64aafb | 663,147 |
import numpy
def filter_greys_using_image(image, target):
"""Filter out any values in target not in image
:param image: image containing values to appear in filtered image
:param target: the image to filter
:rtype: 2d :class:`numpy.ndarray` containing only value in image
and with the same di... | b00870656bd9191550318013b90402c1fad0adbe | 663,148 |
import secrets
import string
def random_name(length: int) -> str:
"""Get a random string suitable for a processes/consumer name"""
return "".join(secrets.choice(string.ascii_lowercase) for _ in range(length)) | 0ed133e0bfdf35f5b5a01b9e87de1fe176966175 | 663,149 |
def pressure_at_model_level(ps, ak, bk):
"""computes pressure at a certain model level.
Uses surface pressure and vertical hybrid coordinates.
**Arguments:**
*ps:*
surface pressure
*ak, bk:*
hybrid coordinates at a certain level
"""
return ak + bk * ps | 32fef19321c7d7802cf64105dcb7e0ffdf8db8c8 | 663,150 |
def is_valid_matrix(mtx):
"""
>>> is_valid_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
True
>>> is_valid_matrix([[1, 2, 3], [4, 5], [7, 8, 9]])
False
"""
if mtx == []:
return False
cols = len(mtx[0])
for col in mtx:
if len(col) != cols:
return False
r... | 2e57455155cca8f37f738ef5ca7444ec118f1f6a | 663,151 |
import socket
def _get_ip_address():
"""get computer's ip address"""
return socket.gethostbyname(socket.gethostname()) | f8c8fb71dd4569aa783f248f2e4dbc62ec6a5148 | 663,152 |
def _gr_ymin_ ( graph ) :
""" Get minimal y for the points
>>> graph = ...
>>> ymin = graph.ymin ()
"""
return graph.bb() [ 2 ] | 781f5a4b8667537f3a449963b78b09907e4eae88 | 663,153 |
import re
def handle_star(github_star):
"""
Get github repository star
:param github_star: 1.1k or 100
:return: 1100 or 100
"""
pattern = r'[^k]+'
star = re.findall(pattern, github_star)
if github_star[-1] == 'k':
return int(float(star[0]) * 1000)
else:
return int(s... | e2f7337a347a94e2fdec2d9f44c2bb68fe4b3e39 | 663,155 |
def binary_to_hex(binary_data, byte_offset, length):
"""Converts binary data chunk to hex"""
hex_data = binary_data[byte_offset:byte_offset + length].hex()
return ' '.join(a+b for a,b in zip(hex_data[::2], hex_data[1::2])) | 708f22a0a0165c97aee77557965d3e720b77729c | 663,157 |
def monitor_normalize(sansdata, mon0=1e8):
""""
Given a SansData object, normalize the data to the provided monitor
**Inputs**
sansdata (sans2d): data in
mon0 (float): provided monitor
**Returns**
output (sans2d): corrected for dead time
2010-01-01 Andrew Jackson?
"""
monit... | c1435a65b812f9bf02e3bf61b4d6f4eb748356c1 | 663,158 |
def filter_examples(sent, examples):
"""
filter out some examples, listed as follows:
(1) attractor is a modifier in a plural noun phrase, e.g. "customer services"
(2) verb immediately follows subject (hence attractor effect would be very weak)
(3) attractor occurs much earlier than subject (same as (3))
"... | 96bc18873d790fdae37029beca2eb22871182696 | 663,159 |
def generate_degradation_matrix(p, h_max):
"""
Generate an upper triangular degradation transition matrix.
Parameters
----------
p : float
The probability of degrading by one unit at each time step.
h_max : int
The index of the failed state.
Returns
-------
list o... | 7fe3a551287e590bc361846e43f3bc08ae1e0907 | 663,160 |
def ncities(cost):
"""
Return the number of cities
"""
nc, _ = cost.shape
return nc | 31177b9b0ccbd252adbe39219c0c6ed0b5f78bd3 | 663,161 |
from typing import Union
import os
def loaddirs(
src_path: Union[os.PathLike, str]
) -> list:
""" Recursively lists the full relative path of all
directories in a directory.
Only lists files, not directories.
----------------------------------
Parameters
----------
... | fe98222a431dd8042a31ace6f1e619e45a1b0462 | 663,162 |
import subprocess
import json
def kubernetes_versions(region):
"""Return list of available kubernetes supported by cloud provider. Sorted from oldest to latest."""
output = subprocess.check_output(
[
"gcloud",
"container",
"get-server-config",
"--region... | af3d8e437e61d545adf2d196164df56cea2bc634 | 663,163 |
def overlap(a1, a2, b1, b2):
"""
Check if ranges a1-a2 and b1-b2 overlap.
"""
a_min = min(a1, a2)
a_max = max(a1, a2)
b_min = min(b1, b2)
b_max = max(b1, b2)
return a_min <= b_min <= a_max or b_min <= a_min <= b_max or \
a_min <= b_max <= a_max or b_min <= a_max <= b_max | d898b46122adbac0777defb0ab658587c0c1d367 | 663,164 |
import re
def check(scrapedPage, inputText):
"""Checks if the input text is present in the whole page.
:param scrapedPage: the HTML string of the page scraped.
:param inputText: the string to look for inside the tags.
:return: True if the text is present in the page, False otherwise
... | a9cbe7e7971e7d2a4c875e0681efc81d4a7e2ead | 663,165 |
import re
def is_unknown_impact(exonicFuncRefGene):
"""
@summary: if no effect known
@param exonicFuncRefGene: [str] The exonic function predicted by RefGene
@return: [int/bool] Rank (10) if is unknown impact; False in other cases
"""
if match_unknown := re.search("unknown", exonicFuncRefGene,... | 4eedd6f086ec6847e593ae389aaea60caf8096cc | 663,166 |
import subprocess
import warnings
def getLuminosity(homedir,minRun,maxRun,isRunBased,verbose):
##############################################
"""Expects something like
+-------+------+--------+--------+-------------------+------------------+
| nfill | nrun | nls | ncms | totdelivered(/fb) | totrecord... | 70eb4520673ba7718e1ea8a8775bda7e1db812a1 | 663,167 |
def _combine_regex(*regexes: str) -> str:
"""Combine a number of regexes in to a single regex.
Returns:
str: New regex with all regexes ORed together.
"""
return "|".join(regexes) | a8488f80345e37a8123111164206f501800c5019 | 663,168 |
def ofp_instruction_from_jsondict(dp, jsonlist, encap=True):
"""
This function is intended to be used with
fluxory.lib.ofctl_string.ofp_instruction_from_str.
It is very similar to ofp_msg_from_jsondict, but works on
a list of OFPInstructions/OFPActions. It also encapsulates
OFPAction into OFPIns... | 5071c826702bf96a52524fd09aba97a332348a08 | 663,169 |
def parse_return(data):
"""
Returns the data portion of a string that is colon separated.
:param str data: The string that contains the data to be parsed. Usually the
standard out from a command
For example:
``Time Zone: America/Denver``
will return:
``America/Denver``
"""
if ... | be91b07aa4ad0e17e6197aa38f7f4b37e8ce50a5 | 663,170 |
import json
def extract_json(text, fields):
"""Extract specified fields from text."""
if not isinstance(fields, list):
fields = [fields]
obj = json.loads(text)
return " ".join([obj.get(field) for field in fields if obj.get(field)]) | 7ef6328caf660c48b1fe947e0cfb4b8338cb5694 | 663,171 |
import subprocess
def get_manager_container_id():
""" Retrieves manager container id
Arguments:
None
Returns:
Manager container id
"""
docker_command = 'docker container ls -q -f name=manager'
id_ = subprocess.check_output(docker_command, she... | 4a78e8e282931d9ef2ab3814c422609d759c58b3 | 663,172 |
def _find_version_line_in_file(file_path):
"""
Find and return the line in the given file containing `VERSION`.
:param file_path: Path to file to search.
:return: Line in file containing `VERSION`.
"""
with open(str(file_path), "r") as fileh:
version_lines = [
line for line ... | ef3e648ac6b4e9f89e67986507eba74ba65ded2d | 663,173 |
def xor_decode(ciphertext, key):
"""
Decode some ciphertext with the given key with XOR algorithm
ciphertext: the ciphertext to decode (as a string)
key: the key to use (array of ints representing ASCII codes)
"""
return "".join([chr(c ^ key[index % len(key)]) for index, c in enumerate(ciphertex... | 6136df5afe9f7303129cb440fc7b0d05ec9751bf | 663,174 |
def all_but_last(items):
"""Return a tuple of all but the last item in items.
>>> all_but_last([1, 2, 3, 4])
(1, 2, 3)
"""
return tuple(items[0:-1]) | 1b13cb2074198cd8351dbbc16561ad33a86a08ed | 663,175 |
def flex_load_capacity_rule(model, geography, timepoint, feeder):
"""
Maximum flexible load that can be shifted to a given timepoint.
"""
if feeder == 'bulk':
return model.Flexible_Load[geography, timepoint, feeder] == 0
else:
return model.min_flex_load[geography, feeder] <= model.Fl... | bacd1aa58b572069c918eff75dacad56c4df5d68 | 663,176 |
def pudl_etl_parameters(etl_settings):
"""Read PUDL ETL parameters out of test settings dictionary."""
return etl_settings.datasets | c89bfa8087611e5c6106117131383ad1d42b4399 | 663,177 |
def decorate_class(cls, decorator, exclude=[], *args, **kwargs): # pragma: no cover
"""
Decorates a class with a give docorator. Returns a subclass with
dectorations applied
Parameters
----------
cls : Class
A class to be decorated
decorator : callable
callable to... | a9509f778ace2c643cd3e3cb89380c445e6dc407 | 663,178 |
import os
def _path_is_relative(pth):
""" is this a relative path?
"""
return os.path.relpath(pth) == pth | 45fc557dc8d21bb1111f7db6d1baeab9f0a3baa9 | 663,179 |
def make_rid_index_mapper(rids_index):
"""
Parameters
----------
rids_index :
Returns
-------
"""
return (
rids_index.to_series(index=range(1, rids_index.shape[0] + 1), name="rids")
.reset_index()
.set_index("rids")
.iloc[:, 0]
) | 9dc71cc90f9f2e4776b32cfa0c540013b5c53ff9 | 663,180 |
import threading
import queue
import contextlib
def pool(builder, size, timeout=None):
"""Create a pool that imposes a limit on the number of stored
instances.
Args:
builder: a function to build an instance.
size: the size of the pool.
timeout(Optional[float]): the seconds to wait... | 42f72e88d6fa3b811240d82e8462a1785e3090fa | 663,181 |
import getpass
def get_user(lower=True):
"""
Returns the current user
:param lower: bool
:return: str
"""
username = getpass.getuser()
return username.lower() if lower else username | b1bae74d2dfde860c931a05d56e4f84e4f2386e1 | 663,182 |
import os
def find_highest_export(exportsfolder):
"""Sort through the export directory to all exported subdirectories
and find the most recent export"""
# assume that the current folder is the highest folder
highest = max([os.path.basename(next_dir)
for next_dir in os.sca... | e0de922835ab859c83452eb8afa3ec46179f3820 | 663,183 |
def get_img_height() -> int:
"""
Auxiliary method that sets the height, which is fixed for the Neural Network.
"""
return 32 | 6c2336f8468397e828f3afa52efa01cc4ecd82d6 | 663,185 |
def scale_dimensions(dic, size=2):
""" for mac retina displays """
for x in dic:
dic[x] = int(dic[x] * size)
return dic | dc11b0231d5ed70757051a312ee8949646d4b508 | 663,186 |
def moveRowDimension(obj, i, j, numrows, numcols, section, more, custom):
"""Move a row in front of another row.
Note that this will change the nesting hierarchy
parameters:
from: row number to move from
to: row number to move to
Default action interchanges the first two columns of the row label... | 6bef8a01a289a4132d824b5b3b6f254eccb3bbdb | 663,187 |
def _option_boolean(arg):
"""
Check boolean options.
"""
if not arg or not arg.strip(): # no argument given, assume used as a flag
return True
if arg.strip().lower() in ("no", "0", "false"):
return False
if arg.strip().lower() in ("yes", "1", "true"):
return True
rai... | 7d649f8b435f8cfecee9ece94fcb5191e8b86bba | 663,188 |
import re
def cleantext(msg):
""" Clear text from malicius data """
return re.sub(r"[^a-z|A-Z|0-9|?| |'|!|?|_|-|,|.]", "", msg) | 55aa07ee6de95c5d42c2f9bf300480aced444cf0 | 663,189 |
def csv_format_cuts(cuts):
"""flattens and formats cuts for CSV file"""
# cut_branches = []
# cut_bounds = []
cut_flat = []
for c in cuts:
cut_flat.append(c[0])
cut_flat += c[1:3]
# return cut_branches, cut_bounds
return cut_flat | 13d1c2ddc809be8bb1f416b48765e9daa63ec547 | 663,190 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.