content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def validate(val_loader, model, crf_criterion, vb_decoder):
"""
Performs one epoch's validation.
:param val_loader: DataLoader for validation data
:param model: model
:param crf_criterion: viterbi loss layer
:param vb_decoder: viterbi decoder
:return: validation F1 score
"""
model.e... | 65,000 |
async def test_reloadable_late(hass, mqtt_client_mock, caplog, tmp_path):
"""Test reloading the MQTT platform with late entry setup."""
domain = sensor.DOMAIN
config = DEFAULT_CONFIG[domain]
await help_test_reloadable_late(hass, caplog, tmp_path, domain, config) | 65,001 |
def base_context(request):
"""
`nav_category` gets a default value here, but you can override it by setting a `nav_category` property on the
`request` object to the value you want.
"""
user = request.user
following, following_truncated = [], []
if user.is_authenticated():
following ... | 65,002 |
def sort_box(box):
"""
对box排序,及页面进行排版
box[index, 0] = x1
box[index, 1] = y1
box[index, 2] = x2
box[index, 3] = y2
box[index, 4] = x3
box[index, 5] = y3
box[index, 6] = x4
box[index, 7] = y4
"""
box = sorted(box,key=lambda x:sum([x[1],x... | 65,003 |
def main():
"""Start the program and call the functions."""
data, features, prices = get_data('Data/housing.csv')
# Shuffle and split the data into training and testing subsets
X_train, X_test, y_train, y_test = train_test_split(features, prices, test_size=0.20, random_state=42)
print("\n** 20% of... | 65,004 |
def test_tls_only_client_leaf_trusted_and_fingerprint_of_client_CA(
mgr, temp_chains, cleanup
):
"""Verify that when the server only trusts the client's leaf
certificate but has a cert-to-name fingerprint that matches the
client's root CA the connection is accepted"""
do_cert_test(
mgr... | 65,005 |
def authGSSServerInit(service):
"""
Initializes a context for GSSAPI server-side authentication with the given service principal.
authGSSServerClean must be called after this function returns an OK result to dispose of
the context once all GSSAPI operations are complete.
@param service: a string co... | 65,006 |
def get(proj_dir, key) :
"""return settings value by key, default value if the value
doesn't exist in the project-local settings file
:param proj_dir: absolute project directory
:param key: settings key
:returns: settings value, default value for key, or None
"""
util.e... | 65,007 |
def test_plugin_msteams_templating(mock_post, tmpdir):
"""
NotifyMSTeams() Templating
"""
# Disable Throttling to speed testing
plugins.NotifyBase.request_rate_per_sec = 0
# Prepare Mock
mock_post.return_value = requests.Request()
mock_post.return_value.status_code = requests.codes.ok
... | 65,008 |
def pair_correlation_neighbor_list(
displacement_or_metric: Union[DisplacementFn, MetricFn],
box_size: Box,
radii: Array,
sigma: float,
species: Array=None,
dr_threshold: float=0.5):
"""Computes the pair correlation function at a mesh of distances.
The pair correlation function measures the... | 65,009 |
def generate_trade_id():
"""
采取一定规则生成一个11位的交易号
"""
import time, random
trade_id = str(time.time())
trade_id = trade_id[:3] + str(random.randint(1000, 10000)) + trade_id[7:10] + trade_id[11]
return trade_id | 65,010 |
def clean_ranks(menu_items):
"""
Resets ranks from 0 to n, n being the number of items.
"""
rank = 0
for menu_item in menu_items:
menu_item.rank = rank
menu_item.save()
rank += 1 | 65,011 |
def area(spectra, energy, a, b):
"""
This function helps to determinate area under each photopeak through,
trapeziodal method.
Where:
spectra: net count rate vector
energy: energy vector
a: lower limit
b: upper limit
"""
spec = []
spec = spectra
... | 65,012 |
def get_task_app_id(task_id):
"""
Return the application id associated to the given task_id
:param task_id: Task id
:return: The associated application id associated to the given task id
"""
global fgapisrv_db
task_info = fgapisrv_db.get_task_info(task_id)
app_record = task_info.get('app... | 65,013 |
def create_tuple_1(t0_type_info: CLTypeInfo):
"""Returns CL type information for a byte array.
:param CLTypeInfo t0_type_info: Type information pertaining to first tuple element.
"""
return CLTypeInfoForTuple1(
typeof=CLType.TUPLE_1,
t0_type_info=t0_type_info
) | 65,014 |
def request_path( request ):
"""
Get the path of the request
"""
return str(request.path) | 65,015 |
def user_activity_list(
user_id: str, limit: int, offset: int
) -> list[Activity]:
"""Return user_id's public activity stream.
Return a list of all activities from or about the given user, i.e. where
the given user is the subject or object of the activity, e.g.:
"{USER} created the dataset {DATASE... | 65,016 |
def add_bridge(interface):
"""Add a bridge.
:param interface: the name of the bridge
"""
processutils.execute('brctl', 'addbr', interface) | 65,017 |
def test_return_project_list_old_method():
"""Test that projects can be returned iva the original function in the Config class"""
result = False
config_obj = prism.Config(api_client=_api())
projects = config_obj.get_projects()
if projects:
result = True
assert not result | 65,018 |
def test_cps1():
"""Test module cps1.py by downloading
cps1.csv and testing shape of
extracted data has 15992 rows and 10 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = cps1(test_path)
try:
assert x_train.shape == (15992, 10)
except:
shutil.rmtree(test_path)
raise() | 65,019 |
def thirtythree():
"""http://cryptopals.com/sets/5/challenges/33/"""
dh_params = matasano.public.dh_keys()
print("Generated DH keys:\n{},\n{}.".format(
dh_params.priv, dh_params.pub
)) | 65,020 |
def repo_file(repo, *path, mkdir=False):
"""
"""
if repo_dir(repo, *path[:-1], mkdir=mkdir):
return repo_path(repo, *path) | 65,021 |
def executable_directory():
"""Always determine the directory of the executable, even when run with py2exe or otherwise frozen"""
executable = get_executable()
path = os.path.abspath(os.path.dirname(executable))
return path | 65,022 |
def rescale(x, y, coeff, mx, my):
"""
Rescale x y - axis.
Args:
x: (todo): write your description
y: (todo): write your description
coeff: (todo): write your description
mx: (todo): write your description
my: (todo): write your description
"""
# Bring the da... | 65,023 |
def node_restart_silencer(alert: PrometheusKubernetesAlert, params: NodeRestartParams):
"""
Silence alerts for pods on a node that recently restarted.
"""
if not alert.pod:
return # Silencing only pod alerts on NodeRestartSilencer
# TODO: do we already have alert.Node here?
node: Node ... | 65,024 |
def lang_code_search(search_term, script_search):
"""
Returns a tuple: name of a code or a script, is it a script? (that's a boolean)
:param search_term: The term we're looking for.
:param script_search: A boolean that can narrow down our search to just ISO 15925 script codes.
:return:
"""
... | 65,025 |
def finish():
"""
Used at the end of each test to check if it passed and print the answer
"""
check_test_in_progress()
global test_failed, n_failed_tests, test_in_progress
if test_failed:
n_failed_tests += 1
print("Test failed")
else:
print("Test passed")
test_in_... | 65,026 |
def wrap_carracing(env, clip_rewards=True, frame_stack=True, scale=False):
"""Configure environment for DeepMind-style Atari.
"""
env = WarpFrame(env)
if scale:
env = ScaledFloatFrame(env)
if clip_rewards:
env = ClipRewardEnv(env)
if frame_stack:
env = FrameStack(env, 4)
... | 65,027 |
def continuum_imaging_workflow(vis_list, model_imagelist, context='2d', **kwargs):
""" Create graph for the continuum imaging pipeline.
Same as ICAL but with no selfcal.
:param vis_list:
:param model_imagelist:
:param context: Imaging context
:param kwargs: Parameters for functions in ... | 65,028 |
def uneven_subsequent_mask(x_size: int, y_size: int) -> Tensor:
"""
Mask out subsequent positions (to prevent attending to future positions)
Transformer helper function.
:param size: size of mask (2nd and 3rd dim)
:return: Tensor with 0s and 1s of shape (1, size, size)
"""
mask = np.triu(np... | 65,029 |
def getTraceSpec():
"""
Return the module traceSpec used by all instances of Trace.
"""
return Trace.traceSpec | 65,030 |
def _get_version_from_git():
"""
Use the git tag to get a PEP compliant version string
"""
tag = _get_most_recent_git_tag()
# e.g. 1.0.1-4-f0f0333
m = re.match(
r"(?P<version>\d+\.\d+\.\d+)(?:-(?P<nadd>\d+)-(?P<hash>.+))?",
tag)
if not m:
raise RuntimeError("Git tag d... | 65,031 |
def find(json, search_text):
"""
Takes a JSON string and a search string and output a list of
matching keys, values and text.
"""
assert isstr(json) or is_dict_or_list(json)
assert isstr(search_text)
if sys.version[0] == '2' and type(search_text) is str:
search_text = search_text.dec... | 65,032 |
def _token_param_shape():
"""Shape used in place of tokens as top-level computation arguments."""
return xc.Shape.array_shape(np.dtype(np.bool_), []) | 65,033 |
def _is_amplitude_valid(symbolic_pulse: "SymbolicPulse") -> bool:
"""A helper function to validate maximum amplitude limit.
Result is cached for better performance.
Args:
symbolic_pulse: A pulse to validate.
Returns:
Return True if no sample point exceeds 1.0 in absolute value.
""... | 65,034 |
def _sub_hash_password(password):
"""
Hash long password to allow bcrypt to handle password longer than 72 characters.
:param password: password to hash.
:return: (String) The hashed password.
"""
# bcrypt only handles passwords up to 72 characters.
# We use this hashing method as a work aro... | 65,035 |
def get_default_version_hostname():
"""Get the standard hostname of the default version of the app.
For example if your application_id is my-app then the result might be
my-app.appspot.com.
Returns:
The standard hostname of the default version of the application.
"""
return os.getenv('DEFAULT_VER... | 65,036 |
def _find_all_names():
"""Find all names in the Python environment.
"""
with _squash_output(False):
for strategy in (ast_walker.ASTWalkerStrategy(),
sys_modules_scanner.SysModulesStrategy()):
yield from strategy.get_names() | 65,037 |
def _load_restricted_forward(source_vertno1, source_vertno2):
"""Load forward models and restrict them so that they include source
vertices"""
fwd_free = mne.read_forward_solution(fname_fwd)
fwd_free = mne.pick_types_forward(fwd_free, meg='grad', eeg=False)
# Restrict forward
vertno_lh = np.ran... | 65,038 |
def action_create_form_for_tickets_creation(article_id, erroneous_form=None):
"""Show form to register a tickets creation action for the article."""
article = _get_article_or_404(article_id)
shop = shop_service.get_shop(article.shop_id)
brand = brand_service.get_brand(shop.brand_id)
form = (
... | 65,039 |
def login(request, next_page=None, required=False):
"""Forwards to CAS login URL or verifies CAS ticket"""
service_url = get_service_url(request, next_page)
client = get_cas_client(service_url=service_url, request=request)
if not next_page and settings.CAS_STORE_NEXT and 'CASNEXT' in request.session:
... | 65,040 |
def autoallocate(file, allocate_type='single', filename='', export_to='xlsx'):
"""Read and parse a downloaded doode poll (in '.xls' or '.xlsx') where participants are
able to choose as many timeslots as possible. Automatically allocate participants to a
slot based on their chosen availabilities. Returns dat... | 65,041 |
def raise_api_exceptions(response):
"""
Parse the response from the API converting errors into exceptions.
Args:
response - The JSON response from the Janrain API.
Raises:
ApiResponseError
"""
if response['stat'] == 'error':
logger.debug("Response:\n" + to_json(response... | 65,042 |
def MultIntensity( Fin, Intens):
"""
*Multiplies the field with a given intensity distribution.*
:param Fin: input field
:type Fin: Field
:param Intens: N x N square array of real numbers or scalar
:type Intens: numpy.ndarray, float, int
:return: output field (N x N square array of comp... | 65,043 |
def shell(context):
"""Enter the development shell."""
context.run(f"{Composer} exec --workdir /workspace dev bash", pty=True) | 65,044 |
def from_rgb_to_paletton_hue(rgb, paletton):
"""
>>> p = Paletton()
>>> print(from_rgb_to_paletton_hue((120, 0, 106), p))
318
"""
from colorsys import rgb_to_hsv
rhs_hue = round(rgb_to_hsv(*rgb)[0]*360)
if rhs_hue not in paletton.HUE_OFFSETS:
keys = sorted(paletton.HUE_OFFSETS.ke... | 65,045 |
def set_seed(seed=0):
"""Set the same seed for all the RNG.
Argument:
- seed: the specified seed.
"""
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed) | 65,046 |
def eval(loaded_model, tokenizer, label_encoder, data_in_file,data_out_file,delim=","):
"""
Prepare the data
"""
data = []
text_out_file=open(data_out_file,"w")
text_out_file.write("text\tclass_label\tconfidence\n");
data_x, data_y, _ = data_preparation.read_test_data(data_in_file, delim, l... | 65,047 |
def run_example(
device_id: str,
server_host: str = "localhost",
server_port: int = 8004,
plot: bool = True,
stream_rate: int = 12,
inputselect_1: int = 16,
inputselect_2: int = 32,
):
"""run the example."""
apilevel_example = 6 # The API level supported by this example.
# Call... | 65,048 |
def iread_segy(file, endian=None, textual_header_encoding=None,
unpack_headers=False, headonly=False):
"""
Iteratively read a SEG-Y field and yield single ObsPy Traces.
The function iteratively loops over the whole file and yields single
ObsPy Traces. The next Trace will be read after th... | 65,049 |
def matmul_default(
cfg,
tensor_a,
tensor_b,
bias=None,
out_dtype=None,
transpose_a=False,
transpose_b=False,
):
"""Matmul operator on GPU"""
return nn.matmul(tensor_a, tensor_b, bias, out_dtype, transpose_a, transpose_b) | 65,050 |
def is_range_format(expression: str) -> bool:
"""判断表达式是否为范围表达式"""
range_list = expression.split(BuildInChar.HYPHEN)
if len(range_list) != 2:
return False
return True | 65,051 |
def yukawa_green_function(k: float, alpha: float, kappa: float) -> float:
"""
Evaluate the Green's function of Coulomb/Yukawa potential.
.. math::
G(k) = \\frac{4 \\pi }{\\kappa^2 + k^2} e^{- (k^2 + \\kappa^2)/4 \\alpha^2 }
Parameters
----------
k : float, numpy.ndarray
Range ... | 65,052 |
def drop_corr_columns(dataframe: pd.DataFrame, drop_columns: bool = True,
print_columns: bool = True, threshold: float = 0.98) -> pd.DataFrame:
""" Correlated columns eliminator
The function drop correlated columns and keep only one of these columns. Usually removing high correlated colum... | 65,053 |
def update_all_PVs():
"""Send update events to all connected clients for the PVs which have
changed since the last update."""
for PV_name in connected_PVs():
notify_subscribers_if_changed(PV_name, PV_value(PV_name, cached=False)) | 65,054 |
def dt_compat_on_bus(kconf, _, compat, bus):
"""
This function takes a 'compat' and returns "y" if we find an "enabled"
compatible node in the EDT which is on bus 'bus'. It returns "n" otherwise.
"""
if doc_mode or edt is None:
return "n"
if compat in edt.compat2okay:
for node i... | 65,055 |
def rreplace(content, needle, replace):
"""Recursively replaces all occurrences of needle with replace
Args:
content (Iter[str]): An iterable of strings on which to perform the
replacement
needle (str): the value being searched for (an iterable of strings may
be used to... | 65,056 |
def floodlight_report(config, task:dict, floodlight_id: int) -> int:
""" Create a report for a specific floodlight if it does not exist.
Args:
floodlight_id - the floodlight being monitored
Returns:
The id of the created report.
"""
account_id, subaccount_id = parse_account(
config,
task['a... | 65,057 |
def init_server(cli_options):
"""Initialize the flashfocus server with given command line options."""
ensure_single_instance()
if cli_options["opacity"]:
warn("--opacity is deprecated, please use --flash-opacity/-o instead")
if "flash_opacity" not in cli_options:
cli_options["fl... | 65,058 |
def test_withdraw_nlocktime(node_factory):
"""
Test that we don't set the nLockTime to 0 for withdrawal transactions.
"""
l1 = node_factory.get_node(1)
l1.fundwallet(10**4)
addr = l1.rpc.newaddr()["bech32"]
tx = l1.rpc.withdraw(addr, 10**3)["tx"]
nlocktime = node_factory.bitcoind.rpc.de... | 65,059 |
def prep_rays_setup(
ghz = 95,
lat_of_cen = 10,
cml = 20,
radius = 1.1,
bfield = None,
distrib = None,
ray_tracer = None,
):
"""Create and return a VanAllenSetup object that will be used in the
"preprays" tool: it precomputes all of the key quantities need... | 65,060 |
def is_admin(
channel: TextChannel, user_or_member: Union[discord.User, discord.Member]
) -> bool:
"""Checks to see if given user or member has the admin role on this server."""
member = (
user_or_member
if hasattr(user_or_member, "roles")
else channel.guild.get_member(cast(discord.U... | 65,061 |
def test_update_user(mocker):
"""Tests the update_user function."""
mocked_user_obj = mocker.patch('app.dbops.AppUser')
mocked_user = mocked_user_obj.query.filter_by.return_value.first.return_value
mocked_user.orgs = []
mocked_db = mocker.patch('app.dbops.db')
user = update_user({'name': 'foo', ... | 65,062 |
def get_tsne_hazium_data(is_drawing=False, verbose=False):
"""
Get TSNE hazium data.
Get TSNE with hazium data. Save this with pickle format. Last modified: 2019-11-27T09:42:47+0900
Args:
is_drawing (bool): If it is true, this function will draw the tsne plot
verbose (bool): Verbosity ... | 65,063 |
def _get_baseline_options(site):
"""
Extracts baseline options from ``site["infer"]["baseline"]``.
"""
# XXX default for baseline_beta currently set here
options_dict = site["infer"].get("baseline", {}).copy()
options_tuple = (options_dict.pop('nn_baseline', None),
options_d... | 65,064 |
def _launch_client(gke_settings, stress_server_settings, stress_client_settings,
bq_settings, kubernetes_proxy):
""" Launches a configurable number of stress test clients on GKE cluster """
if not kubernetes_proxy.is_started:
print 'Kubernetes proxy must be started before calling this functio... | 65,065 |
def test_validate_fetch_incidents_parameters_maxfetch(args, message):
"""Test cases for failure scenarios of validate_fetch_incidents_parameters_success"""
from SolarWinds import validate_fetch_incidents_parameters, ERR_MSG
with pytest.raises(ValueError, match=ERR_MSG[message]):
validate_fetch_incid... | 65,066 |
def find_largest_digit(n):
"""
:param n:
:return:lar
"""
global lar, new_lar
if abs(n) > 0:
r = abs(n) % 10 # 取(剩下的數字)最後的數字 用餘數來取
if lar < r:
lar = r
new_lar = r
find_largest_digit(int(n/10)) # 取剩下的數字
lar = 0 # for the next to compare
return new_lar | 65,067 |
def theaterChaseRainbow(strip, wait_ms=25):
"""Rainbow movie theater light style chaser animation."""
for j in range(256):
for q in range(3):
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i+q, wheel((i+j) % 255))
strip.show()
time.sleep(... | 65,068 |
def convert(value, as_type, source):
"""Convert the value as a given type where the value comes from the given source"""
getter = _get_converter(as_type)
try:
return getter(value)
except Exception as exception:
logging.warning("%s failed to convert %r as %r because %r", source, value, ge... | 65,069 |
def extractMatrix(
source,
bounds=None,
boundsSRS="latlon",
maskBand=False,
autocorrect=False,
returnBounds=False,
band=1,
):
"""extract all or part of a raster's band as a numpy matrix
Note:
-----
Unless one is trying to get the entire matrix from the raster dataset, usage
... | 65,070 |
def solveKnightsTour(n):
"""
function to solve the Knight Tour problem using Backtracking,
It calls the recursive function with the required parameters
Print one of the possible solution
"""
# initialization og board matrix all boxes as -1 means yeat to visit
board = [[-1 for i in ran... | 65,071 |
def write(text, file):
"""
Writes a generated HTML page to a file, but checks with a HTML parser before.
:param text:
:param file:
"""
# output file
if isinstance(file, str):
file = [file]
file = os.path.join(c.web_path, *file)
# check file hash and use previous version
... | 65,072 |
def paginate(items, page=0, max_per_page=10):
"""Simple generic pagination.
Given an iterable, this function returns:
* the slice of objects on the requested page,
* the total number of items, and
* the total number of pages.
The `items` parameter can be a list, tuple, or iterator:
>>>... | 65,073 |
def calculate_sklearn_imputer_output_shapes(operator):
"""
Allowed input/output patterns are
1. [N, C_1], ..., [N, C_n] ---> [N, C_1 + ... + C_n]
It's possible to receive multiple inputs so we need to concatenate
them along C-axis. The produced tensor's shape is used as the
output shape.
... | 65,074 |
def change_hsv(image, sat, bright):
"""
Args:
image : numpy array of image
sat: saturation
bright : brightness
Return :
image : numpy array of image with saturation and brightness added
"""
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
... | 65,075 |
def select_foreground_proposals(
proposals: List[Instances], bg_label: int
) -> Tuple[List[Instances], List[torch.Tensor]]:
"""
Given a list of N Instances (for N images), each containing a `gt_classes` field,
return a list of Instances that contain only instances with `gt_classes != -1 &&
gt_classe... | 65,076 |
def hutchinson_trace_autodiff_blockwise(V):
"""Hessian trace estimate using autodiff block HVPs."""
trace = 0
for _ in range(V):
for p in model.parameters():
v = [rademacher(p.shape)]
Hv = hessian_vector_product(loss, [p], v)
vHv = torch.einsum("i,i->", v[0].flat... | 65,077 |
def check_received_rewards(cadet, reward_tier):
"""[checks if given reward has recieved the reward for the given reward tier]
Arguments:
cadet {[Cadet]} -- [cadet object]
reward_tier {[int]} -- [reward tier]
Return:
boolean
"""
if User_Reward_Log.objects.filter(cadet=c... | 65,078 |
def batch_obs(
obs: List[Observation], obs_space: ObsSpace, action_space: Dict[str, ActionSpace]
) -> ObsBatch:
"""
Converts a list of observations into a batch of observations.
"""
entities = {}
ids = []
action_masks: Dict[str, ActionMaskBatch] = {}
reward = []
done = []
end_of_... | 65,079 |
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'db'):
g.db.disconnect()
if error:
logger.error('Database connection closed because of :' + str(error)) | 65,080 |
def brusselator(t, X, **kwargs):
"""
The Brusselator.
@type t: number
@param t: current time
@type X: vector
@param X: current state
@rtype: vector
@return: derivative
"""
x = X[0]
y = X[1]
if len(kwargs) == 0:
x_dot = 1 - (BRUSS_B + 1) * x + BRUSS_A * x**2 *... | 65,081 |
def _main(args=None):
"""Main entry point for the CLI application.
Args:
args (list): List of arguments to be parsed and used, first one being the command.
"""
if not args:
args = argv[1:]
if cd_is_project() and get_config_value('version') != get_distribution("pavo").version:
... | 65,082 |
def nearest_neghbors(descriptor_dict, descs):
"""
Computes the nearest neighbors of a list of descriptors in a descriptor dictionary
:param descriptor_dict: a descriptor dictionary like in create_kmeans_dict
:param descs: a list of descriptors of an image
:return: the indices of the nearest neighbor... | 65,083 |
def generate_config_from_os():
"""
Determines runlevel and project_env from environment variables, then
returns generate_eve_config(project_env, runlevel).
"""
project_env = ProjectEnv.detect_from_os(fallback_to_default=True)
LOGGER.info("Detected PROJECT_ENV: " + str(project_env))
runlevel... | 65,084 |
def match_bounding_boxes(t_boxes, d_boxes, iou_threshold):
"""Matches detection boxes with tracked boxes based on IoU.
This function can be used to find matches between sets of bounding boxes
found with an object detector and tracked with a tracker. It yields three
arrays with indices indicating which ... | 65,085 |
def OpenStreetMapNominatim(lon, lat):
"""
Get the target's street infomation from ip lon and lat locations by using OpenStreetMap.
請求次數少量可用,大量請求使用MapQuest提供的API.->使用geocoder庫即可。
:param lon: The IP lon infos, which refer WGS84.
:param lat: The IP lat infos, which refer WGS84.
:return: The OpenS... | 65,086 |
def copy_artifacts(config: Configuration) -> None:
"""
Copies compiled JavaScript files to output directory after `transcrypt` has been run.
"""
dist_directory = os.path.join(config.base_dir, 'dist')
try:
os.makedirs(dist_directory)
except OSError as e:
if e.errno == errno.EEXIS... | 65,087 |
def check_format(format, subtype=None, endian=None):
"""Check if the combination of format/subtype/endian is valid.
Examples
--------
>>> import soundfile as sf
>>> sf.check_format('WAV', 'PCM_24')
True
>>> sf.check_format('FLAC', 'VORBIS')
False
"""
try:
return bool(_f... | 65,088 |
def kingdom_death(return_type=None):
""" Returns a dictionary of all assets. """
output = OrderedDict()
all_assets = list_game_assets()
for asset_collection in all_assets:
asset_object = get_game_asset(asset_collection, return_type=object)
if getattr(asset_object, 'is_game_asset', Fals... | 65,089 |
def wait_for_task(task, timeout=60.0, pause_timeout=True):
"""
Waits for a single vim.Task to finish and returns its result.
:param task: The task to wait for
:type task: vim.Task
:param float timeout: Number of seconds to wait before terminating task
:param bool pause_timeout: Pause timeout co... | 65,090 |
def iobes2iob(iobes):
"""Converts a list of IOBES tags to IOB scheme."""
dico = {pfx: pfx for pfx in "IOB"}
dico.update({"S": "B", "E": "I"})
return [dico[t[0]] + t[1:] if not t == "O" else "O" for t in iobes] | 65,091 |
def spread_scores_over_map(score_map):
# type: (np.ndarray) -> np.ndarray
"""Given a 2D score array, spread these scores to their neighbours.
The maximum neighbour wins. Deduct by 1."""
neighbour_scores = np.zeros(score_map.shape + (4,))
neighbour_scores[1:, :, 0] = score_map[:-1, :]
neighbour_scores[:-1, :, 1] ... | 65,092 |
def create_obb(bbox, R, color=(0, 1, 0)):
"""Draw an oriented bounding box."""
assert len(bbox) == 6, f'The format of bbox should be xyzwlh, but received {len(bbox)}.'
obb = o3d.geometry.OrientedBoundingBox(bbox[0:3], R, bbox[3:6])
obb.color = color
return obb | 65,093 |
def resnet50(pretrained=False, fixed_feature=True):
""" "ResNet-50 model from torchvision's resnet model.
:param pretrained: if true, return a model pretrained on ImageNet
:param fixed_feature: if true and pretrained is true, model features are fixed while training.
"""
from torchvision.models.resn... | 65,094 |
def constant_prices_data(report_name: str, investor_name: str, months: int) -> pd.DataFrame:
"""Переводит данные в постоянные цены."""
df = get_investor_data(report_name, investor_name)
df = df.iloc[-months - 1 :]
cpi = indexes.cpi(df.index[-1])
cpi = cpi[-len(df) :]
cpi = cpi.cumprod()
cpi ... | 65,095 |
def delta_update_basesamdb(refsampath, sampath, creds, session, lp, message):
"""Update the provision container db: sam.ldb
This function is aimed for alpha9 and newer;
:param refsampath: Path to the samdb in the reference provision
:param sampath: Path to the samdb in the upgraded provision
:param... | 65,096 |
def pipe_cmds(command1, command2):
"""
Pipe to commands together. Useful for things like `ps x | grep python`
Args:
command1 (str): The initial command to run
command2 (str): The command to receive stdout of command1
Returns:
list: Output of piped command
"""
p1 = subpro... | 65,097 |
def full_url(path):
"""
Return the full URL for the given path (eg. with scheme and domain)
"""
# Only in production
if settings.DEBUG:
return path
else:
return make_full_url(path) | 65,098 |
def check_znak(m1,p1,m2,p2, treshold = 100):
"""
Checks wheather we should check for people to know each other
:type m1: numeric list
:param m1: list with all circles for client 1
:type p1: numeric list
:param p1: list with probabilities of circles for client 1
:type m2: numer... | 65,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.