content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import numpy
def basins_manually(cube, lat_array, lon_array, pacific_lon_bounds, indian_lon_bounds):
"""Define basins manually (i.e. without assistance from CMIP basin file)
in the output array:
north atlantic = 11
south atlantic = 12
north pacific = 13
south pacific = 14
indian... | caf9db0696833654a0a99ecf65ed88315491f622 | 34,249 |
import re
def unstem_ngram(concept, sentence):
"""
converts all words of a string which contains stemmed words into their original form
:param concept:
:param sentence:
:return:
"""
ngrams = concept.split(' ')
words = []
for token in ngrams:
try:
word, p... | 89c80f3bd6e70d4f04844ba427c9ce0cb3832e9e | 34,250 |
def updateObjectFromXML(xml_doc, obj, mapping):
"""
Handle updating an object. Based on XML input.
"""
nsmap = None
if isinstance(mapping, dict):
# The special key @namespaces is used to pass
# namespaces and prefix mappings for xpath selectors.
# e.g. {'x': 'http://example.... | 4fcb647f03158d0a4d7a3dbb4c89584a141884de | 34,251 |
def get_py_type(json_type):
"""
Given a JSON type return a corresponding Python type.
If no type can be determined, return an empty string.
"""
if json_type in ("enum", "string", "File"):
return "str"
elif json_type == "boolean":
return "bool"
elif json_type == "array":
... | bf738c5257022019ec26ac89a45ba098e129afcd | 34,252 |
import requests
def check_status():
"""Checks if a player is in a live game, returns false if not in a game."""
try:
output = requests.get('https://127.0.0.1:2999/liveclientdata/playerlist', verify = False)
except:
return False
response = output.json()
if not type(response) == list... | ae51cbe39425a67753ade68b2c3a86f748f089b2 | 34,253 |
def link(keys, values):
"""Creates hash table
:param numpy.array keys: key.
:param numpy.array values: value.
:return: (*dict*) -- hash table.
"""
return {k: v for k, v in zip(keys, values)} | 890e0aa99a3027a8e8348b828a56049a78fbbd55 | 34,256 |
def get_mature_sequence(precursor, mature, exact=False):
"""
From precursor and mature positions
get mature sequence with +/- 4 flanking nts.
Args:
*precursor(str)*: long sequence.
*mature(list)*: [start, end].
*exact(boolean)*: not add 4+/- flanking nts.
Returns:
... | 6fa0aaa32173fb1e03b812f83fc895d6c797cc1d | 34,257 |
def int16(s):
"""Validates an hexadecimal (0x...) value"""
i = int(s, 16)
return i | b8d1f4afaaea1e2e15f494d1ebda8229d6661cb9 | 34,258 |
import os
def disintegrate(path_name):
"""
Disintegrates the path name by splitting all of the components apart
"""
return os.path.normpath(path_name).split(os.sep) | 91e367f057bc5d7d7faadbbbbecb4829e6a2a688 | 34,260 |
import re
def stripNonAlphaNum(text):
""" Delete non alphanumerical character into a string text and return a list """
return re.compile(r"\W+", re.UNICODE).split(text) | c348a1f3d9a22c6ba1a6a9121edd9d665e6e3d9f | 34,263 |
def get_buildings(expo, tax, ds):
"""
Helper method to get the buildings value.
"""
expo_tax = expo[expo.Taxonomy == tax]
expo_ds = expo_tax[expo_tax.Damage == ds]
return expo_ds.Buildings.iloc[0] | 59f99854cad80d5037cad09b96cf0254923f0376 | 34,264 |
def stat_ahead_behind(git, local_ref, remote_ref):
"""
Returns a tuple (ahead, behind) describing how far
from the remote ref the local ref is.
"""
behind = 0
ahead = 0
(ret, out) = git.call("rev-list", "--left-right",
"%s..%s" % (remote_ref, local_ref), raises=Fals... | 7275a43a94bf8bc9d4971aa79a198cdedca39031 | 34,265 |
def bpas_log_snr_new(file_name: str, mode: str = "INIT"):
"""
Retrieve ``new`` SNR values from bandpass log file.
Parameters
----------
file_name : str
Log file name.
mode : str, optional
Bandpass stage. The default is 'INIT' that is all stages.
Returns
-------
res ... | 2a323067ace8b8f2965be5ac69d16206a5b93cf3 | 34,266 |
import os
def parse_error():
"""
Find undefined label errors
"""
if os.path.isfile('final.error'):
addrs = []
with open("final.error") as ferror:
for l in ferror:
if 'In function' in l: pass
elif 'undefined reference' in l and 'S_0x' in l:
... | fe8155529039183401cd1ce33337f30146b99755 | 34,267 |
import re
def _remove_phrasing(ipt_txt, phrase, replacement):
"""
removes the given phrase and replaces it with the replacement
:param ipt_txt: string to change
:param phrase: unwatned phrase to be removed
:param replacement: replacement phrase
:return: string with the phrase replaced with rep... | 9b36a46f28c222d44b7b5290e0c02dded81562f7 | 34,270 |
from typing import Tuple
from typing import Optional
def get_dbt_prefix_config(config) -> Tuple[Optional[str], Optional[str]]:
"""
Return (bucket, prefix) tuple
"""
if config.dbtPrefixConfig:
return (
config.dbtPrefixConfig.dbtBucketName,
config.dbtPrefixConfig.dbtObjec... | 762e8afc8b40db49d8fa115b33a0cfc69ea038ac | 34,271 |
def isUsdCrate(path):
""" Check if a file is a USD crate file by reading in the first line of
the file. Doesn't check the file extension.
:Parameters:
path : `str`
USD file path
:Returns:
If the USD file is a crate (binary) file.
:Rtype:
`bool`
"""
wi... | aa6bc6a94552f49b83f2a17239a061d7f0672950 | 34,272 |
def xml_escape(str):
"""Replaces chars ' " < > & with xml safe counterparts"""
if str is None:
return None
str = str.replace("&", "&")
str = str.replace("'", "'")
str = str.replace("\"", """)
str = str.replace("<", "<")
str = str.replace(">", ">")
return str | 8bec0fc289be43e84fba847d4d51bccb44df2839 | 34,273 |
def compare_bit_arrays(bit_array_1, bit_array_2):
"""
:param bit_array_1:
:type bit_array_1: BitArray
:param bit_array_2:
:type bit_array_2: BitArray
"""
if bit_array_1.length != bit_array_2.length:
return False, -1
equal_bits = 0
for bit_array_1_element, bit_array_2_element... | 239430184b2a727f0bd7551211989f73fd4a4dda | 34,274 |
def makeSquare(x, y, w, h):
""" Convert a rectangle ROI to square.
@param: left-most column
@param: top-most row
@param: width of region
@param: height of region
@return: x, y, w, h of the new ROI
"""
c_x = x + w // 2
c_y = y + h // 2
sz = max(w, h)
x = c_x - sz // 2
y... | c6b9cae46fbcb929511802ef125a808a81087e7f | 34,275 |
def make_relative(path: str, root_path: str) -> str:
"""Make path relative with respect to a
root directory
Arguments:
path (str): current path.
root_path (str): root directory path.
Returns:
str: relative path.
"""
r_path = path.replace(root_path, '')
if r_path:
... | 04e98d971a3b1ee0a698f4b082c8cb3529b60185 | 34,276 |
def count_missense_per_gene(lines):
""" count the number of missense variants in each gene.
"""
counts = {}
for x in lines:
x = x.split("\t")
gene = x[0]
consequence = x[3]
if gene not in counts:
counts[gene] = 0
if consequence !... | b20b7deca5b48af30378ee40ed03763069a45768 | 34,278 |
from typing import Mapping
def _get_full_name(artifact_id: int, name_from_id: Mapping[int, str]) -> str:
"""Converts the int-typed id to full string name."""
return name_from_id[artifact_id] | 4bfdee8c9123bef5c25225e8bea3d6488e9a24a7 | 34,280 |
import os
def model_path(*args):
"""Translate model path to file system path."""
return os.path.abspath(os.path.join(os.path.dirname(__file__), "../test/", *args)) | 236040ea6e8ca84081a64d2d5a1b57b4d7947ea2 | 34,281 |
def FourCharCode(fcc):
"""Create an integer from the provided 4-byte string, required for finding keychain items based on protocol type"""
return ord(fcc[0]) << 24 | ord(fcc[1]) << 16 | ord(fcc[2]) << 8 | ord(fcc[3]) | 51e71f6d27f3f1f4813e9208019f7238acd8940a | 34,283 |
import datetime as dt
def make_dates_ordinal(df, dates_column):
"""
This function converts the dates of a DataFrame column to integers, in order to easily fit the data to a regression model.
More specifically, the function toordinal() returns the proleptic Gregorian ordinal of a date.
In si... | 43b84eca8c9329d6c7598a506c2703122f2fb634 | 34,284 |
def generate_filename(in_path, out_dir, bitrate, encoder):
"""
Create a new filename based on the original video file and test bitrate.
Parameters
----------
in_path : str
Full path of input video.
out_dir : str
Directory of output video.
bitrate : int
Video bitrate ... | 6e8edb9a0bfd7e1c8ae779bd5c546f0f50389415 | 34,286 |
def preconvert_bool(value, name):
"""
Converts the given `value` to an acceptable boolean by the wrapper.
Parameters
----------
value : `int`
The value to convert.
name : `str`
The name of the value.
Returns
-------
value : `str`
Raises
------
... | d326f4d414a01f156e7ba1793d8f5a667a0e8b72 | 34,287 |
def get_pressed_button(mx, my, buttons):
"""Checking if the mouse is pressing a button"""
for button in buttons:
if button.x <= mx <= button.x + button.length and button.y <= my <= button.y + button.height:
return button
return None | 6ac49779b8b01f5a6ced1ae01e74f850843264a5 | 34,288 |
def _compare(data, k, threshold, sign=True):
"""
Obtain indicator vector for the samples with k-th feature > threshold
:param data: array-like of shape (n_sample, n_feat)
:param k: int
Index of feature in question
:param threshold: float
Threshold for the comparison
:param sign:... | 730582aa42dec9087de0d4869af42b3b47dd83e0 | 34,290 |
def get_cellId_from_hid(hid, rect_width):
"""
:type index: GridCellId
:type rect_width: int
:return:
"""
thid = hid.transpose(-(rect_width / 2), -(rect_width / 2))
cellId = thid.to_cell_id()
return cellId | a0cbc1813aa5eaed82ba6733692c4a8573da6953 | 34,291 |
def get_live_fs_dates(year, all_obs, fs_from):
"""Generate a forecast at the time of each observation."""
fs_dates = sorted(o['date'] for o in all_obs)
if fs_from is None:
# Return only the most recent forecasting date.
# Important: *must* be a list.
return [fs_dates[-1]]
else:
... | 89c6a217793fa921a5ed3407690b464e45466779 | 34,292 |
def lowest_dropped(grades):
"""
>>> g = ((30, 70, 80), (70, 30), (10, 80, 30))
>>> lowest_dropped(g)
"""
return [list(i).remove(min(i)) for i in grades] | fd6d50ce22abdf8209c8ab63e55476be654190bf | 34,295 |
def get_common_subpeptides(list1, list2):
"""Get intersection of two sub-peptide chain lists (chain names)"""
common_list = [sub_peptide for sub_peptide in list1 if sub_peptide in list2]
return common_list | fa088fa56c2e77cb252af26d7cc848e99bc5dd04 | 34,296 |
def simplefilter(lst, start=0, ss=1, num=50, **kw):
"""Given a set of parameters, filters the list."""
ret = []
for i, el in enumerate(lst[int(start):]):
if len(ret) >= int(num): break
if (i-start) % int(ss) != 0: continue
ret.append(el)
return ret | 4bf0a9fd35f30680a401680f16c9245ec774a4cf | 34,298 |
def trace_driven_cache_hit_ratio(workload, cache, warmup_ratio=0.25):
"""Compute cache hit ratio of a cache under an arbitrary trace-driven
workload.
Parameters
----------
workload : list or array
List of URLs or content identifiers extracted from a trace. This list
only needs to co... | f19da290fc4edf5284e8e52ff14ef60b2c59956b | 34,299 |
def _make_conn_info(self,dev1,port1,dev2,port2,dir='bi'):
""" Returns `switch_name` and ``conn_id`` if available.
and returns ``None`` if the connection stretches over multi optic
switches
"""
sw1 = self._intf_map[dev1.lower()][port1.lower()]['switch-name']
sw2 = self._intf_map[dev1.lower()][p... | 828bc1dcf24d61c6e1e25b892256e75b168f4d11 | 34,300 |
def handle_special_cases(command):
"""
Called by parse_commands.
This is here to separate the special-case manging from the rest of the
code.
"""
# These require the 'cid' param to be given twice for some reason.
if command.name in ('SearchRequest', 'NotFoundResponse'):
command = co... | 460ce2e99bec47c50d9488c0a1ddec5844ddd766 | 34,301 |
import subprocess
import click
def check_tool(tool,local,not_required_message=None):
"""
:param str tool: name of executable, e.g. 'cmake'
"""
completed_which = subprocess.run(['which', tool], capture_output=True, text=True)
which_string = completed_which.stdout.strip().replace('\n', ' ')
if c... | d9979e7e9cfe2a90fc363e790de5a1d4b76e5b96 | 34,303 |
def convert_to_bcd(decimal):
""" Converts a decimal value to a bcd value
:param value: The decimal value to to pack into bcd
:returns: The number in bcd form
"""
place, bcd = 0, 0
while decimal > 0:
nibble = decimal % 10
bcd += nibble << place
decimal /= 10
place... | ea8a950ac54065c8ae14230544c4e8c2d64a4bb6 | 34,307 |
def exclude_points_ranking(dataset):
"""
When we do ranking, none of the existing jobs should be added again
:param dataset:
:return:
"""
return dataset.datapoints | 3a08c90fad7b963fdb5a1a3ff7643c5902d1587c | 34,308 |
def create(element, target, cns_type, compensate=True):
"""
Creates a constraint on the given element, constraining it
against the given target.
:param element: The element to constrain
:type element: Host Specific
:param target: The element to constrain to
:type target: Host Specific
... | 3edcc76133a6e0ce6a4a3909e65b836920ee9f4f | 34,309 |
import argparse
def setup_cli(args):
""" Configure command-line arguements """
description = "outputs a list of domains between start and stop"
parser = argparse.ArgumentParser(description=description, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-s', '--start', action=... | ce1952d8144599d7037ac8e36c2d554edc1a9d84 | 34,310 |
def post_process_weird(system_mentions):
""" Removes all mentions which are "mm", "hmm", "ahem", "um", "US" or
"U.S.".
Args:
system_mentions (list(Mention): A list of system mentions.
Returns:
list(Mention): the filtered list of mentions.
"""
return sorted(
[mention for... | 4cc8198ff29768178859b6115d28dd958f8599be | 34,311 |
def parse_line(record):
"""
Parse the raw input of the data
"""
user_id, item_id, rating = record.split(',')
return int(user_id), int(item_id), int(rating) | 81f3ff6aa967cb8f5af776b33101eef77a4c470b | 34,313 |
def getCluster(self):
"""Get the HDInsight cluster object"""
# Get all the HDInsight clusters
hdinsight_clusters = self.hdinsight_client.clusters.list()
# Get current cluster
for hdinsight_cluster in hdinsight_clusters:
if hdinsight_cluster.name == self.params["CLUSTER_DNS_NAME"]:
... | a6dbd63c1e85db8893d32cbe12c01b5d9df5b350 | 34,315 |
def diff_files(listA, listB, exclude_attrs=[], mapA={}, mapB={}):
"""
Compute the diff of two lists for files, treating them as set-like.
"""
added = []
deleted = []
cleanlistA = []
for fileA in listA:
cleanfileA = fileA.copy()
for exclude_attr in exclude_attrs:
... | 8b23fa6fe5a24c3969cc5e17ad33b0f4271e921c | 34,316 |
import requests
def get_remaining_rate_limit(api_key: str) -> int:
"""
Returns your remaining rate limit by
making a request to
:ref:`Apod <extensions/apod:Apod>` and
getting the header ``X-RateLimit-Remaining``,
that's returned on every API response.
For example, if you are using an
... | 39a1b49ca9148a655cc90e25f8a1b8027f4821b5 | 34,318 |
import six
def is_iterable(x):
"""Determine whether ``x`` is a non-string iterable"""
if isinstance(x, six.string_types):
return False
return hasattr(x, "__iter__") | 38e1d8955c6114bd1dfa2b7b6acdbed7572b5212 | 34,319 |
def _is_fileobj(obj):
""" Is `obj` a file-like object?"""
return hasattr(obj, 'read') and hasattr(obj, 'write') | 8d09dce78239fe134116e641d4cf5934ffc173ec | 34,321 |
def ends_with_blank_line(block):
"""
Returns true if block ends with a blank line, descending if needed
into lists and sublists.
"""
if block.last_line_blank:
return True
if block.t in ['List', 'ListItem'] and block.children:
return ends_with_blank_line(block.children[-1... | 2b079351e69ad288ce17b9d42b5774814a97aed3 | 34,322 |
from typing import List
def person(word: str, parts: List[str]) -> str:
"""
Format a person name.
>>> person("foo", ["Aldous", "Huxley"])
'Aldous Huxley'
>>> person("foo", ["Théodore Agrippa d’", "Aubigné"])
'Théodore Agrippa d’ Aubigné'
>>> person("foo", ["Théodore Ag... | a910de33a2a599496b37848509765e956ae57b25 | 34,323 |
def clause_time(verb, api):
"""Look for an adjunctive Time element in the clause."""
L, F = api.L, api.F
clause_atom = L.u(verb, 'clause_atom')[0]
time_phs = [
p for p in L.d(clause_atom, 'phrase')
if F.function.v(p) == 'Time'
]
data = {'has_time': 0}
if time_phs:
... | 8a4ca0ac32970089e9a4d19dc029a91dfcc1512b | 34,324 |
def get_genus_count(genus_dict, blast_line, sci_name_column="15"):
"""this function count the distribution of the genus for the top hit"""
sci_name_column = int(sci_name_column)-1
scinetific_name = blast_line[sci_name_column]
try:
genus = scinetific_name.split()[0]
except:
return gen... | 2ed19b4accd959cb363cb4d7d40efe6b74ceae73 | 34,325 |
def people():
"""
<enumeratedValueSet variable="People"> <value value="500"/> </enumeratedValueSet>
Integer between 1 and 500
"""
people = 500
return f'<enumeratedValueSet variable="People"> <value value="{people}"/> </enumeratedValueSet>' | 1c42b254a1007d4fb1c3106ae1a66008a64b943c | 34,326 |
import pip
import site
def install_package(package):
"""Install a pip package to the user's site-packages directory."""
exitval = pip.main(['install', '--user', package])
if exitval == 0:
# Reload sys.path to make sure the user's site-packages are in sys.path
site.main()
return exitval... | 3c9781a290e84a2414ba28ea737a774e41dc49e1 | 34,327 |
def get_hit_table(hit):
"""Create context for a single hit in the search.
Args:
hit(Dict): a dictionary representing a single hit in the search.
Returns:
(dict).The hit context.
(list).the headers of the hit.
"""
table_context = {
'_index': hit.get('_index'),
... | 50a6d4b2304381b7cd9977213fb64f36d3485e80 | 34,328 |
def scaler(scale):
"""Create a function that scales by a specific value."""
def inner(val):
return val * scale
return inner | b2e9a8efb5f0aff079fbfaf8c5326978a6990660 | 34,329 |
from typing import Union
import re
def mask_cnpj(texto: str) -> Union[str, None]:
"""
Anonimização de CPF
"""
formatted_text = texto
pattern = '[0-9]{3}\.[0-9]{3}\.[0-9]{3}-[0-9]{2}'
cpfinder = re.compile(pattern)
if isinstance(texto, str):
is_cpf = cpfinder.findall(texto)
... | b2c5e822990dd8836431b6044f477cc3854f408a | 34,330 |
def _remove_empty_events(sse):
"""
Given a sequence of synchronous events (SSE) `sse` consisting of a pool of
pixel positions and associated synchronous events (see below), returns a
copy of `sse` where all empty events have been removed.
`sse` must be provided as a dictionary of type
.. cente... | 0596d43cc75fdd040c5096e3ddb81277b48d7456 | 34,332 |
import calendar
def utc_datetime_to_timestamp(dt):
"""
Converts datetime (UTC) to Unix timestamp
:type dt: datetime
:rtype: int
"""
return calendar.timegm(dt.utctimetuple()) | 2418293fe6ae7c95f2d541281e55a93f074699f9 | 34,333 |
def time_formatter(seconds: int, show: bool = True):
"""将以秒为单位的时间转化为相应的分钟、小时、天。
Args:
seconds: 秒数
show: 是否打印显示信息,默认为True,那么没有返回值,设置为False,不打印信息,但返回值
Returns:
若show为False,则有返回值,tuple中值的为天,小时,分钟,秒
"""
d = int(seconds // 86400)
h = int(seconds // 3600 % 24)
m = int((sec... | 9bb387a43a707843173fc71f25c4f1481e64ca49 | 34,334 |
def remove_comments(s):
"""removes the comments starting with # in the text."""
pos = s.find("#")
if pos == -1:
return s
return s[0:pos].strip() | 47e44d12f35c7b254f3f4ec001c630b5175b1e32 | 34,335 |
def mkcols(l, rows):
"""
Compute the size of our columns by first making them a divisible of our row
height and then splitting our list into smaller lists the size of the row
height.
"""
cols = []
base = 0
while len(l) > rows and len(l) % rows != 0:
l.append("")
for i in rang... | ce097db9e2737c959f9535d4b1464d4c3324c07e | 34,338 |
def get_substrings(string, n):
"""Return a list of substrings of lenght for the given string"""
substrings = set()
for i in range(len(string) - n + 1):
substrings.add(string[i:i+n])
return [substring for substring in substrings] | 1574e91875a753a20bcf292f1b86f1ae86ac2416 | 34,341 |
import re
def rmspecialchars(value):
"""
Remove any special characters except period (.) and negative (-) from numeric values
Parameters
----------
value : string
String value to remove any existing characters from
Returns
-------
value : string
String ... | 26de451a5cfef33f9384ce13bda9e495ae81fc5d | 34,342 |
import numpy
def Anscombe_Poisson_residual(model, data, mask=None):
"""
Return the Anscombe Poisson residuals between model and data.
mask sets the level in model below which the returned residual array is
masked. This excludes very small values where the residuals are not normal.
1e-2 seems to b... | 9ff4d116426f6846afc1853834826697b9b63327 | 34,343 |
def braille_bin(char: str) -> str:
"""Inverse of get_braille()"""
o = ord(char) - 0x2800
s = format(o, "b").rjust(8, "0")
s = s[::-1]
s = (
s[:3] + s[6] + s[3:6] + s[7]
) # rearrange ISO/TR 11548-1 dot order to something more suitable
return s | d5081e46a275b98d567e980ed58a97ed25275ffd | 34,344 |
import re
def remove_urls(text):
"""Remove urls from text"""
return re.sub('(https:|http:|www\.)\S*', '', text) | db7c2fa5e96ee525aa8c2d17ddf2888a354958f7 | 34,347 |
def get_config_rules_statuses(config):
"""Retrieves all of the AWS Config rules.
Args:
config: boto3 config object
Returns:
List of AWS Config rules
"""
config_rules = []
page_iterator = config.get_paginator("describe_compliance_by_config_rule")
for page in page_iterator.p... | 7c3ec7281d06966fb97193274fc62465e8910d08 | 34,348 |
def check_params(params, field_list):
"""
Helper to validate params.
Use this in function definitions if they require specific fields
to be present.
:param params: structure that contains the fields
:type params: ``dict``
:param field_list: list of dict representing the fields
... | 8ce0ad0123c3dfed278564b6cd7fdb8545fdc7a7 | 34,349 |
def resolve_attr(obj, path):
"""A recursive version of getattr for navigating dotted paths.
Args:
obj: An object for which we want to retrieve a nested attribute.
path: A dot separated string containing zero or more attribute names.
Returns:
The attribute referred to by obj.a1.a2.a... | 3951e8436b2e51f7f2815ea0ed2bda35a8fc08ce | 34,350 |
def __red_blue_pixel_filter(pixel):
"""This method applies the filter defined above to a pixel
Returns an int value (255 or 0) as the result of applying the filter
to teh pixel. If the received pixel is transparent returns 0.
"""
white_pixel = 255
black_pixel = 0
red_band_value = pixel[0]
... | 66988554726d99bdbc1eb8a75bb64947b45356af | 34,351 |
def column_to_list(data, index):
"""
Função para adicionar as colunas(features) de uma lista em outra lista, na mesma ordem.
Argumentos:
data: amostra de dados.
index: índice da coluna na amostra.
Retorna:
Uma lista apenas com os dados da coluna informada no index.
"""
co... | 55c8201e72234af57289d546078953aa07f3f1bb | 34,353 |
import sys
def rich_print(*values, **kwargs):
"""A print function allowing bold, italics, and colour, if stdout.write or
stderr.write supports a 'charformat' keyword argument and is connected to a
qtutils.OutputBox. This method accepts the same arguments as the Python print
function, as well as keywor... | 1e4f322595250053b46c28cc370bd1564b9f1bc1 | 34,354 |
from typing import Dict
from typing import Any
def get_mesh() -> Dict[str, Any]:
"""Front-end call."""
return {} | 1bffe4ca7efd1358aa5343749851f4aa05921855 | 34,355 |
def tral_file_filter(file):
"""In file, check whether there are TRs that belong to the same protein and have the same starting amino acid.
This should never occur and these instances are therefore considered duplicates.
Paramters
file (str): Merged TRAL output file that will be checked for duplicates
... | f84e575d0ce0e4ebf850a97b0249261cfa495cae | 34,358 |
def run(*args, **kwargs):
"""
模型函数,计算分值用的.
:param args:
:param kwargs:
:return:
"""
return (args, kwargs) | ed8735f0608a1455f58140057a20d2e7a48b95b1 | 34,359 |
from functools import reduce
def clean(puzzle):
"""Format a given puzzle into the form {name: claim}."""
def clean_claim(claim):
"""Strip uninformative leading words from a given claim."""
rm_claims_comma = lambda x: x.split("claims, ")[1] if "claims, " in x else x
rm_claims_that = lam... | 6c2afd9cad86b235df3005622457dc2b5b6f946d | 34,360 |
def selection_sort(nums: list[float]) -> list[float]:
"""Sorts a list in-place using the Selection Sort approach.
Time complexity: O(n^2) for best, worst, and average.
Space complexity: total O(n) auxiliary O(1).
Args:
nums: A list of numbers.
Returns:
The sorted list.
"""
... | c96c12e7361e6b617528b9cc632b4003963ea8ab | 34,361 |
def canConstruct(ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
for i in set(ransomNote):
if ransomNote.count(i) > magazine.count(i):
return False
return True | aa9159bfdc26d34e56f621bab02cd781200e0594 | 34,362 |
import itertools
def get_pwdist_indices(sequences):
"""
From a list of sequences get lower triangle indices tuples (i,j)
for pairwise comparisons.
Parameters
----------
sequences : list of strings
list of (likely amino acid) strings
Returns
-------
ind_tuples : list
... | f9ab2bbcc4481f898ff83963ad595240b95ad2b2 | 34,363 |
def shot_direct_neighbors(graph, reconstruction, shot_id):
"""Reconstructed shots sharing reconstructed points with a given shot."""
neighbors = set()
for track_id in graph[shot_id]:
if track_id in reconstruction.points:
for neighbor in graph[track_id]:
if neighbor in rec... | 9b7ff5689aa32c30b85d62e535feab15ca6916e9 | 34,365 |
def fix_iso(job):
"""
Add couple xyz to the fix_ensemble inside LAMMPS
Args:
job (LAMMPS): Lammps job object
Returns:
LAMMPS: Return updated job object
"""
job.input.control["fix___ensemble"] = (
job.input.control["fix___ensemble"] + " couple xyz"
)
return job | 376bfb69abc2d59f42e766f4c9bda198468046ee | 34,366 |
def max_rectangle_area(histogram):
"""Find the area of the largest rectangle that fits entirely under
the histogram.
"""
stack = []
top = lambda: stack[-1]
max_area = 0
pos = 0 # current position in the histogram
for pos, height in enumerate(histogram):
start = pos # position ... | 603696f0a358019e54381d9a269b0bde0badf1a2 | 34,367 |
def get_version_v2(uri):
"""
Canned response nova v2 version.
Cf: http://developer.openstack.org/api-ref-compute-v2.1.html
#listVersionsv2.1
"""
return {"version":
{"status": "SUPPORTED",
"updated": "2011-01-21T11:33:21Z",
"links": [{"href": uri,
... | a34b5a0e1ee3e055dd3e559e9e4a79f611654414 | 34,368 |
def number_of_peaks(ds):
"""
Number of peaks found in smoothed waveform, directly from GLAH14 data
"""
return ds.n_peaks | 29ba960cca162526a4fd5c01794ee84be6c93a75 | 34,369 |
def read_iba_file(file_path):
"""
:param file_path: absolute file path
:return: a list of strings, each item being a row in the text file
:rtype: list
"""
f = open(file_path, 'r')
text = f.read()
return text.replace('\r', '').split('\n') | f536f2b2d520799fe4f81825055315ed3a1f9d6d | 34,370 |
def format_messages(messages_dict):
""" Formats input messages in Polymer format to native Android format. This means replacing
hyphens with underscores in keys and escaping apostrophes in values. """
formatted_messages = {}
for k,v in messages_dict.items():
formatted_messages[k.replace("-", "_")] = v.r... | 00fe6bfb76ce8e146a16a3bc3f108fc2d1277908 | 34,372 |
from functools import reduce
def getAllTextWords(texts):
""" Returns a set of all the words in the given texts """
return reduce(lambda x,y: x | set(y), texts.values(), set()) | 52e475b180031b0abf67bad3fe148b9509baaed1 | 34,375 |
import sys
import os
def file_is_available(filename):
"""
Checks if a file is in use by another process
https://stackoverflow.com/a/37256114/2302759
The SO thread also includes solutions for Linux.
"""
if not sys.platform == "win32":
raise Exception("`check_if_file_is_available` is on... | a93775afa70ddd74c273ca6d3b147cb686e23d10 | 34,376 |
def get_tensor_dependencies(tensor):
"""
Utility method to get all dependencies (including placeholders) of a tensor (backwards through the graph).
Args:
tensor (tf.Tensor): The input tensor.
Returns: Set of all dependencies (including needed placeholders) for the input tensor.
"""
dep... | 1c92b9fda9e5ca563bc43638f74f09c0bc16f264 | 34,378 |
def _get_vals_wo_None(iter_of_vals):
""" Returns a list of values without Nones. """
return [x for x in iter_of_vals if x is not None] | e020ec4049217c5656c74bed6d20bfcdb8a89e78 | 34,379 |
import pandas as pd
import os
def load_plot_data(attack_name):
"""
reads data saved with log_plot_data
:param attack_name: string of attack name (the folder to read from)
:return: a pandas dataFrame containing plot data.
"""
path = os.path.join('Attack Logs', attack_name, 'plot_data')
df =... | db95cf9c2d79b23f0f53015aa35a24fefd3aa65c | 34,380 |
def ao_ordering(l):
"""list of Cartesian basis function with angular momentum l"""
if l == 0:
return [(0,0,0)]
elif l == 1:
return [(1,0,0), (0,1,0), (0,0,1)]
elif l == 2:
# ordering of d-functions in TeraChem: dxy,dxz,dyz,dxx,dyy,dzz
return [(1,1,0), (1,0,1), (0,1,1), (2... | 8252fa918f9a312d2d8f34e1d50964ff2994b262 | 34,382 |
def read_rescue(spark):
"""
Reads animal rescue CSV data from HDFS
Args:
spark (SparkSession): active Spark session
Returns:
spark DataFrame: animal rescue data
"""
return spark.read.csv("/training/animal_rescue.csv",
header=True, inferSch... | 6260b6914e2b1d8747791a1b2531793cd3c82781 | 34,384 |
import torch
def process_ckp(ckp_path):
"""Hack that enables checkpointing from mid-epoch."""
if not ckp_path:
return ''
if ckp_path == '.pl_auto_save.ckpt':
return ''
ckp = torch.load(ckp_path, map_location='cpu')
for key in ckp['loops']['fit_loop'][
'epoch_loop.val_lo... | 5947f63a52f2aff96dacaea19b2ede1064daf8ba | 34,385 |
def to_bool(val):
"""Conservative boolean cast - don't cast lists and objects to True, just existing booleans and strings."""
if val is None:
return None
if val is True or val is False:
return val
if isinstance(val, str):
if val.lower() == 'true':
return True
... | 21934eb7ab28d53e2c415da988eee2cd3af2d2cc | 34,386 |
def get_shm_dir():
"""Get shm dir for temporary usage."""
return '/dev/shm' | 9280aa8b751e2c20307b09ad76d4720e82e5904f | 34,387 |
def node_value(node, input_values, neuron_outputs): # PROVIDED BY THE STAFF
"""
Given
* a node (as an input or as a neuron),
* a dictionary mapping input names to their values, and
* a dictionary mapping neuron names to their outputs
returns the output value of the node.
This function d... | 4088211ce025b6e868c1a9ecffdd7955d5adf168 | 34,389 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.