content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def dates(min_year=None, max_year=None):
"""Return a strategy for generating dates.
.. deprecated:: 3.9.0
use :py:func:`hypothesis.strategies.dates` instead.
All generated dates will be between min_year and max_year, inclusive.
"""
note_deprecation('Use hypothesis.strategies.dates, which s... | 5,308,000 |
def _get_top_left_coordinates(height, width, patch_size):
"""Calculate coordinates of top-left corners for patches."""
n_h = math.ceil(height / patch_size)
n_w = math.ceil(width / patch_size)
tops = np.linspace(0, height - patch_size, n_h, dtype=int)
lefts = np.linspace(0, width - patch_size, n_w, ... | 5,308,001 |
def NoCallback(*args, **kwargs):
"""Used where the conclusion of an asynchronous operation can be
ignored.
"""
pass | 5,308,002 |
def create_stream(data_type, transaction_id):
"""
Construct a 'createStream' message to issue a new stream on which data can travel through.
:param data_type: int the RTMP datatype.
:param transaction_id: int the transaction id in which the message will be sent on.
"""
msg = {'msg': data_type,
... | 5,308,003 |
def pdg_case ( error ) :
"""Classify according to PDG prescription
- see http://pdg.lbl.gov/2010/reviews/rpp2010-rev-rpp-intro.pdf
- see section 5.3 of doi:10.1088/0954-3899/33/1/001
The basic rule states that
- if the three highest order digits of the error lie between 100 and 354, we round to... | 5,308,004 |
def step_impl(context):
"""
:type context: behave.runner.Context
"""
raise NotImplementedError(u'STEP: And Response BODY "GET" is non-empty') | 5,308,005 |
def _version_string_to_tuple(version_string):
"""Convert a version_string to a tuple (major, minor, patch) of integers."""
return (int(n) for n in version_string.split('.')) | 5,308,006 |
def load_environmental_variables(file) -> bool:
"""Populates the environment with variables from a .env file.
:param file: path to the file with environmental variables.
:returns: ``True`` if variables have been successfuly loaded.
"""
if os.path.isfile(file):
dotenv_path = join(
... | 5,308,007 |
def build_averaged_flowgram(flowgrams):
"""Builds an averaged flowgram from a list of raw signals."""
result=[]
if(len(flowgrams)==1):
return flowgrams[0]
for tuple in map(None, *flowgrams):
k=0
sum=0
for element in tuple:
if (element!=None):
... | 5,308,008 |
def request_extra_time_dialog(request):
""" TODO: add doc string
"""
logger.debug('request_extra_time_dialog starts')
task_id = request.matchdict.get('id')
task = Task.query.filter_by(id=task_id).first()
action = '/tasks/%s/request_extra_time' % task_id
came_from = request.params.get('cam... | 5,308,009 |
def get_environment_settings():
"""
Summary line.
Extended description of function.
Returns
-------
The appropriate integer for that selection.
"""
arrival_rate = [1, 5, 10, 20, 30, 40]
waiting_cost = [0.5, 1, 2, 4, 1000]
ar_counter = 0
while ar_counter < len(arrival_rate)... | 5,308,010 |
def live_plot(info):
"""
Set live plot limits, remove data out of window
"""
now = int(time.time())
axis = plt.gca()
axis.set_xlim([(now - 86400), (now + 86400)])
# Prevent Memory Leak Outside Plot Window; remove unnecessary data
for line in axis.get_lines():
xval = line.get_xdat... | 5,308,011 |
def flatten(request, root, write):
"""
Incrementally write out a string representation of C{root} using C{write}.
In order to create a string representation, C{root} will be decomposed into
simpler objects which will themselves be decomposed and so on until strings
or objects which can easily be co... | 5,308,012 |
def get_dates(dates):
"""Returns a list of dates
date format: yyyy-mm-dd
input can be a single date or a list of two (start and end date)
"""
ans_list = []
if not isinstance(dates, (list, tuple)):
dates = [dates]
if len(dates) == 1:
try:
validate_date(dates... | 5,308,013 |
def drawImpactScale(lossdict, ranges, losstype, debug=False):
"""Draw a loss impact scale, showing the probabilities that estimated losses fall into one of many bins.
:param lossdict:
Dictionary containing either 'TotalFatalities' or 'TotalDollars', depending on losstype.
:param ranges:
Ordered... | 5,308,014 |
def with_previous(iterable):
"""Yield (previous, current) tuples,
starting from second
"""
iterator = iter(iterable)
previous = next(iterator)
for item in iterator:
yield previous, item
previous = item | 5,308,015 |
def _ctypes_free_resource(rhandle):
"""callback to free resources when it it not needed."""
pyobj = ctypes.cast(rhandle, ctypes.py_object)
ctypes.pythonapi.Py_DecRef(pyobj) | 5,308,016 |
def cli(output_path, normal_bam,tumor_bam, comparison, genome_reference_fasta, excludable_regions):
"""
It runs Delly and svtools to obtain bedpe files with the structural variant calls
"""
tumor_id = comparison.split("_vs_")[0]
normal_id = comparison.split("_vs_")[1]
sample_tsv = pd.DataFrame.... | 5,308,017 |
def register_op_attr(op_name, attr_key, value=None, level=10):
"""Register an operator property of an operator by name.
Parameters
----------
op_name : str
The name of operator
attr_key : str
The attribute name.
value : object, optional
The value to set
level : in... | 5,308,018 |
def posix_mkfifo(space, fname, mode):
""" posix_mkfifo - Create a fifo special file (a named pipe) """
try:
os.mkfifo(fname, mode)
return space.newbool(True)
except OSError, e:
space.set_errno(e.errno)
return space.newbool(False) | 5,308,019 |
def sep_plots(
da_list: List[xr.DataArray],
var_list: List[str],
min_max_list: Union[List[list], any] = None,
cmap_list: Union[List[any], any] = None,
) -> None:
"""
Separate plots.
Args:
da_list (Sequence[xr.DataArray]): list of xr.DataArray.
var_list (List[str]): list of ... | 5,308,020 |
def dump_data(data, fname, ftype, **kws):
"""Dump PV data to file or CFS, defined by *ftype*, support types:
- *sql*: SQLite database
- *csv*: CSV spreadsheet
- *json*: JSON string file
- *cfs*: Channel Finder Service
Parameters
----------
data : list(dict)
List of dict, each d... | 5,308,021 |
def test_panelist_retrieve_all():
"""Testing for :py:meth:`wwdtm.panelist.Panelist.retrieve_all`
"""
panelist = Panelist(connect_dict=get_connect_dict())
panelists = panelist.retrieve_all()
assert panelists, "No panelists could be retrieved"
assert "id" in panelists[0], "'id' was not returned f... | 5,308,022 |
def check_file_exists(base, path, ftype="markdown"):
"""Check if the target file exists.
NOTE: We build a normalized path using 'base' and 'path' values. Suppose
the resulted path string is 'foo/bar', we check if 'foo/bar.md' exists,
AND we check if 'foo/bar/_index.md' exists.
:param base: The bas... | 5,308,023 |
def assess_status():
"""Just call the DesignateCharm.singleton.assess_status() command to update
status on the unit.
@returns: None
"""
DesignateCharm.singleton.assess_status() | 5,308,024 |
def validateProof(target_hash, proof):
"""Core validation utility
Validates the inserted proof by comparing to the provided target hash, modifies the proof's
status as ``True`` or ``False`` according to validation result and returns this result
:param target_hash: the hash to be presumably attained at... | 5,308,025 |
def get_major_version(version):
"""
Enable checking that 2 versions are within the same
major version
"""
components = re.findall(r"\d+", version)
major = components[0]
return major | 5,308,026 |
def calc_intersection_PAL(xy_1_a, xy_1_b, xy_2_a, xy_2_b):
"""
Calculates intersection points of the polygonal audience lines
This function is necessary for the handling of gaps in the audience lines and
is used to create the non-audience lines.
Calculation of the intersection of two adjacent sectio... | 5,308,027 |
def delete(rt_info):
"""
删除rt的mysql存储相关配置
:param rt_info: rt的配置信息
:return: rt的mysqls存储清理结果
"""
# 对于mysql中表删除,考虑通过rename表名,在尾部标记to_delete,然后定期清理的方式
mysql = rt_info[STORAGES][MYSQL]
physical_tn = mysql[PHYSICAL_TABLE_NAME]
ptn_arr = physical_tn.split(".")
conn_info = json.loads(mys... | 5,308,028 |
def create_person_ruler(nlp: Language) -> EntityRuler:
"""Create entity ruler that extracts person name with regex.
Notes:
This component must be used with `camphr.lang.mecab.Japanese`.
In order to imporove accuracy, it is recommended to create a Mecab user dictionaly. See scripts/mecab_person_... | 5,308,029 |
def to_pixel_samples(img):
""" Convert the image to coord-RGB pairs.
img: Tensor, (3, H, W)
"""
coord = make_coord(img.shape[-2:])
rgb = img.view(3, -1).permute(1, 0)
return coord, rgb | 5,308,030 |
def inverse_transform(X, scaler, trend=None):
"""
:param X: the data
:param scaler: the scaler that have been used for transforming X
:param trend: the trebd values that has been removed from X. None if no detrending has been used.
It has to be the same dim. as X.
:return:
X with tre... | 5,308,031 |
def render_latex(formula, fontsize=5, dpi=300):
"""Renders LaTeX formula into Streamlit."""
fig = plt.figure()
text = fig.text(0, 0, '$%s$' % formula, fontsize=fontsize)
fig.savefig(BytesIO(), dpi=dpi) # triggers rendering
bbox = text.get_window_extent()
width, height = bbox.size / float(dpi)... | 5,308,032 |
def get_available_snapshots(session, identifier, snapshot_type=None):
"""Returns snapshots in the available state for a given DB or Cluster `identifier`.
Args:
session (:class:`boto.rds2.layer1.RDSConnection`): The RDS api connection
where the database is located.
identifier (str): T... | 5,308,033 |
def write_config(configString, type):
"""
This function writes the Co-Simulation configuration file to disk
Inputs
configString - Python dictionary that hold the JSON config information to write to disk
type - either JSON or YAML
Outputs
None
"""
# the config dict... | 5,308,034 |
def p_factor1(p):
"""factor1 : value
| SIGN value""" | 5,308,035 |
def is_action(value: Any) -> bool:
"""Returns ``True`` if the value is an action."""
return isinstance(value, dict) and "action" in value | 5,308,036 |
def get_parse_args_definitions(wanted=None):
"""
Parse the args the script neeeds
:param: wanted: list of args the application will use
:returns: A list with the options for the wanted args
"""
definitions = {
'kolibri_dev': [
'-kd', '--kolibri-dev', {
'requir... | 5,308,037 |
def _create_machine_azure(conn, key_name, private_key, public_key,
machine_name, image, size, location, cloud_init,
cloud_service_name, azure_port_bindings):
"""Create a machine Azure.
Here there is no checking done, all parameters are expected to be
sani... | 5,308,038 |
def euclidean_distance(q1, q2):
"""Returns Euclidean distance between arrays q1 and q2."""
diff = ravel(q1 - q2)
return sqrt(sum(diff*diff, axis=0)) | 5,308,039 |
def merge(root, *others):
"""Combine a bunch of dictionaries and return the result"""
cp = clone(root)
[cp.update(other) for other in others]
return cp | 5,308,040 |
def load_WADE_data(year,datadir='/ocean/eolson/MEOPAR/obs/WADE/ptools_data/ecology'):
""" This function automatically loads the nutrient bottle data from WADE for a given year
specified by the user. The output is a pandas dataframe with all of te necessary
columns and groups needed for matching to ... | 5,308,041 |
def fetch_hpps_streamflow(dst_dir, url=None):
"""
Fetch streamflow data from chmi fetch_hpps_data
"""
session = HTMLSession()
n_charts = 0
datatype_prefix = 'streamflow'
agency = 'chmi'
pagesize = 50
n_pages = 20
for page in range(0, n_pages):
subpage_url = "http://hyd... | 5,308,042 |
def expand_path(path):
"""Get the canonical form of the absolute path from a possibly relative path
(which may have symlinks, etc.)"""
return os.path.expandvars(os.path.expanduser(path)) | 5,308,043 |
def read_config(config_file, default_config=None):
"""
Return a dictionary with subdictionaries of all configFile options/values
"""
config = SafeConfigParser()
config.optionxform = str
config.read(config_file)
sections = config.sections()
dict1 = OrderedDict()
for section in section... | 5,308,044 |
def source_status(request):
"""
Source availability status endpoint for Platform Sources to get cost management source status.
Parameter:
source_id corresponds to the table api_sources
Returns:
status (Dict): {'availability_status': 'unavailable/available',
'ava... | 5,308,045 |
def get_path_rel_to_proj(full_path):
"""
"""
#| - get_path_rel_to_proj
subdir = full_path
PROJ_dir = os.environ["PROJ_irox_oer"]
ind_tmp = subdir.find(PROJ_dir.split("/")[-1])
path_rel_to_proj = subdir[ind_tmp:]
path_rel_to_proj = "/".join(path_rel_to_proj.split("/")[1:])
return(pa... | 5,308,046 |
def name_to_components(name):
"""Converts a name to a list of components.
Arguments:
name - Name in the format /name1=value1/name2=value2/..
Returns: list of (name, value) tuples
"""
ret = []
components = [x for x in name.split('/') if x]
components = [x.split('=') for x in componen... | 5,308,047 |
def flow2img(flow_data):
"""
convert optical flow into color image
:param flow_data:
:return: color image
"""
# print(flow_data.shape)
# print(type(flow_data))
u = flow_data[:, :, 0]
v = flow_data[:, :, 1]
UNKNOW_FLOW_THRESHOLD = 1e7
pr1 = abs(u) > UNKNOW_FLOW_THRESHOLD
... | 5,308,048 |
def multiple_testing_correction(ps, alpha=0.05, method='benjamini-hochberg', **kwargs):
""" correct pvalues for multiple testing and add corrected `q` value
:param ps: list of pvalues
:param alpha: significance level default : 0.05
:param method: multiple testing correction method [bonferroni|benjamini... | 5,308,049 |
def test_integer_enumeration002_1539_integer_enumeration002_1539_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : facet=enumeration and value=123 and
document value=123
"""
assert_bindings(
schema="msData/datatypes/Facets/integer/integer_enumeration002.xsd",
... | 5,308,050 |
def detect_format(filename):
"""Return the name of the format based on the start of the file."""
enough_bytes = 0x1000
with open(filename, 'rb') as f:
data = f.read(enough_bytes)
if isinstance(data, bytes):
data = data.decode(errors='replace')
if data.startswith('DRCOV VERSION: 2'):... | 5,308,051 |
def test_string_duration() -> None:
"""
Test ``StringDuration``.
"""
assert StringDuration().parse("12:34:56") == datetime.timedelta(
hours=12,
minutes=34,
seconds=56,
)
assert StringDuration().parse("12:34:56.789012") == datetime.timedelta(
hours=12,
minu... | 5,308,052 |
def clear_tab_complete_vocabulary() -> None:
"""
Resets vocabulary used for tab completion. It's important to either use the cleanup argument in tab_complete,
or call this function after setting a vocabulary. This will prevent irrelevant options displaying when the user
presses tab.
:return:
"""... | 5,308,053 |
def test_label_frame_init():
"""Test constructing the label frames for a project."""
project = models.Project.create(DummyLoader())
label_frames = project.label_frames
for frame in label_frames:
assert frame.frame.ndim == 3 # Height, width, features
assert frame.frame_id is not None | 5,308,054 |
def _cache_filename(url):
"""yyyy-mm-url-slug.json"""
today = datetime.utcnow().strftime("%Y-%m")
slug = slugify(url)
filename = CACHE_DIR / f"{today}-{slug}.json"
return filename | 5,308,055 |
def fixupAnchor(anchor):
"""Miscellaneous fixes to the anchors before I start processing"""
# This one issue was annoying
if anchor.get("title", None) == "'@import'":
anchor["title"] = "@import"
# css3-tables has this a bunch, for some strange reason
if anchor.get("uri", "").startswith("??... | 5,308,056 |
def deep_merge(base, updates):
""" apply updates to base dictionary
"""
for key, value in updates.iteritems():
if key in base and isinstance(value, dict):
base[key] = deep_merge(base[key] or {}, value)
else:
base[key] = value
return base | 5,308,057 |
def plot(model, range=10):
"""
x_train, x_test, y_train, y_test = get_data(start=-range, stop=-range, rate=1.0)
x = x_train
"""
x = np.arange(0, 9, step=0.001)
y1 = model.predict(x)
y2 = np.sin(x)
plt.plot(x, y1)
plt.plot(x, y2)
plt.show() | 5,308,058 |
def load_vocab_dict(vocab_file):
"""Returns a dictionary and the vocabulary size."""
def count_lines(filename):
"""Returns the number of lines of the file :obj:`filename`."""
with open(filename, "rb") as f:
i = 0
for i, _ in enumerate(f):
pass
... | 5,308,059 |
async def load(ctx, extension):
"""Loads an extension"""
try:
client.load_extension(extension)
message = ('Loaded {}'.format(extension))
print(message)
await ctx.send(message)
except Exception as error:
error_loading = ("error loading [{}]".format(extension, error))
... | 5,308,060 |
def with_concurrency_limit(
bucket_id: str,
/,
*,
error_message: str = "This resource is currently busy; please try again later.",
) -> collections.Callable[[CommandT], CommandT]:
"""Add the hooks used to manage a command's concurrency limit through a decorator call.
.. warning::
Concur... | 5,308,061 |
def test_Editops():
"""
basic test for levenshtein.editops
"""
assert Levenshtein.editops("0", "").as_list() == [("delete", 0, 0)]
assert Levenshtein.editops("", "0").as_list() == [("insert", 0, 0)]
assert Levenshtein.editops("00", "0").as_list() == [("delete", 1, 1)]
assert Levenshtein.edi... | 5,308,062 |
def request_oauth_token():
""" Prompts user for credentials and returns Oauth token from GitHub """
print "Requesting an oauth token from GitHub."
print "Your username and password will not be stored."
username = raw_input("GitHub Username: ")
password = getpass.getpass("GitHub Password: ")
try:
g = ... | 5,308,063 |
def preprocessor(normalization="auto", assume_immutability=False, renormalize=False):
""" Wrapper function that generates lambda expressions for the method to_sparse_matrix.
Args:
normalization: Normalization parameter for `to_sparse_matrix` (default is "auto").
assume_immutability: If True, th... | 5,308,064 |
def bar_facets_from_pivoted_df(not_pivoted_df, plot_x, plot_y, order_list,
color_list, filename=None, portrait=True):
"""
General function to produce faceted plots (O2 vs rep or vice versa)
given already-pivotd data.
:param not_pivoted_df: a dataframe that will be pivoted... | 5,308,065 |
def jax_issue_role(name, rawtext, text, lineno, inliner, options=None,
content=()):
"""Generate links to jax issues or PRs in sphinx.
Usage::
:jax-issue:`1234`
This will output a hyperlink of the form
`#1234 <http://github.com/google/jax/issues/1234>`_. These links work even
for PR... | 5,308,066 |
def delete_user(user_id):
""" Delete User from Firebase
:param user_id: User ID
"""
auth.delete_user(user_id) | 5,308,067 |
def test_filter_features_multi_point():
"""MultiPoints should be turned into multiple Points"""
features = [
{
"type": "Feature",
"geometry": {"type": "MultiPoint", "coordinates": [[0, 0], [1, 0]]},
}
]
expected = [
{"type": "Feature", "geometry": {"type":... | 5,308,068 |
def planckwavenum(waven, Temp):
"""
input: wavenumber (m^{-1}), Temp (K)
output: planck function in W/m^2/m^{-1}/sr
"""
Bwaven = c1 * waven**3. / (np.exp(c2 * waven / Temp) - 1)
return Bwaven | 5,308,069 |
def validate_name_request(filing: Dict, filing_type='registration') -> list:
"""Validate name request."""
nr_path = f'/filing/{filing_type}/nameRequest/nrNumber'
nr_number = get_str(filing, nr_path)
msg = []
# ensure NR is approved or conditionally approved
try:
nr_json = namex.query_nr... | 5,308,070 |
def complete_addition(df, sumcol, addcol1, addcol2):
"""
If there are columns that share the relation sumcol = addcol1 + addcol2
this function ensures that a missing value is calculated based on the other two
"""
missingtwo = (df[sumcol].notnull()) & (df[addcol1].notnull()) & (df[addcol2].isnull())
... | 5,308,071 |
def wasserstein_hinge_discriminator_loss(
discriminator_real_outputs,
discriminator_gen_outputs,
real_weights=1.0,
generated_weights=1.0,
real_hinge=1.0,
generated_hinge=1.0,
scope=None,
loss_collection=tf.compat.v1.GraphKeys.LOSSES,
reduction=tf.compat.v1.losses.Reduction.SUM_BY_NON... | 5,308,072 |
def dict_to_hfdataset(dic: Dict[str, List]) -> HFDataset:
"""helper function to convert to huggingface's dataset class
"""
return HFDataset.from_dict(dic) | 5,308,073 |
def experiment_fixture():
"""'experiment--test' in tmpdir. Returns Experiment object."""
exp_path = Path(__file__).parent / "fixtures" / "experiment--test"
return Experiment(str(exp_path)) | 5,308,074 |
def check_call(cmd, *args, **kw):
"""Like `run_process` above but treat failures as fatal and exit_with_error."""
print_compiler_stage(cmd)
try:
return run_process(cmd, *args, **kw)
except subprocess.CalledProcessError as e:
exit_with_error("'%s' failed (%s)", shlex_join(cmd), returncode_to_str(e.return... | 5,308,075 |
def train(dataset, model, build_info, checkpointer, writers, training_steps,
**train_loop_kwargs):
"""Main training loop."""
logging.info("Start training")
# Setup/restore the checkpoint.
state = checkpointer.get_experiment_state(LATEST_TRAIN)
if not checkpointer.can_be_restored(LATEST_TRAIN):
... | 5,308,076 |
def PostScriptDC_GetResolution(*args):
"""
PostScriptDC_GetResolution() -> int
Return resolution used in PostScript output.
"""
return _gdi_.PostScriptDC_GetResolution(*args) | 5,308,077 |
def find_indices(x, y):
"""
Find the index of every element of y in x
"""
# indices that would sort x (length x)
index = np.argsort(x)
sorted_x = x[index]
# index of every element of y in sorted x (length y)
# can't plug this into either x or y:
# it's too short for x (being leng... | 5,308,078 |
def load_data(filepath) -> DataFrame:
"""Load dataset from file. Extract datasets and category names
Args:
filepath (str): user level file path
Return:
df (DataFrame): DateFrame
"""
df = spark.read.csv(filepath, header=True, inferSchema=True)
return df | 5,308,079 |
def test_excellontstmt():
""" Smoke test ExcellonStatement
"""
stmt = ExcellonStatement()
stmt.to_inch()
stmt.to_metric()
stmt.offset() | 5,308,080 |
def test_ddt_kale():
"""Test module ddt_kale.py by downloading
ddt_kale.csv and testing shape of
extracted data has 15 rows and 1 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = ddt_kale(test_path)
try:
assert x_train.shape == (15, 1)
except:
shutil.rmtree(test_path)
raise() | 5,308,081 |
def get_storage_type(storage_path):
"""Get storage type for a storage path (local and supported remote storages)"""
for storage_type in storage_prefex_config:
if storage_path.startswith(storage_prefex_config[storage_type]):
return storage_type
raise StorageNotSupported("Storage path type... | 5,308,082 |
def get_file_size(item_container, is_protected=False):
""" liefert die Dateigroesse """
filename = get_file_name(item_container, is_protected)
try:
st = os.stat(filename)
return st[6]
except:
return -1 | 5,308,083 |
def check_if_bigger(size_1, size_2, name_1, name_2):
""" Checks if the first value is bigger than the second
:param size_1: The first to be checked size
:param size_2: The second to be checked size
:param name_1: The name of the first to be checked size
:param name_2: The name of the second t... | 5,308,084 |
def delete_article(id):
"""
A view function for administrators to delete an articles.
"""
article = Article.query_by_id(id)
article.delete()
flash(f"Article id {id} deleted", "success")
current_app.logger.info(f"{str(article)} deleted.")
return render_template("result.html", url=url_for(... | 5,308,085 |
def calculate_scaling_factors(blk):
"""Look for calculate_scaling_factors methods and run them. This uses a
recursive function to execute the subblock calculate_scaling_factors
methods first.
"""
def cs(blk2):
""" Recursive function for to do subblocks first"""
for b in blk2.componen... | 5,308,086 |
def main(args):
"""Main train and evaluation function.
Parameters
----------
args: argparse.Namespace
Arguments
"""
formatter = logging.Formatter('%(asctime)s %(levelname)s - %(funcName)s: %(message)s',
"%H:%M:%S")
logger = logging.getLogger(__name_... | 5,308,087 |
def test_lookup_invalid() -> None:
"""Test argument default value lookup with invalid argument."""
with pytest.raises(ValueError, match=r"No argument `.*` is associated with `.*`\."):
arguments.lookup_default(arguments.Method.SAMPLE, "invalid_argument") | 5,308,088 |
def smooth_serie(dfi):
"""Smooth a serie by doing a time_average 2 times"""
df = time_average(dfi, months=12, center=True)
return time_average(df, months=6, center=True) | 5,308,089 |
def echo(object, f=sys.stderr):
"""Print an object is f
If the object has a method Print(), this method is used.
repr(object) is used otherwise
"""
print(f, object) | 5,308,090 |
def file_format():
"""Provide a prettified permanent output of the addresses."""
today = date.today()
register = []
header = str("# file: wikimedia_addresses.txt\n")
header += str("# date: {} (YYYY-MM-DD)\n".format(today))
# File input:
try:
with open("1.txt", mode="r") as source:
... | 5,308,091 |
def create_ast_dict(commits, repo_path, repo_name, g):
"""
Creates a dictionary mapping the SHA1 of each version in `commits` to a node
object that contains the abstract syntax trees of all the Python code in that
version.
:param commits: the list of commits in a repo
:type commits: Git.Commit ... | 5,308,092 |
def test_update_asset(lunch_money_obj: LunchMoney, lunchmoney_asset: AssetsObject):
"""
Update an Asset
"""
response = lunch_money_obj.update_asset(asset_id=lunchmoney_asset.id, balance=5.20)
assert isinstance(response, AssetsObject)
logger.info(response) | 5,308,093 |
def convert(filename, material_id, filetype):
"""Wrapper for converting Raw to AIF"""
data_meta, data_ads, data_des = parse(filetype, filename)
outputfilename = os.path.splitext(filename)[0] + '.aif'
print(f'Writing output to {outputfilename}')
makeAIF(data_meta, data_ads, data_des, material_id, fil... | 5,308,094 |
def blit_in_rect(dst, src, frame, align='tl', margin=0):
"""
Draws the image onto the surface within the rectangle frame, aligned according to align. The
alignment string may contain any meaningful combination of the letters
- _l_
- _r_
- _t_
- _b_
- _c_
for _left_, _right_, _top_,... | 5,308,095 |
def rotgliquad_fit(dra, ddc, dra_err, ddc_err, ra, dc, ra_dc_cor=None,
fit_type="full", pos_in_rad=False,
num_iter=100, **kwargs):
"""VSH degree 02 fit and return rotation, glide, &quadrupolar vectors
Parameters
----------
dra/ddc : array of float
R.A.(*cos... | 5,308,096 |
def get_license(license: Optional[str] = None,
project: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetLicenseResult:
"""
Returns the specified License resource. *Caution* This resource is intended for use only by third-party partners who are cr... | 5,308,097 |
def TemporaryDirectory(suffix='', prefix='tmp', base_path=''):
"""A context manager to create a temporary directory and clean up on exit.
The parameters are the same ones expected by tempfile.mkdtemp.
The directory will be securely and atomically created.
Everything under it will be removed when exiting the co... | 5,308,098 |
def usage():
"""Print usage info."""
print(("""%s <config field>""" % sys.argv[0])) | 5,308,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.