content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import tempfile
import requests
import os
import zipfile
def download_dataset(url):
"""Download zipped file from given URL, unzip
:param url: URL of zipped archive
:return: filename
"""
global TEMPDIR
TEMPDIR = tempfile.mkdtemp(prefix="dronedeploy-")
r = requests.get(url)
zip_file =... | dc1375413ff5565527f3e965c8a7347cab93f601 | 45,716 |
import os
def check_file_existence(path_to_file):
"""
Check that the given file path exists.
If not, raise RuntimeError.
:param path_to_file: File path to check.
:type path_to_file: string
"""
if not os.path.exists(path_to_file):
raise RuntimeError("Cannot find file: " + path_to_f... | 56c23141afb807875eea1be040f11ce16115fdbc | 45,718 |
from typing import Union
def strint(value: Union[int, str, float]) -> str:
"""
If the passed value is a number type, return the number as a string with no
decimal point or places.
Else just return the string.
"""
if type(value) in (int, float):
return str(int(value))
else:
... | 271424978e0816d9e998221b18c86cc88c9adfb0 | 45,719 |
def batch_data(data, batch_size):
"""Given a list, batch that list into chunks of size batch_size
Args:
data (List): list to be batched
batch_size (int): size of each batch
Returns:
batches (List[List]): a list of lists, each inner list of size batch_size except possibly
... | 1404f67ff4a2e2515c555905e9b5ec5fdf560dd6 | 45,720 |
def get_current_system_from_log(entries_parsed: list, log_function=print, verbose=False) -> str:
"""Return name of the last star system the commander visited"""
if verbose:
log_function("Looking for current system")
all_session_systems = []
for entry in entries_parsed:
if "StarSystem" ... | ec7621b66cf235f098996f9ecb5e58749fc23b7d | 45,721 |
def _get_flags(flag_val, flags):
"""
Return a list of flag name strings.
`flags` is a list of `(flag_name, flag_value)` pairs. The list must be in sorted in order of the
highest `flag_value` first and the lowest last.
"""
if not flags:
return "Flags not parsed from source."
ret = [... | 654a052e0840a4d2ae038bcde5070a59f3e41443 | 45,723 |
import argparse
def handle_arguments():
"""
Method to Set CLA
Parameters:
None
Returns:
parser (ArgumentParser object)
"""
parser = argparse.ArgumentParser(description="Take 3MileBeach trace and convert to DAG")
parser.add_argument("-i", "--input", dest="inpu... | 4f8b4bf3c01ad2212071048cfcce8b958ed9448e | 45,724 |
def compute_scores_on_distance_measure(first_data, memento_data, distance_function):
"""Calculates the distance between scores for those measures that use
functions from the distance library.
"""
score = None
if len(memento_data) == 0:
if len(first_data) == 0:
score = 0
... | 4e411d88567b2e2de4d61ccd02102aa894c5190e | 45,725 |
import os
def get_corpus(data_dir):
"""
Get the corpus data with retrieve
:param data_dir:
:return:
"""
words = []
labels = []
for file_name in os.listdir(data_dir):
with open(os.path.join(data_dir, file_name), mode='r', encoding='utf-8') as f:
for line in f:
... | 1204958cac7343dbeeca77ec3e13337ddf24baad | 45,726 |
def parse_account(config, auth, account):
""" Breaks a [account:advertiser@profile] string into parts if supplied.
This function was created to accomodate supplying advertiser and profile
information
as a single token. It needs to be refactored as this approach is messy.
Possible variants include:
* [a... | a1c00ebc9f03358d7864765bac5ad545497444ad | 45,728 |
def get_intel_doc_label_item(intel_doc_label: dict) -> dict:
""" Gets the relevant fields from a given intel doc label.
:type intel_doc_label: ``dict``
:param intel_doc_label:
The intel doc label obtained from api call
:return: a dictionary containing only the relevant fields.
... | 578467798f08bfd0776aa285790dc95d4686a830 | 45,731 |
def removeExposures(plates, startDate):
"""Removes all real exposures taking after startDate."""
for plate in plates:
for ss in plate.sets:
ss.isMock = True
validExps = [exp for exp in ss.totoroExposures
if exp.getJD()[0] < startDate]
if len(... | a5753da31f7f5b4c37f21b9acb362cfee4a7a1dd | 45,734 |
import pkg_resources
import os
def get_sql(fname, sql_dir='sql', pkg_name='alpaca2pg') -> str:
"""Reads SQL query from file at `sql_dir`/`fname`."""
fp = pkg_resources.resource_filename(pkg_name, os.path.join(sql_dir, fname))
with open(fp, 'r', encoding='utf-8') as f:
return f.read() | 82883859c3d54ff00fea5fe269206d52aef9123d | 45,735 |
import os
def _pid():
"""
Return the current process pid
"""
return os.getpid() | ee7c0ace3f2d171eda9f0e322b5108c2c3f7a7b2 | 45,736 |
def Extensible(cls):
"""Returns a subclass of cls that has no __slots__ member.
This allows you to set arbitrary members in each instance, even if they
don't exist already in the class.
This is useful for making one-off Exporter() instances in tests,
for example.
Args:
cls: a class to inherit from.
... | ce579072a24652fa3195cbb809978bc21fef5c29 | 45,737 |
def make_grid(gates):
"""
Generate a grid that can be used my the A star search algorithm. It has an added heuristic function
causing A star to avoid lower layers.
"""
# Change grid size based on the netlist
if len(gates) == 25:
y_range = 13
else:
y_range = 17
grid = {... | c9115118d3361c7ef2b00171d2faacb2c1d9441f | 45,738 |
async def mock_successful_connection(*args, **kwargs):
"""Return a successful connection."""
return True | fc3801c8be6a98033c265a97de3bb413d0c249cc | 45,739 |
import os
from pathlib import Path
def get_image_path(image_name: str) -> str:
"""Return the path to the test image."""
# get this file folder 'test'
working_path = os.path.dirname(os.path.realpath(__file__))
# get object detection folder
object_detection_path = Path(working_path).parent.absolute(... | f657230b3a0886ac5693558a3c4ef6b2f8ed9c23 | 45,742 |
def filter_scopes(scopes, *args):
"""
:param scopes:
:param args:
:return:
"""
if not args:
return scopes
return [scope for scope in scopes if any(arg in scope for arg in args)] | 77a9971452fe338577429e1d0b5c9120e42dbd97 | 45,743 |
import re
def validate_password(passw):
"""Validates password."""
return True if re.match("^(?=.*[A-Za-z])(?=.*[\d!@#$%&*?.])[A-Za-z\d!@#$%&*?.]{6,12}$", passw) else False | 2edba4ea6fa697616d8f0611cb66149d972adbb7 | 45,744 |
def _norm(x, max_v, min_v):
""" we assume max_v > 0 & max_v > min_v """
return (x-min_v)/(max_v-min_v) | 6b1e010106fe16828106642a0d9bc6cae69b0642 | 45,745 |
def get_challenge():
"""Read lines from the challenge input file"""
lines = list()
with open("./input", 'r') as hdl:
for line in hdl.readlines():
lines.append(line.strip())
return lines | af367685f9f5a20b058d224e6a951ca73eb50021 | 45,746 |
def process(max_slices, no_of_types, slices_list):
"""
The main program reads the input file, processes the calculation
and writes the output file
Args:
max_slices: Maximum number of slices allowed
no_of_types: Number of Pizza to be selected
slices_list: List of number of slices... | d5fc22b5485e684304a483c63ff461f2b805bee4 | 45,748 |
import socket
import ipaddress
def _verify_hostname(host):
"""Verify a hostname is resolvable."""
try:
resolved = socket.getaddrinfo(host, None)[0][4][0]
ip = ipaddress.ip_address(resolved)
return ip
except (socket.gaierror, ValueError):
return False | d0b74fdcf7fabec0083cd5de295199077ad6e676 | 45,749 |
def is_gcs_path(path):
# type: (str) -> bool
"""Returns True if given path is GCS path, False otherwise."""
return path.strip().lower().startswith("gs://") | c6b8035d685264a206555abf219c67bb5e04d340 | 45,750 |
def read(file):
"""Read a $file to memory"""
with open(file, 'rb') as f:
buffer = f.read()
return buffer | 09dcf131cb8a3899a02bb279bc49cd83e06f6df4 | 45,751 |
def load_w2v_vocab(fname):
"""Load vocabulary file generated by gensim as a dictionary.
Note that this does not correspond to the gensim vocabulary
object.
Parameters
----------
fname: string
Filename where the w2v model is stored.
Returns
-------
vocab: dict{str: int}
... | a53c1f88ec6f67d5ad4173316ac4e4975bbd487f | 45,752 |
def gene_push_text(item, desc_len: int):
"""
生成推送内容
"""
text = f"标题:{item.title}\n链接:{item.link}"
if desc_len != 0:
text += f"\n描述:{item.summary[:desc_len]}"
return text | c1ecfcca6e4834b7a7ba0a1a245c2e9a8637ab0e | 45,754 |
def create_mw_bw_short_tab(res):
"""create the short table for mw-bauwerk data
"""
df = res["mischwasserbauwerke"]
# print(list(df.columns))
df["QF"] = df["QF24"] / df["AUA128"]
# calculate spezific volume
df["SPEZFRACHT"] = df["SFUEIN128"] / df["AUA128"]
df["SPEZVOL"] = df["VOLUMEN"] / ... | 6f09f728cd8594a24e686b4bd47a498edc949555 | 45,755 |
def service(container, name=None):
"""A decorator to register a service on a container.
For more information see :meth:`Container.add_service`.
"""
def register(service):
container.add_service(service, name)
return service
return register | 4d372ba99f8a494b2b8ad781c1501047c9049c9e | 45,756 |
def aspectRatio(size, maxsize, height=False, width=False, assize=False):
"""Resize size=(w,h) to maxsize.
use height == maxsize if height==True
use width == maxsize if width==True
use max(width,height) == maxsize if width==height==False
"""
w, h = size
scale = 1.0
if width !=Fa... | ce6dcbb191533c50343d1c10968a19b0713d2d1e | 45,758 |
def nestedmaps():
""" Nested-dictionary fixture function """
return {'body': {'declare_i': {'id': {'name': 'i', 'type': 'Identifier'},
'init': {'type': 'Literal', 'value': 2},
'type': 'VariableDeclarator'},
... | 2cc7d8a1a4f9b335e65842c72708e59245c3a561 | 45,759 |
def find_easy(control, length):
"""Find numbers that can be deduced from the number of switched on lights."""
matches = list(filter(lambda x: len(x) == length, control))
if len(matches) != 1:
raise ValueError('Something went wrong. Expected a single match.')
return ''.join(sorted(matches[0])) | 2a3f9293a5915570ae8f80daa0e2d7ad7faa69b5 | 45,760 |
import sys
def _common_():
"""Stuff common to _demo_ and _tool()
"""
script = sys.argv[0]
return script | 6122f9c091e89bc4408904720c9e81196e73a808 | 45,762 |
import re
def slurp_word(s, idx):
"""Returns index boundaries of word adjacent to `idx` in `s`."""
alnum = r"[A-Za-z0-9_]"
start, end = idx, idx
while True:
if re.match(alnum, s[start - 1]):
start -= 1
else:
break
end = idx
while True:
if re.mat... | 0b04de59cc1a848fac02bf58081ec990c8aa245b | 45,763 |
def get_user_rating_max(ratings,n=20):
"""Return the keys of users with at most ratings"""
return [key for key,value in ratings.iteritems() if len(value)<=n] | 9b4ba9c0ee6e11d1d5ec14ac41b1b93f029d6db4 | 45,764 |
def hybrid_collision_handler(slug, node1, node2):
"""This collision handler allows a static file to shadow a dynamic resource.
Example: ``/file.js`` will be preferred over ``/file.js.spt``.
"""
if node1.type == 'directory' and node2.type != 'directory':
if not node1.children:
# Igno... | d1dea686cb89baa7eca849e195488d02a31169ab | 45,766 |
def _calculate_rtb_ensemble_size(_CWPBN_, _Beams_,
IsE0000001, IsE0000002, IsE0000003,
IsE0000004, IsE0000005, IsE0000006,
IsE0000007, IsE0000008, IsE0000009,
IsE0000010, IsE0000011, IsE00... | 7a49d0cd360db6d4e475a839003cd0bf1e89a44c | 45,770 |
def strxor(str1, str2):
"""Xors 2 strings character by character.
"""
minlen = min(len(str1), len(str2))
ans = ""
for (c1, c2) in zip(str1[:minlen], str2[:minlen]):
ans += chr(ord(c1) ^ ord(c2))
return ans | 05051bd6938726f4ce222ec01c063f53a43536cb | 45,774 |
import os
def find_workflow(repo_directory):
"""Determine if `repo_directory` contains a `cookiecutter.json` file.
:param repo_directory: The candidate repository directory.
:return: True if the `repo_directory` is valid, else False.
"""
if not os.path.isdir(repo_directory):
return ""
... | bb90b00cd290af7391b50cfa2d7a18e0075974fb | 45,775 |
def delFunc(change):
""" diffable del """
return change.wasDeleted() and not change.isDirectory() | 60e3cb141cc75b3aa58b3bbb5fd3706c88209df9 | 45,776 |
def string_from_source(source) :
"""Returns string like "CxiDs2.0:Cspad.0" from "Source('DetInfo(CxiDs2.0:Cspad.0)')" or "Source('DsaCsPad')"
"""
str_in_quots = str(source).split('"')[1]
str_split = str_in_quots.split('(')
return str_split[1].rstrip(')') if len(str_split)>1 else str_in_quots | 741ea85cda2e197f6b882852f32f4df5e5338355 | 45,777 |
def _linked_feature_label(linked_feature):
"""Generates the label on edges between components.
Args:
linked_feature: spec_pb2.LinkedFeatureChannel proto
Returns:
String label
"""
return """<
<B>{name}</B><BR />
F={num_features} D={projected_dim}<BR />
{fml}<BR />
<U>{source_translator}</U><B... | b5235d6a0559ca7fdef2655071e3ca84db62328a | 45,778 |
def make_values(repo_pkg, cur_ver, new_ver, branch, check_result):
"""
Make values for push_create_pr_issue
"""
values = {}
values["repo_pkg"] = repo_pkg
values["cur_version"] = cur_ver
values["new_version"] = new_ver
values["branch"] = branch
values["check_result"] = check_result
... | 38d5cbc983c57c04bbcf1efcddcc67cabb02b4fb | 45,779 |
def get_coordinates_from_token(token, mod):
""" A function which takes a mod and a token, finds the token in the mod,
and then returns the coordinate (tuple) at which the token is found. If it
is not found, it returns None. """
for coordinates, token_in_mod in mod.items():
# No possibility of du... | 429e42a6439972d23bc54ac5108f196aa0ca93b7 | 45,780 |
import json
def failed_validation(*messages, **kwargs):
"""Return a validation object that looks like the add-on validator."""
upload = kwargs.pop('upload', None)
if upload is None or not upload.validation:
msgs = []
else:
msgs = json.loads(upload.validation)['messages']
for msg i... | fc9b54d5ef480ccaf0943f75042b3619a56a0924 | 45,781 |
import time
def current_time_millis():
"""
File times are in integer milliseconds, to avoid roundoff errors.
"""
return int(round(time.time() * 1000)) | 14b58cee1cb33a90c12aacd7a03c8b293824f2e2 | 45,782 |
def make_unique(arr):
"""Choose only the unique elements in the array"""
return list(set(list(arr))) | e1ef04f55f1c132e54d3db4c7118469979303876 | 45,784 |
def total_occurences(s1, s2, ch):
"""(str, str, str) -> int
Precondition: len(ch) == 1
Return the total number of times ch appears in s1 and s2.
>>> total_occurences('red', 'blue', 'u')
1
"""
# total_occurences('Yellow', 'Blue', 'u')
return (s1 + s2).count(ch) | 03340fdf269a9ddabb6eaaad37bb168bd3a627e0 | 45,786 |
def ensure_list(obj, tuple2list=False):
"""
Return a list whatever the input object is.
Examples
--------
>>> ensure_list(list("abc"))
['a', 'b', 'c']
>>> ensure_list("abc")
['abc']
>>> ensure_list(tuple("abc"))
[('a', 'b', 'c')]
>>> ensure_list(tuple("abc"), tuple2list=True... | 9f14560525f39951e3296b606c232d3fdb806f07 | 45,787 |
import os
def make_directory(conf_data):
"""Making directory to save results and trained-model.
Parameters
----------
conf_data: dict
Dictionary containing all parameters and objects.
Returns
-------
conf_data: dict
Dictionary containing... | fad9af0d08f60e9c21dc6aa37c5f4f96a6bc9453 | 45,788 |
import re
def parse_chapter_name(name):
"""
解析章节名字符串
:param name: 章节名字符串
:return: 章节编号, 章节名
"""
pattern = r'^(\u7b2c[\u4e00-\u9fa50-9]+\u7ae0)\s?([\u4e00-\u9fa5]+)\s?'
result = re.findall(pattern, name)
if result is not None and len(result) == 1:
chapter_num = result[0][0]
... | 721468c7e2db19abe26cbef9513174142b742231 | 45,790 |
def env_chk(val, fw_spec, strict=True, default=None):
"""
env_chk() is a way to set different values for a property depending
on the worker machine. For example, you might have slightly different
executable names or scratch directories on different machines.
env_chk() works using the principles of ... | b33218f924064beda1dc0c8f922d4577bf4bd307 | 45,791 |
def _clean_subpath(subpath, delim="/"):
"""
Add / to the subpath if needed to avoid partial s-exon matching.
"""
first = subpath[0]
last = subpath[len(subpath)-1]
cleaned_subpath = ""
if first != "s": # start
cleaned_subpath += delim
cleaned_subpath += subpath
if last != "p"... | 2195bfea9f798a88e688de62eafa75e1519ab647 | 45,792 |
def preconvert_str(value, name, lower_limit, upper_limit):
"""
Converts the given `value` to an acceptable string by the wrapper.
Parameters
----------
value : `str`
The string to convert,
name : `str`
The name of the value.
lower_limit : `int`
The minimal length... | 226d9109b9056057f0998634d10f3f5801a2db09 | 45,793 |
import logging
import torch
def restore_checkpoint(model, optimizer, checkpoint_file, device):
"""
Restores model and optimizer from a checkpoint file and returns checkpoint information.
Has side effect of loading the state_dict for model and optimizer (i.e. modifies the instances).
:param model: [cla... | 8a620531bded9000c6f030d45d65df27a261a67a | 45,795 |
import re
import subprocess
def get_dpkg_package_version(package_name):
"""Get the version of an installed package.
Args:
package_name (str): The package name
Returns:
str: The version of the package
"""
return re.findall(r"(?<=Version: ).+", subprocess.check_output(["dpkg", "-s"... | 74957eea39d2283d3092edcec47e01f052de4d9f | 45,796 |
def reorder_elements(data_frame):
"""Reorder elements dataframe for readability.
Args:
data_frame ([type]): [description]
Returns:
pd.DataFrame: Elements get team and web_name first.
"""
try:
_elements_columns = sorted(data_frame.columns.tolist())
_elements_columns.... | 9559a3151d75b0fc0319c2614847b53a7dcea718 | 45,797 |
def check_smtp(email):
"""[check if smtp from string email is valid]
Args:
email ([string]): [email adress]
Raises:
KeyError: [in case the email inputed is not accounted for]
Returns:
[string]: [provider]
"""
smtp_dict = {"gmail": ['smtp.gmail.com', 587],
... | d3563a5d40b79e7b14dccc67bbe91d889920b9aa | 45,798 |
def singleton_observable(observable):
"""
This function defines a decorator to declare some observable classes as
*Singleton observables*. This means that in a specific interpretation, only
one observation of that observable can be present.
This characteristic is implemented as a decorator because i... | 60fd106b222418086560a623336f14a10177f473 | 45,799 |
import re
def get_testcase_summary(output):
"""! Searches for test case summary
String to find:
[1459246276.95][CONN][INF] found KV pair in stream: {{__testcase_summary;7;1}}, queued...
@return Tuple of (passed, failed) or None if no summary found
"""
re_tc_summary = re.compile(r... | e1d0b1afaaa0cf0862dc0b86c930ced59f75688d | 45,800 |
def import_tnmr_pars(path):
"""
Import parameter fields of tnmr data
Args:
path (str) : Path to .tnt file
Returns:
params (dict) : dictionary of parameter fields and values
"""
params = {}
with open(path, "rb") as f:
params["version"] = f.read(8).decode("utf-8")
... | 19a7043fb261d7d909d453f7ee2f7518a26a7ec7 | 45,801 |
def download(remote, path, pkg):
"""Downloads package"""
if not pkg.package:
return False
res = remote.download_packages(pkg, path)
if res['errors']:
return False
pkg_path = res['downloaded'] and res['downloaded'][0] or res['skipped'][0]
if not pkg_path:
return False
... | a5b83987df1c6c57357c6ff619753a4739cf1416 | 45,803 |
def bash_and_fish_comment(line: str) -> str:
"""Make a bash/fish comment.
line: Text to comment. Must not contain newlines.
"""
return f"# {line}" | 4b1662912ab3bfcaab688ca4a38840e8acbbe186 | 45,804 |
from typing import Mapping
def recursive_round(ob, dp, apply_lists=False):
""" map a function on to all values of a nested dictionary """
if isinstance(ob, Mapping):
return {k: recursive_round(v, dp, apply_lists) for k, v in ob.items()}
elif apply_lists and isinstance(ob, (list, tuple)):
r... | 686e9cc2270606c3b9fa6c65467ec1427fa73746 | 45,806 |
import os
import shutil
def copy_dir(src, dest, enforce=True):
"""Copy the directory if necessary."""
if os.path.exists(dest):
if enforce:
shutil.rmtree(dest)
shutil.copytree(src, dest)
else:
shutil.copytree(src, dest)
return dest | 0d165a510b21063cde4d53409f65772f35ab1311 | 45,807 |
def format_time(seconds):
"""Simple text formating of time"""
if seconds < 60:
return '%ds' % seconds
if seconds > 60 and seconds < 3600:
minutes = seconds / 60
seconds = seconds % 60
return '%dm %02ds' % (minutes, seconds)
if seconds > 3600:
hours = seconds / 360... | 77b05c1d6434d8f996d7e15075824ff3f47a146c | 45,808 |
def porcentual(valor, porcentaje, incremento=False, decremento=False):
""" returns the porcuentual of a value """
if incremento and decremento:
raise ValueError("No se puede incrementar y decrementar a la vez.")
_multiplo = porcentaje / 100
if incremento:
_multiplo += 1
if decremento:
_multiplo = 1 - _mul... | 9054769cee4c31869949ab9b88ca0254c11edc31 | 45,809 |
def bingpg2(bingpg_maker):
""" return an initialized bingpg instance different from the first. """
return bingpg_maker() | d7118873533adc2f8b13edf941910e33468c3df5 | 45,810 |
import os
import shutil
def theme_project_tmpdir(tmpdir):
"""Copy themes-project to a temp dir, and copy demo-project content to it."""
themes_dir = os.path.join(os.path.dirname(__file__), "themes-project")
content_dir = os.path.join(os.path.dirname(__file__), "demo-project", "content")
temp_dir = tm... | b5c48c6fbde8ac4ea870ba3f055fbbf6de40fedf | 45,811 |
from typing import Optional
def _extract_sequence_identifier(description: str) -> Optional[str]:
"""Extracts sequence identifier from description. Returns None if no match."""
split_description = description.split()
if split_description:
return split_description[0].partition('/')[0]
else:
return None | b6f927daf3726a8a933eb47d066ed2aeee82fc70 | 45,812 |
import uuid
def parse_uid(message:dict, uid_columns:list=['user_id_got', 'user_id_set']):
"""Parce uuid fields"""
for column in uid_columns:
if 'uid' in message[column]:
message[column] = str(uuid.UUID(message[column].replace('uid=','')))
return message | 0baf6208cfb6454479f4726e1faaa0824750d349 | 45,813 |
def render_fobi_forms_list(context, queryset, *args, **kwargs):
"""Render the list of fobi forms.
:syntax:
{% render_fobi_forms_list [queryset] [show_edit_link] \
[show_delete_link] \
[show_export_link] %}
:... | 0e2df881729ec6bf0cd2a9798a67de2c2973526c | 45,815 |
def cents_to_hz(F_cent, F_ref=55.0):
"""Converts frequency in cents to Hz
Notebook: C8/C8S2_FundFreqTracking.ipynb
Args:
F_cent (float or np.ndarray): Frequency in cents
F_ref (float): Reference frequency in Hz (Default value = 55.0)
Returns:
F (float or np.ndarray): Frequency... | c73c67bb931d07743ee3b53a662485924b0c3f56 | 45,816 |
def get_continuous_column_by_class(dataset):
"""Separates continuous column by binary class"""
# Separate continuous column by class
continuous_column = dataset.columns_that_are('continuous')[0]
continuous_true = []
continuous_false = []
for cont_value, class_value in zip(continuous_column, data... | 71c52e3703f6e9eea60c6dbdba839ef45365b3fa | 45,817 |
def get_bibtex(citation):
"""将网页返回的索引格式转换为bibtex格式"""
paper_bibtex={
'Author':'',
'Title':'',
'Journal':'',
'Year':'',
'Volume':'',
'Issue':'',
'Pages':'',
'DOI':''
}
if len(citation)==0:#网页没有返回索引信息
return paper_bibtex
... | c072d65924cad8df3dc396b7c4d2801a9b0a55b2 | 45,818 |
import torch
def _solarize(inp, thresholds=0.5):
"""
For each pixel in the image, select the pixel if the value is less than the threshold.
Otherwise, subtract 1.0 from the pixel.
"""
if not isinstance(inp, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {ty... | 78d071f3c272f4af2f8c9d5cb8a697c38a186224 | 45,820 |
import os
def match_key_from_match_dir(match_dir):
"""Converts the match directory into a key for the match."""
return os.path.split(os.path.normpath(match_dir))[-1] | 594336036440d29d77d3da359ef46825a19ad13e | 45,821 |
def get_mac_s(output: bytes) -> bytes:
"""Support function to get the 64-bit resynchronisation authentication code
(MAC-S) from OUT1, the output of 3GPP f1* function.
:param output: OUT1
:returns: OUT1[64] .. OUT1[127]
"""
edge = 8 # = ceil(63/8)
return output[edge:] | c5f1d2d14819e9a9bf660aeb82dd24b8111263b5 | 45,823 |
def custom_sort(dictionary, sort_top_labels, sort_bottom_labels):
""" Given a dictionary in the form of
{'<a_label>': {
'label': '<a_label>'
'value': '<a_value>'
},
...
}
and two... | 41d8b12fcf397e416ba9c2adb5bd8f2cafee36b1 | 45,824 |
def reconstruct_path(current, came_from):
"""
Reconstruct path using last node and dictionary that maps each node on path
to its predecessor.
Args:
current (int): Last node in discovered path
came_from (dict): Dictionary mapping nodes on path to their predecessors
Retuns:
(... | 43d05b50987d3022f748d40b76942de38f866ac5 | 45,826 |
def gcd_steps(a, b):
""" Return the number of steps needed to calculate GCD(a, b)."""
# GCD(a, b) = GCD(b, a mod b).
steps = 0
while b != 0:
steps += 1
# Calculate the remainder.
remainder = a % b
# Calculate GCD(b, remainder).
a = b
b = remainder
#... | 768d52c795c8c8eb20f4adfaf26f10da12962534 | 45,827 |
import math
def avp_from_temperature_min(temperature_min):
"""
Estimate actual vapour pressure (*ea*) from minimum temperature.
This method is to be used where humidity data are lacking or are of
questionable quality. The method assumes that the dewpoint temperature
is approximately equal to the ... | 2eeeaac62d228c6fb05ff583a5e539ab3bafffe4 | 45,829 |
def sort_items(sort=None):
"""
Function to generate the sort query. Code is from https://stackoverflow.com
questions/8109122/how-to-sort-mongodb-with-pymongo
"""
sort_file = {
'featured': [('_id', 1)],
'date-added': [('date_added', -1), ('name', 1)],
'price-asc': [('price', 1... | 26f8799fca1751d17159c4c8526047d42ac22a23 | 45,830 |
def divideGT(GT, X, Y):
"""
LT - left top;
RT - right top;
LB - left bottom;
RB - right bottom;
"""
# width and height of the GT
hei, wid = GT.shape
area = float(wid * hei)
# copy 4 regions
LT = GT[0:Y, 0:X]
RT = GT[0:Y, X:wid]
LB = GT[Y:hei, 0:X]
... | a4fb1d43205b9c33dd828aba6365cd85d12695c9 | 45,831 |
def make_mock_video_ids(num_videos):
"""Makes a list of video ids used for unit tests.
num_videos: an integer; the number of mock video ids to make.
Returns: a list of strings of that can be used as video ids for unit tests.
"""
video_ids = []
for video_num in range(num_videos):
vide... | 14ec177575d4a11aa44a0e42e70cfd5791e38ad2 | 45,832 |
import binascii
def int_to_bytes(i: int):
"""
Convert an integer to a byte(s)
Args:
i: Integer to convert
Returns:
bytes
"""
width = i.bit_length()
width += 8 - ((width % 8) or 8)
fmt = '%%0%dx' % (width // 4)
return b"\x00" if i == 0 else binascii.unhexlify(fmt % i... | be4bc40913fa0c61f117a1f4ec7b10402e413b6e | 45,833 |
import logging
import sys
import os
def check_project_config(config):
"""
Validation checks on the project config. At least one project must exist
(otherwise exit) and the paths for each project should exist, otherwise the
project entry is removed.
Args:
config (ConfigObj):
Th... | c281a26e3b32259dcad884a5689aec37f6320385 | 45,834 |
def path_decoder(url):
"""Grab the last component of a url as the path."""
components = url.split('/')
if components[-1]:
return components[-1]
else:
return components[-2] | d35112082facb7c378201cac44557c0628ba4563 | 45,835 |
from typing import Tuple
import os
def _get_credentials_as_smart_contract() -> Tuple[str, str]:
"""Attempt to get credentials for a dragonchain from the standard location for a smart contract
Returns:
Tuple of auth_key_id/auth_key of credentials from environment. Empty strings in tuple if not found
... | 7e06340446da282999c116aeee4fac1ebda931c1 | 45,836 |
def get_dir(path):
"""
Returns the directory of a file, or simply the original path if the path is a directory (has no extension)
:param Path path:
:return: Path
"""
extension = path.suffix
if extension == '':
return path
else:
return path.parent | ce40de2223de46be91ca28fba01c4153679a693c | 45,837 |
def insert_output_start_stop_indicators(src):
"""
Insert identifier strings so that output can be segregated from input.
Parameters
----------
src : str
String containing input and output lines.
Returns
-------
str
String with output demarked.
"""
lines = src.sp... | 162724502e581901629bae764a235ca0f71e0c61 | 45,839 |
from typing import Sequence
from typing import AnyStr
from typing import cast
import subprocess
def invoke_formatter(formatter_args: Sequence[str], code: AnyStr) -> AnyStr:
"""
Given a code string, run an external formatter on the code and return new
formatted code.
"""
# Make sure there is somet... | 9b0b994d3c8f1da0cec068812623a3b2b5370b61 | 45,840 |
def get_images(directory):
"""
Gets all PNG, JPG, GIF, and BMP format files at path
:param Path directory: location to search for image files
"""
files = []
patterns = ('*.png', '*.jpg', '*.gif', '*.bmp')
for pattern in patterns:
files.extend(directory.glob(pattern))
return fil... | e6c599814d5d31de5a64e502d88f40996d49888f | 45,841 |
def prepare_table_rows(rows):
"""Given a list of lists, make sure they are prepared to be formatted into a table
by making sure each row has the same number of columns and stringifying all values."""
rows = [list(map(str, r)) for r in rows]
max_cols = max(list(map(len, rows)))
for row in rows:
... | 8f4730d08400a88234e9ac0137d58d255e1fbddb | 45,842 |
import re
def replace_all(src_string, regex, replacement):
"""
Replace each occurrence of regular expression match in
the first string with the replacement string and return the
replaced string. A 'regex' string with null value is considered as
no change. A 'replacement' string with null value is ... | 410e6c8f333e9776daad08c9bbbd39831640d350 | 45,844 |
def parse_kid(line, kid):
""" parses a "@ ale01.cha 1;4.28" line into name/month ("ale", 16) """
tmp = line.split('\t')
if len(tmp) < 3 or not (".cha" in tmp[1] or ".txt" in tmp[1]):
return kid
else:
date = tmp[2].split(';')
return (tmp[1][:3], int(date[0]) * 12 + int(date[1]... | 3fe1af7f741cb27eb36159ed211049e6e14f67c2 | 45,845 |
import math
def compare_lines(l1, l2, mode='p'):
"""
Compare 2 lines.
Returns true if they are similar, false otherwise
"""
if mode == 'p':
dist_error = 50 # pixels, max distance between points
if (math.sqrt((l1[0] - l2[0]) ** 2 + (l1[1] - l2[1]) ** 2) < dist_error and \
... | e6c61d13deda5f7cd178eb3a2b32e14aa0f9474c | 45,846 |
import re
def make_filename(url):
"""
Extracts domain from a url and append '.html'
:param url: string
return <domain>.html string
"""
rx = re.compile(r'^https?:\/\/(?:www.)?([^\/]+)\/?')
m = rx.search(url)
if m:
return m[1] + '.html'
else:
print(f'Can not get domain from {url}')
exit(0) | 12ce1ec1acb77c2147a361f563c051edf6f73e83 | 45,848 |
import ast
def _log_function(item):
"""
Handler function for log message types.
:param item: ast object being inspected for certain properties
:type item: :class:`~ast.AST`
:return: Returns the descriptor and arg offset of the item.
:rtype: tuple (str, int)
"""
level_arg = item.args[0... | cd7f798b5e28d1835d270e8d2b64b73faef4f853 | 45,850 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.