content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def compute_quasisymmetry_error(
R_lmn,
Z_lmn,
L_lmn,
i_l,
Psi,
R_transform,
Z_transform,
L_transform,
iota,
helicity=(1, 0),
data=None,
):
"""Compute quasi-symmetry triple product and two-term errors.
f_C computation assumes transform grids are a single flux surface... | 5,336,900 |
def int_to_uuid(number):
""" convert a positive integer to a UUID :
a string of characters from `symbols` that is at least 3 letters long"""
assert isinstance(number,int) and number >= 0
if number == 0:
return '000'
symbol_string = ''
while number > 0:
remainder = number % base
... | 5,336,901 |
def VPLoadCSV(self):
"""
Load Velocity Profile .csv
"""
VP_CSVName = askopenfilename()
self.VP_CSV = pd.read_csv(VP_CSVName, delimiter=',')
self.VP_Rad, self.VP_Prof = self.VP_CSV['Radius'].values, self.VP_CSV['Velocity Profile'].values
#Update Equation Box
self.VPEqu.delete(0, T... | 5,336,902 |
def key_value_data(string):
"""Validate the string to be in the form key=value."""
if string:
key, value = string.split("=")
if not (key and value):
msg = "{} not in 'key=value' format.".format(string)
raise argparse.ArgumentTypeError(msg)
return {key: value}
... | 5,336,903 |
def count_digit(n, digit):
"""Return how many times digit appears in n.
>>> count_digit(55055, 5)
4
"""
if n == 0:
return 0
else:
if n%10 == digit:
return count_digit(n//10, digit) + 1
else:
return count_digit(n//10, digit) | 5,336,904 |
def _get_courses_in_page(url) -> [Course]:
"""
Given a WebSoc search URL, creates a generator over each Course in the results page
"""
# Get the page that lists the courses in a table
with urllib.request.urlopen(url) as source:
soup = bs.BeautifulSoup(source, "html.parser")
# Itera... | 5,336,905 |
def cal_chisquare(data, f, pepoch, bin_profile, F1, F2, F3, F4, parallel=False):
"""
calculate the chisquare distribution for frequency search on the pepoch time.
"""
chi_square = np.zeros(len(f), dtype=np.float64)
t0 = pepoch
if parallel:
for i in prange(len(f)):
phi = (da... | 5,336,906 |
def test_spacy_german():
"""Test the parser with the md document."""
docs_path = "tests/data/pure_html/brot.html"
# Preprocessor for the Docs
preprocessor = HTMLDocPreprocessor(docs_path)
doc = next(preprocessor._parse_file(docs_path, "md"))
# Create an Parser and parse the md document
par... | 5,336,907 |
def main():
""" Play around the pie chart with some meaningless data. """
# slices: list[int] = [120, 80, 30, 20]
# labels: list[str] = ['Sixty', 'Forty', 'Fifteen', 'Ten']
# colours: list[str] = ['#008fd5', '#fc4f30', '#e5ae37', '#6d904f']
# plt.pie(slices, labels=labels, colors=colours, wedgeprops... | 5,336,908 |
def get_css_urls(bundle, debug=None):
"""
Fetch URLs for the CSS files in the requested bundle.
:param bundle:
Name of the bundle to fetch.
:param debug:
If True, return URLs for individual files instead of the minified
bundle.
"""
if debug is None:
debug = sett... | 5,336,909 |
def myt():
"""
myt - my tASK MANAGER
An application to manage your tasks through the command line using
simple options.
"""
pass | 5,336,910 |
def rng() -> np.random.Generator:
"""Random number generator."""
return np.random.default_rng(42) | 5,336,911 |
def add_values_in_dict(sample_dict, key, list_of_values):
"""Append multiple values to a key in the given dictionary"""
if key not in sample_dict:
sample_dict[key] = list()
sample_dict[key].extend(list_of_values)
temp_list = sample_dict[key]
temp_list = list(set(temp_list)) # remove duplica... | 5,336,912 |
def parse_length(line, p) -> int:
""" parse length specifer for note or rest """
n_len = voices[ivc].meter.dlen # start with default length
try:
if n_len <= 0:
SyntaxError(f"got len<=0 from current voice {line[p]}")
if line[p].isdigit(): # multiply note length
... | 5,336,913 |
def get_dual_shapes_and_types(bounds_elided):
"""Get shapes and types of dual vars."""
dual_shapes = []
dual_types = []
layer_sizes = utils.layer_sizes_from_bounds(bounds_elided)
for it in range(len(layer_sizes)):
m = layer_sizes[it]
m = [m] if isinstance(m, int) else list(m)
if it < len(layer_siz... | 5,336,914 |
def linear_search(alist, key):
""" Return index of key in alist . Return -1 if key not present."""
for i in range(len(alist)):
if alist[i] == key:
return i
return -1 | 5,336,915 |
def create_pipeline(ctx: Context, pipeline_path: Text, build_target_image: Text,
skaffold_cmd: Text, build_base_image: Text) -> None:
"""Command definition to create a pipeline."""
click.echo('Creating pipeline')
ctx.flags_dict[labels.ENGINE_FLAG] = kubeflow_labels.KUBEFLOW_V2_ENGINE
ctx.fla... | 5,336,916 |
def register_object_name(object, namepath):
"""
Registers a object in the NamingService.
The name path is a list of 2-uples (id,kind) giving the path.
For instance if the path of an object is [('foo',''),('bar','')],
it is possible to get a reference to the object using the URL
'corbaname::host... | 5,336,917 |
def overlap_integral(xi, yi, zi, nxi, nyi, nzi, beta_i,
xj, yj, zj, nxj, nyj, nzj, beta_j):
"""
overlap <i|j> between unnormalized Cartesian GTOs
by numerical integration on a multicenter Becke grid
Parameters
----------
xi,yi,zi : floats
Cartesian posit... | 5,336,918 |
def save_project_id(config: Config, project_id: int):
"""Save the project ID in the project data"""
data_dir = config.project.data_dir
filename = data_dir / DEFAULT_PROJECTID_FILENAME
with open(filename, "w") as f:
return f.write(str(project_id)) | 5,336,919 |
async def session_start():
"""
session_start: Creates a new database session for external functions and returns it
- Keep in mind that this is only for external functions that require multiple transactions
- Such as adding songs
:return: A new database session
... | 5,336,920 |
def apply(bpmn_graph: BPMN, parameters: Optional[Dict[Any, Any]] = None) -> graphviz.Digraph:
"""
Visualize a BPMN graph
Parameters
-------------
bpmn_graph
BPMN graph
parameters
Parameters of the visualization, including:
- Parameters.FORMAT: the format of the visualiz... | 5,336,921 |
def _predict_exp(data, paulistring):
"""Compute expectation values of paulistring given bitstring data."""
expectation_value = 0
for a in data:
val = 1
for i, pauli in enumerate(paulistring):
idx = a[i]
if pauli == "I":
continue
elif pauli ... | 5,336,922 |
def allocate_single(size=1024 ** 3):
"""Method allocates memory for single variable
Args:
size (int): size
Returns:
void
"""
data = '0' * size
del data | 5,336,923 |
def AGI(ymod1, c02500, c02900, XTOT, MARS, sep, DSI, exact, nu18, taxable_ubi,
II_em, II_em_ps, II_prt, II_no_em_nu18,
c00100, pre_c04600, c04600):
"""
Computes Adjusted Gross Income (AGI), c00100, and
compute personal exemption amount, c04600.
"""
# calculate AGI assuming no foreign... | 5,336,924 |
def tokenize(headline_list):
"""
Takes list of headlines as input and returns a list of lists of tokens.
"""
tokenized = []
for headline in headline_list:
tokens = word_tokenize(headline)
tokenized.append(tokens)
return tokenized | 5,336,925 |
def create_en_sentiment_component(nlp: Language, name: str, force: bool) -> Language:
"""
Allows the English sentiment to be added to a spaCy pipe using nlp.add_pipe("asent_en_v1").
"""
LEXICON.update(E_LEXICON)
return Asent(
nlp,
name=name,
lexicon=LEXICON,
intensif... | 5,336,926 |
def p_term_comparison(p):
"""term : factor GREATER_THAN factor
| factor GREATER_THAN_EQUALS factor
| factor LESS_THAN factor
| factor LESS_THAN_EQUALS factor
| factor EQUALS factor
| factor NOT_EQUALS factor
| factor IS_NOT_EQUALS factor
... | 5,336,927 |
def set_current(path):
"""Write the current file. """
fpath = pth.expandvars("$HOME/.excentury/current")
with open(fpath, 'w') as _fp:
_fp.write(path) | 5,336,928 |
def lambda_handler(event, context):
"""
店舗一覧情報を返す
Parameters
----------
event : dict
フロントより渡されたパラメータ
context : dict
コンテキスト内容。
Returns
-------
shop_list : dict
店舗一覧情報
"""
# パラメータログ
logger.info(event)
try:
shop_list = get_shop_list()
... | 5,336,929 |
def mask_land_ocean(data, land_mask, ocean=False):
"""Mask land or ocean values using a land binary mask.
Parameters
----------
data: xarray.DataArray
This input array can only have one of 2, 3 or 4
dimensions. All spatial dimensions should coincide with those
of the land binary... | 5,336,930 |
def create_project_type(project_type_params):
"""
:param project_type_params: The parameters for creating an ProjectType instance -- the dict should include the
'type' key, which specifies the ProjectType subclass name, and key/value pairs matching constructor arguments
for that ProjectType subc... | 5,336,931 |
def env_str(env_name: str, default: str) -> str:
"""
Get the environment variable's value convert into string
"""
return getenv(env_name, default) | 5,336,932 |
def test_list_g_year_month_min_length_1_nistxml_sv_iv_list_g_year_month_min_length_2_1(mode, save_output, output_format):
"""
Type list/gYearMonth is restricted by facet minLength with value 6.
"""
assert_bindings(
schema="nistData/list/gYearMonth/Schema+Instance/NISTSchema-SV-IV-list-gYearMonth... | 5,336,933 |
def server_bam_statistic(ip, snmp_config_data):
"""
:param ip:
:param snmp_config_data:
:return:
"""
try:
var_binds = get_snmp_multiple_oid(oids=oids_bam, ip=ip, snmp_config_data=snmp_config_data)
server_memory_usage = get_memory_usage(var_binds)
server_cpu_usage = get_cp... | 5,336,934 |
def extract_sigma_var_names(filename_nam):
"""
Parses a 'sigma.nam' file containing the variable names, and outputs a
list of these names.
Some vector components contain a semicolon in their name; if so, break
the name at the semicolon and keep just the 1st part.
"""
var_names = []
wit... | 5,336,935 |
def vectors_to_arrays(vectors):
"""
Convert 1d vectors (lists, arrays or pandas.Series) to C contiguous 1d
arrays.
Arrays must be in C contiguous order for us to pass their memory pointers
to GMT. If any are not, convert them to C order (which requires copying the
memory). This usually happens ... | 5,336,936 |
def random_name_gen(size=6):
"""Generate a random python attribute name."""
return ''.join(
[random.choice(string.ascii_uppercase)] +
[random.choice(string.ascii_uppercase + string.digits) for i in range(size - 1)]
) if size > 0 else '' | 5,336,937 |
def load_player_history_table(div_soup):
"""Parse the HTML/Soup table for the numberfire predictions.
Returns a pandas DataFrame
"""
if not div_soup:
return None
rows = div_soup.findAll('tr')
table_header = [x.getText() for x in rows[0].findAll('th')]
table_data = [[x.getText() for x in row.findAll('t... | 5,336,938 |
def is_identity(u, tol=1e-15):
"""Test if a matrix is identity.
Args:
u: np.ndarray
Matrix to be checked.
tol: float
Threshold below which two matrix elements are considered equal.
"""
dims = np.array(u).shape
if dims[0] != dims[1]:
raise Exception("... | 5,336,939 |
def main():
"""main entry point"""
_me = os.path.splitext(os.path.basename(__file__))[0]
_output = _me + ".lld"
_parser = ArgumentParser()
_parser.add_argument("-o", "--oratab", action="store",
default="/etc/oratab",
help="oratab file to use on *nix"... | 5,336,940 |
def get_metrics():
"""
Collects various system metrics and returns a list of objects.
"""
metrics = {}
metrics.update(get_memory_metrics())
metrics.update(get_cpu_metrics())
metrics.update(get_disk_metrics())
return metrics | 5,336,941 |
def getPost(blog_id, username, password, post_id, fields=[]):
"""
Parameters
int blog_id
string username
string password
int post_id
array fields: Optional. List of field or meta-field names to include in response.
"""
logger.debug("%s.getPost entered" % __name__)
user = get_user... | 5,336,942 |
def create_fun(name: str, obj, options: dict):
"""
Generate a dictionnary that contains the information about a function
**Parameters**
> **name:** `str` -- name of the function as returned by `inspect.getmembers`
> **obj:** `object` -- object of the function as returned by `inspect.getmembers`
... | 5,336,943 |
def serial_ss(file_read, forward_rate, file_rateconstant,
file_energy, matrix, species_list, factor,
initial_y, t_final, third_body=None,
chemkin_data=None, smiles=None, chemkin=True):
"""
Iteratively solves the system of ODEs for different rate constants
generated ... | 5,336,944 |
def contains_left_button(buttons) -> bool:
"""
Test if the buttons contains the left mouse button.
The "buttons" should be values returned by get_click() or get_mouse()
:param buttons: the buttons to be tested
:return: if the buttons contains the left mouse button
"""
return (buttons & QtC... | 5,336,945 |
def init():
"""Initialize default fixtures."""
load_fixtures() | 5,336,946 |
def extract_interest_from_import_batch(
import_batch: ImportBatch, interest_rt: ReportType) -> List[Dict]:
"""
The return list contains dictionaries that contain data for accesslog creation,
but without the report_type and import_batch fields
"""
# now we compute the interest data from it
... | 5,336,947 |
def run(input_file, log_file, mode):
"""Entry point for the INOIS application."""
log_level = logging.DEBUG if log_file else logging.CRITICAL
log_location = log_file if log_file else "inois.log"
logging.basicConfig(format='%(asctime)s (%(levelname)s): %(message)s', filename=log_location, level=log_leve... | 5,336,948 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
_LOGGER.debug("Disconnecting from spa")
spa: BalboaSpaWifi = hass.data[DOMAIN][entry.entry_id]
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
hass.dat... | 5,336,949 |
def is_bst(t: BST) -> bool:
"""Returns true if t is a valid BST object, false otherwise.
Invariant: for each node n in t, if n.left exists, then n.left <= n, and if
n.right exists, then n.right >= n."""
if not isinstance(t, BST):
return False
if t._root and t._root.parent is not None:
... | 5,336,950 |
def koch(t, n):
"""Draws a koch curve with length n."""
if n<3:
fd(t, n)
return
m = n/3.0
koch(t, m)
lt(t, 60)
koch(t, m)
rt(t, 120)
koch(t, m)
lt(t, 60)
koch(t, m) | 5,336,951 |
def are_embedding_layer_positions_ok_for_testing(model):
"""
Test data can only be generated if all embeddings layers
are positioned directly behind the input nodes
"""
def count_embedding_layers(model):
layers = model.layers
result = 0
for layer in layers:
if is... | 5,336,952 |
def all_tasks_stopped(tasks_state: Any) -> bool:
"""
Checks if all tasks are stopped or if any are still running.
Parameters
---------
tasks_state: Any
Task state dictionary object
Returns
--------
response: bool
True if all tasks are stopped.
"""
for t in tas... | 5,336,953 |
def enhance_color(image, factor):
"""Change the strength of colors in an image.
This function has identical outputs to
``PIL.ImageEnhance.Color``.
Added in 0.4.0.
**Supported dtypes**:
* ``uint8``: yes; fully tested
* ``uint16``: no
* ``uint32``: no
* ``uint64``: ... | 5,336,954 |
def set_amc_animation(amc_file_path: str, frame_distance=1):
"""set animation with data of amc form
:param data: file path to amc data
:param frame_distance: set keyframe across every frame_distance, default is 1
"""
with open(amc_file_path, "rb") as f:
cur_frame = 0
character ... | 5,336,955 |
def locate_blocks(codestr):
"""
For processing CSS like strings.
Either returns all selectors (that can be "smart" multi-lined, as
long as it's joined by `,`, or enclosed in `(` and `)`) with its code block
(the one between `{` and `}`, which can be nested), or the "lose" code
(properties) that... | 5,336,956 |
def random_deceleration(most_comfortable_deceleration, lane_pos):
"""
Return a deceleration based on given attribute of the vehicle
:param most_comfortable_deceleration: the given attribute of the vehicle
:param lane_pos: y
:return: the deceleration adopted by human driver
"""
if lane_pos:
... | 5,336,957 |
def dataclass_fields(dc):
"""Returns a dataclass's fields dictionary."""
return {name: getattr(dc, name)
for name in dc.__dataclass_fields__} | 5,336,958 |
def gets_ontology_statistics(file_location: str, owltools_location: str = './pkt_kg/libs/owltools') -> str:
"""Uses the OWL Tools API to generate summary statistics (i.e. counts of axioms, classes, object properties, and
individuals).
Args:
file_location: A string that contains the file path and na... | 5,336,959 |
def listener():
"""
Initialize the ROS node and the topic to which it subscribes.
"""
rospy.init_node(
'subscriber_example', anonymous=True)
# Subscribes to topic 'joint_states'
rospy.Subscriber("joint_states", JointState, callback)
rospy.spin() | 5,336,960 |
def get_directives(app: Sphinx):
"""Return all directives available within the current application."""
from docutils.parsers.rst.directives import _directives, _directive_registry
all_directives = {}
all_directives.update(_directive_registry)
all_directives.update(_directives)
for key, (module... | 5,336,961 |
def _get_wavs_from_dir(dir):
"""Return a sorted list of wave files from a directory."""
return [os.path.join(dir, f) for f in sorted(os.listdir(dir)) if \
_is_wav_file(f)] | 5,336,962 |
def SqlReader(sql_statement: str, **kwargs):
"""
Use basic SQL queries to filter Reader.
Parameters:
sql_statement: string
kwargs: parameters to pass to the Reader
Note:
`select` is taken from SQL SELECT
`dataset` is taken from SQL FROM
`filters` is taken from S... | 5,336,963 |
def _handle_consent_confirmation(user, is_confirmed):
"""
Return server response given user consent.
Args:
user (fence.models.User): authN'd user
is_confirmed (str): confirmation param
"""
if is_confirmed == "yes":
# user has already given consent, continue flow
resp... | 5,336,964 |
def local_coherence(img, window_s=WSIZ):
"""
Calculate the coherence according to methdology described in:
Bazen, Asker M., and Sabih H. Gerez. "Segmentation of fingerprint images."
ProRISC 2001 Workshop on Circuits, Systems and Signal Processing. Veldhoven,
The Netherlands, 2001.
"""
coherence = []... | 5,336,965 |
def storeIDToWebID(key, storeid):
"""
Takes a key (int) and storeid (int) and produces a webid (a 16-character
str suitable for including in URLs)
"""
i = key ^ storeid
l = list('%0.16x' % (i,))
for nybbleid in range(0, 8):
a, b = _swapat(key, nybbleid)
_swap(l, a, b)
ret... | 5,336,966 |
def _jupyter_server_extension_paths():
"""
Set up the server extension for collecting metrics
"""
return [{"module": "jupyter_resource_usage"}] | 5,336,967 |
def plot_alpha(ax=None):
"""Plot angle of attack versus vertical coordinate."""
df = pr.load_sampled_velocity(name="inflow")
pitch = pr.read_alpha_deg()
df["alpha_deg"] = pitch - np.rad2deg(np.tan(df.U_1/df.U_0))
if ax is None:
fig, ax = plt.subplots()
ax.plot(df.z, -df.alpha_deg)
ax... | 5,336,968 |
def _make_ordered_node_map(
pipeline: p_pb2.Pipeline
) -> 'collections.OrderedDict[str, p_pb2.PipelineNode]':
"""Helper function to prepare the Pipeline proto for DAG traversal.
Args:
pipeline: The input Pipeline proto. Since we expect this to come from the
compiler, we assume that it is already topo... | 5,336,969 |
def read_omex_meta_files_for_archive(archive, archive_dirname, config=None):
""" Read all of the OMEX Metadata files in an archive
Args:
archive (:obj:`CombineArchive`): COMBINE/OMEX archive
archive_dirname (:obj:`str`): directory with the content of the archive
config (:obj:`Config`, o... | 5,336,970 |
def fmin_b_bfgs(func, x0, args=(), options=None):
"""
The BFGS algorithm from
Algorithm 6.1 from Wright and Nocedal, 'Numerical Optimization', 1999, pg. 136-143
with bounded parameters, using the active set approach from,
Byrd, R. H., Lu, P., Nocedal, J., & Zhu, C. (1995).
'A Limite... | 5,336,971 |
def find_broken_in_text(text, ignore_substrings=None):
"""Find broken links
"""
links = _find(text, ignore_substrings=ignore_substrings)
responses = [_check_if_broken(link) for link in links]
return [res.url for res in responses if res.broken] | 5,336,972 |
def revision_info():
"""
Get the git hash and mtime of the repository, or the installed files.
"""
# TODO: test with "pip install -e ." for developer mode
global _REVISION_INFO
if _REVISION_INFO is None:
_REVISION_INFO = git_rev(repo_path())
if _REVISION_INFO is None:
try:
... | 5,336,973 |
def home():
""" route for the index page"""
return jsonify({"message" : "welcome to fast_Food_Fast online restaurant"}) | 5,336,974 |
def test_get_default_output_for_example():
"""Tests for get_default_output_for_example()."""
from reana.cli import get_default_output_for_example
for (example, output) in (
('', ('plot.png',)),
('reana-demo-helloworld', ('greetings.txt',)),
('reana-demo-root6-roofit', ('p... | 5,336,975 |
def singlediode_voc(effective_irradiance, temp_cell, module_parameters):
"""
Calculate voc using the singlediode model.
Parameters
----------
effective_irradiance
temp_cell
module_parameters
Returns
-------
"""
photocurrent, saturation_current, resistance_series, resistan... | 5,336,976 |
async def test_generated_text_with_phrase() -> None:
"""Тестирует работу функции с непустой фразой"""
phrase = 'Тестовая фраза'
is_empty_phrase, generated_text = await get_generated_text(phrase)
assert not is_empty_phrase
assert generated_text | 5,336,977 |
def YumUninstall(vm):
"""Stops collectd on 'vm'."""
_Uninstall(vm) | 5,336,978 |
def test_cogeo_invalidresampling(runner):
"""Should exit with invalid resampling."""
with runner.isolated_filesystem():
result = runner.invoke(
cogeo, ["create", raster_path_rgb, "output.tif", "-r", "gauss", "-w"]
)
assert result.exception
assert result.exit_code == 2... | 5,336,979 |
def _exec_document_lint_and_script(
limit_count: Optional[int] = None) -> List[str]:
"""
Execute each runnable scripts in the documents and check with
each lint.
Parameters
----------
limit_count : int or None, optional
Limitation of the script execution count.
R... | 5,336,980 |
def balance_boxplot(balance_name, data, num_color='#FFFFFF',
denom_color='#FFFFFF',
xlabel="", ylabel="", linewidth=1,
ax=None, **kwargs):
""" Plots a boxplot for a given balance on a discrete metadata category.
Parameters
----------
x, y, hue... | 5,336,981 |
def walk(dirname, file_list):
"""
This function is from a book called Think Python
written by Allen B. Downey.
It walks through a directory, gets names of all files
and calls itself recursively on all the directories
"""
for name in os.listdir(dirname):
path=os.path.join(dirna... | 5,336,982 |
def new_auto_connection(dsn: dict, name: str = "DSN"):
"""
---------------------------------------------------------------------------
Saves a connection to automatically create database cursors, creating a
used-as-needed file to automatically set up a connection. Useful for
preventing redundant cursors.
The func... | 5,336,983 |
def delete_nodes_not_in_list(uuids):
"""Delete nodes which don't exist in Ironic node UUIDs.
:param uuids: Ironic node UUIDs
"""
inspector_uuids = _list_node_uuids()
for uuid in inspector_uuids - uuids:
LOG.warning(
_LW('Node %s was deleted from Ironic, dropping from Ironic '
... | 5,336,984 |
def getCustomEvaluatorClusters(evaluator):
"""
Get the clusters for a given custom evaluator, if any.
"""
pass | 5,336,985 |
def _apply_result_filters(key_gender_token_counters: Dict[Union[str, int], GenderTokenCounters],
diff: bool,
sort: bool,
limit: int,
remove_swords: bool) -> KeyGenderTokenResponse:
"""
A private helper functi... | 5,336,986 |
def blog_delete(request):
"""Delete blog entry by id."""
blog_id = int(request.params.get('id'))
entry = BlogRecordService.by_id(blog_id, request)
if not entry:
return HTTPNotFound()
request.dbsession.delete(entry)
return HTTPFound(location=request.route_url('home')) | 5,336,987 |
async def get_ios_cfw():
"""Gets all apps on ios.cfw.guide
Returns
-------
dict
"ios, jailbreaks, devices"
"""
async with aiohttp.ClientSession() as session:
async with session.get("https://api.appledb.dev/main.json") as resp:
if resp.status == 200:
... | 5,336,988 |
def log_exporter(message):
"""Log a message to the exporter log"""
logger = logging.getLogger(EXPORTER_LOGGER_NAME)
logger.info(message) | 5,336,989 |
def server_error(errorMsg):
"""
Shorthand for returning error message.
"""
resp = HttpResponse(status=502)
resp.write("<h3>502 BAD GATEWAY: </h3>")
resp.write("<p>ERROR: {}</p>".format(errorMsg))
return resp | 5,336,990 |
def protein_variant(variant):
"""
Return an HGVS_ variant string containing only the protein changes in a
coding HGVS_ variant string. If all variants are synonymous, returns the
synonymous variant code. If the variant is wild type, returns the wild
type variant.
:param str variant: coding vari... | 5,336,991 |
def parser():
"""Parses arguments from command line using argparse.
Parameters"""
# default directory for reddit files
default_directory = os.path.join(os.getcwd(), "data")
parser = argparse.ArgumentParser()
# obligatory
parser.add_argument("mode", type = int, help = "execution mode: 1 buil... | 5,336,992 |
def dump_func_name(func):
"""This decorator prints out function name when it is called
Args:
func:
Returns:
"""
def echo_func(*func_args, **func_kwargs):
logging.debug('### Start func: {}'.format(func.__name__))
return func(*func_args, **func_kwargs)
return echo_func | 5,336,993 |
def calc_predictability_trace_of_avg_cov(x, k, p, ndim=False):
"""
The main evaluation criterion of GPFA, i.e., equation (2) from the paper.
:param x: data array
:param k: number of neighbors for estimate
:param p: number of past time steps to consider
:param ndim: n-dimensional evaluation if T... | 5,336,994 |
def nx_to_loreleai(graph: nx.Graph, relation_map: Dict[str, Predicate] = None) -> Sequence[Atom]:
"""
Converts a NetworkX graph into Loreleai representation
To indicate the type of relations and nodes, the functions looks for a 'type' attribute
Arguments:
graph: NetworkX graph
relation... | 5,336,995 |
def _kohn_sham_iteration(
density,
external_potential,
grids,
num_electrons,
xc_energy_density_fn,
interaction_fn,
enforce_reflection_symmetry):
"""One iteration of Kohn-Sham calculation."""
# NOTE(leeley): Since num_electrons in KohnShamState need to specify as
# static argument in ji... | 5,336,996 |
def get_sync_func_driver(physical_mesh):
"""Get the sync function on the driver."""
def sync_func_driver():
assert isinstance(physical_mesh, LocalPhysicalDeviceMesh)
physical_mesh.devices[0].synchronize_all_activity()
return sync_func_driver | 5,336,997 |
def get_nc_BGrid_GFDL(grdfile):
"""
Bgrd = get_nc_BGrid_GFDL(grdfile)
Load B-Grid grid object for GFDL CM2.1 from netCDF grid file
"""
nc = pyroms.io.Dataset(grdfile)
lon_t = nc.variables['geolon_t'][:]
lat_t = nc.variables['geolat_t'][:]
lon_uv = nc.variables['geolon_c'][:]
lat_u... | 5,336,998 |
def _getTimeDistORSlocal(fromLocs, toLocs, travelMode, port, speedMPS):
"""
Generate two dictionaries, one for time, another for distance, using ORS-local
Parameters
----------
fromLocs: list, Required
The start node coordinates in format of [[lat, lon], [lat, lon], ... ]
toLocs: list, Required
The End node ... | 5,336,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.