content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_all_coords(rdmol):
"""Function to get all the coordinates for an RDMol
Returns three lists"""
conf = rdmol.GetConformer()
x_coords = []
y_coords = []
z_coords = []
for atm in rdmol.GetAtoms():
x_coords.append(conf.GetAtomPosition(atm.GetIdx()).x)
y_coords.append(conf.... | 14399748a77d565f2d65f8ae8f47ec2924c64683 | 42,500 |
import os
import logging
def valid_fn(path, fn_name):
"""Shorten file name in case it exceeds system's maximum length."""
PC_PATH_MAX = os.pathconf("/", "PC_PATH_MAX") - 4
PC_NAME_MAX = os.pathconf("/", "PC_NAME_MAX") - 4
full_len = len(path + fn_name)
if full_len > os.pathconf("/", "PC_PATH_MAX"... | d82b25ec7e7bdcc429ec8ab474a6abec2e73ccd3 | 42,501 |
from typing import BinaryIO
from typing import Any
def make_sized_bytes(size):
"""
Create a streamable type that subclasses "hexbytes" but requires instances
to be a certain, fixed size.
"""
name = "bytes%d" % size
def __new__(self, v):
v = bytes(v)
if not isinstance(v, bytes)... | 24f2da59ef3ce64419dfbf585fba51cbd368f417 | 42,502 |
def evaluations(ty, pv):
"""
evaluations(ty, pv) -> ACC
Calculate accuracy using the true values (ty) and predicted values (pv).
"""
if len(ty) != len(pv):
raise ValueError("len(ty) must equal to len(pv)")
total_correct = total_error = 0
for v, y in zip(pv, ty):
if y == v:
... | 021c80dab1d4ed97876bebc882db3423af107ea5 | 42,503 |
def _is_member_of(cls, obj):
"""
returns True if obj is a member of cls
This has to be done without using getattr as it is used to
check ownership of un-bound methods and nodes.
"""
if obj in cls.__dict__.values():
return True
# check the base classes
if cls.__bases__:
f... | c5bfb2920efc3992a92da236471f1de85cdb27a1 | 42,504 |
from typing import Union
from typing import List
def get_base_info(stock_codes: Union[str, List[str]]) -> Union[pd.Series, pd.DataFrame]:
"""
Parameters
----------
stock_codes : Union[str, List[str]]
股票代码或股票代码构成的列表
Returns
-------
Union[Series, DataFrame]
- ``Series`` : 包... | a0d0064eaf0abdadbc9bf5a2cd6a4769085a7421 | 42,505 |
def photom(data,stars,uncertainty=None,rad=[3],skyrad=None,display=None,
gain=1,rn=0,mag=True,utils=True) :
""" Aperture photometry of input image with current star list
"""
# input radius(ii) in a list
if type(rad) is int or type(rad) is float: rad = [rad]
# uncertainty either speci... | e1a79fd63f3ac6be2e6c52eec800e771c586b8b9 | 42,506 |
def process_adapter_message(message):
"""
This method is called from the component logic.
It is up to the developer of the logic to decide how a message
will look like. In the end both parties must support the same
set of messages to be compatible.
One often used message in Wirehome is the _in... | 42464e41e46493701f37cf5f5317c03e1d44d6f4 | 42,507 |
def discount_cumsum(x, dones, gamma):
"""
computing discounted cumulative sums of vectors that resets with dones
input:
vector x, vector dones,
[x0, [0,
x1, 0,
x2 1,
x3 0,
x4] 0]
output:
[x0 + discount * x1... | ee72c39586cca74ff64b00ed3c97b426c8756c8e | 42,508 |
from typing import Iterable
import itertools
def determine_resolves_to_generate(
all_known_user_resolve_names: Iterable[KnownUserResolveNames],
all_tool_sentinels: Iterable[type[GenerateToolLockfileSentinel]],
requested_resolve_names: set[str],
) -> tuple[list[RequestedUserResolveNames], list[type[Generat... | 7ba59edece64a71d01a0651747cf7fc160ea035e | 42,509 |
import torch
def prepare_laplacian(laplacian):
"""Prepare a graph Laplacian to be fed to a graph convolutional layer
"""
def estimate_lmax(laplacian, tol=5e-3):
r"""Estimate the largest eigenvalue of an operator."""
lmax = sparse.linalg.eigsh(laplacian, k=1, tol=tol,
... | 4bd310141f3b19306f1749b80ed8a4c5b01d41f3 | 42,510 |
import hmac
def hash_str(s):
"""Hash the user_id and SECRET (a constant) to create a cookie hash."""
return hmac.new(SECRET, s).hexdigest() | 8df6dfc971788940807ce2762e86feaddb1705bb | 42,511 |
from typing import Optional
from typing import Any
from typing import Tuple
def transition_kernel_wrapper(
current_state: 'fun_mc_lib.FloatNest', kernel_results: 'Optional[Any]',
kernel: 'tfp.mcmc.TransitionKernel') -> 'Tuple[fun_mc_lib.FloatNest, Any]':
"""Wraps a `tfp.mcmc.TransitionKernel` as a `Transiti... | ed67dfe84f211545f73e4e74e16a991eda479557 | 42,512 |
def get_valid_output_response(data):
"""
Returns success message correct processing of post/get request
:param str data: message
:return: response
:rtype: object
"""
response = {"status": 200, "message": "Success", "data": data}
return response | d4b44feafbae82570819595a79205acd765920f0 | 42,513 |
def _get_column_data_type(dataframe: pd.DataFrame):
"""
Returns
-------
when krx.read_date(date='2021-06-22')
{'종목명': 'str',
'시장구분': 'str',
'소속부': 'str',
'종가': 'np.int64',
'대비': 'np.int64',
'등락률': 'float',
'시가': 'np.int64',
'고가'... | 88c3da9999ca8332b05f3035805c25e98c4b5106 | 42,514 |
from typing import Dict
from typing import Any
async def create_pr(
maintainer_can_modify: bool = True,
draft: bool = False,
*,
owner: str,
repo: str,
head: str,
base: str,
title: str,
body: str,
app: Application,
logger: BoundLogger,
) -> Dict[str, Any]:
"""Create a Gi... | b20492f803625d526d3c30afe4ea65bc86f61249 | 42,515 |
def build_metadata_table(city_names):
"""Return the name of a temp file with metadata from the given city."""
metadata = get_complete_metadata(uploadable=True)
city_metadata_rows = metadata[COLUMNS.CITY].str.lower().isin(city_names)
city_metadata = metadata[city_metadata_rows]
city_metadata_file_han... | 234eb9ba29c6918de9063a6f616b026dba0b1c52 | 42,516 |
from datetime import datetime
def format_log_entry(msg):
"""Add timestamp and align msg for logging purposes"""
timestamp = str(datetime.datetime.now())
# Align colon (msg must begin with 'CTRL', 'SEM' or '3VIEW'):
try:
i = msg.index(':')
except:
i = 0
return (timestamp[:22] + ... | 048d878a6a12b4d1e1f0e569f4d09696bf414dcd | 42,517 |
from ldap3.extend import StandardExtendedOperations
from anima.utils import authenticate
def test_authenticate_with_stalker_and_ldap_authenticates_an_existing_ldap_user(ldap_server, create_db, monkeypatch):
"""testing if the anima.utils.authenticate() function will authenticate a
ldap user without a problem
... | 8ea9a4ae5ee8d03eaa869e5f2a0d7101ab2b58cc | 42,518 |
def get_likes_v2(owner_id):
"""Get amount of likes in last 100 posts of any type"""
# wall.get request - get response or raise an error.
try:
response = api.wall.get(owner_id=owner_id, count=100)
except vk.exceptions.VkAPIError:
print('Access denied')
# TODO: get exception key
... | 48e0550b28c8d5294febc73925689cf611a8303a | 42,519 |
def multi_quat_diff(nq1, nq0):
"""return the relative quaternions q1-q0 of N joints"""
nq_diff = np.zeros_like(nq0)
for i in range(nq1.shape[0] // 4):
ind = slice(4*i, 4*i + 4)
q1 = nq1[ind]
q0 = nq0[ind]
nq_diff[ind] = quaternion_multiply(q1, quaternion_inverse(q0))
ret... | 2b99a73f01ba0c712930990b56cd2737390ad8a8 | 42,520 |
def _clean_graph_def(graph_def: tf.compat.v1.GraphDef) -> tf.compat.v1.GraphDef:
"""Edit the GraphDef proto to make it more performant for TFF.
WARNING: This method must _NOT_ make any semantic changes (those that would
change the results of the computation). TFF does not really want to be
modifying the graph ... | d4bef043ae3889c15c9b0c8ba0713e912ebd211c | 42,521 |
import os
def _remove_creds(creds_file=None):
"""
Remove ~/.onecodex file, returning True if successul or False if the file didn't exist
"""
if creds_file is None:
fp = os.path.expanduser("~/.onecodex")
else:
fp = creds_file
if os.path.exists(fp):
os.remove(fp)
... | ea25ea62b825353bd5f71dc003ceb6e530aab7c6 | 42,522 |
def index(path):
"""UI base view."""
return render_template('invenio_app_ils/index.html') | 729f67884dc6996d64bb55ef89c9a7f3a5a40910 | 42,523 |
def wrap_exceptions(callable):
"""Call callable into a try/except clause so that if an
OSError EPERM exception is raised we translate it into
psutil.AccessDenied.
"""
def wrapper(self, *args, **kwargs):
try:
return callable(self, *args, **kwargs)
except OSError, err:
... | 074720b53329f11a79712619f9b24364e93147eb | 42,524 |
def multi_multi_log_loss(predicted,
actual,
class_column_indices=BOX_PLOTS_COLUMN_INDICES,
eps=1e-15):
""" Multi class version of Logarithmic Loss metric as implemented on
DrivenData.org
"""
class_scores = np.ones(len(clas... | 676e7481bcbd5506e526fef449a8f16cd0742609 | 42,525 |
def filter_production_brand(production_id):
"""
产品品牌
:param production_id:
:return:
"""
production_info = get_production_row_by_id(production_id)
return production_info.production_brand if production_info else '-' | 0ffb27e2f615e621c31c58a34cb917c06786b249 | 42,526 |
def print_sami(s, idfile, queryText, outFile=True, verbose=True):
# ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
""" Define a Row Iterator for screen output """
# Prepare some variables.
counter = 0
idlist = []
# Iterate over all supplied rows.
if outFile:
... | 9fda3b8db21bacdc8c845a69b123610145fb3687 | 42,527 |
def extract_tables(sql):
"""
获取sql语句中的库、表名
:param sql:
:return:
"""
tables = list()
for i in extract_tables_by_sql_parse(sql):
tables.append({
"schema": i.schema,
"name": i.name,
})
return tables | 73e9ecbd5f1a243561e64d42d9ec89c630e1770d | 42,528 |
import traceback
def session_wrapper(send_message=True, private=False):
"""Create a session, handle permissions, handle exceptions and prepare some entities."""
def real_decorator(func):
"""Parametrized decorator closure."""
@wraps(func)
def wrapper(update, context):
sessio... | 6a69a802021fce0d6c621441fdd53a08205000c9 | 42,529 |
import requests
def fetch_j_league_schedule(year: int = 1992) -> pd.DataFrame:
"""Load J League schedule dataset."""
url = "https://data.j-league.or.jp/SFMS01/search"
params = {"competition_years": year, "lang": "en"}
response = requests.get(url, params=params)
attrs = {"class": "table-base00 sea... | c1777c989ce8d9a9b8609d4fb0e8c4ffe5378487 | 42,530 |
def cancel_job(request, job_id):
"""
Cancels the current job.
:param request: Django request object.
:param job_id: id of the job.
:return: Redirects to relevant view.
"""
should_redirect = False
# to decide which page to forward if not coming from any http referrer.
# this happens... | da13f47b55cba8a99314043bc87ec0a3ed725b6f | 42,531 |
from typing import Optional
from typing import Dict
from typing import List
def scripts(page_content: Optional[Dict]) -> List[str]:
"""
.. _`example reference server`: https://github.com/stellar/django-polaris/tree/master/example
Replace this function with another by passing it to
``register_integrat... | 8e591eace462a5649533811bf1c54575f5714174 | 42,532 |
def simplesubspec(signal, wlen, inc, NIS, a, b):
"""
simple spectral subtraction denoise
:param signal: noisy speech signal
:param wlen: frame length
:param inc: frame shift
:param NIS: leading unvoiced segment frame number
:param a: over subtraction factor
:param b: gain compensation factor
:return output: de... | dc5982f5bb76095650b8dc5aee05788fb673c065 | 42,533 |
def get_possible_topologies(no_ami_fgs, no_alde_fgs):
"""
Determine possible topologies based on the FGs in BBs.
"""
if no_ami_fgs == 2 and no_alde_fgs == 3:
pos_topo = ['2p3', '4p6', '4p62', '6p9']
elif no_ami_fgs == 3 and no_alde_fgs == 3:
pos_topo = ['1p1', '4p4']
return po... | 99078a354408de8c10bbf0b46dde53b6188d8ac2 | 42,534 |
import tempfile
import os
import sys
def DownloadUsingGsutil(filename):
"""Downloads the given file from Google Storage chrome-wintoolchain bucket."""
temp_dir = tempfile.mkdtemp()
assert os.path.basename(filename) == filename
target_path = os.path.join(temp_dir, filename)
gsutil = download_from_google_stor... | ec8290f96fd1f5af5ace1a806b714c7c82e32e88 | 42,535 |
import requests
def hits(batter_id=None):
"""Get the number of hits for each historical batter. If batterId is specified, only that batter is returned.
`batter_id` is a single string UUID or list of string UUIDs.
Returns dictionary {batter_id: count}"""
params = {}
if batter_id:
params['b... | b0435098eefbb3a48d348beb50d9d4592996920d | 42,536 |
def valid_axes(
draw,
ndim,
pos_only=False,
single_axis_only=False,
permit_none=True,
min_dim=0,
max_dim=None,
):
""" Hypothesis search strategy: Given array dimensionality, generate valid
`axis` arguments (including `None`) for numpy's sequential functions.
Examples from this s... | d5b42530b09fb37df094fd6f1d9ad22cf58cb063 | 42,537 |
def index_intellectuels() :
"""
Route permettant l'affichage de l'index des intellectuels enregistrés
:return : affichage du template index_intellectuels.html
"""
titre="index_intellectuels"
#On vérifie que la base de données n'est pas vide
intellectuells = Intellectuel.query.all()
if len(intellectuells) ==... | 84badd1c1a219d28b44c6f0c513f5c98e4795476 | 42,538 |
import os
def data_file(f):
"""Get absolute path for file inside pythondata_cpu_serv."""
fn = os.path.join(data_location, f)
fn = os.path.abspath(fn)
if not os.path.exists(fn):
raise IOError("File {f} doesn't exist in pythondata_cpu_serv".format(f))
return fn | a6a2feb70c8f67256652c020a3f0dc27b2d5127a | 42,539 |
import time
def random_split_by_user(dataset,
user_id='user_id',
item_id='item_id',
max_num_users=1000,
item_test_proportion=.2,
random_seed=0):
"""Create a recommender-friendly train-test ... | d511ca6a75dcf3aaedf1cdf6ec4480f3e97cce37 | 42,540 |
from typing import Union
from typing import List
from typing import Any
import yaml
def read_yaml(content: Text, reader_type: Union[Text, List[Text]] = "safe") -> Any:
"""Parses yaml from a text.
Args:
content: A text containing yaml content.
reader_type: Reader type to use. By default "safe"... | b4e5b463df4a8044b3e65a6afc9613dd220c6bbf | 42,541 |
import argparse
def describe_argparser():
"""
Return an argument parser for the describe function
"""
parser = argparse.ArgumentParser()
parser.add_argument("variant", help="Variant to describe, example: RV64GC")
return parser | a5c78d2c39373e73204fce8724e240ef084ab0b6 | 42,542 |
def _GetSheriffForTest(test):
"""Gets the Sheriff for a test, or None if no sheriff."""
if test.sheriff:
return test.sheriff.get()
return None | daa272df6a1882e1379531b2d34297da8bec37b3 | 42,543 |
def smooth_surround_LS_v1(p, is_obs, sd_dv):
"""
Smooth via LS on each vic in a loop.
:param p: n, n_vic
:param is_obs: n, n_vic
:param sd_dv:
:return:
x: n, n_vic, 2
"""
n, n_vic = p.shape
x0 = np.zeros((n_vic, 2))
P0 = np.zeros((n_vic, 2, 2))
P0[:] = np.eye(2) * 1e8... | 5688eabd580a6decbc83e5c6f8dc69a2e6c013d2 | 42,544 |
def booth(args):
""" Booth function
Global minimum: f(1.0,3.0) = 0.0
Search domain: -10.0 <= x, y <= 10.0
"""
return (args[0] + 2*args[1] - 7)**2 + (2*args[0] + args[1] - 5)**2 | 8adf94d9e96ee19758a6e495775d8bdb10330794 | 42,545 |
import fnmatch
def is_cms_app(app_name):
"""
Return whether the given application is a CMS app
"""
for pat in appsettings.FLUENT_DASHBOARD_CMS_APP_NAMES:
if fnmatch(app_name, pat):
return True
return False | 80ed2925a9c7464909e336f8f44b1459ab0c8151 | 42,546 |
def deeplabv3_resnet101(pretrained=False, progress=True,
num_classes=21, aux_loss=None, **kwargs):
"""Constructs a DeepLabV3 model with a ResNet-101 backbone.
Args:
pretrained (bool): If True, returns a model pre-trained on COCO train2017 which
contains the same clas... | f07eec8f6abfdc8703875de0f67ed5784bf2849f | 42,547 |
def query_model(master_df, query_sid):
"""
NOTE: Fields containing enzyme, compound PubChem sid, and SMILES string must be named
['entry', 'PubChem', 'SMILES'] respectively
"""
# get query SMILES string & pair query compound with each unique enzyme in the master DataFrame
updated_df = pair_q... | 7daf570e477e4545b05924f543da98556802a539 | 42,548 |
def makeset(weatherpart):
"""
with open("WeatherWear/clothes.csv") as f:
reader = csv.reader(f)
next(reader)
data = []
for row in reader:
data.append(
[float(cell) for cell in row[:13]]
)
clothes = data
"""
clothes = [[0.0... | be8ca4b1e64585fed368bde0baa447a13d2da7e3 | 42,549 |
import requests
from bs4 import BeautifulSoup
def create_soup(url):
"""
Create soup object from url
"""
try:
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
return soup
except Exception as e:
print("[ERROR] Error occurred in requesting htm... | 43c6478754807763a74b03bf346d8735bcbf5ba5 | 42,550 |
def get_vtk_edges(vtkdata):
"""
Get mesh edges.
Parameters
----------
vtkdata : VTK object
Mesh, scalar, vector and tensor data.
Returns
-------
edges : VTK object
Mesh, scalar, vector and tensor data.
"""
edges = vtk.vtkExtractEdges()
if vtk_version < 6:
... | cf9a27c8844e5e51b90fb4b51af79dce200768df | 42,551 |
def DispatchKeyForTagSpecOrNone(tag_spec):
"""For a provided tag_spec, generates its dispatch key.
If the value (or value_casei) is used, uses the first value from the
protoascii.
Args:
tag_spec: an instance of type validator_pb2.TagSpec.
Returns:
a string indicating the dispatch key, or None.
""... | 00a43e14a8a66e218b51b535a3617675a4c3d571 | 42,552 |
def convert_column_to_input(column: Column) -> InputField:
"""Converts a sqlalchemy column into a graphql field or input field"""
sqla_type = type(column.type)
gql_type = convert_input_type(sqla_type)
return InputField(gql_type) | e8237205682c8ce45eacd2822babed21427e5d12 | 42,553 |
import math
def rainbow_search(x, y, step):
"""Returns RGB color tuple
"""
xs = math.sin((step) / 100.0) * 20.0
ys = math.cos((step) / 100.0) * 20.0
scale = ((math.sin(step / 60.0) + 1.0) / 5.0) + 0.2
r = math.sin((x + xs) * scale) + math.cos((y + xs) * scale)
g = math.sin((x + xs) * s... | dc1d05f24fe9fb44857210c9fd962ffa4465e1f9 | 42,554 |
def check_codes(df, col, schema_codes):
"""
Get values not in list of codes.
Parameters
----------
df : pd.DataFrame
col : str
pd.DataFrame column name
schema_codes : array_like
List of allowed values
Returns
-------
array_like
Invalid values
>>> in... | 4ed277e7275678f2487697120828e1bb2c72d8cc | 42,555 |
from typing import Optional
def orbit_number_validator(orbit_number: str) -> Optional[str]:
"""Validates the parameter to check whether it is a valid orbit number
(1 To 999999)
Args:
orbit_number::str
Value that could be orbit number either single value or a range
Returns:
... | 3376816f393711bf0345646c231743d043bcb933 | 42,556 |
def get_result(data: bytes):
"""start the thrift client and transform data to server through the client"""
with TransportClient(host=config.THRIFT_HOST, port=config.THRIFT_PORT) as client:
res = client.send(data)
return res | 6dd3d78451edae58567d4ec32aae8ece463c361a | 42,557 |
def generate_pwd(number=8):
"""
Generate radom secure password
:return: random string for pasword
"""
generater = pwgen.pwgen
password = generater(number)
return password | 690a21dc4cc7185dd394900ef8b77fc7f32daf19 | 42,558 |
def check_devices_connectivity(nr: Nornir) -> bool:
"""
This function will test the connectivity to each devices
:param nr:
:return bool: True if ALL devices are reachable
"""
devices = nr.filter()
if len(devices.inventory.hosts) == 0:
raise Exception(f"[{ERROR_HEADER}] no device ... | 4dc98e1f52184e973449352303fa403a6971a026 | 42,559 |
def map_remove_by_value_rank_range_relative(
bin_name, value, offset, return_type, count=None, inverted=False):
"""Create a map remove by value rank range relative operation
Create map remove by value relative to rank range operation.
Server removes and returns map items nearest to value and greate... | 0bf1f6542dc6bf327c681beb401c524e7470e0ef | 42,560 |
def _has_scf_convergence_message(output_str):
""" Assess whether the output file string contains the
message signaling successful convergence of the SCF procedure.
:param output_str: string of the program's output file
:type output_str: str
:rtype: bool
"""
pattern = 'Conve... | e2f9b7b5a89e6de6d7bf500b61f5e1d8a1c3155d | 42,561 |
from typing import List
from re import I
from typing import Union
def append_measure_register(program: Program,
qubits: List = None,
trials: int = 10,
ham: PauliSum = None) -> Program:
"""Creates readout register, MEASURE instruct... | 71e1c37aee863a3f941d741bf2b9f32a58e6359b | 42,562 |
import copy
def lmfitter(time, data, model, uncertainty=None, verbose=True, **kwargs):
"""Use lmfit
Parameters
----------
data: sequence
The observational data
model: ExoCTK.lightcurve_fitting.models.Model
The model to fit
uncertainty: np.ndarray (optional)
The uncerta... | fd7b86f57717ef6e53a91780b9e79e715816f126 | 42,563 |
def recursive_any_to_dict(anyElement):
"""
Recursive any nested type into a dict (so that it can be JSON'able).
:param anyElement: Just about any 'attrs-ized' instance variable type in Python.
:return: A dict structure
"""
if isinstance(anyElement, dict):
simple_dict = {}
for key... | 7e94c93c9470c218781ee0a0059f8b95b0f663e5 | 42,564 |
from datetime import datetime
import re
import os
import time
import webbrowser
def make_html(ne_list, filename, start_time):
"""Save the report as a HTML file"""
#Keep list of accessible nodes
reachable_nodes=[]
#ne_list contains link status of all nodes
for item in ne_list:
#Us... | d3310ca18e106251b2bc59d74ad45a97917ca2b3 | 42,565 |
from typing import OrderedDict
def genListHeaders(P4Graph):
""" Generate the dictionnary of headers.
P4Graph : JSon imported file
Name, size
"""
headers = OrderedDict()
return headers | 6077d41968dc8958ebf1f0d55d1c05607d77915c | 42,566 |
def colorize(s, color, bold=False, reverse=False, start=None, end=None):
"""
Colorize a string with the color given.
:param string s: The string to colorize.
:param color: The color to use.
:type color: :class:`Colors` class
:param bool bold: Whether to mark up in bold.
:param bool reverse:... | ae50e9d2720d05e99e2ed55e5cd68e6dfd97a4d3 | 42,567 |
def getLinkImage(pageCont):
"""
Extrae el link de la imagen de una obra contenida en pageCont
:param pageCont:
:return: Link de la imagen de la obra
"""
linksImagen = []
imagenInfo = pageCont.find(class_="section-viewer")
for img in imagenInfo.findAll('img'): # Obtención de todos los i... | 1efa0a0a55d7c97784a63f4a904b56ee3d334082 | 42,568 |
def join_url(url, *paths):
"""
Joins individual URL strings together, and returns a single string.
Usage::
>>> join_url("pillar:5000", "shots")
'pillar:5000/shots'
"""
assert isinstance(url, string_type), 'URL must be string type, not %r' % url
url_parts = [url.rstrip('/')]
... | a44dac12ec3be2e72c8c69c9cd11f0798c8d1c66 | 42,569 |
def has_liked(obj, user_or_id):
"""whether the objects is liked by an user.
:param obj: Any Django model instance.
:param user_or_id: :class:`~hashup.users.models.User` instance or id.
"""
obj_type = get_obj_type_for_model(obj)
if isinstance(user_or_id, get_user_model()):
user_id = use... | 9a99267072f943f2927e069cc787f3d582fdf7c8 | 42,570 |
from typing import Dict
import subprocess
from pathlib import Path
def get_existing_mirrored_repos(ssh_host: str) -> Dict[str, str]:
"""Gathers information about the libraries that are currently mirrored."""
run_result = subprocess.run(["ssh", ssh_host, f"bash -c 'sha256sum {GO_DEPS_WWWW_DIR}/*'"], check=True... | 05aa3eca89a228931f2fb890e82d7207e0c0cb84 | 42,571 |
from matplotlib import pyplot as plt
from matplotlib import gridspec
def plot_overlays(stat_imgs, contour_imgs, bg_img=None,
figsize=(2.5, 3), title_fontsize=32, title='', **kwargs):
"""Plots each contour_imgs as an overlay of its corresponding `stat_imgs`.
`contour_imgs` and `stat_imgs` mus... | 642d35848c5681bf832a34796a01440b6b1ab89c | 42,572 |
def _int_to_riff(i: int, length: int) -> bytes:
"""Convert an int to its byte representation in a RIFF file.
Represents integers as unsigned integers in *length* bytes encoded
in little-endian.
Args:
i (int):
The integer to represent.
length (int):
The number of... | 9c382486be14af3e5ec22b5aed7c2d9dc3f21d57 | 42,573 |
def read(filename):
"""
Read the file
"""
if "time" not in filename.name:
args = dict(unpack=True, comments="P", skiprows=2)
else:
args = dict(unpack=True, delimiter=":", usecols=1)
data = np.loadtxt(filename, **args)
return data | ee95c2915972efb0012e51ab8146403829223590 | 42,574 |
from typing import List
def get_site_surveys(client: SymphonyClient, location: Location) -> List[SiteSurvey]:
"""Retrieve all site survey completed in the location.
Args:
location ( `pyinventory.consts.Location` ): could be retrieved from getLocation or addLocation api
Returns:
... | c1107abca990800bb86685753377b3c6da7d4658 | 42,575 |
import sys
def confirm(prompt=None, resp=False):
"""prompts for yes or no response from the user. Returns True for yes and
False for no.
'resp' should be set to the default value assumed by the caller when
user simply types ENTER.
>>> confirm(prompt='Create Directory?', resp=True)
Create Dir... | 3c8aeb8e9d41236a8dae56a6315f34d14ef35444 | 42,576 |
def backwardEliminationP(x, y, sl):
"""Function that applies a Backward Elimination
on a model with p-values only
Arguments:
x {Array} -- The Predictors values
y {Array} -- The Dependent Variable
sl {Float} -- The Significance Level
Returns:
Array -- The New Optimized M... | 0c304dde0c3be264f81331ab3c2ff426ca18c24b | 42,577 |
import pathlib
def sample_odb_fixture():
"""Get the fully qualified path to the sample odb file."""
return str(pathlib.Path(__file__).parent.parent / "resources" / "sample.odb") | 12bb3567dc5c5e86bfd6c1042c1c4c3fe310b95a | 42,578 |
def day_of_week(df):
"""Return weekday/weekend using NHTSA convention."""
hr = df['HOUR']
day = df['DAY_WEEK']
conditions = [
(((day == 2) & hr.between(6, 23)) | day.isin([3, 4, 5]) |
((day == 6) & (hr.between(0, 17) | (hr == 24)))),
(((day == 6) & hr.between(18, 23)) | day.isi... | 5642b2aa96094cecbd33dc3fad04908f689bc41f | 42,579 |
def C_r(m_pert, m_c, a, j1, j2):
""" Constant from resonant part of disturbing function (M+D equation 8.32) """
alpha = (j2/(j2-1))**(2/3)
P = 2*np.pi*np.sqrt(a**3/m_c)
n = 2*np.pi/P
return (m_pert/m_c)*n*alpha*f_d(j1, alpha) | bc6386c474e1eeb2b295c4100b3bbd0a40bd0212 | 42,580 |
import six
import collections
def to_iterable(item):
"""Converts an item or iterable into an iterable."""
if isinstance(item, six.string_types):
return [item]
elif isinstance(item, collections.Iterable):
return item
else:
return [item] | 6d672d231c84c2254b84d5618f35eaf47b7ac71c | 42,581 |
def reproject(link, node, epsg):
"""
reporoject link and node geodataframes
for nodes, update X and Y columns
"""
link = link.to_crs(epsg=epsg)
node = node.to_crs(epsg=epsg)
node["X"] = node["geometry"].apply(lambda p: p.x)
node["Y"] = node["geometry"].apply(lambda p: p.y)
retur... | 5ead99d074ea1d643f598d790b083dda511caa1a | 42,582 |
def task_project1_setup():
"""
Sets up the environment for Project 1.
"""
def invoke_create_extension_hypopg(psql):
sql = f"CREATE EXTENSION IF NOT EXISTS hypopg;"
return f'PGPASSWORD={DB_PASSWORD} psql --host=localhost --dbname={DEFAULT_DB} --username={DB_USERNAME} --command="{sql}"'
... | 25127cfbd805e0e2db4acb7f8dc5fbc28bad7e82 | 42,583 |
def conv2d(conv_input, n, kernel, stride, pad, name='', bias=True, init_method=None, scale=0.1):
"""
define simple 2d convlution
"""
if init_method == 'kaiming_normal':
std = nn.initializer.calc_normal_std_he_forward(
conv_input.shape[1], n, kernel=(kernel, kernel))
w_init =... | b2e8fbb4e2c1d050b3009728705aeda708178077 | 42,584 |
import tqdm
def get_accuracy(params_repl, nbr_samples):
"""Returns accuracy evaluated on the test set."""
good = total = 0
steps = nbr_samples // batch_size #20000 // batch_size
for _, batch in zip(tqdm.trange(steps), ds_test.as_numpy_iterator()):
predicted = vit_apply_repl(params_repl, batch['image'])
... | c2bb6bfcdd380e132049e01bd86c63c72c2fcdb2 | 42,585 |
from typing import cast
def binary_search(ib, sequence_offset, search_range, sorted_sequence, value, right, out_dtype):
"""Common IR generator for binary search used by CPU and GPU backends.
`sorted_sequence` is a N-D Buffer whose innermost dimension we want to search for `value`,
and `search_range` is t... | 2fbd4e100e2eb63251502249255d5d3993168b45 | 42,586 |
import re
def genbank_features_parser(input_filename):
""" Return dictionary with features contains inside a genbank file.
:param str input_filename: genbank formated file
"""
logger.warning("deprecated. please use GenBank.genbank_features_parser instead")
new_feature = {}
records = {}
fe... | 06be96c2734cff0916bbd10f43297632fc4cf0ed | 42,587 |
def guess_shape(dic):
"""
Determine data shape and complexity from Bruker dictionary.
Returns
-------
shape : tuple
Shape of data in Bruker binary file (R+I for all dimensions).
cplex : bool
True for complex data in last (direct) dimension, False otherwise.
"""
# determ... | f76006f17d8deac09752ed8e7299c33dfc19f950 | 42,588 |
def diff_element_with_children():
"""Construct a DiffElement that has some diffs of its own as well as a child diff with additional diffs."""
# parent_element has differing "role" attribute, while "location" does not differ
parent_element = DiffElement("device", "device1", {"name": "device1"})
parent_el... | 618d50580885c4f8792bd51fda0424b191157e6f | 42,589 |
def cohort_preview():
"""List the samples, cases, and counts a given set of cohort filters would produce"""
code = None
response_obj = None
st_logger.write_text_log_entry(log_name, activity_message.format(request.method, request.full_path))
try:
cohort_counts = get_cohort_counts()
... | 911abe454c2405654e0d7418eddc1167a93466fd | 42,590 |
def rle(inarray):
""" run length encoding. Partial credit to R rle function.
Multi datatype arrays catered for including non Numpy
returns: tuple (runlengths, startpositions, values) """
ia = np.asarray(inarray) # force numpy
n = len(ia)
if n == 0:
return (None, ... | b78b2d65e6862c6299bac3bed3435ffdd320ab63 | 42,591 |
def extract_coordinates_combined(ref, trj, sel_string, out_name, start_frame=0, verbose=False):
"""
Extracts selected coordinates from several trajectory files.
Parameters
----------
ref : list of str
File names for the reference topologies.
Can read all MDAnalysis... | ca7e62735710e0b144e9d40deb99fbe54eab44d0 | 42,592 |
def route_search(search_string):
"""
Searches through titles.
Parameters
----------
search_string : str
The search string.
Returns
-------
A JSON string that contains a list of the found titles grouped by categories.
"""
result = _search_video_titles(search_string)
... | e9000eab782ec0ce6efefff05f7759e5b2cbdbc4 | 42,593 |
def katamari():
"""creates and returns the katamari object"""
k = Katamari()
return k | 307acda287717b681de4b1189016be98d45d80b0 | 42,594 |
def fft_fftn(*args, **kwargs):
"""Call the core fft library function fftn.
If the anfft library is used, enable 'measure' optimization.
"""
if using_fft_library == "anfft":
return fft.fftn(*args, measure=True, **kwargs)
else:
return fft.fftn(*args, **kwargs) | 804bd06b668edb98e646885561df833a4eedcdfa | 42,595 |
from autograde.cli.util import load_patched, render, list_results, merge_results, b64str, plot_fraud_matrix, \
def cmd_summary(args):
"""Generate human & machine readable summary of results"""
plot_score_distribution, summarize_results
path = Path(args.result or Path.cwd()).expanduser().absolute()
... | fa1a005340facd3dbbe5d8c3c7bccfd1f103fb5f | 42,596 |
import psutil
def total() -> int:
"""
The total amount of space provided by the storage.
:return: The amount of storage space in Bytes.
"""
storage = psutil.disk_usage('/')
return storage.total | 26435b41c0fa894db2bb24c6a04b1e39ae35b386 | 42,597 |
import os
def folder_name(c):
"""Return salitized name of chat to be used as a folder name."""
c = c.replace(os.path.sep, "|")
d = os.path.join(backup_dir, c)
return d | 0750ec6b81ca362d1262f92d775975a370b99c3d | 42,598 |
import functools
import time
def timing(unit="millisecond", message="{func.__name__}() {time:.3f} {unit}"):
"""Measures the execution time of the function.
The value that can be used for specified the ``unit`` parameter are:
======== ================= ==================
Short Long ... | 73a7b2db1ebf01ee16a811f67ca6c10ca55b379d | 42,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.