content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def create_user(db, django_user_model: AbstractUser, test_password: str):
""" factory for creating users """
def make_user(username, email, first_name, last_name) -> AbstractUser:
new_user: AbstractUser = User.objects.create(username=username, email=email,
... | 51,800 |
def _read_network_data_from_h5(fname):
"""Read the network stored by the write_network_to_h5 function"""
bias_accumulator = []
weight_accumulator = []
with h5py.File(fname, "r") as hdf:
n_dense_layers = hdf["n_dense_layers"][...][0]
activation = list(hdf["activation"].keys())[0] # Extra... | 51,801 |
def credentials_from_file(file):
"""Load credentials corresponding to an evaluation from file"""
with open(file) as file:
return json.load(file) | 51,802 |
def get_workspace_vars(auth, workspace_id):
"""
Function to get variables created in a workspace
"""
headers = {"Content-Type": "application/json"}
url = f"https://intersight.com/tfc/api/v2/workspaces/{workspace_id}/vars"
response = requests.get(url, headers=headers, auth=auth)
response_data... | 51,803 |
def GetFileOutPassName():
""" """
pass | 51,804 |
def locate_btn(game, team_name, mkt_type, verbose=False):
"""
given selenium game, team_name, and mkt_type
returns find the specific bet button for the givens
game: selenium obj
team_name: str
mkt_type: 0 is point spread, 1 is moneyline, and 2 is over/under
"""
bet_buttons = get_bet_but... | 51,805 |
async def test_async_edit_tag(aresponses, radarr_client: RadarrClient) -> None:
"""Test editing tag."""
aresponses.add(
"127.0.0.1:7878",
f"/api/{RADARR_API}/tag",
"PUT",
aresponses.Response(
status=202,
headers={"Content-Type": "application/json"},
... | 51,806 |
def create_testing_account():
"""
Creates an account for usage in tests. This account should never be logged into, and is only accessed by
username in test cases
"""
# Only create a testing account if it doesn't exist already
if not get_user_by_name_db('testing'):
password = str(uuid.uu... | 51,807 |
def mailchimp_get_endpoint(**kwargs):
"""Endpoint that the mailchimp webhook hits to check that the OSF is responding"""
return {}, http_status.HTTP_200_OK | 51,808 |
def format_date(value, format='%Y-%m-%d'):
"""Returns a formatted time string
:param value: The datetime object that should be formatted
:param format: How the result should look like. A full list of available
directives is here: http://goo.gl/gNxMHE
"""
return value.strftime(fo... | 51,809 |
def Transpose(node):
"""(Simple) transpose
>>> print(matlab2cpp.qscript("a = [1,2,3]; b = a.'"))
sword _a [] = {1, 2, 3} ;
a = irowvec(_a, 3, false) ;
b = arma::strans(a) ;
"""
# unknown datatype
if not node.num:
return "arma::strans(%(0)s)"
"""
# colvec -> rowvec
... | 51,810 |
def get_xml_type(val):
"""Returns the data type for the xml type attribute"""
if type(val).__name__ in ('str', 'unicode'):
return 'str'
if type(val).__name__ in ('int', 'long'):
return 'int'
if type(val).__name__ == 'float':
return 'float'
if type(val).__name__ == 'bool':
... | 51,811 |
def DatetimeToWmiTime(dt):
"""Take a datetime tuple and return it as yyyymmddHHMMSS.mmmmmm+UUU string.
Args:
dt: A datetime object.
Returns:
A string in CMI_DATETIME format.
http://www.dmtf.org/sites/default/files/standards/documents/DSP0004_2.5.0.pdf
"""
td = dt.utcoffset()
if td:
offset =... | 51,812 |
def _add_suffix(params, model):
"""Add derivative suffixes to a list of parameters."""
params_full = params.copy()
suffix = {
"basic": {},
"derivatives": {"derivative1"},
"power2": {"power2"},
"full": {"derivative1", "power2", "derivative1_power2"},
}
for par in param... | 51,813 |
def format_config(args):
"""
Formats default parameters from argparse to be easily digested by module
"""
fn_train = os.path.abspath(args.dataset_path)
#Calculate area_min and area_max if none provided (default)
if args.area_min==args.area_max:
data = pd.read_csv(fn_train+'.csv').to_num... | 51,814 |
def _random_covariance_matrix(batch_size):
"""Generate a batch of random covariance matrices.
Args:
batch_size: Number of elements in the first dimension returned.
Returns:
A tensor with dimensions [batch_size, 2, 2].
"""
# Make a random covariance matrix by taking the outer product of 10 random
#... | 51,815 |
def parse_ranges_highlight(ranges_string):
"""Process ranges highlight string.
Args:
ranges_string: (str) A string representing a numerical range of a list of
numerical ranges. See the help info of the -r flag of the print_tensor
command for more details.
Returns:
An instance of tensor_forma... | 51,816 |
def have_instance(nova_connection: NovaConnection, instance_name: str):
"""
Check if the instance_name is in the same region that nova_connection
:param nova_connection: NovaConnection
:param instance_name: str content the instance name
:return: bool
"""
for server in nova_connection.conne... | 51,817 |
def torchify_dict(data: dict):
"""
Transform np.ndarrays to torch.tensors.
Parameters
----------
data : dict
property data of np.ndarrays.
References
----------
.. [1] https://github.com/ken2403/schnetpack/blob/6617dbf4edd1fc4d4aae0c984bc7a747a4fe9c0c/src/schnetpack/data/atoms.... | 51,818 |
def run_command_output_file(cmd,
output_file_name,
shell_executable=None,
directory=None,
osenv=None,
input_file_name=None,
**kwargs):
"""
Run ... | 51,819 |
def select_black_ou(board):
"""
手番側の有効な王の利きを求めるために使う
:param board:
:return:
"""
# 桂馬で王手されているかを調べるために、擬似的に王から桂馬の効きを計算する
# 王の通常の動きの計算もある
# 2回使うので、collectionに登録する
name = 'black_short_ou'
collection = tf.get_collection_ref(name)
if len(collection) == 0:
selected = tf.to_... | 51,820 |
def question_senti(input_df):
"""Page for individual question's sentiment."""
questions = st.multiselect(
label="Select specific questions below:",
options=selected_nan_df.columns[2:],
)
select_text, questions_senti_df = ut.compute_question_senti(
questions, input_df
)
if... | 51,821 |
def bytes_to_decimal_bytes(bytes_decimal_str, is_little_endian=False):
"""
:param bytes_decimal_str:
:param is_little_endian:
:return:
"""
if not bytes_decimal_str.isdigit():
raise Exception('bytes_decimal_str 不是数字字符串!')
return
length = len(bytes_decimal_str)
tmp_list = ... | 51,822 |
def cython_img2d_color_std(img, seg, means=None):
""" wrapper for fast implementation of colour features
:param ndarray img: input RGB image
:param ndarray seg: segmentation og the image
:param ndarray means: precomputed feature means
:return: np.array<nb_lbs, 3> matrix features per segment
..... | 51,823 |
def prepareSpectrogram(
sim=None,
timeRange=None,
electrodes=['avg', 'all'],
pop=None,
LFPData=None,
NFFT=256,
noverlap=128,
nperseg=256,
minFreq=1,
maxFreq=100,
stepFreq=1,
smooth=0,
includeAxon=True,
logy=False,
normSignal=False,
normPSD=Fals... | 51,824 |
def log_api(msg):
"""log a message from api-website"""
print colored('API', 'green'), msg
# TODO: use log util, log to file, including time, module, etc. | 51,825 |
def note_view():
"""Displays the notes from your Google Keep account in a grid view with borders."""
google_notes = keep.all()
os.system('clear')
print(consts.YELLOW_BOLD)
print(fig.renderText('Keep...'))
if len(google_notes) == 0:
print(consts.RED, end='')
print('You don\'t ha... | 51,826 |
def setup_no_ip(opp, aioclient_mock):
"""Fixture that sets up NO-IP."""
aioclient_mock.get(UPDATE_URL, params={"hostname": DOMAIN}, text="good 0.0.0.0")
opp.loop.run_until_complete(
async_setup_component(
opp,
no_ip.DOMAIN,
{
no_ip.DOMAIN: {
... | 51,827 |
def mock_func_call(*args, **kwargs):
"""
Mock function to be used instead of benchmark
"""
options = Options()
cost_func = make_cost_function()
results = []
result_args = {'options': options,
'cost_func': cost_func,
'jac': 'jac',
'hes... | 51,828 |
def _full_gauss_den(x, mu, va, log):
""" This function is the actual implementation
of gaussian pdf in full matrix case.
It assumes all args are conformant, so it should
not be used directly Call gauss_den instead
Does not check if va is definite positive (on inversible
for that mat... | 51,829 |
def load_texture_pair(filename):
""" Handles textures """
return[
arcade.load_texture(filename),
arcade.load_texture(filename, mirrored=True)
] | 51,830 |
def set_field_value(context, field_value):
"""populates variable into a context"""
if field_value:
context['field_value'] = field_value
else:
context['field_value'] = ''
return '' | 51,831 |
def get_bbox(src_bbox, offset):
"""src_bboxにoffsetを適用し、元の領域を復元する。
RPNから得たoffset予測値をアンカーボックスに適用して提案領域を得る。といったケースで利用する。
Args:
src_bbox (tensor / ndarray): オフセットを適用するBoudingBox。
Its shape is :math:`(R, 4)`.
2軸目に以下の順でBBoxの座標を保持する。
:math:`p_{ymin}, p_{xmin}, p_{ymax},... | 51,832 |
def del_operation_times(operation_times_key):
"""
清除操作次数
参数:
operation_times_key 缓存key
"""
# 记录获取次数
cache_helper.delete(operation_times_key) | 51,833 |
def show_books(object_list):
"""
加载指定书籍列表的模板。
:param object_list: Book模型实例的列表
:return: 返回一个字典作为模板的上下文
"""
if len(object_list) > 0:
try:
getattr(object_list[0], 'object')
except AttributeError:
pass
else:
object_list = map(lambda ele: e... | 51,834 |
def update_db():
"""Update movie dB"""
movieSearchUrl = "https://unogsng.p.rapidapi.com/search"
countryListUrl = "https://unogsng.p.rapidapi.com/countries"
apiKey = os.environ.get("RAPID_KEY")
headers = {
'x-rapidapi-host': "unogsng.p.rapidapi.com",
'x-rapidapi-key': apiKey
}
... | 51,835 |
def destroy_env(env):
"""
Dummy function that destroys properly an OpenRAVE environment.
@note: Useful when working with C{IPython} + QtCoin viewer.
@type env: orpy.Environment
@param env: The OpenRAVE environment
"""
env.Reset()
env.Destroy() | 51,836 |
def test_Config_dotenv_overwrite(get_handler, mocker):
"""dotenv values should overwrite baseline"""
config = get_handler(target_module)
mocker.patch.object(config, "dotenv_values", return_value=config_sample)
c = config.Config()
assert c.obs_host == "foo"
assert c.obs_port == 1337
assert c.... | 51,837 |
def load_mesh_from_file(filepath, color=None, alpha=None):
"""
Load a a mesh or volume from files like .obj, .stl, ...
:param filepath: path to file
:param **kwargs:
"""
actor = load(str(filepath))
actor.c(color).alpha(alpha)
return actor | 51,838 |
async def fulfill_bundle(bundle_id, missing_files, api_key=''):
""" Upload missing files to bundle via API """
if not missing_files:
return
logger.debug('Uploading {} missing files'.format(len(missing_files)))
with tqdm(total=len(missing_files), desc='Uploading missing files', unit='files', leav... | 51,839 |
def find_html_form(forms, form_match):
# type: (Dict[AnyKey, Form], FormSearch) -> Optional[Form]
"""
Searches for the specified form amongst a group of multiple forms.
:param forms: Possible forms to distinguish and look for a specific one.
:param form_match:
Search criteria to retrieve th... | 51,840 |
def parse_dict(s, sep=None):
"""
parser for (ordered) dicts
:s: the input string to parse, which should be of the format
key1 := value1,
key2 := value2,
key3 := value3,
where the last comma is optional
:sep:... | 51,841 |
def compute_pdi(value_matrix, slice_list):
"""
Computes a 'preference' discordance index
:param value_matrix:
:param slice_list:
:return:
"""
pdi = ['x']
pdimax = ['x']
for i in slice_list:
incident = compute_incident(value_matrix, i)
complement = invert_matrix(incide... | 51,842 |
def sublist_search(array1, array2):
"""
:param array1: sublist
:param array2: list
:return: Whether list contains sublist
Time complexity: O(n * m)
"""
# Empty array
if len(array1) == 0:
return True
for start_idx in range(len(array2)):
if check_is_contained(array1, a... | 51,843 |
def _Uninstall(vm):
"""Uninstalls the OpenMPI package on the VM."""
vm.RemoteCommand('cd {0} && sudo make uninstall'.format(MPI_DIR)) | 51,844 |
def E_ab(a, b, edgePair, width, height, debug = False):
"""
Calculate the energy in the inverval a to b.
Parameters:
a, b - interval to integrate over
edgePair - the edge pair to interpolate
width, height - texture's dimensions
Returns: Energy matrix for the interval
"""
... | 51,845 |
def get_instance_names(node: AST) -> list[str]:
"""Extract names from an assignment node, only for instance attributes.
Parameters:
node: The node to extract names from.
Returns:
A list of names.
"""
return [name.split(".", 1)[1] for name in get_names(node) if name.startswith("self... | 51,846 |
def is_geq_than(x,y):
""" x is not None and greater than or equal to y """
if x != None:
if x>=y: return True
return False | 51,847 |
def write_title():
"""Write information to the track definition line of the wiggle file.
:return: None
"""
trackline = "track type=wiggle_0 name=\"GC percentage\" description=\"{}\"\n".format(record.description)
variablestep = "variableStep chrom={} span={}\n".format(record.id, str(window_size))
... | 51,848 |
def distr_selectbox_names():
"""
Accessing stats.name.
"""
names = ['alpha',
'anglit',
'arcsine',
'argus',
'beta',
'betaprime',
'bradford',
'burr',
'burr12',
'cauchy',
... | 51,849 |
def read_file(filename):
"""Read filename; return contents as one string."""
with open(filename) as my_file:
return my_file.read() | 51,850 |
def _walk_spec_mro(cls):
"""Walk the class MRO in reverse order, yielding the SPEC attr as it is
found on the class itself (and not inherited).
"""
for scls in reversed(cls.__mro__):
if 'SPEC' in vars(scls):
yield scls.SPEC | 51,851 |
def remove_intercept_column(X: np.ndarray) -> np.ndarray:
"""
Remove the first column
"""
if len(X.shape) == 1:
return X[1:]
return X[:, 1:] | 51,852 |
def get_user_configurations() -> Tuple[list, list]:
"""
Function that reads the $HOME/.pip folder and return two lists,
containing filenames and absolute path from them.
"""
pip_config_path = UserPath.PIP_CONFIG_DIRECTORY.value
config_filenames = read.get_user_configuration_files()
config_... | 51,853 |
def test_bst_full_in_order_trav(bst_full):
"""Test bst in order trav with full bst."""
nodes = []
gen = bst_full.in_order()
for _ in range(bst_full.size()):
node = next(gen)
nodes.append(node)
assert nodes == [0, 3, 4, 6, 8, 9, 11, 12, 13, 100] | 51,854 |
def compute_codebase_tallies(codebase, keep_details, **kwargs):
"""
Compute tallies of a scan at the codebase level for available scans.
If `keep_details` is True, also keep file and directory details in the
`tallies` file attribute for every file and directory.
"""
from summarycode.copyright_t... | 51,855 |
def say(number):
"""
print out a number as words in North American English using short scale terms
"""
number = int(number)
if number < 0 or number >= 1e12:
raise ValueError
if number == 0:
return "zero"
def quotient_and_remainder(number, divisor):
"""
retu... | 51,856 |
def get_s3_versions(bucket_name, key_name):
"""Get versioning information for a given key.
:param bucket_name: the bucket's name
:type bucket_name: string
:param key_name: the key's name
:type key_name: string
:return: for each version, the version id and the last modified date
:rtype: a li... | 51,857 |
def indentitems(items, indent, level):
"""Recursively traverses the list of json lines, adds indentation based on the current depth"""
res = ""
indentstr = " " * (indent * level)
for (i, item) in enumerate(items):
if isinstance(item, list):
res += indentitems(item, indent, level+1)
... | 51,858 |
def dcg_at_k(r, k):
"""
Args:
r: Relevance scores (list or numpy) in rank order
(first element is the first item)
k: Number of results to consider
Returns:
Discounted cumulative gain
"""
assert k >= 1
r = np.asfarray(r)[:k] != 0
if r.size:
return n... | 51,859 |
def birds():
"""
this program draws 3 to 5 birds in the sky by random
"""
n = random.randint(3, 5)
for i in range(n):
x = random.randint(0, w.width)
y = random.randint(0, 300)
size = random.randint(10, 30)
l_wing = GLine(x, y, x-size, y-size/2)
r_wing = GLine(... | 51,860 |
def switch(parser, token):
"""
Switch tag. Usage::
{% switch meal %}
{% case "spam" %}...{% endcase %}
{% case "eggs" %}...{% endcase %}
{% endswitch %}
Note that ``{% case %}`` arguments can be variables if you like (as can
switch arguments, buts t... | 51,861 |
def rm_noise(diff):
"""Filter out noise from diff text.
Args:
diff (str): diff text
Returns:
str: cleaned diff text
"""
result = diff
patterns = ["\n", "\u0020+", "་+?"]
for pattern in patterns:
noise = re.search(pattern, diff)
if noise:
result = ... | 51,862 |
def restore_rank_envs():
"""Restore rank envs."""
global _envs
for env in _envs:
os.environ[env] = _envs[env] | 51,863 |
async def auth_relogin(sessionid: str = Form(...),
clients: ClientStorage = Depends(get_clients)) -> str:
"""Relogin by username and password (with clean cookies)
"""
cl = clients.get(sessionid)
result = cl.relogin()
return result | 51,864 |
def taxonomy_data_collector():
"""
Read the accession stored in sqlite, get the taxonomy,
and store the accession-taxonomy relationship data in sqlite.
"""
n = ret_start
rows = ret_max
l = int(rows)
while l >= ret_max:
res = seqid_loader(n, rows)
seq_id_lst = [x[0] for x ... | 51,865 |
def delete_qsession_command(session_id: str, cloud_request_id: str) -> dict:
"""
Delete a queued RTR session command by session ID and cloud request ID
:param session_id:
:param cloud_request_id:
"""
endpoint_url = '/real-time-response/entities/queued-sessions/command/v1'
if he... | 51,866 |
def dict_factory(cursor, row):
""" convert sursor into dict """
result = {}
for idx, col in enumerate(cursor.description):
result[col[0]] = row[idx]
return result | 51,867 |
def variant_with_no_attributes(category):
"""Create a variant having no attributes, the same for the parent product."""
product_type = ProductType.objects.create(
name="Test product type", has_variants=True, is_shipping_required=True
)
product = Product.objects.create(
name="Test product... | 51,868 |
def spec_resid(pars,wave,flux,err,models,spec):
"""
This helper function calculates the residuals between an observed spectrum and a Cannon model spectrum.
Parameters
----------
pars : array
Input parameters [teff, logg, feh, rv].
wave : array
Wavelength array for observed spect... | 51,869 |
def return_mospp(
source_coord: Tuple[float, float], target_coord: Tuple[float, float],
) -> List[Dict[str, str]]:
"""
Find the least polluted path.
secretfile: Path to the database secretfile.
instance_id: Id of the air quality trained model.
source: (source latitude, source longitude) for sour... | 51,870 |
def timestamp_d_b_Y_H_M_S(value):
"""Convert timestamp string to time in seconds since epoch.
Timestamps strings like '18 Jun 2013 12:00:00 GMT' are able to be converted
by this function.
Args:
value: A timestamp string in the format '%d %b %Y %H:%M:%S GMT'.
Returns:
The time in s... | 51,871 |
def config_file_update():
"""
Function to determine if we need to update our yaml configuration file after an upgrade.
"""
log.debug('config_file_update() Started....')
if os.path.isfile(skel_config_file):
log.debug('New config SKEL file located, checking to see if an update is needed:')
... | 51,872 |
def lintlib(quiet=False):
""" Run the python linter on petlib with project specific options (see pylintrc petlib). """
tell("Run pylint on the library")
sh('pylint --rcfile=pylintrc petlib', capture=quiet) | 51,873 |
def cli(ctx, version):
"""
PyPtax Command Line Interface.
PyPtax is a Python library to retrieve information on Ptax rates.
"""
if not ctx.invoked_subcommand and version:
click.secho(pyptax.__version__)
ctx.exit()
elif not ctx.invoked_subcommand:
click.secho(LOGO_CLI, f... | 51,874 |
def constrained_fit(
model_constructor,
pdf_transform=False,
default_rtol=1e-10,
default_atol=1e-10,
default_max_iter=int(1e7),
learning_rate=1e-6,
):
"""
Wraps a series of functions that perform maximum likelihood fitting in the
`two_phase_solver` method found in the `fax` python mo... | 51,875 |
def create_backup_text_file(backup_base_folder):
"""
Creates a file containing the current time into the given folder. This is meant to signify
when the most recent backup has been completed.
:param backup_base_folder: The folder to write the file to.
"""
current_time = datetime.now().strftime("... | 51,876 |
def save_array_to_nifti(affine: Tuple, array: numpy.array, out_path: PathLike) -> None:
"""
Save a numpy array as a nifti image.
Args:
affine (Tuple): The affine of the image.
array (numpy.array): Array of data to save.
out_path (PathLike): Where to write the image. Can write gunzip... | 51,877 |
def _raise_sigint(duration):
"""Raises the standard ^C signal interrupt to test proper termination of the
threads.
Args:
duration (float): how many seconds to wait before raising the signal.
"""
#If the simulated port was running in script mode, it would also have a
#signal interrupt handle... | 51,878 |
def write_file(path, content, signature=''):
"""update a platform's dsc file content.
- create the folder when it does not exist.
- skip write attempt when the contents are identical"""
if isinstance(content, (list, tuple)):
content = '\n'.join(content)
if signature:
content = signa... | 51,879 |
def word2array(ft_names, word):
"""Converts `word` [[(value, feature),...],...] to a NumPy array
Given a word consisting of lists of lists/sets of (value, feature) tuples,
return a NumPy array where each row is a segment and each column is a
feature.
Args:
ft_names (list): list of feature ... | 51,880 |
def random_motif_search(
sequences: List[Sequence],
pattern_length: int,
laplace: bool = True,
) -> Dict[str, Union[List[Sequence], Sequence, int]]:
"""Finds a motif matrix in a randomized search.
Args:
sequences: Collection of sequences that will be searched for patterns.
pattern_l... | 51,881 |
def update_global_metrics():
"""Updates the metrics in GLOBAL_METRICS."""
futures = []
for b in config.get_buckets_async().get_result():
futures.extend([
set_build_status_metric(
CURRENTLY_PENDING, b.name, model.BuildStatus.SCHEDULED),
set_build_status_metric(
CURRENTLY_RUNNING... | 51,882 |
def test_module_without_init():
"""
Test module without __init__.py.
https://github.com/ipython/ipython/issues/11226
"""
fake_module_name = "foo"
with TemporaryDirectory() as tmpdir:
sys.path.insert(0, tmpdir)
try:
os.makedirs(os.path.join(tmpdir, fake_module_nam... | 51,883 |
def get_tweet_sentiment(tweets):
"""
Uses the VADER SentimentIntensityAnalyzer from NLTK to classify tweet sentiment polarity.
Takes in input a list of tweets (text-only, not JSON).
Checks which party a tweet refers to and averages the score for all tweets for each party.
Returns a dictionary o... | 51,884 |
def find_final_status_files(path):
"""Find all files named `final_status.json` in qcg-pilotjob auxiliary directories in given path.
First we look for auxilary directories, and then in those dirs we look for `final_status.json` files.
Args:
path (str): path to directory where to look for report file... | 51,885 |
def external(field):
"""
Mark a field as external.
"""
field._external = True
return field | 51,886 |
def from_file(
file: Union[IO[str], str],
*,
app: Any = None,
base_url: Optional[str] = None,
method: Optional[Filter] = None,
endpoint: Optional[Filter] = None,
tag: Optional[Filter] = None,
operation_id: Optional[Filter] = None,
skip_deprecated_operations: bool = False,
validat... | 51,887 |
def rand_score_choice():
"""
返回一个看似合理分布的成绩
:return: int
"""
score_choice = [randint(50, 80), randint(40, 60), randint(60, 80), randint(60, 80), randint(70, 90), randint(80, 100)]
return choice(score_choice) | 51,888 |
def getExactFreePlaceIndexForCoordinate(freePlaceMap, x, y):
"""
Returns the Exact Value for a given Coordinate on the FreePlaceMap
:param freePlaceMap: The generated FreePlaceMap
:param x: The X Coordinate on the FreePlaceMap
:param y: The Y Coordinate on the FreePlaceMap
:return: The Indexvalu... | 51,889 |
async def get_bc_history(start_time: Optional[str] = None, end_time: Optional[str] = None, isp: Optional[str] = ''):
"""
## **param**:
start_time: 开始时间(可选参数) str 默认 当前时间前一月
end_time: 结束时间(可选参数) str 默认 当前时间
isp: 运营商(可选参数) str 默认 '',... | 51,890 |
def copy_images(apps, schema_editor):
""" Copy existing wagtail image records into new image model"""
FieldImage = apps.get_model('field_wagtail', 'FieldImage')
Image = apps.get_model('wagtailimages', 'Image')
django_content_type = apps.get_model('contenttypes', 'contenttype')
tagged_item_model = a... | 51,891 |
def get_member_class(resource):
"""
Returns the registered member class for the given resource.
:param resource: registered resource
:type resource: class implementing or instance providing or subclass of
a registered resource interface.
"""
reg = get_current_registry()
if IInterfac... | 51,892 |
def test_randomize_corrmat_dist():
"""Test that the distribution looks right."""
a = rs.randn(3, 20)
for n_i in [5, 10]:
p_mat, dist = stat.randomize_corrmat(a, n_iter=n_i, return_dist=True)
assert_equal(n_i, dist.shape[-1])
p_mat, dist = stat.randomize_corrmat(a, n_iter=10000, return_d... | 51,893 |
def split_on_text(row):
"""Spliting original text into million character blocks for Spacy"""
val = round(row['original_text_length'] / 1000000)
final_texts = []
count = 1000000
counter = 0
for i in range(0, val):
if (count + 1000000) > row['original_text_length']:
final_texts... | 51,894 |
def valid_date(s):
""" validate passed date and throw exception if it is not valid """
try:
return datetime.datetime.strptime(s, "%Y-%m-%d")
except ValueError:
msg = "Not a valid date: '{0}'.".format(s)
raise argparse.ArgumentTypeError(msg) | 51,895 |
def make_child_node(parent_node, action, state):
""" Construct an child search node """
return SearchNode(state, parent_node, action) | 51,896 |
def get_number(number):
"""
Repeats back a number to you
---
operationId: getPetsById
parameters:
- name: number
in: path
type: string
description: the number
responses:
200:
description: Hello number!
"""
return "Hello {}!".format(numbe... | 51,897 |
def get_user_by_id(uid, session=None):
"""Get user by id."""
with session_scope() as session:
return session.query(User)\
.filter(User.id == uid)\
.first().to_json() | 51,898 |
def main():
"""main entry point for module execution"""
argument_spec = dict(
gather_subset=dict(
default=["!config"],
type="list",
elements="str",
choices=[
"all",
"default",
"hardware",
"int... | 51,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.