content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def characterizePrimal(lp):
"""
Defines primal variables, and their boundaries within the
primal problem formulation (using function call).
This might enhance the speed, but is no requirement.
- *lp* cplex lp object
- *primalConstraints* primal constraint names (metabol... | 729f7af45430ee3a32075771cc87ed10abdef484 | 669,009 |
def sanitize_wwpn_for_api(wwpn):
"""Updates the format of the WWPN to match the expected PowerVM format.
:param wwpn: The original WWPN.
:return: A WWPN of the format expected by the API.
"""
return wwpn.upper().replace(':', '') | b9a5e6826dd2437ede8cc1b2698d8d584bd5977e | 669,010 |
def initTerrain(s): # THE CLASSIC
"""
Initialization of the terrain with graph like terrain... vertices are modeled implicitly
"""
nt = ["A", "C", "G", "U"]
nt2 = [
"AA",
"AC",
"AG",
"AU",
"CA",
"CC",
"CG",
"CU",
"GA",
... | 85cfc797f823035732187b1cc807af4949f4bb25 | 669,011 |
def buffer_raster(arr):
"""
"""
max_row = arr.shape[0]
max_col = arr.shape[1]
buffered = arr.copy()
for row in range(0, max_row):
for col in range(0, max_col):
loc = (row, col)
if arr[loc] == 1:
for i in range(-1, 2):
for j i... | 60bebecc9706f12379713fcc3d657a5af3d7de2a | 669,012 |
import warnings
def unit(self):
"""DEPRECATED"""
warnings.warn(
"The FitVal class has been depreacted and replaced with UFloat "
"objects which do not contain units. This will return the .tag "
"property which may be equivalent to the FitVal.unit property "
"if constructed from... | 1824ba9abc82ec258fcc170522d06ae202c600ff | 669,013 |
def encode_state(fs, fluent_map):
""" Convert a FluentState (list of positive fluents and negative fluents) into
an ordered sequence of True/False values.
It is sometimes convenient to encode a problem in terms of the specific
fluents that are True or False in a state, but other times it is easier (or ... | a24a2207914dc77e38a4ec18551c025b2309361a | 669,014 |
def reply(read=20, write=20):
"""Return the kwargs for creating the Reply table."""
return {
'AttributeDefinitions': [
{
'AttributeName': 'Id',
'AttributeType': 'S'
},
{
'AttributeName': 'ReplyDateTime',
... | 61e8a3e90a215e38d180960ba4affc1bcf259261 | 669,015 |
def dummy_gettext(message):
"""
Mimic ``gettext()`` function. This is a passthrough function with the same
signature as ``gettext()``. It can be used to simulate translation for
applications that are untranslated, without the overhead of calling the
real ``gettext()``.
"""
return message | 88b9e37932cf35e7b227af75e8b8604c973fbe74 | 669,016 |
def new(name):
"""
Creates a new visual layer
:param name: Name of hte layer to create
:type name: str
:return: Host Specific
"""
return None | 28e2d26dbf916aacf244dc244d19b58a9197ee0b | 669,017 |
def get_sets_from_mask(meta, mask_name):
"""
Recursively retrieve the sets indicated by the named mask.
"""
sets = []
for item in meta['masks'][mask_name]['items']:
source, name = item['source'].split('@')
if source=='sets':
sets.append(name)
elif source=='column... | 1618abcbba325aa416286b1db9f1b30cbd83f600 | 669,019 |
def escape(line):
"""Escapes special LaTeX characters by prefixing them with backslash"""
for char in '#$%&_}{':
line = [column.replace(char, '\\'+char) for column in line]
return line | 7a5e1c5a0bfe126e1231f916a873ed69213e4109 | 669,022 |
import re
def read_babidialog(file_name):
"""
read babi dialog dataset
"""
babi_dialog = []
with open(file_name, 'r') as f:
temp = []
KB = []
for line in f:
line = line.strip()
if line == '':
babi_dialog.append({"dialogue": temp, "met... | a955587211ab500264a3350f0712ddb6fd17317b | 669,024 |
def toggle_settings(toolbar=False, nbname=False, hideprompt=False):
""" toggle main notebook toolbar (e.g., buttons) & filename
"""
toggle = ''
if toolbar:
toggle += 'div#maintoolbar {margin-left: 8px !important;}\n'
else:
toggle += 'div#maintoolbar {display: none !important;}\n'
... | 451d13577030b050f593e11c0376eb7403e97e54 | 669,025 |
from pathlib import Path
def get_script_path(script_name: str):
"""
Retrieves script path where name is matching {{script_name}}.
"""
p = Path(__file__).parents[1]
script_path = str(Path(p, "assets/scripts", script_name))
return script_path | 95ac410b677f0799425bfc9fc91890d17c02cd5c | 669,026 |
import os
def check_files_in_dir_from_file(directory, file):
"""
Check that a list of files from a file exist in a dir
Parameters
----------
directory
file
Returns
-------
"""
with open(file) as f:
lines = f.readlines()
files_in_dir = os.listdir(directory)
f... | 41f84fcd2e256185c4035365ca5b116f9ce8309b | 669,027 |
def remove_suffixes(text: str, suffixes:list) -> str:
"""Removes pre-defined suffixes from a given text string.
Arguments:
text: Text string where suffixes should be removed
suffixes: List of strings that should be removed from the end of the text
Returns:
text: Text string with re... | f2436cf470361d3a90373046ff0df32477d6cb9e | 669,028 |
def run_and_return_first_line(run_lambda, command):
"""Runs command using run_lambda and returns first line if output is not empty"""
rc, out, _ = run_lambda(command)
if rc != 0:
return None
return out.split("\n")[0] | 53754cea0ff023a6b318e7064471b9eb3910c548 | 669,029 |
def load_template(config):
"""Return text of template file specified in config"""
with open(config['template'], 'r') as template_file:
return template_file.read() | 273ec44bc951889d5d5b4f33e3238b60d7df1143 | 669,030 |
def norm_shape(shape):
"""
Normalize numpy array shapes so they're always expressed as a tuple,
even for one-dimensional shapes.
Parameters
shape - an int, or a tuple of ints
Returns
a shape tuple
"""
try:
i = int(shape)
return (i,)
except TypeError:
... | fd27472b059276db6e632f461442d35917bff2ba | 669,031 |
def batch_size(y_true, y_pred):
"""Count the number of items in the current batch."""
return y_true.shape[0] | b8390da3cc98ad49d03f3dfc830c1695b19cc593 | 669,032 |
import logging
def formatterStd():
"""Returns a standard formatter.
:rtype: logging.Formatter
"""
return logging.Formatter("%(asctime)s: %(message)s") | 077e4c1d14a52b258896154a0daa263f12389cd3 | 669,033 |
import hashlib
import os
import uuid
import base64
def _generate_token_sign_sharedkey():
"""Generate an ASCII-safe key from proper randomness, time, MAC.
Returns:
str: key with 80 ASCII-safe characters.
"""
# Pull in 512 bytes from the operating system's random source, and combine
# this ... | dd331198bbc9058cb80997443e2a911a855d4f94 | 669,034 |
import time
def convert_atom_timestamp_to_epoch(text):
"""Helper function to convert a timestamp string, for instance
from atom:updated or atom:published, to milliseconds since Unix epoch
(a.k.a. POSIX time).
`2007-07-22T00:45:10.000Z' ->
"""
return str(int(time.mktime(time.strptime(text.spli... | 0795d3eac9e7d71f669112f435c88925f7ed10e3 | 669,035 |
import sys
def _line(depth=0):
"""
get current code line number
:param depth: the depth of the frame at the top of the call stack.
:return: line number
"""
return sys._getframe(depth + 1).f_lineno | b20b30373c1fd4db9ba6f99886295f5fc504e0bc | 669,036 |
def find_field(d, candidates):
"""
Given a dict and a list of possible keys, find the first key
which is included into this dict. Throws ValueError if not found.
"""
for c in candidates:
if c in d:
return c
raise ValueError(f"Can't find any of: {candidates}") | 3b716ec557a8477775c5321ecf56fdc2d9d5be3b | 669,037 |
def __renumber(dictionary):
"""Renumber the values of the dictionary from 0 to n
"""
count = 0
ret = dictionary.copy()
new_values = dict([])
for key in dictionary.keys():
value = dictionary[key]
new_value = new_values.get(value, -1)
if new_value == -1:
new_va... | 7f97325f1f9635fe45c3e24e5a3c073ee6e06c30 | 669,038 |
def get_container_type(full_name: str) -> type:
"""
get a new type to be used as a container
Args:
full_name (str): full name to distinguish from other types.
Returns:
type: a new type
"""
cls_name = "".join([name.capitalize() for name in full_name.split(".")])
return type... | d5a0e54836dd362b41dd01683291f29dd8a4b621 | 669,039 |
def react_with_multiple_reactants(mol_tuple, mol_name, rxn_obj):
"""
This will run a single molecule through a 1-reactant reaction.
If it fails it will return the name of mol (mol_info[1])
If it passes it will return None
Inputs:
:param tuple mol_tuple: a tuple of all mols to react
:param s... | c9fb55ca8c9efec1981dd429a6dce02df9369ed2 | 669,040 |
def binom(n, k):
"""Quickly adapted from https://stackoverflow.com/questions/26560726/python-binomial-coefficient"""
if k < 0 or k > n:
return 0
if k == 0 or k == n:
return 1
total_ways = 1
for i in range(min(k, n - k)):
total_ways = total_ways * (n - i) // (i + 1)
return... | 3225136c4bdcc792adefe1cd1f2231e19dae3c84 | 669,042 |
def leadingzero(number, minlength):
"""
Add leading zeros to a number.
:type number: number
:param number: The number to add the leading zeros to.
:type minlength: integer
:param minlength: If the number is shorter than this length than add leading zeros to make the length correct.
:retur... | b44213cec111c387b2b6670a2ccad363cb7b81a8 | 669,043 |
def entry_value(el):
"""given a DTIPrep QA entry element, return the text of its child <value>"""
children = el.getElementsByTagName('value')
if not children:
return ''
s = ''
for cn in children[0].childNodes:
if cn.nodeType == cn.TEXT_NODE:
s += cn.data
return s | 5feb108d7b9f576a6765d06bfa434edf8a4fa864 | 669,044 |
from pathlib import Path
def _find_json(db_dir):
"""Search with tags.
Args:
db_dir (str): Directory path which has database files.
Returns:
(list): List of json file path.
"""
p = Path(db_dir)
json_list = list(p.glob("**/*.json"))
json_list.sort()
return json_list | e19aec0491625194874aa57b09c1c946bd199941 | 669,045 |
def trace(root):
"""root: a Value object with name"""
nodes, edges = set(), set()
def build(v):
if v not in nodes:
nodes.add(v)
for child in v._prev:
edges.add((child, v))
build(child)
build(root)
return nodes, edges | 7985ee4d413a902e8372ebd894f189c923b8607d | 669,046 |
import numpy
def general_basis_change(general_tensor, rotation_matrix, key):
"""Change the basis of an general interaction tensor.
M'^{p_1p_2...p_n} = R^{p_1}_{a_1} R^{p_2}_{a_2} ... ... | 6cd88a4dd0bbfdd5cb9e07afdc6a26990ad4f885 | 669,047 |
def get_maintainers():
""" replace the maintainers content while creating the package"""
with open("MAINTAINERS.md", "r", encoding="utf8") as fh:
maintainers_description = fh.read()
return maintainers_description | d6cca98f2febc2bd6dae5738af0d8df44bc36b57 | 669,048 |
def ndpa_read(ndpa_file, force_closed=False):
"""Read all annotations.
Args:
ndpa_file (str): annotation file name
force_closed (bool): should polygonal lines be forced to form a closed
contour (i.e. first and last points are identical)
Returns:
-a dictionary with keys ... | f19d663b590b0a005594a97f07801d5f58ddf2d3 | 669,049 |
def ConvertToInterval(timestamp):
"""Converts a datetime timestamp to a time interval for a cron job.
Args:
timestamp: a datetime.datetime object
Returns:
A value between 0 and 55 corresponding to the interval the timestamp
falls in. In this calculation, 12am on Monday is interval 0 and each
int... | 95be0fd67d36cb700bbc920b46affa58f26e3356 | 669,050 |
import json
def json_loads(*args, **kwargs):
"""Deserialize a str or unicode instance to a Python object.
'simplejson' is used in Python 2.6 environment, because standard 'json'
library not include several important features(for example
'object_pairs_hook', which allows to deserialize input object to... | 5189baf662c57fa20ec2167257933d71cde786c7 | 669,051 |
def cast_list(*elements) -> list:
"""this method transform everything in a list, ex:\n
cast_list("a","b") returns: ["a","b"]\n
cast_list([1,2]) returns: [1,2]\n"""
# when * is used all the arguments will be passed as tuple
# means just one element were passed as arg
if len(elements) == 1:
... | c59a24522fb1822040149a2e2a8091509efa8919 | 669,052 |
def flops_to_string(flops):
"""Converts flops count to a human-readable form"""
flops_str = ''
if flops // 10 ** 9 > 0:
flops_str = str(round(flops / 10. ** 9, 2)) + 'GMac'
elif flops // 10 ** 6 > 0:
flops_str = str(round(flops / 10. ** 6, 2)) + 'MMac'
elif flops // 10 ** 3 > 0:
... | e34165bbfa4d43416c77a45e440a9addcb39df32 | 669,053 |
def _filter(names, spec):
"""Remove names from list of names."""
if isinstance(spec, str):
names.remove(spec)
elif isinstance(spec, list):
for item in spec:
names.remove(item)
elif isinstance(spec, dict):
for item in spec.values():
names.remove(item)
r... | 92a5409bdc31a64359ef5c37f103679d1db6591e | 669,054 |
from typing import List
def data() -> List:
"""Data fixture."""
return [-4, 2, 0.5, None, "hey", [10], {"k": 1}] | 28fb3d65e2fbfb92f2eac9eb4b20b074ec990759 | 669,056 |
def _blank_out_conflicting_opts(opt_list, opt_names, conflicting_opts=None):
"""Utility for :py:meth:`MRJobRunner._combine_opts()`: if multiple
configs specify conflicting opts, blank them out in all but the
last config (so, for example, the command line beats the config file).
This returns a copy of *... | 7547f60e5484058fbc76a613656a15d494632b4d | 669,058 |
def replace_final_line(edited_lines):
"""Replace final line internal tutorial link with external links."""
expected_final_line = (
"For a more thorough introduction,"
" check out the :ref:`tutorial`.\n"
)
new_final_line = (
"You can find the complete documentation"
"\ninc... | a85cd0d64eb7ad0a322c04a2f5056b9882a72aa8 | 669,059 |
import getpass
def getpassword() -> str:
"""
This function has been manually tested.
It successfully detects and exits when user enters a blank password,
or when the user enters 2 passwords that don't match.
"""
password1 = getpass.getpass("Enter a password: ")
password2 = get... | c092080144cd184625aa1808c3447faaadc02e6d | 669,060 |
import os
def get_file_size_in_bytes(file_path):
""" Get size of file at given path in bytes"""
size = os.path.getsize(file_path)
return size | 5739fad50fcb20fb12a1583d1e59e07b1fcda10b | 669,061 |
def count(g: int)->int:
"""
function is calculating the number of digitd in the given number,
by dividing the number by 10 with every iteration and increasing the count.
Input: Integer
Output: Integer
"""
c = 0
while g!=0 :
g //= 10
c +=1
return c | 845871eb46cd5ac7ea43dbd68c30da26a7d78796 | 669,062 |
def get_average(img, u, v, n):
"""img as a square matrix of numbers"""
s = 0
for i in range(-n, n+1):
for j in range(-n, n+1):
s += img[u+i][v+j]
return float(s)/(2*n+1)**2 | f5fb895539f38937e7a248333adb007f30e2e0a8 | 669,063 |
def _create_padded_message(message: str) -> str:
"""Create padded message, used for encrypted responses."""
extra = len(message) % 16
return (16 - extra) * "0" + message | 616b36648a1f4d39354fd5978d532a97edd7e156 | 669,064 |
def basic_stats(db):
"""Collect basic statistics to be fed to output functions"""
rps = len(list(db['rp'].keys()))
users = len(list(db['users'].keys()))
logins = db['logins']
return {"rps": rps, "users": users, "logins": logins} | bdb4d93807d078789dfb44f1b47158a67f28165c | 669,065 |
def strip_chrom(chrom):
"""
Remove Chr or chr from the chromosome id
:param chrom: String
:return: String
"""
if 'chr' in chrom.lower():
return chrom[3:]
else:
return chrom | 58cd995d36f35c0b63ad7b1e1cda8210117573a0 | 669,066 |
def _get_user_display_name(user):
"""Return a human-friendly display name for a user."""
# An anonymous user has no display name
if user.is_anonymous:
return ''
# Form display name by concatenating first and last names and stripping whitespace
display_name = user.get_full_name().strip()
... | dfd8572893bb5c491d2b6c16e07975f6a141b235 | 669,067 |
import random
def query_random_uuids(conn):
"""Query for 10 random UUIDs by generating 10 random IDs locally"""
cur = conn.cursor()
cur.execute("""
select uuid_generate_v4 from t_random
where s in ({})
""".format(", ".join([str(random.randint(1, 5000000)) for x in range(5)])))
retu... | 802591b864e42ea4a70285bf4ecaea96652d09e9 | 669,068 |
import random
def fragment_list(tot_len, n_frags):
"""
A little function to help trouble shoot list_chunker. Creates a list of lists
by randomly fragmenting range(tot_len) into n_frags list
Args:
tot_len: the total number of elements in the lists
n_frags: the number of lists
Retu... | 0b7229fffd75b4b25d31ae702c0d4c7e4eecd2a5 | 669,069 |
def clean_Es(Es):
""" Auxiliary method """
return [ x for x in Es if x != 0 ] | 6ee966e6a9251f88f29930dca746f71e295a0f51 | 669,070 |
def integer_to_vector_multiple_numbers(x, n_options_per_element, n_elements, index_to_element):
"""Return a vector representing an action/state from a given integer.
Args:
x (int): the integer to convert.
n_options_per_element(list): number of options for each element in the vector.
n_e... | 2fad0f9de6c8906793b9b0ef0049009d11ca98eb | 669,071 |
def _time_last_active(cluster_summary, steps):
"""When did something last happen with the given cluster?
Things we look at:
* cluster's ``CreationDateTime`` (always set)
* cluster's ``ReadyDateTime`` (i.e. when bootstrapping finished)
* step's ``CreationDateTime`` for any step
* step's ``Start... | d0c2a77b50ba7380455ab2f2eded72f2b4ff8c31 | 669,072 |
def binarySearch(nums, target):
"""
递归版本
"""
def search(nums, target, left, right):
if left > right:
return -1
mid = (left + right) / 2
if nums[mid] == target:
return mid
if nums[mid] > target:
return search(nums, target, left, mid-1)
... | 24c306aa48801a6fb1269d6292cfd8216235629a | 669,073 |
import re
def format_imports(text):
"""
Takes a string of text and formats it based on rule 3 (see docs).
"""
# rule to find consective imports
regex4 = r"^import[\s\w]+?(?=from|^\s*$)"
# this subsitution will happen with a function
def subst4(match_obj):
pattern = r"import (\w+)"... | 2b66fded4660396c1b386daa99666250aa5a3f06 | 669,074 |
def combine_uptake_dates_release(df, rls_date_df, vers_col="dvers"):
"""
Add `version` and `date` colums to df to get release dates.
These release datese will be pulled from `product details`
and `buildhub` (for beta rc).
@df: version updake data that contains `vers_col`
@rls_date_df: df with `v... | c3cc56638b8ed4ce3fc2d9a3ceb341776829fe59 | 669,076 |
def reconcile_journal (schol, graph, pub, disputed):
"""
reconcile the journal entity and ISSN for the given publication
"""
journal_list = graph.journals.extract_journals(pub)
count, freq_issn, issn_tally = graph.journals.extract_issn(pub)
graph.journals.issn_hits += count
# attempt a matc... | d8f565b4e9f993a1466cfe3cdc2a10c0a6cccfbb | 669,077 |
def rev_vid(image):
"""
Performs reverse video filter on input image.
:param image: an ndarray for a single-layer greyscale image,
where each element corresponds to a pixel.
:return: An ndarray that is the reverse video of input
"""
inverted = 255 - image
return inverted | d087206dfc9822d08287c84da2623c471e423bb4 | 669,078 |
def set_prior_installation_required( repository, required_repository ):
"""Return True if the received required_repository must be installed before the received repository."""
# This method is called only from Galaxy when rendering repository dependencies for an installed tool shed repository.
required_repo... | 92a200d26e1ff7abef740fd2d448164d166e48c9 | 669,079 |
def check_version_info(cfg_file):
"""Checks for bumpversion version info.
If found, prints it out and exits.
Returns: None, if nothing found. """
with open(cfg_file, "r") as f:
for i, line in enumerate(f.readlines()):
version_line_start = "current_version"
if li... | f1703c4956e86209d7aefc3f2d6d831a66acbcf8 | 669,080 |
import os
def _get_umask():
"""
Get current umask (without changing it as os.umask does).
"""
umask = os.umask(0) # Get umask and set it to 0
os.umask(umask) # Set umask back to its original value
return umask | a08c40d13e0c91304468b6fba8038b5f6465f76f | 669,081 |
def mapSingleRegion(item):
"""
Used to assign the required zone to each coordinate by reading wool colour from the world of the block.
"""
if item == 2:
return "Cockpit"
elif item == 1:
return "Forward Cabin"
elif item == 4:
return "Left Wing"
elif item == 15:
... | ba95b00882d6f6774c2aa80fffea1b473c07619e | 669,082 |
def get_central_meridian(srs):
"""
Get the central meridian of the projection
Parameters
----------
srs : object
OSR spatial reference system
Returns
-------
: float
central meridian
"""
return srs.GetProjParm('central_meridian', 0.0) | c7b042472de0d4a2f486eabec36eb8ef60967d64 | 669,083 |
from typing import List
from typing import Dict
from typing import Callable
from typing import Any
def _dict_from_terse_tabular(
names: List[str],
inp: str,
transformers: Dict[str, Callable[[str], Any]] = {})\
-> List[Dict[str, Any]]:
""" Parse NMCLI terse tabular output into a lis... | 159a4db05c18ab181526a0e4b574d4859c5d9ad2 | 669,084 |
def pytest_funcarg__doctree(request):
"""
The transformed doctree of the ``content``.
.. note::
This funcarg builds the application before test execution.
"""
app = request.getfuncargvalue('app')
app.build()
return app.env.get_doctree('index') | ed92d4a5cb0f1511753b6956ffe0f8851049c10e | 669,085 |
import argparse
def get_input_args():
"""
Command Line Arguments:
1. Image path
2. Path of the saved model
3. Number of the top k most likely classes as --top_k with default value 5
4. JSON file to map categories to real names as --category_names with default value label_map.json
T... | 4a9a22739c61bd060d778453bf65f7d2bc47153b | 669,087 |
def snake2pascal(string: str):
"""String Convert: snake_case to PascalCase"""
return (
string
.replace("_", " ")
.title()
.replace(" ", "")
) | 5b0d9687924425d93c9f6611cd27a14dc2473497 | 669,088 |
def taille(arbre):
"""Renvoie la taille de l'arbre"""
if arbre is None:
return 0
else:
return 1 + taille(arbre.get_gauche()) + taille(arbre.get_droite()) | bafc78eaf1d4b3a6e4f272fda6f15d54212af5ce | 669,089 |
def all_keys_true(d, keys):
"""Check for values set to True in a dict"""
if isinstance(keys, str):
keys = (keys,)
for k in keys:
if d.get(k, None) is not True:
return False
return True | 86a2fe99abf682b5b930b08eee79903514baf29d | 669,090 |
def event_callback(callback, **kw):
"""
Add keyword arguments to the event callback.
"""
return lambda evt: callback(evt,**kw) | 69471eb654594794643af6ba2c7ea1e88f083f1e | 669,091 |
import re
def convert_newline(value):
"""convert CR-LF to unix-like new line as LF"""
return re.sub(r"\r\n", r"\n", value) | 19b83cbc4e5f325e5d07b9c5234893bea6d5510d | 669,092 |
def parseLinkList(theData):
"""
Plug the verified data into here...
"""
DLDICT,VERDICT = {},{}
sectStr = None
for line in theData.split('\n'):
pcs = line[1:].split()
if line.startswith('# SECTION-') and 'INSTALLERS' in line:
sectStr = pcs[0].split('-')[-1].lower()
if no... | e270cdaedac4e8d9b84cffa445fcddf4dc054568 | 669,093 |
def rise_velocity_selector(size_class, w_rise_list):
"""
This removes the smallest rise velocity from w_rise_list
:param size_class:
:param w_rise_list:
:return:
"""
if size_class is 'large':
if -0.0003 in w_rise_list:
w_rise_list.remove(-0.0003)
return w_rise_list | b90bd936ce66bb0bf4c7d0e28acce7dd984e069c | 669,095 |
def this_exist_not_null(param):
"""Check if parameter exists or not"""
if (
not param or
len(param) < 1
):
return False
return True | 17377e1deab25071dda62637932ca85ba1f28b00 | 669,097 |
def places():
""" all the positions on a board """
return ((x,y) for x in range(9) for y in range(9)) | d638846f2cfd66436e95369b287f11980518f61e | 669,098 |
def score_edit_distance(proposed, existing):
"""Score a proposed change primarily by edit distance"""
sum = 0
for p in proposed:
if p not in existing:
sum += 1
for e in existing:
if e not in proposed:
sum += 1
return sum | 176657113fdc72acfb9e4ac57f7b6b8bdf1d2347 | 669,099 |
def prepare_board():
""" make board in form of nested lists
returns: nested lists """
board = []
temp = []
for i in range(100,0,-1):
temp.append(str(i))
if (i-1)%10 == 0:
board.append(temp)
temp = []
for j in range(len(board)):
if j%2:
... | 5048111bd1e4569372ac4065e84f04efb2aa6e31 | 669,100 |
def InpDattoSITE(TASK):
"""InpDattoSITE function: prepare data for sankey plot (from Input-Dataset to Site)"""
count_rows = 0
for k in TASK["data"]["datasets"]:
for i in TASK["data"]["datasets"][k]["jobs"]:
count_rows = count_rows + 1
f = count_rows
c = 3 # c: number of columns
... | 54560f5f12ae59c25097af49f29ee17347f9d8d9 | 669,101 |
def get_safe_filename(title):
"""
Get a safe string to use as a filename
:param title: your target file title
:return: the filename to use
:rtype: str
"""
keep_chars = (' ', '.', '_')
return "".join(c for c in title if c.isalnum() or c in keep_chars).rstrip() | 10a3b274bf166681c79ed05b9651326eb37898fd | 669,102 |
def parse_data(data, d=None):
""" Function to parse the incoming -D options into a dict """
if d is None:
d = {}
for kv in data:
key = kv.split('=')[0]
try:
val = kv.split('=', 1)[1]
except IndexError:
val = True
d[key] = val
return d | ca80085c1b3d898138f36d4473eef5e21eb5f751 | 669,103 |
def time_format(num, digits=1, align_unit=False):
# type: (float, int, bool) -> str
"""Format and scale output according to standard time
units.
Example
-------
>>> time_format(0)
'0.0 s'
>>> time_format(0, align_unit=True)
'0.0 s '
>>> time_format(0.002)
'2.0 ms'
>>> t... | 806cefcd7c9ddeff8214031bbbdfee09ad7fa27f | 669,104 |
def encrypted_unencrypted():
"""Return None for a unencrypted test."""
return None | 88d1e5f75cfc5a942b27814c968328bf262bc4fe | 669,105 |
import torch
def compute_accuracy(dataloader, pred_list, nb_models):
"""
Computes the accuracy across al batches between the true labels in the dataloader and the batch predictions in pred_list
------------------
Input:
dataloader: contains the validation dataset X,y
pred_list: list of of tens... | 10e2eda9a0fce953ba5856cff59ed0520c70d36d | 669,106 |
import re
def retrieveQueries(queryFile):
""" Retrieves the queries done on Google Ngram Viewer
from the name of the .csv file """
queries = []
nameFile = queryFile.split('-fre')[0]
if re.search(r'([A-Z]{3,4})', queryFile) != None:
nameFile = nameFile.split('_')
if '[' in queryFil... | 5877f1c570f594d59b61c69cb6492c8571626084 | 669,107 |
def word2number(s: str) -> int:
"""方法number_translator的辅助方法,可将[零-九]正确翻译为[0-9]
:param s: 大写数字
:return: 对应的整形数,如果不是数字返回-1
"""
return {
"零": 0,
"0": 0,
"一": 1,
"1": 1,
"二": 2,
"两": 2,
"2": 2,
"三": 3,
"3": 3,
"四": ... | 86f6beae4f939c6f080508a6bcecdb871e49201a | 669,108 |
def get_flood_risk_rating(num):
"""Converts an integer value of a flood risk rating to the rating it
represents - low (0/1), moderate (2), high (3), severe (4)"""
if num == 0 or num == 1:
return "Low"
if num == 2:
return "Moderate"
if num == 3:
return "High"
if num == 4... | 6c75676b58ec970a3c730ba59f6383794ea0438b | 669,110 |
def canSum(numbers, target, memo=None):
"""
Given a array of positive whole numbers, finds if there is a subarray whose sum equals the given target
"""
if memo == None:
memo = dict()
if target in memo:
return memo[target]
if target == 0:
return True
if target < 0:
... | 291f8091c9a11b00ad5079c76d53c3aaa339b743 | 669,111 |
def hexline(data):
"""Convert a binary buffer into a hexadecimal representation"""
LOGFILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or \
'.' for x in range(256)])
src = ''.join(data)
hexa = ' '.join(["%02x"%ord(x) for x in src])
printable = src.translate(LOGFILTER)
ret... | bb7b78c0f9f44ed19c12169bbf6f67df3f78803f | 669,112 |
def _chain2dict(chain, v = 'newiban'):
"""Convert a block chain into dict. K-v pairs are alias-iban pairs
:param v = newiban or newbank
"""
result = {}
for block in chain:
for trnx in block['transactions']:
result[trnx['alias']] = trnx[v]
return result | 6243e9972673c759ff95be7ffa885aba6432b400 | 669,113 |
def cross_compile(*args, **kwargs):
"""Compile the source string into a code object
__future__ imports change the behavior of default compile function
This function just provides the 'compile' free of __future__ imports
"""
return compile(*args, **kwargs) | bad06e0b5d1b87ea8b5ec47b92e1a9f92831a58e | 669,114 |
def autoparse(text):
"""
Guesse the type of a value encoded in a string and parses
"""
# int
try:
return int(text)
except:
pass
# float
try:
return float(text)
except ValueError:
pass
# string
return text | 7478eac961bd865f4f56912a66c97cd507bd6e85 | 669,115 |
def calc_personal_check_digits(number):
"""Calculate the check digits for the 12-digit personal ИНН."""
weights = (7, 2, 4, 10, 3, 5, 9, 4, 6, 8)
d1 = str(sum(w * int(n) for w, n in zip(weights, number)) % 11 % 10)
weights = (3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8)
d2 = str(sum(w * int(n) for w, n in zip(... | e0f4e3a08ceebc79cfb271c2f3817b014210bb92 | 669,116 |
def importobj(modpath, attrname):
"""imports a module, then resolves the attrname on it"""
module = __import__(modpath, None, None, ["__doc__"])
if not attrname:
return module
retval = module
names = attrname.split(".")
for x in names:
retval = getattr(retval, x)
return retv... | e849a363b69195516cff46ff8ab3b6743b5383bb | 669,117 |
def abc1D (u, up, alpha, src):
"""
Absorbing Boundaries Condition based on hybrid scheme which is explained in [2].
If N=1, the method is the same as [1].
Parameter
---------
ul = wavefield at time step t-1
u = wavefield at given time step t
up = wavefield at time step t+1 (calculated wa... | 2185d369958115aee559849ddcca94d65a4b2f67 | 669,118 |
def get_channel(version: str) -> str:
"""Find channel based on version number."""
if "dev0" in version:
return "dev"
if "dev" in version:
return "nightly"
if "b" in version:
return "beta"
return "stable" | 38b3ea838c68593b9d9e1a9213d5b45f0886cba2 | 669,119 |
from pathlib import Path
def splitall(path):
"""
Split path into each part, top catalogue on top, filename (if included) last
"""
out = Path(path).parts
return out | 2ff81f9182de04763a43a75cab45c25b2f6fd2e3 | 669,120 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.