content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def plus97_modulus26_minus97(number):
"""
Replica algunas operaciones realizadas por el DGA a cada caracter.
Suma 97, realiza el modulo 26 y vuelve a sumar 97
:param number: entero que representa el carácter en base a la tabla ASCII
:return: el carácter resultante
"""
return chr(((number - 9... | ddf68bb67775fd033d20a6662602a2c0ef34a628 | 698,737 |
def browser_to_use(webdriver, browser):
"""Recover the browser to use with the given webdriver instance.
The browser string is case insensitive and needs to be one of the values
from BROWSERS_CFG.
"""
browser = browser.strip().upper()
# Have a look the following to see list of supported brows... | 0e6bca7bad48c7c2934b81fce080f848e9bcdb22 | 698,738 |
def update_appliance_hostname(
self,
ne_pk: str,
hostname: str,
) -> bool:
"""Add or update hostname to Edge Connect appliance. This operation
will take a few seconds to run.
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* -... | c08af64efe2e9c1e31faec0845e6bf61606b527b | 698,739 |
def get_max_table_size(final_tables):
"""
Compute the maximum number of elements that appear in one of the table generated inside the main process.
Parameters
----------
final_tables : list
list of the tables generated inside the loop for each bucket.
Returns:
--------
... | a562d6f944a03785034028e8b2e83bdb19a8d9aa | 698,740 |
import itertools
def next_bigger(n: int) -> int:
"""
A function that takes a positive integer number
and returns the next bigger number formed by the same digits.
If no bigger number can be composed using those digits, return -1
"""
numbers = sorted(set(sorted(int(''.join(i)) for i in iterto... | 8800040f3e88054bcacdb432131f8a9e0a872277 | 698,741 |
def getItemPos(item, inList):
""" get item position from the list """
for i, j in enumerate(inList):
if j == item:
return i
return -1 | a77bc384641881582625d6c48187de8d23e7154b | 698,742 |
import requests
import socket
def _get_response_tuple(url):
"""Return a tuple which contains a result of url test
Arguments:
url -- a string containing url for testing
Result tuple content:
result[0] -- boolean value, True if the url is deemed failed
result[1] -- unchange url argumen... | 786f7ff4e731b968fc502847d1b96b9f3a8274bc | 698,743 |
import re
def ReplaceResourceZoneWithRegion(ref, args, request):
"""Replaces the request.name 'locations/{zone}' with 'locations/{region}'."""
del ref, args # Unused.
request.name = re.sub(
r'(projects/[-a-z0-9]+/locations/[a-z]+-[a-z]+[0-9])[-a-z0-9]*((?:/.*)?)',
r'\1\2', request.name)
return re... | 97f416e77799c28699b251ccd45a89f29cd34c65 | 698,744 |
def get_mac_addr_from_datapath(datapath):
"""
Return the MAC address from the datapath ID.
According to OpenFlow switch specification, the lower 48 bits of the datapath
ID contains the MAC address.
"""
mac_addr_int = datapath.id & 0x0000ffffffffffff
mac_addr = format(mac_addr_int, '02x')
return... | 539c0b0a92f3eead947aed65ed62a1e630dcb30f | 698,745 |
def create_empty(val=0x00):
"""Create an empty Userdata object.
val: value to fill the empty user data fields with (default is 0x00)
"""
user_data_dict = {}
for index in range(1, 15):
key = "d{}".format(index)
user_data_dict.update({key: val})
return user_data_dict | 55e614059940b7eda5a0684dd105a60dbc7f1549 | 698,746 |
import re
def remove_tags(text):
"""
remove html style tags from some text
"""
cleaned = re.sub('<[^>]+>', '', text)
return re.sub('\s+',' ', cleaned).strip() | 5bbce34ca179f871eca6306f7fbe50b5cc1ee893 | 698,747 |
def decorator_blank_line_and_sleep(function):
""" This decorator just waits one second and prints a blank line after executing function"""
def inner_wrapper(*args, **kwargs):
input("")
value = function(*args, **kwargs)
print()
return value
return inner_wrapper | 1f544c87990c24b0cd82eeefe524cdf0649de69b | 698,748 |
def get_note_type(syllables, song_db) -> list:
"""
Function to determine the category of the syllable
Parameters
----------
syllables : str
song_db : db
Returns
-------
type_str : list
"""
type_str = []
for syllable in syllables:
if syllable in song_db.motif:
... | 621448603581a56af22ec9c559f9854c62073318 | 698,749 |
import asyncio
def _get_selector_noop(loop) -> asyncio.AbstractEventLoop:
"""no-op on non-Windows"""
return loop | b2b53006c66a2900642858a9bc975c54225d8034 | 698,750 |
def get_plain_text(values, strip=True):
"""Get the first value in a list of values that we expect to be plain-text.
If it is a dict, then return the value of "value".
:param list values: a list of values
:param boolean strip: true if we should strip the plaintext value
:return: a string or None
... | 3c0937d1faefda4ba8649005e29c9961afbadc0a | 698,751 |
import os
def check_wiki_art(artical_name):
"""
takes the user input (the artical name) and checks if its in the dicts file
outputs
- bool (is the file on the disk of not)
- a list of all file names for all files in dict dictionary
"""
list_of_text_files = []
for i in os.listdir('di... | cbed2a33a2855a50347640dbfe6d2ad9a2e35f18 | 698,752 |
def move_polygon(polygon_coords=None, move_coords=None, limit_x=None, limit_y=None):
"""
update coordinate pairs in a list by the specified coordinate pair that represents distance
:param polygon_coords: a list of coordinate pairs
:param move_coords: a coordinate pair that holds offset values for the x... | 4f21f5e6e561697edde7e1e3c6baefada16fe7e9 | 698,753 |
def validate_request(request):
"""
Make sure the request is from Twilio and is valid.
Ref: https://www.twilio.com/docs/security#validating-requests
"""
# Forgot where this token if from. Different from above.
# From: https://www.twilio.com/user/account/developer-tools/test-credentials
# Sho... | a83f3065fcebcb8231be4ed5558743fa6d837754 | 698,754 |
def mathprod(seq): # math.prod function is available at python 3.8
"""
returns product of sequence elements
"""
v = seq[0]
for s in seq[1:]:
v *= s
return v | b75ff229e4cfaabe42e542367dd27e257f1d33ec | 698,755 |
from typing import List
from typing import Any
def _split_list_into_chunks(x: List[Any], chunk_size: int = 50) -> List[List[Any]]:
"""Helper function that splits a list into chunks."""
chunks = [x[i:i + chunk_size] for i in range(0, len(x), chunk_size)]
return chunks | b9972b57a18a97fceec78ec1d55156c83d255f9f | 698,756 |
import math
def fix(x):
"""
From http://www.mathworks.com/help/matlab/ref/fix.html
fix
Round toward zero
Syntax:
B = fix(A)
Description:
B = fix(A) rounds the elements of A toward zero,
resulting in an array of integers.
For complex A, the im... | d57d4dd7088b2191e63fff16d0000508275f8a09 | 698,758 |
import platform
def is_linux():
"""是否Linux操作系统"""
return 'Linux' in platform.system() | f88693b702396c1ccb1220c0ea0c7edae78d03e6 | 698,759 |
import os
def get_mock_server_mode() -> str:
"""Returns a str representing the mode.
:return: threading/multiprocessing
"""
mode = os.environ.get("BOLT_PYTHON_MOCK_SERVER_MODE")
if mode is None:
# We used to use "multiprocessing"" for macOS until Big Sur 11.1
# Since 11.1, the "mu... | ead2a2b4d6ec569bdbc1b75c57c00382b03a52b2 | 698,760 |
def reversed_dict(choices):
"""Create a reverse lookup dictionary"""
return dict([(b, a) for a, b in choices]) | 85355bac403e8a49e55710eeef979120b1a34788 | 698,761 |
def project_detail(list_of_active_project, user_roles):
"""
To give project details for a particular project id
Args:
list_of_active_project(list):List of project id's.
user_roles(object):UserOrgRole object.
Returns:
Returns project details with org id.
"""
# dict o... | 6bdf9bdd74e33c0553ac2b804b58c54c351b69f0 | 698,762 |
def create_demand_callback(data):
"""Creates callback to get demands at each location."""
def demand_callback(from_node, to_node):
return data["demands"][from_node]
return demand_callback | ceff0d3caaa1e1269fee18e8aa4684afaa7a5e81 | 698,763 |
import re
def is_pages(value: str) -> float:
"""Asserts that a value looks like page number(s)."""
pages = re.compile(r'(\d+)(?:\s+)?[\s\-._/\:]+(?:\s+)?(\d+)')
match = pages.match(value)
if match:
start, end = [int(i) for i in match.groups()]
if start < end:
return 1.0
... | e816007698f902a4812446bd4270224fbb7ae6fc | 698,764 |
import sys
import sqlite3
def canRunPinger():
"""Return true iff we have the required libraries installed to run a pinger.
"""
return sys.version_info[:2] >= (2,2) and sqlite3 is not None | 3c6167412622504b860c971a7a9e976c59f576be | 698,765 |
def _get_unique_index_values(idf, index_col, assert_all_same=True):
"""
Get unique values in index column from a dataframe
Parameters
----------
idf : :obj:`pd.DataFrame`
Dataframe to get index values from
index_col : str
Column in index to get the values for
assert_all_sa... | 306a919a547a6d0056a4547daa50e6149d840910 | 698,766 |
import os
def is_empty_file(f_name):
"""Function: is_empty_file
Description: Checks to see if a file is empty.
NOTE: Returns None if file does not exist.
Arguments:
(input) f_name -> File being checked.
(output) status -> True|False|None -> True if file is empty.
"""
... | f5f04af0cd721424147188fec98a44e054e8614f | 698,767 |
from typing import Counter
def occurences_counter(filepath, writepath='counts.txt'):
"""Counts occurences of words in a dataset
Input:
filepath: file to open
writepath: file where is written the result of the count, format is: key | count
Output:
Counter dictionary object filled w... | cb72b7b9bdcbbbe5dfdf5c86e3c43b5fe98ac3ea | 698,768 |
import os
def locate_blockmesh_template():
"""the function uses the StoveOpt path and blockmesh template name to open the
template version of the blockMeshDict file for editing in the system folder
Args:
None
Returns:
blockmesh_template (str): full file path where blockmesh template lives
... | d2fdbdf5890551f1e808217d70076654ce59e96a | 698,769 |
def count_query(query):
"""
The Google Cloud Datastore API doesn't expose a way to count a query
the traditional method of doing a keys-only query is apparently actually
slower than this method
"""
# Largest 32 bit number, fairly arbitrary but I've seen Java Cloud Datastore
# co... | 6ad65b75838048cac0a0360098972427034e6cca | 698,770 |
import torch
def log_importance_weight_matrix(batch_size, dataset_size):
"""
Calculates a log importance weight matrix
Parameters
----------
batch_size: int
number of training images in the batch
dataset_size: int
number of training images in the dataset
"""
N = dataset_s... | 78555bd2e35bae8587602e43698c98bb0f463b21 | 698,772 |
def algo2(x,y):
"""
Trouve le nombre de carres dans deux listes pour chaque absisse
Args:
x (list): liste des cordonnees en x
y (lsit): liste des coordonnees en y
Returns:
int: Nombre de carres
"""
liste_x = []
liste_y = []
resul = 0
'''Crée une liste qui co... | d2e1c47f98c912fff3f02f759176b81b479ca659 | 698,773 |
def check_board(board):
"""
This function is to check if the board is in correct format
The length of the board must be 9 (Rows)
Each row must have 9 elements (Columns)
Each element must be between 1 - 9
"""
check_if_the_board_is_correct = True
if len(board) == 9:
... | f5940470c6158bfd500aca40a9f89c715d8592ac | 698,774 |
import re
def remove_url(txt):
"""Replace URLs found in a text string with nothing
(i.e. it will remove the URL from the string).
Parameters
----------
txt : string
A text string that you want to parse and remove urls.
Returns
-------
The same txt string with url's removed.
... | 8d1b8b89cb65ca7761c093dc388d1f19729137e7 | 698,775 |
import time
def findLoadOnBus(mirror, Busnum, Id=None):
"""Find first load on bus unless Id specified
Note that Ids are typically a strings i.e. '2'
"""
tic = time.time()
if not mirror.searchDict:
for x in range(len(mirror.Load)):
if mirror.Load[x].Busnum == Busnum:
... | 1b81f7495b5ea5fe060d7eead92db10510b76c97 | 698,776 |
def release_gamepad_input() -> None:
"""release_gamepad_input() -> None
(internal)
Resumes normal gamepad event processing.
"""
return None | fe4ea812ba64d50dec7d67c85f93199af8a27b30 | 698,777 |
def _bin_str_to_int(bin_str):
"""
This function returns integere value extracted from binary string of
length 16.
:param bin_str:
:return:
"""
if len(bin_str) <= 16:
return int(bin_str, 2)
else:
None | 42ea2d6858d9e41f0dcffb9711ea287c8d051f07 | 698,778 |
def str_to_bytes(s):
"""convert string to byte unit. Case insensitive.
>>> str_to_bytes('2GB')
2147483648
>>> str_to_bytes('1kb')
1024
"""
s = s.replace(' ', '')
if s[-1].isalpha() and s[-2].isalpha():
_unit = s[-2:].upper()
_num = s[:-2]
elif s[-1].isalpha():
_unit = s[-1].upper()
... | 71bef1d7a81fad44a00deb268fba83dac1ed633e | 698,779 |
def select_first_node(g):
"""
:param g: the graph
:return: the first node of the node sequence based on which the graph will be partitioned. We select the first node
as the node which has the lowest degree
"""
all_degrees = []
node_list = list(range(0, len(g)))
for node in node_list:
... | 769a36437e38b19984f88f510b544c22df984106 | 698,780 |
def get_subsequences(sequence):
"""
Get length k-1 subsequences of length k sequence
>>> get_subsequences((('A', 'B'), ('C',)))
[(('A', 'B'),), (('A',), ('C',)), (('B',), ('C',))]
>>> get_subsequences((('A', 'B'), ('C',), ('D', 'E')))
[(('A', 'B'), ('C',), ('D',)), (('A', 'B'), ('C',), ('E',)),... | 7f25a3339d7b73eda1d56b7c4cb7941adc17adad | 698,781 |
import typing
import os
def find(root_dir: str, name: str) -> typing.Optional[str]:
"""
recurse through the desired directory, and return a py.path.local
object that matches that name.
"""
for root, _, file_names in os.walk(root_dir):
if name in file_names:
return os.path.join(... | 08657d7a0a20137a283d20af73f39697f0cbdf86 | 698,782 |
import sys
def get_keyword_list(file_name):
"""获取文件中的关键词列表"""
with open(file_name, 'rb') as f:
try:
lines = f.read().splitlines()
lines = [line.decode('utf-8-sig') for line in lines]
except UnicodeDecodeError:
print(u'%s文件应为utf-8编码,请先将文件编码转为utf-8再运行程序', file... | 2d3b2c0feb0fb43dd52cba83ce45ffb6722ad6c4 | 698,783 |
def _flatten(coll):
""" Flatten list and convert elements to int
"""
if isinstance(coll, list):
return [int(a) for i in coll for a in _flatten(i)]
else:
return [coll] | a6f1dee42a5c881e4cf4496283f248a230f38465 | 698,784 |
def augment_parser(parser):
"""Augment parser from sequential wrapper with parallel wrapper"""
group = parser.add_argument_group("Parallel Options", "Configuration of parallel execution")
group.add_argument(
"--threads",
type=int,
default=1,
help="Number of threads to use fo... | 481e0edc9e8d90ccbc5f0d71ef201ccd9ac23a01 | 698,785 |
def to_float_hours(hours, minutes, seconds):
""" (int, int, int) -> float
Return the total number of hours in the specified number
of hours, minutes, and seconds.
Precondition: 0 <= minutes < 60 and 0 <= seconds < 60
>>> to_float_hours(0, 15, 0)
0.25
>>> to_float_hours(2, 45, 9)
2.7... | f94f37585929fc45f4b417ab63ca9b7b501a2e57 | 698,786 |
def fit_simulaid(phi):
"""
DEPRECATED AND WORKING FOR SMALL NUMBER OF SAMPLES
--
Fit theta such as:
phi_i = theta * i + phi_0 (E)
Solving the system:
| SUM(E)
| SUM(E*i for i)
that can be written:
| a11 * theta + a12 * phi_0 = b1
| a21 * theta + a22 * ph... | 98a9bf064e56a48312170a8c32e032654317d40f | 698,787 |
import difflib
def _get_suggestion(provided_string, allowed_strings):
"""
Given a string and a list of allowed_strings, it returns a string to print
on screen, with sensible text depending on whether no suggestion is found,
or one or more than one suggestions are found.
:param provided_string: th... | ebd1b963116bddebbc340312f2d7a16be36b11c6 | 698,789 |
def iso_8601(datetime):
"""Convert a datetime into an iso 8601 string."""
if datetime is None:
return datetime
value = datetime.isoformat()
if value.endswith('+00:00'):
value = value[:-6] + 'Z'
return value | 968b9d9edfe13340e4c2f74fb78c11cb38d6c013 | 698,790 |
import os
def to_abs_path(relative_path):
"""Returns a canonical path for the specified path relative to the script
directory.
"""
script_dir = os.path.dirname(os.path.realpath(__file__))
return os.path.realpath(os.path.join(script_dir, relative_path)) | c333c999fce96ba9a05975d4df690c7c86ac0426 | 698,791 |
def compute_accuracy(y_pred, y_test):
"""Compute accuracy of prediction.
Parameters
----------
y_pred : array, shape (N_test)
Predicted labels.
y_test : array, shape (N_test)
True labels.
"""
true_counter = 0
for i in range(len(y_pred)):
if y_pred[i] == y_test[i]... | a06b4d91f1878288ab4746d1f729040c95b91a91 | 698,793 |
def get_request_url(url, *args, **kwargs):
"""Returns url parameter that request will use"""
return url | fde43b531d53e0f3cf80655b0da9895b7a001e13 | 698,794 |
import sys
def _load(target, **vars):
""" Fetch something from a module. The exact behaviour depends on the the
target string:
If the target is a valid python import path (e.g. `package.module`),
the rightmost part is returned as a module object.
If the target contains a colon (e.... | 44446d742765ff96f4bbc38546157c5abc3dffa8 | 698,795 |
def square_table_while(n):
"""
Returns: list of squares less than (or equal to) N
This function creates a list of integer squares 1*1, 2*2, ...
It only adds those squares that are less than or equal to N.
Parameter n: the bound on the squares
Precondition: n >= 0 is a number
"""
... | 8eb94d9690f4138fb6759cf73d5a602659571b34 | 698,796 |
import os
def val_dir(string: str) -> str:
"""Check that provided string is a directory."""
if os.path.isdir(string):
return string
else:
raise NotADirectoryError | 092689cc81c40a29c71aa8475f231423f2bc2e3b | 698,797 |
def populate_words(words, oxford_api, words_api=None, allow_messages=True):
"""
Iterates the words dictionary, populating the data of each object using the OxfordAPI and with the optional
WordsAPI to be used in the case the word is not found in the Oxford dictionary.
:param words: The dictionary contain... | 6f435b2e8d9947a9e7c6ba558aa43e13fe0dcfd6 | 698,798 |
import argparse
def read_cmd():
"""Reading command line options."""
desc = "Program for relinking Khan Content Bakalari NEXT e-learning module."
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-s','--subject', dest='subject', default='root', help='Relink content for a given domain/... | 7015f4d4917fcabf9ee5e9437ac813138db1b874 | 698,799 |
def media_artist(self):
"""Artist of current playing media, music track only."""
return self._media_artist | 12e0538850bfb04ae52fe6840b7445423e393687 | 698,800 |
def flattenEmailAddresses(addresses):
"""
Turn a list of email addresses into a comma-delimited string of properly
formatted, non MIME-encoded email addresses, suitable for use as an RFC
822 header
@param addresses: sequence of L{EmailAddress} instances
"""
return ', '.join(addr.pseudoForma... | 91c235451006747e419cfd1e01eb7151eec952ed | 698,801 |
def split(text):
""" sometext|split """
return text.split() | 5067bad72a36827f221bde6fcd86c3c124f0b12b | 698,802 |
def structural_parameters(keys, columns):
"""
Gets the structural parameters in a specific order (if catalog is generated by the method in tbridge.binning)
"""
mags = columns[keys.index("MAGS")]
r50s = columns[keys.index("R50S")]
ns = columns[keys.index("NS")]
ellips = columns[keys.index("EL... | 3e6fd7c231f31f4fdcb47cd76359411d194f5539 | 698,803 |
def poly(a, x, y, order=4):
"""Polynomial evaluation.
pol = a[i,j] * x**(i-j) * y**j summed over i and j, where i runs from 0 to order.
Then for each value of i, j runs from 0 to i.
For many of the polynomial operations the coefficients A[i,j] are contained in an
array of dimension (order+1, order+... | e5575d4df2ae4cc5f7f1eea467d9b04ebbb97942 | 698,804 |
import argparse
def parser(args):
"""Return parsed command line arguments."""
parser = argparse.ArgumentParser(
description=(
'Extracts the convergence indicators of a ONETEP BFGS geometry\n'
'optimisation calculation from the output file, and compares\n'
'them to t... | bef30fbd9278a17e06c68bf7af9d04b877883b1c | 698,805 |
import struct
def short_to_bytes(short_data):
"""
For a 16 bit signed short in little endian
:param short_data:
:return: bytes(); len == 2
"""
result = struct.pack('<h', short_data)
return result | 26eeb2de936fa6b434c724ef80c008d93aec0446 | 698,806 |
def adjust(new_rows, maxi):
"""
A function to set all with maxi number of columns
for making csv compatible
"""
rows = []
for each_row in new_rows:
if len(each_row) < maxi:
for i in range(maxi - len(each_row)):
each_row.append("-")
rows.append(each_row... | 2151362add7a85c4a236ad9ee936dcc08578534b | 698,807 |
def unflatten_B(t):
""" Unflatten [B*3, ...] tensor to [B, 3, ...] tensor
t is flattened tensor from component batch, which is [B, 3, ...] tensor
"""
shape = t.shape
return t.view(shape[0]//3, 3, *shape[1:]) | 77017ca136a942f975dfd498fe3aa8d3d20f67b9 | 698,808 |
import torch
def l12_smooth(input_tensor, a=0.05):
"""Smoothed L1/2 norm"""
if type(input_tensor) == list:
return sum([l12_smooth(tensor) for tensor in input_tensor])
smooth_abs = torch.where(torch.abs(input_tensor) < a,
torch.pow(input_tensor, 4) / (-8 * a ** 3) + to... | f6de684a53605aa3f28cf21f46f90dbb5d325616 | 698,809 |
def _dedupe_entities(alerts, ents) -> list:
"""Deduplicate incident and alert entities."""
alrt_ents = []
for alrt in alerts:
if alrt["Entities"]:
alrt_ents += [ent.__hash__() for ent in alrt["Entities"]]
for ent in ents:
if ent.__hash__() in alrt_ents:
ents.remo... | 9fc56c217d5a6f2ad85c100f3ee5f8a049de0d1c | 698,810 |
def find_components(value):
""" Extract the three values which have been combined to
form the given output.
"""
r1 = value >> 20 # 11 most significant bits
r2 = (2**10 - 1) & (value >> 10) # 10 middle bits
r3 = (2**10 - 1) & value # 10 least significant bits
return... | 80a235cafe8ceb37cafb6453f3338e03653bffe1 | 698,811 |
def most_energetic(df):
"""Grab most energetic particle from mc_tracks dataframe."""
idx = df.groupby(["event_id"])["energy"].transform(max) == df["energy"]
return df[idx].reindex() | 031e5a92d9e890743323012227ffbd4048d0052a | 698,812 |
def GetInvalidTypeErrors(type_names, metrics):
"""Check that all of the metrics have valid types.
Args:
type_names: The set of valid type names.
metrics: A list of rappor metric description objects.
Returns:
A list of errors about metrics with invalid_types.
"""
invalid_types = [m for m in metri... | 27af3804cb4a857d044ad365cdfee090a0d1ab56 | 698,813 |
import textwrap
def indent(multiline_str: str, indented=4):
"""
Converts a multiline string to an indented string
Args:
multiline_str: string to be converted
indented: number of space used for indentation
Returns: Indented string
"""
return textwrap.indent(multiline_str, " " ... | 9fd5f2310ade00071a57731040435428cff88557 | 698,815 |
def list_pattern_features(client, patter_name, type_=None, file_=None):
"""List features in a Creo Pattern.
Args:
client (obj):
creopyson Client.
patter_name (str):
Pattern name.
`type_` (str, optional):
Feature type patter (wildcards allowed: True).
... | d1923ccdb178a211ecd896c325170a5e247557aa | 698,816 |
def get_binary_mask(x):
"""
Return binary mask from numpy array
:param x: numpy array
:return: binary mask from numpy array
"""
x[x >= 0.5] = 1.
x[x < 0.5] = 0.
return x | d63a2cff4d8398c52ea97fff720d78a8d6df66b5 | 698,817 |
def is_possible_move(direction, you, snake_heads, occupied, height, width, spacing=1):
"""
:param direction: up down left or right
:type direction: str
:param you: all blocks our body is occupying
:type you: list of dict
:param occupied: all blocks all snakes are occupying
:type occupied:... | 01909f9daecd01fd21b13c5a24bc0081ce50b7c9 | 698,818 |
def valid_permlink(permlink, allow_empty=False):
"""Returns validated permlink or throws Assert."""
assert isinstance(permlink, str), "permlink must be string: %s" % permlink
if not (allow_empty and permlink == ''):
assert permlink and len(permlink) <= 256, "invalid permlink"
return permlink | ec5094ed8ac938b85c423218527d92b89ba3f1f3 | 698,819 |
def get_answer(offer, user):
"""Returns an user answer for the given offer"""
if not user.is_authenticated:
return None
return offer.answers.filter(user=user).first() | e89da7d11e6e8a01deb8177d3af9c693267fe09a | 698,820 |
import os
def getMusZs(directory=""):
"""
Searches directory specified and returns a list of redshifts for GadgetMUSIC
snapshots.
Assumes file names are of format GadgetMUSIC-NewMDCLUSTER_0001.z0.000...
Directory must only contain files with names of this format.
Parameters
----------
... | 8834b8dbae8e07056fd68fe974476d54be64487a | 698,821 |
async def oppio_client_supervisor(opp, aiohttp_client, oppio_stubs):
"""Return an authenticated HTTP client."""
access_token = opp.auth.async_create_access_token(oppio_stubs)
return await aiohttp_client(
opp.http.app,
headers={"Authorization": f"Bearer {access_token}"},
) | ccc821b17490e8c9163a813d8b9aab03f1467713 | 698,822 |
import os
import json
def load_gt(file_name):
"""load ground truth data, if existent"""
file_path = os.path.join(os.path.realpath('.'), 'mock', file_name + '.gt.json')
if os.path.exists( file_path ):
with open(file_path, 'r') as file:
# load file
processed_table = json.loa... | bec3389d0316f3965fed874aa6668a2a44e27d8d | 698,823 |
import logging
import os
def get_path_contents(folder_path):
"""
Get the entire contents of a path. Returns both files and folders at this path, and does not return
filenames contained within sub-folders at this path.
:param folder_path: a string containing a valid path to a computer directory
:r... | bcae9d348e236ebdd3716e1397cbf23eecb9e883 | 698,824 |
def leiaDinheiro(msg):
"""
-> Função que verifica se um preço digitado é valido
:param msg: recebe a menssagem pedindo um preço
:return: retorna o preço válido
"""
while True:
preco = input(msg).strip().replace(',', '.')
if preco.isalpha() or preco == "":
print(f'\033... | 9712bf74c29f0ac62d6f2326794d0537cc885b5c | 698,825 |
def process_dsn(dsn):
"""
Take a standard DSN-dict and return the args and
kwargs that will be passed to the psycopg2 Connection
constructor.
"""
args = ['host=%s dbname=%s user=%s password=%s' % (dsn['host'], dsn['db'], dsn['user'], dsn['passwd'])]
del dsn['host']
del dsn['db']
del dsn['user']
del dsn['passw... | c73b641cd4e28c5824db6d37d3aec2786c7461ff | 698,826 |
import sys
def Unchecked():
"""Verify if the command "Unchecked" is present. In this case it means the action was just unchecked from RoboDK (applicable to checkable actions only)."""
if len(sys.argv) >= 2:
if "Unchecked" in sys.argv[1:]:
return True
return False | 70e288eb5a662f0aca9ebf6f4429b3b8510ea307 | 698,827 |
import random
def _random_level():
"""Returns a random level for the new skiplist node
The return value of this function is between 1 and ZSKIPLIST_MAXLEVEL
(both inclusive), with a powerlaw-alike distribution where higher
levels are less likely to be returned.
"""
level = 1
while random.... | 3f5f13defae1140836fedf29c257ed6fc9b68384 | 698,829 |
import subprocess
def capture(command):
"""
Run input command as subprocess and caputure the subprocess' exit code, stdout and stderr.
Parameters
----------
command : list of str
Command to be run as subprocess.
Returns
-------
out : str
Standard output message.
e... | b2d668f4ff125f1793b2688c127276fe9c209651 | 698,830 |
from string import Template
import os
def css_renditions(selector=None):
"""
Returns a (long) string containing all the CSS styles in order to support
terminal text renditions (different colors, bold, etc) in an HTML terminal
using the dump_html() function. If *selector* is provided, all styles will
... | 0582fce55be4b9e5a5e617dac02d930159857b20 | 698,831 |
import re
def quac_qasm_transpiler(qiskit_qasm: str) -> str:
"""Converts Qiskit-generated QASM instructions into QuaC-supported instructions
:param qiskit_qasm: a string with a QASM program
:return: a string with a modified QuaC-supported QASM program
"""
quac_qasm = ""
for line in qiskit_qas... | 1db5932053e00756e80db49b555ee70d3f4d881c | 698,832 |
def moftype(cimtype, refclass):
"""Converts a CIM type name to MOF syntax."""
if cimtype == 'reference':
_moftype = refclass + " REF"
else:
_moftype = cimtype
return _moftype | c09697b9a1fabea1f1529de8ab7ee7eeed4da846 | 698,834 |
def shift(arr: list):
"""
方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度
从数组中删除的元素; 如果数组为空则返回 undefined(None)
"""
if len(arr):
return arr.pop(0)
return None | ff7ea2320c6b9f846b8d047e6a6a76d0cd7ab645 | 698,835 |
def handle_status_update(loan_id, new_status):
"""Handles a status update for an order."""
# lookup order in your system using loan_id
# set order status to new_status
return '' | d75f6c145346d7fe9c6fd124dc0590fd66b64da6 | 698,836 |
def name_fun(n):
"""
input: stopping rule
output: finish nodes
"""
output = []
temp = ['']
for i in range(2*n - 1):
temp_cur = []
for j in temp:
candidate_pos = j + '+'
candidate_neg = j + '-'
if str.count(candidate_pos, '+') >= n:
... | 74111c9a31475a764ed98ab5e2cfae6ec894b10c | 698,838 |
import json
def translate_header(df, dictionary, dictionary_type='inline'):
"""change the headers of a dataframe base on a mapping dictionary.
Parameters
----------
df : `DataFrame`
The dataframe to be translated
dictionary_type : `str`, default to `inline`
The type of dictionary,... | 371443bc112fa2b0892bbcf945e3089aab995122 | 698,839 |
def isHit(obbTree, pSource, pTarget):
"""
From https://blog.kitware.com/ray-casting-ray-tracing-with-vtk/
:param obbTree:
:param pSource:
:param pTarget:
:return:
"""
code = obbTree.IntersectWithLine(pSource, pTarget, None, None)
if code == 0:
return False
return True | 6c37fcb3ffc6f33d308e9762b1b0c27b2b374ef7 | 698,840 |
def rect2pathd(rect):
"""Converts an SVG-rect element to a Path d-string.
The rectangle will start at the (x,y) coordinate specified by the
rectangle object and proceed counter-clockwise."""
x, y = float(rect.get('x', 0)), float(rect.get('y', 0))
w, h = float(rect.get('width', 0)), float(rect.... | 60827810118abb4de47b12457806199639626aee | 698,841 |
import numpy
def weights(x, y, seeds, influences, decay=2):
"""
Calculate weights for the data based on the distance to the seeds.
Use weights to ignore regions of data outside of the target anomaly.
Parameters:
* x, y : 1d arrays
The x and y coordinates of the observations
* seeds :... | 2841c0740614cda25a157c3ff8a4eb0aa859e16c | 698,842 |
def judge_same_month(input_month_list):
"""
判断 数据 是否 在同一个月
:param input_month_list:list
:return: str or bool
"""
month_list = []
for item in input_month_list:
month_list.append(item["trade_date"].strftime("%Y-%m"))
month_set = set(month_list)
if len(month_set) != 1:
r... | 69082ac16150082bfe6cd9b384fa010a3849e682 | 698,843 |
def _create_trip_from_stack(temp_trip_stack, origin_activity, destination_activity):
"""
Aggregate information of trip elements in a structured dictionary
Parameters
----------
temp_trip_stack : list
list of dictionary like elements (either pandas series or python dictionary). C... | f2ddb6c19650c001c714ddeb8372b81ff40f2abe | 698,844 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.