content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_smembers(delete_keys):
""" SMEMBERS key
Available since 1.0.0.
Time complexity: O(N) where N is the set cardinality.
redis> SADD myset "Hello"
(integer) 1
redis> SADD myset "World"
(integer) 1
redis> SMEMBERS myset
1) "World"
2) "Hello"
redis>
""... | 5,309,100 |
def toPSPmatrix(psp, N_neuron, index):
"""
推定したPSPの値からPSP matrix作る
indexをもとに、行列を作成する。
args:
psp: 推定結果のndarray
return:
psp_mat: PSP行列の2次元ndarray。行は結合先、列は結合元のニューロン番号を表す。
"""
# hintom diagramにする
psp_mat = np.zeros([N_neuron, N_neuron])
# 明示的にindexが与えられているのならば
assert... | 5,309,101 |
def repeat(a, n, axis, name='repeat'):
"""repeat a tensor along the axis.
For expamle:
a=[0, 1, 2, 3], n=2, axis=0
return [0, 0, 1, 1, 2, 2, 3, 3]
"""
with tf.name_scope(name):
ndim = len(a.shape)
if axis < 0:
axis += ndim
if axis < 0 or axis... | 5,309,102 |
def disp_curve_list(result_list, base_list):
"""
Read in a result list and trace out the disp_curve_list
for different methods
"""
# initialize
constraint = "DP"
err_bar = False
dataset = ''
for result in result_list:
train_eval = result['train_eval']
test_eval = res... | 5,309,103 |
def get_syn_func_caller(func_name, domain_dim=None, fidel_dim=None,
noise_type='no_noise', noise_scale=None,
to_normalise_domain=True):
""" Returns a FunctionCaller object from the function name. """
func_name = func_name.lower()
funcs = ['hartmann', 'hartmann6', 'h... | 5,309,104 |
def make_network_arc_consistent(csp: CSP, assignment: Dict[str, int]) -> bool:
"""Implementation of the AC-3 algorithm
Parameters
----------
csp : CSP
binary CSP constraint
assignment : [type]
current assignment of variables in CSP
Returns
-------
bool
True if v... | 5,309,105 |
def cuda_if_gpu(T):
"""
Move tensor to GPU, if one is available.
:param T:
:return:
"""
return T.cuda() if use_cuda else T | 5,309,106 |
def test_join():
""" JOIN command """
command = "JOIN"
message = ":n!u@h JOIN #c"
expected_kwargs = {"nick": "n", "user": "u", "host": "h",
"channel": "#c"}
validate(command, message, expected_kwargs) | 5,309,107 |
def run():
""" 主程序入口"""
# 判断当前环境是否为 python 3
if sys.version_info[0] == 2:
print('此项目不支持 Python 版本!')
return
# 检查依赖库是否都已经安装上
try:
import itchat
import apscheduler
import requests
import requests_html
from bs4 import BeautifulSoup
if it... | 5,309,108 |
def convert_archive_posts(archive_posts):
"""Convert a list of SQL post rows to the format used for display within the post archive."""
converted_archive = [];
current_year = ""
current_month = ""
for post in archive_posts:
# If the posts created year is not the current year being parsed, ... | 5,309,109 |
def storePose(root, posename):
"""Stores the current pose of all of a model's selected joints.
Existing poses of the same name will be overwritten.
Args:
root(bpy_types.Object): root of the model the pose belongs to
posename(str): name the pose will be stored under
Returns:
: No... | 5,309,110 |
def sigmoid(x):
"""
Compute the sigmoid of x
Arguments:
x -- A scalar or numpy array of any size
Return:
s -- sigmoid(x)
"""
s = 1 / (1 + np.exp(-x))
return s | 5,309,111 |
def show_tree(tree, total_width=36, fill=' '):
"""Pretty-print a tree."""
output = StringIO()
last_row = -1
for i, n in enumerate(tree):
if i:
row = int(math.floor(math.log(i+1, 2)))
else:
row = 0
if row != last_row:
output.write('\n')
... | 5,309,112 |
def stream_bytes(
data: ty.Union[bytes, gen_bytes_t], *, chunk_size: int = default_chunk_size
) -> ty.Tuple[gen_bytes_t, ty.Dict[str, str]]:
"""Gets a buffered generator for streaming binary data.
Returns a buffered generator which encodes binary data as
:mimetype:`multipart/form-data` with the corresponding head... | 5,309,113 |
def VerifyType(owner, attr, value, template, callback):
"""Checks if an attribute has correct form.
@type owner: str
@param owner: name of the object containing the attribute
@type attr: str
@param attr: name of the attribute
@type value: dict
@param value: actual value of the attribute
@type template:... | 5,309,114 |
def _get_search_text(keywords):
"""Get search text."""
search_text = ' '.join(['"{}"'.format(keyword) for keyword in keywords])
search_text = search_text.replace(':', ' ')
search_text = search_text.replace('=', ' ')
return search_text | 5,309,115 |
def _ExtractAddrs(header_value):
"""Given a message header value, return email address found there."""
friendly_addr_pairs = list(rfc822.AddressList(header_value))
return [addr for _friendly, addr in friendly_addr_pairs] | 5,309,116 |
def readnext(x):
"""x is a list"""
if len(x) == 0:
return False
else:
return x.pop(0) | 5,309,117 |
def ceil(x1, **kwargs):
"""
Compute the ceiling of the input, element-wise.
For full documentation refer to :obj:`numpy.ceil`.
Limitations
-----------
Parameter ``x1`` is supported as :obj:`dpnp.ndarray`.
Keyword arguments ``kwargs`` are currently unsupported.
Otherwise th... | 5,309,118 |
def obfuscate_file(bnf_parser, source_file, from_dir, from_sub_dir, to_dir,
is_verbose=False, is_discovery=True, is_python=True,
do_obfuscate=True, platform=None):
"""Obfuscate a file.
Parameters
----------
bnf_parser
do_obfuscate: bool
from_dir : str
f... | 5,309,119 |
def test_nonuniform_illumination_rgb(transform_test_data):
"""Test for PlantCV."""
# Load rgb image
rgb_img = cv2.imread(transform_test_data.small_rgb_img)
corrected = nonuniform_illumination(img=rgb_img, ksize=11)
assert np.mean(corrected) < np.mean(rgb_img) | 5,309,120 |
def main():
"""
Main program loop
"""
if len(sys.argv) != 2:
print("Invalid usage. Provide a StephScript file name to compile and run")
print("Example: python main.py steph_file.stsc")
return
if not os.path.isfile(sys.argv[1]):
print("Invalid file specified")
... | 5,309,121 |
def vMain():
""" The main function
"""
dctCounterPar = {}
dctCounterPar['iFunctionCounter'] = 0
# Start the prometheus client listen server
start_http_server(8000)
# Continuously call the function collecting the telemetry
while True:
vPeriodicFunction(dctCounterPar)
... | 5,309,122 |
def check_pq(pq):
"""Input validation for position and orientation quaternion.
Parameters
----------
pq : array-like, shape (7,)
Position and orientation quaternion: (x, y, z, qw, qx, qy, qz)
Returns
-------
pq : array, shape (7,)
Validated position and orientation quaterni... | 5,309,123 |
def add_sources(lib, patterns) -> None:
"""
Adds source files to Vunits lib which are matching pattern (recursively).
"""
for pattern in patterns:
p = join(str(d.parent), pattern)
log.debug('Adding sources matching {}'.format(p))
for f in glob(p, recursive=True):
if f... | 5,309,124 |
def elevate_nurbs_curve_degree(n, p, uk, cpw, t=1):
"""
Elevate the degree of a NURBS curve *t* times.
:param int n:
:param int p:
:param ndarray uk:
:param ndarray cpw:
:param int t:
:return: New number of control points - 1, new knot vector, and the new
control points of NURB... | 5,309,125 |
async def async_setup(hass, config):
"""Platform setup, do nothing."""
return True | 5,309,126 |
def insert_collections(request, orion_db, clean_db):
"""Drop a collection prior a test"""
collections_data = (
request.node.get_closest_marker("insert_collections").args[0]
if request.node.get_closest_marker("insert_collections")
else {}
)
for name, data in collections_data.items... | 5,309,127 |
def test_spectrum_document_peak_getter():
"""Test peak getter"""
mz = np.array([10, 20, 30, 40], dtype="float")
intensities = np.array([0, 0.01, 0.1, 1], dtype="float")
metadata = {"precursor_mz": 100.0}
spectrum_in = Spectrum(mz=mz, intensities=intensities, metadata=metadata)
spectrum_document ... | 5,309,128 |
def set_car_properties(records: dict, forza: CarInfo):
"""set car properties before running
Args:
records (dict): records
forza ([type]): forza
"""
gears = np.array([item['gear'] for item in records])
gear_list = np.unique(gears)
forza.minGear = gear_list.min()
forza.maxGear... | 5,309,129 |
def coding_problem_19(house_costs):
"""
A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost
while ensuring that no two neighboring houses are of the same color. Given an N by K matrix where the nth row and
kth column represents the cost to ... | 5,309,130 |
def create_account(data):
"""Creates a new account for a customer identified by customer_id"""
mandatory_params = ['customer_id', 'initial_deposit']
result = check_required_params(mandatory_params, data)
if result:
return result
customer = Customer.query.filter_by(id=data['customer_id']).fi... | 5,309,131 |
def test_custom_resource_definition():
"""
Should not cause a recursion error while loading a CRD yaml definition.
For more details on the source of this scenario see:
https://github.com/sernst/kuber/issues/1
"""
bundle = kuber.create_bundle(kubernetes_version="latest").add_file(
os.path... | 5,309,132 |
def requests_get(url):
"""Make a get request using requests package.
Args:
url (str): url to do the request
Raises:
ConnectionError: If a RequestException occurred.
Returns:
response (str): the response from the get request
"""
try:
r = requests.get(url)
e... | 5,309,133 |
def _add_intermol_molecule_type(intermol_system, parent): # pragma: no cover
"""Create a molecule type for the parent and add bonds.
This method takes an intermol system and adds a
parent compound, including its particles and bonds, to it.
"""
from intermol.forces.abstract_bond_type import (
... | 5,309,134 |
def get_mysensors_name(gateway, node_id, child_id):
"""Return a name for a node child."""
node_name = '{} {}'.format(
gateway.sensors[node_id].sketch_name, node_id)
node_name = next(
(node[CONF_NODE_NAME] for conf_id, node in gateway.nodes_config.items()
if node.get(CONF_NODE_NAME) ... | 5,309,135 |
def bloch_sunburst(vec, colormap):
"""Create a Bloch disc using a Plotly sunburst.
Parameters:
vec (ndarray): A vector of Bloch components.
colormap (Colormap): A matplotlib colormap.
Returns:
go.Figure: A Plotly figure instance,
Raises:
ValueError: Input vector is not... | 5,309,136 |
def test_get_event_list():
"""Verify device events list method."""
mock_config = Mock()
with patch(
"axis.event_services.session_request", new=Mock(return_value=EVENT_INSTANCES)
):
event_list = get_event_list(mock_config)
assert "motion" not in event_list
assert "vmd3" in event_... | 5,309,137 |
def link_models():
"""return settings or default"""
return getattr(project_settings, 'HTML_EDITOR_LINK_MODELS', ()) | 5,309,138 |
def profiling_info(label=""):
"""
Runtime memory measurements
"""
if cfgget('dbg'):
console_write("{} [PROFILING INFO] - {} {}".format('~'*5, label, '~'*5))
mem_info()
console_write("~"*30) | 5,309,139 |
def _join_dicts(*dicts):
"""
joins dictionaries together, while checking for key conflicts
"""
key_pool = set()
for _d in dicts:
new_keys = set(_d.keys())
a = key_pool.intersection(new_keys)
if key_pool.intersection(new_keys) != set():
assert False, "ERROR: dicts ... | 5,309,140 |
def resolve(segments):
""" given the predicts of a segment from multiple files (as a pandas Series), return a new class (as a pandas Series) """
# strategy: weight each probability by the relative size of its area
# first calculate the relative size of each segment
segments['area'] = segments['area']/su... | 5,309,141 |
def getCandidates(fi, fo, sLang, dLang):
"""Check if a url could be a candidate or not."""
nCandidates = 0
for line in fi:
line = line.rstrip()
# tld url crawl<TAB>json_data
url = getURL(line)
url_components = normalize(url)
mapS = rulesOn(url, url_components, sLan... | 5,309,142 |
def set_passphrase(module, **kwargs):
"""Adds or replace a LUKS passphrase in a give slot.
Return: <result> <error>"""
for req in ["device", "slot", "valid_passphrase", "new_passphrase"]:
if req not in kwargs:
return False, {"msg": "{0} is a required parameter".format(req)}
is_keyf... | 5,309,143 |
def run_train(config, data, inds):
"""
Sets splitter. Partitions train/val/test.
Loads model from config. Trains and evals.
Returns model and eval metrics.
"""
train_inds = inds["train_inds"]
val_inds = inds["val_inds"]
test_inds = inds["test_inds"]
model = keras_gcn(config)
los... | 5,309,144 |
def test_invaliddn():
""" Test InvalidDN exception. """
with pytest.raises(errors.InvalidDN):
_ = LDAPDN("cn=test,dc=one+two") | 5,309,145 |
def get_upgrades():
""" Returns nested list of available upgrade paths"""
files = [x for x in os.listdir(sql_folder) if x.endswith('.sql')]
versions = [(x[:-4].split('_to_')) for x in files]
return [tuple(int(j) for j in i) for i in versions] | 5,309,146 |
def cases_vs_deaths(df):
"""Checks that death count is no more than case count."""
return (df['deaths'] <= df['cases']).all() | 5,309,147 |
def retrieve_ledger_details_data(
token_address: str,
data_id: str,
issuer_address: Optional[str] = Header(None),
db: Session = Depends(db_session)):
"""Retrieve Ledger Details Data"""
# Validate Headers
validate_headers(issuer_address=(issuer_address, address_is_valid_addre... | 5,309,148 |
def sim1c_error(target_stats, cmr_stats):
"""
Sim 1c fits only the conditional SPCs and PFR, and uses mean squared error
instead of chi-squared error because standard errors are not available.
"""
y = []
y_hat = []
# Fit SPC and PFR
for stat in ('spc_fr1', 'spc_frl4', 'pfr'):
... | 5,309,149 |
def is_between(thing, start=None, end=None):
"""
given a thing with a date, returns true if the thing is between the start and end date
Parameters
----------
thing: dict
the thing that we want to know whether or not is after a date
start: datetime.date object
a date for the start. ... | 5,309,150 |
def list_files_in_dir(dir_path):
"""
List out files only from a target directory path.
"""
if not os.path.isdir(dir_path):
raise ValueError('`dir_path` must be a directory.')
return iter(f for f in os.listdir(dir_path)
if os.path.isfile(os.path.join(dir_path, f))) | 5,309,151 |
def CreateBoxOnStick(point1, point2, tipRatio=0.3):
"""
Creates an stick with a box as tip from point1 to point2.
Use tipRatio for setting the ratio for tip of the arrow.
"""
direction = map(lambda x, y: x - y, point2, point1)
length = math.sqrt(sum(map(lambda x: x ** 2, direction)))
unitDir = map(lambda x: x /... | 5,309,152 |
def is_platform_file(path):
"""
Return True if the file is Mach-O
"""
if not os.path.exists(path) or os.path.islink(path):
return False
# If the header is fat, we need to read into the first arch
with open(path, 'rb') as fileobj:
bytes = fileobj.read(MAGIC_LEN)
if bytes =... | 5,309,153 |
def post_instagram_facebook(report_type, country, title, filename, url):
"""
Publish a post in instagram.com/buscamascotapy and in the official page at facebook about the specific report
"""
username = 'buscamascotapy'
INSTA_PASS = config('INSTAGRAM_PASSWORD')
bot = Bot()
bot.log... | 5,309,154 |
def generatePARFile(cgen, charge, estimation, generateCharges):
"""
Generate a BOSS PAR file (parameters files)
Parameters
----------
cgen : str, ('CM1A', CM1A-LBCC')
Charge method
charge : int
Formal charge of the molecule
estimation : str
BOSS parameter
generateCharges ... | 5,309,155 |
def test_mcquestion_shuffle1():
"""Test shuffle with one question added
"""
q = exam.MultiChoiceQuest("Who are you?")
a1 = exam.MultiChoiceAnswer("That's me.")
q.add_answer(a1)
random.seed(1)
q.shuffle()
assert q.correct_answer == a1
assert q.correct_index == 0
assert q.correct_... | 5,309,156 |
def ParseData(audit_data, log_record, audit_env_options):
"""Read the strace data."""
if audit_data:
for env_var, env_value in audit_data.items():
log_record.env_vars[env_var] = env_value | 5,309,157 |
def _calcFiberLength(fiberData, fidx):
""" * INTERNAL FUNCTION *
Calculates the fiber length via arc length
INPUT:
fiberData - fiber tree containing tractography information
fidx - fiber index
OUTPUT:
L - fength of fiber
"""
no_of_pts = fiberData.pts_per_fiber
if n... | 5,309,158 |
def choose_license_and_version(
license_url=None, license_=None, license_version=None
):
"""
Returns a valid license pair, preferring one derived from license_url.
If no such pair can be found, returns None, None.
Three optional arguments:
license_url: String URL to a CC license page.... | 5,309,159 |
def default_options(add_flags=True, flags=None):
"""Creates a DeepVariantOptions proto populated with reasonable defaults.
Args:
add_flags: bool. defaults to True. If True, we will push the value of
certain FLAGS into our options. If False, those option fields are left
uninitialized.
flags: obj... | 5,309,160 |
def alert(title=None, message='', ok=None, cancel=None, other=None, icon_path=None):
"""Generate a simple alert window.
.. versionchanged:: 0.2.0
Providing a `cancel` string will set the button text rather than only using text "Cancel". `title` is no longer
a required parameter.
.. version... | 5,309,161 |
def evaluate(metric,
netG,
log_dir,
evaluate_range=None,
evaluate_step=None,
num_runs=3,
start_seed=0,
overwrite=False,
write_to_json=True,
device=None,
**kwargs):
"""
Evaluates a ge... | 5,309,162 |
def _split_data(data, FEATURES, sort_keys=True, TEST_SIZE=TEST_SIZE, SEED=SEED, scale=False):
""" extracting features, split data """
data = featureFormat(data, FEATURES, sort_keys=sort_keys)
y, x = targetFeatureSplit(data)
if scale:
scaler = StandardScaler()
x = scaler.fit_transform(x)
... | 5,309,163 |
def save_checkpoint(checkpoint_dict: dict, is_best: bool):
"""Saves a model checkpoint to file. Keeps most recent and best model.
Params:
- checkpoint_dict (dict): dict containing all model state info, to pickle
- is_best (bool): whether this checkpoint is the best seen so far.
"""
checkpoint_fi... | 5,309,164 |
def random_quote():
"""Retrieve a correctly formatted quote."""
quote_file = f"{get_full_path('etc')}/quotes"
quote_list = []
if not os.path.isfile(quote_file):
return '', ''
else:
with open(quote_file, 'r') as quote_h:
for line in quote_h.readlines():
if ... | 5,309,165 |
def add_like(db, filename, usernick=None):
"""Increment the like count for this image"""
flowTowCursor = db.cursor()
if imageExist(db=db, filename=filename):
if usernick:
if userExist(db=db, usernick=usernick):
SQL = """INSERT INTO likes(filename, usernick) VALUES (?, ?)"... | 5,309,166 |
def get_test_loc(
test_path,
test_data_dir,
debug=False,
must_exist=True,
):
"""
Given a `test_path` relative to the `test_data_dir` directory, return the
location to a test file or directory for this path. No copy is done.
Raise an IOError if `must_exist` is True and the `test_path` doe... | 5,309,167 |
def widget_url(widget, action='', prefix=None):
"""Returns the URL of the controller to perform `action` on `widget`.
If no `prefix` is passed the it will be tried to be fetched from
`tw.framework.request_local` where the :class:`WidgetBrowser` leaves it
on every request.
Example::
>>> fr... | 5,309,168 |
def build_transformer_block(
net_part: str,
block: Dict[str, Any],
pw_layer_type: str,
pw_activation_type: str,
) -> Union[EncoderLayer, TransformerDecoderLayer]:
"""Build function for transformer block.
Args:
net_part: Network part, either 'encoder' or 'decoder'.
block: Transfo... | 5,309,169 |
def remove_pool_snapshot(service, pool_name, snapshot_name):
"""Remove a snapshot from a RADOS pool in Ceph.
:param service: The Ceph user name to run the command under.
:type service: str
:param pool_name: Name of pool to remove snapshot from.
:type pool_name: str
:param snapshot_name: Name of... | 5,309,170 |
def mondiode_value(fits_file, _, factor=5):
"""Compute the effective monitoring diode current by integrating
over the pd current time history in the AMP0_MEAS_TIMES extension
and dividing by the EXPTIME value.
"""
with fits.open(fits_file) as hdus:
x = hdus['AMP0.MEAS_TIMES'].data.field('AMP... | 5,309,171 |
def get_loss_fn(loss_config, model):
"""Creates a loss function based on loss_config.
Args:
loss_config: (dict) loss config with following parameters:
- name: (str) name of the loss
- params: (dict) loss parameters if any
model: a model which its parameters might be used for defining
... | 5,309,172 |
def main(Files, FoilDyn, FoilGeo, axs, plot_col=1, dataOutput = False, cutoff = 0.15):
"""Go into wall shear folder and process raw data"""
FoilDyn.cutoff = cutoff
data_path = Files.data_path
print('\n' + Files.project_name)
if Files.org_path == 'None':
savePath = Files.folder_path+"\\_... | 5,309,173 |
def pick_from_log(log_path: str, min_epoch: int = 50):
"""Read training log from checkpoint folder."""
log_name = '-'.join(os.path.basename(os.path.dirname(log_path)).split('-')[:-3])
dataset = os.path.basename(os.path.abspath(os.path.join(log_path, '..'))).split('-')[-1]
if not os.path.exists(log_path)... | 5,309,174 |
def add_pronom_link_for_puids(text):
"""If text is a PUID, add a link to the PRONOM website"""
PUID_REGEX = r"fmt\/[0-9]+|x\-fmt\/[0-9]+" # regex to match fmt/# or x-fmt/#
if re.match(PUID_REGEX, text) is not None:
return '<a href="https://nationalarchives.gov.uk/PRONOM/{}" target="_blank">{}</a>'.... | 5,309,175 |
def dataset_description_file(outdir):
"""
Create dataset_description.json file if it does not exist.
If it exists, do nothing.
Parameters
----------
outdir: path
Full path to the output directory.
"""
# dictionary that will be written for the basic dataset description version
... | 5,309,176 |
def add_unknown_utilities_to_db(db_source, db_target, prob_of_unknown=0.3):
"""
Add utilities and unknown utilities to the target database. For each utility term in the source database: with
probability prob_of_unknown, the term has an unknown probability in the target database. With a probability of
1-... | 5,309,177 |
def process_all_events(parent_result_section: ResultSection, file_ext: str, events: Optional[List[Dict]] = None) -> None:
"""
This method converts all events to a table that is sorted by timestamp
:param parent_result_section: The overarching result section detailing what image this task is being sent to
... | 5,309,178 |
def runtime(ctx, project_folder, init=False, **options):
"""If no options are set, display the runtime currently used by the project. To create a new runtime in the project root
use --init and the global --runtime option.
"""
options.update(ctx.obj)
projectPath = os.path.abspath(project_folder)
... | 5,309,179 |
def delete_vit(request):
"""
Delete a vit with API
"""
user = KeyBackend().authenticate(request)
if request.method == "POST":
if request.user.is_authenticated:
try:
vit = Vit.objects.get(id=request.POST.get('vit_pk'))
if vit.user == request.user:
... | 5,309,180 |
def convert(df_column):
"""
Converts a DataFrame column to list
"""
data_list = []
for element in df_column:
data_list.append(element)
return data_list | 5,309,181 |
def get_model(embedding_matrix, name='baseline_model'):
"""
create model.
:return: model
"""
num_class = 4
inputs = tf.keras.layers.Input(shape=(config.MAX_SEQUENCE_LENGTH,))
embedding = tf.keras.layers.Embedding(embedding_matrix.shape[0], embedding_matrix.shape[1],
... | 5,309,182 |
def _get_remote_svg_tile(hass, host, port, prefix, name, width_tiles, c1, c2):
"""Get remote SVG file."""
url_tile = URL_TILE_MASK.format(host, port, prefix, name, width_tiles)
ok, r_svg, status = False, None, -1
try:
r_svg = yield from hass.async_add_job(
partial(requests.get, url_t... | 5,309,183 |
def sub(a: PipeNumeric, b: PipeNumeric):
"""
Pipeline node which subtracts b from a.
Optimization is performed where possible.
The return type is int if both parameters were integer and so the result is static.
Otherwise a OneCycleNode is returned.
:param a: parameter a
:param b: parameter b... | 5,309,184 |
def format_nested_dicts(value: Mapping[str, Mapping[str, Any]]) -> str:
"""
Format a mapping from string keys to sub-mappings.
"""
rows = []
if not value:
rows.append("(empty)")
else:
for outer_key, outer_value in value.items():
if isinstance(outer_value, dict):
... | 5,309,185 |
def MD5collect(signatures):
"""Deprecated. Use :func:`hash_collect` instead."""
_show_md5_warning("MD5collect")
return hash_collect(signatures) | 5,309,186 |
def adadelta(lr, tparams, grads, inp, cost, opt_ret=None, rho=0.99, eta=1e-7):
"""
Adadelta optimizer
:param lr:
:param tparams:
:param grads:
:param inp:
:param cost:
:param opt_ret:
:param rho: adadelta rho
:param eta: adadelta eta
:return f_grad_shared, f_update:
"""
... | 5,309,187 |
def shuffle_string(s):
"""
Shuffle a string.
"""
if s is None:
return None
else:
return ''.join(random.sample(s, len(s))) | 5,309,188 |
def check_jsons() -> None:
"""
Make sure all JSON configuration files are present.
"""
CONFIG: str = f"{DATA}/config.json"
try:
f: IO = open(CONFIG, "r")
f.close()
except FileNotFoundError:
TOKEN: str = input("BOT SETUP - Enter bot token: ")
with open(CONFIG, "w+") as f:
json.dump({"token": TOKEN}, f, ... | 5,309,189 |
def get_or_create_tables(options, session, create=True):
"""
Load or create canonical ORM KB Core table classes.
Parameters
----------
options : argparse.ArgumentParser
session : sqlalchemy.orm.Session
Returns
-------
tables : dict
Mapping between canonical table names and SQLA ORM classes.
e.g. {'origin... | 5,309,190 |
def dmp_zeros(n, u, K):
"""
Return a list of multivariate zeros.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.densebasic import dmp_zeros
>>> dmp_zeros(3, 2, ZZ)
[[[[]]], [[[]]], [[[]]]]
>>> dmp_zeros(3, -1, ZZ)
[0, 0, 0]
"""
if not n:... | 5,309,191 |
def to_ea(*args):
"""
to_ea(reg_cs, reg_ip) -> ea_t
Convert (seg,off) value to a linear address.
@param reg_cs (C++: sel_t)
@param reg_ip (C++: ea_t)
"""
return _ida_ida.to_ea(*args) | 5,309,192 |
def p_bucketargs(p):
"""bucketargs : field"""
p[0] = p[1] | 5,309,193 |
def get_chi_analysis_pipeline( primary_spectrum: Union[ Spectrum, str ], speclist: Iterable[ Union[ Spectrum, str ] ],
wl_limits: Tuple[ float, float ], maximum_chi_value: float, n_sigma: float = 1,
scale_AB_mag: float = CHI_BASE_MAG ) -> analysis_pipeline:
... | 5,309,194 |
def rank(words: List[str], exclude_stopwords: bool = False) -> Counter:
"""
Sort words by frequency
:param list words: a list of words
:param bool exclude_stopwords: exclude stopwords
:return: Counter
"""
if not words:
return None
if exclude_stopwords:
words = [word for... | 5,309,195 |
def get_restaurant(request):
"""
通过openid获取餐厅信息
"""
openid = request.GET.get('openid', None)
try:
restaurant = Restaurant.objects.get(openid=openid)
except Restaurant.DoesNotExist:
return Response('restaurant not found', status=status.HTTP_404_NOT_FOUND)
serializer = Restaur... | 5,309,196 |
def level_info():
"""Returns True if info logging is turned on."""
return get_verbosity() >= INFO | 5,309,197 |
def _get_low_and_high_version_from_range(version_range):
"""
Parse a version range into its low and high components.
:param version_range: the version range
:return: the low and high version components, an empty string is returned if there is no upper bound
"""
_method_name = '_get_low_and_high_... | 5,309,198 |
async def test_min_max_mireds(hass):
"""Test min/max mireds reporting."""
await async_setup_component(
hass,
LIGHT_DOMAIN,
{
LIGHT_DOMAIN: {
"platform": DOMAIN,
"entities": ["light.test1", "light.test2"],
}
},
)
has... | 5,309,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.