content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def test_sparse_classification(): """Check classification for various parameter settings on sparse input.""" class CustomSVC(SVC): """SVC variant that records the nature of the training set""" def fit(self, X, y): super(CustomSVC, self).fit(X, y) self.data_type_ = type(...
95181b2405589c6f7d8aaf561eac513293f0041d
61,600
def unit_uri(ip_address: str) -> str: """Generates URI that is used by MongoDB to connect to a single replica. Args: ip_address: ip address of replica/unit """ return "mongodb://{}:{}/".format(ip_address, PORT)
9b2901c4f00036ed201e82979c0c42ae59c4749f
61,601
def get_ip_spec(addr, subnet=None): """Get the IP address with the subnet prefix length. Args: addr: network.addr object subnet: network.net object Returns: A string of the IP address with prefix length. Raises: Exception: if ip not in subnet """ if subnet is None: ...
d841ec672dcc35fe8352ec368d1841afe92dc885
61,602
import json def load_configuration(descriptor): """ Load configuration from the given descriptor. Could be either a `spleeter:` prefixed embedded configuration name or a file system path to read configuration from. :param descriptor: Configuration descriptor to use for lookup. :returns: Loaded de...
a68e355972510e8aa28be300cfbec6025886be20
61,603
def list_all(request): """Currently unused - Draw a page with a full list of PVs and Alerts. Attributes ---------- request : django.http.HttpRequest Returns ------- django.http.HttpResponse """ context = {} context['pv_list'] = Pv.objects.all() context['alert_list'] = ...
a180e45aa6435dcdab9cf8f34a9e309a5bb88a9a
61,604
def aim (p, q): """Return true if p is "aiming towards" q's half-plane edge.""" # First check if p.tail is in the half-plane of q inside = inhalfplane(p.tail(), q) # compute cross product of q x p to determine orientation # en.wikipedia.org/wiki/Cross_product#Computational_geometry # normalize ...
a1880f4e472a369abf9c8dace9d1f0b55967f4c3
61,605
from typing import Union import os from typing import Set def find_modules(path: Union[str, os.PathLike]) -> Set[str]: """Finds Python modules under a given path and returns them. :param path: The path to search for Python modules :return: A set of found modules """ modules: Set[str] = set() ...
729c9902746549d0fd428ef0318226a864cabad3
61,606
def cancer_variants(institute_id, case_name): """Show cancer variants overview.""" form = CancerFiltersForm(request.args) data = controllers.cancer_variants(store, request.args, institute_id, case_name, form) return data
e28f80a4aed77a8e0638895caa9b0471b08eb0aa
61,607
from descartes.patch import PolygonPatch from matplotlib.collections import PatchCollection def _plot_polygon_collection( ax, geoms, values=None, color=None, cmap=None, vmin=None, vmax=None, **kwargs ): """ Plots a collection of Polygon and MultiPolygon geometries to `ax` Parameters ---------- ...
c9640930ee5cabc65893b49f16383f1c87300de5
61,608
def vecEnv(env_kwargs_local, env_class): """ Local Env Wrapper :param env_kwargs_local: arguments related to the environment wrapper :param env_class: class of the env :return: env for the pretrained algo """ train_env = env_class(**{**env_kwargs_local, "record_data": False, "renders": False...
19bfd52c14815605776dd8fc60d600838e29b4a6
61,609
def searchVisits(**kwargs): """ Search visits data file allVisit-l30e.2.fits, which should be stored in the folder set as environmental variable 'APOGEE_DATA' @Jessica Birky Input: 'id_name' : 2MASS name Output: 'ap_id', 'plates', 'mjds', 'fibers' : info needed to download visit spectra """ ...
1816fed39b3ffd37795247079ff8788d610657cd
61,610
import os import torch def load_eran_dataset(eps_temp=None): """ Load sampled data and define the robustness region """ database_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'datasets/eran') if arguments.Config["data"]["dataset"] == "CIFAR_ERAN": X = np.load(os.path.joi...
5162a75044a7f1b26403375691d99940a2df6a86
61,611
def optimize_read_slicers(sliceobj, in_shape, itemsize, heuristic): """ Calculates slices to read from disk, and apply after reading Parameters ---------- sliceobj : object something that can be used to slice an array as in ``arr[sliceobj]``. Can be assumed to be canonical in the sense ...
4d0fdea55649393ad4d31bf9c332c3cf8d9a437b
61,612
import typing import math def make_pretty_range2(value_low: float, value_high: float, ticks: int = 5, logarithmic: bool = False) -> typing.Tuple[float, float, typing.Sequence[float], float, int, float]: """Returns minimum, maximum, list of tick values, division, and precision. Value high and value low specif...
18e617e696c34919f4ef1eeeb1520300f7d942f4
61,613
from typing import Dict from typing import Any def hardware_compile( schedule: Schedule, hardware_map: Dict[str, Any] ) -> Dict[str, Any]: """ Main function driving the compilation. The principle behind the overall compilation works as follows: For every instrument in the hardware mapping, we ins...
2347e74dc6e4821e455271b297030558f7a670c9
61,614
import os def env_maker(environment_id, seed, serial_id, monitor=False, allow_early_resets=False, normalize_observations=False, normalize_returns=False, normalize_gamma=0.99): """ Create a relatively raw atari environment """ env = gym.make(environment_id) env.seed(seed + serial_id) # M...
54a4fb14017e37306702cc5fb51c06680f794482
61,615
import argparse import sys def get_options(cmd_args=None): """ Argument Parser. """ parser = argparse.ArgumentParser( prog='{}'.format(sys.argv[0]), usage='%(prog)s [options]', description='SAGA Live Monitoring') parser.add_argument( '--tripinfo', type=str, required=True, ...
eab3eff5847defd3e2c68a2924bf2f0410f9a282
61,616
def two_step(A, B, a, b): """Combine linear step followed by a polynomial step into a single polynomial. Designed to process Sabatke polynomials which had a linear transformation ahead of the polynomial fits. Starting from a pair of polynomial arrays A and B such that u = A[i,j[ * xp**(i-j) * yp**...
2331b615dcce83283d320adb99c5fe0a0caee9a8
61,617
def get_test_specific_options(test, BLIND=False, ignore_others=True, ignore_labels=None): """ Function to use for determining test specific options, currently this is tuned to 4CR dataset; Need to be replaced for specific dataset. """ # Need to change when the total test options changed # Color key ...
0b56619a7eefadc58921a1d7145afeba9e7b9d74
61,618
import pandas def load_groundtruth( groundtruth_path, object_path): """Loads the ground truths for visual relationship detection. This function loads the visual relationship ground truths from csv files. Please refer to the dataset description of ``2.5D Visual Relationship Detection'' for more inform...
351c21dd349532ba21dc242086a3a1c6c9debb84
61,619
def create_schedule(section_schedule): """ Create a object of schedule class. By default, current project use the PrioritySchedule class to execute schedule. if user don't want to implement a schedule strategy by yourself, keep the follow default configuration items: [schedule.schedule_module_name]...
852657f61276fc49164716445b10be610c5c3922
61,620
def sense_landmarks(state, field_map, max_observations): """ Observes num_observations of landmarks for the current time step. The observations will be in the front plan of the robot. :param state: The current state of the robot (format: np.array([x, y, theta])). :param field_map: The FieldMap obje...
46bd76faf59e87d030081ebac0a2f939e0bf12d9
61,621
import math def radians(img): """Converts image from degrees to radians""" return img.toFloat().multiply(math.pi).divide(180)
3a2a11d84a9719937771517f13cc37f83f9bac6c
61,622
def generate_array(xml_file): """ Produce a *Ac.hpp, *Ac.cpp, and *.py files for serializable arrays. Return True if xml file was an array, otherwise return False and generate nothing. """ xml = XmlParser.XmlParser(xml_file) if xml() == "array": # # Parse array xml here ...
1d4c73d55d5006de0ddd15613ce52604f3ba3417
61,623
def people(): """ People in organization :return: list of users """ # users = get_users() return dict()
ac2c0b1403d9d00fe7fa6c8b631fefcf71c8266b
61,624
from .gip_router import GipRouter def classFactory(iface): # pylint: disable=invalid-name """Load GipRouter class from file GipRouter. :param iface: A QGIS interface instance. :type iface: QgsInterface """ # return GipRouter(iface)
e46d334e795c99e942baf4e019227411eb3684b7
61,625
def locked_view_after_tomorrow(request): """View, locked starting from tomorrow.""" return HttpResponse('A locked view.')
a0a11f02a6d6cab325616d098cd3b3960c7a2b70
61,626
def SetupPMLForPolarContactsView(Name, Selection1, Selection2, Enable = True, Color = "yellow", Cutoff = None): """Setup PML commands for creating polar contacts view between a pair of selections. The polar contact view is generated using 'util.dist' command. The distance labels are shown by default. A...
88f0a0b7ccc7a09d9afa51af2652836373cd71b9
61,627
import gcsfs.mapping def write_n_chunk_copies_gcs(gcs_path, gcs_project, gcs_token, size, ncopies): """ Return a function to write a chunk by index to the given file to produce n copies of the array. """ def write_n_chunks(index_arr): gcs = gcsfs.GCSFileSystem(gcs_project, token=gcs_token) ...
dd01134e30c700b775204dd4694b4c341016ac76
61,628
def parse_by_category(category, data): """ filters database content by category from dumps :param category: accepts string :param data: accepts multi-dimensional iterable data type :return: returns filtered multi-dimensional LIST containing TUPLES """ new_dat = [] for entry in data: ...
255d69580ed666aac38eaa70442ee4e215a7e802
61,629
def unzip_axes(x: np.ndarray, start_axis: int = 0, end_axis: int = -1) -> np.ndarray: """Unzip (de-interleave) axes starting from `start_axis`. Changes the shape as follows: `[..., X, X, ..., Y, Y, ..., Z, Z, ...] -> [..., X, Y, Z, ..., X, Y, Z, ...]` Args: x: `np.ndarray` wi...
1274f3f5f65758b55a246e54261945a076dd988e
61,630
def user_to_dict(user): """Build a json flask response using the given data. :Returns: A flask response with json data. :Returns Type: :py:class:`flask.Response` """ data = {} if user.is_authenticated: roles = [{'id': r.id, 'description': r.description, 'name': r.name} f...
aed99bf8ff05dfca0b4bac4b2a674c4e71871c54
61,631
def display_home_page(request): """Display the home page of the application""" return render(request, 'index.html', {})
86dd7328b298effcf7285c766bf2296fb8720569
61,632
def iscsi_initiators_result_list(entity): """ Get the IQN and id associated with the Unity ISCSI initiators """ result = [] if entity: LOG.info('Successfully listed.') for item in entity: result.append( { "IQN": item.initiator_id, ...
40a1577ee19bc286059e771e2a8e70b2dc11871e
61,633
from pagure.hooks import BaseHook def get_enabled_plugins(project): """Returns a list of plugins enabled for a specific project. Args: project (model.Project): The project to look for. Returns: (list): A list of tuples (pluginclass, dbobj) with the plugin classess and dbobjects for plugi...
ca9517a1de2f59bcb770e6f40af431f654d38a38
61,634
def return_saved_jobs(): """Returns all the jobs that a user saved.""" user_id = session.get('user_id') if not user_id: flash("Please sign in first to save this job") return redirect("/login") else: user = User.query.options(db.joinedload('saved_jobs')).get(user_id) ...
067ca3d21b1d96dff1323a7e3868ea36a707f267
61,635
def r1_factor(self, other, scale_factor=None, assume_index_matching=False, use_binning=False): """Get the R1 factor according to this formula .. math:: R1 = \dfrac{\sum{||F| - k|F'||}}{\sum{|F|}} where F is self.data() and F' is other.data() and k is the factor to put F' on the ...
f8b1f80f69fe6d950d9a11cfdfec55f5d521205f
61,636
def scaled_normal_trace(field): """ u1 = scaled_normal_trace(field, ellipse) Return the scaled normal trace of the field u along the ellipse. Parameters ---------- field : Field Field class Returns ------- u_dir : Function t ↦ |γ´(t)| ∂ₙu(ε cos(t), sin(t)) """ ...
4dfd823204d59a97c00e2b0f7f1326ab834636f8
61,637
def convert_port(port: int): """ Converts a port number from Integer to HEX-value :param port: Integer which represents a port :return: HEX representation of port number (string), without preceeding '0x' """ port = hex(int(port)) port = port[2:].zfill(4) return port
1e3ac2f74f47355e601a3ca73a39c3b0b416af9d
61,638
def _feature_check_all_variants(metric_df, baseline_variant, assume_normal=True, percentiles=[2.5, 97.5], min_observations=20, nruns=10000, relative=False): """Applies delta to all variants, given a metric.""" baseline_metric = metric_df.iloc[:, 2][metric_df.variant == baseline_variant] def do_delta...
7c03b7a9ff7b4caf245e4f470dca38b82ad74012
61,639
import numpy def calculate_ccc_values(filename, logger, lo=2.0, hi=96.0, bins=1000): """ Determine min and and max values for a Cumulative Count Cut """ ds = gdal.Open(filename) band = ds.GetRasterBand(1) # min, max, mean, std stats = band.GetStatistics(False, True) hist = numpy.array(band.Get...
f5ffee8a16f58bd9d77390bd78689dfec2bd02f1
61,640
def bytes_to_long(bytestring): """Given a ``bytestring`` returns its integer representation ``N``. """ bytestring = '\x00' + bytestring N = int(bytestring.encode('hex'), 16) return N
d62703c6b23ce23c994160936ec3684cde97133e
61,641
import numpy def flatten_training(training_pairs): """Convert active label training pairs to two lists. Args: :training_pairs: (dict) dictionary of either 'match' or 'distinct', where 'match' is a list of pairs of records which are the same, and 'distinct' is a list of pairs o...
0813134356eed5478cf61b73cc054cda8fc460c5
61,642
def extract_sentences(paper_path, para_yes): """extracts sentences from a paper into two lists, given that para_yes contains a list of document element numbers corresponding to paragraphs manually identified as those containing synthesis information""" f = open(paper_path, 'rb') doc = Document.from...
00d866b1bf3a5005776f3b0a6468b7fe3f6bc4c8
61,643
import logging def setup_logging(log_config, instance_id, verbosity_adjust=0, fluentd=None): """ Set up logging such that: - The primary logging entry method is structlog (see http://structlog.readthedocs.io/en/stable/index.html) - By default, the logging backend is Python standard lib logger ...
5f5975a8a3729b1189d7b666a31235f16ec32795
61,644
from typing import Optional from typing import List from typing import Dict from typing import Any def untag_columns( database: str, table_name: Optional[str] = None, columns: Optional[List[str]] = None, key: Optional[str] = None, table_tag: Optional[str] = None, ) -> Dict[str, Any]: """ R...
60067a7dad270d12fa6f2c76f33c7c18b023bca5
61,645
def find_price_inverter(inverter_model): """ Returns the price of the inverter. """ if inverter_model in INVERTERS: return INVERTERS[inverter_model] else: raise 'The inverter does not in database'
6c667b29c4bff206e6fedf537f27647679f51448
61,646
def XdmfConditionResults(h5_results): """Return a list of XDMF Attribute objects for element results in an HDF5 file. Keyword arguments: h5_results -- the HDF5 group containing the results Checks for results stored by variable name in: - h5_results["ConditionDataValues/<variable>"] If no resu...
5765177d74cee3c8c5d80bb7895d7399ac209d6a
61,647
import time def join_abp(): """Joins the LoRaWAN network using Activation By Personalization (ABP)""" lora = LoRa(mode=LoRa.LORAWAN) log('Initializing LoRaWAN (ABP), DEV EUI: {} ...'.format( hexlify(lora.mac()).decode('ascii').upper())) authentication = (unpack(">l", unhexlify(LORA_ABP_DEVADD...
4eec40ced3002752b1f9fe24569007891a1a56d8
61,648
async def save_https(filename: str = "https_proxygrab.txt", method: str = "all"): """Save https proxies from get_proxies_func() function.""" proxies = await get_proxies_func("https", method) with open(filename, "w+") as f: f.write("\n".join(proxies)) return filename
6dce3e0e82493f49927f067c3a83646dc9a37e86
61,649
def variable_replacement(): """ Displays a website with "Hello <name>!", where <name> is passed in as a "name" HTTP GET parameter. With PyCharm, a link to the HTML file referenced will appear next to the method header. :return: HTML data generated from render_template() """ name = request.args.g...
090520a6743765be28ed0c336cf27c7ba43601fe
61,650
import ctypes def ENgetlinknodes(index): """Retrieves the indexes of the end nodes of a specified link. Arguments: index: link index""" j1= ctypes.c_int() j2= ctypes.c_int() ierr= _lib.ENgetlinknodes(index,ctypes.byref(j1),ctypes.byref(j2)) if ierr!=0: raise ENtoolkitError(ierr) retur...
7bec2e57960857398f22ec935de0df569768721a
61,651
import re def to_boolean(obj, true_values=('true', '1'), false_values=('false', '0')): """Convert `obj` to boolean. This is not like the builtin ``bool`` function. By default commonly considered strings values are converted to their boolean equivalent, i.e., ``'0'`` and ``'false'`` are converted to ``...
079732c32ca3993ca0821915782c74d5ca415d64
61,652
from typing import List def create_merge_table(context_id: str, command_id: str, table_names: List[str]) -> str: """ Parameters ---------- context_id : str The id of the experiment command_id : str The id of the command that the merge table table_names: List[str] Its a ...
107578e1a03d2ac699384ef303df0226636d86ae
61,653
from typing import List def nsga2_selection(population) -> List[Individual]: """Apply NSGA-II selection operator on the *population*. Usually, the size of *population* will be larger than *k* because any individual present in *population* will appear in the returned list at most once. Having the size ...
ef7aa70faf0c3cc8d158599785ca74bbe8aeb5aa
61,654
from typing import Dict from typing import Pattern import re def parse_probes(probe_file: str) -> PROBE_CONTAINER: """ Extracts all of the probe directives from the file pointed to by probe_file. """ # lines contains each line of the file which doesn't # start with a # and is not empty. li...
313fee8ca14358d19273bdf4eb38eafdba81b6e8
61,655
import os def validate_xml_file_and_extract_data(xmlfilename, xsdfilename): """ This function is responsible for validating xml file against an xsd and to extract data from xml if validation succeeds :param xmlfilename: This parameter holds the path to the xml file :param xsdfilename: This parameter ...
f630d3939d1949a2bac0f42b423704831b408175
61,656
import os import logging def upload_file(self,file_name: str, bucket: str, object_name=None): """Upload a file to an S3 bucket :param file_name: File to upload :param bucket: Bucket to upload to :param object_name: S3 object name. If not specified then file_name is used :return: True if file was u...
9ed4333c1af6e2a27971c967c705f0ccd7d32950
61,657
def add_families(yaml_metric_groups, yaml_metrics): """Add all metrics as label groups. Takes the known metric groups and the (possibly expanded by identify_incoming_metrics) known metrics, both from the YAML file. Returns a dictionary with these families. """ # Anatomy: metric group, metric, fa...
ca6e8227d03f21b10095db7be9f3088142af7950
61,658
from osgeo import gdal import os def save_vrt( filename=None, array=None, rows=None, cols=None, dtype=None, outfile=None, rsc_file=None, rsc_data=None, interleave=None, bands=[1], num_bands=None, relative=True, metadata_dict=None, metadata_domain=None, verbo...
42e0140fe4ac1b82d58ef0cc7945cedc3197cb20
61,659
def convert_shape_to_tensor(shape, name=None): """Convert a static shape to a tensor.""" if isinstance(shape, (tuple, list)) and not shape: dtype = tf.dtypes.int32 else: dtype = None return tf.convert_to_tensor(shape, dtype=dtype, name=name)
abd5bfad082095c4f954fa6412b15f7dcb7a5fa8
61,660
from ezdxf.lldxf.validator import is_dxf_file, is_binary_dxf_file from ezdxf.tools.codepage import is_supported_encoding from ezdxf.lldxf.tagger import binary_tags_loader from typing import Union from pathlib import Path def readfile( filename: Union[str, "Path"], encoding: str = None, errors: str = "surr...
e398610ab0e8ceb1647399eb3db9bb07c358f6c0
61,661
def mock_subprocess_run(*args, **kwargs): """Mock calls to subprocess by routing them to the right mock""" command = args[0][1] if command == "show": return mock_pip_show(*args, **kwargs) elif command == "freeze": return mock_pip_freeze(*args, **kwargs)
da7b24cef209c1d4d56e55609d3c318d9895d470
61,662
def kick(ips, tau): """Kick operator. """ ips.set_acc(ips) if ips.include_pn_corrections: return kick_pn(ips, tau) return kick_n(ips, tau)
d47e826c0bb8f066fcae25e4ba871d38905f51b0
61,663
def replace_extension(filename, new_extension, add_to_end=False): """Replaces the extension in the filename with the new_extension.""" dot = filename.rfind(".") if dot < 0 or filename[dot + 1:] == new_extension or add_to_end: filename_base = filename else: filename_base = filename[:dot] ...
75b04c37dffb3dd92f3fe12295b18efb52dfa2ef
61,664
from bs4 import BeautifulSoup def wrap_with_tag(html: str, document_wrapper_class: str) -> str: """ Wraps a string of HTML with a div using a given wrapper class Args: html (str): The HTML to be wrapped document_wrapper_class(str): The class with which to wrap the HTML Returns: ...
075cf4ef818eb38f2b0a8a16c76fcc5cc11cdec9
61,665
def slave_entry(slave, programs, filesystems): """ Template tag {% slave_entry slave programms %} is used to display a single slave. Arguments --------- slave: Slave object programs: Array of programs Returns ------- A context which maps the slave object to slave an...
7449eec9d906bfe74245cbdec2a76fd7a2fc8157
61,666
from dateutil import tz import logging def initialize_free(begin_datetime,end_datetime): """ initialize the free time """ #Generates the free time array every date from user defined time ini_free = [] datetime_diff = end_datetime - begin_datetime #Initialize the free date and time free_end_datetime = arrow....
a85e8058375baafb734852be02234c13c3eef415
61,667
def get_scatter_xy(x, y): """ Generate scatterplot with auxiliaries by given columns `x` and `y`. The return is JSON in vega-lite schema. """ df = pd.DataFrame({"x": x, "y": y}) return get_scatter(df)
f782c5efb6a884b0be0816f49f50b31cb99eb0d4
61,668
def extractor(data, cell_type, conditions, cell_type_key="cell_type", condition_key="condition"): """ Returns a list of `data` files while filtering for a specific `cell_type`. # Parameters data: `~anndata.AnnData` Annotated data matrix cell_type: basestring s...
397ec9fa41ae6686e85754aac75c43fab19e817b
61,669
def get_depth_to_slice(image_instance, depth='auto'): """ Parameters ---------- image_instance: ImageInstance An image depth: str|tuple One of {'auto', 'time', 'zStack'} or a tuple containing {'time', 'zStack'} in any order. Which field to read for getting the depth. Returns ...
44d7854db735d3ba077dc61f23a9cf771560748f
61,670
def cfd(signal, fraction, delay=1, threshold=0): """Constant Fraction Discriminator :param np.array signal: the input from the digitizer :param float fraction: the fraction, from 0 to 1 :param float delay: the delay of the CFD :param float threshold: the threshold :return np.array edge_indices:...
25308beffeb29211bd7d6f2f85e16bc621206c1e
61,671
import json def cluster_list_by_ids(realm): """ this function returns the doc matching the cluster id """ cluster = Cluster(ES) account = Account(ES) account_email = json.loads(request.cookies.get('account'))["email"] cluster_ids = request.args.getlist('ids[]') if account.is_active_realm_mem...
9bed8e1b98453d357ea9a406f05e41b8144d527f
61,672
def dreadSkull(Z, p=None, Z0=None, ET=None): """ par_set['zoom'] = 0.4 Args: Z: a real or complex number p: a real of complex number Returns: Z: the result (complex) p[0] MATLAB: Z = (-Z)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)^(exp(Z^x)^(-...
678e0b782a3fb55529ef4afcf35e1207facc5d14
61,673
def rescale_sound(snd_array, rescale): """Rescale the sound with the provided rescaling method (if supported). Args: snd_array (array): The array containing the sound data. rescale ({'standardize', 'normalize', None}): Determines type of rescaling to perform. 'standardize' will divide by the max valu...
ccb8f970d14da59b18eb74118260c33d48c1b7ba
61,674
import logging def count_total_molecules(filename: str) -> int: """Counts number of molecules in a file""" logging.info("Counting total molecules in file %s", filename) total = 0 ifs = oechem.oemolistream(filename) mol = oechem.OEMol() while oechem.OEReadMolecule(ifs, mol): total += 1 ...
ed376769e5468c8d8943e9ab370c69981df69363
61,675
from pathlib import Path def get_and_mark_bundle_cache_version(bundle_base: str, *, previously_bundled: bool) -> int: """ Check and return the bundle cache version. The marker filename is `.bundle_cache_version`. :param str bundle_base: The bundle directory ...
74ab1584b60ffb77dbb3709d01ea4df00a448ea4
61,676
def order_details(order_id): """Shows details of an order. arguments: order_id - id of the order Requires administrator privileges. """ order = Order.get_by_id(order_id) return render_template('order/order_details.html', order=order)
0b59f1ee859129343902c4ac8e326f56b823a680
61,677
def simulate_Poisson(intensity, region=(0, 1), seed=None): """ Provide points that are distributed by a uniform Poisson point process within the boundaries given by `region`. Parameters ---------- intensity : int, float The intensity (points per unit region measure) of the point process ...
5d93a40bf032037e362d857f0bad8e56fec9c78f
61,678
def mdown(context,text): """ Exported version of mdown. """ return _mdown(text)
24efeee8241304335cce0b93421b84e5f5f32dba
61,679
def sample_bernoulli(mean: np.ndarray) -> np.ndarray: """Samples from a bernoulli distribution with `mean`. Args: mean (np.ndarray): Mean of the bernoulli distribution. Returns: np.ndarray: Returns the drawn samples. Example: >>> # Sample from a bernoulli distribution with mea...
9615c38c02f3cd941183bdbdeb187df80bc4d1b3
61,680
import torch import test def construct_and_train(name='last_model', dataset='cifar10', model='vgg', resume=False, epochs=100, lr=0.1, batch_size=128, momentum=0.9, weight_decay=5e-4, comp=False, noscale=False, memory=False, mnorm=False, mback=False, norm_ratio=False): ...
8a75691fd8be9f4d1a35f7f307adb18079276e8c
61,681
import sys def load_img(input_img_path, img_type="color_rgb"): """ 画像の入力 Parameter ---------- input_img_path : str 入力する画像のパス img_type : str color_bgr, color_rgb, color_hsv, gray Return ------- img : numpy.ndarray 入力画像 """ if img_type == "color_bgr"...
469033865d3c16f3ca7664be62628eec46f54030
61,682
import click def command(*args, **kwargs): """ A helper for decorating commands a-la `click.command`, but pulling the help string from `<function>.__doc__` by default. Also allows the use of custom arguments, which are stored on the command, as in "adoc_examples". """ disable_opts = kwarg...
929ac24a4c70e920fc0b238f6ccf98bed1750266
61,683
def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees). Use of Euclidean distance in calculating geographical distance is rarely, if ever, recommended. """ # convert decimal degrees to radians lon1, la...
34dc735d350bba7a33c47cf69d009a2022ee6af2
61,684
import asyncio async def async_setup(hass, config): """Set up the Ais Files platform.""" # register services @asyncio.coroutine async def async_remove_file(call): if "path" not in call.data: return await _async_remove_file(hass, call.data["path"]) @asyncio.coroutine ...
69429f377e0c375b56527ded9d0d7623e4d8d3bf
61,685
def _background(cmd, sockname="dtach"): """ Run tasks in background Make sure dtach is installed. """ return run('dtach -n `mktemp -u /tmp/%s.XXXX` %s' % (sockname, cmd))
05d4c6fcc83d1aaa2552c8594450c80bd47c3acc
61,686
def isinrectbnd(x: int, y: int, xmin: int, ymin: int, xmax: int, ymax: int) -> bool: """Checks if the x and y values lie within the rectangular area defined by xmin, ymin and xmax, ymax Args: x, y: (x,y) coordinates to test xmin, ymin: min (x, ...
3f67de8669a258a554a8754786579517a07bc321
61,687
def get_column_combinations(columns, k=5): """ Returns all possible combinations using k columns. """ results = combinations(columns, k) return results
0bab7b7d9377526d4ac98b6464d4e65435edd7a1
61,688
import binascii def crc_srec(hexstr): """Calculate the CRC for given Motorola S-Record hexstring. """ crc = sum(bytearray(binascii.unhexlify(hexstr))) crc &= 0xff crc ^= 0xff return crc
835da45b3407e2fb32e8a715d465647ea9b86805
61,689
import torch def get_masks(slen, lengths, causal, padding_mask=None): """ Generate hidden states mask, and optionally an attention mask. """ alen = torch.arange(slen, dtype=torch.long, device=lengths.device) if padding_mask is not None: mask = padding_mask else: assert lengths....
828dea2c33420a9e038e739e979d3c8ab211dfef
61,690
def every_other(x, name=None): """Drops every other value from the tensor and returns a 1D tensor. This is useful if you are running multiple inputs through a model tower before splitting them and you want to line it up with some other data. Args: x: the target tensor. name: the name for this op, defa...
848d1050435ba014f627e372cdaea6b637667e35
61,691
from pathlib import Path import os def find_qmk_firmware(): """Look for qmk_firmware in the usual places. This function returns the path to qmk_firmware, or the default location if one does not exist. """ if in_qmk_firmware(): return in_qmk_firmware() if cli.config.user.qmk_home: ...
7637489fa82c89649f5499d35c40fc3f90fe3d3a
61,692
import requests from bs4 import BeautifulSoup import os from typing import Container def crawl(user_input, file_format='json', save_path="."): """ mode : list, must define the :param 'list_' with a list mode : range, must define the :param 'start' and the :param 'end' with integers :param file_format ...
22b92a14c806214c9a67766fe718b049ee5c9d31
61,693
def clock_in(client_id, employee_id, project_id=None): """ Clock in an employee. Args: client_id: The ID of the client the employee works for. employee_id: The ID of the employee who is clocking in. project_id: The ID of the project the employee i...
f895328c624cf94c1e1929ec21770e69546ba174
61,694
def draw_region(img): """Driver function for the user to draw a rectangle Parameters ---------- img : numpy.dnarray image to draw a rectangle on Returns ------- array coordinates of the rectangle the user has draw """ while True: # displaying the image ...
f40a13f33e438de146d52ea1a8f9e71dec55e79a
61,695
def tn_category_columns_builder(features): """Builds tensornet category feature columns.""" columns = {} for slot in set(features): columns[slot] = tn.feature_column.category_column(key=slot) return columns
74d166b31f4aa229d6340c852052a3bef4c202d7
61,696
import os def _get_citeseer_filepath(): # type: () -> Tuple[str, str] """Construct a filepath which stores citeseer dataset. This method does not check if the file is already downloaded or not. Returns: feat_cache_path (str): file path for citeseer dataset (features). edge_cache_path ...
e3ccaddcd8e269c3ca55c2b25797542ec8ef8ad3
61,697
def removepackages(pkgnames, forcedeletebundles=False, listfiles=False, rebuildpkgdb=False, noremovereceipts=False, noupdateapplepkgdb=False): """ Our main function, called by installer.py to remove items based on receipt info. """ if pkgnames == []: mun...
7165d5d26ffce126d529104a589790878ac21693
61,698
def _estimate_sigma_kth( X: np.ndarray, Y: np.ndarray, percent: float = 0.3 ) -> np.ndarray: """Private function to compute kth percent sigma.""" # compute distance matrix dists = pdist_squareform(X, Y) # find the kth distance sigma = kth_percent_distance(dists=dists, k=percent) return sigm...
6f3c93e521eb75af55a7d764caea7d99722356c3
61,699