content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def parse_url(url: str) -> str:
"""
Makes sure the URL starts with 'http://'
"""
# Replace HTTPS with HTTP (if exists)
url = url.replace("https://", "http://")
if url.startswith("http://"):
return url
return f"http://{url}" | 01155dede22db6211d2eafb30492a59663ceda69 | 618,949 |
def extract(str_value, start_='{', stop_='}'):
"""Extract a string between two symbols, e.g., parentheses."""
extraction = str_value[str_value.index(start_)+1:str_value.index(stop_)]
return extraction | 780731894102aa3c439e81b6a60983cd690b0fbf | 618,951 |
import time
def get_agg_log(db, sessionID, start='', end=''):
"""
Retrieve all Collection entries in a given time frame.
:param db: The database object.
:param sessionID: Current user's session ID.
:param start: (Optional) The start of the time frame.
:param end: (Optional) The end of the time... | acb37d78382837a2b02377cf6505373a447bd854 | 618,955 |
def graph_to_triples(digraph, sent):
"""
Convert a single graph to triples
"""
return ["{}\t{}\t{}".format(" ".join(sent[u[0]: u[1]]),
" ".join(digraph[u][v]["label"]),
" ".join(sent[v[0]: v[1]]))
for (u, v) in digraph.edges()] | c93d0f1111c031fe5e37affde4dc08dda07d99e8 | 618,956 |
from datetime import datetime
def weekday(date):
""" Generate day of the week based on date (as string or as datetime object)"""
if isinstance(date, str):
date = datetime.strptime(date, "%m-%d-%Y") # change the format if necessary # "%Y-%m-%d"
return date.strftime("%A") | c080c946e5b5de206604c32bbb8f826f4b1a703b | 618,964 |
def _is_macos(repository_ctx):
"""Determines if the host is running MacOS.
Args:
repository_ctx: A `repository_ctx` instance.
Returns:
A `bool` indicating whether the host is running MacOS.
"""
os_name = repository_ctx.os.name.lower()
return os_name.startswith("mac os") | 35d12c32243ebe6e7253cc863280dbe53d99b0e2 | 618,969 |
def run_episode(env, policy, gamma = 1.0, render = False):
""" Runs an episode and return the total reward """
obs = env.reset()
total_reward = 0
step_idx = 0
while True:
if render:
env.render()
obs, reward, done, _ = env.step(int(policy[obs]))
total_reward += (ga... | 0fe4fc9c43582567050764a015e53797446810b0 | 618,970 |
def get_wred_profiles(host_ans):
"""
Get all the WRED/ECN profiles of a SONiC switch
Args:
host_ans: Ansible host instance of the device
Returns:
WRED/ECN profiles (dictionary) or None.
Example format is given below:
{
u'AZURE_LOSSLESS': {
u... | 9d0d81727124fcbee13672e378b42d1c864bb34b | 618,972 |
def c_array_buf(ctype, buf):
"""Create ctypes array from a Python buffer."""
return (ctype * len(buf)).from_buffer(buf) | e3bb85f6e144564df9e47f6c9cf42261df538ea3 | 618,974 |
import requests
def requestCourseEnroll(sess, subject, cournum):
"""
Get a request instance from http://www.adm.uwaterloo.ca/cgi-bin/cgiwrap/infocour/salook.pl
after requesting the class enrollment data
Parameters:
sess: int or str
subject: str
cournum: int or str
Ret... | 2576291902ff1764648617fd0138f34ab6a78cad | 618,975 |
def get_header_list(sheet):
"""
Get a list of header row cell values.
:param sheet:
:return: Returns a list of values from the first row in the sheet.
"""
return [c.value for c in sheet.row(0)] | 9b9ec77529b8e24296316ab47bf8eadff44ffdf5 | 618,978 |
from typing import Sequence
def combine_dicts(dict_ls: Sequence[dict], strict=True, dict_class=dict):
"""Merges entries from one or more dicts into a single dict (shallow copy).
Args:
dict_ls (Sequence[dict]): sequence of dictionaries to combine.
strict (bool): whether to throw an exception i... | d07ee0aee98bf62a512dc6e170202371d25e178d | 618,979 |
def cast_keep_none(obj, dest_type: type):
"""
Cast ``obj`` to ``dest_type``.
If ``obj`` is ``None``, returns ``None``.
:param obj: object to be casted
:param dest_type: target type to cast `obj`
:return: casted `obj`
"""
if obj is None:
return None
if issubclass(dest_type,... | c461d21af4749affd3f4dcfbac2b3a76ff49742b | 618,989 |
import hashlib
def file_hash(file_path):
"""Returns the SHA-1 hash of |file_path| contents."""
chunk_size = 51200 # Read in 50 KB chunks.
digest = hashlib.sha1()
with open(file_path, 'rb') as file_handle:
chunk = file_handle.read(chunk_size)
while chunk:
digest.update(chun... | 1076f3587f5c427a83e9b8f8f193dc13a628a228 | 618,990 |
def isAlphanum(c):
"""return true if the character is a letter, digit, underscore,
dollar sign, or non-ASCII character.
"""
return ((c >= 'a' and c <= 'z') or (c >= '0' and c <= '9') or
(c >= 'A' and c <= 'Z') or c == '_' or c == '$' or c == '\\' or (c is not None and ord(c) > 126)); | c955f5f7417ebcb0ce391bbbe244c2938035de81 | 618,998 |
def _group_ccs_with_issuetracker(ccs_payload, ccs_issuetracker):
"""Group ccs from ggrc system and issuetracker.
Args:
- ccs_system: CCs on Issue Tracker Payload
- ccs_tracker: CCs from Issue Tracker
Returns:
list of grouped ccs from ggrc and issuetracker.
"""
ccs_system = set(cc.strip() for c... | e43265bca4eb7047aa9ab2f2ed0c49fabb0b5ed2 | 619,000 |
def is_prime(num):
"""Returns True if the number is prime
else False."""
if num == 0 or num == 1:
return False
for x in range(2, num):
if num % x == 0:
return False
else:
return True | 9dfcb3e6fd0022b6cf3ca3fa2253c3cc627a4615 | 619,005 |
def is_clone(g):
"""
Return True if the generator `g` is a clone of another generator, otherwise return False.
"""
return g.parent is not None | 6f9e801da93ce067fac21aa0797918b3a100b4d6 | 619,006 |
from typing import Counter
def createPositionLookup(frags, pos=1):
"""Create dictionary where key is subsetted fragment coords
(no start or no stop), value is the list of full fragments
that share the coordinates in the key.
Only entries where >1 full fragments share the same coordinate
are retain... | 3cf1855fb8cb2f9d228c556c8cecc9191b68897b | 619,009 |
def is_memcpy(cluster):
"""
True if `cluster` emulates a memcpy and the target object is a mapped
Array, False otherwise.
"""
return (len(cluster.exprs) == 1 and
cluster.exprs[0].lhs.function.is_Array and
cluster.exprs[0].lhs.function._mem_mapped and
cluster.exprs... | 9af0ec028bfd313d2100bfabc4ebf21fe85f72e4 | 619,016 |
import logging
def info_blocref(app, doctree, fromdocname, class_name,
entry_name, class_node, class_node_list):
"""
Log information with :epkg:`Sphinx`.
@param app application (Sphinx)
@param doctree document tree
@param fromdocname ... | 17d5736a164334499290fca3f2d0eb6106fc2219 | 619,022 |
def contains_only(seq, aset):
""" Check whether sequence seq contains ONLY items in aset. """
for c in seq:
if c not in aset: return False
return True | 918e8e166f9f78085cce30205ccec379870734fd | 619,024 |
def compile_function(name, code, globs):
"""
Given a *code* string, compile it with globals *globs* and return
the function named *name*.
"""
co = compile(code, "<string>", "exec")
ns = {}
eval(co, globs, ns)
return ns[name] | 541752401fda091928e7ca172472473268b075e2 | 619,025 |
from typing import Callable
from typing import Tuple
def retry_fn(fn: Callable, allowable_exceptions: Tuple, retry_count: int=5):
"""
Call fn, retrying if exception type in allowable_exceptions is raised up to retry_count times
"""
for i in range(0, retry_count):
try:
return fn()
... | d531751d7e3b1706667c3d2a66c57844f0334888 | 619,034 |
def last(x):
""" Returns the last element of a series.
Params:
x (pd.Series)
Returns:
scalar of x.dtype
"""
return x.iloc[-1] | da2f54b818f4c02ffe24233a0b0384273f79b3fe | 619,035 |
def _round(*args, unit=1):
"""Return `args` normalized by `unit` and rounded."""
return tuple(round(x / unit, 3) for x in args) | 235f00ce6eb0036f75d4cbf55f83e0ecef284ea4 | 619,039 |
from typing import List
from typing import Union
from typing import cast
def concat_tokens(tokens: List[Union[str, bool]]) -> str:
"""Concatenate the tokens in the output list.
Parameters
----------
tokens: list
List of string and boolean values
Returns
-------
string
"""
... | 9363155607e1de1cc8d9330dda40c1d8cf95fe0b | 619,041 |
def box(text: str, lang: str = "") -> str:
"""Put content in a code block
Parameters
----------
text: :class:`str`
The text to place in the code block
lang: :class:`str`
The language for the block
Defaults to an empty string
"""
ret = "```{}\n{}```".format(lang, text... | eaa7a840a63c04805a57770a5a2a1451ba33b7bf | 619,043 |
def pulses_plugin(pulses_workbench):
"""Setup the workbench and return the pulses manager plugin.
"""
return pulses_workbench.get_plugin('exopy.pulses') | 480a24ce3c4d8d1f765af8f5921f8315ffd62df3 | 619,044 |
import typing
def py_sorted(numbers: typing.List[int]) -> typing.List[int]:
"""The Python sorted algorithm.
Args:
numbers (typing.List[int]): A list of integers.
Returns:
typing.List[int]: A list of integers ordered from smallest value
to largest value.
"""
return sorted(... | a22abb349b6bf720c556029df4a427665363bc76 | 619,045 |
def _DetermineNamespacePrefix(unused_url):
"""Returns the SOAP prefix to use for definitions within the given namespace.
Args:
unused_url: string The URL of the namespace. The DFA library doesn't
actually check this value.
Returns:
string The SOAP namespace prefix to use for the given na... | 91f6fbf5332d7e816c4cb77e12f9bb39109dbae9 | 619,048 |
from typing import Tuple
from typing import Set
def _process_line(line: str) -> Tuple[str, str, Set[str]]:
"""Return the pathway name, url, and gene sets associated.
:param line: gmt file line
:return: pathway name
:return: pathway info url
:return: genes set associated
"""
name, info, *e... | 41c2ce42f7142aa9cff081adc8646c9c2b8c9a4a | 619,050 |
def supplies_value(value):
"""Creates a function that returns the specified value when invoked."""
return lambda _: value | 1395432c6d1c98d64f5651b2292f5c89338915ea | 619,053 |
def calculate_text_size(text):
"""
Simplistic function that calculate a size of a text based on the number and type of characters.
It uses an averaged size for lower/upper-case, digits, spaces and underscores.
It also assumes that the font is using latex "scriptsize" text size.
"""
text_size = 0... | c31282a416393f639c95097df694445d32cc50a2 | 619,055 |
def search_linearw(a, x):
"""
Returns the index of x in a if present, None elsewhere.
"""
i = 0
while i < len(a) and a[i] != x:
i += 1
if i == len(a):
return None
else:
return i | 1c974754aac62074d546fa0ebb88be584ecdca31 | 619,057 |
def equal(a, b):
"""
Case insensitive string compare.
@param a: String to compare.
@param b: String to compare.
@return: True if equal, False if not.
"""
return a.lower() == b.lower() | afe665f72b434dd23dd6abc36ac90f052d4e6e82 | 619,059 |
import csv
def parseList(string):
"""
Decomposes strings like '"val1,val2",val3,"val4,val5"'
into a list of strings:
[ 'val1,val2' ,'val3', 'val4,val5' ]
"""
for line in csv.reader([string],delimiter=","):
values = line
#for i,value in enumerate(values):
# values[i] = valu... | 66cd73e80b67621576f2571e99ac328672acc440 | 619,060 |
def _csr_filename(file_prefix):
"""
Construct the name of a file for use in storing a certificate signing
request.
:param str file_prefix: base file name for the certificate signing request
(without the extension)
:return: certificate signing request file name
:rtype: str
"""
re... | ad338fce85b403e96fa49957b78978069a8b2218 | 619,061 |
def _load_version() -> str:
"""Load version from VERSION file"""
from pathlib import Path # pylint: disable=import-outside-toplevel
here = Path(__file__).parent.resolve()
with open(str(here / "VERSION")) as version_file:
return version_file.read().strip() | 78cbf3cf23ab01926590aaf95f7d8cf2c5b81f68 | 619,063 |
import gzip
def fopen(p, flag="r"):
"""Opens as gzipped if appropriate, else as ascii."""
if p.endswith(".gz"):
if "w" in flag:
return gzip.open(p, "wb")
else:
return gzip.open(p, "rt")
else:
return open(p, flag) | dc9eaaf69e7ce8bc4d148b4e586ea6decbb75a38 | 619,065 |
import math
def encode_integer_vlq(value: int) -> bytes:
"""Encode an integer with the unsigned VLQ encoding.
:param int value:
The value to encode. Must be a non-negative integer.
:return: ``value`` encoded as a variable-length integer in VLQ format.
:rtype: bytes
"""
if value < 0:
... | cfa18bb646ae6eb8a67c3ef09c5aabb9ba1902e3 | 619,067 |
def bbox_xr(dataset):
"""Get the lon/lat bounding box (minx, miny, maxx, maxy) from an xarray dataset"""
if "lat" in dataset.coords:
y = dataset["lat"]
elif "y" in dataset.coords:
y = dataset["y"]
else:
raise ValueError("dataset {} must contain 'lat' or 'y'".format(dataset))
... | 723f7e5aea91e306048adbb42f35eda280cb1f25 | 619,072 |
from typing import Optional
from typing import List
from typing import Dict
def all_checks_passed(runs: Optional[List[Dict]]) -> Optional[bool]:
"""
check whether all checks from a PR head ref have completed and passed
"""
if runs is None:
return None
for c in runs:
if c['status'] ... | 15f0f4a11506d284b5b9feb434e3f4306eeb2cf7 | 619,073 |
import re
def txt2list(txt_path=None):
"""
Load txt file and split the sentences into a list of strings
"""
if txt_path is None:
raise ValueError("txt_path must be specified as a named argument! \
E.g. txt_path=../dataset/yourfile.txt")
# Read input sequences from .txt file and pu... | 8fdb9ec2991f820fb58ee9706ff520c132b6ab3b | 619,076 |
def _annotate_point(ax, annot_tuple, xytext=None, **kwargs):
"""
Use ax to annotate a given tuple.
annot_tuple should be (text, (x,y))
but can have additional postional or keyword args
EG: (text, (x,y), {'rotation': 45})
Extra args will be merged with kwargs. This allows for global se... | 058d989446cb31ae3842f74770777d640875e5f8 | 619,077 |
def remove_duplicates(lst: list):
"""Remove duplicates from list while preserving order."""
vals = set()
return [i for i in lst if i not in vals and (vals.add(i) or True)] | c634da68a2d0d84c731ea82b0621290981338f7e | 619,079 |
import copy
def _create_output_header(header):
"""Create the header of the output file from the input file.
Keep most metadata, but remove view, multiView and channel information and add comment.
"""
header = copy.deepcopy(header)
header['channels'] = {}
header.pop('view', None)
header.po... | bb332a31c9b01c34664acfe09b7600f7bbdab776 | 619,082 |
def _common_neighbors(set_one: list, set_two: list) -> int:
"""
Calculate Common neighbors score for input lists
:param set_one: A list of graph nodes -> part one
:param set_two: A list of graph nodes -> part two
:return: Common neighbours score
"""
return len(set(set_one) & set(set_two)) | 73f71a9bfb33d2f367e41727f0fea46b0f2b1371 | 619,085 |
def parse_thumbprint_from_openssl_output(raw_fingerprint):
"""Parses the thumbprint value from the raw OpenSSL output.
Example output from openSSL:
SHA1 Fingerprint=3B:C3:70:46:00:0C:B2:0B:F9:86:98:CF:9D:11:DF:EB:22:B7:41:F5
Returns:
string : The certificate thumbprint.
"""
return raw_... | 40e2cb2970377d5500af8685c1c6461456bb3d21 | 619,090 |
def make_versioned_tag(tag, version):
""" Generate a versioned version of a tag. """
return '%s-%d' % (tag, version) | 621efd19766fbd87acc393324247092ca71da1d3 | 619,096 |
import yaml
def parse_config(config_file):
"""Parses a config file written in the YAML-format.
"""
return yaml.load(config_file, Loader=yaml.FullLoader) | 7ccda1a7c49fed5f01f6fdfb55a0cd7456edcb48 | 619,097 |
def var(image):
"""The variance of pixel intensities"""
return image.var() | 46a5c765f1d8ee43f0d483e72ae179e87d881ddf | 619,100 |
def PATCH_getControlSurfaceCount(tixi, comp_seg_uid):
"""
Function to get the number of Control Surfaces
Function 'getControlSurfaceCount' returns the number of control surface
(only TED) on a given component segment.
Args:
:tixi (TIXI Handle): TIXI Handle of the CPACS file
:comp_s... | 1eda2df358fb7a26b39bdc3ab97428251210d263 | 619,103 |
def mix_labellers(labellers, class_name="MixtureLabeller"):
"""Combine Labeller classes dynamically.
The Labeller class aims to split plot labeling in ArviZ into atomic tasks to maximize
extensibility, and the few classes provided are designed with small deviations
from the base class, in many cases on... | 729c8621b530ecc9d150717750887a3d5148b30f | 619,104 |
def test_size(STDictonary_root, count=0):
"""Test function for the size counter of the STDict-class, STDictonary_root = root of STDict to test , O(n)"""
if STDictonary_root is None:
return count
else:
count += 1
count = test_size(STDictonary_root._left, count)
count = test_si... | bf992f36bc0c337c36cf49e15e16636055b4ce1d | 619,106 |
def tab(contents, num_spaces):
"""
Inserts the specified amount of spaces in front of each line of the contents
"""
return "\n".join(["%s%s" % (" " * num_spaces, line) for line in contents.splitlines()]) | 4cbce515ade7ab61514d972ea8cad11db2eacfad | 619,109 |
def desnake(string):
"""snake_case -> snake case"""
return " ".join(string.split("_")) | baed8cea5fe1b312c012ee198f8c43d9d46856c7 | 619,113 |
def get_longest_matching_prefix(word, prefix_list):
"""Find the longest prefix of word that is in prefix_list. None otherwise."""
to_return = None
for i in range(len(word)):
prefix = word[: i + 1]
if prefix in prefix_list:
to_return = prefix
return to_return | ab71579c326e8ef00009b37c4242bc44a37e6b99 | 619,114 |
def gp_predict(gpmodel, para_array_rescaled):
"""Returns a Gaussian Process prediction of PCA weights
Parameters
----------
gpmodel: GPflow object
Trained GPflow model corresponding to a particular redshift
para_array_rescaled: ndarray of shape (5, )
Rescaled Cosmological paramete... | c4df97f3e9bb26c762dfe6751753ef8037863b6a | 619,117 |
def onedmoffat(x, H, A, dx, alpha, beta):
"""
Returns a 1-dimensional moffat of form
H + A * (1 + ((x-dx)/alpha)**2)**(-beta) """
return H + A * (1 + ((x-dx)/alpha)**2)**(-beta) | 4b22c2830deaf737aed879321064e7036a0cf3a7 | 619,124 |
def user_is_resource_editor(user):
"""
Single test for whether a user is in the Resource Editor group
"""
return user.groups.filter(name="Resource Editor").exists() | 733bb6d44d6b868ba6af60adcb338000c381a609 | 619,127 |
import json
def load_endpoint_json(path):
"""
Loads a given JSON file & returns it.
:param path: The path to the JSON file
:type path: string
:returns: The loaded data
"""
with open(path, 'r') as endpoints_file:
return json.load(endpoints_file) | 686ce3263513ba0c1b478c360dc4fd58d5a5c76c | 619,128 |
import difflib
def closest_title(title, series):
"""
Return closest movie name in a given dataframe.
-------
Parameters:
title (string): Movie name
series: (pandas Series): Series to search for closest title
"""
matches = difflib.get_close_matches(title, series)
if matches:
... | 4052122f8cf141eff1ad59ccf019144f81392220 | 619,132 |
def rosenbrock(tensor):
"""
Compute Rosenbrock function.
# https://en.wikipedia.org/wiki/Test_functions_for_optimization
"""
x, y = tensor
return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2 | ab036bf21aa5a23739a1c560da409a59af3ea4cb | 619,133 |
def merge_intervals(intervals, delta= 0.0):
"""
A simple algorithm can be used:
1. Sort the intervals in increasing order
2. Push the first interval on the stack
3. Iterate through intervals and for each one compare current interval
with the top of the stack and:
A. If current interval... | e1748216507b90bdf5d4e126b9dd0fd591bcc7ed | 619,137 |
def ten_recipes_result(recipes, puzzle):
"""Return 10 recipes after the recipe number puzzle."""
return ''.join(str(num) for num in recipes[puzzle:puzzle + 10]) | 68ab52c82c9756ba9bc6972312f33601a5218064 | 619,139 |
def scrub(input_string):
"""Clean an input string (to prevent SQL injection).
Parameters
----------
input_string : str
Returns
-------
str
"""
return "".join(k for k in input_string if k.isalnum()) | a2ba76721d23a8acec8cdb917cb841d181360702 | 619,140 |
def read_torrent_file(filepath):
"""Reads torrent file from filesystem and returns its contents."""
f = open(filepath, 'rb')
contents = f.read()
f.close()
return contents | 644c7e0c3b39957a3eba54bd8455768c290d4795 | 619,141 |
def get_log_print_level(client):
"""Get log print level
Returns:
Current log print level
"""
return client.call('get_log_print_level') | 425a7395904e007e6f894e06b7ee04cd8893b718 | 619,144 |
def drawCutoffVert(ax,x,cl="r",lb="",ls="--",lw=.5):
"""
This method draws a vertical cutoff line or lines
:Arguments:
:type ax: matplotlib axis
:param ax: axis to draw lines on
:type x: int/float or list of ints/floats
:param x: x value(s) on which to draw cutoff lines
... | ae689d83b960c47f3fe496c1fe1c89b15ce9cabb | 619,148 |
def new_bname(filename, suffix):
""" return a new basename (without path, without extension, + suffix) """
filename = filename[filename.rfind("/"):]
filename = filename[:filename.rfind(".")]
return filename + "_" + suffix | c93dc6e27b01c9fac12f2e964fee19fb29436963 | 619,149 |
def compare_version(version1, version2):
"""
Compare version strings.
Return 1 if version1 is after version2;
-1 if version1 is before version2;
0 if two versions are the same.
"""
v1_arr = version1.split(".")
v2_arr = version2.split(".")
len1 = len(v1_arr)
len2 = le... | 0b6adc3861a8925d8ce69481927feac7e8d7bab0 | 619,152 |
import csv
def load_csv(csvpath):
"""Reads the CSV file from path provided.
Args:
csvpath (Path): The csv file path.
Returns:
A header list
A list of lists that contains the rows of data from the CSV file.
"""
with open(csvpath, "r") as csvfile:
data = []
... | dd17a63b09a85ec4cc4953016a20a61bb4a31c6f | 619,157 |
def wrap_line(line):
"""Add end of line at character eighty, to match PDB record standard."""
output = ""
for i in range(0, len(line), 80):
output += "%s\n" % line[i : i + 80]
return output | 92a8d482361fd58d43364e4a2a05aea395bb375a | 619,158 |
import time
def make_time_stamp(tim):
"""Make timestamp in ISO format from UTC time in seconds."""
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(tim)) | 45de1be2e10ab05381f4342a089695cb55a3fb94 | 619,161 |
import re
def compare(asm_simulation_output, asm_correct_outputs):
"""
Compare the student's circuit output with the correct one
:param asm_simulation_output: File containing the simulated outputs
:param asm_correct_outputs: File containing the correct outputs
:return: Percentage of correctness
... | 565fa112e7d3c293dd1abec97a12701df1298b6b | 619,163 |
def quick_sort(collection):
"""Pure implementation of quick sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> quick_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
... | 9e01efdf6d13820c1a37c282a7386b1f20abed15 | 619,164 |
def getGRBComboQuery(GRB):
"""
Get the several versions of a GRB name that could come up in ADS searches.
E.g., 010222A, 10222A, GRB010222A, GRB1022A
:param GRB:
The GRB to get name combinations of.
:type GRB:
:class:`str`
:returns:
String of GRB name combinations separa... | 69f61760d35bd7dd68128359eba857ba11d1a4b4 | 619,166 |
def to_pomdp_file(agent, output_path=None,
discount_factor=0.95):
"""
Pass in an Agent, and use its components to generate
a .pomdp file to `output_path`.
The .pomdp file format is specified at:
http://www.pomdp.org/code/pomdp-file-spec.html
Note:
* It is assumed that th... | 69e12bd64c5ef773ed7fe58719cb06cb57c6c486 | 619,168 |
import math
def calc_sides(coords, angle):
"""Calculates the four points of the car (top and bottom right & left)"""
length = 50
top_left = [
coords[0] + math.cos(math.radians(360 - (angle + 30))) * length,
coords[1] + math.sin(math.radians(360 - (angle + 30))) * length
]
top_right... | 5b74ec319a8e32fead70a29c90f1634fb174f81a | 619,170 |
def strip_comments(line,ws_too=False):
"""
Strips comments from a line (and opptionally leading/trailing whitespace).
"""
bam = -1
ix = 0
while True:
bam = line[ix:].find('#',bam + 1)
if bam == -1:
break
bam = ix + bam
if bam == 0:
return '... | 054ec7f0dff2e91344ce2e4388695d6645e22ab8 | 619,171 |
import csv
def read_csv(path):
"""
Reads the CSV file at path, and returns a list of rows. Each row is a
dictionary that maps a column name to a value in that column, as a string.
"""
output = []
for row in csv.DictReader(open(path)):
output.append(row)
return output | 1da5749b32aa3ec28894a448295e86e5786cce1b | 619,173 |
from datetime import datetime
def from_epoch(epoch: int, tz_offset: int = 0) -> datetime:
"""
Returns a datetime from an epoch int with optional UTC timezone offset
"""
return datetime.fromtimestamp((epoch - tz_offset) / 1000) | bb0866fae4f397399f637e53b11babd1d6ce74df | 619,174 |
def base32_decode(base32_value: str) -> int:
"""
Convert base32 string to integer
Example 'A' -> 10
"""
return int(base32_value, 32) | 3abebc1d84830a016c8beb880a3aedb14838c428 | 619,177 |
from typing import List
def get_text_as_list(self) -> List:
"""
Returns the text in it's logical form as a list of lines.
:param self: Texteditor-Class
:return: List of lines containing the text. Lines cane be empty Strings.
"""
return self.line_string_list | c05a2c37f4bd079b80b23f6aa272450fac782e0c | 619,179 |
def add_milliseconds_to_epoch_time(epoch_time):
"""
Add 1 millisecond so we would not get duplicate incidents.
Args:
epoch_time: Epoch time as it is in the raw_content
Returns:
epoch_time with 1 more millisecond.
"""
epoch_time = int(epoch_time / 1000 + 1) / 1000
return epoch... | f33366b42651c437ffd0ca8bc8983ec167c89aac | 619,181 |
def _check_uniqueness_of_entries(data_set, data_set_name=None, raise_exception=True):
"""
Check if all entries in iterable are unique in iterable
Parameters
----------
data_set : [list, set]
iterable containing the entries to test for uniqueness
data_set_name : str, optional
the... | 9f0580981ad191d1575cf6b1c01a12c4d97bcd08 | 619,182 |
import re
def get_element_namespace(element):
"""
Gets the namespace of an element.
:param element: Element to get the namespace of.
:return: Namespace of given element.
"""
result = re.match("{.+}", element.tag)
return result.group(0) if result else "" | 6748c346a8d6842a35884bc711c817a00b125516 | 619,183 |
def sequences_to_dictionary(sequence, index):
""" Converts a sequence of sequences to a dictionary, where the dictionary key is the entry at
index in the subsequence, i.e. if index = 1 then:
[[1, "45"], [2, "46"]]
becomes
{
"45": [1, "45"],
"46": [2, "46"]
}
Args:
... | 2aa913a913cfa2fc658f1cf059957530cf43e300 | 619,184 |
def check_valid_multiple(category: str, field: str, val: str, multiple: int) -> str:
"""Check valid value being a multiple
Parameters
----------
category : str
category of open insider screener
field : str
field from category of open insider screener
val : str
value's fi... | 55b9a58bf44f3f209831f64652a6fa6ae0a9dd75 | 619,187 |
def escape_facet_value(value: str) -> str:
"""Escape and quote a facet value for an Algolia search."""
value = value.replace('"', r"\"").replace("'", r"\'")
value = f'"{value}"'
return value | 243a315568d51b4866c049a6b989398bd7171380 | 619,190 |
def add(a: float, b: float):
"""
Add two floats.
This is a very nice function that performs the following operation
.. math:: c = a + b
Parameters
----------
a : float
First parameter
b : float
Second parameter
Returns
-------
c : float
This value ... | afb590a1f84b2423ffdcb4411c50cdca3753abe2 | 619,192 |
import yaml
def update_config(cfg):
""" Updates the config file with the given settings. """
with open('config.yml', 'w') as outfile:
yaml.dump(cfg, outfile, default_flow_style=False)
return None | 956d77e08c1047823b9e7002c0f29763a4728a18 | 619,197 |
import re
def dict_from_sdkconfig(path):
"""
Parse the sdkconfig file at 'path', return name:value pairs as a dict
"""
regex = re.compile(r"^([^#=]+)=(.+)$")
result = {}
with open(path) as f:
for line in f:
m = regex.match(line)
if m:
result[m.gr... | ac52b59f2179033ee265d3ea0b8dbdaabfc7740e | 619,199 |
def add_options(options):
"""
A decorator to add a set of options to a click command. This allows options that
are used in multiple places to be defined in one place.
:param options: A list of click options to add to the command
"""
def _add_options(func):
for option in reversed(option... | 2802f26f84401002744247eca087b0b3e7b4c8f2 | 619,201 |
def getBridgeDBPID(pidfile="bridgedb.pid"):
"""Read the ``bridgedb.pid`` file in **rundir**, if it exists, to get the
PID.
:param str pidfile: The path to the BridgeDB pidfile.
:rtype: int
:returns: The process ID, if available, otherwise ``0``.
"""
fh = None
try:
fh = open(pidf... | 246c98acb20b85ad5980e57628f0d62bd82dda8c | 619,202 |
import re
def latexify_spacegroup(spacegroup_symbol):
"""
Generates a latex formatted spacegroup. E.g., P2_1/c is converted to
P2$_{1}$/c and P-1 is converted to P$\overline{1}$.
Args:
spacegroup_symbol:
A spacegroup symbol
Returns:
A latex formatted spacegroup with p... | ca741f12e88993749dad84d46af2fb511ebc2a8e | 619,204 |
def query_mysql(cnx, query, args=None, dict_=False):
"""Run query and return results."""
cursor = cnx.cursor(dictionary=dict_)
cursor.execute(query, args)
results = cursor.fetchall()
cursor.close()
return results | a9dfdef9618793c6e69ce6dcfd78de8c4585f6af | 619,205 |
def add_homeruns(user, player_id, hrs):
"""Add a hr by a player
Parameters:
user: the dictionary of the user (dict)
player_id: the player id (int)
hrs: the number of hr hit (int)
Returns:
user: the update user (dict)
"""
for __ in range(0, hrs):
user['game'][... | 554c35c96540ee1a376c5e5c754434f06cef6400 | 619,208 |
def remove_properties_containing_None(properties_dict):
"""
removes keys from a dict those values == None
json schema validation might fail if they are set and
the type or format of the property does not match
"""
# remove empty properties - as validations may fail
new_dict = dict()
for... | 1835b14491a7a31bfe9b763486e4ee06f1aff583 | 619,211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.