content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def show_output(frame, frame_number, y_value):
""" Shows the video output in a window. """
cv2.putText(frame, "Frame: %i" % frame_number, (150, 200), cv2.FONT_HERSHEY_SIMPLEX, 2, 255, thickness=3)
cv2.putText(frame, "Y: %s" % str(y_value), (150, 300), cv2.FONT_HERSHEY_SIMPLEX, 2, 255, thickness=3)
cv2.namedWindow(... | 20,800 |
def make_map_counts(events, ref_geom, pointing, offset_max):
"""Build a WcsNDMap (space - energy) with events from an EventList.
The energy of the events is used for the non-spatial axis.
Parameters
----------
events : `~gammapy.data.EventList`
Event list
ref_geom : `~gammapy.maps.WcsG... | 20,801 |
def stats_aggregate():
""" RESTful CRUD Controller """
return crud_controller() | 20,802 |
def format_dB(num):
"""
Returns a human readable string of dB. The value is divided
by 10 to get first decimal digit
"""
num /= 10
return f'{num:3.1f} {"dB"}' | 20,803 |
def _check_index_dtype(k):
"""
Check the dtype of the index.
Parameters
----------
k: slice or array_like
Index into an array
Examples
--------
>>> _check_index_dtype(0)
dtype('int64')
>>> _check_index_dtype(np.datetime64(0, 'ms'))
dtype('<M8[ms]')
>>> _check_in... | 20,804 |
def _wrapper_for_precessing_snr(args):
"""Wrapper function for _precessing_snr for a pool of workers
Parameters
----------
args: tuple
All args passed to _precessing_snr
"""
return _precessing_snr(*args) | 20,805 |
def readpcr(path):
"""
Only for multipattern formats.
"""
with open(path) as file:
lines = file.readlines()
# Strip comments
lines = [line for line in lines if not line.startswith("!")]
pcr = {} # main dictionary
line = 0 # line reference
##### start read
# pcr name... | 20,806 |
def put_file_store(store_name, store, block_on_existing=None, user=None): # noqa: E501
"""Create/update store
# noqa: E501
:param store_name: Name of the store
:type store_name: str
:param store: Store information
:type store: dict | bytes
:rtype: FileStore
"""
if connexion.requ... | 20,807 |
def assign_sections(region_table: RegionTable, sections: Dict[str, int]):
"""Assign memory sections.
This is a packing problem and therefore reasonably complex.
A simplistic algorithm is used here which may not always be optimal if user
assigned addresses are used for some sections.
"""
used_sp... | 20,808 |
def humanize_arrow_date( date ):
"""
Date is internal UTC ISO format string.
Output should be "today", "yesterday", "in 5 days", etc.
Arrow will try to humanize down to the minute, so we
need to catch 'today' as a special case.
"""
try:
then = arrow.get(date).to('local')
now... | 20,809 |
def getCourseTeeHoles(request, courseId, courseTeeId):
"""
Getter function for list of courses and tees
"""
resultList = list(Tee.objects.filter(course_tee_id=courseTeeId).values('id', 'yardage', 'par', 'handicap', 'hole__id', 'hole__name', 'hole__number'))
return JsonResponse({'data' : resultList}) | 20,810 |
def simulate(SNOwGLoBESdir, tarball_path, detector_input="all", verbose=False):
"""Takes as input the neutrino flux files and configures and runs the supernova script inside SNOwGLoBES, which outputs calculated event rates expected for a given (set of) detector(s). These event rates are given as a function of the n... | 20,811 |
def args():
"""
Argument Parsing Handler:
-m <path_to_keras> :
Path to keras model
-o <model_output> :
Path to directory that will store pb model
"""
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--path_to_keras", type=str,
help="Path to keras... | 20,812 |
def test_add_htmls_to_section():
"""Test adding html str to mne report."""
report = Report(info_fname=raw_fname,
subject='sample', subjects_dir=subjects_dir)
html = '<b>MNE-Python is AWESOME</b>'
caption, section = 'html', 'html_section'
report.add_htmls_to_section(html, caption,... | 20,813 |
def set_transactions_received(sender, instance, signal, created, **kwargs):
""" Check if a transactions was received """
if instance.balance <= 0:
return # Balance too small
for transaction_request in instance.transactionrequest_set.all():
if transaction_request.payment_received:
... | 20,814 |
def create_zone_ajax(request):
"""
This view tries to create a new zone and returns an JSON with either
'success' = True or 'success' = False and some errors.
"""
qd = request.POST.copy()
# See if the domain exists.
# Fail if it already exists or if it's under a delegated domain.
root_d... | 20,815 |
def print_shape(torch_dict, paddle_dict):
"""
Compare state dictionary from pytorch and paddle.
:param torch_dict:
:param paddle_dict:
:return:
"""
for k, v in torch_dict.items():
if k in paddle_dict:
print("key:", k, ", torch shape:", v.shape, ", paddle shape:", paddle_d... | 20,816 |
def region_distance(**kwargs):
"""Create scatter plot of distance to theoretical AF over every region."""
reader, regions = _setup_region_values(**kwargs)
region_distance_main(
reader,
kwargs.get("output_dir"),
regions,
kwargs.get("name"),
kwargs.get("dpi")
) | 20,817 |
def main_plot():
"""The view for rendering the scatter chart"""
img = get_main_image()
return send_file(img, mimetype='image/png', cache_timeout=0) | 20,818 |
def test_arbitration_id_integer(expected: int, parts: ArbitrationIdParts) -> None:
"""It should convert parts to an arbitration id."""
c = ArbitrationId(parts=parts)
assert c.id == expected | 20,819 |
def symbols_involved(expression):
"""
Lists the symbols that are present in this expression.
"""
expression.atoms(sympy.Symbol) | 20,820 |
def Ising2dT(beta = 0.4, h = 0, isSym = False):
"""
T = Ising2dT(J,h).
-------------------------
Set up the initial tensor for 2d classical Ising model on a square lattice.
Argument: J is defined to be beta * J = J / kT, and h is
defined to be beta*h = h / kT, where J and h are conventional coup... | 20,821 |
def __grid_count(self):
"""Get number of grids in the case"""
try:
return self.__case_stub.GetGridCount(self.__request()).count
except grpc.RpcError as exception:
if exception.code() == grpc.StatusCode.NOT_FOUND:
return 0
return 0 | 20,822 |
def run( # noqa: C901
in_json: in_params.InputConfigurationType,
out_dir: str,
epi_step: int = 30,
region_size: int = 500,
disparity_margin: float = 0.02,
epipolar_error_upper_bound: float = 10.0,
epipolar_error_maximum_bias: float = 0.0,
elevation_delta_lower_bound: float = -1000.0,
... | 20,823 |
def load_fixtures():
"""Loads data from tests/fixtures into the connected database"""
db.database_proxy.create_tables([StorageGroup, StorageNode])
# Check we're starting from a clean slate
assert StorageGroup.select().count() == 0
assert StorageNode.select().count() == 0
with open(path.join(te... | 20,824 |
def timer(method):
"""
Decorator to time a function.
:param method: Method to time.
:type method: function
"""
def wrapper(*args, **kwargs):
"""
Start clock, do function with args, print rounded elapsed time.
"""
starttime = compat.perf_clock()
method(*ar... | 20,825 |
def test_get_tool_descriptor_given_relative_path_success():
"""Test `GET /tools/{id}/versions/{version_id}/{type}/descriptor/
{relative_path}` for retrieving descriptor given relative file_path.
"""
relative_path = MOCK_DESCRIPTOR_FILE["tool_file"]["path"]
endpoint = (
f"/tools/{test_obj_id}... | 20,826 |
def plot_map_from_nc(path_nc, out_path, var_name, xaxis_min=0.0, xaxis_max=1.1, xaxis_step=0.1,
annotate_date=False, yr=0, date=-1, xlabel='', title='', tme_name='time', show_plot=False,
any_time_data=True, format='%.2f', land_bg=True, cmap=plt.cm.RdBu, grid=False, fill_mask=Fa... | 20,827 |
def f5_add_policy_method_command(client: Client, policy_md5: str, new_method_name: str,
act_as_method: str) -> CommandResults:
"""
Add allowed method to a certain policy.
Args:
client (Client): f5 client.
policy_md5 (str): MD5 hash of the policy.
new... | 20,828 |
def shortdate(value: Union[datetime, date]) -> str:
"""Render a date in short form (deprecated for lack of i18n support)."""
dt: Union[datetime, date]
utc_now: Union[datetime, date]
if isinstance(value, datetime):
tz = get_timezone()
if value.tzinfo is None:
dt = utc.localize... | 20,829 |
def test_set(sc,
idfModel,
numFeatures,
test_file = "data/test_clean.csv"
):
"""
Input :
IDF model obtained in the training phase
number of retained features in the tweet-term structure
Output :
normalized twee... | 20,830 |
def is_object_based_ckpt(ckpt_path: str) -> bool:
"""Returns true if `ckpt_path` points to an object-based checkpoint."""
var_names = [var[0] for var in tf.train.list_variables(ckpt_path)]
return '_CHECKPOINTABLE_OBJECT_GRAPH' in var_names | 20,831 |
def search(todos, **kwargs):
"""Return a list of todos that matches the provided filters.
It takes the exact same parameters as the :class:`todotxtio.
Todo` object constructor, and return a list of :class:`todotxtio.Todo` objects as well.
All criteria defaults to ``None`` which means that the criteria... | 20,832 |
def evaluate_prettiness(sampler=None,
folder=None,
input_2='cifar10-train',
n=50000,
batch_size=1000,
clean_afterwards=False,
fid=False,
isc=False,
... | 20,833 |
def read_file(input_file):
"""
Read an SRT file to SrtEntry objects,
Args:
input_file (string): input file name
Yields:
generator of SrtEntry objects
"""
for seq, begin, end, text in read_file_tuples(input_file):
entry = SrtEntry()
entry.seq = seq
entry.... | 20,834 |
def send_desc_request(controller, switch):
"""Method responsible for request stats of flow to switches.
Args:
controller(:class:`~kytos.core.controller.Controller`):
the controller being used.
switch(:class:`~kytos.core.switch.Switch`):
target to send a stats request.
... | 20,835 |
def test_authenticate_returns_a_user(rf, django_user_model):
"""
We can't do the real authentication but we do need to make sure a
real user is returned from the backend authenticate method if the
TokenValidator succeeds, so fake success and see what happens.
"""
user = django_user_model.objects... | 20,836 |
def print_shape(varname, var):
"""
:param varname: tensor name
:param var: tensor variable
"""
print('{0} : {1}'.format(varname, var.get_shape())) | 20,837 |
def gather(first_step: str = PATH, *, filename: str = FILE, stamp: bool = True) -> dict[str, dict[str, Any]]:
"""Walk the steps on the path to read the trees of configuration."""
user = USER if filename == FILE else filename.split('.')[0]
trees = [(where, tree) for where, tree in walk_the_path(first_step, ... | 20,838 |
def test_mlp (learning_rate = 0.01, L1_reg = 0.00, L2_reg = 0.0001, n_epochs = 1000,
dataset = 'mnist.pkl.gz', batch_size = 20, n_hidden = 500):
"""
Gradient descent on a multi-layer-perceptron
learning_rate : float
factor for gradient descent
L1_reg : float, L1-... | 20,839 |
def WriteUmbrellaHeader(output_path, imported_headers):
"""Writes the umbrella header.
Args:
output_path: The path to the umbrella header.
imported_headers: A list of headers to #import in the umbrella header.
"""
year = datetime.date.today().year
header_guard = ComputeHeaderGuard(output_path)
impo... | 20,840 |
def main(args):
"""
An intermediate function that will call either REINFORCE learn or PPO learn.
Parameters:
args - the arguments defined below
Return:
None
"""
if args.alg == 'PPO':
train_ppo(args)
elif args.alg == 'reinforce':
train_rei... | 20,841 |
def _extractKernelVersion(kernel):
"""
Extract version string from raw kernel binary.
@param bytes kernel Raw kernel binary.
@return string Version string if found.
"""
try:
versionOffset = kernel.index(b'Linux version')
for i in range(versionOffset, versionOffset+1024):
... | 20,842 |
def get_vdw_rad(atomic_num):
"""Function to get the user defined atomic radius"""
atomic_rad_dict = {6: 1.7, 7: 1.55, 8: 1.52, 9: 1.47}
if atomic_num in atomic_rad_dict:
return atomic_rad_dict[atomic_num]
else:
return float(Chem.GetPeriodicTable().GetRvdw(atomic_num)) | 20,843 |
def main():
"""Main export program"""
# Read input arguments
args = get_args()
# Read articles from database
print('Exporting retracted articles to %s...' % args.file)
rows = []
articles = Article.query.order_by(Article.id).all()
for article in articles:
fields = {
... | 20,844 |
def input_literal(term, prompt):
"""Get console input of literal values and structures."""
while True:
input_string = read_line(term, prompt)
if input_string:
break
return eval_literal(input_string) | 20,845 |
def walk2(top, topdown=True, onerror=None, followlinks=False, level=False,
excludes=None):
"""
Add options to os.walk:
exclusive filtering for dirnames, filenames (list or regex)
level option
:param top: <string>; see os.walk
:param topdown: <boolean>; see os.walk
:param o... | 20,846 |
def test_example(cx,
name=None,
tag=None,
):
"""Test a specific doc example in the current virtual environment."""
if name is None:
examples = visit_examples()
else:
examples = [name]
for example in examples:
path = example
assert pat... | 20,847 |
def _parse_string(
value_expr: str, target_expr: str, ref_parts: List[str],
a_type: Union[mapry.String, mapry.Path],
pattern_uids: Mapping[Pattern[str], int],
auto_id: mapry.go.generate.AutoID) -> str:
"""
Generate the code to parse a string.
The code parses the JSONable ``v... | 20,848 |
def add_metadata_for_subject (rdf_graph,subject_uri,namespaces,nidm_obj):
"""
Cycles through triples for a particular subject and adds them to the nidm_obj
:param rdf_graph: RDF graph object
:param subject_uri: URI of subject to query for additional metadata
:param namespaces: Namespaces in input g... | 20,849 |
def cleanup_makefile():
"""Delete any leftover BUILD files from the Makefile build.
These files could interfere with Bazel parsing.
"""
makefile_download_dir = os.path.join(_TF_WORKSPACE_ROOT, 'tensorflow',
'contrib', 'makefile', 'downloads')
if os.path.isdir(makefile_d... | 20,850 |
def get_dots_case_json(casedoc, anchor_date=None):
"""
Return JSON-ready array of the DOTS block for given patient.
Pulling properties from PATIENT document.
Patient document trumps casedoc in this use case.
"""
if anchor_date is None:
anchor_date = datetime.now(tz=timezone(settings.TIM... | 20,851 |
def rel_path(path, parent_path):
"""Return path relative to parent_path."""
# Use realpath to avoid issues with symlinked dirs (see gh-7707)
pd = os.path.realpath(os.path.abspath(parent_path))
apath = os.path.realpath(os.path.abspath(path))
if len(apath) < len(pd):
return path
if apath =... | 20,852 |
def sleeping_func(arg, secs=10, result_queue=None):
"""This methods illustrates how the workers can be used."""
import time
time.sleep(secs)
if result_queue is not None:
result_queue.put(arg)
else:
return arg | 20,853 |
def _callable_intersect(in_file, callable_bed, data):
"""Return list of original VCF SVs intersected by callable regions.
Does not try to handle BNDs. We should resolve these and return where possible.
"""
with tx_tmpdir(data) as tmpdir:
in_bed = os.path.join(tmpdir, "%s-convert.bed" % utils.sp... | 20,854 |
def suffix(s):
"""Add '3' suffix to programs for Python 3."""
if sys.version_info[0] == 3:
s = s + '3'
return s | 20,855 |
def test_resolve_recursive_reference_returns_and_adds_orphan(
mocker: MockerFixture,
) -> None:
"""Returns first referenced component and adds orphans to schema."""
component = mocker.MagicMock(spec=ModelElement)
orphan = mocker.MagicMock(spec=ModelElement)
model_element_uris = [None, component, Non... | 20,856 |
def make_coll(db_auth, db_user, db_pass, mongo_server_ip='127.0.0.1'):
"""
Function to establish a connection to a local MonoDB instance.
Parameters
----------
coll_name: String.
Name of MongoDB collection to retrieve.
db_auth: String.
MongoDB database that sh... | 20,857 |
def convert_directory_to_txt(directory):
""" Converts an entire directory of PDF to TXT file
Variables
---------
directory: directory in which many PDFs are placed
"""
for filename in glob.iglob('{}*.pdf'.format(directory)):
convert_pdf_to_txt(filename) | 20,858 |
def sms_send(recipient):
"""
Attempt to send SMS message using Twilio's API.
If this fails, use the Summit API to send the SMS message.
"""
body = request.get_data()
try:
message = send_sms_through_provider('Twilio', recipient, body)
except TwilioRestException:
message = send... | 20,859 |
def cat_to_sub_cat(
dp: Image, categories_dict_names_as_key: Dict[str, str], cat_to_sub_cat_dict: Optional[Dict[str, str]] = None
) -> Image:
"""
Replace some category with its affiliated sub category of CategoryAnnotations. Suppose your category name is 'foo'
and comes along with sub_category_annotatio... | 20,860 |
def index_to_str(idx):
"""
Generates a string representation from an index array.
:param idx: The NumPy boolean index array.
:return: The string representation of the array.
"""
num_chars = int(idx.shape[0] / 6 + 0.5)
s = ""
for i in range(num_chars):
b = i * 6
six = idx... | 20,861 |
def ais_refactor(package, proprietary, consent, color, organisation, industry,
country, admin_area):
"""Refactor a STIX package to meet AIS requirements."""
# Add an AIS Marking to the header
# Note add_ais_marking() removes existing markings
ais.add_ais_marking(
stix_package=pa... | 20,862 |
def ArclinkStatusLine_ClassName():
"""ArclinkStatusLine_ClassName() -> char const *"""
return _DataModel.ArclinkStatusLine_ClassName() | 20,863 |
def build_sfdisk_partition_line(table_type, dev_path, size, details):
"""Build sfdisk partition line using passed details, returns str."""
line = f'{dev_path} : size={size}'
dest_type = ''
source_filesystem = str(details.get('fstype', '')).upper()
source_table_type = ''
source_type = details.get('parttype',... | 20,864 |
def test_load_from_env_missing(example_config_env_missing):
"""Test looking up a config file via an environment variable that is set to a nonexistent file."""
a = ExampleConfig.load(
number=3,
floaty_number=5,
flag=False,
word='hello',
_lookup_config_envvar='config',
... | 20,865 |
def parse_args() -> argparse.Namespace:
"""Parse user command line arguments."""
parser = argparse.ArgumentParser(
description='compare annotations in xml format between different image label sets')
parser.add_argument('--verbose', action='store_true')
parser.add_argument('--prune', action='st... | 20,866 |
def get_allocation_window(allocation,
default_start_date=_get_zero_date_utc(),
default_end_date=_get_current_date_utc()):
"""
Returns a tuple containing the allocation windows start and end date
"""
if not allocation.start_date:
window_start_da... | 20,867 |
def get_instances_in_service(group, region: str):
"""Get set of instance IDs with ELB "InService" state"""
instances_in_service = set()
# TODO: handle auto scaling groups without any ELB
lb_names = group["LoadBalancerNames"]
if lb_names:
# check ELB status
elb = BotoClientProxy("elb"... | 20,868 |
def IDFromUID(s,code=''):
""" Create an ID object from the given string UID.
This can raise an Error in case the string does not map to a
valid UID. code is used in the verification process if given.
"""
id = _EmptyClass()
id.__class__ = ID
id.set_uid(s,code)
return id | 20,869 |
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up Tuya (de)humidifier dynamically through Tuya discovery."""
hass_data: HomeAssistantTuyaData = hass.data[DOMAIN][entry.entry_id]
@callback
def async_discover_device(devi... | 20,870 |
def ordered_pair_accuracy(labels, predictions, weights=None, name=None):
"""Computes the percentage of correctedly ordered pair.
For any pair of examples, we compare their orders determined by `labels` and
`predictions`. They are correctly ordered if the two orders are compatible.
That is, labels l_i >... | 20,871 |
def samp(*args, **kwargs):
"""
The HTML <samp> element is an element intended to identify sample
output from a computer program. It is usually displayed in the
browser's default monotype font (such as Lucida Console).
"""
return el('samp', *args, **kwargs) | 20,872 |
def get_fsuae_dir():
"""Get FS-UAE dir"""
user_home_dir = os.path.expanduser('~')
directories = [os.path.join(user_home_dir, _f) for _f in os.listdir(user_home_dir) \
if os.path.isdir(os.path.join(user_home_dir, _f))]
for directory in directories:
fsuae_dir = os.path.join(direc... | 20,873 |
def _generate_sections_of_url(url: str) -> 'List[str]':
"""Generate Sections of a URL's path
:param url: The URL you wish to split
:type url: str
:return: A list of url paths
:rtype: List[str]
"""
path = urlparse.urlsplit(url).path
sections = []
temp = ""
while (path != '/'):
temp = os.path... | 20,874 |
def get_ucs_cco_image_list(username=None, password=None, mdf_id_list=None,
proxy=None):
"""
Gets the list of images available on CCO
Args:
username (str): username to connect to image server
password (str): password to connect to image server
mdf_id_list (... | 20,875 |
def knownTypes():
"""Returns all known resource types"""
return loader.typeToExtension.keys()+['WorldModel','MultiPath','Point','Rotation','Matrix3','ContactPoint'] | 20,876 |
def run(args: argparse.Namespace) -> None:
"""Run."""
with open_read_text(args.input) as fp:
coco: GtType = json.load(fp)
scalabel, config = coco_to_scalabel(coco)
has_videos = all(frame.videoName is not None for frame in scalabel)
if not has_videos:
assert args.output.endswith(".js... | 20,877 |
def _check_dict_value(_dict: dict, prefix: str = ''):
"""
递归检查字典中任意字段的值是否符合要求
:param _dict: 被检查的字典
:param prefix: 递归时键值的前缀
:return:
"""
keys = list(_dict.keys())
for key in keys:
value = _dict[key]
if isinstance(value, (np.str, str)) or value is None:
con... | 20,878 |
def args_for_blocking_web_whatsapp_com_http():
""" Returns arguments for blocking web.whatsapp.com over http """
return ["-iptables-reset-keyword", "Host: web.whatsapp.com"] | 20,879 |
def zeta_vector():
"""The :func:`zeta` vector.
:func:`zeta_vector` returns :math:`\zeta` parameters calculated
by formula (5) on page 17 in `the technical paper`_, which is
.. math::
\\bf \zeta= W^{-1}(p-\mu)
"""
return np.linalg.inv(W_matrix()) @ (m_vector() - mu_vector()) | 20,880 |
def check_if_raster_file_exists(fpath: str):
""" Check if GeoTif file exists """
if not os.path.isfile(fpath):
raise FileNotFoundError(f'{fpath} not found!\nRun download()') | 20,881 |
def get_fourier_col_name(k, col_name, function_name="sin", seas_name=None):
"""Returns column name corresponding to a particular fourier term, as returned by fourier_series_fcn
:param k: int
fourier term
:param col_name: str
column in the dataframe used to generate fourier series
:param... | 20,882 |
def field_by_regex(fc, field_regex, escape_tables=True):
"""Returns a list of field names matching a regular expression."""
for f in arcpy.Describe(fc).fields:
if escape_tables:
field_regex = field_regex.replace("$.", "\\$\\.")
if re.findall(field_regex, f.name):
yield f.... | 20,883 |
def unique_filename():
"""Creates a UUID-based unique filename"""
return str(uuid.uuid1()) | 20,884 |
def _create_trajectory(molecule):
"""Create an `mdtraj` topology from a molecule object.
Parameters
----------
molecule: openff.toolkit.topology.Molecule
The SMILES pattern.
Returns
-------
mdtraj.Trajectory
The created trajectory.
"""
import mdtraj
# Check whe... | 20,885 |
def display_notification(video_source, requested_target, remote_domain):
"""Show notification to the user"""
notification_ui = notification.Notification()
notification_ui.video_source = video_source
notification_ui.requested_target = requested_target
notification_ui.remote_domain = remote_domain
... | 20,886 |
def preprocess(image):
"""Load and preprocess image."""
# Create the array of the right shape to feed into the keras model
data = []
size = (96, 96)
image = ImageOps.fit(image, size, Image.ANTIALIAS)
image = np.asarray(image)
x = preprocess_input(image)
data.append(x)
data = np.array... | 20,887 |
def create_images(link_array, c_id):
"""
Inserts every image in the array with a category
Parameters
----------
link_array : array
an array of links.
c_id : int
id of a category
"""
for link in link_array:
Image.create_image(link=link[0], description='',
... | 20,888 |
def move_to(obj, device):
"""Credit: https://discuss.pytorch.org/t/pytorch-tensor-to-device-for-a-list-of-dict/66283
Arguments:
obj {dict, list} -- Object to be moved to device
device {torch.device} -- Device that object will be moved to
Raises:
TypeError: object is of type that is... | 20,889 |
def split(C, dims, axis=1):
"""
Splits the columns or rows of C.
Suppse C = [X_1, X_2, ..., X_B] is an (n x sum_b d_b) matrix.
Returns a list of the constituent matrices as a list.
Parameters
----------
C: array-like, shape (n, sum_b d_b)
The concatonated block matrix.
dims: li... | 20,890 |
def test_underscored_number(
parse_tokens,
assert_errors,
default_options,
code,
):
"""Ensures that underscored numbers raise a warning."""
file_tokens = parse_tokens(code)
visitor = WrongPrimitivesVisitor(default_options, file_tokens=file_tokens)
visitor.run()
assert_errors(visito... | 20,891 |
def write_xyz_file_from_structure(struct, filename, labels=True):
"""
From a StructureData, returns an xyz file located in `filename`
absolute path.
"""
xyz_tuple = struct._prepare_xyz()
if labels:
# We add the labels
open(filename, 'wb').write(xyz_tuple[0])
else:
#... | 20,892 |
def build_binary_value(char_str, bits, alphabet) -> str:
"""
This method converts a string char_str into binary, using n bits per
character and decoding from the supplied alphabet or from ASCII when bits=7
This is almost the inverse method to build_string in the decompress module.
:param char_str:... | 20,893 |
def computeAnswer(inputData):
"""Compute the answer to the task, from the input data."""
# Do some calculations on the inputData
answer = str(int(inputData) * 2)
# EDIT ME (remove this line once done)
return answer | 20,894 |
def label_schema_matching(
df, endpoint=DBpedia, uri_data_model=False, to_lowercase=True, remove_prefixes=True,
remove_punctuation=True, prefix_threshold=1, progress=True, caching=True):
"""A schema matching method by checking for attribute -- rdfs:label between
links.
Args:
df (pd.DataFr... | 20,895 |
def write_feature_importance(model: int,
fname: str):
"""Write sorted feature importance data to `fname`.
Args:
model: a Catboost model
fname: destination
"""
importance = model.get_feature_importance(type=EFstrType.FeatureImportance)
logging.vlog(1, "Feature importance retu... | 20,896 |
def create_stats_table(stats, yaxes):
""" Create data table with median statistics
Parameters
----------
stats : :obj:`list`
List of lists containing data stats for each iterations from
:func:`ragavi.ragavi.stats_display`
yaxes : :obj:`list`
Contains y-axes for the current pl... | 20,897 |
def get_last_month_date_dmy() -> str:
"""Returns last month date (dd/mm/yyyy for calls report)."""
return (datetime.now() - timedelta(30)).date().strftime("%d/%m/%Y") | 20,898 |
def irange(start, end):
"""Inclusive range from start to end (vs. Python insanity.)
irange(1,5) -> 1, 2, 3, 4, 5"""
return range( start, end + 1 ) | 20,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.