content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import math
def entropy(classes: list, instances: list):
"""
function to calculate the entropy of the given instances
:param classes: is a one-dimensional list containing the class names
:param instances: is a two-dimensional list where each row respresents
one attribute(in the order of '... | 682cd04cdae2e7f914962789baf11b4416f6bb37 | 585,700 |
def sort_nodes(nodes, func, desc=False):
"""
Sort nodes in-place.
:param nodes: list of nodes.
:param func: a function that returns an item as sorting key.
:param desc: whether in descending order.
"""
nodes.sort(key=func, reverse=desc)
return nodes | ff043f4a33d1a064e7e42bd2d6e9d9c326bc06bf | 585,701 |
from typing import Union
from typing import Iterable
from typing import Mapping
from typing import Callable
import json
def map_nested_objs(
obj: Union[Iterable, Mapping], func: Callable
) -> Union[Iterable, Mapping]:
"""
This function recursively applies `func` to each obj nested within a
dictionary/... | 1e5dad24fc4fcb73e86735ecc8529ffbc50da6d3 | 585,704 |
def ballOnTexter(ballOnTens, ballOnOnes):
"""Sets ballOnText to blank if no value, or adds "Ball On " if value exists."""
ballOn = chr(ballOnTens) + chr(ballOnOnes)
if ballOnOnes == 32:
ballOnText = ""
else:
ballOnText = "Ball On " + ballOn
return(ballOnText) | 709de94926b2ba948d218938e8cf0f78f30193a7 | 585,714 |
def to_insert(table, d):
"""Generate an insert statement using the given table and dictionary.
Args:
table (str): table name
d (dict): dictionary with column names as keys and values as values.
Returns:
tuple of statement and arguments
>>> to_insert('doc.foobar', {'name': 'Marv... | d25832eff4a68a5f22e1d8629814e5cb8ed200cd | 585,715 |
import math
def _bitsfor(maxval):
""" Convert a maxval into a number of bits (left shift).
Raises a ValueError if the maxval is not a power of 2. """
maxvalbits = int(round(math.log(maxval)/math.log(2)))
if maxval != (1 << maxvalbits):
raise ValueError("maxval must be a power of 2, not %d"... | ce434a7f592d1086bf7ef4e1fa426f45ccbd1102 | 585,717 |
def segment_times(timeseries, max_gap):
"""
Returns an N-D array where each row represents a separate segmentation of continuous data with no gaps
greater than the max gap.
"""
time_segments = []
is_contiguous = False
arr_n = -1
for i, t in enumerate(timeseries):
if not is_contig... | 1751be2f415297e07eb8952709388f5033ba7da4 | 585,723 |
import collections
import bz2
import tqdm
def extract_popularities(popularity_dump):
"""Iterate through the Wikipedia popularity dump without decompressing
it, storing each English Wikipedia page's number of page views.
Args:
popularity_dump: ``str`` A path to a .BZ2 file containing Wikipedia
... | 8a7d669e34c1fee5f215eae629df3126c2e4714b | 585,726 |
def m_coolwater_waste(Q_wastecooler, Cp_wastecooler, t_coolwater_exit, t_coolwater_enter):
"""
Calculates the flow rate steam of waste cooler.
Parameters
----------
Q_wastecooler : float
The heat load feed of waste cooler, [W] [J/s]
Cp_wastecooler : float
The heat capacity of wat... | 6d7f53719a7d768a021e3d44ff4fa84254d3dd29 | 585,729 |
def borders_flipped(array):
""" Return true if any of the border elements are flipped.
"""
return array[0,:,:].any() or array[-1,:,:].any() or array[:,0,:].any() or array[:,-1,:].any() or array[:,:,0].any() or array[:,:,-1].any() | a8649ab88ee8e84b44f7e0f20dc4f380dd4b0dde | 585,730 |
import ctypes
def _int_ptr(val=0):
"""Utility function to create integer pointers."""
return ctypes.pointer(ctypes.c_int(val)) | 7373f9006212a79f044710c6648c5aac04215a7b | 585,731 |
def convert_locp(locp, converter):
"""
Convert the given list of card plays using the converter
:param locp: CardPlays to convert
:type locp: [CardPlay, ...]
:param converter: method to convert a CardPlay
:type converter: CardPlay -> PyJSON or None
:return: the list of PyJSON
:rtype: [Py... | 23330bec68ef8b5a658f387f421144d88c2d5a39 | 585,733 |
def test_args(args):
""" Ensures arguments are properly formatted.
Inspired by `automated_scripts/cal_uvis_make_darks/cal_uvis_make_darks.py`
by M. Bourque.
Paramters
---------
args : object
Containing the image and destination arguments.
Returns
-------
args : object
... | 189360156b5ff031b9865b20aee984d77dd7c349 | 585,735 |
def format_artist(__, data):
"""Returns a formatted HTML line describing the artist."""
return "<li><a href='{artist_tag}/index.html'>{artist}</a></li>\n".format(**data) | 87cd2b9021dc31b938197b5d44bdad7fb0552819 | 585,736 |
import six
def convert_prefix_forced_case(data, prefix):
"""If <prefix> is a prefix of data, case insensitive, then force its case
This converter forces the case of a given prefix of a string.
Example, with prefix="Foo":
* 'foobar' converted into 'Foobar'
* 'fOozar' converted into 'Foozar'
*... | 960bbdb99ad6317a96be23ec2e95c87f5c60fc2e | 585,737 |
def build_directory(fileName):
"""construnct full path of for the file"""
csv_file_path = '/home/amaskey/Documents/log_analysis/csv/'
dirName = csv_file_path + fileName
return dirName | 88e3bf4a180fda1a0da8d6e7aac5d9e0b51421d6 | 585,738 |
import re
def device_name_convention(host):
"""
Helper filter function to filter hosts based targeting
host names which a specified naming convention
Examples:
- lab-junos-08.tst.dfjt.local
- lab-arista-22.prd.dfjt.local
- lab-nxos-01.lab.dfjt.local
:param host: The host ... | 5469d6c1569167e404952c9774afe6642fd4f65c | 585,739 |
def state_to_databases(state, get_state):
"""Convert the state to a dict of connectable database clusters.
The dict is:
{"databases": {
"databaseA": {
"master": "10.0.0.19",
"nodes": {
"10.0.0.9":
{
... | 0e1039dae02e1a7548002ef0724e3456f74dc4ce | 585,740 |
def pop_pseudo_headers(entries):
"""Remove and return HTTP/2 `pseudo-headers`__ from a list of headers.
__ https://tools.ietf.org/html/rfc7540#section-8.1.2.1
:param entries:
A list of header name-value pairs,
as would be passed to :class:`httpolice.Request`
or :class:`httpolice.Re... | a460d5c238052922d3294451d83f5bde5977b2fe | 585,741 |
def time_to_num(time):
"""
time: a string representing a time, with hour and minute separated by a colon (:)
Returns a number
e.g. time_to_num("9:00") -> 9 * 2 = 18
time_to_num("21:00") -> 21 * 2 = 42
time_to_num("12:30") -> 12.5 * 2 = 25
"""
time_comps = time.split(":")
... | 4112b8c59140c81a901d871f2cb0be4313817155 | 585,747 |
import torch
def hyab(reference, test, eps):
"""
Computes the HyAB distance between reference and test images
:param reference: reference image tensor (with NxCxHxW layout in the standard or Hunt-adjusted L*A*B* color space)
:param test: test image tensor (with NxCxHxW layout in the standard or Hunt-adjusted L*a... | fab79ed62b6773182e9d63db763dadece2f7f537 | 585,749 |
def get_command(data):
"""
Figure out what is the command being run from request data
:param dict data:
:return str:
"""
return data.get("command") | 88af37b52cdf976b2f7e8b07c0b025d6afade42e | 585,752 |
def is_valid_arp(pkt):
"""Check if a packet is arp."""
try:
return pkt[12:14] == b'\x08\x06'
except:
return False | d03348cabbdca2dd76032c30696ae67d93faeaaf | 585,757 |
import re
def parse_key_frames(string, prompt_parser=None):
"""Given a string representing frame numbers paired with parameter values at that frame,
return a dictionary with the frame numbers as keys and the parameter values as the values.
Parameters
----------
string: string
Frame number... | 5bd0090db5819561e4ba96a09019a89ef10d4acf | 585,759 |
def set_norm_options(opts, use_stable_statistics=False):
"""Set the IPU options related to norms.
Args:
use_stable_statistics: If True, computes the mean first and subtracts
the activations by it before computing the variance. The
implementation with this flag set to True is slower than when set
... | ce358ebbb36f3c7bf17831e426081db063b399e5 | 585,762 |
def Property(function):
""" Property(function)
A property decorator which allows to define fget, fset and fdel
inside the function.
Note that the class to which this is applied must inherit from object!
Code based on an example posted by Walker Hale:
http://code.activestate.com/recipes... | d96f12397502b58ab6e3021dd0a60c6cf6044f4a | 585,763 |
def is_inline(*points):
"""
Checks whether all given points are on a single line. The points order
is not important.
Args:
*points: ((float, float),)
Collection of points to check as (x,y) coordinates.
Returns:
bool
Returns True if all points are on ... | 3ce6ebcc6a94189736f8ecf7a543d81c3bac63d1 | 585,773 |
def get_analyzer_for(language_code, default='snowball'):
"""
Get the available language analyzer for the given language code or else the default.
:param language_code: Django language code
:param default: The analyzer to return if no language analyzer has been found.
Defaults to 'sno... | c0cd3d52e080d69dab4edb4033991f9099302946 | 585,774 |
import math
def circumference(r):
"""计算圆的周长
Args:
r ([float]): [圆的半径]
Returns:
[float]: [圆的周长]
"""
return 2 * math.pi * r | 0cde8cd681512a7d6d661fc03cdb4851356808fc | 585,775 |
def class_size(cls):
"""Get the number of bytes per element for a given data type.
Parameters:
cls (str): Name of the data type
Returns:
int: Number of byte per element
"""
if cls in ['float64', 'int64', 'uint64']:
n_byte = 8
elif cls in ['float32', 'int32', 'uint32']:
... | d645f16dde69594b4d2374066b984c93fb892267 | 585,777 |
from typing import List
from typing import Any
from typing import Tuple
def pairs(xs: List[Any]) -> List[Tuple[(Any, Any)]]:
""" Create a list of pair/tuples from a list """
return [(xs[i], xs[i + 1]) for i in range(0, len(xs) - 1)] | 3a2d3275ab2ef78880da88ba6b9d53cdccb017fc | 585,778 |
def get_last_month(month, year):
"""
Get last month of given month and year
:param month: given month
:param year: given year
:return: last month and it's year
"""
if month == 1:
last_month = 12
last_year = year - 1
else:
last_month = month - 1
last_year =... | a78de7164ee652903712f02d8c71a262eeb2e4f4 | 585,779 |
def median(lst):
"""
Calculates list mediana
"""
n = len(lst)
if n < 1:
return None
if n % 2 == 1:
return sorted(lst)[n//2]
else:
return sum(sorted(lst)[n//2-1:n//2+1])/2.0 | 5da9c14d7fe94dc9f2935c96b88b265583122127 | 585,780 |
from typing import Dict
def format_error(status: int, description: str) -> Dict[str, str]:
"""
Uniform error format for API responses.
:param status: the error status code
:param description: the error description
:return: a dictionary describing the error
"""
errors = {
400: 'Bad... | 135058517a04c38f1321c02ce8ce29e447d1920f | 585,781 |
def set_bit_at_pos(A: int, pos: int) -> int:
"""0-indexed, little endian
Args:
A:
pos:
Returns:
Examples:
>>> bin(set_bit_at_pos(int("0000", 2), pos=0))
'0b1'
>>> bin(set_bit_at_pos(int("0001", 2), pos=0))
'0b1'
>>> bin(set_bit_at_pos(int("0001"... | a13866274e4873655222123e9ade9e70361afc85 | 585,782 |
def __stretch__(p,s1,f1):
""" If a point has coordinate p when the steep/flat points are at s0/f0,
this returns its coordinates when the steep/flat points are at s1/f1.
This is necessary to preserve the colourmap features.
"""
s0 = 0.3125
f0 = 0.75
dsf = f0 - s0
if p <= s0:
... | 12caf11212be490ce81e4910a4d94619d63877b5 | 585,788 |
def num_bytes_to_struct_char(n: int):
"""
Given number of bytes, return the struct char that can hold those bytes.
For example,
2 = H
4 = I
"""
if n > 8:
return None
if n > 4:
return "Q"
if n > 2:
return "I"
if n > 1:
return "H"
if n =... | d5f014a610f8b5d12d88b87915718ff43a106c78 | 585,789 |
def intoDecimal(n): #converts the incoming character into decimal
"""
Input:
String value as 'n'
Returns:
Corresponding decimal value of 'n'
"""
return int(n,2) | 284bcd3d457ad6bf0245f2d00e74f47b7e7a75e9 | 585,790 |
def read_int(msg):
"""
-> Válida um número inteiro.
:param msg: valor digitado pelo usuário.
:return: valor inteiro validado
"""
while True:
try:
i = int(input(msg))
except (ValueError, TypeError):
print(f'\033[31mErro! Digite um número inteiro válido.\033... | 885bf978cdf9cda524924b00ed9355cdad52f6f5 | 585,791 |
def _construct_result(left, result, index, name, dtype):
"""
If the raw op result has a non-None name (e.g. it is an Index object) and
the name argument is None, then passing name to the constructor will
not be enough; we still need to override the name attribute.
"""
out = left._constructor(res... | d4023396166d5305b5729349c5fc2bf9896f528e | 585,792 |
def _greedy(I: list, w: list, v: list, K: int, greedness: str) -> tuple:
"""
Solve knapsack problem with asked greedness.
Parameters:
-----------
- I : items
- w : items' weights
- v : items' value
- K : knapsack size
- greedness : parameter to be gre... | 1bef9292857de9e1b839621d6d76de5bed9af827 | 585,793 |
from datetime import datetime
def is_date_in_month(d, m):
"""Determine if the given date is in the given month."""
d, m = datetime.strptime(d, '%Y-%m-%d'), datetime.strptime(m, '%Y-%m')
return d.month == m.month | 082d7fd090eef6277450acf343564de2fd0992c8 | 585,794 |
def balance_weights(labels):
"""
Generates a mapping of class weights that will re-weight a training set
in a balanced way such that weight(label) = len(obs) / freq(label in obs).
"""
counts = {}
for l in labels:
counts[l] = counts.get(l, 0) + 1
return {l: (len(labels) / counts[l]) ... | 8709a9c89831ec54232d2efeb50f1ad602d66526 | 585,795 |
import logging
def get_formatted_logger(log_level):
"""
Helper function to create and return a formatted logger
"""
class CustomLogFormatter(logging.Formatter):
def __init__(self):
super().__init__(datefmt="%Y-%m-%d %H:%M:%S")
def format(self, record):
if reco... | 0fe0f344ecd8cc90534b8a5c4f57c3b6f136e9bb | 585,800 |
def get_max_index(list_array):
"""
Get indexes of maximum values
Args:
list_array (list of numbers): List of integers from which we want to extract the index, as well as the maximum value selected
Return:
max_value (number): Maximum of the list_array
p... | 634d716f8f8403fb220976274b81257cd6d4081e | 585,801 |
import itertools
def uniquelines(q):
"""
Given all the facets, convert it into a set of unique lines. Specifically
used for converting convex hull facets into line pairs of coordinates.
Args:
q: A 2-dim sequence, where each row represents a facet. E.g.,
[[1,2,3],[3,6,7],...]
... | 8c9ffaf34865b77fca0c89820acbd7de6cdd3dab | 585,806 |
def parse_currency(string: str) -> str:
"""
Parse currency string.
:param string: Currency string
:return: Normalised currency string
:raises ValueError: on invalid string
"""
lookup = {'$': 'USD',
'£': 'GBP',
'€': 'EUR'}
if string in lookup:
return l... | 4f80b3aebb4e102993cd83d5886118ebe526db3c | 585,807 |
import importlib
def dotname2cls(dotname):
"""
The class associated to the given dotname (i.e. `pkg.subpkg.mod.cls`)
"""
modname, clsname = dotname.rsplit('.', 1)
return getattr(importlib.import_module(modname), clsname) | 336a181822248b4a6a98b33c33c31896ed6dcb98 | 585,809 |
def get_node_address_for_fabric(node):
"""Return the network address to be used by fabric to connect to the node
By convention the address used is the address of its first network interface
"""
return node.networks[0].address | 2c9f383b006462016576a8014b43767d23827789 | 585,810 |
import re
def camel_to_title(name):
"""Takes a camelCaseFieldName and returns an Title Case Field Name
Args:
name (str): E.g. camelCaseFieldName
Returns:
str: Title Case converted name. E.g. Camel Case Field Name
"""
split = re.findall(r"[A-Z]?[a-z0-9]+|[A-Z]+(?=[A-Z]|$)", name)
... | d90b48d9b26a072d22c478c31c469ed40712e78d | 585,814 |
from typing import List
def is_empty(stack: List[str]) -> bool:
"""
Check if a stack is empty.
We add this custom method, as Python does not have a built-in is_empty() method.
:param stack: is the stack to inspect.
:return: a boolean value determining whether the stack is empty or not.
"""
... | 5a2ca546c08c5c417526869d272ae353469fc30f | 585,816 |
def get_score(words_from_dialog, subs):
"""
:param subs: A list containing the substitles we try to match to this dialog line. sub.txt has to be BOW.
:param words_from_dialog: A dialog line (i.e. a character's dialog block from the screenplay) in BOW representation.
:return: the matching's score.
"... | bc259f3d84d975f177ff0ee7c2cb46d09ea2c397 | 585,821 |
import math
def highest_bit(num):
"""highest_bit(num) -> n
Determines the bit position of the highest bit in the given number.
Example: 0x800000 returns 24.
"""
try:
return int(math.floor(math.log10(num) / math.log10(2))) + 1
except OverflowError:
assert(num == 0)
retur... | c9441061e8ec7f7267b641d647477ad6f873ab17 | 585,823 |
def sort_by_visibility(objs: list) -> list:
"""
Sort a list of object by their visibility value (decreasing).
"""
s = True
while s:
s = False
for i in range(len(objs) - 1, 0, -1):
if objs[i].get_visibility_value() > objs[i - 1].get_visibility_value():
# S... | 3eafeefd5510501812745d26304ffff716374452 | 585,826 |
def count_common_connections(network, user_A, user_B):
"""
Finds the number of people that user_A and user_B have in common.
Arguments:
network: the gamer network data structure.
user_A: a string containing the name of user_A.
user_B: a string containing the name of user_B.
Returns:
Th... | 870ef7039227f2a1bc5b3cbfe9312494654495ab | 585,827 |
def generator_next(g):
"""
Return next elements in generator.
:param g|generator:
:rtype generator: return None if stopping iteration.
"""
try:
e = g.__next__()
return e
except StopIteration:
return None | c903c7675dbeb05f76401ea3ee4d8fdcbcc2592a | 585,830 |
def user_name(user):
"""Return the USER's name (string)."""
return user[0] | 138914a38f7043f222428232edaeeae06ea7a1c6 | 585,834 |
import html
def linebrk(s, n):
""" Break input string s with <br/> for every n charactors."""
result = ""
j = 0
for i, c in enumerate(s):
if j == n and i != len(s) - 1:
result = result + "\n"
j = 0
j = j + 1
result = result + c
result = html.escape(s... | bfae6d96ab042e283ade4358df69e23bacac4b5f | 585,836 |
import torch
def interface_r_vec(polarization, n_i, n_f, th_i, th_f):
"""
reflection amplitude (from Fresnel equations)
polarization is either "s" or "p" for polarization
n_i, n_f are (complex) refractive index for incident and final
th_i, th_f are (complex) propegation angle for incident and fina... | df8d1bca62871de9a8dd9d407274bfb10d05f516 | 585,857 |
from typing import Iterable
from typing import Any
from typing import Callable
def _find_first_index(
iterable: Iterable[Any], pred: Callable[[Any], bool]) -> int:
"""Returns the index of the first element that satisfies the predicate, or -1."""
for n, item in enumerate(iterable):
if pred(item... | 1f59d1dad6450a27b3d4b1b1a902b76ff00267be | 585,858 |
from functools import reduce
def get_eqns_unk (eqns, knowns):
"""Returns the list of unknowns, given the knowns, from a list of equations"""
if not isinstance(eqns, (list, tuple)):
eqns = [eqns]
atoms = reduce(lambda acc, eqn: acc.union(eqn.atoms()), eqns, set())
return filter(lambda x: not x.... | 565a5a2bedd1453aa7f15f651fbecb7dc21b1237 | 585,859 |
def reverseArray(data, dqMarker):
"""
reverses the contents of the array 'data'
before the spot marked by the int dqMarker
returns the array after reversing it
"""
print("Reversing array")
temp = -1
counter = 0
#iterate through the list until halfway point (not counting dqs... | 9873ba3f25cd5eef4a96fa10f662e604d8933299 | 585,861 |
import random
import string
def random_lower_string() -> str:
"""generate random lowercase str"""
return "".join(random.choices(string.ascii_lowercase, k=32)) | 99088578fa07387365391e8d91f9e777345586d5 | 585,869 |
def get_mask(source, source_lengths):
"""
Arguments
---------
source : [T, B, C]
source_lengths : [B]
Returns
-------
mask : [T, B, 1]
Example:
---------
>>> source = torch.randn(4, 3, 2)
>>> source_lengths = torch.Tensor([2, 1, 4]).int()
>>> mask = get_mask(source,... | 3042598f7fe1ecc0a9b4f69ab3e8fca6823e7d32 | 585,870 |
def filter_by_residue(residue, carbon_atoms):
"""
Higher order function that takes in a residue and carbon atoms
and returns a function that only evaluates to true if the atom
satisfies the criteria.
"""
def predicate(line):
if line['resName']==residue and line['name'] in carbon_atoms:
... | 5e7b5845cc0329a7352890b470825c589ac0c800 | 585,874 |
def _all_the_same(items):
"""
Checks whether all values in a list are the same.
"""
return all(items[0] == item for item in items) | 1413051180da39b834391ef166e905883bceb09e | 585,877 |
import torch
def cal_kld(mean, logv):
""" Calculate KL Divergence"""
# KL Divergence
kl_loss = -0.5 * torch.sum(1 + logv - mean.pow(2) - logv.exp())
return kl_loss | 6729c226197acb1f69f7b392f252544976fd17d1 | 585,883 |
def find_column(text, token):
""" Compute column number
Parameters
----------
text : str
The parsed text
token : sly.token
The token whose positition is to find
Returns
-------
int
The corresponding column number
"""
last_cr = text.rfind('\n', 0, token.i... | 41742b46e8e9c5d30a17444f2a38d6666068a95b | 585,888 |
def cubicPolyCoeffs(a, b, c, d):
"""Converts the four control points of a cubic Bezier curve into the degree-3 polynomial form.
Returns the coefficient of the monomials of degree 1, 2 and 3."""
return 3.0*(b-a), 3.0*(c - 2.0*b + a), d + 3.0*(b - c) - a | f2d628d90794f32715d095bec5ef83fac91d6c1f | 585,889 |
from typing import Any
from typing import Generic
def _is_instance_of_generic_class(instance: Any) -> bool:
"""
>>> class A: pass
>>> a = A()
>>> _is_instance_of_generic_class(a)
False
>>> from typing import TypeVar, Generic
>>> T = TypeVar('T')
>>> class B(... | 9593eda9f482b26979e6a030ce85d989862d385a | 585,893 |
def count_amplitudes(n_spinorbitals,n_electrons):
"""Count the number of singles and doubles amplitudes for a given UCCSD-VQE run
Args:
n_spinorbitals(int): integer representing the number of spinorbitals (qubits) for
a given molecule and basis set
n_electrons(int): ... | bb66f8b014695bc4c482b23b881b74e3592f0d65 | 585,895 |
def willoughby_wallaby(name):
"""
A function that converts the first letter(s) of your name to a "W"
:param name: Your name
:return: Your name, with the first one or two letters replaced with a "W"
"""
# A list of all the likely consonant blends
consonant_blends = ["bl", "br", "ch", "ck", ... | a4f36beb3dae652e31e984c53146d6b197efc8c1 | 585,896 |
def bfs(G, d, queue):
"""bfs: breadth-first search
Args:
G (list): G[i] is the list of neighbors of node i.
d (list): d[i] is the distance from the source to node i.
queue (collections.deque): queue of nodes to visit next.
Returns:
list: d[i] for all nodes i in the breadth-... | 0d9fa7ccd20f7c40b263d95a4bf54b13fc477c77 | 585,897 |
def value_or_none(value):
"""Return string value if not empty. Otherwise, returns None."""
if value.strip() == "":
return None
return value | cd330a8435074a75e13f1e257738df8850d18cf2 | 585,901 |
def is_input(port):
"""Judge whether the port is an input port."""
try:
return port.mode == 'r'
except Exception:
return False | bb23f90cef7e447595f1cc6938814968d69c7231 | 585,902 |
def w_s(integer):
"""
Reads in weather ID, and outputs a colour, marker, and weather name.
"""
# Setup empty vector for color and marker information
output=''
# Assign weather ID a colour and marker
# Clear night, white circle
if integer == 0:
color = 'white'
marker = 'o'
type = 'Clear Night'
# Sunny... | 33a73e31f79c048be65b6bcb322a00947dff6704 | 585,907 |
import re
def extract_time(file_name):
"""
extracts time and date from file_name
:param file_name: string, example "img-2021-08-07T18-02-19devID1.jpg"
:return: string, example "2021-08-07 18:02:19"
"""
result = re.findall(r"\d{4}-\d{2}-\d{2}", file_name)[0]
result += " "
result += re.f... | 2b892a845b95606e8d16ce5c4f67b5ae610d845a | 585,908 |
def _setdefault(obj, key, value):
"""
DO NOT USE __dict__.setdefault(obj, key, value), IT DOES NOT CHECK FOR obj[key] == None
"""
v = obj.get(key)
if v == None:
obj[key] = value
return value
return v | 853d73291f8f5d7802e17a8ac52e7c32a99f1699 | 585,910 |
import json
def extract_json(infile):
"""Returns distance and RSSI measurements as tuple"""
# Load JSON output
with open(infile, "r") as f:
data = json.load(f)
# Extract data
dist = float(data.keys()[0])
adict = data.values()[0]
rssi_list = adict.values()[0]
return (dist,rssi_list) | cc5f846e0d876e69c6e88d0fdd88234fd7e9b36c | 585,914 |
def eta(filesize, a, b):
"""
Determines how long the transfer of filesize bytes from A to B should take.
units for filesize are bytes, a and b is speed in kilobytes
"""
return filesize/(min(a, b)*1024) | 0f181922313f66f4d06a776a83bbab9ec1e4ac5f | 585,916 |
def truncate_stats(stat, threshold, name='Other'):
"""
Combines all entries (name, count) with a count below the threshold and appends a new entry
"""
a, b = [], []
for s in stat:
(a, b)[s[1] < threshold].append(s)
c = 0
for s in b:
c += s[1]
a.append([name, c])
retur... | c143288b633a2d11e6be224d3355b4a8d1ca2048 | 585,917 |
def initialize_counts_2(shots, hex_counts=True):
"""Initialize test circuits reference counts."""
targets = []
if hex_counts:
# Initialize 0 to |1> from |++>
targets.append({'0x1': shots / 2, '0x3': shots / 2})
# Initialize 1 to |1> from |++>
targets.append({'0x2': shots / 2,... | d9163c70010adaf8e230806cdc27728da9f5cda7 | 585,918 |
def sensor2int(float_sensor):
"""
Convert sensor data from float to int.
"""
int_time = int(float_sensor * 1000000)
return int_time | 4c7f07eb800e9debcb5d0ef02b73fad5354b99b8 | 585,920 |
import string
def remove_punctuation(myString):
"""Remove punction from input string
Arguments
- myString: a string of text
Returns:
- newString: a string of text without punctuation
"""
translator = str.maketrans('', '', string.punctuation)
newString = myString.tra... | 12f2d3ca6e231b341e6c106c59ac40d392c1cfcc | 585,922 |
import resource
def get_open_fd_limit() -> int:
"""
Return the OS soft limit of open file descriptors per process.
"""
soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
return soft_limit | 6e2806b8f7e1091ef27a368afb4e1ed985da10e1 | 585,925 |
def get_final_stage(args):
"""
Gets the final stage number, which depends on PGO or a stage one only build
:param args: The args variable generated by parse_parameters
:return: The final stage number
"""
if args.build_stage1_only:
return 1
elif args.pgo:
return 3
else:
... | d57db351b89a5e8e9a996802e997895b0aa792d5 | 585,927 |
import math
def is_prime(x, known_primes=None):
"""
Naively check if a number is a prime by checking for divisibility by 2 & all
odd numbers <= sqrt(x). Not the most efficient, but simple and it works.
Alternatively, if known_primes is a list of ints, we check if x is in that list
and don't do a... | 3b71d6410e980ea1528570e9f54d098924bc3b40 | 585,930 |
def parse_segment(data, pos):
"""Parses a single 7-segment digit from raw multimeter data
:param data: Raw multimeter data, aligned to 15-byte boundary
:type data: bytes
:param pos: Number of segment to parse (numbered left to right)
:type pos: int
:return: 7-segment digit configuration
:r... | 571432b51854d348451ff66dd6d4154960a4a6a2 | 585,931 |
def quantity_to_tuple(quantity, unit_str):
"""
Splits a quantity into a tuple of (value,unit) where unit is FITS complient.
Useful to write FITS header keywords with units in a comment.
Parameters
----------
quantity : astropy quantity
The Astropy quantity to split.
unit_str: str
... | e2ad3d83c7f68fd9d23b50e27fb42ff83d804b6c | 585,937 |
def get_audio_mode(mode):
"""
Get audio mode (channels mode) into a human easy readable format.
Arguments:
:param mode: integer
:return: string
"""
options = {0: "Stereo",
1: "Joint Stereo",
2: "Dual Channel",
3: "Mono",
}
return options.get(mode, "U... | dcf3ceb88e11c086b6260150f8bef440377c4731 | 585,938 |
def _format_credits(cs: str) -> str:
"""
Format credits data into a search link, if possible
"""
# no data
if not cs.strip():
return ""
# multiple artists, cant search
elif "|" in cs:
return cs
else:
search_link: str = (
r"https://www.nhk.or.jp/minna/s... | ccd2f4488b88e9f61af81f162dab11802946419e | 585,939 |
def concat_flex(row):
""" Concatenates the headers and contents of all the flex cells in one row of a submission and joins the list
on commas
Args:
row: the dataframe row containing the submission row flex fields
Returns:
A concatenated list of "header: cell" pairs ... | 937c14f0f5a49125afdcc728d460bae022d9ed2e | 585,943 |
import math
def progress_bar(
width: int,
progress: float,
end_char: str = '|',
fill_char: str = '-',
empty_char: str = ' '
) -> str:
"""
Draw a progress bar that shows the given progress. Will only be full at exactly 100% progress.
:param width: The width of the progress bar, inc... | 50278768e719134ca69e6715f70ceb31a98e2f26 | 585,945 |
def transform_bit_moments_to_pauli(mean_c, var_c):
"""
Changes the first two moments of a bit (a Bernoulli process) to Pauli operator moments.
E.g. if the original mean is on [0,1] the returned mean is on [-1,+1].
:param mean_c: bit probability of heads or tails.
:param var_c: variance of bit
... | 854e21a50c7f387376cbd93123477088d64b2b40 | 585,946 |
def _sorting_key(s):
"""Numerical/lexicographical sorting.
"""
try:
val = int(s)
norm = "{:010}".format(val)
except ValueError:
norm = s
return norm | 0e9a45ec1bb498752e05d954f1ce6557620024ba | 585,947 |
def _read_text_file_lines(file_name):
"""
Read text file lines.
Open a text file and read it, return a list of lines.
Parameters
----------
file_name: string
Path to the file to be read.
Returns
-------
list of strings
A list of lines.
"""
with open(file_n... | e5c12777b35289196ef13aced84709004a4968a3 | 585,955 |
import re
def str_cleaner(data_array, column_name, return_str_len=False):
"""Clean up formatting of technology description strings in imported data.
In the imported EIA data, the strings that describe the technology
and performance level have inconsistent formatting and often have
leading or trailing... | 86afd5e9ddbcc5d89b7859d785245485efd9a266 | 585,957 |
def angle_difference(a, b):
""" Compute angle difference (b-a) in the range of -180 deg to 180 deg.
:param a: Angle in degrees.
:paramtype: float
:param b: Angle in degrees.
:paramtype b: float:
:returns: (b-a) in range of -180 deg to 180 deg.
:rtype: float
Usage:
.. code-block:... | 0088a0202ce6ef599227c26b0ec05cf87da4667b | 585,958 |
import json
def get_genesis_content(accounts):
"""
Create genesis json for geth.
Accounts will be funded with 1 million ether.
Accounts[0] is the coinbase/etherbase
"""
# 1 Million ether
initial_balance = '0xD3C21BCECCEDA1000000'
data = {
"config": {
"chainId": 1213,
... | 1f848fa951cec19836c9203d75d96f12bc9bc739 | 585,959 |
def aumentar(preco, fator):
"""
--> Aumenta em uma dada porcentagem o valor inserido.
:param preco: valor a ser aumentado
:param fator: fator de aumento, em porcentagem
:return: valor aumentado
"""
final = (preco * (1 + fator/100))
return final | 1b30415ca9d380a708cfd9bc12620ef70a35e21c | 585,960 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.