content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def depart_edit(request, nid):
""" 修改部门 """
if request.method == "GET":
row_object = models.Department.objects.filter(id=nid).first()
return render(request, 'depart_edit.html', {"row_object": row_object})
title = request.POST.get("title")
models.Department.objects.filter(id=nid).update(t... | 5,303,200 |
def get_defectdojo_date(date):
"""
Returns date as required by DefectDojo.
:param date:
:return: yyyy--mm-dd
"""
regex = r"([0-9]{2})\/([0-9]{2})\/([0-9]{4})"
matches = re.finditer(regex, date, re.MULTILINE)
match = next(enumerate(matches))
date = match[1].groups()
day = date... | 5,303,201 |
def run_pto(number, env, ref=False):
"""Lead titanate 6 atoms SZP/diagonalisation PBE """
name = "PTO"
description = "Lead titanate 5 atoms SZP diagonalisation"
grid_cutoff = 80.0
xc = "PBE"
kpts = [9,9,9]
basis = "small"
basis = {'Pb' : {'file' : 'Pb_SZP_v323_PBE.ion'},
'Ti' : {'file' : 'Ti... | 5,303,202 |
def get_container_colors(containers):
"""
Sets an ANSII color cmd to use for each container based on it's position in the list.
Unit tested: test_get_container_colors
:param containers: The containers found from docker ps.
:type containers: list
:returns: Added color cmd to each container.
... | 5,303,203 |
def temporary_search_template(es, template_file, template_id_in_file, size=None, with_source=False):
"""A context manager that manages a temporary search template."""
def random_string(length=10):
"""Generate a simple random string to use as a temporary template ID"""
return ''.join(random.choi... | 5,303,204 |
def convert2_ratio_perim_area(width, length):
"""Convert width and length data into ratio of perimeter to area."""
perimeter = (
np.pi
/ 2
* (3 * (width + length) - np.sqrt((3 * width + length) * (3 * length + width)))
)
area = np.pi / 4 * width * length
return perimeter / a... | 5,303,205 |
def connect():
"""Connect to the PostgreSQL database score_it. Returns a database connection
and a cursor object and raises eceptions if the connection cannot be made.
"""
try:
conn = psycopg2.connect("dbname = score_it")
except psycopg2.DatabaseError:
print "The program could not c... | 5,303,206 |
def gift_card_verify_code(self, referenceNo: str, **kwargs):
"""Verify a Binance Code (USER_DATA)
GET /sapi/v1/giftcard/verify
This API is for verifying whether the Binance Code is valid or not by entering Binance Code or reference number.
Please note that if you enter the wrong binance code 5 times ... | 5,303,207 |
def prettify(input_string: str) -> str:
"""
Reformat a string by applying the following basic grammar and formatting rules:
- String cannot start or end with spaces
- The first letter in the string and the ones after a dot, an exclamation or a question mark must be uppercase
- String cannot have mu... | 5,303,208 |
def calculate_m_value(methylated_noob, unmethylated_noob, offset=0):
""" the log(base 2) (1+meth / 1+unmeth) intensities (with a min clip intensity of 1 to avoid divide-by-zero-errors, like sesame)"""
methylated = np.clip(methylated_noob, 1, None) + offset
unmethylated = np.clip(unmethylated_noob, 1, None) ... | 5,303,209 |
def makeresources(repos,
resourcedir="data/rsrc",
combine=False,
cssfiles=[],
jsfiles=[],
imgfiles=[],
staticsite=False,
legacyapi=False,
sitename="MySite",
s... | 5,303,210 |
def I_inj_t(t):
"""
This function returns the external current to be injected into the network at any time step from the current_input matrix.
Parameters:
-----------
t: float
The time at which the current injection is being performed.
"""
# Turn indices to integer and extract from ... | 5,303,211 |
def dumps(obj, **kwargs):
"""
convert configuration object to a json string
"""
obj = _encode(obj)
return json.dumps(obj, **kwargs) | 5,303,212 |
def lambda_handler(event, context):
"""
PayPay API(reserve)の通信結果を返す
Parameters
----------
event : dict
POST時に渡されたパラメータ
context : dict
コンテキスト内容
Returns
-------
response : dict
PayPay APIの通信結果
"""
logger.info(event)
if event['body'] is None:
... | 5,303,213 |
def _get_tmp_dir(filepath):
"""
copy .jar to a temporary directory
"""
tmp_dir = tempfile.mkdtemp()
if os.name == 'posix':
os.chmod(tmp_dir, 0o755)
LOG.info("Copying %s to a temporary directory", filepath)
shutil.copyfile(filepath, os.path.join(tmp_dir, "tmp.jar"))
return os.... | 5,303,214 |
def get_soup(url: str) -> BeautifulSoup:
"""
Get BeautifulSoup HTML document by url.
Args:
url (str): Request URL
Returns:
BeautifulSoup: HTML document
"""
logger.info(f"Fetching {url}")
request = requests.get(url)
return BeautifulSoup(request.text, "html.parser") | 5,303,215 |
def draw_graph2(out_file_name):
"""
https://github.com/pgv/pygraphviz/blob/master/examples/subgraph.py
"""
# init empty graph
a = pgv.AGraph(directed=True)
a.node_attr['fontname'] = 'helvetica'
a.node_attr['shape'] = 'box'
a.add_node("aardvark")
items0 = ["coyote", "dingo", "dog",... | 5,303,216 |
def distance(A, B, metric='riemann'):
"""Return the distance between
two covariance matrices A and B according to the metric :
:param A: First covariance matrix
:param B: Second covariance matrix
:param metric: the metric (Default value 'riemann'), can be : 'riemann' , 'logeuclid' , 'euclid' , 'lo... | 5,303,217 |
def is_luhn_valid(cc):
"""Validate a credit card number using the Luhn algorithm.
@see: U{http://en.wikipedia.org/wiki/Luhn_algorithm}
@type cc: str
@param cc: Credit card number.
@rtype: bool
@return: C{True} if the credit card number appears to be valid.
"""
num = map(int, cc)
retu... | 5,303,218 |
def _FakeService():
""" use if you need a fake service from build """
class e:
execute = lambda : {'sheets':[],}
class v:
def get(range=None):
return []
class g:
def get(spreadsheetId=None, includeGridData=None, range=None):
return e
values = lamb... | 5,303,219 |
def ensure_directory(path):
"""Make the directory if not already there."""
import errno
from os import makedirs
try:
makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise | 5,303,220 |
def print_sites(localconfig):
"""
print web site information
"""
# print("line 2693")
# print("localconfig value:", localconfig)
# print("localconfig type:", type(localconfig))
# for one in sorted(localconfig):
for one in localconfig:
if "domains" in one:
print("Domai... | 5,303,221 |
def histDerivative(hist, bins, giveHist=False, binInput='lin'):
"""Takes in a histogram assuming linear/uniform bins.
Returns interpolating function for derivative of the hist
up to accuracy (deltabin)^2.
Uses a forward difference scheme in the first bin,
a central difference scheme in the 'bulk' bi... | 5,303,222 |
def qs(**kwargs):
"""Build a URL query string."""
url = ''
for k, v in kwargs.iteritems():
if k == 'username' or k == 'password':
pass
for value in v:
url += '&%s=%s' % (quote(k), value)
return url | 5,303,223 |
def load_data(image_key: str = "x",
label_key: str = "y",
label_mode: str = "fine") -> Tuple[NumpyDataset, NumpyDataset]:
"""Load and return the CIFAR100 dataset.
Please consider using the ciFAIR100 dataset instead. CIFAR100 contains duplicates between its train and test sets.
... | 5,303,224 |
def profile_update_scene(request):
"""
Handle User Profile page, scene post submit requests.
"""
if request.method != "POST":
return JsonResponse({}, status=status.HTTP_400_BAD_REQUEST)
if not request.user.is_authenticated:
return JsonResponse(
{"error": "Not authenticate... | 5,303,225 |
def syntactic_parse_features(paragraph, parse):
""" Returns the count for the usage of S, SBAR units in the syntactic parse,
plus statistics about the height of the trees """
KEPT_FEATURES = ['S', 'SBAR']
# Increment the count for the part-of-speech of each head of phrase
counts_of_heads = Counter()
tree_... | 5,303,226 |
def test_persist_results(db, tmpdir, settings, data_review):
"""
Test persistence of validation results
"""
# Setup test data
settings.BASE_DIR = os.path.join(tmpdir, "test")
persist_results = validation_run.persist_results
data_review.validation_resultset.delete()
vr = ValidationRunFact... | 5,303,227 |
def random_user_agent():
"""
This function selects a random User-Agent from the User-Agent list, which is a constant
variable that can be found at `investpy.utils.constant.USER_AGENTS`. User-Agents are used in
order to avoid the limitations of the requests to Investing.com. The User-Agent is
specifi... | 5,303,228 |
def test_wallpaper_path_with_calendar():
"""
Test '_get_wallpaper_path' method of WallpaperDownloader class.
Method is tested for the wallpaper with calendar.
"""
downloader = WallpaperDownloader("07-2020")
wallpaper_name = "july-20-birdie-july-cal-1920x1080.png"
wallpaper_path = downloader... | 5,303,229 |
def SetLogsOn(level=1):
""" Turn logging on with loglevel level."""
SetLogLevel(level) | 5,303,230 |
def to_bel_lines(graph):
"""Return an iterable over the lines of the BEL graph as a canonical BEL Script (.bel).
:param pybel.BELGraph graph: the BEL Graph to output as a BEL Script
:return: An iterable over the lines of the representative BEL script
:rtype: iter[str]
"""
return itt.chain(
... | 5,303,231 |
def get_gs_energy(H, tensors):
""" Returns ground-state energy and norm of the iPEPS """
E, nrm, *_ = get_obs(H, tensors, measure_obs=False)
return E[0], nrm | 5,303,232 |
def is_weekend(date):
"""Is the specified date (a datetime.date object) a weekend?"""
return date.weekday() in [5, 6] | 5,303,233 |
def removeUser(user_id):
"""
Function intended to remove users
"""
if user_id:
try:
user = Users.query.get(user_id)
db.session.delete(user)
db.session.commit()
return True
except Exception as e:
print(e)
return Fals... | 5,303,234 |
def get_python_libs_root():
"""
Get absolute path to scripts
>>> os.path.isdir(get_python_libs_root())
True
"""
return os.path.join(get_cime_root(), get_python_libs_location_within_cime()) | 5,303,235 |
def first_writable_file_that_preferably_exists(files):
"""
Returns the first file in files (sequence of path names) that preferably
exists and is writable. "Preferably exists" means that two loops are done
over the files -- the first loop returns the first file that exists and is
writable. If no f... | 5,303,236 |
def get_sample_source(prob_label):
"""Return a (SampleSource, n) representing the problem"""
if prob_label not in label2fname:
raise ValueError('Unknown problem label. Need to be one of %s'%str(list(label2fname.keys())) )
if prob_label == 'crop48_h0':
one_sample = glo.load_data_file(label2... | 5,303,237 |
def relu_backward(output, input, layer):
"""RELU backward
Args:
output: a dictionary contains output data and shape information
input: a dictionary contains input data and shape information
layer: one cnn layer, defined in testLeNet.py
Returns:
input_od: gradients w.r.t input data
"""
input_... | 5,303,238 |
def SendResetRequest(sock, addr):
"""Send a reset request over sock to addr.
This will cause the target system to reboot into the bootloader and wait for
an update. We send it 5 times just to make sure it gets through.
Args:
sock: The transmitting socket.
addr: The target address.
"""
reset_messa... | 5,303,239 |
def wallace_reducer(wire_array_2, result_bitwidth, final_adder=kogge_stone):
"""
The reduction and final adding part of a dada tree. Useful for adding many numbers together
The use of single bitwidth wires is to allow for additional flexibility
:param [[Wirevector]] wire_array_2: An array of arrays of ... | 5,303,240 |
def _make_worker(dispatcher_address,
data_transfer_protocol,
shutdown_quiet_period_ms=0,
port=0,
worker_tags=None):
"""Creates a worker server."""
defaults = server_lib.WorkerConfig(dispatcher_address=dispatcher_address)
config_proto = service_co... | 5,303,241 |
def finalize():
"""
Destruction of the singleton
"""
global TaskMngr
if TaskMngr:
TaskMngr.stop()
TaskMngr.join()
TaskMngr = None | 5,303,242 |
def findfiles(paths, regexp, full=False, maxcount=10000):
"""
:param paths:
:type paths:
:param regexp:
:type regexp:
"""
LOG.debug("Start find files")
LOG.debug("Paths: %s", paths)
LOG.debug("Regexp: '%s'", regexp)
results = []
re_obj = re.compile(regexp)
path_seen =... | 5,303,243 |
def clean_up(loc):
"""Remove unfinished result directories and entries in results.csv."""
for model_folder in glob(os.path.join(loc, '*')):
# delete folders with no results.csv
if not os.path.isfile(os.path.join(model_folder, 'results.csv')):
print('removing', model_folder)
... | 5,303,244 |
def calculate_precision(gts, preds, threshold = 0.5, form = 'coco', ious=None) -> float:
# https://www.kaggle.com/sadmanaraf/wheat-detection-using-faster-rcnn-train
"""Calculates precision for GT - prediction pairs at one threshold.
Args:
gts: (List[List[Union[int, float]]]) Coordinates of the avai... | 5,303,245 |
def _identifier_filtered_iterator(graph) -> Iterable[Tuple[str, str]]:
"""Iterate over names in the given namespace."""
for data in graph:
for pair in _get_node_names(data):
yield pair
for member in data.get(MEMBERS, []):
for pair in _get_node_names(member):
... | 5,303,246 |
def _table_view(self):
"""
Create a new table expression that is semantically equivalent to the
current one, but is considered a distinct relation for evaluation
purposes (e.g. in SQL).
For doing any self-referencing operations, like a self-join, you will
use this operation to create a referenc... | 5,303,247 |
def main(as_module=False):
"""Load cube-builder as package in python module."""
import sys
cli.main(args=sys.argv[1:], prog_name="python -m cube_builder" if as_module else None) | 5,303,248 |
def plot_gt_data(img_path, surr_polys_dict, show=True):
""" Plots the groundtruth data for the article separation network or saves it to the directory
:param img_path: path to the image the groundtruth is produced for
:param article_rect_dict: the ArticleRectangle dictionary
:param img_width: the width... | 5,303,249 |
def formatEx(excepInst):
"""
_formatEx_
given a DbdException instance, generate a simple message from it
"""
msg = "%s:%s %s" % (excepInst.__class__.__name__,
excepInst.getErrorMessage(),
excepInst.getErrorCode(),
)
return ... | 5,303,250 |
def test_barcode_umi_extract(configuration_module):
"""
Test that the results of barcode and UMI extraction are as expected.
:param configuration_module: temporary configuration and \
configuration file
:type configuration_module: tuple(dict, str or unicode)
"""
config, _ = configuration_mo... | 5,303,251 |
def resolutionstart(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
"""
Mark the given function as the first frame before resolution of objects begins. Additional
frames will be injected
"""
RESOLUTION_START.add(func.__code__)
return func | 5,303,252 |
def testrun_md5_input_json_w_extra_file_object_name(env='webdev'):
"""Creates a random file object with no md5sum/content_md5sum and run md5 workflow.
It waits for 6 mintues till the workflow run finishes and checks the input file object
has been updated.
"""
bucket = "elasticbeanstalk-fourfront-" +... | 5,303,253 |
def setup(bot: MangoPi):
"""
Function necessary for loading Cogs.
Parameters
----------
bot : MangoPi
pass in bot reference to add Cog
"""
bot.add_cog(Warn(bot))
print("Load Cog:\tWarn") | 5,303,254 |
def filter_tb(tbexeclist, tbinfo, tbexecgolden, tbinfogolden, id_num):
"""
First create filter list, then find start of filter, then call recursive filter
"""
filters = build_filters(tbinfogolden)
tbexecpd = tbexeclist
"""Sort and re-index tb exec list"""
tbexecpd.sort_values(by=["pos"], asc... | 5,303,255 |
def ema_update(student, teacher, alpha=0.9, verbose=False):
"""Update a teacher model based on the exponential moving average
of its weights and that of the current studen model.
Controlled by alpha \\in [0, 1] with
* alpha -> 1: teacher = past teacher
* alpha -> 0: teacher = student, std S... | 5,303,256 |
def test_custom_validate_input_values():
"""Test if error is raised when input array is not binary"""
with pytest.raises(ValueError):
sg.lifeforms.Custom(np.random.uniform(size=(3, 3))) | 5,303,257 |
def render_controls_box(data):
"""Render "top left" controls for the box plot for the given ``data``."""
return html.Div(
[
html.Label("select grouping"),
dcc.Dropdown(
id="expression_box_select_group",
options=[{"label": c, "value": c} for c in da... | 5,303,258 |
def resolve_node(ib, node_id, node_description, default_timeout=None):
"""
Resolve node description
:param str node_id: The internal unique identifier of the node.
:param node_description: The description of the node type. This will be
resolved to :ref:`Node Definition <nodedefinition>`, which ... | 5,303,259 |
def anc_at_rank(tax_id, tax_df, rank):
"""Return the ID of the parent of a taxon at a given rank."""
# Check to see if we are already at this rank
if tax_df.loc[tax_id, "rank"] == rank:
return tax_id
# Otherwise, walk up the parents until you find it
else:
for anc_tax_id in path_to... | 5,303,260 |
def reverse_domain_from_network(ip_network):
"""Create reverse DNS zone name from network address (ipaddress.IPv4Network)"""
prefixlen = ip_network.prefixlen
if prefixlen % 8:
return ip_network.reverse_pointer # classless
else:
return ip_network.network_address.reverse_pointer[(4 - (pr... | 5,303,261 |
def build_violations(res):
"""Build an expected violation.
Args:
res (Resource): resource to create violation from.
Returns:
RuleViolation: The violation.
"""
violation_data = {
'full_name': res.full_name,
'resource_type': res.type,
'locations': res.location... | 5,303,262 |
def use_no_vasp(original_wf, ref_dirs):
"""
Instead of running VASP, does nothing and pass task documents from task.json files in ref_dirs
to task database.
Args:
original_wf (Workflow)
ref_dirs(dict): key=firework name, value=path to the reference vasp calculation directory
Return... | 5,303,263 |
def load_model(config, shape):
"""Load a model."""
model = create_model(wili.n_classes, shape)
print(model.summary())
return model | 5,303,264 |
def random_ordered_tree(n, seed=None):
"""
Creates a random ordered tree
TODO
----
- [ ] Rename to random_ordered_directed_tree ?
- [ ] Merge in with other data generators?
Parameters
----------
n : int
A positive integer representing the number of nodes in the tree.
s... | 5,303,265 |
def main():
"""
Read the server file.
Make a request to server for status.
Save status to a DB.
Create a list of Applications
Create reports by quering DB.
"""
try:
db = CONN[SERVER]
coll = db[COLLECTION]
except KeyError:
db_initialize(SER... | 5,303,266 |
def player1():
"""Return a list of sample names."""
# Use Pandas to perform the sql query
stmt = db.session.query(players).statement
df = pd.read_sql_query(stmt, db.session.bind)
# Return a list of the column names (sample names)
# return jsonify(list(df.columns)[2:])
return jsonify(list(d... | 5,303,267 |
def get_past_date(str_days_ago: str, to_date: datetime = None,
tz: pytz.tzinfo = pytz.utc) -> object:
"""
Returns date in specified timezone relative to to_date parameter.
e.g.
'5 hours ago',
'yesterday',
'3 days ago',
'4 months ago',
'2 years ago',
'today'
Ar... | 5,303,268 |
def get_cosine_similarity(text1_: str, text2_: str) -> float:
"""
Calculate cosine similarity between two strings
This code is taken from with few modifications:
https://stackoverflow.com/a/15174569
:param text1_:
:param text2_:
:return:
"""
# convert text to vector and normalize ... | 5,303,269 |
def setup_logging(stream=None):
"""Do logging setup:
We want a prettier default format:
do: level: ...
Spacing. Lower case. Skip " level:" if INFO-level.
"""
hdlr = logging.StreamHandler(stream)
defaultFmt = "%(name)s: %(levelname)s: %(message)s"
infoFmt = "%(name)s: %(message)s"
... | 5,303,270 |
def clean_shutdown(exit_code):
"""
Method to cleanly shutdown the reviewer.
@param exit_code: the exit code to use
"""
# informs about an upcoming shutdown
running_event.clear()
############################################################################
# closes the databse connecti... | 5,303,271 |
def read_dyn(filename, natoms=None):
"""Read one dynamical matrix file (for 1 qpoint) produced by ``ph.x`` and
extract the same as :func:`read_matdyn_modes` for this qpoint only.
All arrays have one dim less compared to :func:`read_matdyn_modes`.
Parameters
----------
filename : str
Na... | 5,303,272 |
def visualise_cut(S_partition, working_graph, plt_title_string):
"""Plot and output the graph cut information.
could be eventually removed
"""
# Generate the colors.
coloring = []
for node in working_graph:
if node in S_partition:
coloring.append('blue')
else:
... | 5,303,273 |
def get_anchor_href(markup):
"""
Given HTML markup, return a list of hrefs for each anchor tag.
"""
soup = BeautifulSoup(markup, 'lxml')
return ['%s' % link.get('href') for link in soup.find_all('a')] | 5,303,274 |
async def get_asterisk_chan(response_json):
"""Get the Asterisk Channel from the JSON responses"""
if response_json["type"] in ["PlaybackStarted", "PlaybackFinished"]:
return str(response_json.get("playback", {}).get("target_uri")).split(":")[1]
else:
return response_json.get("channel", {}).... | 5,303,275 |
def load_pascal_data(data_dir, max_epochs=None, thread_count=3,
imsize=(128,128)):
"""Will use a filename queue and img_queue and load the data
"""
file_queue = core.FileQueue()
# d = img_dict(data_dir)
img_queue = core.ImageQueue(files_in_epoch=250, maxsize=1000)
threads ... | 5,303,276 |
def inplace_xor(program, classic_bits, qubits):
"""
Performs an XOR on a classical bit string and a qubit array. This
is an in-place implementation, meaning the qubit array will contain
the results of the XOR when this function returns.
Parameters:
program (Program): The program being const... | 5,303,277 |
def get_valid_uuids(uuids: list, full_paths: list, valid_full_paths: list) -> list:
"""Returns valid uuids."""
return [uuid for uuid, full_path in zip(uuids, full_paths) if full_path in valid_full_paths] | 5,303,278 |
def open_pad(path=None, first_line="", query=''): # {{{1
"""Creates or opens a note.
path: a valid path for a note.
first_line: a string to insert to a new note, if given.
query: the previous search, if any.
"""
# we require self.save_dir_set to be set to a valid path
if get_save_dir() ... | 5,303,279 |
def test_data(images_fp, lidar_fp, use_lidar):
"""
Grabs the file names of all the test images.
Parameters:
-----------
data_set: File path given by user leading to the main folder with the data
Returns:
--------
img_tensor: List of file names for the images
orig_dim: Original dime... | 5,303,280 |
def extract_time_invariants(cluster, template, *args):
"""
Extract time-invariant subexpressions, and assign them to temporaries.
"""
make = lambda: Scalar(name=template(), dtype=cluster.dtype).indexify()
rule = make_is_time_invariant(cluster.exprs)
costmodel = lambda e: estimate_cost(e, True) >... | 5,303,281 |
def background_task_callback(task: asyncio.Task) -> None:
"""Check if the finished background task failed to make sure we log errors."""
if task.cancelled():
log.info(f"Background task `{task.get_name()}` was cancelled.")
elif exception := task.exception():
log.error(f"Background task `{task... | 5,303,282 |
def copy_remote_file(web_file, destination):
"""
Check if exist the destination path, and copy the online resource
file to local.
Args:
:web_file: reference to online file resource to take.
:destination: path to store the file.
"""
size = 0
dir_name = os.path.dirname(destina... | 5,303,283 |
def get_pacients():
"""Funkcija pogleda če ima uporabnik pravice, če jih ima potem vrne vse paciente v bolnici kjer smo prijavljeni."""
(username, ime, vloga, bolnisnica) = get_user()
# Preverimo vlogo uporabnika
if vloga == "zdravstveni_delavec":
c = baza.cursor()
# TODO izberem vse pac... | 5,303,284 |
def MakePartitionTable(file_path):
"""Create a partition table in a file.
Args:
file_path: A path to a file where a partition table will be created.
"""
RunCommand(['parted', file_path, 'mklabel', 'msdos']) | 5,303,285 |
def score_grammars(features, labels, config, is_training=False):
"""load in grammar
"""
# features {N, 1, M}
grammars = config.get("grammars")
pwms = config.get("pwms")
assert grammars is not None
assert pwms is not None
# input - {N, 1, M}, ie 1 cell state
# generate two array ... | 5,303,286 |
def _serialise(data: any, prefix: str='') -> str:
"""Serialise an ordered map.
:arg data: An ordered map.
:arg prefix: Partially serialised result.
:returns: An ordered map string.
"""
if not isinstance(data, dict):
return '{}={}\n'.format(prefix, data)
result = ''
for key in ... | 5,303,287 |
def _DefaultFetchFunc(uri, cache_file):
"""The default fetch function.
This simply downloads the uri into the cache file using urilib
Args:
uri: The URI to download.
cache_file: The path to put the downloaded file in.
"""
urilib.Copy(uri, cache_file) | 5,303,288 |
def setup_crl_publishing():
"""Do some minimal CRL configuration.
We just need to create the default configuration.
The CRLs will be published every 15 days and the location will be the STATIC folder.
"""
from django.conf import settings
from webca.config.models import ConfigurationObject as Co... | 5,303,289 |
def upgrade(name: str):
"""Update a PyPI package"""
try:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', name])
except:
print(white + name + " succesfully ugraded") | 5,303,290 |
def get_sequence(ctx, seq_id, seq_type):
"""
Get sequence from provided Ensembl ID.
"""
sequences = ctx.obj['client'].get_sequence(seq_id, seq_type)
if sequences:
print(json.dumps(sequences, sort_keys=True, indent=4)) | 5,303,291 |
def eval_genomes(genomes, config):
"""
runs the simulation on the current population of
ufos and sets their fitness based on the distance reached
"""
global WIN, gen, score
win = WIN
gen += 1
# arrays to hold genome data
nets = []
ufos = []
ge = []
#initialize current g... | 5,303,292 |
def massage_error_code(error_code):
"""Massages error codes for cleaner exception handling.
Args:
int Error code
Returns:
int Error code. If arg is not an integer, will change to 999999
"""
if type(error_code) is not int:
error_code = 999999
return error_code | 5,303,293 |
def LinksEff(network):
"""
Parameters
----------
network : PyPSA network type
input network
Returns
-------
linkseff : array
an array of the types of links that have an efficency. Used to calculate the response values
"""
linkseff = network.links # Save link d... | 5,303,294 |
def run_antechamber(infile, outfile, at='gaff', c='gas', logfile='antechamber.log', version='14', skip_unrecognized_atoms=False):
""" use H++ idea of running antechamber multiple times with bcc's charge method to estimate the appropriate net charge!!"""
suffix, ext = os.path.splitext(infile)
ext = ext[1:]
... | 5,303,295 |
def Tm_Wallace(seq, check=True, strict=True):
"""Calculate and return the Tm using the 'Wallace rule'.
Tm = 4 degC * (G + C) + 2 degC * (A+T)
The Wallace rule (Thein & Wallace 1986, in Human genetic diseases: a
practical approach, 33-50) is often used as rule of thumb for approximate
Tm calculatio... | 5,303,296 |
def process_dual_lib(self):
"""
Find the location of a foreign library. Used by :py:class:`lmbrwaflib.lumberyard_sdks.read_dual_library_shared` and
:py:class:`lmbrwaflib.lumberyard_sdks.read_dual_library_static`.
"""
node = None
library_name = convert_dual_task_name_to_lib_name(self.name)
... | 5,303,297 |
def db_to_df(amount, connection=create_connection()):
"""
Transfer results of a SQL query to a dataframe
:param amount: limit amount of entries returned
:param connection: connection object
:return: dataframe
"""
query = pd.read_sql(f"CALL select_reviews(%(amount)s)", connection, params={"am... | 5,303,298 |
def alternative_floating_algae_index(Red, Rededge, Near):
"""transform near and short wave infrared arrays to get a algae-index
Parameters
----------
Red : numpy.array, size=(m,n)
red band of satellite image
Rededge : numpy.array, size=(m,n)
rededge band of satellite image
Near ... | 5,303,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.