code
stringlengths
70
11.9k
docstring
stringlengths
4
7.08k
text
stringlengths
128
15k
def seqs_continuous_indexesnot_slices(ol,value,seqs): rslt = [] length = ol.__len__() seq = -1 cursor = 0 begin = None slice = [] while(cursor < length): cond1 = not(ol[cursor] == value) cond2 = (begin == None) if(cond1 & cond2): begin = cursor ...
from elist.elist import * ol = [1,"a","a",2,3,"a",4,"a","a","a",5] seqs_continuous_indexesnot_slices(ol,"a",{0,2})
### Input: from elist.elist import * ol = [1,"a","a",2,3,"a",4,"a","a","a",5] seqs_continuous_indexesnot_slices(ol,"a",{0,2}) ### Response: def seqs_continuous_indexesnot_slices(ol,value,seqs): rslt = [] length = ol.__len__() seq = -1 cursor = 0 begin = None slice = [] ...
def load_edited_source(self, source, good_cb=None, bad_cb=None, filename=None): with LiveExecution.lock: self.good_cb = good_cb self.bad_cb = bad_cb try: compile(source + , filename or self.filename, "exec") self.edite...
Load changed code into the execution environment. Until the code is executed correctly, it will be in the 'tenuous' state.
### Input: Load changed code into the execution environment. Until the code is executed correctly, it will be in the 'tenuous' state. ### Response: def load_edited_source(self, source, good_cb=None, bad_cb=None, filename=None): with LiveExecution.lock: self.good_cb = good...
def convert_graphic_elements(self): for graphic in self.main.getroot().findall(): graphic.tag = graphic.attrib[] = ns_xlink_href = ns_format(graphic, ) if ns_xlink_href in graphic.attrib: xlink_href = graphic.attrib[ns_xlink_href] ...
This is a method for the odd special cases where <graphic> elements are standalone, or rather, not a part of a standard graphical element such as a figure or a table. This method should always be employed after the standard cases have already been handled.
### Input: This is a method for the odd special cases where <graphic> elements are standalone, or rather, not a part of a standard graphical element such as a figure or a table. This method should always be employed after the standard cases have already been handled. ### Response: def convert_...
def identify(self, geometry, mapExtent, imageDisplay, tolerance, geometryType="esriGeometryPoint", sr=None, layerDefs=None, time=None, layerTimeOptions=None, ...
The identify operation is performed on a map service resource to discover features at a geographic location. The result of this operation is an identify results resource. Each identified result includes its name, layer ID, layer name, geometry and geometry type, and other...
### Input: The identify operation is performed on a map service resource to discover features at a geographic location. The result of this operation is an identify results resource. Each identified result includes its name, layer ID, layer name, geometry and geometry type, ...
def integral(self, bandname): intg = {} for det in self.rsr[bandname].keys(): wvl = self.rsr[bandname][det][] resp = self.rsr[bandname][det][] intg[det] = np.trapz(resp, wvl) return intg
Calculate the integral of the spectral response function for each detector.
### Input: Calculate the integral of the spectral response function for each detector. ### Response: def integral(self, bandname): intg = {} for det in self.rsr[bandname].keys(): wvl = self.rsr[bandname][det][] resp = self.rsr[bandname][det][] intg[...
def update_lb_node_condition(self, lb_id, node_id, condition): self._request( , % (lb_id, node_id), data={: condition})
Update node condition - specifically to disable/enable :param string lb_id: Balancer id :param string node_id: Node id :param string condition: ENABLED/DISABLED
### Input: Update node condition - specifically to disable/enable :param string lb_id: Balancer id :param string node_id: Node id :param string condition: ENABLED/DISABLED ### Response: def update_lb_node_condition(self, lb_id, node_id, condition): self._request( ...
def get_membership_cache(self, group_ids=None, is_active=True): membership_queryset = EntityGroupMembership.objects.filter( Q(entity__isnull=True) | (Q(entity__isnull=False) & Q(entity__is_active=is_active)) ) if is_active is None: membership_queryset = EntityGro...
Build a dict cache with the group membership info. Keyed off the group id and the values are a 2 element list of entity id and entity kind id (same values as the membership model). If no group ids are passed, then all groups will be fetched :param is_active: Flag indicating whether to filter on...
### Input: Build a dict cache with the group membership info. Keyed off the group id and the values are a 2 element list of entity id and entity kind id (same values as the membership model). If no group ids are passed, then all groups will be fetched :param is_active: Flag indicating whether ...
def new(conf): algorithm = conf.get("algorithm") salt = conf.get("salt").encode("utf-8") if algorithm == "none": return Hash(salt, None) elif algorithm.startswith("pbkdf2"): kwargs = {} tail = algorithm.partition(":")[2] for func, key in ((int, "iterations"), (int,...
Factory to create hash functions from configuration section. If an algorithm takes custom parameters, you can separate them by a colon like this: pbkdf2:arg1:arg2:arg3.
### Input: Factory to create hash functions from configuration section. If an algorithm takes custom parameters, you can separate them by a colon like this: pbkdf2:arg1:arg2:arg3. ### Response: def new(conf): algorithm = conf.get("algorithm") salt = conf.get("salt").encode("utf-8") if algor...
def namedb_get_num_names( cur, current_block, include_expired=False ): unexpired_query = "" unexpired_args = () if not include_expired: unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block ) unexpired_query = .format(unexpired_query) query ...
Get the number of names that exist at the current block
### Input: Get the number of names that exist at the current block ### Response: def namedb_get_num_names( cur, current_block, include_expired=False ): unexpired_query = "" unexpired_args = () if not include_expired: unexpired_query, unexpired_args = namedb_select_where_unexpired_na...
def _read_frame(self, length): response = self._read_data(length+8) logger.debug(.format(binascii.hexlify(response))) if response[0] != 0x01: raise RuntimeError() offset = 1 while response[offset] == 0x00: offse...
Read a response frame from the PN532 of at most length bytes in size. Returns the data inside the frame if found, otherwise raises an exception if there is an error parsing the frame. Note that less than length bytes might be returned!
### Input: Read a response frame from the PN532 of at most length bytes in size. Returns the data inside the frame if found, otherwise raises an exception if there is an error parsing the frame. Note that less than length bytes might be returned! ### Response: def _read_frame(self, length): ...
def list_patches(refresh=False, root=None, **kwargs): * if refresh: refresh_db(root) return _get_patches(root=root)
.. versionadded:: 2017.7.0 List all known advisory patches from available repos. refresh force a refresh if set to True. If set to False (default) it depends on zypper if a refresh is executed. root operate on a different root directory. CLI Examples: .. code-blo...
### Input: .. versionadded:: 2017.7.0 List all known advisory patches from available repos. refresh force a refresh if set to True. If set to False (default) it depends on zypper if a refresh is executed. root operate on a different root directory. CLI Examples: ...
def _wait_for_exit(please_stop): try: import msvcrt _wait_for_exit_on_windows(please_stop) except: pass cr_count = 0 while not please_stop: if cr_count > 30: (Till(seconds=3) | please_stop).wait() try: line = sys.stdin.rea...
/dev/null PIPED TO sys.stdin SPEWS INFINITE LINES, DO NOT POLL AS OFTEN
### Input: /dev/null PIPED TO sys.stdin SPEWS INFINITE LINES, DO NOT POLL AS OFTEN ### Response: def _wait_for_exit(please_stop): try: import msvcrt _wait_for_exit_on_windows(please_stop) except: pass cr_count = 0 while not please_stop: if cr_count > 3...
def values_to_array(input_values): if type(input_values)==tuple: values = np.array(input_values).reshape(-1,1) elif type(input_values) == np.ndarray: values = np.atleast_2d(input_values) elif type(input_values)==int or type(input_values)==float or type(np.int64): values = np.atl...
Transforms a values of int, float and tuples to a column vector numpy array
### Input: Transforms a values of int, float and tuples to a column vector numpy array ### Response: def values_to_array(input_values): if type(input_values)==tuple: values = np.array(input_values).reshape(-1,1) elif type(input_values) == np.ndarray: values = np.atleast_2d(input_values) ...
def get_headers(self, cmd, msg_length, extra_headers): cmd_header = "%s %s" % (cmd, PROTOCOL_VERSION) len_header = "Content-length: %s" % msg_length headers = [cmd_header, len_header] if self.user: user_header = "User: %s" % self.user headers.append(user_...
Returns the headers string based on command to execute
### Input: Returns the headers string based on command to execute ### Response: def get_headers(self, cmd, msg_length, extra_headers): cmd_header = "%s %s" % (cmd, PROTOCOL_VERSION) len_header = "Content-length: %s" % msg_length headers = [cmd_header, len_header] if self.user:...
def add_organism(self, common_name, directory, blatdb=None, genus=None, species=None, public=False): data = { : common_name, : directory, : public, } if blatdb is not None: data[] = blatdb if genus is not None...
Add an organism :type common_name: str :param common_name: Organism common name :type directory: str :param directory: Server-side directory :type blatdb: str :param blatdb: Server-side Blat directory for the organism :type genus: str :param genus: Gen...
### Input: Add an organism :type common_name: str :param common_name: Organism common name :type directory: str :param directory: Server-side directory :type blatdb: str :param blatdb: Server-side Blat directory for the organism :type genus: str :para...
def body(cls, description=None, default=None, resource=DefaultResource, **options): return cls(, In.Body, None, resource, description, required=True, default=default, **options)
Define body parameter.
### Input: Define body parameter. ### Response: def body(cls, description=None, default=None, resource=DefaultResource, **options): return cls(, In.Body, None, resource, description, required=True, default=default, **options)
def format_wsfc_domain_profile(result): from collections import OrderedDict order_dict = OrderedDict() if result.cluster_bootstrap_account is not None: order_dict[] = result.cluster_bootstrap_account if result.domain_fqdn is not None: order_dict[] = result.domain_fqdn if re...
Formats the WSFCDomainProfile object removing arguments that are empty
### Input: Formats the WSFCDomainProfile object removing arguments that are empty ### Response: def format_wsfc_domain_profile(result): from collections import OrderedDict order_dict = OrderedDict() if result.cluster_bootstrap_account is not None: order_dict[] = result.cluster_bootstrap_...
def start(opts, bot, event): name = opts[] now = datetime.datetime.now() bot.timers[name] = now return bot.start_fmt.format(now)
Usage: start [--name=<name>] Start a timer. Without _name_, start the default timer. To run more than one timer at once, pass _name_ to start and stop.
### Input: Usage: start [--name=<name>] Start a timer. Without _name_, start the default timer. To run more than one timer at once, pass _name_ to start and stop. ### Response: def start(opts, bot, event): name = opts[] now = datetime.datetime.now() bot.timers[name] = now return ...
def find_broadly_matched_key(self, broad, string): keys = list(broad.keys()) for i in range(0, len(keys)): key = keys[i] if string.find(key) >= 0: return key return None
A helper method for matching error strings exactly vs broadly
### Input: A helper method for matching error strings exactly vs broadly ### Response: def find_broadly_matched_key(self, broad, string): keys = list(broad.keys()) for i in range(0, len(keys)): key = keys[i] if string.find(key) >= 0: return key ...
def _remove_localizers_by_orientation(dicoms): orientations = [] sorted_dicoms = {} for dicom_header in dicoms: image_orient1 = numpy.array(dicom_header.ImageOrientationPatient)[0:3] image_orient2 = numpy.array(dicom_header.ImageOrientationPatient)[3:6] image_orien...
Removing localizers based on the orientation. This is needed as in some cases with ct data there are some localizer/projection type images that cannot be distiguished by the dicom headers. This is why we kick out all orientations that do not have more than 4 files 4 is the limit anyway for converting to nif...
### Input: Removing localizers based on the orientation. This is needed as in some cases with ct data there are some localizer/projection type images that cannot be distiguished by the dicom headers. This is why we kick out all orientations that do not have more than 4 files 4 is the limit anyway for conve...
def ljust(self, width, fillchar=None): if fillchar is not None: return fmtstr(self.s.ljust(width, fillchar), **self.shared_atts) to_add = * (width - len(self.s)) shared = self.shared_atts if in shared: return self + fmtstr(to_add, bg=shared[str()]) if t...
S.ljust(width[, fillchar]) -> string If a fillchar is provided, less formatting information will be preserved
### Input: S.ljust(width[, fillchar]) -> string If a fillchar is provided, less formatting information will be preserved ### Response: def ljust(self, width, fillchar=None): if fillchar is not None: return fmtstr(self.s.ljust(width, fillchar), **self.shared_atts) to_add =...
def summary(self, id, seq, intf, filter=None, inline=False): schema = SummarySchema() resp = self.service.get(self._base(id, seq)+str(intf)+, params={: filter, : inline}) return self.service.decode(schema, resp)
Get a capture's summary. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param filter: (optional) PCAP filter to apply as string. :param inline: (optional) Use inline version of capture file. :return: ...
### Input: Get a capture's summary. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param filter: (optional) PCAP filter to apply as string. :param inline: (optional) Use inline version of capture file. ...
def infer_alpha_chain(beta): if beta.gene.startswith("DRB"): return AlleleName(species="HLA", gene="DRA1", allele_family="01", allele_code="01") elif beta.gene.startswith("DPB"): return AlleleName( species="HLA", gene="DPA1", allele_family="01", allele...
Given a parsed beta chain of a class II MHC, infer the most frequent corresponding alpha chain.
### Input: Given a parsed beta chain of a class II MHC, infer the most frequent corresponding alpha chain. ### Response: def infer_alpha_chain(beta): if beta.gene.startswith("DRB"): return AlleleName(species="HLA", gene="DRA1", allele_family="01", allele_code="01") elif beta.gene.startswith("...
def heightmap_lerp_hm( hm1: np.ndarray, hm2: np.ndarray, hm3: np.ndarray, coef: float ) -> None: lib.TCOD_heightmap_lerp_hm( _heightmap_cdata(hm1), _heightmap_cdata(hm2), _heightmap_cdata(hm3), coef, )
Perform linear interpolation between two heightmaps storing the result in ``hm3``. This is the same as doing ``hm3[:] = hm1[:] + (hm2[:] - hm1[:]) * coef`` Args: hm1 (numpy.ndarray): The first heightmap. hm2 (numpy.ndarray): The second heightmap to add to the first. hm3 (numpy.ndar...
### Input: Perform linear interpolation between two heightmaps storing the result in ``hm3``. This is the same as doing ``hm3[:] = hm1[:] + (hm2[:] - hm1[:]) * coef`` Args: hm1 (numpy.ndarray): The first heightmap. hm2 (numpy.ndarray): The second heightmap to add to the first. hm3...
def config_finish(self): _LOGGER.info("Config finish") if not self.config_started: return True success, _ = self._make_request( SERVICE_DEVICE_CONFIG, "ConfigurationFinished", {"NewStatus": "ChangesApplied"}) self.config_started = not success re...
End of a configuration session. Tells the router we're done managing admin functionality.
### Input: End of a configuration session. Tells the router we're done managing admin functionality. ### Response: def config_finish(self): _LOGGER.info("Config finish") if not self.config_started: return True success, _ = self._make_request( SERVICE_D...
def _SID_call_prep(align_bams, items, ref_file, assoc_files, region=None, out_file=None): base_config = items[0]["config"] for x in align_bams: bam.index(x, base_config) params = ["-R", ref_file, "-T", "SomaticIndelDetector", "-U", "ALLOW_N_CIGAR_READS"] paired = vcfuti...
Preparation work for SomaticIndelDetector.
### Input: Preparation work for SomaticIndelDetector. ### Response: def _SID_call_prep(align_bams, items, ref_file, assoc_files, region=None, out_file=None): base_config = items[0]["config"] for x in align_bams: bam.index(x, base_config) params = ["-R", ref_file, "-T", "SomaticIndelDetector"...
def qa(ctx): header(qa.__doc__) with ctx.cd(ROOT): info() flake8_results = ctx.run(, pty=True, warn=True) if flake8_results.failed: error() else: success() info() readme_results = ctx.run(, pty=True, warn=True, hide=True) if re...
Run a quality report
### Input: Run a quality report ### Response: def qa(ctx): header(qa.__doc__) with ctx.cd(ROOT): info() flake8_results = ctx.run(, pty=True, warn=True) if flake8_results.failed: error() else: success() info() readme_results = ctx.run...
def _unlinkUser(self): KEY = "linked_contact_uid" if not self.hasUser(): return False user = self.getUser() username = user.getId() user.setMemberProperties({KEY: ""}) logger.info("Unlinked Contact UID from User {}" ...
Remove the UID of the current Contact in the User properties and update all relevant own properties.
### Input: Remove the UID of the current Contact in the User properties and update all relevant own properties. ### Response: def _unlinkUser(self): KEY = "linked_contact_uid" if not self.hasUser(): return False user = self.getUser() username = u...
def mmols(self): mmols_dict = {} mmol_dir = os.path.join(self.parent_dir, ) if not os.path.exists(mmol_dir): os.makedirs(mmol_dir) mmol_file_names = [.format(self.code, i) for i in range(1, self.number_of_mmols + 1)] mmol_files = [os.path.join(mmol_dir, x) fo...
Dict of filepaths for all mmol files associated with code. Notes ----- Downloads mmol files if not already present. Returns ------- mmols_dict : dict, or None. Keys : int mmol number Values : str Filepath for the c...
### Input: Dict of filepaths for all mmol files associated with code. Notes ----- Downloads mmol files if not already present. Returns ------- mmols_dict : dict, or None. Keys : int mmol number Values : str Filepa...
def installed_packages(self): packages = [] CMDLINE = [sys.executable, "-mpip", "freeze"] try: for package in subprocess.check_output(CMDLINE) \ .decode(). \ splitlines(): for comparator in ["==", ">=", "<=", "<", ">"]:...
:return: list of installed packages
### Input: :return: list of installed packages ### Response: def installed_packages(self): packages = [] CMDLINE = [sys.executable, "-mpip", "freeze"] try: for package in subprocess.check_output(CMDLINE) \ .decode(). \ splitlines(): ...
def _lmder1_linear_full_rank(n, m, factor, target_fnorm1, target_fnorm2): def func(params, vec): s = params.sum() temp = 2. * s / m + 1 vec[:] = -temp vec[:params.size] += params def jac(params, jac): jac.fill(-2. / m) for i in range(n): ...
A full-rank linear function (lmder test #1)
### Input: A full-rank linear function (lmder test #1) ### Response: def _lmder1_linear_full_rank(n, m, factor, target_fnorm1, target_fnorm2): def func(params, vec): s = params.sum() temp = 2. * s / m + 1 vec[:] = -temp vec[:params.size] += params def jac(params, jac): ...
def authentication(self, event): try: self.log("Authorization has been granted by DB check:", event.username, lvl=debug) account, profile, clientconfig = event.userdata useruuid = event.useruuid originatingclientuuid = event.client...
Links the client to the granted account and profile, then notifies the client
### Input: Links the client to the granted account and profile, then notifies the client ### Response: def authentication(self, event): try: self.log("Authorization has been granted by DB check:", event.username, lvl=debug) account, profile, clie...
def add(self, widget, condition=lambda: 42): assert callable(condition) assert isinstance(widget, BaseWidget) self._widgets.append((widget, condition)) return widget
Add a widget to the widows. The widget will auto render. You can use the function like that if you want to keep the widget accecible : self.my_widget = self.add(my_widget)
### Input: Add a widget to the widows. The widget will auto render. You can use the function like that if you want to keep the widget accecible : self.my_widget = self.add(my_widget) ### Response: def add(self, widget, condition=lambda: 42): assert callable(condition) as...
def encode_conjure_union_type(cls, obj): encoded = {} encoded["type"] = obj.type for attr, field_definition in obj._options().items(): if field_definition.identifier == obj.type: attribute = attr break else: rais...
Encodes a conjure union into json
### Input: Encodes a conjure union into json ### Response: def encode_conjure_union_type(cls, obj): encoded = {} encoded["type"] = obj.type for attr, field_definition in obj._options().items(): if field_definition.identifier == obj.type: attribut...
def _process_response(response): error = response.exception() if error: if isinstance(error, aws_exceptions.AWSError): if error.args[1][] in exceptions.MAP: raise exceptions.MAP[error.args[1][]]( error.args[1][]) ...
Process the raw AWS response, returning either the mapped exception or deserialized response. :param tornado.concurrent.Future response: The request future :rtype: dict or list :raises: sprockets_dynamodb.exceptions.DynamoDBException
### Input: Process the raw AWS response, returning either the mapped exception or deserialized response. :param tornado.concurrent.Future response: The request future :rtype: dict or list :raises: sprockets_dynamodb.exceptions.DynamoDBException ### Response: def _process_response(res...
def ecc_correct_intra_stream(ecc_manager_intra, ecc_params_intra, hasher_intra, resilience_rate_intra, field, ecc, enable_erasures=False, erasures_char="\x00", only_erasures=False, max_block_size=65535): fpfile = StringIO(field) fpfile_ecc = StringIO(ecc) fpentry_p = {"ecc_field_pos": [0, len(fiel...
Correct an intra-field with its corresponding intra-ecc if necessary
### Input: Correct an intra-field with its corresponding intra-ecc if necessary ### Response: def ecc_correct_intra_stream(ecc_manager_intra, ecc_params_intra, hasher_intra, resilience_rate_intra, field, ecc, enable_erasures=False, erasures_char="\x00", only_erasures=False, max_block_size=65535): fpfile...
def create_container(self, image, command=None, hostname=None, user=None, detach=False, stdin_open=False, tty=False, ports=None, environment=None, volumes=None, network_disabled=False, name=None, entrypoint=None, working...
Creates a container. Parameters are similar to those for the ``docker run`` command except it doesn't support the attach options (``-a``). The arguments that are passed directly to this function are host-independent configuration options. Host-specific configuration is passed with the `...
### Input: Creates a container. Parameters are similar to those for the ``docker run`` command except it doesn't support the attach options (``-a``). The arguments that are passed directly to this function are host-independent configuration options. Host-specific configuration is passe...
def init_optimizer(self, kvstore=, optimizer=, optimizer_params=((, 0.01),), force_init=False): assert self.binded and self.params_initialized if self.optimizer_initialized and not force_init: self.logger.warning() return if self._params_...
Installs and initializes optimizers. Parameters ---------- kvstore : str or KVStore Default `'local'`. optimizer : str or Optimizer Default `'sgd'` optimizer_params : dict Default `(('learning_rate', 0.01),)`. The default value is not a dictio...
### Input: Installs and initializes optimizers. Parameters ---------- kvstore : str or KVStore Default `'local'`. optimizer : str or Optimizer Default `'sgd'` optimizer_params : dict Default `(('learning_rate', 0.01),)`. The default value is ...
def predict(self, lon, lat, **kwargs): assert self.classifier is not None, pred = np.zeros(len(lon)) cut_geometry, flags_geometry = self.applyGeometry(lon, lat) x_test = [] for key, operation in self.config[][]: assert operation.lower() in ...
distance, abs_mag, r_physical
### Input: distance, abs_mag, r_physical ### Response: def predict(self, lon, lat, **kwargs): assert self.classifier is not None, pred = np.zeros(len(lon)) cut_geometry, flags_geometry = self.applyGeometry(lon, lat) x_test = [] for key, operation in ...
def add(self, cbobject, metadata): with self._lock: if cbobject not in self._metadata: self._metadata[cbobject] = metadata return self._metadata[cbobject]
Add the specified CoreBluetooth item with the associated metadata if it doesn't already exist. Returns the newly created or preexisting metadata item.
### Input: Add the specified CoreBluetooth item with the associated metadata if it doesn't already exist. Returns the newly created or preexisting metadata item. ### Response: def add(self, cbobject, metadata): with self._lock: if cbobject not in self._metadata: ...
def generate(self): tar_bytes = BytesIO() tar = tarfile.open(fileobj=tar_bytes, mode=) self._generate_contents(tar) self._process_files(tar) tar.close() tar_bytes.seek(0) gzip_bytes = BytesIO() gz = gzip.GzipF...
Returns a ``BytesIO`` instance representing an in-memory tar.gz archive containing the native router configuration. :returns: in-memory tar.gz archive, instance of ``BytesIO``
### Input: Returns a ``BytesIO`` instance representing an in-memory tar.gz archive containing the native router configuration. :returns: in-memory tar.gz archive, instance of ``BytesIO`` ### Response: def generate(self): tar_bytes = BytesIO() tar = tarfile.open(fileobj=tar_by...
def configure_scraper(self, scraper_config): endpoint = scraper_config[] scraper_config.update( { : self._ssl_verify, : self._ssl_cert, : self._ssl_private_key, : self.headers(endpoint) or {}, } )
Configures a PrometheusScaper object with query credentials :param scraper: valid PrometheusScaper object :param endpoint: url that will be scraped
### Input: Configures a PrometheusScaper object with query credentials :param scraper: valid PrometheusScaper object :param endpoint: url that will be scraped ### Response: def configure_scraper(self, scraper_config): endpoint = scraper_config[] scraper_config.update( ...
def manifest(self, entry): entries = [] for fname in self._sorted_nicely(os.listdir(entry.directory)): if fname == : continue fpath = os.path.abspath(os.path.join(entry.directory, fname)) metadata = self.metadata_from_fname(fname) ...
Returns manifest as a list. :param entry: :class:`jicimagelib.image.FileBackend.Entry` :returns: list
### Input: Returns manifest as a list. :param entry: :class:`jicimagelib.image.FileBackend.Entry` :returns: list ### Response: def manifest(self, entry): entries = [] for fname in self._sorted_nicely(os.listdir(entry.directory)): if fname == : ...
def clean_download_cache(self, args): ctx = self.ctx if hasattr(args, ) and args.recipes: for package in args.recipes: remove_path = join(ctx.packages_path, package) if exists(remove_path): shutil.rmtree(remove_path) ...
Deletes a download cache for recipes passed as arguments. If no argument is passed, it'll delete *all* downloaded caches. :: p4a clean_download_cache kivy,pyjnius This does *not* delete the build caches or final distributions.
### Input: Deletes a download cache for recipes passed as arguments. If no argument is passed, it'll delete *all* downloaded caches. :: p4a clean_download_cache kivy,pyjnius This does *not* delete the build caches or final distributions. ### Response: def clean_download_cache(self, args)...
def get_config(self, retrieve="all"): get_startup = retrieve == "all" or retrieve == "startup" get_running = retrieve == "all" or retrieve == "running" get_candidate = (retrieve == "all" or retrieve == "candidate") and self.config_session if retrieve == "all": comma...
get_config implementation for EOS.
### Input: get_config implementation for EOS. ### Response: def get_config(self, retrieve="all"): get_startup = retrieve == "all" or retrieve == "startup" get_running = retrieve == "all" or retrieve == "running" get_candidate = (retrieve == "all" or retrieve == "candidate") and self.c...
def findall(dir = os.curdir): all_files = [] for base, dirs, files in os.walk(dir, followlinks=True): if base==os.curdir or base.startswith(os.curdir+os.sep): base = base[2:] if base: files = [os.path.join(base, f) for f in files] all_files.extend(filter(os.p...
Find all files under 'dir' and return the list of full filenames (relative to 'dir').
### Input: Find all files under 'dir' and return the list of full filenames (relative to 'dir'). ### Response: def findall(dir = os.curdir): all_files = [] for base, dirs, files in os.walk(dir, followlinks=True): if base==os.curdir or base.startswith(os.curdir+os.sep): base = base...
def calculate_health(package_name, package_version=None, verbose=False, no_output=False): total_score = 0 reasons = [] package_releases = CLIENT.package_releases(package_name) if not package_releases: if not no_output: print(TERMINAL.red(.format(package_name))) return 0...
Calculates the health of a package, based on several factors :param package_name: name of package on pypi.python.org :param package_version: version number of package to check, optional - defaults to latest version :param verbose: flag to print out reasons :param no_output: print no output :param l...
### Input: Calculates the health of a package, based on several factors :param package_name: name of package on pypi.python.org :param package_version: version number of package to check, optional - defaults to latest version :param verbose: flag to print out reasons :param no_output: print no output ...
def _ctl_cmd(cmd, name, conf_file, bin_env): ret = [_get_supervisorctl_bin(bin_env)] if conf_file is not None: ret += [, conf_file] ret.append(cmd) if name: ret.append(name) return ret
Return the command list to use
### Input: Return the command list to use ### Response: def _ctl_cmd(cmd, name, conf_file, bin_env): ret = [_get_supervisorctl_bin(bin_env)] if conf_file is not None: ret += [, conf_file] ret.append(cmd) if name: ret.append(name) return ret
def datapoint_indices_for_tensor(self, tensor_index): if tensor_index >= self._num_tensors: raise ValueError( %(tensor_index, self._num_tensors)) return self._file_num_to_indices[tensor_index]
Returns the indices for all datapoints in the given tensor.
### Input: Returns the indices for all datapoints in the given tensor. ### Response: def datapoint_indices_for_tensor(self, tensor_index): if tensor_index >= self._num_tensors: raise ValueError( %(tensor_index, self._num_tensors)) return self._file_num_to_indices[tensor_index]
def input_checks(catalogue, config, completeness): if isinstance(completeness, np.ndarray): if np.shape(completeness)[1] != 2: raise ValueError() else: cmag = completeness[:, 1] ctime = completeness[:, 0] elif isinstance(completeness, float): ...
Performs a basic set of input checks on the data
### Input: Performs a basic set of input checks on the data ### Response: def input_checks(catalogue, config, completeness): if isinstance(completeness, np.ndarray): if np.shape(completeness)[1] != 2: raise ValueError() else: cmag = completeness[:, 1] ...
def indel_at( self, position, check_insertions=True, check_deletions=True, one_based=True ): (insertions, deletions) = self.get_indels( one_based=one_based ) if check_insertions: for insertion in insertions: if insertion[0] == position: return Tru...
Does the read contain an indel at the given position? Return True if the read contains an insertion at the given position (position must be the base before the insertion event) or if the read contains a deletion where the base at position is deleted. Return False otherwise.
### Input: Does the read contain an indel at the given position? Return True if the read contains an insertion at the given position (position must be the base before the insertion event) or if the read contains a deletion where the base at position is deleted. Return False otherwise. #...
def temperature_effectiveness_basic(R1, NTU1, subtype=): rcounterflowparallelcrossflowcrossflow approximatecrossflow, mixed 1crossflow, mixed 2crossflow, mixed 1&2counterflow if subtype == : P1 = (1 - exp(-NTU1*(1 - R1)))/(1 - R1*exp(-NTU1*(1-R1))) elif subtype == : P1 = (1 - exp(-N...
r'''Returns temperature effectiveness `P1` of a heat exchanger with a specified heat capacity ratio, number of transfer units `NTU1`, and of type `subtype`. This function performs the calculations for the basic cases, not actual shell-and-tube exchangers. The supported cases are as follows: ...
### Input: r'''Returns temperature effectiveness `P1` of a heat exchanger with a specified heat capacity ratio, number of transfer units `NTU1`, and of type `subtype`. This function performs the calculations for the basic cases, not actual shell-and-tube exchangers. The supported cases are as follows:...
def register(self, app, options, first_registration=False): self.jsonrpc_site = options.get() self._got_registered_once = True state = self.make_setup_state(app, options, first_registration) if self.has_static_folder and \ not self.name + in state.app.view_funct...
Called by :meth:`Flask.register_blueprint` to register a blueprint on the application. This can be overridden to customize the register behavior. Keyword arguments from :func:`~flask.Flask.register_blueprint` are directly forwarded to this method in the `options` dictionary.
### Input: Called by :meth:`Flask.register_blueprint` to register a blueprint on the application. This can be overridden to customize the register behavior. Keyword arguments from :func:`~flask.Flask.register_blueprint` are directly forwarded to this method in the `options` dictionary. ...
def _store_model_progress(self, res, now): raw_progress, delay = res raw_progress = clamp(raw_progress, 0, self._maxval) self._progress_data.append((now, raw_progress)) if delay < 0: delay = self._guess_next_poll_interval() self._ne...
Save the current model progress into ``self._progress_data``, and update ``self._next_poll_time``. :param res: tuple (progress level, poll delay). :param now: current timestamp.
### Input: Save the current model progress into ``self._progress_data``, and update ``self._next_poll_time``. :param res: tuple (progress level, poll delay). :param now: current timestamp. ### Response: def _store_model_progress(self, res, now): raw_progress, delay = res raw_...
def parse_error( self, exception=ParseError, *args ): line, col = self._to_linecol() return exception(line, col, *args)
Creates a generic "parse error" at the current position.
### Input: Creates a generic "parse error" at the current position. ### Response: def parse_error( self, exception=ParseError, *args ): line, col = self._to_linecol() return exception(line, col, *args)
def ListFiles(self, ext_attrs=False): if not self.IsDirectory(): raise IOError("%s is not a directory." % self.path) for path in self.files: try: filepath = utils.JoinPath(self.path, path) response = self._Stat(filepath, ext_attrs=ext_attrs) pathspec = self.pathspec.Cop...
List all files in the dir.
### Input: List all files in the dir. ### Response: def ListFiles(self, ext_attrs=False): if not self.IsDirectory(): raise IOError("%s is not a directory." % self.path) for path in self.files: try: filepath = utils.JoinPath(self.path, path) response = self._Stat(filepath, ext...
def dict_sequence(self, node, keep_var_ambigs=False): seq = {} node_seq = node.cseq if keep_var_ambigs and hasattr(node, "original_cseq") and node.is_terminal(): node_seq = node.original_cseq for pos in self.nonref_positions: cseqLoc = self.full_to_redu...
For VCF-based TreeAnc objects, we do not want to store the entire sequence on every node, as they could be large. Instead, this returns the dict of variants & their positions for this sequence. This is used in place of :py:meth:`treetime.TreeAnc.expanded_sequence` for VCF-based objects throughou...
### Input: For VCF-based TreeAnc objects, we do not want to store the entire sequence on every node, as they could be large. Instead, this returns the dict of variants & their positions for this sequence. This is used in place of :py:meth:`treetime.TreeAnc.expanded_sequence` for VCF-based objec...
def scatter_density(self, x, y, dpi=72, downres_factor=4, color=None, cmap=None, alpha=1.0, norm=None, **kwargs): self.set_xlim(np.min(x), np.max(x)) self.set_ylim(np.min(y), np.max(y)) scatter = ScatterDensityArtist(self, x, y, dpi=dpi, downres_factor=downres_...
Make a density plot of the (x, y) scatter data. Parameters ---------- x, y : iterable The data to plot dpi : int or `None` The number of dots per inch to include in the density map. To use the native resolution of the drawing device, set this to None....
### Input: Make a density plot of the (x, y) scatter data. Parameters ---------- x, y : iterable The data to plot dpi : int or `None` The number of dots per inch to include in the density map. To use the native resolution of the drawing device, set t...
def zernike(zernike_indexes,labels,indexes): indexes = np.array(indexes,dtype=np.int32) nindexes = len(indexes) reverse_indexes = np.empty((np.max(indexes)+1,),int) reverse_indexes.fill(-1) reverse_indexes[indexes] = np.arange(indexes.shape[0],dtype=int) mask = reve...
Compute the Zernike features for the labels with the label #s in indexes returns the score per labels and an array of one image per zernike feature
### Input: Compute the Zernike features for the labels with the label #s in indexes returns the score per labels and an array of one image per zernike feature ### Response: def zernike(zernike_indexes,labels,indexes): indexes = np.array(indexes,dtype=np.int32) nindexes =...
def try_greyscale(pixels, alpha=False, dirty_alpha=True): planes = 3 + bool(alpha) res = list() apix = list() for row in pixels: green = row[1::planes] if alpha: apix.append(row[4:planes]) if (green != row[0::planes] or green != row[2::planes]): retur...
Check if flatboxed RGB `pixels` could be converted to greyscale If could - return iterator with greyscale pixels, otherwise return `False` constant
### Input: Check if flatboxed RGB `pixels` could be converted to greyscale If could - return iterator with greyscale pixels, otherwise return `False` constant ### Response: def try_greyscale(pixels, alpha=False, dirty_alpha=True): planes = 3 + bool(alpha) res = list() apix = list() for r...
def target_sequence_length(self): if not self.is_aligned(): raise ValueError("no length for reference when read is not not aligned") if self.entries.tlen: return self.entries.tlen if self.header: if self.entries.rname in self.header.sequence_lengths: return self.header.sequence_len...
Get the length of the target sequence. length of the entire chromosome throws an error if there is no information available :return: length :rtype: int
### Input: Get the length of the target sequence. length of the entire chromosome throws an error if there is no information available :return: length :rtype: int ### Response: def target_sequence_length(self): if not self.is_aligned(): raise ValueError("no length for reference when read...
def transform_i_to_j_optional(self, line: str) -> str: words = line.split(" ") space_list = string_utils.space_list(line) corrected_words = [] for word in words: found = False for prefix in self.constants.PREFIXES: if word.startswith(prefi...
Sometimes for the demands of meter a more permissive i to j transformation is warranted. :param line: :return: >>> print(VerseScanner().transform_i_to_j_optional("Italiam")) Italjam >>> print(VerseScanner().transform_i_to_j_optional("Lāvīniaque")) Lāvīnjaque >>>...
### Input: Sometimes for the demands of meter a more permissive i to j transformation is warranted. :param line: :return: >>> print(VerseScanner().transform_i_to_j_optional("Italiam")) Italjam >>> print(VerseScanner().transform_i_to_j_optional("Lāvīniaque")) Lāvīnjaque...
def pause_all(self): for alias, service in self._service_objects.items(): with expects.expect_no_raises( % alias): service.pause()
Pauses all service instances.
### Input: Pauses all service instances. ### Response: def pause_all(self): for alias, service in self._service_objects.items(): with expects.expect_no_raises( % alias): service.pause()
def fixed_interval_scheduler(interval): start = time.time() next_tick = start while True: next_tick += interval yield next_tick
A scheduler that ticks at fixed intervals of "interval" seconds
### Input: A scheduler that ticks at fixed intervals of "interval" seconds ### Response: def fixed_interval_scheduler(interval): start = time.time() next_tick = start while True: next_tick += interval yield next_tick
def clear_current() -> None: old = IOLoop.current(instance=False) if old is not None: old._clear_current_hook() if asyncio is None: IOLoop._current.instance = None
Clears the `IOLoop` for the current thread. Intended primarily for use by test frameworks in between tests. .. versionchanged:: 5.0 This method also clears the current `asyncio` event loop.
### Input: Clears the `IOLoop` for the current thread. Intended primarily for use by test frameworks in between tests. .. versionchanged:: 5.0 This method also clears the current `asyncio` event loop. ### Response: def clear_current() -> None: old = IOLoop.current(instanc...
def parse_children(self, node): if in node.lattrib: name = node.lattrib[] else: self.raise_error() if in node.lattrib: type_ = node.lattrib[] else: self.raise_error("Children must specify a type.", name) self.current_...
Parses <Children> @param node: Node containing the <Children> element @type node: xml.etree.Element
### Input: Parses <Children> @param node: Node containing the <Children> element @type node: xml.etree.Element ### Response: def parse_children(self, node): if in node.lattrib: name = node.lattrib[] else: self.raise_error() if in node.lattr...
def update(self, **kwargs): if not self.object_id: return False url = self.build_url( self._endpoints.get().format(id=self.object_id)) data = {self._cc(key): value for key, value in kwargs.items() if key in {, }} ...
Updates this item :param kwargs: all the properties to be updated. only name and description are allowed at the moment. :return: Success / Failure :rtype: bool
### Input: Updates this item :param kwargs: all the properties to be updated. only name and description are allowed at the moment. :return: Success / Failure :rtype: bool ### Response: def update(self, **kwargs): if not self.object_id: return False ...
def gen_binder_url(fpath, binder_conf, gallery_conf): fpath_prefix = binder_conf.get() link_base = binder_conf.get() relative_link = os.path.relpath(fpath, gallery_conf[]) path_link = os.path.join( link_base, replace_py_ipynb(relative_link)) if fpath_prefix is not None:...
Generate a Binder URL according to the configuration in conf.py. Parameters ---------- fpath: str The path to the `.py` file for which a Binder badge will be generated. binder_conf: dict or None The Binder configuration dictionary. See `gen_binder_rst` for details. Returns ----...
### Input: Generate a Binder URL according to the configuration in conf.py. Parameters ---------- fpath: str The path to the `.py` file for which a Binder badge will be generated. binder_conf: dict or None The Binder configuration dictionary. See `gen_binder_rst` for details. Retu...
def sympy_empirical_equal(expr1, expr2): atoms_1 = expr1.atoms() atoms_1 = [a for a in atoms_1 if isinstance(a,sympy.Symbol)] atoms_2 = expr2.atoms() atoms_2 = [a for a in atoms_2 if isinstance(a,sympy.Symbol)] atoms = set(atoms_1 + atoms_2) arbitrary_values = [] arbitrary_va...
Compare long , complex, expressions by replacing all symbols by a set of arbitrary expressions :param expr1: first expression :param expr2: second expression :return: True if expressions are empirically equal, false otherwise
### Input: Compare long , complex, expressions by replacing all symbols by a set of arbitrary expressions :param expr1: first expression :param expr2: second expression :return: True if expressions are empirically equal, false otherwise ### Response: def sympy_empirical_equal(expr1, expr2): at...
def resample(self, data, input_rate): data16 = np.fromstring(string=data, dtype=np.int16) resample_size = int(len(data16) / self.input_rate * self.RATE_PROCESS) resample = signal.resample(data16, resample_size) resample16 = np.array(resample, dtype=np.int16) return resam...
Microphone may not support our native processing sampling rate, so resample from input_rate to RATE_PROCESS here for webrtcvad and deepspeech Args: data (binary): Input audio stream input_rate (int): Input audio rate to resample from
### Input: Microphone may not support our native processing sampling rate, so resample from input_rate to RATE_PROCESS here for webrtcvad and deepspeech Args: data (binary): Input audio stream input_rate (int): Input audio rate to resample from ### Response: def resamp...
def start(self): if self._timer.isActive(): return self._starttime = datetime.datetime.now() self._timer.start()
Starts running the timer. If the timer is currently running, then this method will do nothing. :sa stop, reset
### Input: Starts running the timer. If the timer is currently running, then this method will do nothing. :sa stop, reset ### Response: def start(self): if self._timer.isActive(): return self._starttime = datetime.datetime.now() self._timer....
def get_largest_component(G, strongly=False): start_time = time.time() original_len = len(list(G.nodes())) if strongly: if not nx.is_strongly_connected(G): sccs = nx.strongly_connected_components(G) largest_scc = max(sccs, key=len) ...
Return a subgraph of the largest weakly or strongly connected component from a directed graph. Parameters ---------- G : networkx multidigraph strongly : bool if True, return the largest strongly instead of weakly connected component Returns ------- G : networkx multidi...
### Input: Return a subgraph of the largest weakly or strongly connected component from a directed graph. Parameters ---------- G : networkx multidigraph strongly : bool if True, return the largest strongly instead of weakly connected component Returns ------- G : netw...
def get_container(self, name): name = adapt_name_for_rest(name) url = .format(self._instance, name) response = self._client.get_proto(url) message = mdb_pb2.ContainerInfo() message.ParseFromString(response.content) return Container(message)
Gets a single container by its unique name. :param str name: Either a fully-qualified XTCE name or an alias in the format ``NAMESPACE/NAME``. :rtype: .Container
### Input: Gets a single container by its unique name. :param str name: Either a fully-qualified XTCE name or an alias in the format ``NAMESPACE/NAME``. :rtype: .Container ### Response: def get_container(self, name): name = adapt_name_for_rest(name) u...
def compare(self, other, filter_fcn=None): if not isinstance(other, type(self)): return False if filter_fcn is None: def filter_unique(_, field): return not field.unique filter_fcn = filter_unique return self.to_json_...
Returns True if properties can be compared in terms of eq. Entity's Fields can be filtered accordingly to 'filter_fcn'. This callable receives field's name as first parameter and field itself as second parameter. It must return True if field's value should be included on comparis...
### Input: Returns True if properties can be compared in terms of eq. Entity's Fields can be filtered accordingly to 'filter_fcn'. This callable receives field's name as first parameter and field itself as second parameter. It must return True if field's value should be included on ...
def expected_cost_for_region(short_numobj, region_dialing_from): if not _region_dialing_from_matches_number(short_numobj, region_dialing_from): return ShortNumberCost.UNKNOWN_COST metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from) if metadata is None: return ...
Gets the expected cost category of a short number when dialled from a region (however, nothing is implied about its validity). If it is important that the number is valid, then its validity must first be checked using is_valid_short_number_for_region. Note that emergency numbers are always considered to...
### Input: Gets the expected cost category of a short number when dialled from a region (however, nothing is implied about its validity). If it is important that the number is valid, then its validity must first be checked using is_valid_short_number_for_region. Note that emergency numbers are always c...
def get_amplification_factors(self, imt, sctx, rctx, dists, stddev_types): dist_level_table = self.get_mean_table(imt, rctx) sigma_tables = self.get_sigma_tables(imt, rctx, stddev_types) mean_interpolator = interp1d(self.values, numpy.log10(dist_leve...
Returns the amplification factors for the given rupture and site conditions. :param imt: Intensity measure type as an instance of the :class: `openquake.hazardlib.imt` :param sctx: SiteCollection instance :param rctx: Rupture instance ...
### Input: Returns the amplification factors for the given rupture and site conditions. :param imt: Intensity measure type as an instance of the :class: `openquake.hazardlib.imt` :param sctx: SiteCollection instance :param rctx: Rupture i...
def diffs(self): differences = [] for item in self._get_recursive_difference(type=): if item.diffs: if item.past_dict: differences.append({item.past_dict[self._key]: item.diffs}) elif item.current_dict: differen...
Returns a list of dictionaries with key value pairs. The values are the differences between the items identified by the key.
### Input: Returns a list of dictionaries with key value pairs. The values are the differences between the items identified by the key. ### Response: def diffs(self): differences = [] for item in self._get_recursive_difference(type=): if item.diffs: if item...
def dump(self): logger.warn() ret = False if self.system.files.no_output: return True if self.write_lst() and self.write_dat(): ret = True return ret
Dump the TDS results to the output `dat` file :return: succeed flag
### Input: Dump the TDS results to the output `dat` file :return: succeed flag ### Response: def dump(self): logger.warn() ret = False if self.system.files.no_output: return True if self.write_lst() and self.write_dat(): ret = T...
def connect(self, object, callback): def signal_fired(sender, object, iface, signal, params): callback(*params) return object._bus.subscribe(sender=object._bus_name, object=object._path, iface=self._iface_name, signal=self.__name__, signal_fired=signal_fired)
Subscribe to the signal.
### Input: Subscribe to the signal. ### Response: def connect(self, object, callback): def signal_fired(sender, object, iface, signal, params): callback(*params) return object._bus.subscribe(sender=object._bus_name, object=object._path, iface=self._iface_name, signal=self.__name__, signal_fired=signal_fired...
def was_applied(self): if self.response_future.row_factory not in (named_tuple_factory, dict_factory, tuple_factory): raise RuntimeError("Cannot determine LWT result with row factory %s" % (self.response_future.row_factory,)) is_batch_statement = isinstance(self.response_future.que...
For LWT results, returns whether the transaction was applied. Result is indeterminate if called on a result that was not an LWT request or on a :class:`.query.BatchStatement` containing LWT. In the latter case either all the batch succeeds or fails. Only valid when one of the of the in...
### Input: For LWT results, returns whether the transaction was applied. Result is indeterminate if called on a result that was not an LWT request or on a :class:`.query.BatchStatement` containing LWT. In the latter case either all the batch succeeds or fails. Only valid when one of t...
def get_user_id_from_email(self, email): accts = self.get_all_user_accounts() for acct in accts: if acct[] == email: return acct[] return None
Uses the get-all-user-accounts Portals API to retrieve the user-id by supplying an email.
### Input: Uses the get-all-user-accounts Portals API to retrieve the user-id by supplying an email. ### Response: def get_user_id_from_email(self, email): accts = self.get_all_user_accounts() for acct in accts: if acct[] == email: return acct[] re...
def _latex_item_to_string(item, *, escape=False, as_content=False): if isinstance(item, pylatex.base_classes.LatexObject): if as_content: return item.dumps_as_content() else: return item.dumps() elif not isinstance(item, str): item = str(item) if escape...
Use the render method when possible, otherwise uses str. Args ---- item: object An object that needs to be converted to a string escape: bool Flag that indicates if escaping is needed as_content: bool Indicates whether the item should be dumped using `~.LatexObject.d...
### Input: Use the render method when possible, otherwise uses str. Args ---- item: object An object that needs to be converted to a string escape: bool Flag that indicates if escaping is needed as_content: bool Indicates whether the item should be dumped using `~.L...
def _generate_SAX_single(self, sections, value): sax = 0 for section_number in sections.keys(): section_lower_bound = sections[section_number] if value >= section_lower_bound: sax = section_number else: break return str...
Generate SAX representation(Symbolic Aggregate approXimation) for a single data point. Read more about it here: Assumption-Free Anomaly Detection in Time Series(http://alumni.cs.ucr.edu/~ratana/SSDBM05.pdf). :param dict sections: value sections. :param float value: value to be categorized. ...
### Input: Generate SAX representation(Symbolic Aggregate approXimation) for a single data point. Read more about it here: Assumption-Free Anomaly Detection in Time Series(http://alumni.cs.ucr.edu/~ratana/SSDBM05.pdf). :param dict sections: value sections. :param float value: value to be catego...
def _finalize_nonblock_blob(self, ud, metadata): needs_resize, final_size = ud.requires_resize() if needs_resize: self._resize_blob(ud, final_size) if (ud.requires_non_encrypted_md5_put or ud.entity.cache_control is not None): ...
Finalize Non-Block blob :param Uploader self: this :param blobxfer.models.upload.Descriptor ud: upload descriptor :param dict metadata: metadata dict
### Input: Finalize Non-Block blob :param Uploader self: this :param blobxfer.models.upload.Descriptor ud: upload descriptor :param dict metadata: metadata dict ### Response: def _finalize_nonblock_blob(self, ud, metadata): needs_resize, final_size = ud.requi...
def get_c2ps(self): c2ps = defaultdict(set) for goid_child, goid_parent in self.edges: c2ps[goid_child].add(goid_parent) return c2ps
Set child2parents dict for all parents used in this set of edges.
### Input: Set child2parents dict for all parents used in this set of edges. ### Response: def get_c2ps(self): c2ps = defaultdict(set) for goid_child, goid_parent in self.edges: c2ps[goid_child].add(goid_parent) return c2ps
def conditions(self, trigger_id): response = self._get(self._service_url([, trigger_id, ])) return Condition.list_to_object_list(response)
Get all conditions for a specific trigger. :param trigger_id: Trigger definition id to be retrieved :return: list of condition objects
### Input: Get all conditions for a specific trigger. :param trigger_id: Trigger definition id to be retrieved :return: list of condition objects ### Response: def conditions(self, trigger_id): response = self._get(self._service_url([, trigger_id, ])) return Condition.list_t...
def resize(self, size, interp=): gray_im_resized = self.gray.resize(size, interp) depth_im_resized = self.depth.resize(size, interp) return GdImage.from_grayscale_and_depth( gray_im_resized, depth_im_resized)
Resize the image. Parameters ---------- size : int, float, or tuple * int - Percentage of current size. * float - Fraction of current size. * tuple - Size of the output image. interp : :obj:`str`, optional Interpolation to use for re-si...
### Input: Resize the image. Parameters ---------- size : int, float, or tuple * int - Percentage of current size. * float - Fraction of current size. * tuple - Size of the output image. interp : :obj:`str`, optional Interpolation to u...
def generate_nonce(): nonce = .join([str(randint(0, 9)) for i in range(8)]) return HMAC( nonce.encode(), "secret".encode(), sha1 ).hexdigest()
Generate nonce number
### Input: Generate nonce number ### Response: def generate_nonce(): nonce = .join([str(randint(0, 9)) for i in range(8)]) return HMAC( nonce.encode(), "secret".encode(), sha1 ).hexdigest()
def close_all(self): if self._try_close_dirty_tabs(): while self.count(): widget = self.widget(0) self.remove_tab(0) self.tab_closed.emit(widget) return True return False
Closes all editors
### Input: Closes all editors ### Response: def close_all(self): if self._try_close_dirty_tabs(): while self.count(): widget = self.widget(0) self.remove_tab(0) self.tab_closed.emit(widget) return True return False
def create(cls, zmq_context, endpoint): socket = zmq_context.socket(zmq.ROUTER) socket.bind(endpoint) return cls(socket)
Create new server transport. Instead of creating the socket yourself, you can call this function and merely pass the :py:class:`zmq.core.context.Context` instance. By passing a context imported from :py:mod:`zmq.green`, you can use green (gevent) 0mq sockets as well. :param zm...
### Input: Create new server transport. Instead of creating the socket yourself, you can call this function and merely pass the :py:class:`zmq.core.context.Context` instance. By passing a context imported from :py:mod:`zmq.green`, you can use green (gevent) 0mq sockets as well. ...
def hist(self, var: str, title: str = , label: str = ) -> object: code = "proc sgplot data=" + self.libref + + self.table + self._dsopts() code += ";\n\thistogram " + var + " / scale=count" if len(label) > 0: code += " LegendLABEL=" code += ";\n" ...
This method requires a numeric column (use the contents method to see column types) and generates a histogram. :param var: the NUMERIC variable (column) you want to plot :param title: an optional Title for the chart :param label: LegendLABEL= value for sgplot :return:
### Input: This method requires a numeric column (use the contents method to see column types) and generates a histogram. :param var: the NUMERIC variable (column) you want to plot :param title: an optional Title for the chart :param label: LegendLABEL= value for sgplot :return: ### Re...
def items(self): content_type = ContentType.objects.get_for_model(Entry) return comments.get_model().objects.filter( content_type=content_type, is_public=True).order_by( )[:self.limit]
Items are the discussions on the entries.
### Input: Items are the discussions on the entries. ### Response: def items(self): content_type = ContentType.objects.get_for_model(Entry) return comments.get_model().objects.filter( content_type=content_type, is_public=True).order_by( )[:self.limit]
def _get_serializer(output): serializers = salt.loader.serializers(__opts__) try: return getattr(serializers, output) except AttributeError: raise CommandExecutionError( "Unknown serializer found for output option".format(output) )
Helper to return known serializer based on pass output argument
### Input: Helper to return known serializer based on pass output argument ### Response: def _get_serializer(output): serializers = salt.loader.serializers(__opts__) try: return getattr(serializers, output) except AttributeError: raise CommandExecutionError( "Unknown s...
def b1_boundary(b_hi, N): b_lo = b_hi-1 b1_lo = b1_theory(N, b_to_mu(b_lo)) b1_hi = b1_theory(N, b_to_mu(b_hi)) if b1_lo >= -4: return np.sqrt(b1_lo*b1_hi) else: return 0.5*(b1_lo+b1_hi)
B1 ratio boundary for selecting between [b_hi-1, b_hi] alpha = b + 2
### Input: B1 ratio boundary for selecting between [b_hi-1, b_hi] alpha = b + 2 ### Response: def b1_boundary(b_hi, N): b_lo = b_hi-1 b1_lo = b1_theory(N, b_to_mu(b_lo)) b1_hi = b1_theory(N, b_to_mu(b_hi)) if b1_lo >= -4: return np.sqrt(b1_lo*b1_hi) else: return 0.5*(b1_l...
def _update_variables_shim_with_recalculation_table(self): if not hasattr(self._executable, "recalculation_table"): return for memory_reference, expression in self._executable.recalculation_table.items(): self._variables_shim[memory...
Update self._variables_shim with the final values to be patched into the gate parameters, according to the arithmetic expressions in the original program. For example: DECLARE theta REAL DECLARE beta REAL RZ(3 * theta) 0 RZ(beta+theta) 0 gets tr...
### Input: Update self._variables_shim with the final values to be patched into the gate parameters, according to the arithmetic expressions in the original program. For example: DECLARE theta REAL DECLARE beta REAL RZ(3 * theta) 0 RZ(beta+theta) 0 ...
def Statistics(season=None, clobber=False, model=, injection=False, compare_to=, plot=True, cadence=, planets=False, **kwargs): campaign = season if cadence == : return ShortCadenceStatistics(campaign=campaign, clobber=clobber, ...
Computes and plots the CDPP statistics comparison between `model` and `compare_to` for all long cadence light curves in a given campaign :param season: The campaign number or list of campaign numbers. \ Default is to plot all campaigns :param bool clobber: Overwrite existing files? Default :py:o...
### Input: Computes and plots the CDPP statistics comparison between `model` and `compare_to` for all long cadence light curves in a given campaign :param season: The campaign number or list of campaign numbers. \ Default is to plot all campaigns :param bool clobber: Overwrite existing files? D...
def type(self, sequence_coverage_collection, min_gene_percent_covg_threshold=99): best_versions = self.get_best_version( sequence_coverage_collection.values(), min_gene_percent_covg_threshold) return [self.presence_typer.type(best_version) fo...
Types a collection of genes returning the most likely gene version in the collection with it's genotype
### Input: Types a collection of genes returning the most likely gene version in the collection with it's genotype ### Response: def type(self, sequence_coverage_collection, min_gene_percent_covg_threshold=99): best_versions = self.get_best_version( sequence_cover...
def passing(self, kind=): doc = self.get_doc() table = (doc() if kind == else doc()) df = sportsref.utils.parse_table(table) return df
Gets yearly passing stats for the player. :kind: One of 'R', 'P', or 'B'. Case-insensitive; defaults to 'R'. :returns: Pandas DataFrame with passing stats.
### Input: Gets yearly passing stats for the player. :kind: One of 'R', 'P', or 'B'. Case-insensitive; defaults to 'R'. :returns: Pandas DataFrame with passing stats. ### Response: def passing(self, kind=): doc = self.get_doc() table = (doc() if kind == else ...
def _get_tool_dict(self, tool_name): tool = getattr(self, tool_name) standard_attrs, custom_attrs = self._get_button_attrs(tool) return dict( name=tool_name, label=getattr(tool, , tool_name), standard_attrs=standard_attrs, custom_attrs=cus...
Represents the tool as a dict with extra meta.
### Input: Represents the tool as a dict with extra meta. ### Response: def _get_tool_dict(self, tool_name): tool = getattr(self, tool_name) standard_attrs, custom_attrs = self._get_button_attrs(tool) return dict( name=tool_name, label=getattr(tool, , tool_name...
def get_password(self, service, username): service = escape_for_ini(service) username = escape_for_ini(username) config = configparser.RawConfigParser() if os.path.exists(self.file_path): config.read(self.file_path, encoding=) try: ...
Read the password from the file.
### Input: Read the password from the file. ### Response: def get_password(self, service, username): service = escape_for_ini(service) username = escape_for_ini(username) config = configparser.RawConfigParser() if os.path.exists(self.file_path): config.re...