content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def rowcol_to_cell(row, col, row_abs=False, col_abs=False):
"""Convert numeric row/col notation to an Excel cell reference string in
A1 notation.
"""
d = col // 26
m = col % 26
chr1 = "" # Most significant character in AA1
if row_abs:
row_abs = '$'
else:
row_abs = ''... | 1bb1c8559421cc769fb45fe5014fe12da4e895f4 | 623,338 |
def autolabel(dropdown):
"""Automatically set Dropdown label on_click"""
def callback(event):
for label, _value in dropdown.menu:
if event.item == _value:
dropdown.label = label
dropdown.on_click(callback)
return callback | 69c228ccefe15474d30b8d42314f2d76f5964314 | 623,340 |
import re
def caml_to_snake(word):
"""Convert a string written in CamlCase to a string written in snake_case.
Args:
word (str): Input string.
Returns:
str: Output string.
"""
return re.sub(r'(?<!^)(?=[A-Z])', '_', word).lower() | f04121c6ebdc14851a36b82dee06e40ade55c18d | 623,341 |
import itertools
import random
import socket
def find_open_port(ip, port, n=50):
"""Find an open port near the specified port"""
ports = itertools.chain((port + i for i in range(n)),
(port + random.randint(-2 * n, 2 * n)))
for port in ports:
s = socket.socket(socket.AF... | bfcdf33d36b2e1cdbd51cfb1535b6693917a9996 | 623,343 |
import types
def patch_method(obj):
"""
Patch method for given class or object instance.
If a class is passed in, patches ALL instances of class.
If an object is passed in, only patches the given instance.
"""
def decorator(method):
if not isinstance(obj, object):
raise Va... | 61eb2ced6c2b6aacd1305b883b03f31149dbf7ac | 623,345 |
def _nullable_list_symmetric_difference(list_1, list_2):
"""
Returns the symmetric difference of 2 nullable lists.
Parameters
----------
list_1 : `None` or `list` of ``DiscordEntity``
First list.
list_2 : `None` or `list` of ``DiscordEntity``
First list.
Returns
... | b0d44674f0c32f1909c52d5bf0b617dfb7d2547d | 623,346 |
import re
def nmap_handle_special(tmp_file):
"""
This function returns the open ports from nmap scan output file
:param tmp_file: the file to grep open ports from
:return: a list of open ports
"""
for line in open(tmp_file):
if "Ports" in line:
line = line.split("Ports")[1]... | 8a5edea70c95ebb1d80d41df16ea328751c57a91 | 623,347 |
def pycode(msg: str):
"""Format to code block with python code highlighting"""
return f'```py\n{msg}```' | 9df1e3aabe22bc129ee47e3c5e9bf140c52c2d4b | 623,349 |
def list_user_policies(iam_client, user):
""" List IAM user policies """
return iam_client.list_user_policies(UserName=user) | dd37e23fc21683dca89316aced12b446294cfb7a | 623,350 |
def bit(value: int, byte: int, position: int) -> int:
"""Encode a bit value
:param value: Value to encode
:param byte: The byte to apply the value to
:param position: The position in the byte to set the bit on
"""
return byte | (value << position) | 8708e295cb358a87b1aafe4d2881568088d434f5 | 623,351 |
def is_DER_sig(sig: bytes) -> bool:
"""Checks if the data is a DER encoded ECDSA signature
https://bitcoin.stackexchange.com/questions/92680/what-are-the-der-signature-and-sec-format
:param sig: Potential signature.
:type sig: bytes
:return: True if the passed in bytes are an ECDSA signature in ... | 8b71b8944bff77fbec793ba19b51f8b622d1a158 | 623,355 |
def make_safe_for_html(html):
"""Turn the text `html` into a real HTML string."""
html = html.replace("&", "&")
html = html.replace(" ", " ")
html = html.replace("<", "<")
html = html.replace("\n", "<br>")
return html | 18feac5e745bc86a51829bd7b1a7c4d73c15f1c9 | 623,356 |
def handle_command_line(argument_parser):
"""
Take command line arguments, check for issues, return the arguments.
Args:
`argument_parser` (`argparse.ArgumentParser`): The argument parser that is \
returned in `create_cmd_arguments()`.
Returns:
(`argparse.NameSpace`): c... | 22a94caec6553bc94d236935837c05adc91a3be9 | 623,363 |
import csv
def write_output_csv(output_csv_path, data, csv_type):
"""
Accepts a dictionary of rows and writes a new CSV
Columns should be: ID, chromosome_name, start_position, end_position, strand, padj, log2FoldChange
"""
count = 1
# Open a second output file and write only unique rows
w... | 3c73f73283c693ec887f545aafd889d9ea673526 | 623,364 |
def add_edge(locations,edge):
"""
Add edge to list of locations, returning a list of edge-added locations
"""
if edge != None:
return [tuple([i+j for i,j in zip(edge,l)]) for l in locations]
return locations | 6de81b525194ac6cb848de4e3997d2552d2976a1 | 623,365 |
def winning_player(players, payoffs):
"""
The index of a winning player from a pair of payoff values
Parameters
----------
players : tuple
A pair of player indexes
payoffs : tuple
A pair of payoffs for the two players
Returns
-------
integer
The index of the... | a33b33b0dccfdf53f44ad056e255bc8a4d99189c | 623,366 |
def ClassicalRegister_to_c(self):
"""Syntax conversion for creating a classical register."""
return f'int {self.name}[{self.size}];'+"\n"+f'for (int i = 0; i < {self.size}; i++) {self.name}[i] = 0;' | c4c2372c660b232778ede25244a774f1273e7fba | 623,368 |
from bs4 import BeautifulSoup
from datetime import datetime
def parse_html(html):
"""Parse FX html, return date and dict of {symbol -> rate}"""
soup = BeautifulSoup(html, 'html.parser')
# <h4>Date: <i class="date">2019-11-11</i></h4>
i = soup('i', {'class': 'date'})
if not i:
raise ValueE... | 174652860acbcb5f1bd120ee6544870c151bf8b5 | 623,372 |
def document_config_types(agent_config_dict):
"""
Returns a single string containing all available config types,
for Docs team to reference.
"""
return 'Available config types: \n\n' + '\n'.join(agent_config_dict.keys()) | 60454caedaeab1e9b5223902d24e7aaaa43a9b67 | 623,377 |
def calc_gc(sequence):
"""
Calculates GC percentage from DNA sequence
Does not consider IUPAC ambiguity codes
:param sequence:
:return: float
"""
if len(sequence) == 0:
raise ValueError("Sequence must have minimum length 1")
gc = 0
for char in sequence:
if char.upper(... | 72d586911142ce8a93a2c19e87b4d55d00d01115 | 623,382 |
def line_preformatter(line: str) -> str:
"""Preformats a line to be better readable by `ast.literal_eval()`
Args:
line (str): Input String from SQL File
Returns:
str: Formatted string with special replacements
"""
# <!-- Clear comments -->
#line = line[:line.find('--')]
# <... | 10d043a896ec6d39b108ec0460c2896c105c4a21 | 623,386 |
def hex_switchEndian(s):
""" Switches the endianness of a hex string (in pairs of hex chars) """
pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
return b''.join(pairList[::-1]).decode() | 055b677ec5a6eeddf3d2381da0ccacdde227dfb0 | 623,387 |
def _AndroidAbiToCpuArch(android_abi):
"""Return the Chromium CPU architecture name for a given Android ABI."""
_ARCH_MAP = {
'armeabi': 'arm',
'armeabi-v7a': 'arm',
'arm64-v8a': 'arm64',
'x86_64': 'x64',
}
return _ARCH_MAP.get(android_abi, android_abi) | 28371fd991f3dd4a2659ffa6c37d56dcaeedf782 | 623,388 |
def wait_for_task(task):
""" wait for a vCenter task to finish """
task_done = False
while not task_done:
if task.info.state == 'running':
pass
if task.info.state == 'success':
return task.info.result
if task.info.state == 'error':
print ("there ... | d16d90a597748a9dab0306193d1e26c4d4cde91d | 623,389 |
import itertools
def groupby(itr, key_fn=None):
"""
An wrapper function around itertools.groupby to sort each results.
:param itr: Iterable object, a list/tuple/genrator, etc.
:param key_fn: Key function to sort `itr`.
>>> import operator
>>> itr = [("a", 1), ("b", -1), ("c", 1)]
>>> res... | 8ffc6b69b3891468505f98b0608e65f4a265a55d | 623,392 |
def cropping_center(x, crop_shape, batch=False):
"""Crop an input image at the centre.
Args:
x: input array
crop_shape: dimensions of cropped array
Returns:
x: cropped array
"""
orig_shape = x.shape
if not batch:
h0 = int((orig_shape[0] - crop_shape[0])... | 3c05077017e06e73a92f9fded47ed5d304811079 | 623,394 |
from typing import List
import inspect
def _get_function_params(function) -> List[str]:
"""
Returns the list of variables names of a function
:param function: The function to inspect
:rtype: List[str]
"""
parameters = inspect.signature(function).parameters
bound_arguments = [
name... | 78985d40b02847f721547ebb9ff82d9c85ccba13 | 623,400 |
def ith_bit(x: int, i: int) -> int:
"""
Return the i-th bit of the input parameter.
LSB has index 0, MSB has the greatest index (31 for a word).
:param x: A number.
:param i: The bit index.
:return: The ith-bit of x.
"""
assert i >= 0 # Do not support negative indexes, ATM
return (... | 1c39cdfc4ff24468161f3c1e56d676f45c0887f3 | 623,408 |
def base_name(var):
"""Extracts value passed to name= when creating a variable"""
return var.name.split('/')[-1].split(':')[0] | 9aa33c008fcb8957d51697b25a2ae53aeb250d97 | 623,410 |
def _split_value_units(raw_str):
"""Take a string with a numerical value and units, and separate the
two.
Args:
raw_str (str): the string to parse, with numerical value and
(optionally) units.
Returns:
A tuple (value, units), where value is a string and units is
either ... | c0d377b3ad7fdf393d152a7d6d809c4b211aaea4 | 623,411 |
from datetime import datetime
def get_media_insert(media, event):
"""
Gets all insertion data for a single media object
Parameters
----------
media: dict
Dictionary object of a media object
event: str
Event name of query the media was retrieved from
Returns
-------
... | 98f429c2a2570e39372ae1956a00c9a3f1c6d398 | 623,412 |
def lotkavolterra(y, t=0, a=1, b=1, c=1, d=1):
"""Lotka-Volterra predator prey model
"""
prey, pred = y
dydt = [a * prey - b * pred * prey,
c * pred * prey - d * pred]
return dydt | d4cf04fe1df489b80109502d5b59ddf64b69e65f | 623,413 |
def extract_from_dict(data, path):
"""
Navigate `data`, a multidimensional array (list or dictionary), and returns
the object at `path`.
"""
value = data
try:
for key in path:
value = value[key]
return value
except (KeyError, IndexError):
return '' | e228678722226289e9cc2e1e1be8aa751159746e | 623,415 |
import requests
def get_current_version(election_id: str, state_code: str) -> str:
"""Checks the base website to get the current data version number for later
data download"""
current_version_url = f"https://results.enr.clarityelections.com//{state_code}/{election_id}/current_ver.txt"
r = requests.g... | 7c10dd38bb1ff995a21bbb094091d5a14f017a68 | 623,418 |
import torch
def get_constraint(w, reg_type=1, beta=0.7):
"""
Input:
- w (1D torch tensor): weights
- reg_type (integer): id for the type of regularization
- beta (float): beta for regularization corresponding to reg_type=2
Output:
- Values of the regularization constraint (reg_value)... | 8e0853649daf8df8e51ff2bb45742645c036d44b | 623,420 |
import time
def random_time_range(start, end, file_format, prop):
"""Get a time at a proportion of a range of two formatted times.
start and end should be strings specifying times formated in the
given format (strftime-style), giving an interval [start, end].
prop specifies how a proportion of the in... | 40d8e84b2d2c44d932967430a7e585f287a1ac9b | 623,421 |
from datetime import datetime
def update_date_of_sale(date_input):
"""
Update date format from DD/MM/YYYY to YYYY-MM-DD
"""
current_format = datetime.strptime(date_input, "%d/%m/%Y")
new_format = current_format.strftime("%Y-%m-%d")
return new_format | 84a4da8bc9b44b30331cbccef2a7019c63bb6709 | 623,427 |
import time
def decode_tag(tag, time_format):
""" Return prefix and time represented by playlist tag.
Args:
tag ::: (str) playlist tag to decode
time_format ::: (str) format specifier for `time.strftime`
see http://strftime.org/
Returns:
prefix ::: (str) un... | 9cccb6dffc5e3d75095e1e3049f8b965d6b6ec3d | 623,428 |
def inclusion_one_param_from_template(arg):
"""Expected inclusion_one_param_from_template __doc__"""
return {"result": "inclusion_one_param_from_template - Expected result: %s" % arg} | 9c4e4f842faaf87f7d328515fbe96ef9d1be2208 | 623,431 |
import yaml
def load_config(config_path):
"""
Loads a YAML config file and returns data as a nested dictionary.
"""
with open(config_path, 'r') as f:
config = yaml.safe_load(f)
return config | 3ce4473094173d0860b2220e792e681a98095d3a | 623,437 |
def merge(items1, items2):
"""Merge given lists of items, each assumed to already be in sorted order,
and return a new list containing all items in sorted order.
Running time: O(n) Passes over each element once
Memory usage: O(n) Makes a new list for all the elements
"""
ind_1, ind_2 = 0, 0
... | 3fa477a93d3aed5337a2b62a516b653b88929d30 | 623,441 |
def compose1(f, g):
""""Return a function h, such that h(x) = f(g(x))."""
def h(x):
return f(g(x))
return h | 1613e41cf70446755586b4edf0093c1ed75c3915 | 623,442 |
def get_resource_identifier(iot_finding):
"""Get resource name from IoT device Defender finding"""
resource = iot_finding['nonCompliantResource']['resourceIdentifier']
if list(resource.keys())[0] == "policyVersionIdentifier":
return resource["policyVersionIdentifier"]["policyName"]
else:
... | 44ccd6519c79b4a69f9fe34eec0ca400368e8929 | 623,443 |
from typing import Optional
from typing import Any
def ifnone(item: Optional[Any], alt_item: Any) -> Any:
"""Return ``alt_item`` if ``item is None``, otherwise ``item``."""
return alt_item if item is None else item | d0bf78a5a3de54b350bfa60b9d2aa1b909c94f80 | 623,448 |
def _clean_dict(my_dict):
""" Remove empty entries from dictionary """
return dict((k, v) for k, v in my_dict.iteritems() if v) | 11b9cf22f54b2facfb03f5362dd6248fc66a8c3d | 623,450 |
import re
def checkIPAddr(ipAddr: str) -> bool:
"""
Check IP Address
Parameters
----------
ipAddr: str
IP Address from UI
Returns
----------
boolean
"""
pattern = r'\d{1,3}'
lst_ipAddr = ipAddr.split('.')
if len(lst_ipAddr) != 4:
print('numb... | a73c3699d01186177f92625cee755b98aebbccb1 | 623,453 |
def _ScoreRequested(params):
"""Returns True if match scoring requested, False otherwise."""
return params.has_scorer_spec() and params.scorer_spec().has_scorer() | 64b09f426a6249c4c6c953bcb5dac2ace287e464 | 623,454 |
def num_unique_objects(df, obj_frequencies):
"""Total number of unique object ids encountered."""
del df # unused
return len(obj_frequencies) | 60857ecee53efaa5de243ffd6163c5dd3d63982d | 623,459 |
def is_staff(request):
"""Returns whether or not the request's user is an authenticated staff member."""
return request.user is not None and request.user.is_staff and request.user.is_authenticated() | fa4b26f4dd45926f48f0deb85fde09a82e87f6f8 | 623,462 |
import re
def remove_spacing(query: str) -> str:
"""Take an SQL query string and return with single spaces, except at the
beginning and end of the string.
"""
query = re.sub(r'\s+', ' ', query)
query = re.sub(r'(^\s|\s$)', '', query)
return query | d92852132ed09d3612e01a7a7f9b79b229739021 | 623,472 |
from datetime import datetime
def changeTimestampToDate(timestamp):
"""
Méthode permettant de changer un timestamp en date de forme AAAA-MM-JJ-HH-MM-SS
:param timestamp: le timestamp à convertir
:return: la date obtenue
:raises TypeError: Exception levée si le paramètre n'est pas un integer
"... | a94f5c3dae61bc0290f287f06bbeb455c6d9c96a | 623,473 |
def two_dec(num: float) -> str:
"""Format a floating point number with 2 decimal places."""
return "{0:.2f}".format(num) | beeebd8a06f049f16e25f9ff14f10ed5681d11b1 | 623,475 |
def utilization_to_state(state_config, utilization):
""" Transform a utilization value into the corresponding state.
:param state_config: The state configuration.
:type state_config: list(float)
:param utilization: A utilization value.
:type utilization: number,>=0
:return: The state corres... | e93254c5c7c50b9136f0ca0759a233e09481af45 | 623,477 |
import itertools
def basis_labels(n):
"""
Generate a list of basis labels for `n` qubits, ordered from least to greatest, in big-endian
format:
['00..00', '00..01', ..., '11..11']
:param n:
:return: A list of strings of length n that enumerate the n-qubit bitstrings
:rtype: list
... | a677c74f36cf89089a34ecb8b731c2b4a76f77fe | 623,478 |
def get_auth_server_info(environ):
"""
Return some info about the available auth servers.
"""
auth_server_info = []
auth_servers = environ['tiddlyweb.config'].get('oauth.servers')
for server in auth_servers:
server_info = auth_servers[server]
auth_server_info.append({
... | 03998beb1cb8540f687922975d00a626e416f3dd | 623,480 |
import re
def clean_filename(filename):
"""
Remove non-alphanumeric characters from filenames.
*Parameters*
filename : str
The filename to be sanitized.
*Returns*
clean : str
A sanitized filename that contains only alphanumeric
characters and underscores.
"""
... | 99b355c5df26a7e5ba97d5001dd32bb64576d5e8 | 623,485 |
def get_first(values: list):
"""
Function that takes in a list and returns the first value (and the .text attribute if it exists), otherwise returns nothing
@param values: list that contains 0-many results
@returns: the first item of the list or None
"""
out=None
if len(values) > 0:
... | e6d7fa949b30fff3a9f48945b47a7624c9168988 | 623,487 |
def function_maker(func):
"""Wraps a function to return [params, f(params)]"""
def f(params):
try:
r = func(**params)
except Exception as e:
r = e
return [params, r]
return f | ba1add09c09b924db27500f04c0c3938e3940e93 | 623,489 |
from typing import Tuple
def extended_euclid(a: int, b: int) -> Tuple[int, int, int]:
"""
Extended Euclidean Algorithm
:param a: integer
:param b: integer
:return: The gcd of a and b, and x and y such that ax + by = gcd(a, b)
"""
if a == 0 and b == 0:
return 0, 0, 0
equation1... | db191cdfb2e325d88930c9954cf94c942153f3bd | 623,490 |
def nonterminal_graph_edge_constraints(new_edges, init_source_side):
"""
Ensure that the new non-terminal rule respects edge constraints:
1. No edges should originate from subtracted part of the graph
2. All edges in the new graph should connect to no more than one distinct node in the subtracte... | dc8cf530c93ac5100b548f4d04059497492b2912 | 623,491 |
import torch
def NEG_INF_DIAG(n, device):
"""Returns a diagonal matrix of size [n, n].
The diagonal are all "-inf". This is for avoiding calculating the
overlapped element in the Criss-Cross twice.
"""
return torch.diag(torch.tensor(float('-inf')).to(device).repeat(n), 0) | 0c635e62078524532da803937331909bd035c9b6 | 623,492 |
def count_by_activity(contract_json):
"""
Given a full JSON contracts dictionary, return a new dictionary of counts
by activity.
"""
by_activity = contract_json['contracts']
activities = by_activity.keys()
return dict(zip(activities, [len(by_activity[a]) for a in activities])) | 61ae1d6329e518d377169ec8e0fa58f671f9b5b8 | 623,494 |
import random
def __randomInt(limit: int) -> int:
""" Return a random between 1 and limit """
return random.randrange(1, limit) | b4087d485fb561ab7c77e64dd28b7c4b9c1701e3 | 623,495 |
def format_decimal_value(value):
""" Format number as string, limiting decimal length based on value
Input:
- value: Integer or float
Output: String containing converted value
"""
if value > 1:
# Format as 3 point decimal for smaller amounts
return "{:0.3f}".format(value).r... | 0c0cd49f6766a85775e5211dcd18c6b212f64146 | 623,500 |
def number_to_20_cen_year(number):
"""
Convert "1" to "2001", "21" to "2021" etc.
:param number: int
:return: formatted year
"""
year = "2000"[:len("2000")-len(str(number))] + str(number)
return year | 4003f6bde312863a8f8ba20348ac4df1e9867273 | 623,501 |
def strip_query(path):
"""Strips query from a path."""
query_start = path.find('?')
if query_start != -1:
return path[:query_start]
return path | 05245f7fead449431e5af0007ad61da42b3ac246 | 623,505 |
def return_chopped_list(inputlist, left_index=0, right_index=64):
"""Input a list of strings and return a new list of strings that have
been sliced by the left and right index values (int).
"""
newlist = []
for item in inputlist:
newlist.append(item[left_index:right_index])
return newlis... | 624c9d18a6e10fd3dc1865e842b6cd9ab472014e | 623,507 |
def get_gender_from_label(gender):
"""
Method to get the passed gender in XNAT format
:param gender: gender selected
:return: value accepted by xnat: 'female' or 'male'
"""
if gender.lower() in ['female', 'f']:
return 'female'
elif gender.lower() in ['male', 'm']:
return 'ma... | a9a760dbedbd24bf9b8a89623685bf705e579db8 | 623,510 |
def flatten(l):
"""
Flatten a list of lists into a plain list
:param l: list to flatten (list)
:return: list flattened (list)
"""
return [item for sublist in l for item in sublist] | 7a08d410e5addb53030982e5542bef7d03f9f1d4 | 623,512 |
def sweep_config_err_text_from_jsonschema_violations(violations):
"""Consolidate violation strings from wandb/sweeps describing the ways in which a
sweep config violates the allowed schema as a single string.
Parameters
----------
violations: list of str
The warnings to render.
Returns... | ddd3700b9a55be44063b55f767963b6ebb7ba58a | 623,513 |
def conv19bitToInt32(threeByteBuffer):
""" Convert 19bit data coded on 3 bytes to a proper integer (LSB bit 1 used as sign). """
if len(threeByteBuffer) != 3:
raise ValueError("Input should be 3 bytes long.")
prefix = 0;
# if LSB is 1, negative number, some hasty unsigned to signed conversion to do
if ... | 59fdfa92ae14b29740047ecabaa214323d7ad44c | 623,514 |
def _q_stop(query_seq, q_seq):
"""
returns the ending python string index of query alignment (q_seq) in the query sequence (query_seq)
:param query_seq: string
:param q_seq: string
:return: integer
"""
q_seq = q_seq.replace("-", "")
q_start = query_seq.find(q_seq)
q_stop = q_start ... | 7c5ec336493154f6f6a5a31c41330b6c5d58986b | 623,517 |
import requests
def get_random_quote(quotes_api_url, quotes_api_key):
""" Get a random quote from quotes api. """
headers = {"Authorization": "Bearer {}".format(quotes_api_key)}
res = requests.get(quotes_api_url + "/quotes/random", headers=headers)
data = res.json()
return data | 3e1ab3052f9b8e7f8c5167de1b3f89f6353d9755 | 623,518 |
from typing import List
from pathlib import Path
def get_files(directory: str, extension: str) -> List[str]:
"""
Get a list of files with a given extension.
:param directory: path to directory.
:param extension: extension for file filtering -
only files with this extension will be preserved.
:... | 2349c4a334a80f39b0ec50582a3b06eeb6d351a7 | 623,519 |
import re
def delete_useless(statement: str) -> str:
"""
無駄な移動/計算を相殺、削除
>>> delete_useless("+++--<<>>>")
'+>'
>>> delete_useless("---++>><<<")
'-<'
>>> delete_useless(">++++[-][-]")
'>[-]'
>>> delete_useless(">--[-]++[-]")
'>[-]'
"""
while True:
if "<>" in stat... | 3bd2b63f0634b53360c18637029a27eb30957c91 | 623,522 |
def get_min_key(d):
"""Return the key from the dict with the min value."""
return min(d, key=d.get) | a5204125ff29140b14e11dd0a2b1b9e18564c024 | 623,527 |
def standard_event_metrics_to_list(standard_event_results):
""" Converting standard event metric results to a list (position of each item is fixed)
Argument:
standard_event_results (dictionary): as provided by the 4th item in the results of eval_events function
Returns:
list: Item order: 1... | 5b12840f4d2e539086ba60d7897fb3a5b5a76de2 | 623,532 |
def remove_first_word(string):
"""Remove the first word of the line.
:param str string: string
:rtype str
:return: string without the first word
"""
return string.split(' ', 1)[1].strip() | 8b23bae07e902ca3e31b40317d5c0ae8c13b852b | 623,533 |
import re
def extract_adquisition_rate(line):
"""Extracts the adquisition rate in Hz from the line of text that
is supposed to contain that information. Raises an exception if it is not
found.
INPUT:
line: string, file line containing a number followed by "Hz".
OUTPUT:
integer.
... | a16f6acc955c45cf19f64739ada859d172f7c47d | 623,534 |
def get_approving_reviewers(props):
"""Retrieves the reviewers that approved a CL from the issue properties with
messages.
Note that the list may contain reviewers that are not committer, thus are not
considered by the CQ.
"""
return sorted(
set(
message['sender']
for message in props... | 3153b1c3e50292f7f5aace70843d3f910f4fefb8 | 623,536 |
def parseLines(text):
"""Returns a list of lines from the given text. Understands end-of-line escapes '\\n'"""
lines = text.strip().split('\n')
esclines = []
esc = False
for l in lines:
if esc:
esclines[-1] = esclines[-1]+l
else:
esclines.append(l)
if... | 1c7fb60a5f9051bbb80bfcf53d6d7d6a1c686210 | 623,541 |
from typing import MutableMapping
from typing import Any
def flatten_dict(
d: MutableMapping[str, Any], *, parent_key: str = "", sep: str = "."
) -> dict[str, Any]:
"""Flatten a nested dictionary by separating the keys with `sep`.
:param d: Dictionary to be flattened.
:param parent_key: Key-prefix (s... | 0d248bb1de45d68d041e761b778c7e089ad45618 | 623,542 |
def get_varying_levels(df, is_index=True):
"""Return the name of the levels that are varying in multi index / columns."""
if is_index:
levels, names = df.index.levels, df.index.names
else:
levels, names = df.columns.levels, df.columns.names
return [n for l, n in zip(levels, names) if len... | 821426e29e9dbc0f0d58522b0f33a9d7fc9bfb77 | 623,543 |
from typing import List
def add(a: List[int], b: List[int]) -> List[int]:
"""
Adds two lists of bits together. When summing bits, they are added from
left to right. For that reason, a reverse range is used to iterate through
the bits backwards. The resulting bits are then reversed after addition to
... | eb016c0f63e8f1e2bdd2ac5d4fb6d823d1af01e0 | 623,548 |
def normalise_value(value):
"""
Default normalisation of value simply returns the value as is.
Custom implementations can normalise the value for various storage schemes.
For example, converting datetime objects to iso datetime strings in order to
comply with JSON standard.
"""
return value | 745575c591ca4740f60a5972e76a721b42f5bc42 | 623,551 |
def beta_mean(x,y):
"""Calculates the mean of the Beta(x,y) distribution
Args:
x (float): alpha (shape) parameter
y (float): beta (scale) parameter
Returns:
float: A float that returns x/(x+y)
"""
output = x / (x+y)
return output | 24cbb908cff98886b11443fb5a6b8603731ecc3b | 623,552 |
def ebs_settings_validator(param_key, param_value, pcluster_config):
"""
Validate the following cases.
Number of EBS volume specified is lower than maximum supported
Parameter shared_dir is specified in every EBS section when using more than 1 volume
User is not specifying /NONE or NONE as shared_d... | 45dceff9a34bb9e8b6e1013a9775bcaaad1e4876 | 623,553 |
def get_s3_index_arn(bosslet_config):
"""
Get arn of the DynamoDB s3 index.
Args:
bosslet_config (BossConfiguration): target bosslet
Returns:
(str):
"""
names = bosslet_config.names
dynamo = bosslet_config.session.client('dynamodb')
resp = dynamo.describe_table(TableNam... | bb3084b7506feeaa869f7dcdcc6f8ef2a133f799 | 623,554 |
def represents_int(s):
"""Judge whether string s represents an int.
Args:
s(str): The input string to be judged.
Returns:
bool: Whether s represents int or not.
"""
try:
int(s)
return True
except ValueError:
return False | 6e318d5df6ac2160047fddb188e26a8f6c42a2f6 | 623,555 |
import string
import random
def random_text(length: int, alph: str = string.ascii_letters + string.digits) -> str:
""" Generates random string text
:param int length: length of text to generate
:param str alph: string of all possible characters to choose from
:return str: generated random string of s... | 61b69634efa4bb6edcfd223689798d9004b2b38f | 623,556 |
def select_top_address_candidate(geocode_candidate_response_json):
"""
Selects the geocoded address candidate with the highest score
:param geocode_candidate_response_json: JSON object containing address candidates
returned from the ArcGIS Geodcoding API
:return: Dict containing address string ... | e5fb7b6adb8c348dbbea56c6e56d2467ecf53f91 | 623,560 |
def start(producers):
"""
Take a list of actors and call their "run" function remotely (as in ray so in parallel).
The returned object can be used to wait for the completion of the tasks with ray.get.
"""
return [producer.run.remote() for producer in producers] | 48b784635d1b855ffeb1e5fd87900c42ca0c970c | 623,561 |
def number_of_nonzero_coef(X, model):
"""
Calculates the number of non-zero coefficients in a model. Useful for
evaluating models with an L1 penalty.
Parameters
----------
X : numpy array or pandas dataframe
The design or feature matrix.
model : sklearn object, or similar
Th... | 48ba44193d91e953ad6e2935091585d363fbeb6d | 623,562 |
from typing import List
def flatten(list_of_lists: List[List]) -> List:
"""Reduce a lists of lists to a list, comprehensively
>>> assert flatten([[1, 2], [3, 4]]) == [1, 2, 3, 4]
Thanks to Alex Martelli at
https://stackoverflow.com/a/952952/500942
"""
return [item for list_ in list_of_li... | ad9f3045bc7d4045a8a4a8c69e54333a71f88b5e | 623,563 |
def is_variable(v):
"""Returns if input is of variable type."""
return type(v).__name__ == 'Variable' | 3646dab431dc0715a3ffcb9a9fe8f98a7ae0ed44 | 623,568 |
def get_args_command_name(layer: int):
"""Return the specified layer's command name"""
return "__layer{layer}_command".format(layer=layer) | 3051ed9d5139a57ddc10d0d40c5457285ca006cf | 623,573 |
def flux(im):
"""Total flux of the image (M00)"""
return im.sum() | bdca0b0766e2c18f5734198dc5c3a7d54df2cb6c | 623,574 |
def get_all_padj_and_log2FoldChange_keys(keys_list: list, identify: str, split: str = '_') -> dict:
"""
:param keys_list: 最开始的所有的键列表
:param identify:padj和logkey 的标识符
:param split: 键名的分隔符
:return: {"DK_vs_CT_log2FoldChange": "DK_vs_CT"}
"""
result = {}
for i in keys_list:
if str(i... | e81c13f89a8ec30f4458a1039ec304a5e6fc630d | 623,575 |
def roe(net_income, average_equity):
"""Computes return on equity.
Parameters
----------
net_income : int or float
Net income
average_equity : int or float
Average total equity
Returns
-------
out : int or float
Return on equity
"""
return net_income / a... | 947f0623987395ecea199fb42eb32e76763a592a | 623,577 |
def param_string_to_dict(param_str, delim='|'):
"""
Reverse of the dict_to_param_string() function.
Note that this will not completely rebuild a dict() after being serialised as a param_string: any '=' or
{delim} characters get eaten by dict_to_param_string().
:param param_str: str
:return: di... | fa33b5f20fcbb923a567a30872dbd8836c7d460d | 623,579 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.