content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def plain_text_to_html(string):
"""Convert plain text to HTML markup."""
string = string.replace("&", "&")
return string | 8dfaf9287ec8f765d77c241e2161c1729cb8c422 | 624,374 |
def slice_doubles(doubles):
"""Get the heads and relations from a matrix of doubles."""
return (
doubles[:, 0:1], # heads
doubles[:, 1:2], # relations
) | 35ffcc48382f78c9c547eb49fcde19413d2a9f5b | 624,380 |
import copy
def tuple_to_string(tuptup):
""" Converts a tuple to its string representation. Uses different separators (';', '/', '|') for
different depths of the representation.
Parameters
----------
tuptup : list
Tuple to convert to its string representation.
Returns
-------
... | a11fa135e5e001b57c6c4c0255de6e3896e97048 | 624,381 |
import torch
from typing import Dict
def update_lr(lr_scheduler: torch.optim.lr_scheduler._LRScheduler) -> Dict[str, float]:
"""
Update lr scheduler and returns the current learning rate as a summary
- Parameters:
- lr_scheduler: A `torch.optim.lr_scheduler._LRScheduler` to update
- Returns: ... | 1b8bae8f88a9f4b1044485251b87661bfef6bfb9 | 624,382 |
from typing import List
import torch
def _pad(tokenized: List[torch.Tensor], value: int) -> torch.Tensor:
"""Utility function that pads batches to the same length."""
batch_size = len(tokenized)
max_len = max(len(t) for t in tokenized)
output = torch.zeros((batch_size, max_len), dtype=tokenized[0].dty... | 9f495cd5bd779f24521081b0ad7fa67557eb82a0 | 624,387 |
def compose_submit_url(contest: str, contest_no: int) -> str:
"""
与えられたコンテスト名、コンテスト番号から
提出先のURLを生成する
Parameters
----------
contest : str
コンテスト名. ABC, ARC or AGC
contest_no : int
コンテスト番号
Returns
----------
url : str
対応する提出先のURL
"""
host = 'https:/... | 00389ba253aa4094cb4995adc58b9c3b0f40250f | 624,389 |
def cap_at_n(lines, n=2000):
"""
Takes in a list of strings and joins them with `\n`, but no more than n
characters. The Discord message character limit is 2000.
"""
text = ""
for line in lines:
if len(text) + len(line) + 1 < n - 3:
text += line + "\n"
else:
text += "..."... | 0203fc5acff6da3be6a8ee5ac7b0a3d7c2d02e0d | 624,390 |
import random
def improved_evaluation_function(game_state, agent, **context):
"""
This simple evaluation functions improves the basic one by adding some
randomness when choosing among non final states.
In some cases this evaluation function behaves better than the basic one
since it can block oppo... | a5f1b8007a018fcbe83c10a126c42d4d4fabb74e | 624,392 |
def str_to_bool(value):
"""
Convert a human readable string into a boolean.
"""
valuestr = str(value).lower()
if valuestr in ['1', 'yes', 'enable', 'true']:
return True
elif valuestr in ['0', 'no', 'disable', 'false']:
return False
else:
raise Exception("Unable to con... | d5de50a562aee6fbfc02a852b9642010598e05a9 | 624,393 |
import uuid
def generate_uuid(class_name: str, identifier: str,
test: str = 'teststrong') -> str:
""" Generate a uuid based on an identifier
:param identifier: characters used to generate the uuid
:type identifier: str, required
:param class_name: classname of the object to create a... | 223b9b80fcd3579db2846c6d3c79394aef7d5612 | 624,394 |
from typing import Type
def isnestedclass(cls: Type, scope: Type) -> bool:
"""Returns true, if the given class ``cls`` is a member on an outer class ``scope``."""
for mroClass in scope.mro():
for memberName in mroClass.__dict__:
member = getattr(mroClass, memberName)
if isinstance(member, Type):
if cls ... | 0233013f446e7e16b751947b7ab57d5b1e7e0254 | 624,395 |
def midPoint(pointA,pointB):
"""
Input : two points A,B.
Output : Midpoint of these two points
"""
X = int(pointA.x+pointB.x)/2
Y = int(pointA.y+pointB.y)/2
return (X,Y) | 402fbd8fe95e4ff42f2aacd57ed8a9ed41c1be8d | 624,397 |
def _throw_exception(exception: Exception):
"""Returns a function pointer for a function throwing an arbitrary
exception"""
def _throw(*args, **kwargs):
raise exception
return _throw | 53ce9c1edb2d6101fe2fa99fad9963eca576c086 | 624,398 |
def summation(lower, upper):
"""returns the sum of the numbers from lower through upper"""
#!base case
if lower > upper:
return 0
#!recursive case
return lower + summation(lower + 1, upper) | 54ff82089e8f422ade4fa7e384c50cce37ab635b | 624,400 |
def get_recommended_modification(simple_order, impact):
"""
Generate a recommendation string from an operator and the type of impact
:param simple_order: simplified operator
:param impact: whether the change has positive or negative impact
:return: formatted recommendation string
"""
bigger_... | 4f23de8adfdae94a1bb609e7b6eb5dcf81388bd0 | 624,403 |
def grb_rate_wp(z, z_inhom=0.):
"""Returns the rate of Gamma-Ray Burst, per comoving volume, evaluated at the specified redshift.
Ref:
Wanderman, Piran: Mon.Not.Roy.Astron.Soc.406:1944-1958,2010
Args:
z (float): redshift
z_inhom (float): redshift where the universe becomes inhomogenous... | cd6b809953448cde9596c1cf3a695216a316b2b5 | 624,406 |
import hmac
def calculate_message_signature(key: str, msg: str):
"""
calculate a message signature using a SHA1 HMAC
:param key: the secret token
:param msg: the message
:return: the calculated HMAC
"""
return hmac.new(key.encode(), msg=msg.encode(), digestmod='sha1').hexdigest() | d38ca1d4c219cc3e3e47b87c0ad71e4921f63e93 | 624,413 |
from typing import List
def calculate_pages(page_range_string) -> List[int]:
"""
Calculate a list of pages from the ranges given as CLI parameter page-range.
:param page_range_string: CLI parameter page-range
:return: list of pages in given range
"""
page_ranges = page_range_string.split(',')... | 7dcc0c297ce065efe5caa689cf4b8eb9b17d55c7 | 624,414 |
def stringXor(a, b):
"""
Calculates the bitwise xor for every value of the arrays. The arrays need to be
equally long
:param a: The first array
:param b: The second array
:return: The calculated result
"""
if len(a) != len(b):
raise Exception("stringXor: the two arrays must have... | a5d86a8821b6143e02a0d64d7d269e04c5c3069d | 624,418 |
def strip_trailing_nl(s):
"""If s ends with a newline, drop it; else return s intact"""
return s[:-1] if s.endswith('\n') else s | c408b7fd409d5706e22aceb1072792224245e280 | 624,419 |
def permdb(ind, beta=0.5):
"""Perm function D, BETA defined as:
$$ f(x) = \sum_{i=1}^d (\sum_{j=1}^n (j^i+\beta) ((\frac{x_j}{j})^i - 1) )^2$$
with a search domain of $-n < x_i < n, 1 \leq i \leq n$.
The global minimum is at $f(x_1, ..., x_n) = f(1, 1/2, ..., 1/n) = 0.
"""
return sum(( \
... | f8f776dd9a41a31be421b0b518d0ced5abd6adf3 | 624,423 |
def hashable(cls):
"""Makes sure the class is hashable.
Needs a working __eq__ and __hash__ and will add a __ne__.
"""
# py2
assert "__hash__" in cls.__dict__
# py3
assert cls.__dict__["__hash__"] is not None
assert "__eq__" in cls.__dict__
cls.__ne__ = lambda self, other: not sel... | 77649d82d592eaf3e8a1acff15fff3402056d6b9 | 624,424 |
import random
def random_tuple(k, n):
"""
Return a random tuple of k integers lower than n, all differents, uniformaly
"""
t = random.sample([x for x in range(n)], k)
return tuple(t) | b568ff85cb67a76a6e14abb96e21b5913cbf4803 | 624,428 |
from typing import Dict
from typing import Any
def dict_get(prop: str, obj: Dict[str, Any]) -> Any:
"""
Get value of prop within obj.
This simple function exists to facilitate a partial function defined :ref:`here<is_utterance>`.
:param prop: A property within a :code:`dict`.
:type prop: str
... | 5589690676736f5744654822c261ad4692d2d9b6 | 624,430 |
def inexact(pa, pb, pc):
"""Direction from pa to pc, via pb, where returned value is as follows:
left: + [ = ccw ]
straight: 0.
right: - [ = cw ]
returns twice signed area under triangle pa, pb, pc
"""
detleft = (pa[0] - pc[0]) * (pb[1] - pc[1])
detright = (pa[1] - pc[1]) * (pb[... | 31b7643c5fc9c91294a7aef9c81acd6205a80b16 | 624,434 |
def release_to_text(release):
"""
Translate this Release object into a text string that would trigger this
plugin's matcher.
In other words, translate the release into something that could match
ReleaseTask.from_text().
:param release: txproductpages.release.Release object
:returns: str, l... | 7c74f5749089dbbe64028f17e93355bb9fe63c7c | 624,445 |
import torch
def collate_fn(batch):
"""
Specify batching for the torch Dataloader function
:param batch: each batch of the JsonlDataset
:return: text tensor, attention mask tensor, img tensor, modal start token, modal end token, label
"""
lens = [len(row["sentence"]) for row in batch]
bsz... | 6d2f9facac3fd0718eb5e9fdc78ff16eca2391a7 | 624,446 |
from bs4 import BeautifulSoup
def create_soup(path):
"""
Reads a file and returns a lxml-xml BeautifulSoup object.
"""
with open(path, encoding="utf8") as f:
return BeautifulSoup(f.read(), "lxml-xml") | de7d0978b875d0a77432fcdfe3326b6fff162456 | 624,448 |
def rt_range_overlaps(rt1, rt2):
"""
inputs:
rt1: metatlas.datastructures.metatlas_objects.RtReference
rt2: metatlas.datastructures.metatlas_objects.RtReference
returns:
True if there is overlap in the RT min-max regions of rt1 and and rt2
"""
return ((rt2.rt_min <= rt1.rt_mi... | ae37524475114607f4ae5e5bf757a309e96506f0 | 624,450 |
def split_half(args):
""" Split the given list into two parts (equal if possible, if not
the right one gets one more)
Arguments
---------
args : list
list to split
Returns
-------
list, list
Args split in two parts
"""
split = int(len(args) // 2)
return arg... | ed326308ab83f8f725585971fc951073f7bc1f4d | 624,451 |
def get_fit(eq_individual):
"""Given an Equation object, it will return its fitness score."""
return eq_individual.get_fitness() | da50793b1aed9093516f6f1a4b2ca2d33afe71ea | 624,457 |
def rubygems_homepage_url(name, version, repo='https://rubygems.org/gems'):
"""
Return a Rubygems.org homepage URL given a name, optional version and a base
rubygems `repo` web interface URL.
For instance: https://rubygems.org/gems/mocha/versions/1.7.0 or
https://rubygems.org/gems/mocha
"""
... | 4ee2b9c80a6b5908ec755ad900009dd242316f5f | 624,459 |
import importlib
def import_class(what):
"""Import a class by given full name.
Args:
what (str): a string with full classname to import
Return:
(type): a class which has been imported
"""
modulename, classname = what.rsplit('.', 1)
module = importlib.import_module(modulename)
... | d47665d1373d427de1858f629b39279529d6635f | 624,460 |
import math
def polysum(n, s):
"""
n: Number of sides
s: Length of each side
returns: sum of the area and square of the perimeter of the regular polygon
"""
area = (0.25*n*s*s)/math.tan(math.pi/n)
perimeter = n*s
sum = area + perimeter**2
return round(sum,4) | d2e7be6f8f02c7b5d481a08fed7f35aa8aa1c411 | 624,464 |
def dict_join(*dicts):
"""Join multiple dicts into one, updating duplicate keys from left-to-right
manner.
Thus the items from the rightmost dict will take precedence."""
rslt = {}
for d in dicts:
rslt.update(d)
return rslt | 4d4810cb4ad07676a0359b63eedf072e598d51f3 | 624,465 |
def parse_hour(hour, sep=':') -> tuple:
"""Returns a tuple of integer from an hour like '14:34'."""
if not isinstance(hour, str):
return hour
return tuple([int(x) for x in hour.split(sep)]) | 95a9dd6bfd80ed1ac2350a8e75d5a8dfa9892e7a | 624,469 |
def valid_dictionary_word(word, words_list):
"""Function to check if the word is in the dictionary.
Args:
word (str): word to test
words_list (list): the "dictionary"
Returns:
bool: wether or not the word is in the dictionary
"""
if word in words_list:
return True
... | a74883830eed0c5c9af27168eb9b2b45c49b0437 | 624,470 |
def create_multidimensional_list(shape, element=None):
"""Creating a multidimensional list
The recusion using list comprehension was obtained from create_empty_array_of_shape()
at stackoverflow. Erko added element and the possibility to let element be a list.
For example shape = [2... | 5a619bbb658bf0ebc7657baeb6fb9ee91205c9e0 | 624,477 |
def get_transfer_stats(client, pg_vol_snap_name):
""" Returns a tuple of (started time, progress) """
transfer_stats = client.list_volumes(names=pg_vol_snap_name, snap=True, transfer=True)[0]
return (transfer_stats["started"], transfer_stats["progress"]) | 09d9657ece762386b36e2a7ff5c49c550b346011 | 624,481 |
def _getsubnodetext(node, name):
"""Get an element from an XML node, raise an error otherwise.
Parameters
----------
node: Element
XML Element
name: str
Child element name
Returns
-------
test: str
Text contents of the child nodes
"""
subnode = node.find... | 123b089d6e615a972d15424255fca3ac4ad10def | 624,482 |
import re
def isNegative(phrase):
"""
Returns True if the input phrase has a negative sentiment.
Arguments:
phrase -- the input phrase to-be evaluated
"""
return bool(re.search(r'\b(no(t)?|don\'t|stop|end)\b', phrase,
re.IGNORECASE)) | ae7760d9200db664b8312d1eb8527099901e4469 | 624,485 |
def freq_at_bit(in_data: list, position: int) -> tuple:
"""Returns frequency of bit '0' and '1' in the position 'position' for input data (list of str)
Args:
in_data (list): list of str
position (int): position to check the bit in
Returns:
tuple: (int, int)
"""
bits = [0, 0] ... | 82be7bbde95ec66d332160b1c58e598ea8157ddd | 624,486 |
def pixel_points(y1, y2, line):
"""
Converts the slope and intercept of each line into pixel points.
Parameters:
y1: y-value of the line's starting point.
y2: y-value of the line's end point.
line: The slope and intercept of the line.
"""
if line is None:
... | 00c33c53fffb63ab52af74e4d4b77bf4b3756533 | 624,487 |
from typing import List
def get_valid_package_keys_matching(all_keys: List,
input_key: str) -> List[str]:
"""Return a list of keys of graph nodes that match a package input.
For our use case (matching user input to package nodes),
a valid key is one that ends with the ... | 3faf693ceb1b0207f3479b3e9a5f97e0cd120c93 | 624,488 |
from typing import Optional
from typing import List
from typing import Tuple
def dict_flatten(
attrs: dict,
delim: Optional[str] = None,
indent_char: Optional[str] = None,
bullet_char: Optional[str] = None,
) -> List[Tuple[str, str, str]]:
"""Recursively flattens dictionary to its atomic elements.... | 5bb7c49786b1a2e8ef169cf8b9b4be37c9352abe | 624,490 |
def get_givenl(l, osc, osckey):
"""
Returns frequencies, radial orders, and inertias or uncertainties of a
given angular degree l.
Parameters
----------
l : int
Angular degree between l=0 and l=2
osc : array
An array containing the individual frequencies in [0,:] and the
... | a4fd5ebb25c404fa8164016801af189f0a9088de | 624,496 |
def isintlike(value):
"""
Checks if an object can be converted to an integer.
@param value: {object}
@return {bool}
"""
try:
int(value)
return True
except (TypeError, ValueError):
return False | 43c98f6bf7bf7a20a83a64356e0b3fb3c6ce6a4b | 624,499 |
def map_outputs(building_name, outputs, mapping):
"""
Maps outputs from EnergyPlus to OPC tags
Inputs:
building_name- The name of the building
outputs- List of values from EnergyPlus
Outputs:
[(OPC_tag, value)]- List of tuples of tags and values
"""
output_tags = mapping[building_name]["Outputs"]
ret = []
... | 5b858205d5ecc80dafb7c74443b5bfa219a1e3d3 | 624,504 |
def slack_escape(text: str) -> str:
"""
Escape special control characters in text formatted for Slack's markup.
This applies escaping rules as documented on
https://api.slack.com/reference/surfaces/formatting#escaping
"""
return text.replace("&", "&").replace("<", "<").replace(">", ">... | 46dd7c138e117a45b4b567d9b63a15de8b4332a0 | 624,505 |
def strip_none(none_list):
"""
Given a list that might contain None items, this returns a list with no
None items.
:params list none_list: A list that may contain None items.
:returns: A list stripped of None items.
"""
if none_list is None:
return []
results = [x for x in none... | 7529f2f559defb57f7e935c0ad869b40116274b4 | 624,507 |
def coding_problem_49(arr):
"""
Given an array of numbers, find the maximum sum of any contiguous subarray of the array.
For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements
42, 14, -5, and 86. Given the array [-5, -1, -8, -9], the maximum su... | 9cf09e1813e0315f45939e097986ac782309fb52 | 624,508 |
import typing
import re
def get_package_namespace(package: str, namespaces: typing.Dict[typing.Union[str, None], str]) -> typing.Tuple[str, str]:
""" Get the prefix and URI for the namespace of an SBML package
Args:
package (:obj:`str`): SBML package id (e.g., ``fbc``, ``qual``)
namespaces (:... | f4b5339fc2f7eaab0081e787a60bca2621d586dd | 624,509 |
import math
def atan_norm(value):
"""The arctan function grows more and more slowly as its input
increases, so it is applied in hope of reducing the influence
of possible outliers.
Args:
value (int): Byte frequency of a byte integer between 0-255.
Returns:
float: arctan nor... | 1e7dacd497fd572aa7f8e0c9ac4b9ce22cca4074 | 624,510 |
def _edgeness(hxx, hyy, hxy):
"""Compute edgeness (eq. 18 of Otero et. al. IPOL paper)"""
trace = hxx + hyy
determinant = hxx * hyy - hxy * hxy
return (trace * trace) / determinant | eca87ae8ecee269fbbdaa84a3070a0eb86f6a47d | 624,513 |
def parse_wgac_alignment(wgac_alignment):
"""
Parses a WGAC alignment from a list into a tuple of tuples for each sequence
in the alignment.
"""
wgac_alignment[1:3] = map(int, wgac_alignment[1:3])
wgac_alignment[5:7] = map(int, wgac_alignment[5:7])
return (
tuple(wgac_alignment[:4]),... | 41f8130604e54bac8510b785d33ca9c672de69c1 | 624,516 |
def format_taxon(taxonomy):
""" Format the taxonomy string. """
genus = taxonomy.split(';')[-2]
organism = taxonomy.split(';')[-1]
return [genus, organism] | de0e83cf7d4fa6fe381597b40a117ccc80ac4814 | 624,520 |
import torch
import math
def matern_spectrum(
w: torch.Tensor,
amplitudes: torch.Tensor,
lengthscales: torch.Tensor,
nu: float = 1.5,
) -> torch.Tensor:
"""Evaluate the Matern 5/2 power spectrum element-wise at ``w``.
Args:
w: The (dimensionless) frequencies at which to evaluate the p... | cda62315cb017a2cf4ced7d4240bb5e9d4f97635 | 624,523 |
def is_in_list(item, list_, kind):
"""Check whether an item is in a list; kind is just a string."""
if item not in list_:
raise KeyError(f"Specify {kind} from {list_}: got {item}")
return True | 25887a0b22061149777d2f6b5a2f792c6bcfc1a7 | 624,527 |
def none_bool(x):
"""Implementation of `none_bool`."""
return False | efd1f31f6daf029c237ff27632a0a743ed4e7d96 | 624,528 |
def validate_management_key_id_against_chain_id(key_id, chain_id):
"""
Checks if the chain in the key_id matches the value supplied in chain_id.
Parameters
----------
key_id: bytes or str
The partial or full key identifier
chain_id: str
The chain ID
Raises
------
Un... | da02214f46528298f1c3ca336ffef2df3529b638 | 624,529 |
def get_lomb_amplitude(lomb_model, i, j):
"""
Get the amplitude of the jth harmonic of the ith frequency from a fitted
Lomb-Scargle model.
"""
return lomb_model['freq_fits'][i-1]['amplitude'][j-1] | e4d0da88d90e53d8be1a0dab540c14db89918ba7 | 624,530 |
def _can_create(model):
"""Returns True if the given model has implemented the autocomplete_create
method to allow new instances to be creates from a single string value.
"""
return callable(getattr(
model,
'autocomplete_create',
None,
)) | b8d81da32bc4f69373996617aef7cd2dd06ff3b6 | 624,532 |
def selection_sort(t_input):
""" Selection Sort Algorithm
Simple, stable algorithm with in-place sorting
http://en.wikipedia.org/wiki/Selection_sort
Best case performance: O(n^2)
Worst case performance: O(n^2)
Worst Case Auxiliary Space Complexity: O(n)
:param t_input: [list] of numbers
... | e50c3d6ab420eeccf674dbb7a5b68f2cbdba1eac | 624,533 |
def isQualified(name):
"""
Check if a property name is qualified
"""
return name.find(':') != -1 | e01cbbd4219542b830f9ce8070e9761d7a3b03c2 | 624,534 |
def patch(program: list[int], noun: int, verb: int) -> list[int]:
"""Restore the gravity assist program
:param program: Intcode program
:param noun: updated noun value
:param verb: updated verb value
:return: patched Intcode program
"""
program[1] = noun
program[2] = verb
return pro... | 0822a15abb354f235e7a14ff05c255a2bc300af4 | 624,542 |
def build_json_response(status, value):
"""
Generate json format from input params
:param status: string
:param value: string
:return: json array
"""
return {
'status': status,
'message': value
} | 28785fabcf56af4e3a9b2172d6a4efc8718867cc | 624,543 |
import re
def parse_chains(chains):
"""Parses a given chains string returned from the MySQL DB
"""
## Turns "A:100:1:aa" -> "A", "100", "1", "aa"
## I.e.: chain_id = A, num_residues = 100,
## selected = 1/True, type = aa/amino acids
## NOTE:
## - aa = amino acid
## - na = nuc... | 6695eda3c8355345fa4251107fb282f11dc3ecb1 | 624,544 |
def _StoryToGtestFilter(story_name):
"""Returns a gtest_filter to run only tests generating data for |story_name|.
WebRTC perf tests story names and gtest names are different and use different
formats (e.g. snake case vs camel case). This function uses some heuristics
to create a gtest filter that will allow P... | c200aaf8d746dc41bd4fa053ec673321c4c931b9 | 624,546 |
def _transform_to_rc_coords(start, end, read_length):
"""Transforms the given start and end coordinates into the RC equivalents using the given read_length."""
return read_length - end - 1, read_length - start - 1 | c072a5992ba5cd11d16a30cdf9432a8c1f6bdb30 | 624,554 |
def segment(*segments):
"""Select a (list of) segment(s)."""
vsegment = [t for t in segments]
return {"segment": vsegment} | 7c5e816ab721969eedad412bc9e5749af1259f2c | 624,556 |
def _var_names(var_names):
"""Handle var_names input across arviz.
Parameters
----------
var_names: str, list, or None
Returns
-------
var_name: list or None
"""
if var_names is None:
return None
elif isinstance(var_names, str):
return [var_names]
else:
... | f9887e46f0c6f836e84be1aabec4ead8b6f977f9 | 624,558 |
def get_partial_failure_messages(client, response):
"""Get a list of all partial failure error objects for a given response.
Shows how to retrieve partial_failure errors from a response message (in
the case of this example the message will be of type MutateAdGroupsResponse)
and how to unpack those erro... | 80da221ad810533ceb81797fcec56d12b41e552d | 624,559 |
def fast_zeta_transform(counts, size):
"""
高速ゼータ変換
ret[s]: sum of counts[t] (t ⊆ s)
https://qiita.com/Euglenese/items/260f9ddf513f772d7e42#本題
O(2^N * N); len(counts) == 2^N
:param list of int counts:
:param int size:
"""
assert (1 << size) == len(counts)
dp = list(counts)
for... | af3917b935295d1f3131af3f776eb118054a8df5 | 624,560 |
def _limit(query, hints):
"""Applies a limit to a query.
:param query: query to apply filters to
:param hints: contains the list of filters and limit details.
:returns: updated query
"""
# NOTE(henry-nash): If we were to implement pagination, then we
# we would expand this method to suppo... | b52a6476c598b54ec4b2cd34bb563ba16f91216a | 624,562 |
def get_power( df ):
"""
Creates a Pandas DataFrame containing the power of the JV curves.
:param df: DataFrame containing the JV curves.
Values are currents, index is voltage.
:returns: A Pandas DataFrame containg the power at each voltage index value.
"""
pwr = df.mul( df.index, axis ... | a45cca425971cf45dc48efc704a1019d37a578e1 | 624,563 |
from typing import Dict
def get_operating_json(json: Dict) -> Dict:
"""
Get operating in rawsec json.
Parameters
----------
json: Dict
rawsec json.
Returns
-------
Dict
operating dict.
"""
return json["operating_systems"] if "operating_systems" in json else {} | 3ff570d50305cce04b2c0b1a4eaef0511d5ffb13 | 624,564 |
def init_record(msg):
"""Initialize a TaskRecord based on a request."""
header = msg['header']
return {
'msg_id' : header['msg_id'],
'header' : header,
'content': msg['content'],
'metadata': msg['metadata'],
'buffers': msg['buffers'],
'submitted': header['date... | 1fbb3136354423acbb028d7a1c340d41faad555c | 624,566 |
import re
def template_token_subst(buf, key, val):
"""
Given a string (buf), a key (e.g. '@@MASTER_IP@@') and val, replace all
occurrences of key in buf with val. Return the new string.
"""
targetre = re.compile(re.escape(key))
return re.sub(targetre, str(val), buf) | 4ecf929203506223a66e634660bf259c441c7640 | 624,567 |
def expand(dirs):
"""
Expands four directions per CSS convention.
`dirs` may be a four-element iterable of (top, right, bottom, left), or
a two-element iterable of (top-bottom, left-right), or a single-element
iterable or a plan value for all four directions.
@return
A `tuple` of top, ri... | eefe32892f2fee6f9b84f74ad7366868372dad25 | 624,569 |
def isint(x):
"""Test whether an object is an instance of int."""
return isinstance(x, int) | 4413f2cc4feca99914323e33afaf75401f9ac3cb | 624,571 |
import glob
def get_globfiles(fileglob, minfiles=1, maxfiles=1):
"""
Get file(s) matching ``fileglob``. If the number of matching
files is less than minfiles or more than maxfiles then an
exception is raised.
:param fileglob: Input file glob
:param minfiles: Minimum matching files (None => n... | 15318ed3c7c7c80f70295ca9a74d7fb6f5b299fd | 624,572 |
def is_at_least_one_not_none(*args):
"""
>>> is_at_least_one_not_none(1, 2, 3)
True
>>> is_at_least_one_not_none(None, 2, 3)
True
>>> is_at_least_one_not_none(1, None, 3)
True
>>> is_at_least_one_not_none(1, 2, None)
True
>>> is_at_least_one_not_none(1, None, None)
True
>... | 5239b68798b630e9a0508f85a4a5fb5678a68fda | 624,573 |
from typing import Any
from typing import Mapping
def is_mapping(obj: Any) -> bool:
"""Just a shorthand for instancecheck on :py:class:`typing.Mapping`.
"""
return isinstance(obj, Mapping) | 00d4312cf3e1bce1b663329ce880ea41926b5f24 | 624,574 |
def _highest_error_only(errors):
"""Removes any duplicate concentrations that have lower errors.
This script take a list of errors and concentrations and returns
only the highest error for each concentration.
Parameters
----------
errors : list of lists of floats
A list containing [err... | ad2642e89b699ec400572d0f868858337fe66e25 | 624,577 |
from typing import Any
from typing import Iterable
def is_atom(entity: Any) -> bool:
"""Everything that is NOT an iterable(except strings) are considered atoms.
>>> is_atom("plain string")
True
>>> is_atom(1)
True
>>> is_atom([1, 2])
False
Added in version: 0.1.0
"""
... | 45014fdb6569fd2f273b21af7d9425638bd4746f | 624,581 |
def find_name(slaves, name):
"""Function: find_name
Description: Locates and returns a slave's instance from an array of slave
instances.
Arguments:
(input) slaves -> List of slave instances.
(input) name -> Name of server being searched for.
(output) Slave instance or N... | 90be5b22b4d4fdd0a93e1df2abb6565933cdd10f | 624,583 |
def format(keyword: str, keyword_style: str) -> str:
"""Returns formatted keyword
Args:
keyword: target keyword
keyword_style: formatting style
Returns:
formatted keyword
"""
expected: str = keyword
if keyword_style == 'lower':
expected = keyword.lower()
if... | 0ec8a52be9fd62f92ba13659166b1ea06e1c2ec0 | 624,584 |
import socket
def get_hostname() -> str:
"""Returns the fully-qualified domain name of the server this code is
running on.
"""
return socket.getfqdn() | 8f2f65498a993c1034f26991369613d05c0bd083 | 624,587 |
import requests
import json
def get_ipaddr(url='http://httpbin.org/ip', proxy=None):
""" gets the external IP address """
if proxy:
proxy = 'http://{0}'.format(proxy)
proxies = {'http': proxy, 'https': proxy}
response = requests.get(url, proxies=proxies)
else:
response = r... | e8e6a531ad1e3de74e05f78db20d8fa71907c74c | 624,588 |
def ensure_divisible_by(feats, N):
"""Ensure that the number of frames is divisible by N.
Args:
feats (np.ndarray): Input features.
N (int): Target number of frames.
Returns:
np.ndarray: Input features with number of frames divisible by N.
"""
if N == 1:
return feat... | bb8da0adc85dcb6fec3f3dfc2aebef1a23156cf2 | 624,590 |
import json
def load_json(path: str) -> dict:
"""Get json schema to format from file.
Args:
path(str): path to json.
Returns:
(dict): db.
"""
with open(path, "r", encoding="utf-8") as file:
return json.load(file) | 32063ce9c5bf7be26d601aeeb247bc849fdfb889 | 624,591 |
import torch
def get_column(data: torch.Tensor, i):
"""get a column from a tensor.
Args:
data (torch.Tensor): a matrix
i (int): the index of column
Return:
column (torch.Tensor): a vector with a shape (:, 1).
"""
d = data.size(dim=-1)
x = data.view(-1, d)
retur... | f2019c092a5d79c807afd394e479a2544bbf7163 | 624,592 |
def get_table(table, expand=False):
"""
Return GRIB2 code table as a dictionary.
Parameters
----------
**`table`**: Code table number (e.g. '1.0'). NOTE: Code table '4.1' requires a 3rd value
representing the product discipline (e.g. '4.1.0').
**`expand`**: If `True`, expand output dicti... | 0b028cd5de28bcada1af86a2d1edf457f93cc05d | 624,595 |
def b(s):
"""Byte string with LSB first into an integer.
>>> b("1")
1
>>> b("01")
2
>>> b("101")
5
"""
return int(s[::-1], 2) | 3519d44ab4248d338590340bbb3d7c22e1d6619c | 624,598 |
def add_points_to_skills(skills, embedding_2d):
"""Add x and y points from 2 dimensional skills embedding
to skills dataframe
Args:
skills (df): skills dataframe
embedding_2d (array): skills embedding with 2 dimensions
Returns:
df: skills dataframe with additional columns for x... | 82e699d940660164750802ebb3c8b8d98cc4be9b | 624,600 |
import math
def specify_significant_figures(float_value, num_sig_figs):
"""Round float_value to num_sig_figs significant figures."""
try:
# Find my_mult, my_exp such that float_value = my_mult*10^my_exp
# such that 1. <= my_mult < 10.
my_exp = math.floor(math.log10(abs(float_value))... | cec7b793401962cf04509c099f76c5f29389fc24 | 624,601 |
def duplicate(N, Elem):
"""
N = integer() >= 0
Elem = T
List = [T]
T = term()
Returns a list which contains N copies of the term Elem. For example:
> lists:duplicate(5, xx).
[xx,xx,xx,xx,xx]
Note: Function taken from Erlang -
http://erldocs.com/17.3/stdlib/lists.html#duplicat... | 57aa86a7e555485f61813b423389ea823327fc9c | 624,603 |
import torch
def confidence_mask(tensor: torch.Tensor, confidence: float) -> torch.Tensor:
"""
Returns the masked form of the input tensor with respect to given
confidence
Arguments:
tensor (torch.Tensor): tensor to be masked by confidence
confidence (float): confi... | 2c2117f343dbba63e0b6e29d82ed847e87b4285a | 624,604 |
def slug_from_id(page_id: str) -> str:
"""Extract Notion page slug from the given id, e.g. lwuf-kj3r-fdw32-mnaks -> lwufkj3rfdw32mnaks."""
return page_id.replace("-", "") | 9f38ae38540666ca3b439852883390068924a2f4 | 624,607 |
def contains_memory(memoryrange, memory):
"""Returns True if the given `memory` is in `memoryrange`, False if not."""
for field, value in memoryrange.lower.ListFields():
if getattr(memory, field.name) < value:
return False
for field, value in memoryrange.upper.ListFields():
if ge... | 91133402ee4e150fde8bfa85e4c4a84363ef9c20 | 624,608 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.