content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def fold_change(c, RK, KdA=0.017, KdI=0.002, Kswitch=5.8):
""" Function computes the theoretical fold change in repression."""
# Compute fold change
fold_change = (1 + RK*((1+c/KdA))**2/((1+c/KdA)**2 + Kswitch*(1+c/KdI)**2))**(-1)
# Return concentration array and fold change array
return fold_change | 2fbc0eee45667443ba33a08f34bae7f7d80073cd | 313,145 |
def denpify(f):
"""
Transforms a function over a tuple into a function over arguments.
Suppose that
`g` = ``denpify(f)``,
then
`g(a_1, a_2, ..., a_n) = f((a_1, a_2, ..., a_n))`.
Examples
--------
>>> flip((0, 1))
(1, 0)
>>> f = denpify(flip)
>>> f(0, 1) # note the the... | 57ee3aa381352eab2823da0a30e6252d0377bdfe | 662,007 |
def lol_tuples(head, ind, values, dummies):
"""List of list of tuple keys
Parameters
----------
head : tuple
The known tuple so far
ind : Iterable
An iterable of indices not yet covered
values : dict
Known values for non-dummy indices
dummies : dict
Ranges of... | 68ab4c1e8bf159f3fb0828a9e2a7812c1623ee6a | 479,196 |
import asyncio
async def service_failed(unit_name):
"""
Return true if service with given name is in a failed state.
"""
proc = await asyncio.create_subprocess_exec(
'systemctl',
'is-failed',
unit_name,
# hide stdout, but don't capture stderr at all
stdout=async... | 6af31bd1ddbdd6f8c67fabb527f8b571e7c8d90c | 529,859 |
import hashlib
import json
def check_hash(hash: str, content: dict) -> bool:
"""Check that the stored hash from the metadata file matches the pyproject.toml file."""
# OG source: https://github.com/python-poetry/poetry/blob/fe59f689f255ea7f3290daf635aefb0060add056/poetry/packages/locker.py#L44 # noqa: E501
... | 5b4d9407c95eb2239c42dd13c5052ce011f4fa5a | 36,694 |
def _normalize(df, col, start_values, target_values):
"""Normalize the values in **col** relative to the total possible improvement.
We normalize the values of **col** by calculating the share of the distance between
the start and target values that is still missing.
Note: This is correct whether we h... | a57705ec4591a51bb2a7b4f1db3a81474c387892 | 139,796 |
def get_title(file_path: str) -> str:
"""
Get the title of the file based on its position in the file.
If there is a title, it will be the first line followed by two blank lines.
"""
with open(file_path, 'r', encoding='utf-8') as f:
MAX_BLANK_LINES = 2
blank_lines = 0
lines =... | ad9136958f63a91a47e8488a94f896164b833353 | 396,704 |
def toggle_bits(S, *positions):
"""
Returns a new set from set `S` with bits toggled (flip the status of) in the given `positions`.
Examples
========
Toggle the 2-nd item and then 3-rd item of the set
>>> S = int('0b101000', base=2)
>>> S = toggle_bits(S, 2, 3)
>>> bin(S)
'0b100100... | dd933090595273832b42e8e68de5d4e3be472ff8 | 353,442 |
import re
def remove_vowels(txt):
"""Remove every vowel from string txt."""
return re.sub(r'[a|e|i|o|u|A|E|I|O|U]', '', txt) | 7f187e8e07211c23fb94dbf28b9a081f666f1ac8 | 564,306 |
def check_port(port):
""" Check if a port is valid. Return an error message indicating what is invalid if something isn't valid. """
if isinstance(port, int):
if port not in range(0, 65535):
return 'Source port must in range from 0 to 65535'
else:
return 'Source port must be an i... | 6aa6d4113613daf6520251f142dcd8f94cd1b213 | 552,278 |
def build_event_info(info, time):
"""Adds created_at time to event info dict."""
return {**info, 'created_at': time} | a7faa2d3798d2692310af16e84099d7b86fa84f0 | 49,192 |
def _str_to_hex(s: str) -> str:
"""
Convert given string to hex string.
given string can be one of hex format, int, or a float between 0 and 1.
>>> _str_to_hex('0xFf')
'Ff'
>>> _str_to_hex('200')
'c8'
>>> _str_to_hex('0.52')
'84'
"""
if s.startswith('0x'):
return s[... | a7def289214f593c287938591b0e0523ba1f2994 | 539,207 |
def number_factor(PD, SC=30.0, OD=0.32153):
"""
PD - Planet density
OD - Optimal density
SC - a number used to scale how bad it is to differ from the
optimal density. Lower number means less bad
Returns a number between 0.0 and 1.0 indicating how good the
density of planets is compared ... | be28fd46ca29552acd0f099c1843a00a75ccaa34 | 255,204 |
from typing import Counter
def same(word_1: str, word_2: str) -> bool:
"""
a simple helper function for checking if words match
:param word_1: a word
:param word_2: a word
:return: boolean, do words consist of exactly same letters?
"""
return Counter(list(word_1)) == Counter(list(word_2)) | 5fbe06e9699c84bdbdedae1e265dc773e82cb4ab | 513,214 |
import math
def poids_attirance(p, dist):
"""
Calcule le poids d'attraction d'une neurone vers une ville.
"""
d = p[0] * p[0] + p[1] * p[1]
d = math.sqrt(d)
d = dist / (d + dist)
return d | 4a997566d19dc7e436a3a1704be7b5ac74424266 | 12,688 |
def contains(main_str: str, sub_str: str) -> bool:
"""
>>> "a" in "abc"
True
>>> "bc" in "abc"
True
>>> "ac" in "abc"
False
>>> "" in "abc"
True
>>> "" in ""
True
"""
return sub_str in main_str | 7d949e1dcc6d5dfad020bf6debe34fd1a13cf40c | 124,084 |
def reduceColours(image, mode="optimised"):
"""Reduces the number of colours in an image. Modes "logo", "optimised"
Args:
image (PIL.Image.Image): Input image
mode (str, optional): Mode "logo" or "optimised". Defaults to
"optimised".
Returns:
PIL.Image.Image: A PIL Image
"""
modes = {"logo": 16, "optimis... | 5f655ed6f0cb16f049a62a95558b203a0ea23059 | 237,437 |
def is_route(tag):
""" Checks if an HTML tag is a bus route.
:param tag A BeautifulSoup tag
:return True if the tag has a "data-routes" attribute, False otherwise"""
return tag.has_attr("data-routes") | a568a7cd610095e233eed7f04caf04983572e4d7 | 615,840 |
def upsert_resource(apiroot, settings):
"""
Convenience function to create or update a resource
Args:
apiroot (obj): API endpoint root eg `api.cnxn.pipes`
settings (dict): resource settings
Returns:
response (obj): server response
data (dict): json returned by server
... | 949326354ab41b2cc291dc7536d27755926856b2 | 585,179 |
def find_if(pred, iterable, default=None):
"""
Returns a reference to the first element in the ``iterable`` range for
which ``pred`` returns ``True``. If no such element is found, the
function returns ``default``.
>>> find_if(lambda x: x == 3, [1, 2, 3, 4])
3
:param pred: a predica... | 90515e2652cd9da0b446591b801593b02ad39d3d | 544,123 |
import itertools
def subsets(S):
"""
Return an iterator with all possible subsets of the set S.
Parameters
----------
S: set
a given set
Returns
-------
subsets: iterable
an iterable over the subsets of S, in increasing size
"""
subsets = []
for r in rang... | d757b03fdf541a89d803da19aa370382418c7f7b | 535,331 |
def output(the_bytes, as_squirrel=True):
"""
Format the output string.
Args:
the_bytes (list): The individual integer byte values.
as_squirrel (bool): Should we output as Squirrel code? Default: True
Returns:
str: The formatted output.
"""
out_str = "local unicodeStr... | 4042aaa1b44f2c52f81082a0f382bd11fa9613d0 | 432,715 |
def get_lomb_trend(lomb_model):
"""Get the linear trend of a fitted Lomb-Scargle model."""
return lomb_model['trend'] | 10334d850c8c6559169b4653912dd0bffc03f1fa | 319,245 |
def create_dataset(connection, body):
"""Create a single-table dataset from external data uploaded to the
MicroStrategy Intelligence Server.
Args:
connection (object): MicroStrategy connection object returned by
`connection.Connection()`.
body (str): JSON-formatted definition of... | 094d9eef49663b6606a40d73c6684f7f90f382f8 | 235,055 |
async def id_exists(collection, id_: str) -> bool:
"""
Check if the document id exists in the collection.
:param collection: the Mongo collection to check the _id against
:param id_: the _id to check for
:return: does the id exist
"""
return bool(await collection.count_documents({"_id": id_... | 2c3355227b7d24133dc1383e47a26c03c468e2a4 | 578,243 |
def strToListFloat(s):
""" Convert a string to a list of float
"""
return map(float,s.split()) | 94317f2a6e802986d268ced16f09e2e0d3f5c507 | 560,020 |
def set_bit(number, site, N, bit):
"""
Change the bit value of number at a single site.
:param number: the number to be changed
:param site: the index of the site starting from left
:param bit: the bit value to be changed
:returns: the changed number
"""
if bit:
return number | ... | 01225923c410f0dbb76b5aa94854e8a2f961eb68 | 619,654 |
def id_is_int(patient_id):
""" Check if patient id is integer
Check if the patient's id is a integer
Args:
patient_id (int): id number of the patient
Returns:
True or str: indicate if the input patient id is an integer
"""
try:
int(patient_id)
return True
... | 21400915bf15cbdd01f594fc6d7e01ff045d528d | 127,196 |
def clean_code(code: str) -> str:
"""Replaces certain parts of the code, which cannot be enforced via the generator"""
# Mapping used for replacement
replace_map = [
("...", "default_factory=list"),
("type_class", "typeClass"),
("type_name", "typeName"),
("from core", "from ... | f09eee589c74c4211afa778515c6186ea0c79496 | 119,683 |
from typing import List
from typing import Union
def findFirstVar(results : List[Union[None, int]]) -> Union[None, int]:
"""Finds the first index in a list of none's
Args:
results (List[Union[None, int]]): A list of none's and integers
Returns(either):
int: The first item's value(index)
... | cb092688119a580707b98d810469ea832a5fd9a6 | 230,421 |
def drop_unneeded_cols(df_adverse_ev):
""" Drop the columns that will not be used as features """
drop_cols = ['companynumb','duplicate', 'occurcountry',
'patient',
'primarysourcecountry', 'receiptdateformat',
'receiver', 'receivedate', 'receivedateformat', 'r... | 1d50de5e5bacf772fe128e491d5b1a872054d883 | 175,710 |
from typing import List
def ok(lines: List[str], join_on_newline: bool = True) -> bytes:
"""Send the given lines to stdout, preceded by a 20 (success) \
response.
:param lines: List of lines to send to stdout.
:param join_on_newline: Whether to join `lines` on newlines, or an \
em... | bbd6df9bc18425f8ad144992a4f048670dc8ae8b | 319,069 |
def round_family(family, num_digits=3):
"""Round the matrix coefficients of a family to specified significant digits.
Parameters
-----------
family: iterable of Model objects that represents
a family.
num_digits: integer
Number if significant digits to which the matrix coefficients ... | 35e8f6bac7824d8b35d04820b40ce649609f885e | 499,502 |
import inspect
def _source(obj):
"""
Returns the source code of the Python object `obj` as a list of
lines. This tries to extract the source from the special
`__wrapped__` attribute if it exists. Otherwise, it falls back
to `inspect.getsourcelines`.
If neither works, then the empty list is re... | 0faf18c32fa03ef3ac39b8e163b8e2ea028e1191 | 674,432 |
def line_format(data, length=75, indent=0):
"""Format the input to a max row length
Parameters
----------
data: list
list och items that is beeing formated
length: int
how long is the max row length
indent: int
how many whitespaces should each line start with
Return... | 67dd9438ff96868bac5f9e3c4e7827bc718a8a36 | 78,049 |
import random
import torch
def get_example_inputs(multichannel: bool = False):
"""
returns a list of possible input tensors for an AudacityModel.
Possible inputs are audio tensors with shape (n_channels, n_samples).
If multichannel == False, n_channels will always be 1.
"""
max_channels = 2 if multich... | a0abd8c700375bb97425ef11072319168a682c39 | 494,035 |
def get_twin(ax):
"""
Retrieves a twin Y axis for a given matplotlib axis. This is useful when we have two axes one placed at each side
of the plot.
@param ax: the known matplotlib axis.
@return: the twin axis.
"""
for other_ax in ax.figure.axes:
if other_ax is ax:
contin... | c60fb151d72d28242ba9aef12a1ae688f1725d0c | 459,372 |
import requests
import json
def westBengalStateID(state):
"""
Function to get state id from state name derived by reverse engineering
pincode
Parameters
----------
state : String
State name.
Returns
-------
state_id : String
ID associated with that state name
... | 4ddef75ea2206ac2ef92d6d84975f5b2a4b2af77 | 270,516 |
def makeBundlesDictFromList(bundleList):
"""Utility to convert a list of MetricBundles into a dictionary, keyed by the fileRoot names.
Raises an exception if the fileroot duplicates another metricBundle.
(Note this should alert to potential cases of filename duplication).
Parameters
----------
... | ae121beaa69f0f69e8d544dea7b8e208e7b609ca | 118,961 |
def align(s, offset):
"""Adds 'offset' times whitespaces end of the string 's'"""
return s + (' ' * offset) | d9f6d58387f044566e1a9aedb52f8542acb753a0 | 138,553 |
def strip_numbers(s):
"""
Return a string removing words made only of numbers. If there is an
exception or s is not a string, return s as-is.
"""
if s:
s = u' '.join([x for x in s.split(' ') if not x.isdigit()])
return s | 64c55a6777bd43e8cbc5a5c872c1c2f3302e0545 | 139,818 |
import re
def simplify_string(string):
""" Removes punctuation and capitalization from given string
Args:
string(string): string to be simplified
Returns:
string: a string without punctuation or capitalization
"""
return re.sub(r'[^a-zA-Z0-9]', '', string).lower() | b324763092f5410e9d8382158310a728725fa030 | 236,749 |
def example_netcdf_path(request):
"""Return a string path to `sample_tile.nc` in the test data dir"""
return str(request.fspath.dirpath('data/sample_tile.nc')) | 5fb5bf102c3ea8b21d6c847f8d5fc88c2d6e0615 | 143,974 |
def create_generic_templating_dict(dashboard_info):
"""
Generic templating dictionary: name just maps to value
:param dashboard_info: Grafana dashboard API response
:return: dict of {"name": "value"}
"""
templates = {}
templating_info = dashboard_info['dashboard']['templating']
for temp... | 6cd6f7ad56c2a8e5dd7d32d23fb76ff644835b03 | 157,312 |
import inspect
def _is_model_class(obj):
"""Return whether or not the given object is a Model class."""
if not inspect.isclass(obj):
return False
if obj.__name__ == 'Model':
# Base model class, don't include.
return False
return 'Model' in [o.__name__ for o in inspect.getmro(obj)] | 7e1f2eba38c709f1c6017ff1a147290c16ff0b38 | 152,314 |
import re
def convert_to_platform_safe(dir_file_name):
"""
:param dir_file_name: a string to be processed
:return: a string with all the reserved characters replaced
"""
return re.sub('[\?|<>=:*,;+&"@]', '_', dir_file_name) | 8fd0495b78aa9628dc6de79612f8fba945b1f871 | 538,655 |
def fill_world_template(world_temp, model_info):
"""
Write relevant information into the world file template.
"""
# Replace template values
world_content = world_temp
world_content = world_content.replace("$FILENAME$", model_info.name)
return world_content | 1f81ef2e95d3eecffc4a3f5d1d66f5d10f39675a | 173,428 |
import string
def ignore_whitespace(a):
"""
Compare two base strings, disregarding whitespace
Adapted from https://github.com/dsindex/blog/wiki/%5Bpython%5D-string-compare-disregarding-white-space
"""
WHITE_MAP = dict.fromkeys(ord(c) for c in string.whitespace)
return a.translate(WHITE_MAP) | 9f90e0cd10744fe337f9469913654d0dd951f2a5 | 38,416 |
import math
from typing import Counter
def entropy(data, unit='natural'):
"""
Compute and return the entropy of a stream of data.
:param bytearray data: Stream to compute entropy on.
:param str,optional unit: Passed to math.log calculation.
Default is natural.
:return: Entropy calculation
... | 68120db58a921c83945e52b1d36fd8c458bac461 | 294,215 |
def print_exam_schedule(exam_schedule):
"""
Prints the exam schedule in a prettier format.
Parameters:
-----------
exam_schedule (2D list): Departments for each exam block
returns (NoneType): None
"""
for i in range(len(exam_schedule)):
print("Block " + str(i+1) + ": [" + ', ... | dbb8a7813c6e76d33a5874c88f0a7eb123b1b881 | 481,580 |
def orthogonal_vector(vector):
""" Given a vector, returns a orthogonal/perpendicular vector of equal length.
Returns
------
(float, float): A vector that points in the direction orthogonal to vector.
"""
return -1 * vector[1], vector[0] | 760ec2adf8994d4b2871d57b054a660a1d03411f | 357,027 |
def concatenate_url(endpoint, url):
""" concatenate endpoint & url
:param endpoint: the base url for example http://localhost:port/v1
:param url: the target url for example "/dashboard"
:return: concatenated url for example http://localhost:port/v1/dashboard
"""
return "%s/%s" % (endpoint.rstrip... | 2c4eb63fcad9cdf99bbc16e53452601b79f17b4f | 250,416 |
def _read_first_line(file_path):
"""
Returns the first line of a file.
"""
with open(file_path, 'r') as file_:
first_line = file_.readline().strip()
return first_line | 035f22e1e35aa2f945d6ee6d8435d44fee17cc01 | 33,197 |
def data_from_response(response: dict) -> dict:
"""If the response is OK, return its payload.
- response: A dict like::
{
"status": 200, # <int>
"timestamp": "....", # ISO format string of the current date time
"payload": { ... } # dict with the returned data
}
- Returns a di... | 368b099264168b935f146f787d3999a2494e4446 | 326,965 |
def region_filters(DF, lon_min, lon_max, lat_min, lat_max, shapefile=False):
"""Takes a Dataframe with the all the rivers information and filters the data
from the rivers in an especific region.
Parameters
----------
DF: Dataframe
is the River_sources dataframe.
lat_min, lat_max, lon_mi... | 73be07602873444ab22e2febe7aea8c421e92321 | 127,079 |
def image_type(file):
"""Returns str of file type. 'jpeg', 'png', 'gif'.
Returns None if unable to identify file type"""
if isinstance(file, str):
f = open(file, 'rb')
binary_string = f.read(32)
else:
binary_string = file.read(32)
if binary_string[6:10] in (b'JFIF', b'Exif'):... | b19e53dc86bc92c7bb4bff1810678fee5b0fb44b | 530,724 |
def get_parameter(model, name):
"""
Finds the named parameter within the given model.
"""
for n, p in model.named_parameters():
if n == name:
return p
raise LookupError(name) | ba35b743d9189c94da0dcce27630bba311ea8a46 | 5,964 |
from typing import List
def calc_share(total: int, no: int, yes: int, maybe: int, bad: int) -> List[float]:
"""Calculate the share of each category on the total count."""
no_share = no / total
yes_share = yes / total
maybe_share = maybe / total
bad_share = bad / total
return [no_share, yes_sh... | b9b18124f9c82fede43032a1776e57bc16a403fb | 605,862 |
def _select_mapping(items, keep=(), drop=()):
"""Helper function for `select`.
Parameters
----------
items: Mapping
Dict (or similar mapping) to select/drop from.
keep: Iterable[str]
Sequence of keys to keep.
drop: Iterable[str]
Sequence of keys to drop. You should speci... | 2fd34956b79fc222b423d50eb94d1b646f1b86ac | 362,460 |
def str2bool(s):
"""
Convert a string to a boolean value. The supported conversions are:
- `"false"` -> `False`
- `"true"` -> `True`
- `"f"` -> `False`
- `"t"` -> `True`
- `"0"` -> `False`
- `"1"` -> `True`
- `"n"` -> `False`
- `"y"` -> `True`
- `"no"` -> `False`
- `"yes... | e9305e3d377333d1d51756a7ac6c227b2e37a2dd | 248,224 |
def file_size_formatter(size):
"""
File size with units formatting
:param size: File size to be formatted
:type size: String, float or integer
:returns: File size with units
:rtype: String
Examples:
>>> file_size_formatter('60')
'60.0B'
>>> file... | 4c0af463afea0166ac58f393426a40caead9305c | 380,447 |
from typing import Dict
def table(services: Dict[str, str]) -> str:
"""
Collect all services and their current otp as a table.
:param services: Dictionary of service name to otp
:return: the table representation of d as a string
"""
# the longest service name or 10
left_column = max(... | 608f4749cab6b09ca75e3e2ad1eb810625008262 | 151,680 |
def splitBinNum(binNum):
"""Split an alternate block number into latitude and longitude parts.
Args:
binNum (int): Alternative block number
Returns:
:tuple Tuple:
1. (int) Latitude portion of the alternate block number.
Example: ``614123`` => ``614``
2.... | da9b9cc67d592e73da842f4b686c0d16985f3457 | 706,514 |
def linear(x):
"""
Linear activation function
"""
return x | 57395e300e2c4186662c7c96c5938ff92bee2a0a | 157,526 |
def create_look_up_table(vocab_list):
"""Create tables for encoding and decoding texts."""
vocab2int = {word: i for i, word in enumerate(vocab_list)}
int2vocab = vocab_list
return vocab2int, int2vocab | d9f0591d50e92cb518c3b6fda3a5240d3beacfbb | 279,028 |
def __evaluate_model(valid_world, batchsize, datatype, display_examples, max_exs=-1):
"""Evaluate on validation/test data.
- valid_world created before calling this function
- batchsize obtained from opt['batchsize']
- datatype is the datatype to use, such as "valid" or "test"
- display_examples is ... | 3cf3fbd9dd6b1430f4f086786b26abc3e9c90e5b | 120,311 |
def shorten_unique(names, keep_first=4, keep_last=4):
"""
Shorten strings, inserting '(...)', while keeping them unique.
Parameters
----------
names: List[str]
list of strings to be shortened
keep_first: int
always keep the first N letters
keep_last: int
always keep ... | bf23e2f2eeddb5b5541613284291ba0b6a1e271f | 117,795 |
import string
import itertools
def standardize_col(col: str) -> str:
"""Standardize a column for Snowflake table.
(1) Replaces spaces with underscores, trims leading & trailing
underscores, forces upper-case
(2) Replaces special characters with underscores
(3) Reduces repeated special charact... | 78a84d8d6951d7fe58645e32e34ec69ea3aeac64 | 611,863 |
import importlib
def timport(name):
"""
Try to import and return the module named `name`, and return `None` on
failure.
"""
try:
return importlib.import_module(name)
except ImportError:
return None | 60b34bf39304a56ff49a455e510b372c4f2dd2dc | 481,730 |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
high = number
low = 0
while low <= high:
mid = (low + high) // 2
midsquare = mid * mid
... | 1dca451d1b96ec88a36753d9d07edd9ba2f34de8 | 19,652 |
def msg_mutator(plan, msg_proc):
"""
A simple preprocessor that mutates or deletes single messages in a plan
To *insert* messages, use ``plan_mutator`` instead.
Parameters
----------
plan : generator
a generator that yields messages (`Msg` objects)
msg_proc : callable
Expec... | 452ac6ba74b4a8a1258a071c025dba89ce586f9c | 501,825 |
def Kronecker(a,b):
"""
Kronecker delta function.
Parameters
----------
a: int
first index
b: int
second index
Returns
-------
Return value 0 if a and b are not equal; return value 1 if a and b
are equal.
"""
if a == b:
retur... | b91e4aed97220c106f73b7520f9a80b0f400e535 | 558,572 |
def find_parents(graph, node):
"""
Get the governing nodes of a given node in the graph
"""
return graph.reverse()[node].keys() | 22f63019f9725f3764b4c59392acc1cefaf433c9 | 570,867 |
def _convertTextToType(valueToConvert, defaultValue, desiredType=None):
"""
Ensure the value has the correct expected type by converting it.
Since the values are extracted from text, it is normal that they
don't have the expected type right away.
If the value cannot be converted, use the default va... | 5326f98674e6573a18e7b419903a7bc1b4172428 | 140,951 |
def strip_comment(line):
"""Get rid of fortran comments."""
idx = line.find("!")
if idx != -1:
return line[:idx].strip()
return line | db5a63466bae41d40336b6fbdc73d3d79832ce6c | 525,210 |
def format_freqs(counter):
"""
Format a counter object for display.
"""
return '\n'.join('%s: %d' % (tag, counter[tag])
for tag in sorted(counter.keys())) | f2a7c781a27ab1c60a3312f35ca44bf960e066a0 | 348,475 |
def index_range(raw):
"""Parse index ranges separated by commas e.g. '1,2-5,7-11'."""
if not raw:
return None
indices = set()
try:
with open(raw, 'r') as f:
for l in f:
l = l.strip()
if len(l) == 0 or l[0] == '#':
continue
... | 1699abbb4b6ec8c4cfc69cd7428a01e84066caca | 581,060 |
def dxdt(y, z):
"""Computes the equation for x prime"""
dx = -y - z
return dx | 5307deada35d965dafa6e32576d67335c522d775 | 691,551 |
def source(*_):
"""Return a link to the repo for this bot."""
return (
"I'm an open source bot. If you want to contribute or are curious "
"how I work, my source is available for you to browse here: "
"https://github.com/esi/esi-bot/"
) | a8c25a3b5b24c98d711669f10e3a1485e578dffa | 206,207 |
def merge_codegen_params(reload_list, arg_list):
"""Merge the codegen reload params list additional arguments list with no duplicates"""
if reload_list:
new_reload_list = reload_list
else:
new_reload_list = []
if arg_list:
new_arg_list = arg_list
else:
new_arg_list ... | 3fdb11bbded7f2300a159cc2510e4ee13c02fe1b | 69,961 |
def sci_format(x,lim):
"""
Ticks formatter scientific notation with base 10. Adapted from https://www.py4u.net/discuss/140199
"""
a, b = '{:.0e}'.format(x).split('e')
b = int(b)
return r'${} \times 10^{{{}}}$'.format(a, b) | 5737322630ccd4b32e29b8afe34544ead74686c4 | 181,437 |
def parse_dat_mantid_function_def(function):
"""
Helper function that parses the function definition of a NIST problem
and returns the function name and parameters.
@param function :: NIST function definition string
@returns :: formatted function name and the final function
paramet... | 2f3287926f55dc542c03a24e9af9f95ac0a7e0d7 | 367,255 |
import hashlib
def get_hashed_name(name: str) -> str:
"""
Generate hashed name
Args:
name: string to be hashed
Returns:
str: hashed string
"""
return hashlib.sha224(name.encode('utf-8')).hexdigest() | 1784f92b8734f18bf0cf39660b2a07b2247ea8df | 390,386 |
def get_aside_from_xblock(xblock, aside_type):
"""
Gets an instance of an XBlock aside from the XBlock that it's decorating. This also
configures the aside instance with the runtime and fields of the given XBlock.
Args:
xblock (xblock.core.XBlock): The XBlock that the desired aside is decoratin... | 5cb375282144cfbbe0b23d5b224e6370cf9218d7 | 391,033 |
def get_boolean(value) -> bool:
"""Convert a value to a boolean.
Args:
value: String value to convert.
Return:
bool: True if string.lower() in ["yes", "true"]. False otherwise.
"""
bool_val = False
try:
if value.lower() in ["yes", "true"]:
bool_val = True
... | cfd716167e288ae60b6a6545c9bba8eb98b5579c | 281,771 |
def is_springer_url(url):
"""determines whether the server is springer from url
@param url : parsed url
"""
return 'www.springerlink.com' in url.netloc | 16bea33374cf8c5a7e5050fa1019aa563f06906b | 607,662 |
from typing import Any
import json
def _handle_values_for_overrides_list(v: Any) -> Any:
"""
Handle the special massaging of some values of JSON need to for it to be supplied
to Hydra's overrides list.
"""
# python's None --> cmd line null for override list
v = "null" if v is None else v
... | 5b89884dbaef4819c2da6eeecff0997570ccd475 | 516,589 |
def _get_func(module, func_name):
"""
Given a module and a function name, return the function.
func_name can be of the forms:
- 'foo': return a function
- 'Class.foo': return a method
"""
cls_name = None
cls = None
if '.' in func_name:
cls_name, func_name = func_name... | 6ff9af35a50e7dbcb4a0227e8bba2efef5bb7393 | 557,736 |
import re
def rename_dims(name):
"""Simplify dimension names
"""
dimname = re.sub("_[67]", "", name) # Remove _6 or _7
dimname = re.sub("jhisto_", "", dimname) # jhisto_
return(dimname) | d8627ba2d683e48a4b179b38276c5202ce946f35 | 415,579 |
def _put_into_original_order(X, columns_to_subset):
"""Put the columns returned by X.ww.select(...., return_schema=True) into the original order found in X."""
return [col_name for col_name in X.columns if col_name in columns_to_subset] | e0512e06a963aee1defad407c9c02d8d0879bfb9 | 244,609 |
import requests
def fetch(url):
"""Fetch data from url and return fetched JSON object"""
r = requests.get(url)
data = r.json()
return data | 4a1296242c315b88e30ccaecfa4aca1e20a4ed07 | 424,433 |
def to_signed(value):
"""Decode the sign from an unsigned value"""
if value & 1:
value = ~value
value >>= 1
return value | 00fad31f250de7cdb89b235f428bf928d5e00160 | 161,722 |
def get_current_site(request):
"""
Return current site.
This is a copy of Open edX's `openedx.core.djangoapps.theming.helpers.get_current_site`.
Returns:
(django.contrib.sites.models.Site): returns current site
"""
return getattr(request, 'site', None) | 8958df67fa2555055161c28bc35dd2bf81b0c36c | 360,632 |
def list_api_vs(client, resource_group_name, service_name):
"""Lists a collection of API Version Sets in the specified service instance."""
return client.api_version_set.list_by_service(resource_group_name, service_name) | c12a895195a0122afa53649c2cb351e118916a62 | 663,919 |
def wrap_with_links(obj, links, val, root_path, many=False):
"""Adds links key to object (first argument) based on links dictionary and value"""
if many:
for item in obj:
item['links'] = {}
for key in links:
item['links'][key] = root_path + links[key].format(item[... | ea42bff363fe131a423501b8442449f03c3eccb7 | 646,921 |
def rtuFrameSize(data, byte_count_pos):
""" Calculates the size of the frame based on the byte count.
:param data: The buffer containing the frame.
:param byte_count_pos: The index of the byte count in the buffer.
:returns: The size of the frame.
The structure of frames with a byte count field is ... | 12a7d85880a4d30e6ae2bb8978946f270985ac1f | 602,170 |
def num2str(element, decimal_sep='.'):
"""
A helper function that converts strings to numbers if possible
and replaces the float decimal separator with the given value
"""
if isinstance(element, float):
return str(element).replace('.', decimal_sep)
return str(element) | 61e5d7a9ae46c83081068e581b8e1881c4507915 | 173,760 |
def psi0(ctx, z):
"""Shortcut for psi(0,z) (the digamma function)"""
return ctx.psi(0, z) | d59412a12bffc32a3706d5d9469c27b2a2328a67 | 641,354 |
def get_show_name(vid_name):
"""
get tvshow name from vid_name
:param vid_name: video clip name
:return: tvshow name
"""
show_list = ["friends", "met", "castle", "house", "grey"]
vid_name_prefix = vid_name.split("_")[0]
show_name = vid_name_prefix if vid_name_prefix in show_list else "bb... | ec734f72fc3b61f00cc44d50f263af40e546a6a4 | 513,904 |
def tags_to_new_gone(tags):
"""Split a list of tags into a new_set and a gone_set."""
new_tags = set()
gone_tags = set()
for tag in tags:
if tag[0] == '-':
gone_tags.add(tag[1:])
else:
new_tags.add(tag)
return new_tags, gone_tags | 7689928d7c47fddad8566a0e66e1a7a1d9e42cc9 | 542,575 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.