content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def rest(s):
"""Return all elements in a sequence after the first"""
return s[1:] | 268d56ff3a24b3a5c9b1e4b1d1ded557afcdce8c | 29,266 |
def add_int(x, y):
"""Add Integers
Add two integer values.
Parameters
----------
x : int
First value
y : int
Second value
Returns
-------
int
Result of addition
Raises
------
TypeError
For invalid input types.
"""
if not isins... | 7544a6ddb97567364233bb5ce4d335669644f82e | 185,422 |
def parse_labels_mapping(s):
"""
Parse the mapping between a label type and it's feature map.
For instance:
'0;1;2;3' -> [0, 1, 2, 3]
'0+2;3' -> [0, None, 0, 1]
'3;0+2;1' -> [1, 2, 1, 0]
"""
if len(s) > 0:
split = [[int(y) for y in x.split('+')] for x in s.split(';')]
e... | d2f77876f1759e6d4093afc720e7631f1b4d9ff4 | 6,879 |
import math
import json
def process_role_options(options):
"""
Parse Lemur options and convert them to Vault parameter in json format.
:param options: Lemur option dictionary
:return: All needed parameters for Vault roles endpoint in json formatted string.
"""
vault_params = {'allow_subdomains... | ddd437b25ed2adc49480ebd2efa20702f8abf042 | 230,330 |
def enum(*sequential, **named):
""" Enum helper to generate integer values
usage: ENUM_TYPE = enum(VALUE, VALUE2, VALUE3)
or: EnumType = enum(VALUE="V1", VALUE2=3)
The result will be VALUE = 1, VALUE2 = 2, etc.
"""
enums = dict(zip(sequential, range(len(sequential))), **named)
retu... | 3f9bc5a9c07c097c5e133d1add7da7091ed8fb89 | 197,555 |
def apply_gamma_transform(value):
"""
Transforms values from linear scale to non-linea by applying gamma
transform.
:param value: Values to be transformed
:return: Transformed values
"""
if value > 0.0031308:
return (pow(1.055 * value, (1 / 2.4))) - 0.055
else:
return 12... | aa1ebd356ce1b05abfa775d17aff379222f47427 | 155,858 |
from unittest.mock import call
def callWithRaise(command):
"""
Executes the command like call() does but then raise OSError it it fails.
"""
status = call(command)
if status:
raise OSError("Failure on cmd: "+command)
return status | 43065baa75d5452306b5a7e3ff4a1f54fda2de98 | 372,719 |
from typing import Union
from typing import List
from typing import Tuple
import torch
def _format_radius(
radius: Union[float, List, Tuple, torch.Tensor], pointclouds
) -> torch.Tensor:
"""
Format the radius as a torch tensor of shape (P_packed,)
where P_packed is the total number of points in the
... | 872eac571be63362a53f04db792cb28e9d2ffeb5 | 186,755 |
def create_duplicate_dictionary(duplicate_file):
"""Creates a lookup dictionary from the WaPo duplicates file
Args:
duplicate_file (file): WaPo duplicates file
Returns:
dict: duplicates lookup dictionary
"""
dup_dict = {}
data_dups = open(duplicate_file).readlines()
for eac... | 9d42b0cca198d92350f9061c6f7a08ff3217e6bc | 353,341 |
def getDiff(child, bar):
"""Calculates the difference in pieces of a chocolate bar to
the requested pieces by a child.
Args:
child: An integer with pieces requested.
bar: An integer with the number of chocolate pieces.
Returns:
An integer value with the difference of the request... | 1b1a09a5aa0e9d8ed1c6ec9637dc4da356dad8d9 | 142,230 |
def HasProperty(entity, property_name):
"""Returns whether `entity` has a property by the provided name."""
return property_name in entity._properties # pylint: disable=protected-access | 0ce2c7fed31777b5d2e269096fe4d3d6d04169fe | 120,994 |
def get_position(table: tuple[str, str], char: str) -> tuple[int, int]:
"""
>>> get_position(generate_table('marvin')[0], 'M')
(0, 12)
"""
# `char` is either in the 0th row or the 1st row
row = 0 if char in table[0] else 1
col = table[row].index(char)
return row, col | 00c2a5cd7a46c546ecbc02fada0da084a09ba068 | 471,130 |
def disappear_angle_brackets(text: str) -> str:
"""
Remove all angle brackets, keeping the surrounding text; no spaces are inserted
:param text: text with angle bracket
:return: text without angle brackets
"""
text = text.replace("<", "")
text = text.replace(">", "")
return text | b8e9efe435f3246a5347d9ce4cbca27a2d85de5e | 445,299 |
def val(section, key):
""" Return value of section[key] in units specified in configspec
Args:
section (:class:`qcobj.qconfigobj.QConfigObj`.Section`): instance
key (string): valid key for `section`
Returns:
values in section[key] converted to units defined in c... | 5b28d7ba9d1abcf42eecaa1af0a3b13f03dd44e6 | 660,953 |
def Set(assignments, callback, *args):
"""Set the stoplight using assignments and a condition callback.
Args:
assignments: A dict mapping returns of the callback to the stoplight value.
callback: The callback to compute the conditional assignment.
*args: Input arguments to the callback functions.
Ex... | 5727810fc9c84a27d259c014ab116d1691a65df6 | 415,203 |
def slug(value):
"""
Slugify (lower case, replace spaces with dashes) a given value.
:param value: value to be slugified
:return: slugified value
ex: {{ "Abc deF" | slug }} should generate abc-def
"""
return value.lower().replace(' ', '-') | 2dbd51d92a0941c6c9b41fc6f9e56eb19b4b8f46 | 581,324 |
def create_contact_person(client, organization_id, contact_id, name, country_code, email=None):
"""
Creates a contact person object in Billy:
https://www.billy.dk/api/#v2contactpersons
"""
contact = {
'name': name,
'email': email,
'isPrimary': True,
'contactId': conta... | e59a663b159c6cbedd83d4719fab2246156ad5ce | 179,583 |
def calculate_cure_rate(confirmed, cure):
"""
计算治愈比例
:param confirmed: 确诊人数
:param cure: 治愈人数
:return: 治愈比例
"""
cure_rate = cure / confirmed * 100
return cure_rate | d866e21d61dcc8262292daffca7d5dc557ebede6 | 570,627 |
import json
def json_matches_list(json_object, mylist):
"""Check if json matches a keyword from a list"""
for item in mylist:
if item.lower() in json.dumps(json_object).lower():
return True
return False | f65dd01f2a929803c4ad454d4804e3d42a80dc3d | 152,776 |
def sort_dict_by_key(dictionary):
"""
Returns the dictionary sorted as list [(), (),].
"""
return sorted(dictionary.items()) if dictionary else None | 3c59ed5906cd15ed68b39e3c3cfe8ecfbcaeb7cc | 352,473 |
def is_context_variable(context, variable_name):
"""
Returns true if the given variable name is in the template context.
Usage::
{% is_context_variable "variable_name" as variable_exists %}
{% if variable_exists %}
...
{% endif %}
"""
return variable_name in co... | 012a855b503b01f3098869f1292aa068c730e45c | 176,890 |
def min_rank(series, ascending=True):
"""
Equivalent to `series.rank(method='min', ascending=ascending)`.
Args:
series: column to rank.
Kwargs:
ascending (bool): whether to rank in ascending order (default is `True`).
"""
ranks = series.rank(method="min", ascending=ascending)
... | a772618570517a324a202d4803983240cb54396b | 705,443 |
import socket
def ipv4(value):
"""Return true if IP address v4 is valid, otherwise - false."""
try:
socket.inet_pton(socket.AF_INET, value)
return True
except socket.error:
return False | cd1722f7df7abfa3fc7ff2e1038439c5e1a17541 | 621,355 |
def forwardsAdditiveError(image, template):
""" Compute the forwards additive error """
return (template - image).flatten() | be5db9313fd38aaab27e6d2caf07d84388d17c2a | 389,021 |
def prime_divisors_sieve(lim):
"""Computes the list of prime divisors for values up to lim included."""
# Pretty similar to totient
div = [set() for i in range(lim + 1)]
for i in range(2, lim + 1):
if not div[i]:
for j in range(i, lim + 1, i):
div[j].add(i)
return... | 90bb793a4f709fdda49e896917bc600b955fb7e5 | 404,910 |
def get_node_demand(nodes, demand):
"""Get demand injections
Parameters
----------
nodes : pandas DataFrame
Node information
demand : pandas DataFrame
NEM region demand
Returns
-------
df_node_demand : pandas DataFrame
Demand at each at each node
... | 1589bd55604fb50545c146dba938aca4ad401283 | 290,159 |
def layer_output(model, layer_name=None):
"""Output tensor of a specific layer in a model.
"""
conv_index = -1
for i in range(len(model.layers) - 1, -1, -1):
layer = model.layers[i]
if layer_name in layer.name:
conv_index = i
break
if conv_index < 0:
print('Error: could not find the interested layer... | e3f693d8d5759f1ec1d6aab84e5cc85e9764cebc | 632,873 |
def string_to_bool(_value):
"""Converts "True" to True None to False. Case-insensitive."""
if _value is not None and _value.lower() == "true":
return True
else:
return False | 07a6639d4fb2a90fdb2040a0e6d22438d4532167 | 125,599 |
def identity_show(client, resource_group_name, account_name):
"""
Show the identity for Azure Cognitive Services account.
"""
sa = client.get(resource_group_name, account_name)
return sa.identity if sa.identity else {} | 19018c895f3fdf0b2b79788547bf80a400724336 | 709,835 |
import time
def get_balance_metrics(balance_data, ts=None):
"""
Return a list of balance metrics.
Parsed from the [balance](http://dev.datasift.com/docs/api/1/balance)
endpoint.
"""
ts = ts or time.time()
return [
('datasift.balance.credit', (ts, balance_data['balance']['credit']... | 66db8b1c77c89e93ebc0217ce7714c6ea396a6bd | 582,556 |
def v_equil(alpha, cli, cdi):
"""Calculate the equilibrium glide velocity.
Parameters
----------
alpha : float
Angle of attack in rad
cli : function
Returns Cl given angle of attack
cdi : function
Returns Cd given angle of attack
Returns
-------
vbar : float... | 16bd758f7349dd7c79a8441118191155730b1644 | 63,194 |
def terminal_errors_except(*args):
"""
Returns a ``can_retry`` function for :py:func:retry` that only retries if
errors the ``Exception`` types specified.
:return: a function that accepts a :class:`Failure` and returns ``True``
only if the :class:`Failure` wraps an Exception passed in the args.... | f928574ca644bdf6556751e32e46fc12c55f007c | 645,549 |
def valid_bidi(value):
"""
Rejects strings which nonsensical Unicode text direction flags.
Relying on random Unicode characters means that some combinations don't make sense, from a
direction of text point of view. This little helper just rejects those.
"""
try:
value.encode("idna")
... | e58979a1ecd89351a592a89502e848bfbce6ac70 | 566,286 |
def is_json_response(response):
"""Returns ``True`` if response ``Content-Type`` is JSON.
:param response: :class:~`requests.Response` object to check
:type response: :class:~`requests.Response`
:returns: ``True`` if ``response`` is JSON, ``False`` otherwise
:rtype bool:
"""
content_type = ... | 113bc6e1dcb45d4294287454b2a7519f05bad4cb | 607,762 |
def _normalize(df):
"""
Normalise the county data i.e. strip spaces and convert to upper case, and finally sort alphabetically.
:param df: input data frame with county column
:type df: pandas.DataFrame
:return: normalised data
:rtype: pandas.DataFrame
"""
df.sort_values(by='county', in... | 881afe6fcf50108832dd937a1eba5fc78e4097a7 | 308,017 |
def configuration_filename(feature_dir, proposed_splits, split, generalized):
"""Calculates configuration specific filenames.
Args:
feature_dir (`str`): directory of features wrt
to dataset directory.
proposed_splits (`bool`): whether using proposed splits.
split (`str`): tr... | a3fc2c23746be7ed17f91820dd30a8156f91940c | 706,888 |
def parse_functions_option(functions_option):
"""
Return parsed -f command line option or None.
"""
fvas = None
if functions_option:
fvas = [int(fva, 0x10) for fva in functions_option.split(",")]
return fvas | ea1c3ab5e75bb82c9a3706623289bf9b520e9e09 | 468,632 |
def F0F2F4_to_UJ(F0, F2, F4):
"""
Given :math:`F_0`, :math:`F_2` and :math:`F_4`, return :math:`U` and :math:`J`.
Parameters
----------
F0 : float
Slater integral :math:`F_0`.
F2 : float
Slater integral :math:`F_2`.
F4 : float
Slater integral :math:`F_4`.
Ret... | f4f85d9f8d91bd28af14d9f6660f9c9d0f4afda4 | 391,542 |
def sqnorm(v):
"""Compute the square euclidean norm of the vector v."""
res = 0
for elt in v:
for coef in elt:
res += coef ** 2
return res | 1af64ee21d02ae98c62b2a245b8ecb627bb7124b | 384,088 |
import pytz
from datetime import datetime
def datetime_from_timestamp(ts, tzinfo=pytz.utc):
"""
Convert an :term:`HMC timestamp number <timestamp>` into a
:class:`~py:datetime.datetime` object. The resulting object will be
timezone-aware and will be represented in the specified timezone,
defaultin... | 5d44404bf2a9ed41066fd1dc6c6eb20011bf06a2 | 325,270 |
def get_most_and_least_freq_words(frequency_dict_):
"""
This function returns the most and least frequent words that can be considered noise.
:param frequency_dict_: Dictionary that holds the frequency information of words.
:type frequency_dict_: dict
:return: Words that are frequent in these lexic... | 51239fca69ced67d85a0434f9547fd704b473364 | 159,041 |
def calc_lix(n_long_words: int, n_words: int, n_sents: int) -> float:
"""
Вычисление индекса удобочитаемости LIX
Описание:
Чем выше показатель, тем сложнее текст для чтения
Значения индекса лежат в пределах от 0 до 100 и могут интерпретироваться следующим образом:
0-30 - Очень п... | 02557546e5441b129b51bb93cfa43b58c5986227 | 556,410 |
def induce_subgraph(G, node_subset):
"""
Induce a subgraph of G.
Parameters
----------
G : networkx.MultiDiGraph
input graph
node_subset : list-like
the subset of nodes to induce a subgraph of G
Returns
-------
H : networkx.MultiDiGraph
the subgraph of G ind... | 952dea186a93dacdbabda64d64484c6d4aebf889 | 608,607 |
def parse_slice(s, size):
"""
Helper to determine nonnegative integers (start, stop, step) of a slice.
:param slice s: A slice.
:param int size: The size of the array being indexed into.
:returns: A tuple of nonnegative integers ``start, stop, step``.
:rtype: tuple
"""
start = s.start
... | a98db53286d8bbc6aee48026fbd572fee9370819 | 337,709 |
import torch
def get_neighbor_bonds(edge_index, bond_type):
"""
Takes the edge indices and bond type and returns dictionary mapping atom index to neighbor bond types
Note: this only includes atoms with degree > 1
"""
start, end = edge_index
idxs, vals = torch.unique(start, return_counts=True)
... | 96c56c067a3d436b67de093c0407f86900223302 | 58,383 |
def create_empty_board(n):
"""
Creates and returns a grid (list of lists), that has n
rows and each row has n columns. All the elements in
the grid are set to None.
>>> create_empty_board(2)
[[None, None], [None, None]]
"""
grid = [] # Create empty grid
for y in range(n): ... | 5cade24a2373bfba879e0a964f897b7c4974823e | 463,717 |
from typing import List
from typing import Tuple
from typing import Optional
def has_winner(field: List[List[int]]) -> Tuple[bool, Optional[Tuple[int, int]], Optional[Tuple[int, int]]]:
"""
Checks game for winning (or tie) positions
:param field: playing field matrix
:return: Overall answer & position... | 442935063a143981fb91056a14adda52c016f066 | 667,584 |
def remove_smallwords(tokens, smallwords_threshold: int) -> list:
"""
Function that removes words which length is below a threshold
["hello", "my", "name", "is", "John", "Doe"] --> ["hello","name","John","Doe"]
Parameters
----------
text : list
list of strings
smallwords_threshold: ... | 0f824214d621a6c945c6cf30f6c25b5eba3d6a12 | 79,569 |
def query_construction(raw_utterance, conv_id, turn_id, query_config, history, title):
"""
Parameters
----------
raw_utterance - str original conversational query
conv_id - conversation id
turn_id - int, current turn
query_config - QueryConfig, object with configurations to use in query rewr... | 6a3b350b2c0e9bf7f2187cf5818f9c22a3b52d21 | 353,545 |
def input_yesno(prompt, default=None):
"""
ask the user to enter Yes or No
prompt: string to be shown as prompt
default: True (=Yes), False (=No), or None (can not leave empty)
"""
while True:
value = input(prompt).strip()
if not value:
if default is None:
... | 7e38febe24d59a215d4c369f53d4ab524799891d | 659,468 |
def create_hf(geom):
"""Create header and footer for different types of geometries
Args:
geom (str): geometry type, e.g., polygone
"""
if geom == "polygone":
header = """
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
... | 28276e77ccaa2943dfe4bd2f65a19347f6b1cc1c | 683,660 |
def findSmallest(root):
"""
Finds the smallest node in the subtree
:param root: The root node of the tree or subtree
:return: The smallest node in the given subtree
"""
if root.left is None:
return root
else:
return findSmallest(root.left) | a84552ce444e48c45eec32acb93d791ff8de222c | 137,084 |
def isPrime(n):
"""
Determines whether a number is prime
Arguments:
n {integer} -- term
Returns:
isPrime {boolean}
"""
assert n > 0, "invalid number"
if n == 1:
return False
for i in range(2, n):
if (n % i) == 0:
return False
return True | 189e6282ca78008ff90cbc3d4b0af60bc4f2eba8 | 316,461 |
def parse_question_update_sync_agent_data(json):
"""
Parse the incoming statement for a sync agent event concerning a question update.
:param json: A statement concerning a question update.
:type json: dict(str, NoneType)
:return: A dictionary containing a course id, quiz id and all question inform... | d7c018fd0414181acccdd83fd60f34f1a28f8aec | 541,006 |
def fileExists(file_path):
"""
Method:
A more secure way to know if a file exists or not.
Arguments:
file_path (str): path to the file to verify.
Return:
(bool): True if the file exists : False if the file doesn't exists.
"""
try:
with open... | 36dad3a4fbbbfc079b2e31b131db6b9f9d352440 | 258,835 |
def make_html(url, time):
"""
Return browser readable html that loads url in an iframe and refreshes after time seconds
"""
html = f"""
<!doctype html>
<html>
<head>
<title>Kiosk</title>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum... | b87071c19af22c6c81ed100ffec0406d6bca009a | 465,474 |
def uniqueify(items):
"""Return a list of the unique items in the given iterable.
Order is NOT preserved.
"""
return list(set(items)) | b7b85edd311ec261e1db47c17386afaa44a08088 | 644,278 |
def trunc(s: str, left=70, right=25, dots=' ... '):
"""All of string s if it fits; else left and right ends of s with dots in the middle."""
dots = ' ... '
return s if len(s) <= left + right + len(dots) else s[:left] + dots + s[-right:] | 08ed3990baa6df66f3508219e96a53612c1cd9f8 | 71,542 |
import types
def type_legacy_mro(cls):
"""
drop in replacement of type.mro for loading legacy hickle 4.x files which were
created without generalized PyContainer objects available. Consequently some
h5py.Datasets and h5py.Group objects expose function objects as their py_obj_type
type.mro expects ... | 9b859cb06eb10394bb2528a0b3c06e89793ecdab | 493,399 |
def fmt_pairs(obj, indent=4, sort_key=None):
"""Format and sort a list of pairs, usually for printing.
If sort_key is provided, the value will be passed as the
'key' keyword argument of the sorted() function when
sorting the items. This allows for the input such as
[('A', 3), ('B', 5), ('Z', 1)] to... | 6dc1391d65b10df394e94426fdbde828bf4ae698 | 86,101 |
def extract_line_parts(line):
"""
Builds a dict containing tokenized command portion and comment portion of a
config line
"""
config, hash_char, comment = line.partition('#')
return {"command": config.split(), "comment": comment} | 5de954601044e0cd48bb00c4ca2c595f5b2f9e6a | 505,262 |
def class_decision(x):
"""
Returns a vector containing the class with the highest value (probability)
Inverse of one_hot function
Parameters
- x: t.tensor, size=[n, n_classes], where each element represents the probability of the class.
Returns t.tensor, size=[n], dtype=long, integer values i... | 7e891131d62f4fb2814870e13014d47c72ba5c1f | 198,834 |
def _joinNamePath(prefix=None, name=None, index=None):
"""
Utility function for generating nested configuration names
"""
if not prefix and not name:
raise ValueError("Invalid name: cannot be None")
elif not name:
name = prefix
elif prefix and name:
name = prefix + "." + ... | fb26dc39ded907cefc1a319d6d0692e67f8c5007 | 691,404 |
import hashlib
def md5_key(chrom, start, end, ref, alt, assembly):
"""Generate a md5 key representing uniquely the variant
Accepts:
chrom(str): chromosome
start(int): variant start
end(int): variant end
ref(str): references bases
alt(str): alternative bases
ass... | 64db55c0075d063aeec500f97700ec769840cc4f | 8,589 |
import random
def bomber(length, width, bomb, m, n):
"""
Place bombs randomly (position of first click and its surroundings cannot be bombs)
:param length: length of the board
:param width: width of the board
:param bomb: number of bombs
:param m: horizontal position of first click
:param ... | 52591fe68d7d03e29559072148a945700b6aad06 | 35,743 |
def multip(*args):
""" return the accumulated total of all arguments multiplied together
"""
accumulated_total = 1
for i in args:
accumulated_total *= i
return accumulated_total | 96983ad6d907afdf1c4641c1f1f08c54bc6fc617 | 366,332 |
def predict_ball_path(agent):
"""Predicts the path of the ball using the rlBot framework
Args:
agent (BaseAgent): The bot
Returns:
An array of Vec3 containing the predicted locations of the ball. Each location is seperated in time by
1/60 of a second, or one game tick.
... | 327d96ecb4c770ae526862343c111190cae77302 | 478,308 |
def pipe_results_table(case_dom):
"""Print pipe dimensions in a tabular text format
Args:
case_dom (dict): Pipe flow network data model
Returns:
(str): Text table of pipe dimensions, routing, and results"""
result = ' Pipe From To Diameter Length CHW' \
... | 43e8ad3a0f69d96081bcd0e0c0e9cca4313ec125 | 430,988 |
def num_transfer(df):
"""Total number of track transfer."""
return df.extra.Type.isin(['TRANSFER']).sum() | b63861cf2b0299e7d01d946c0d5064ca02cf4792 | 56,367 |
import sqlite3
def get_twinkles_visits(opsim_db_file, fieldID=1427):
"""
Return a sorted list of visits for a given fieldID from an OpSim
db file.
Parameters
----------
obsim_db_file : str
Filename of the OpSim db sqlite file
fieldID : int, optional
ID number of the field ... | 791f779cfba6125eaf7efea1930c6373f71e3efe | 659,305 |
def likert_malign(value):
"""Tell whether a Likert grade is malign."""
assert value in range(1, 6), value
return value > 2 | 5b3f94536a1e118a4b4852d0bf833ed4ef3bfc6d | 149,062 |
from typing import Optional
def percent(flt: Optional[float]) -> str:
"""
Convert a float into a percentage string.
"""
if flt is None:
return '[in flux]'
return '{0:.0f}%'.format(flt * 100) | 937a1608be53460369210cdce9150547bcb1fe56 | 666,522 |
from typing import List
def convert_coordinate(size: tuple, box: List) -> tuple:
"""Convert coordinate from xywh to
x_center, y_center, width, height
Arguments: \n
`size` (tuple): size of image \n
`box` (List): box coordinate \n
Returns:\n
`tuple`: new yolo coordinate
"""
dw ... | a5db82b2c0b8af17b8ccd9a288e8d0e44ebef1a3 | 571,401 |
def taken(diff):
"""Convert a time diff to total number of microseconds"""
microseconds = diff.seconds * 1_000 + diff.microseconds
return abs(diff.days * 24 * 60 * 60 * 1_000 + microseconds) | 64e8022bb0a80fcccc1a755fffb79121e61cad17 | 47,571 |
def find_relocations_for_section(elf, section_name):
""" Given a section, find the relocation section for it in the ELF
file. Return a RelocationSection object, or None if none was
found.
"""
rels = elf.get_section_by_name(b'.rel' + section_name)
if rels is None:
rels = elf.get_s... | 594683f10c57119acfd0d81007f85588cfe1c255 | 523,403 |
def get_locations(data: dict) -> list:
"""
Get users' locations from the dictionary. Return list of lists, every one
of which contains user's nickname and location.
>>> get_locations({'users': [{'screen_name': 'Alina', 'location':\
'Lviv, Ukraine'}]})
[['Alina', 'Lviv, Ukraine']]
"""
result... | 21c2cbc984e085d8b7b6da418e8184aa2d037cd2 | 691,612 |
def symmetric_transmission_constraint_rule(backend_model, loc_tech):
"""
Constrain e_cap symmetrically for transmission nodes. Transmission techs only.
.. container:: scrolling-wrapper
.. math::
energy_{cap}(loc1::tech:loc2) = energy_{cap}(loc2::tech:loc1)
"""
lookup = backen... | 15940abc4ea7a8acc4509e235f94f5167effa87f | 260,549 |
def parse_boss(lines):
"""Parse boss data from lines to dictionary."""
boss = {}
for line in lines:
attribute, value = line.split(':')
boss[attribute] = int(value)
return boss | cc33b2c6d9a00835f7429c532d11090a254842d3 | 419,895 |
def valid_year(entry, minimum, maximum):
"""Validate four digit year entries."""
if len(entry) > 4:
return False
elif int(entry) >= minimum and int(entry) <= maximum:
return True
else:
return False | 12491b406daa3c6d2eceb0929a2a72becca3cb42 | 667,472 |
import io
import re
def pdf_pages(filename):
"""Return number of pages in PDF."""
try:
infile = io.open(filename, "rb")
except IOError:
return 0
for line in infile:
m = re.match(br'\] /Count ([0-9]+)',line)
if m:
return int(m.group(1))
return 0 | a20c5912bb56f0f9b2caad11637bbcfaf4cac4a7 | 564,090 |
def check_prec(schedule):
"""
Checks if a given schedule is acceptable following the order of precedence.
Args:
schedule (list): a list of jobs (node object) listed according to the schedule.
Returns:
(boolean): true if schedule follows order of precendence. False otherwise.
... | fe30069d6d907092ee4bcace4ef167acd9d558cd | 248,875 |
def windows_only_packages(pkgs):
"""Find out which packages are windows only"""
res = set()
for p in pkgs:
for name, info in p.items():
if info.get("OS_type", "").lower() == "windows":
res.add(name)
return res | d6cd806fc83a0829955f632f14fc7ef95dcc084b | 407,993 |
def _get_used_ports(vms):
"""
Return a set of ports in use by the ``vms``.
:param vms: list of virtual machines
:type vms: list(:class:`~.vm.VM`)
:return: set of ports
:rtype: set(int)
"""
used_ports = set()
for vm in vms:
ip, port = vm.get_ssh_info()
... | aaa3e141fb060a78ba86d71d59ed59fb59fd4132 | 619,779 |
def build_array(record: dict):
"""
Build Data Transfer object with whom I'll work /w Python
:param record: raw results of InfluxDB
:return: a properly formatted object to interact with
"""
return [
record['_time'],
record['asset'],
record['_value'],
] | 47f901db998024d4024fef84cadab42f1973010d | 444,756 |
from typing import OrderedDict
def to_native(key):
"""
Given a mapping (e.g. dictionary) or a iterable (e.g. list) with 0d NumPy array or Torch tensor values,
convert these into native Python data type object (e.g. ints and floats).
Args:
key: a mapping or an iterable object
Returns:
... | 6f67ae158b54e2dc459bef67bc3217394ce2ddf8 | 306,624 |
def dustmass(f):
"""
dustFrac * mass
"""
return f['u_dustFrac'] * f['mass'] | d189b9ad10fc0558129c6f85ec2b906797dddd7d | 293,880 |
def valid_options(kwargs, allowed_options):
""" Checks that kwargs are valid API options"""
diff = set(kwargs) - set(allowed_options)
if diff:
print("Invalid option(s): ", ', '.join(diff))
return False
return True | 1d03ebc466ac82fcc691719a066d624a47c220e9 | 246,957 |
def concatenate_evidence(df):
""" Concatenate the evidence for each claim into one string. Edits df in place. """
df.evidence = df.evidence.transform(lambda x: ' '.join(x))
return df | 810df8301ddac0d86531817ca6ec4ff9691797cd | 463,713 |
def sameCategory(Data):
"""
判断是否所有数据均属于相同类型。
Args:
Data (list): 数据集
Returns: (类型, 是否相同)
"""
categories = [y[-1] for y in Data] # 数据集中的y向量(所有数据的标签)
return categories[0], len(set(categories)) == 1 | 0c80a1bc78ba43613e2f6a07dc1bdc73d926cf89 | 224,152 |
import logging
def split_and_put_into_ques(message_batch, que_urls, client, max_batch_size=10):
"""
Args:
message_batch: List of all messages to be put onto the que
que_urls: List of que_urls for messages to be put onto
max_batch_size: Maximum batch size (default to 10 for sqs)
... | 8890a235c6bff4d539dba1295c668c1448a1f102 | 552,898 |
def pulses_plugin(pulses_workbench):
"""Setup the workbench and return the pulses manager plugin.
"""
return pulses_workbench.get_plugin('exopy.pulses') | 480a24ce3c4d8d1f765af8f5921f8315ffd62df3 | 619,044 |
def consoO(R,s,tau,w):
"""Compute the consumption of the old agents
Args:
R (float): gross return on saving
s (float): savings
tau (float): percentage of contribution of the wage of the young agent
w (float): wage
Returns:
(float... | 522b6b51b50db29b60a5adc473d6cd9cc04a6a3a | 691,791 |
def last_char(word):
"""
Return the last letter
example: zerrouki; 'i' is the last.
@param word: given word
@type word: unicode
@return: the last letter
@rtype: unicode char
"""
return word[-1:] | a1973e5af77c1369843929585e77813b6e78e9d7 | 155,259 |
import zipfile
async def extract_zip_archive(
input_file_path: str, output_directory_path: str,
) -> dict:
"""
Extracts a given zip file.
Parameters
----------
input_file_path : str
Path to the zip file
output_directory_path : str
Path where all the files should be extract... | 1429a265ea4f4e6179855aef616784f62a9a3e7e | 548,388 |
import logging
def get_iam_policy(compute_client, image_id, project_id):
"""
Gets the compute image IAM policy.
"""
try:
policy = compute_client.images().getIamPolicy(project=project_id, resource=image_id).execute()
except:
logging.error(f"Could not get compute image IAM policy on... | 16e1fc518903a557f64551de303bf8f2942a0176 | 456,053 |
from typing import Optional
from typing import List
import string
import random
def randomString(length: int, samples: Optional[List[str]] = None) -> str:
"""A random string is generated.
Args:
length: the size of string.
samples: cumstomized letters for sampling. e.g., ['a', 'b'].
"""
... | ceaee6d8fe0f12775c2123f98b90aa33558aabe7 | 498,072 |
def get_template_user_keys(template):
"""
Finds the keys in a template that relate to the HumanUser entity.
:param template: Template to look for HumanUser related keys.
:returns: A list of key names.
"""
# find all 'user' keys in the template:
user_keys = set()
if "HumanUser" in templ... | cfeca37d39775a63b69f0ee0d582a0f4e03bb44e | 69,236 |
def spreadingRate(Q, beta):
"""
Calculates the spreading rate on the planet.
Inputs:
Q - pore space heat flow relative to modern Earth [dimensionless]
beta - scaling parameter [dimensionless]
Returns:
r_sr - the spreading rate relative to the modern Earth [dimensionless]
... | 4aab81278a3e5b9f9996c18d94d259cef8fb845b | 486,300 |
def is_singleton(atoms):
"""
returns whether all the input atoms are the same or not
Inputs
------
atoms: List[.logic.Atom]
[a_1, a_2, ..., a_n]
Returns
-------
flag : bool
a_1 == a_2 == ... == a_n
"""
result = True
for i in range(len(atoms)-1):
res... | 50066b657682fd44e373294764ed14645be93b97 | 224,153 |
import random
def greeting() -> str:
"""Returns a random greeting message.
Returns:
str:
Random greeting.
"""
return random.choice(
["Greetings", "Hello", "Welcome", "Bonjour", "Hey there", "What's up", "Yo", "Cheers"]
) | 6fad78497e4cc0ba41d4417059c20e05e20eab1c | 439,538 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.