content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def batchify(X, size):
"""
```
Splits X into separate batch sizes specified by size.
Args:
X(list): elements
size(int): batch size
Returns:
list of evenly sized batches with the last batch having the remaining elements
```
"""
return [X[x : x + size] for x in rang... | 52,500 |
def _single_entity_stmt(
start_day: dt,
end_day: dt,
event_types: tuple[str, ...],
entity_id: str,
entity_id_like: str,
) -> StatementLambdaElement:
"""Generate a logbook query for a single entity."""
stmt = lambda_stmt(
lambda: _select_events_without_states(start_day, end_day, event... | 52,501 |
def initialize_db_values(db):
""" Initialize the values in the DB that can be used throughout the tests """
# Zips
zip_code_1 = ZipsFactory(zip5='12345', zip_last4='6789', state_abbreviation='NY', county_number='001',
congressional_district_no='01')
zip_code_2 = ZipsFactory(... | 52,502 |
def listtoslides(data):
"""Checks if format is correct + adds img and durration elements"""
slides = []
for slide in data:
slide = slide[:2]
slide[0] = slide[0][:25]
slide[1] = slide[1][:180]
slide.append("imgpath")
slide.append(0)
slides.append(slide)
ret... | 52,503 |
def clean_data(sample):
"""
整体清洗函数,为了方便多线程使用
Args:
sample: 一个元组,包含正文内容和标题内容
Returns:
"""
(content, title) = sample
sample = dict()
# 清洗数据
sample["title"] = clean_weibo_title(title.strip())
sample["content"] = clean_weibo_content(content.strip())
return sample | 52,504 |
def read_cat_as_dataframe(fichero_cat, tipo_registro, columns=None):
"""
Devuelve un pandas.DataFrame con los registros del el tipo deseado
- fichero_cat: fichero .cat, puede estar comprimido.
- tipo_registro: Tipo de registro, p.ej.: '11', '15'
- columns: Lista con los nombres de l... | 52,505 |
def init_cppn_from_img(image: np.array, color: bool = True, sim_threshold: float = 0.6, max_optim_iter: int = 10000,
init_stop_bound: int = 100) -> CPPN:
"""
Initializes a CPPN using the given image by optimizing the SSIM score between the CPPNs output and the image.
This is done by t... | 52,506 |
def unwind_create_nodes_query(data, labels=None, keys=None):
""" Generate a parameterised ``UNWIND...CREATE`` query for bulk
loading nodes into Neo4j.
:param data:
:param labels:
:param keys:
:return: (query, parameters) tuple
"""
return cypher_join("UNWIND $data AS r",
... | 52,507 |
def ZipHunks(rhs_hunks, lhs_hunks):
"""Join two hunk lists on filename."""
for rhs_hunk in rhs_hunks:
rhs_file = rhs_hunk.right.filename.split("/")[1:]
for lhs_hunk in lhs_hunks:
lhs_file = lhs_hunk.left.filename.split("/")[1:]
if lhs_file != rhs_file:
co... | 52,508 |
def test_redo_last_action():
"""Tests redoing a project back to its final state."""
project = models.Project.create(DummyLoader())
# Mock an action, undo, and redo
for frame in project.label_frames:
frame.frame[:] = -1
project.create_memento('last_action')
project.update()
# Save act... | 52,509 |
def test_authorization_header(sut: SystemUnderTest):
"""Perform tests for Assertion.REQ_HEADERS_AUTHORIZATION."""
response = sut.get_response('GET', sut.sessions_uri,
request_type=RequestType.BASIC_AUTH)
if response is None:
msg = ('No response using a basic authentic... | 52,510 |
def _scalePoints(points, scale=1, convertToInteger=True):
"""
Scale points and optionally convert them to integers.
"""
if convertToInteger:
points = [
(int(round(x * scale)), int(round(y * scale)))
for (x, y) in points
]
else:
points = [(x * scale, y ... | 52,511 |
def skewness(values):
"""Calculates the skewness given a sequence of values.
Skewness is a measure of the degree of asymmetry of a distribution
of the mean. If skewed to the left, the distribution has a long tail
in the negative direction. If skewed to the right, the tail will be
skewed in the posi... | 52,512 |
def get_customer_tax_rate(request, product):
"""Returns the specfic customer tax for the current customer and product.
"""
cache_key = 'cached_customer_tax_rate_%s' % product.pk
if request and hasattr(request, cache_key):
return getattr(request, cache_key)
customer_tax = get_first_valid(requ... | 52,513 |
def test_no_metadata_json(mp_tmpdir, cleantopo_br_tiledir):
"""Read raster data."""
# prepare data
with pytest.raises(MapcheteDriverError):
mapchete.open(
dict(cleantopo_br_tiledir.dict, input=dict(file1="tmp/cleantopo_br"))
) | 52,514 |
async def _log_exception(aw):
"""
Log any exceptions that happen while running this awaitable
"""
try:
await aw
except Exception:
logger("Exception raised")
logger(traceback.format_exc())
raise | 52,515 |
def iscoroutinepartial(coro):
"""
Function returns True if function it's a partial instance of coroutine. See additional information here_.
:param coro: Function
:return: bool
.. _here: https://goo.gl/C0S4sQ
"""
while True:
parent = coro
coro = getattr(parent, 'func', No... | 52,516 |
def write_key(key):
"""Write the key to a file so it can me used to make a secure connection.
To enhance security a bit, the file is firstly opened, written, closed,
chmodded to enhance security a bit, and then the key is written to the file.
string key
return string path_to_key"""
# Register... | 52,517 |
def AppendFchunk(funcea, ea1, ea2):
"""
Append a function chunk to the function
@param funcea: any address in the function
@param ea1: start of function tail
@param ea2: end of function tail
@return: 0 if failed, 1 if success
@note: If a chunk exists at the specified addresses, it... | 52,518 |
def testing_audio():
"""Load data for the tests."""
return sf.read(TEST_WAVEFILE_PATH, always_2d=True, dtype='float32') | 52,519 |
def linr(xdata, ydata):
"""Return the linear regression coefficients a and b for (x,y) data.
Returns the y-intercept and slope of the straight line of the least-
squared regression line, that is, the line which minimises the sum of
the squares of the errors between the actual and calculated y values.
... | 52,520 |
def test_update_metadata_success(db_session, make_workspace, upload_file, mocker):
"""Update metadata success conditions"""
mocker.patch('flask_principal.Permission.can', return_value=True)
workspace = make_workspace(families={'base': 0, 'other': 0})
file_id = upload_file(workspace=workspace)
new_m... | 52,521 |
def album_sticker_get(client, album, sticker):
"""Gets a sticker associated with an album."""
# I am pretty sure that MPD only implements stickers for songs, so
# the sticker gets attached to the first song in the album.
tracks = client.find("album", album)
if len(tracks) == 0:
return
... | 52,522 |
def print_confusion_matrix(confusion_matrix, class_names, filename, normalize = True, figsize = (5,5), fontsize=16):
"""Prints a confusion matrix, as returned by sklearn.metrics.confusion_matrix, as a heatmap.
Arguments
---------
confusion_matrix: numpy.ndarray
The numpy.ndarray object retu... | 52,523 |
def parse_zpe(path: str) -> Optional[float]:
"""
Determine the calculated ZPE from a frequency output file
Args:
path (str): The path to a frequency calculation output file.
Returns: Optional[float]
The calculated zero point energy in kJ/mol.
"""
if not os.path.isfile(path):
... | 52,524 |
def group():
""" RESTful CRUD controller """
tablename = "pr_group"
table = s3db[tablename]
response.s3.filter = (table.system == False) # do not show system groups
s3mgr.configure("pr_group_membership",
list_fields=["id",
"person_id",
... | 52,525 |
def colorization_inference(model, img):
"""Inference image with the model.
Args:
model (nn.Module): The loaded model.
img (str): File path of input image.
Returns:
np.ndarray: The predicted colorization result.
"""
# cfg = model.cfg
device = next(model.parameters()).de... | 52,526 |
def std_ver_minor_mixedinst_valid_fullsupport(request):
"""Return an valid minor version number that has full support in pyIATI.
Todo:
Add decimal representations where possible.
"""
return request.param | 52,527 |
def send_keys(session, keys, literal=True):
"""Send keys to a tmux session.
This function is a wrapper around tmux's ``send-keys`` command.
If ``literal`` is ``False``, tmux will attempt to convert keynames such as
``Escape`` or ``Space`` to their single-key equivalents.
:param session: name of a ... | 52,528 |
def test_done_callback_gets_outcomes(testdir):
"""The done callback is passed the outcomes with the Trio entry filled."""
test_file = r"""
import outcome
import qtrio
def test():
result = {}
async def main():
return 93
def done_callback(outcomes):
... | 52,529 |
def load_templates_from_dir(directory: str) -> Environment:
"""Produce an Environment targeted at a directory."""
return Environment(loader=FileSystemLoader(directory)) | 52,530 |
def merge_schemas(a, b, path=None):
"""Recursively zip schemas together
"""
path = path if path is not None else []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_schemas(a[key], b[key], path + [str(key)])
elif ... | 52,531 |
def resample_dataarray2d_to_vertex_grid(da_in, gridprops=None,
xyi=None, cid=None,
method='nearest',
**kwargs):
"""resample a 2d dataarray (xarray) from a structured grid to a new
dataaraay of... | 52,532 |
def parse_arguments():
"""
Basic argument parsing using python's argparse
return: Argparse parser object
"""
parser = argparse.ArgumentParser("Rfam fasta file generation handler")
parser.add_argument('--seq-db', help="Sequence database in fasta format",
action="store",... | 52,533 |
def actuator(config_path: str, execute_type: str) -> NoReturn:
"""
:param config_path: 配置json文件路径
:param execute_type: 执行类型
"""
with open(config_path, "r", encoding="utf-8") as file:
options = json.load(file)
# 这里在日志文件里面做一个执行分割
key = int(datetime.now().timestamp())
logger.info("... | 52,534 |
def load_alexa(limit=None, is_test=False):
"""
Reads top @limit number of popular domains based on alexa.com
"""
alexa_domains = set()
alexa_top_1m = data_folder
if not path.exists(alexa_top_1m):
if is_test:
alexa_top_1m = fetch_alexa_data(url=top_100_alexa)
else:
... | 52,535 |
def an_capabilities(b: bytes) -> list:
""" Decode autonegotiation capabilities
Args:
b: coded ***
Returns:
human readable ***
"""
cap: list = []
i: int = (b[0] << 8) + b[1]
cap_list = ['1000BASE-T (full duplex mode)',
'1000BASE-T (half duplex mod... | 52,536 |
def peer_count(interface_name: str) -> int:
"""Number of peers in the mesh"""
with mesh_client() as client:
return len(client.getPeers(interface_name)) | 52,537 |
def signature_info_v2(args):
""" Validates the signature block and prints the rsa public key digest for valid blocks """
SECTOR_SIZE = 4096
SIG_BLOCK_MAX_COUNT = 3
SIG_BLOCK_SIZE = 1216 # Refer to secure boot v2 signature block format for more details.
image_content = args.datafile.read()
if l... | 52,538 |
def illustrate_bfs_in_graph():
"""Create a gif to illustrate breadth-first search in a graph."""
images_paths = []
M, G = init_adjacency_matrix_with_a_graph()
def step(highligth_value):
"""One step in the algorithm."""
nonlocal images_paths, G
highlight_node(G, highligth_value, ... | 52,539 |
def german_words():
"""Provides same known words list as used by the main script."""
return get_dictionary(language="de") | 52,540 |
def get_source_feed_from_folder_name(dir_path):
"""
get_source_feed_from_folder_name
Get source feed from tf record name
:param dir_path: TFRecord folder name
:return: Source feed name
"""
if os.path.isdir(dir_path):
dir_name = os.path.basename(dir_path)
source_feed = dir_... | 52,541 |
def result():
"""Get results when ready regarding a previously submitted task."""
# Retrieve JSON parameters data.
data = request.get_json() or {}
data.update(dict(request.values))
tid = data.get("tid")
if not tid:
raise abort(400, "missing 'tid' data")
# Get the result (if exists a... | 52,542 |
def pushWPStoArray(aln, halfWPSwindow, start, end, tssWindow, isize, wpsWindow):
"""
for a given alignment, compute the regions that can be fully aligned and not
e.g. [-1, -1 , -1, 1 , 1, 1, 1, 1, 1, -1, -1, -1] for a wps window -f 6 (halfwindow 3 )
this will be added to the defined transcription start ... | 52,543 |
def stdout_handler(level: int = logging.INFO) -> logging.Handler:
"""標準出力用ログハンドラ."""
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(level=level)
formatter = logging.Formatter(
"[%(asctime)s] [%(process)d] [%(name)s] [%(levelname)s] %(message)s"
)
handler.setFormatter(forma... | 52,544 |
def usgs_lithium_parse(*, df_list, source, year, **_):
"""
Combine, parse, and format the provided dataframes
:param df_list: list of dataframes to concat and format
:param source: source
:param year: year
:return: df, parsed and partially formatted to flowbyactivity
specifications
"... | 52,545 |
def plot_voronoi_polys_with_points_in_area(ax, area_shape, poly_shapes, points, poly_to_pt_assignments=None,
area_color='white', area_edgecolor='black',
voronoi_and_points_cmap='tab20',
voron... | 52,546 |
def convert_keys_to_string(dictionary):
""" Recursively converts dictionary keys to strings.
Utility to help deal with unicode keys in dictionaries created from json requests.
In order to pass dict to function as **kwarg we should transform key/value to str.
"""
if isinstance(dictionary, bas... | 52,547 |
def detectron2_available() -> bool:
"""
Returns True if Detectron2 is installed
"""
return bool(_DETECTRON2_AVAILABLE) | 52,548 |
def triplot(vertices, indices, labels=False):
"""
Plot a 2D triangle mesh
"""
vertices,indices = asarray(vertices),asarray(indices)
#3d tensor [triangle index][vertex index][x/y value]
triangles = vertices[numpy.ravel(indices),:].reshape((indices.shape[0],3,2))
col = matplotlib.co... | 52,549 |
def delete_user_by_id_and_name(id):
""" username 或者id 删除用户 """
user = User.query.filter(or_(User.id.like(id), User.username.like(id))).first_or_404()
user.delete()
return user | 52,550 |
def delete_annotations(event, key, namespace=None, matchfunc=None):
"""Delete all event annotations with a matching key."""
if matchfunc is None:
matchfunc = _is_equal
if isinstance(key, Exception):
key = _error_repr(key)
newanns = [ann for ann in event.get("_humilis", {}).get("annotatio... | 52,551 |
def branch(default='master'):
"""used in the `git.latest` state for the `branch` attribute.
If a specific revision exists DON'T USE THE BRANCH VALUE.
There will always be a branch value, even if it's the 'master' default"""
if cfg('project.revision'):
return '' # results in a None value for git... | 52,552 |
def instance_types(gvar):
"""
List EC2 instance types for the specified cloud.
"""
mandatory = ['-cn']
required = []
optional = ['-CSEP', '-CSV', '-g', '-H', '-h', '-itc', '-itf', '-itmn', '-itmx', '-itos', '-itp', '-itpm', '-NV', '-ok', '-r', '-s', '-V', '-VC', '-v', '-v', '-x509', '-xA', '-w'... | 52,553 |
def math_logsumexp(data):
"""
achieve logsumexp by numpy
Args:
data: float array
Returns:
Float
"""
res = []
for i in data:
res.append(math.exp(i))
return math.log(sum(res)) | 52,554 |
def only_numbers(iterable):
"""Returns whether the given iterable contains numbers (or strings that
can be converted into numbers) only."""
return not any(lenient_float(item) is None for item in iterable) | 52,555 |
def gaussian(birth, pers, mu=None, sigma=None):
""" Optimized bivariate normal cumulative distribution function for computing persistence images using a Gaussian kernel.
Parameters
----------
birth : (M,) numpy.ndarray
Birth coordinate(s) of pixel corners.
pers : (N,) numpy.ndarray
... | 52,556 |
async def subject(
loop: asyncio.BaseEventLoop, bus_channel: str
) -> AsyncGenerator[CanDriver, None]:
"""The can driver under test."""
driver = await CanDriver.build(channel=bus_channel, interface="virtual", bitrate=0)
yield driver
driver.shutdown() | 52,557 |
def login():
"""
TASKS: write the logic here to parse a json request
and send the parsed parameters to the appropriate service.
return a json response and an appropriate status code.
"""
data = request.get_json()
user = User.objects(username=data.get('username')).first()
... | 52,558 |
def server_reachable_by_credentials_with_retry(server_url, user, password):
"""
@param server_url: Basic server url to connect and log in
@param user: User for Ambari REST API authentication
@param password: Password for the user used to authenticate the Ambari REST API call
"""
retry_counter = 0
out = No... | 52,559 |
def _process_rules_list(rules, match_rule):
"""Recursively walk a policy rule to extract a list of match entries."""
if isinstance(match_rule, policy.RuleCheck):
rules.append(match_rule.match)
elif isinstance(match_rule, policy.AndCheck):
for rule in match_rule.rules:
_process_ru... | 52,560 |
def get_memoryview_and_address(data):
"""Get a memoryview for the given data and its memory address.
The data object must support the buffer protocol.
"""
# To get the address from a memoryview, there are multiple options.
# The most obvious is using ctypes:
#
# c_array = (ctypes.c_uint8 ... | 52,561 |
def get_inv_dist_mat(node_list):
"""
Get pairwise distance matrix for specified nodes in node list.
Args:
node_list (list): Nodes for which to compute the pairwise distances
Returns:
(numpy.ndarray): Matrix of pairwise distances
"""
# Initialize array.
dist_mat = np.ze... | 52,562 |
def generate(template_type: str, output: IO):
"""Generate a template.
OUTPUT : Where to write the template?
\f
:param str template_type: The type of template to generate.
:param str output: Where to write the template?
"""
template = _TEMPLATES[template_type].build()
output.write(templ... | 52,563 |
def stableSoftMax(x):
"""
stableSoftMax computes a normalized softmax
:param x: Tensor List
:return: Tensor List
"""
x = torch.exp(x - torch.max(x))
return x/torch.sum(x) | 52,564 |
def draw_arrow(image, x, y, options, forward):
"""
Draws an arrow at the specified position.
"""
width, height = size_of_arrow(options)
line_pos = height / 2
indent = options.raildraw_arrow_indent * width
if forward:
image.move_to(x, y + line_pos)
image.line_to(x + indent, y ... | 52,565 |
def is_item(var):
"""
is this a single item
"""
return is_str(var) or (not is_iterable(var)) | 52,566 |
def _str_plot_fields(val, f, field_filter):
"""
get CSV representation of fields used by _str_plot
:returns: list of fields as a CSV string, ``str``
"""
s = _sub_str_plot_fields(val, f, field_filter)
if s is not None:
return "time,"+s
else:
return 'time,' | 52,567 |
def cypher_repr(value, **kwargs):
""" Return the Cypher representation of a value.
This function attempts to convert the supplied value into a Cypher
literal form, as used in expressions.
"""
encoder = CypherEncoder(**kwargs)
return encoder.encode_value(value) | 52,568 |
def compareResultByTimeTupleRangesAndFlags(result, check, dateOnly=False):
"""
Ensures that flags are an exact match and time tuples a close match when
given data in the format ((timetuple), (timetuple), flag)
"""
return (_compareTimeTuples(result[0], check[0], dateOnly) and
_compareTime... | 52,569 |
def check_valid_title(title):
"""Checks if the title contains valid content"""
title_issues = TitleIssues(title_contains_nsfw=title_contains_nsfw(title))
return title_issues | 52,570 |
def ValueWidget(value: Any = None, on_value: typing.Callable[[Any], Any] = None) -> Element[ipywidgets.widgets.valuewidget.ValueWidget]:
"""Widget that can be used for the input of an interactive function
:param value: The value of the widget.
"""
kwargs: Dict[Any, Any] = without_default(ValueWidget, lo... | 52,571 |
def list_all_volumes():
"""Lists all available issues and volumes from the VA registry webpage. Only returns
volumes that are available on HTML.
Returns
-------
volumes : dict
A dictionary where the volumes are the keys and the issues are list entries.
"""
volumes = set()
html =... | 52,572 |
def get_distribution(dist):
"""Return a PyMC distribution."""
if isinstance(dist, str):
if hasattr(pm, dist):
dist = getattr(pm, dist)
else:
raise ValueError(f"The Distribution '{dist}' was not found in PyMC")
return dist | 52,573 |
def schedule(func, arg) -> Any:
"""
Schedule the function *func* to be executed "very soon". The function
is passed the value *arg* as its single argument. "Very soon" means that
the MicroPython runtime will do its best to execute the function at the
earliest possible time, given that it is also t... | 52,574 |
def enforce_cpp_formatting(
filename: str, contents: str, cursor: int, fix_issues: bool) -> int:
"""
Validator function that tests whether the style of the C++
source file follows that dictated by `.clang-format`.
"""
# Opening a pipe with Clang format
p = subprocess.Popen(
[CLA... | 52,575 |
def login_required(f):
"""
Validates the JWT and ensures that is has not expired and the user is still active.
:param f:
:return:
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not request.headers.get("Authorization"):
response = jsonify(message="Missing auth... | 52,576 |
def divisors(num: int, *, start: int = 2, ordered: bool = False, step: int = 1) -> Iterator[int]:
"""
Get all number divisors starting from start.
Faster (sqrt(n) operations) than scanning all numbers using:
divisors = (i for i in range(start, n) if n % mod i == 0).
:param step: step for verifyi... | 52,577 |
def test_left_child_index_from_parent_six(binheap_full_sorted):
"""."""
assert binheap_full_sorted._left_child_index_from_parent(6) == 13 | 52,578 |
def single__intent_topk_accuracy_score(
intent_prediction: List[Dict[str, str]],
y_true: List[str],
k: int = 1,
) -> float:
"""Compute the Accuracy of a single utterance with multi-intents
Accuracy of a single utterance is defined as the proportion of
correctly predicted labels ... | 52,579 |
def safeCellValue(cell, level=warning):
"""
셀 객체로부터 값을 안전하게 얻기 위한 함수
- 안전하지 않은 경우, 공백 문자열을 반환
"""
cellType = type(cell)
if cellType is openpyxl.cell.Cell or cellType is ReadOnlyCell:
noneSpaceString = str(cell.value).strip()
if noneSpaceString not in kIgnoreCharacters:
return noneSpaceString
... | 52,580 |
def _get_port(config):
"""Get the server's port from configuration."""
if not config.has_option("server", "port"):
return None
port = config.getint("server", "port")
return port | 52,581 |
def _get_recursively(zoo_client, path, nodes):
"""get zookeeper nodes recursively
"""
try:
data, _ = zoo_client.get(path)
except NoNodeError as exc:
log.warning("No node exists in path: %s", path)
else:
nodes.append({"path": path, "data": data})
for child in zoo_clien... | 52,582 |
def add_rectangular_plane(
center_loc=(0, 0, 0), point_to=(0, 0, 1), size=(2, 2), name=None):
"""Adds a rectangular plane specified by its center location, dimensions,
and where its +z points to.
Args:
center_loc (array_like, optional): Plane center location in world
coordinates... | 52,583 |
def locations_3d_to_view(locations, extrinsic_matrix, intrinsic_matrix):
""" Transforms 3D locations to 2D camera view."""
world_points = np.ones((4, len(locations)))
for i in range(len(locations)):
world_points[0][i] = locations[i].x
world_points[1][i] = locations[i].y
world_points... | 52,584 |
def superkeyword_presence(document, superkeywords):
"""Return 1 if document contains any superkeywords, 0 if not."""
for word in superkeywords:
if word in document.split():
return True
return False | 52,585 |
def runTest(numClients, numServers, scripts, numFailures, runIndex):
"""
Run a single test of the Fault Tolerant SimpleFileLockService
This takes numClients, numServers, and the test scripts to run.
It SSHs into the requested number of servers and starts up the
Fault Tolerant SimpleFileLockService o... | 52,586 |
def get_tensorrt_backend_config_dict():
""" Get the backend config dictionary for tensorrt backend
NOTE: Current api will change in the future, it's just to unblock experimentation for
new backends, please don't use it right now.
"""
# dtype configs
weighted_op_qint8_dtype_config = {
# o... | 52,587 |
def shuf_device_inclusive_scan(data, temp):
"""
Args
----
data: scalar
input for tid
temp: shared memory for temporary work, requires at least
threadcount/wavesize storage
"""
tid = roc.get_local_id(0)
lane = tid & (_WARPSIZE - 1)
warpid = tid >> 6
roc.barrier()
... | 52,588 |
def chicago(return_X_y=True):
"""Chicago air pollution and death rate data
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pand... | 52,589 |
def sync_main(conf: typing.Optional[json.Data],
log: typing.Optional[str],
syslog_addr: typing.Optional[str],
syslog_pem: typing.Optional[Path],
ui_addr: typing.Optional[str],
ui_pem: typing.Optional[Path],
db_path: typing.Optional[Path... | 52,590 |
def Normalize(normThisData: np.array,toThisData: np.array):
"""Normalize one dataset to another to produce a unitless output.
Args:
normThisData (np.array):
toThisData (np.array):
Returns:
np.array: normalized_data
Notes:
Currently only works for 1D arrays shape=[m,] ?????true? and returns same shape 1D a... | 52,591 |
def bbiboll(df, n=10, k=3):
"""
BBI多空布林线 bbiboll(10,3)
BBI={MA(3)+ MA(6)+ MA(12)+ MA(24)}/4
标准差MD=根号[∑(BBI-MA(BBI,N))^2/N]
UPR= BBI+k×MD
DWN= BBI-k×MD
"""
# pd.set_option('display.max_rows', 1000)
_bbiboll = pd.DataFrame()
_bbiboll['date'] = df.date
_bbiboll['bbi'] = (_ma(df.... | 52,592 |
def write_df_to_csv_and_excel(df, paths):
"""Write Pandas Dataframe to CSV and Excel
Args:
df (DataFrame): dataframe which needs to be written
paths (dict): dictionary where keys are extensions, values are paths
"""
df.to_csv(paths[".csv"], index=False)
if len(df) < 1048576:
... | 52,593 |
def test_convert_i_case_colon(conv):
"""Test "I" case conversion after a colon.
A quoted phrase after a colon is assumed to start a new sentence (capitalized).
In all other cases, the preceding sentence is assumed to continue (lower-case).
"""
assert conv.convert_para('After a colon: I should not b... | 52,594 |
def trim_attribute(node):
"""
Removes "select" attribute from node
@type node: ZenNode
"""
node.start = re_attr.sub('', node.start) | 52,595 |
def find_file_bottom_up(name, from_dir=None):
"""Find the specified file/dir from from_dir bottom up until found or failed.
Returns abspath if found, or empty if failed.
"""
if from_dir is None:
from_dir = get_cwd()
finding_dir = os.path.abspath(from_dir)
while True:
path = os... | 52,596 |
def set_firewall_rules():
"""
Opens firewall ports necessary for a remote device to communicate with the RAD Telemetry server.
Requires administrator privilege.
:return: None
"""
assert WINDOWS, "Only implemented for Windows platforms"
__set_firewall_rule(direction="in", port=_RAD_DEFAULT_P... | 52,597 |
def calc_distance(y1, x1, y2, x2):
"""
Calculate distance between two locations using great circle distance.
Notes:
y1 = lat1, x1 = long1
y2 = lat2, x2 = long2
all assumed to be in decimal degrees
if (and only if) the input is strings
use the following conversions
... | 52,598 |
def suite():
"""suite of unittest"""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestDBManager))
return suite | 52,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.