content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def person(request):
"""
Display information on the specified borrower (person)
"""
title = "Find a person"
if 'person_id' in request.GET:
person_id = request.GET['person_id']
try:
person = Person.objects.get(id_number=person_id)
title = unicode(person)
... | 5,329,700 |
def remove_routes_from_app(app_name: str, route_host: str,
configuration: Configuration, secrets: Secrets,
org_name: str = None, space_name: str = None):
"""
Remove routes from a given application.
See
https://apidocs.cloudfoundry.org/280/apps/remov... | 5,329,701 |
def _follow_word_from_node(node, word):
"""Follows the link with given word label from given node.
If there is a link from ``node`` with the label ``word``, returns the end
node and the log probabilities and transition IDs of the link. If there are
null links in between, returns the sum of the log prob... | 5,329,702 |
def get_cbday():
"""
クラバト日時確認用
bot本体では未使用
return
----
```
None
```
"""
cb_status=fetch_status()
#cb_status = {
# 'cb_start': datetime.strptime('2020/02/23 5:00:00',
# '%Y/%m/%d %H:%M:%S'),
# 'cb_end': datetime.strptime('2020... | 5,329,703 |
def normalize_code(code):
"""Normalize object codes to avoid duplicates."""
return slugify(code, allow_unicode=False).upper() if code else None | 5,329,704 |
def convert_raw_data_to_hdf5(trainIdx, validateIdx, fileIdx,
filename, dataDir, json_data):
"""
Go through the Decathlon dataset.json file.
We've already split into training and validation subsets.
Read in Nifti format files. Crop images and masks.
Save to HDF5 format.
... | 5,329,705 |
def get_weights_for_all(misfit_windows, stations, snr_threshold, cc_threshold, deltat_threshold, calculate_basic, print_info=True):
"""
get_weights_for_all: calculate weights.
"""
weights_for_all = {}
# * firstly we update the weight of snr,cc,deltat
for net_sta in misfit_windows:
weigh... | 5,329,706 |
def tree_feature_importance(tree_model, X_train):
"""
Takes in a tree model and a df of training data and prints out
a ranking of the most important features and a bar graph of the values
Parameters
----------
tree_model: the trained model instance. Must have feature_importances_ and estima... | 5,329,707 |
def chhop_microseconds(delta: timedelta) -> timedelta:
"""
chop microseconds from timedelta object.
:param delta:
:return:
"""
return delta - timedelta(microseconds=delta.microseconds) | 5,329,708 |
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_values[value] = count
new_value = count
... | 5,329,709 |
def get_user_list():
"""
return user list if the given
authenticated user has admin permission
:return:
"""
if requires_perm() is True:
return jsonify({'user_list': USER_LIST,
'successful': True}), 200
return jsonify({'message': 'You are not '
... | 5,329,710 |
def rm_words(user_input, stop_words):
"""Sanitize using intersection and list.remove()"""
# Downsides:
# - Looping over list while removing from it?
# http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python
stop_words = set(stop_words)
for sw in stop_... | 5,329,711 |
def getValueForCoordinate(inputFile, lon, lat, noDataAsNone):
"""
Reads the pixel value of a GeoTIFF for a geographic coordinate
:param inputFile: full path to input GeoTIFF file
:type inputFile: str
:param lon: longitude
:type lon: float
:param lat: latitude
:type lat: float
:param... | 5,329,712 |
def convert_xrandr_to_index(xrandr_val: float):
"""
:param xrandr_val: usually comes from the
config value directly, as a string (it's
just the nature of directly retrieving
information from a .ini file)
:return: an index representation
of the current brightness level, useful
for switch... | 5,329,713 |
def test_get_secret_value_string_metadata_only():
"""
Tests get secret value and the secret has string value. metadtaonly is set
"""
trace_factory.metadata_only = True
client = boto3.client('secretsmanager', region_name='us-west-1')
client.create_secret(Name=TEST_SECRET_NAME, SecretString=TEST_S... | 5,329,714 |
def get_message(name, value):
"""Provides the message for a standard Python exception"""
if hasattr(value, "msg"):
return f"{name}: {value.msg}\n"
return f"{name}: {value}\n" | 5,329,715 |
def calculate_page_info(offset, total_students):
"""
Takes care of sanitizing the offset of current page also calculates offsets for next and previous page
and information like total number of pages and current page number.
:param offset: offset for database query
:return: tuple consist of page num... | 5,329,716 |
def find_files(topdirs, py = False):
"""Lists all python files under any topdir from the topdirs lists.
Returns an appropriate list for data_files,
with source and destination directories the same"""
ret = []
for topdir in topdirs:
for r, _ds, fs in os.walk(topdir):
re... | 5,329,717 |
def get_api_map(level,SYSTEM):
"""Search API from rules, if match the pattern then we said it is API."""
level_config = {
#最高權限(但不包含APIDOC)
"LEVEL1":r'/api/(?!APIDOC)',
#只能看到通用系統api
"LEVEL2":r'/api/<SYSTEM>',
#只看得到APIDOC
"LEVEL3":r'/api/APIDOC'
}
# regexSt... | 5,329,718 |
def _create_argument_parser():
"""Creates the command line arg parser."""
parser = argparse.ArgumentParser(description='create a zip file',
fromfile_prefix_chars='@')
parser.add_argument('-o', '--output', type=str,
help='The output zip file path.')
parser... | 5,329,719 |
def download_office(load=True): # pragma: no cover
"""Download office dataset.
Parameters
----------
load : bool, optional
Load the dataset after downloading it when ``True``. Set this
to ``False`` and only the filename will be returned.
Returns
-------
pyvista.Structured... | 5,329,720 |
def test_duplicated_topics(host):
"""
Check if can remove topics options
"""
# Given
duplicated_topic_name = get_topic_name()
def get_topic_config():
topic_configuration = topic_defaut_configuration.copy()
topic_configuration.update({
'name': duplicated_topic_name,
... | 5,329,721 |
def hazel_custom_package_hackage(
package_name,
version,
sha256 = None,
build_file = None,
build_file_content = None):
"""Generate a repo for a Haskell package fetched from Hackage.
Args:
package_name: string, package name.
version: string, package version.
... | 5,329,722 |
def register(request):
"""
注册账号界面
"""
message = ""
if request.session.get('is_login', None):
return redirect('/account/')
if request.method == 'POST':
username = request.POST.get('username')
email = request.POST.get('email')
password1 = request.POST.get('password... | 5,329,723 |
def asset_type_check(asset):
"""
Verify asset 'type' key abides by naming convention standards.
Naming Convention Rules:
- Asset Types are broken into three categories: <vendor>_<service>_<resource>
- Example: aws_s3_bucket, gcp_iam_user, github_repository (service ommitted as there isn't any)
... | 5,329,724 |
def test_service_span(encoding):
"""Tests that zipkin_attrs can be passed in"""
mock_transport_handler, mock_logs = mock_logger()
zipkin_attrs = ZipkinAttrs(
trace_id="0", span_id="1", parent_span_id="2", flags="0", is_sampled=True,
)
with zipkin.zipkin_span(
service_name="test_servi... | 5,329,725 |
def enter(ctx, work_dir) :
"""
Enters a running pde container.
"""
pCmd = "podman exec -it"
if work_dir is not None :
logging.info("Using the [{}] working directory".format(work_dir))
pCmd = pCmd + " --workdir {}".format(work_dir)
pCmd = pCmd + " {} {}".format(
ctx.obj['pdeName'], ctx.obj['pde']... | 5,329,726 |
def cosh(x):
"""Evaluates the hyperbolic cos of an interval"""
np = import_module('numpy')
if isinstance(x, (int, float)):
return interval(np.cosh(x), np.cosh(x))
elif isinstance(x, interval):
#both signs
if x.start < 0 and x.end > 0:
end = max(np.cosh(x.start... | 5,329,727 |
def tree_intersection(tree_one, tree_two):
"""Checks for duplicate values between two trees and returns those values as a set."""
first_values = []
second_values = []
table = HashTable()
dupes = set([])
tree_one.pre_order(first_values.append)
tree_two.pre_order(second_values.append)
fo... | 5,329,728 |
def saveDataset(X_train, Y_train, X_test, Y_test, path):
"""
A function which saves numpy arrays of a dataset to binary files.
"""
np.save(os.path.join(path, "X_train.npy"), X_train)
np.save(os.path.join(path, "Y_train.npy"), Y_train)
np.save(os.path.join(path, "X_test.npy"), X_test)
np.save... | 5,329,729 |
def new():
"""Deliver new-question interface."""
return render_template('questionNew.html', question_id='') | 5,329,730 |
def merge_dict_recursive(base, other):
"""Merges the *other* dict into the *base* dict. If any value in other is itself a dict and the base also has a dict for the same key, merge these sub-dicts (and so on, recursively).
>>> base = {'a': 1, 'b': {'c': 3}}
>>> other = {'x': 4, 'b': {'y': 5}}
>>> want =... | 5,329,731 |
def two_points_line(feature):
"""Convert a Polyline to a Line composed of only two points."""
features = []
coords = feature['geometry']['coordinates']
for i in range(0, len(coords) - 1):
segment_coords = [coords[i], coords[i+1]]
geom = geojson.LineString(segment_coords)
features... | 5,329,732 |
def main():
"""
Main runs the astroid lookup program
"""
astroid_map = []
with open(sys.argv[1]) as map_file:
for line in map_file:
astroid_map.append([x for x in line.strip()])
marked = mark_astroids(astroid_map)
best = {"coordinates": (0, 0), "sees": 0}
# Check ... | 5,329,733 |
def transform_world_to_camera(poses_set, cams, ncams=4):
"""
Project 3d poses from world coordinate to camera coordinate system
Args
poses_set: dictionary with 3d poses
cams: dictionary with cameras
ncams: number of cameras per subject
Return:
t3d_camera: dictionary with 3d poses... | 5,329,734 |
def generate_static():
"""
Generate CSS and JavaScript files
"""
util.copytree('static', os.path.join(_deploy_dir, 'static')) | 5,329,735 |
def cwebp(input_image: str, output_image: str, option: str,
logging: str = "-v", bin_path: str = None) -> Dict:
"""
now convert image to .webp format
input_image: input image(.jpeg, .pnp ....)
output_image: output image .webp
option: options and quality,it should be given between 0 to 100... | 5,329,736 |
def assert_exists(exists, Model, **kwargs):
"""Check if given object exists or doesn't exist"""
if Model.objects.filter(**kwargs).exists() != exists:
raise AssertionError("Object with arguments {} {}!".format(
kwargs,
"doesn't exist" if exists else "exists"
)) | 5,329,737 |
def dbRegister(app):
"""
注册数据库
"""
env = getEnv()
app.config['MONGODB_SETTINGS'] = {
'db': configObj[env].DBNAME,
'host': configObj[env].DBHOST,
'port': configObj[env].DBPORT
}
db.init_app(app) | 5,329,738 |
def div66():
"""
Returns the divider OOOOOOOOOOOO
:return: divider66
"""
return divider66 | 5,329,739 |
def extract_square_from_file(image_number=1):
"""Given a number of the image file return a cropped sudoku."""
image_string = '/home/james/Documents/projects/sudoku/img/'
image_string += str(image_number) + '.jpg'
binary = read_binary(image_string)
threshold = get_threshold(binary)
square = get_... | 5,329,740 |
def CSV2GRID(strPathInCSV, strPathOutASC, intCol):
""" Function CSV2GRID
args:
Command Syntax: CSV2GRID [switches] inputfile column outputfile
"""
lstCMD = [strPathFuInstall + os.sep + "CSV2GRID",
strPathInCSV,
str(intCol),
strPathOutASC]
... | 5,329,741 |
def get_object_output(bucket: Optional[pulumi.Input[str]] = None,
key: Optional[pulumi.Input[str]] = None,
range: Optional[pulumi.Input[Optional[str]]] = None,
tags: Optional[pulumi.Input[Optional[Mapping[str, str]]]] = None,
versio... | 5,329,742 |
def sequence_extractor(graph, path):
"""
returns the sequence of the path
:param graph: a graph object
:param path: a list of nodes ordered according to the path
:return: sequence of the path
"""
# check if path exists
if len(path) == 1:
return graph.nodes[path[0]].seq
eli... | 5,329,743 |
def plot_matplotlib(
tree: CassiopeiaTree,
depth_key: Optional[str] = None,
meta_data: Optional[List[str]] = None,
allele_table: Optional[pd.DataFrame] = None,
indel_colors: Optional[pd.DataFrame] = None,
indel_priors: Optional[pd.DataFrame] = None,
orient: Union[Literal["up", "down", "left"... | 5,329,744 |
def print_order(order: Order, user_id: int = 0):
"""
订单打印
:param order:
:param user_id:
:return:
"""
shop_id = order.shop.id
shop = get_shop_by_shop_id(shop_id)
receipt_config = get_receipt_by_shop_id(shop_id)
printer = ylyPrinter()
template = jinja2.Template(ORDER_TPL_58)
... | 5,329,745 |
def get_IoU_from_matches(match_pred2gt, matched_classes, ovelaps):
"""
if given an image, claculate the IoU of the segments in the image
:param match_pred2gt: maps index of predicted segment to index of ground truth segment
:param matched_classes: maps index of predicted segment to class number
:par... | 5,329,746 |
def check_audit_unchanged(results, platform):
"""Crash out if the audit in the result doesn't match the one in the
platform"""
from krun.audit import Audit
if Audit(platform.audit) != results.audit:
error_msg = (
"You have asked Krun to resume an interrupted benchmark. "
... | 5,329,747 |
def id_queue(obs_list, prediction_url='http://plants.deep.ifca.es/api', shuffle=False):
"""
Returns generator of identifications via buffer.
Therefore we perform the identification query for the nxt observation
while the user is still observing the current information.
"""
print "Generating the ... | 5,329,748 |
def periodogram(x, nfft=None, fs=1):
"""Compute the periodogram of the given signal, with the given fft size.
Parameters
----------
x : array-like
input signal
nfft : int
size of the fft to compute the periodogram. If None (default), the
length of the signal is used. if nfft... | 5,329,749 |
def handle_429(e):
"""Renders full error page for too many site queries"""
html = render.html("429")
client_addr = get_ipaddr()
count_ratelimit.labels(e, client_addr).inc()
logger.error(f"Error: {e}, Source: {client_addr}")
return html, 429 | 5,329,750 |
def url_path_join(*items):
"""
Make it easier to build url path by joining every arguments with a '/'
character.
Args:
items (list): Path elements
"""
return "/".join([item.lstrip("/").rstrip("/") for item in items]) | 5,329,751 |
def f_match (pattern, string, flags = None):
""" Match function
Args:
pattern (string): regexp (pattern|/pattern/flags)
string (string): tested string
flags (int): regexp flage
Return:
boolean
"""
if build_regexp(pattern, flags).search(to_strin... | 5,329,752 |
def validate_epoch(val_loader, model, criterion, epoch, args):
"""Perform validation on the validation set"""
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
batch_time = AverageMeter()
data_time = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
b... | 5,329,753 |
def test_debugging_when_source_code_is_missing():
"""Test debugging code that its source code is not available.
Note:
In this kind of code we cannot stop at an error, so we fall-back to
simply running this code without interference.
"""
exec("def function(): 1 / 0", locals(), globals())... | 5,329,754 |
def printBoardStatistic(boardname, conn):
"""
Print Statistic for current board.
"""
c = conn.cursor()
for i in c.execute('SELECT * FROM `boards` WHERE `name` IS ?', (boardname,)):
break
if i == None:
raise Exception('SQL Query Failed! in printBoardStatistic()')
print('name: ... | 5,329,755 |
def utf8_german_fix( uglystring ):
"""
If your string contains ugly characters (like ü, ö, ä or ß) in your source file, run this string through here.
This adds the German "Umlaute" to your string, making (ÄÖÜäöü߀) compatible for processing.
\tprint( utf8_german_fix("ü߀") ) == ü߀
"""
... | 5,329,756 |
def subtends(a1, b1, a2, b2, units='radians'):
""" Calculate the angle subtended by 2 positions on a sphere """
if units.lower() == 'degrees':
a1 = radians(a1)
b1 = radians(b1)
a2 = radians(a2)
b2 = radians(b2)
x1 = cos(a1) * cos(b1)
y1 = sin(a1) * cos(b1)
z1 = sin(... | 5,329,757 |
def get_pcgr_bin():
"""Return abs path to e.g. conda/env/pcgr/bin
"""
return os.path.dirname(os.path.realpath(sys.executable)) | 5,329,758 |
def test_response_data():
"""Ensure response with expected data is returned."""
detail = 'Dummy detail'
code = 'dummy_code'
exception = rest_exceptions.APIException(detail=detail, code=code)
response = handlers.handle_rest_framework_api_exception(exception, {})
assert code in str(response.data... | 5,329,759 |
async def test_update(opp, aioclient_mock):
"""Tests switch refreshes status periodically."""
now = dt_util.utcnow()
future = now + timedelta(minutes=10)
aioclient_mock.get(
"http://1.1.1.1/status.xml",
text="<response><relay0>0</relay0><relay1>0</relay1></response>",
)
MockCon... | 5,329,760 |
def get_args(obj):
"""Get a list of argument names for a callable."""
if inspect.isfunction(obj):
return inspect.getargspec(obj).args
elif inspect.ismethod(obj):
return inspect.getargspec(obj).args[1:]
elif inspect.isclass(obj):
return inspect.getargspec(obj.__init__).args[1:]
... | 5,329,761 |
def reset_cli(api_client, pipeline_id):
"""
Resets a delta pipeline by truncating tables and creating new checkpoint folders so data is
reprocessed from scratch.
Usage:
databricks pipelines reset --pipeline-id 1234
"""
_validate_pipeline_id(pipeline_id)
PipelinesApi(api_client).reset(p... | 5,329,762 |
def write_feedback(section, messages, folder=os.getcwd()):
"""Append messages to the status file."""
filepath = os.path.join(folder, STATUS_FILE)
with open(filepath) as stream:
feedback = json.load(stream)
if section not in feedback:
feedback[section] = []
for message in messages... | 5,329,763 |
def get_assumed_role_creds(service_name, assume_role_policy):
"""
Returns a new assume role object with AccessID, SecretKey and SessionToken
:param service_name:
:param assume_role_policy:
"""
sts_client = boto3.client("sts", region_name=os.environ["AWS_REGION"])
assumed_role = sts_... | 5,329,764 |
def name_value(obj):
"""
Convert (key, value) pairs to HAR format.
"""
return [{"name": k, "value": v} for k, v in obj.items()] | 5,329,765 |
def get_ids(id_type):
"""Get unique article identifiers from the dataset.
Parameters
----------
id_type : str
Dataframe column name, e.g. 'pubmed_id', 'pmcid', 'doi'.
Returns
-------
list of str
List of unique identifiers in the dataset, e.g. all unique PMCIDs.
"""
... | 5,329,766 |
def ccw_wkt_from_shapefile(shapefile, out_txt):
"""
Creates wkt with coordinates oriented counter clockwise for a given
shapefile. Shapefiles are oriented clockwise, which is incompatible with
spatial queries in many database management systems. Use this to generate
wkt that you can copy and paste ... | 5,329,767 |
def get_items_info(request):
"""Get a collection of person objects"""
result = request.dbsession.query(Item).all()
results=[]
for c in result:
results.append({'id':c.id, 'markup':c.markup})
return results | 5,329,768 |
def test_UniformTimeSeries_repr():
"""
>>> t=ts.UniformTime(length=3,sampling_rate=3)
>>> tseries1 = ts.UniformTimeSeries(data=[3,5,8],time=t)
>>> t.sampling_rate
3.0 Hz
>>> tseries1.sampling_rate
3.0 Hz
>>> tseries1 = ts.UniformTimeSeries(data=[3,5,8],sampling_rate=3)
>>> tseries1.... | 5,329,769 |
def _test(value, *args, **keywargs):
"""
A function that exists for test purposes.
>>> checks = [
... '3, 6, min=1, max=3, test=list(a, b, c)',
... '3',
... '3, 6',
... '3,',
... 'min=1, test="a b c"',
... 'min=5, test="a, b, c"',
... 'min=1, max=... | 5,329,770 |
def plot_chromaticity_diagram_CIE1976UCS(
cmfs: Union[
MultiSpectralDistributions,
str,
Sequence[Union[MultiSpectralDistributions, str]],
] = "CIE 1931 2 Degree Standard Observer",
show_diagram_colours: Boolean = True,
show_spectral_locus: Boolean = True,
**kwargs: Any,
) -> ... | 5,329,771 |
def generateFilter(targetType, left = False):
"""Generate filter function for loaded plugins"""
def filter(plugins):
for pi in plugins:
if left:
if not pi.isThisType(targetType):
plugins.remove(pi)
logger.info("Plugin: {} is filtered out by predefined filter"\
.format(pi.namePlugin()))
... | 5,329,772 |
def test__prod__homolytic_scission():
""" test graph.reac.prod_homolytic_scission
"""
gra = automol.geom.graph(
automol.inchi.geometry(
automol.smiles.inchi('CCCC')))
prod_gras = graph.reac.prod_homolytic_scission(gra)
print('\n homolyt scission')
for gra in prod_gras:
... | 5,329,773 |
def test_search_no_results(session, search_type, json_data):
"""Assert that a search query with no results returns the expected result."""
query = SearchRequest.create_from_json(json_data, None)
query.search()
assert query.id
assert not query.search_response
assert query.returned_results_size =... | 5,329,774 |
def test_compare_full_flash_hex(
mock_open_temp_html, mock_gen_diff_html, mock_read_flash_hex
):
"""Check that file contents."""
file_hex_path = os.path.join("path", "to", "file.hex")
file_hex_content = "This is the hex file content"
flash_hex_content = "This is the flash hex content"
mock_read_... | 5,329,775 |
def load_vel_map(component="u"):
"""
Loads all mean streamwise velocity profiles. Returns a `DataFrame` with
`z_H` as the index and `y_R` as columns.
"""
# Define columns in set raw data file
columns = dict(u=1, v=2, w=3)
sets_dir = os.path.join("postProcessing", "sets")
latest_time = ma... | 5,329,776 |
def iterate_packages(rospack, mode):
"""
Iterator for packages that contain messages/services
:param mode: .msg or .srv, ``str``
"""
if mode == MODE_MSG:
subdir = 'msg'
elif mode == MODE_SRV:
subdir = 'srv'
else:
raise ValueError('Unknown mode for iterate_packages: %s... | 5,329,777 |
def check_int(es_url, es_index, hash_id):
"""Query for interferograms with specified input hash ID."""
query = {
"query":{
"bool":{
"must":[
{"term":{"metadata.input_hash_id":hash_id}},
]
}
}
}
if es_url.endswi... | 5,329,778 |
def format_sample_case(s: str) -> str:
"""format_sample_case convert a string s to a good form as a sample case.
A good form means that, it use LR instead of CRLF, it has the trailing newline, and it has no superfluous whitespaces.
"""
if not s.strip():
return ''
lines = s.strip().splitlin... | 5,329,779 |
def replace_floats_with_decimals(obj: Any, round_digits: int = 9) -> Any:
"""Convert all instances in `obj` of `float` to `Decimal`.
Args:
obj: Input object.
round_digits: Rounding precision of `Decimal` values.
Returns:
Input `obj` with all `float` types replaced by `Decimal`s rou... | 5,329,780 |
def _calc_range_mixed_data_columns(data, observation, dtypes):
""" Return range for each numeric column, 0 for categorical variables """
_, cols = data.shape
result = np.zeros(cols)
for col in range(cols):
if np.issubdtype(dtypes[col], np.number):
result[col] = max(max(data[:, col])... | 5,329,781 |
def get_from_hdfs(file_hdfs):
"""
compatible to HDFS path or local path
"""
if file_hdfs.startswith('hdfs'):
file_local = os.path.split(file_hdfs)[-1]
if os.path.exists(file_local):
print(f"rm existing {file_local}")
os.system(f"rm {file_local}")
hcopy(f... | 5,329,782 |
def search(request):
"""
Display search form/results for events (using distance-based search).
Template: events/search.html
Context:
form - ``anthill.events.forms.SearchForm``
event_list - events in the near future
searched - True/Fal... | 5,329,783 |
def logout() -> Response:
"""Logout route. Logs the current user out.
:return: A redirect to the landing page.
"""
name: str = current_user.name
logout_user()
flash(f'User "{name}" logged out.', 'info')
url: str = url_for('root')
output: Response = redirect(url)
return output | 5,329,784 |
def load_room(name):
"""
There is a potential security problem here.
Who gets to set name? Can that expose a variable?
"""
return globals().get(name) | 5,329,785 |
def call_ipt_func(ipt_id: str, function_name: str, source, **kwargs):
"""Processes an image/wrapper with an IPT using an function like syntax
:param ipt_id:
:param function_name:
:param source:
:param kwargs:
:return:
"""
cls_ = get_ipt_class(ipt_id)
if cls_ is not None:
... | 5,329,786 |
def is_running(service):
"""
Checks if service is running using sysdmanager library.
:param service: Service to be checked.
:return: Information if service is running or not.
"""
manager = get_manager()
if manager.is_active(service + ".service"):
return 1
return 0 | 5,329,787 |
def pipeline_model(model, pipeline_splits):
"""
Split the model into stages.
"""
for name, modules in model.named_modules():
name = name.replace('.', '/')
if name in pipeline_splits:
logging.info('--------')
logging.info(name)
for split_idx, split in enumerate(pi... | 5,329,788 |
async def setstatus(ctx, status: Option(str, "Set status", choices=["online", "idle", "dnd"])):
"""Change Dalti's status"""
try:
if status == "online":
await Dalti.change_presence(status=discord.Status.online)
Embed = discord.Embed(description=f"<:daltiSuccess:923699355779731476>... | 5,329,789 |
def smoothen(data, kernel):
"""Convolve data with odd-size kernel, with boundary handling."""
n, = kernel.shape
assert n % 2 == 1
m = (n-1) // 2
# pad input data
k = m//2 + 1
data_padded = np.concatenate([
np.full(m, data[:k].mean()),
data,
np.full(m, data[-k:].mean(... | 5,329,790 |
def find_node_name(node_id, g):
"""Go through the attributes and find the node with the given name"""
return g.node[node_id]["label"] | 5,329,791 |
def aes_cbc_decrypt(data, key, iv):
"""
Decrypt with aes in CBC mode
@param {int[]} data cipher
@param {int[]} key 16/24/32-Byte cipher key
@param {int[]} iv 16-Byte IV
@returns {int[]} decrypted data
"""
expanded_key = key_expansion(key)
block_coun... | 5,329,792 |
def score_concepts(merged_graph: AMR, counts: tuple, concept_alignments: Dict[str, str]) -> Counter:
"""
Calculate TF-IDF counts for each node(concept) in `merged_graph` according to their aligned words.
Parameters:
merged_graph(AMR): Graph which contains the concept to be scored.
counts(tu... | 5,329,793 |
def test_apply_bda_pre_fs_int_time_bad_quantity_error():
"""Test error for using an incompatible Quantity for pre_fs_int_time."""
# define parameters
uvd = UVData()
max_decorr = 0.1
pre_fs_int_time = 0.1 * units.m
corr_fov_angle = Angle(20.0, units.degree)
max_time = 30 * units.s
corr_in... | 5,329,794 |
def test_newline_002(settings, sass_parser):
"""
Ensure nothing after import newline is wrongly captured
"""
content = (
"""// Foo\n"""
"""@import candidate1\n"""
"""@import candidate2\n"""
""".foo{ color: red }"""
)
result = sass_parser.parse(content)
assert ... | 5,329,795 |
def timestamp_to_double(sparkdf):
"""
Utility function to cast columns of type 'timestamp' to type 'double.'
"""
for dtype in sparkdf.dtypes:
if dtype[1] == 'timestamp':
sparkdf = sparkdf.withColumn(dtype[0], col(dtype[0]).cast(DoubleType()))
return sparkdf | 5,329,796 |
def get_signal(args):
"""function to get signal from a track around some sites
"""
if not args.out:
args.out = '.'.join(os.path.basename(args.bed).split('.')[0:-1])
chunks = ChunkList.read(args.bed, strand_col = args.strand)
params = _signalParams(args.bg, args.sizes, args.up, args.down,arg... | 5,329,797 |
def get_entrez_id_from_organism_full_name_batch(organism_full_names: List[str]) -> List[str]:
"""Retrieves the Entrez numeric ID of the given organisms.
This numeric identifier is neccessary for BLAST and NCBI TAXONOMY
searches.
This function uses Biopython functions. Returns BLAST-compatible ID as
... | 5,329,798 |
def test_wrong_msgcat(po_file):
"""Test if msgcat is not available"""
environ_saved = os.environ["PATH"]
os.environ["PATH"] = ""
with pytest.raises(SystemExit) as sysexit:
powrap.check_style([po_file])
os.environ["PATH"] = environ_saved
assert sysexit.type == SystemExit
assert sysexi... | 5,329,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.