Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
358,800
def match_check(self, regex, fun): vals = [] if isinstance(fun, six.string_types): fun = [fun] for func in fun: try: if re.match(regex, func): vals.append(True) else: vals.append(False) ...
Validate a single regex to function comparison, the function argument can be a list of functions. It is all or nothing for a list of functions
358,801
def clean_account(self): account = self.cleaned_data[] if not account: return if account.type != Account.TYPES.income: raise ValidationError() try: account.housemate except Housemate.DoesNotExist: pass else: ...
Ensure this is an income account
358,802
def parseStr(self, html): self.reset() if isinstance(html, bytes): self.feed(html.decode(self.encoding)) else: self.feed(html)
parseStr - Parses a string and creates the DOM tree and indexes. @param html <str> - valid HTML
358,803
def data_from_dict(self, data): nvars = [] for key, val in data.items(): self.__dict__[key].extend(val) if len(nvars) > 1 and len(val) != nvars[-1]: raise IndexError( . format(self._name, key)) ...
Populate model parameters from a dictionary of parameters Parameters ---------- data : dict List of parameter dictionaries Returns ------- None
358,804
def add_get(self, path: str, handler: _WebHandler, *, name: Optional[str]=None, allow_head: bool=True, **kwargs: Any) -> AbstractRoute: resource = self.add_resource(path, name=name) if allow_head: resource.add_route(hdrs.METH_HEAD, handler, **kwargs) ...
Shortcut for add_route with method GET, if allow_head is true another route is added allowing head requests to the same endpoint
358,805
def clean_time(time_string): time = dateutil.parser.parse(time_string) if not settings.USE_TZ: time = time.astimezone(timezone.utc).replace(tzinfo=None) return time
Return a datetime from the Amazon-provided datetime string
358,806
def RunMetadata(self, tag): if tag not in self._tagged_metadata: raise ValueError() run_metadata = config_pb2.RunMetadata() run_metadata.ParseFromString(self._tagged_metadata[tag]) return run_metadata
Given a tag, return the associated session.run() metadata. Args: tag: A string tag associated with the event. Raises: ValueError: If the tag is not found. Returns: The metadata in form of `RunMetadata` proto.
358,807
def store_transition(self, frame, action, reward, done, extra_info=None): self.current_idx = (self.current_idx + 1) % self.buffer_capacity self.state_buffer[self.current_idx] = frame self.action_buffer[self.current_idx] = action self.reward_buffer[self.current_idx] = reward ...
Store given transition in the backend
358,808
def detect_all_faces(image, cascade = None, sampler = None, threshold = 0, overlaps = 1, minimum_overlap = 0.2, relative_prediction_threshold = 0.25): if cascade is None: cascade = default_cascade() elif isinstance(cascade, str): cascade = Cascade(bob.io.base.HDF5File(cascade)) if sampler is None: ...
detect_all_faces(image, [cascade], [sampler], [threshold], [overlaps], [minimum_overlap], [relative_prediction_threshold]) -> bounding_boxes, qualities Detects all faces in the given image, whose prediction values are higher than the given threshold. If the given ``minimum_overlap`` is lower than 1, overlapping b...
358,809
def generate_blob_names(self): if not isinstance(keras_layer, _keras.engine.topology.InputLayer): blob_name = layer + _insert_to_dict(self.layers_outputs, layer, blob_name)
Generate blob names for each one of the edge. At this time, Keras does not support "fork" operation (a layer with more than 1 blob output). So we just use names of the src layer to identify a blob. We also assume all neural networks are singly-connected graphs - which should be the case.
358,810
def absolute_magnitude(self, richness=1, steps=1e4): params = {k:v.value for k,v in self._params.items()} params.update(band_1=,band_2=,survey=) iso = self.__class__(**params) mass_init, mass_pdf, mass_act, sdss_g, sdss_r = iso.samp...
Calculate the absolute visual magnitude (Mv) from the richness by transforming the isochrone in the SDSS system and using the g,r -> V transform equations from Jester 2005 [astro-ph/0506022]. Parameters: ----------- richness : isochrone normalization parameter s...
358,811
def get(img, light=False): colors = gen_colors(img) return adjust(colors, light)
Get colorscheme.
358,812
def _import_component(name): for f in (_get_from_module, _get_from_class): try: return f(name) except: pass log.debug("Couldn't load %s" % name)
Returns a class, function, or class method specified by the fully qualified name.
358,813
def _ParseFileData(self, knowledge_base, file_object): line_reader = line_reader_file.BinaryLineReader(file_object) try: reader = line_reader_file.BinaryDSVReader(line_reader, b) except csv.Error as exception: raise errors.PreProcessFail( .format( self.ARTIFACT_DEFI...
Parses file content (data) for user account preprocessing attributes. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_object (dfvfs.FileIO): file-like object that contains the artifact value data. Raises: errors.PreProcessFail: if the preprocessin...
358,814
def zone_exists(zone, region=None, key=None, keyid=None, profile=None, retry_on_rate_limit=None, rate_limit_retries=None, retry_on_errors=True, error_retries=5): if region is None: region = conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ...
Check for the existence of a Route53 hosted zone. .. versionadded:: 2015.8.0 CLI Example:: salt myminion boto_route53.zone_exists example.org
358,815
def get_field_choices(self, field, field_name): if self.request.GET.get(): names = [, ] else: names = [, ] choices_getter = getattr(self, , None) if choices_getter is None: if isinstance(field, ForeignKey): choices_getter = sel...
Returns the valid choices for ``field``. The ``field_name`` argument is given for convenience.
358,816
def initialize_config_values(parsed): try: cfg = UserConfig.from_directory(parsed.profiles_dir) except RuntimeException: cfg = UserConfig.from_dict(None) if cfg.send_anonymous_usage_stats: dbt.tracking.initialize_tracking(parsed.profiles_dir) else: dbt.tracking.do_n...
Given the parsed args, initialize the dbt tracking code. It would be nice to re-use this profile later on instead of parsing it twice, but dbt's intialization is not structured in a way that makes that easy.
358,817
def get_vtkjs_url(*args): if len(args) == 1: host = inURL = args[0] elif len(args) == 2: host = args[0] inURL = args[1] else: raise RuntimeError() if host.lower() == "dropbox": convertURL = convert_dropbox_url(inURL) else: print("--> Warn...
After using ``export_vtkjs()`` to create a ``.vtkjs`` file from a data scene which is uploaded to an online file hosting service like Dropbox, use this method to get a shareable link to that scene on the `PVGeo VTKjs viewer`_. .. _PVGeo VTKjs viewer: http://viewer.vtki.org **Current file hosts sup...
358,818
def _x_start_ok(self, client_properties, mechanism, response, locale): if self.server_capabilities.get(): if not in client_properties: client_properties[] = {} client_properties[][] = True if self.server_capabilities.get(): if not in client_...
Select security mechanism and locale This method selects a SASL security mechanism. ASL uses SASL (RFC2222) to negotiate authentication and encryption. PARAMETERS: client_properties: table client properties mechanism: shortstr selected...
358,819
def select_renderer(request: web.Request, renderers: OrderedDict, force=True): header = request.headers.get(, ) best_match = mimeparse.best_match(renderers.keys(), header) if not best_match or best_match not in renderers: if force: return tuple(renderers.items())[0] else: ...
Given a request, a list of renderers, and the ``force`` configuration option, return a two-tuple of: (media type, render callable). Uses mimeparse to find the best media type match from the ACCEPT header.
358,820
def get_arguments(self): parser = argparse.ArgumentParser( description=) parser.add_argument(, nargs=1, help="URL to scrape") parser.add_argument(, , type=int, default=None, help="Limit on number of images\n") parser.add_argument(, , type...
Gets the arguments from the command line.
358,821
def _pour(opener, flags=0, *args, **kwargs): with _enumerator(opener, *args, entry_cls=_ArchiveEntryItState, **kwargs) as r: ext = libarchive.calls.archive_write.c_archive_write_disk_new() libarchive.calls.archive_write.c_archive_w...
A flexible pouring facility that knows how to enumerate entry data.
358,822
def dotplot(adata, var_names, groupby=None, use_raw=None, log=False, num_categories=7, expression_cutoff=0., mean_only_expressed=False, color_map=, dot_max=None, dot_min=None, figsize=None, dendrogram=False, gene_symbols=None, var_group_positions=None, standard_scale=None, smallest_d...
\ Makes a *dot plot* of the expression values of `var_names`. For each var_name and each `groupby` category a dot is plotted. Each dot represents two values: mean expression within each category (visualized by color) and fraction of cells expressing the var_name in the category (visualized by the s...
358,823
def get_assignable_bank_ids(self, bank_id): mgr = self._get_provider_manager(, local=True) lookup_session = mgr.get_bank_lookup_session(proxy=self._proxy) banks = lookup_session.get_banks() id_list = [] for bank in banks: id_list.append(bank.get_id()...
Gets a list of bank including and under the given bank node in which any assessment part can be assigned. arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank`` return: (osid.id.IdList) - list of assignable bank ``Ids`` raise: NullArgument - ``bank_id`` is ``null`` raise: OperationF...
358,824
def map_url_to_cache_id(self, url): base, _ = self.get_domain_home_from_url(url) if base == : _sub_page = elif base == url or base + == url: _sub_page = else: _sub_page = url.replace(base, ).split() ...
use of the url resource location as cached id e.g.: ``<domain>/foo/bar/a.html => <base>/domain/foo/bar/a.html`` - map the url to local file :param url: :type url: :return: :rtype:
358,825
def list_lv_grid_districts(self, session, lv_stations): gw2kw = 10 ** 6 lv_grid_districs_sqla = session.query( self.orm[].mvlv_subst_id, (self.orm[ ].sector_peakload_residential * gw2kw). label(), (self.orm[].secto...
Imports all lv grid districts within given load area Parameters ---------- session : sqlalchemy.orm.session.Session Database session lv_stations: List required LV_stations==LV districts. Returns ------- pandas Dataframe Table ...
358,826
def execProcCmd(self, *args): out = util.exec_command([psCmd,] + list(args)) return out.splitlines()
Execute ps command with positional params args and return result as list of lines. @param *args: Positional params for ps command. @return: List of output lines
358,827
def _get_template_name(self): start_pattern = r"sys application template\s+" \ r"(\/[\w\.\-]+\/)?" \ r"(?P<name>[\w\.\-]+)\s*\{" template_start = re.search(start_pattern, self.template_str) if template_start: return template_...
Find template name. :returns: string of template name :raises: NonextantTemplateNameException
358,828
def read_var_int(self, max_size=sys.maxsize): fb = self.read_byte() if fb is 0: return fb if hex(fb) == : value = self.read_uint16() elif hex(fb) == : value = self.read_uint32() elif hex(fb) == : value = self.read_uint64() ...
Read a variable length integer from the stream. The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention Args: max_size (int): (Optional) maximum number of bytes to read. Returns: int:
358,829
def reverse_set(self, subid, ipaddr, entry, params=None): params = update_params(params, { : subid, : ipaddr, : entry }) return self.request(, params, )
/v1/server/reverse_set_ipv4 POST - account Set a reverse DNS entry for an IPv4 address of a virtual machine. Upon success, DNS changes may take 6-12 hours to become active. Link: https://www.vultr.com/api/#server_reverse_set_ipv4
358,830
def compute_pointwise_distances(self, other, default=None): import shapely.geometry from .kps import Keypoint if isinstance(other, Keypoint): other = shapely.geometry.Point((other.x, other.y)) elif isinstance(other, LineString): if len(other.coords) == 0...
Compute the minimal distance between each point on self and other. Parameters ---------- other : tuple of number \ or imgaug.augmentables.kps.Keypoint \ or imgaug.augmentables.LineString Other object to which to compute the distances. default...
358,831
def main(): D,I=0.,90. outfile="" infile="" if in sys.argv: print(main.__doc__) sys.exit() if in sys.argv: ind=sys.argv.index() infile=sys.argv[ind+1] data=numpy.loadtxt(infile) else: data=numpy.loadtxt(sys.stdin,dtype=numpy.float) if i...
NAME di_rot.py DESCRIPTION rotates set of directions to new coordinate system SYNTAX di_rot.py [command line options] OPTIONS -h prints help message and quits -f specify input file, default is standard input -F specify output file, default is standard outpu...
358,832
def insert(self, key, minhash, check_duplication=True): s recommended to not change the default, but if you want to avoid the overhead during insert you can set `check_duplication = False`. ' self._insert(key, minhash,...
Insert a key to the index, together with a MinHash (or weighted MinHash) of the set referenced by the key. :param str key: The identifier of the set. :param datasketch.MinHash minhash: The MinHash of the set. :param bool check_duplication: To avoid duplicate keys in the storage...
358,833
def search_ipv6_environment(self, ipv6, id_environment): if not is_valid_int_param(id_environment): raise InvalidParameterError( u) ipv6_map = dict() ipv6_map[] = ipv6 ipv6_map[] = id_environment code, xml = self.submit( {: ipv6...
Get IPv6 with an associated environment. :param ipv6: IPv6 address in the format x1:x2:x3:x4:x5:x6:x7:x8. :param id_environment: Environment identifier. Integer value and greater than zero. :return: Dictionary with the following structure: :: {'ipv6': {'id': < id >, ...
358,834
def clear(self, match="*", count=1000): cursor = while cursor != 0: cursor, keys = self.scan(cursor=cursor, match=match, count=count) if keys: self._client.delete(*keys)
Removes all |{key: value}| entries in :prop:key_prefix of :prop:_client
358,835
def set(self, value: Optional[bool]): prev_value = self._value self._value = value if self._value != prev_value: for event in self._events: event.set()
Sets current status of a check :param value: ``True`` (healthy), ``False`` (unhealthy), or ``None`` (unknown)
358,836
def _get_autoscaling_min_max(template, parameters, asg_name): params = {e[]: e[] for e in parameters} asg = template.get(, {}).get(asg_name, None) if asg: assert asg[] == min = asg.get(, {}).get(, None) max = asg.get(, {}).get(, None) if in min: min = param...
Helper to extract the configured MinSize, MaxSize attributes from the template. :param template: cloudformation template (json) :param parameters: list of {'ParameterKey': 'x1', 'ParameterValue': 'y1'} :param asg_name: logical resource name of the autoscaling group :return: MinSize, MaxSize
358,837
def normalize_hex(hex_value): match = HEX_COLOR_RE.match(hex_value) if match is None: raise ValueError( u" is not a valid hexadecimal color value.".format(hex_value) ) hex_digits = match.group(1) if len(hex_digits) == 3: hex_digits = u.join(2 * s for s in hex_dig...
Normalize a hexadecimal color value to 6 digits, lowercase.
358,838
def leave_chat( self, chat_id: Union[int, str], delete: bool = False ): peer = self.resolve_peer(chat_id) if isinstance(peer, types.InputPeerChannel): return self.send( functions.channels.LeaveChannel( channel=self.res...
Use this method to leave a group chat or channel. Args: chat_id (``int`` | ``str``): Unique identifier for the target chat or username of the target channel/supergroup (in the format @username). delete (``bool``, *optional*): Deletes the ...
358,839
def generate(self, vars=None, env=None): def defined(v, default=None): _v = default if v in vars: _v = vars[v] elif v in env: _v = env[v] return _v namespace = { "de...
Generate this template with the given arguments.
358,840
def create_cert_binding(name, site, hostheader=, ipaddress=, port=443, sslflags=0): *AAA000site0example.com*443 name = six.text_type(name).upper() binding_info = _get_binding_info(hostheader, ipaddress, port) if _iisVersion() < 8: binding_info = binding_info.rpa...
Assign a certificate to an IIS Web Binding. .. versionadded:: 2016.11.0 .. note:: The web binding that the certificate is being assigned to must already exist. Args: name (str): The thumbprint of the certificate. site (str): The IIS site name. hostheader (str): Th...
358,841
def add_suffix(path, suffix=""): return join(dirname(path), basename(path, ext=False) + suffix + extname(path))
Adds a suffix to a filename *path*
358,842
def get_nonce_timestamp(nonce): components = nonce.split(,2) if not len(components) == 3: return None try: return float(components[0]) except ValueError: return None
Extract the timestamp from a Nonce. To be sure the timestamp was generated by this site, make sure you validate the nonce using validate_nonce().
358,843
def build_dot(self): from graphviz import Digraph dot = Digraph() dot.attr("graph", bgcolor=self.theme["background_color"], color=self.theme["outline_color"], fontsize=self.theme["font_size"], fontcolor=self....
Generate a GraphViz Dot graph. Returns a GraphViz Digraph object.
358,844
def get_image_and_mask(self, label, positive_only=True, hide_rest=False, num_features=5, min_weight=0.): if label not in self.local_exp: raise KeyError() segments = self.segments image = self.image exp = self.local_exp[label] mask =...
Init function. Args: label: label to explain positive_only: if True, only take superpixels that contribute to the prediction of the label. Otherwise, use the top num_features superpixels, which can be positive or negative towards the label...
358,845
def check_field_multiplicity(tag, previous_tags): fail = False if not tag.field.multiple: if not tag.id: fail = previous_tags.filter(field=tag.field) else: fail = previous_tags.filter(field=ta...
Check the multiplicity of a 'field' for an object.
358,846
def parse_conservation(variant, info_key): raw_score = variant.INFO.get(info_key) conservations = [] if raw_score: if isinstance(raw_score, numbers.Number): raw_score = (raw_score,) for score in raw_score: if score >= CONSERVATION[info_key][]: c...
Get the conservation prediction Args: variant(dict): A variant dictionary info_key(str) Returns: conservations(list): List of censervation terms
358,847
def render(template, **kwargs): import jinja2 import os.path as path searchpath = path.join(path.dirname(__file__), "templates") loader = jinja2.FileSystemLoader(searchpath=searchpath) env = jinja2.Environment(loader=loader) temp = env.get_template(template) retur...
Renders the HTML containing provided summaries. The summary has to be an instance of summary.Summary, or at least contain similar properties: title, image, url, description and collections: titles, images, descriptions.
358,848
def compute(self, feedforwardInput=(), lateralInputs=(), feedforwardGrowthCandidates=None, learn=True, predictedInput = None,): if feedforwardGrowthCandidates is None: feedforwardGrowthCandidates = feedforwardInput if not learn: self._computeInferenceMode(feed...
Runs one time step of the column pooler algorithm. @param feedforwardInput (sequence) Sorted indices of active feedforward input bits @param lateralInputs (list of sequences) For each lateral layer, a list of sorted indices of active lateral input bits @param feedfo...
358,849
def execute_task(task_id, verbosity=None, runmode=, sigmode=None, monitor_interval=5, resource_monitor_interval=60): tf = TaskFile(task_id) tf.status = try: signal.signal(signal.SIGTERM, signal_hand...
Execute single or master task, return a dictionary
358,850
def parseTimestamp(s): s = s.strip() for pattern in DATETIME_FORMATS: try: return datetime.datetime.strptime(s, pattern) except ValueError: pass raise ValueError( % (s, .join(DATETIME_FORMATS)))
Parses a textual datetime format and return a Python datetime object. The supported format is: ``yyyy-mm-dd h:m:s.ms`` The time component is optional. - hours are 00..23 (no AM/PM) - minutes are 00..59 - seconds are 00..59 - micro-seconds are 000000..999999 :param s: (string) input time text :return...
358,851
def finalise(self): assert(self._is_solved()) g = self._get_minimal_graph() scopes = dict((x.package_name, x) for x in self.scopes if not x.package_request.conflict) fam_cycle = find_cycle(g) if fam_cycle: cycle = [] ...
Remove conflict requests, detect cyclic dependencies, and reorder packages wrt dependency and then request order. Returns: A new copy of the phase with conflict requests removed and packages correctly ordered; or, if cyclic dependencies were detected, a new phase mar...
358,852
def _cas_1(self): lonc = self._format_lon(self.lonm) latc = self._format_lat(self.latm) img = self._format_name_map(lonc, latc) img_map = BinaryTable(img, self.path_pdsfiles) return img_map.extract_grid(self.lonm, self.lonM, self.latm, self.latM)
1 - The desired structure is entirely contained into one image.
358,853
def _executor(self, host): try: exec_rc = self._executor_internal(host) if not exec_rc.comm_ok: self.callbacks.on_unreachable(host, exec_rc.result) return exec_rc except errors.AnsibleError, ae: ...
handler for multiprocessing library
358,854
def list(self, var, cast=None, default=NOTSET): return self.get_value(var, cast=list if not cast else [cast], default=default)
:rtype: list
358,855
def status(self, head): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if head: sock.connect((self.server, self.port)) else: sock.connect((self.server2, self.port2)) self._hello(sock) comms.send_message(sock, "<Status/>".encode()) ...
Get status from server. head - Ping the the head node if True.
358,856
def from_twodim_list(cls, datalist, tsformat=None, dimensions=1): ts = MultiDimensionalTimeSeries(dimensions=dimensions) ts.set_timeformat(tsformat) for entry in datalist: ts.add_entry(entry[0], entry[1]) ts._normalized = ts.is_normalized() ...
Creates a new MultiDimensionalTimeSeries instance from the data stored inside a two dimensional list. :param list datalist: List containing multiple iterables with at least two values. The first item will always be used as timestamp in the predefined format, the second is a list, con...
358,857
def create_query_constraint(): op = oneOf("= < > >= <= != <>", caseless=True).setName("operator") basic_constraint = (var + op + var_val).setResultsName("operator") between = ( var + Suppress(upkey("between")) + value + Suppress(and_) + value ).setResultsName("between") is_in = (var + S...
Create a constraint for a query WHERE clause
358,858
def qteGetAppletFromWidget(widgetObj): if widgetObj is None: return None if hasattr(widgetObj, ): return widgetObj._qteAdmin.qteApplet visited = [widgetObj] wid = widgetObj.parent() while wid not in visited: if hasattr(wid, ): return wi...
Return the parent applet of ``widgetObj``. |Args| * ``widgetObj`` (**QWidget**): widget (if any) for which the containing applet is requested. |Returns| * **QtmacsApplet**: the applet containing ``widgetObj`` or **None**. |Raises| * **None**
358,859
def return_tip(self) -> : if not self.hw_pipette[]: self._log.warning() loc = self._last_tip_picked_up_from if not isinstance(loc, Well): raise TypeError( .format(loc)) bot = loc.bottom() bot = bot._replace(point=bot.po...
If a tip is currently attached to the pipette, then it will return the tip to it's location in the tiprack. It will not reset tip tracking so the well flag will remain False. :returns: This instance
358,860
def python_2_unicode_compatible(klass): if sys.version_info[0] == 2: klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode() return klass
A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class.
358,861
def cgi_parameter_exists(form: cgi.FieldStorage, key: str) -> bool: s = get_cgi_parameter_str(form, key) return s is not None
Does a CGI form contain the key?
358,862
def fetch(self, vault_client): backends = [(self.mounts, SecretBackend), (self.auths, AuthBackend), (self.logs, LogBackend)] for b_list, b_class in backends: backend_list = b_list() if backend_list: existing = getat...
Updates the context based on the contents of the Vault server. Note that some resources can not be read after they have been written to and it is up to those classes to handle that case properly.
358,863
def attach_to_container(self, container_id): sock = self._docker.containers.get(container_id).attach_socket(params={ : 1, : 1, : 0, : 1, }) return FixDockerSocket(sock)
A socket attached to the stdin/stdout of a container. The object returned contains a get_socket() function to get a socket.socket object and close_socket() to close the connection
358,864
def nrzi(data): current = True for bit in data: if not bit: current = not current yield current
Packet uses NRZI (non-return to zero inverted) encoding, which means that a 0 is encoded as a change in tone, and a 1 is encoded as no change in tone.
358,865
def multilevel_rpn_losses( multilevel_anchors, multilevel_label_logits, multilevel_box_logits): num_lvl = len(cfg.FPN.ANCHOR_STRIDES) assert len(multilevel_anchors) == num_lvl assert len(multilevel_label_logits) == num_lvl assert len(multilevel_box_logits) == num_lvl losses = [] wi...
Args: multilevel_anchors: #lvl RPNAnchors multilevel_label_logits: #lvl tensors of shape HxWxA multilevel_box_logits: #lvl tensors of shape HxWxAx4 Returns: label_loss, box_loss
358,866
def require_request_model(cls, validate=True): def decorator(handler): async def new_handler(request, *args, **kwargs): body = await request.json() model = cls(**body) if validate: model.validate() return await handler(request, model, *a...
Makes a handler require that a request body that map towards the given model is provided. Unless the ``validate`` option is set to ``False`` the data will be validated against the model's fields. The model will be passed to the handler as the last positional argument. :: @require_request_model(Mod...
358,867
def __start_command_queue_listener(self): thread_function = self.__command_queue_listener class QueueListenerThread(threading.Thread): def run(qltself): thread_function() assert not hasattr(self, "__queue_listener_thread") self.log.debug("Starting q...
Start the function __command_queue_listener in a separate thread. This function continuously listens to the pipe connected to the frontend.
358,868
def __build_level(self, previous_level_blocks, level): current_level_blocks = [] split_dimension = level % len(self.__data[0]) cache_require = (level == self.__levels - 1) for block in previous_level_blocks: self.__split_block(block, split_dimension, cache_...
! @brief Build new level of directory. @param[in] previous_level_blocks (list): BANG-blocks on the previous level. @param[in] level (uint): Level number that should be built. @return (list) New block on the specified level.
358,869
def get_partial_object(self, bucket_name, object_name, offset=0, length=0, request_headers=None, sse=None): is_valid_bucket_name(bucket_name) is_non_empty_string(object_name) return self._get_partial_object(bucket_name, object_name, ...
Retrieves an object from a bucket. Optionally takes an offset and length of data to retrieve. This function returns an object that contains an open network connection to enable incremental consumption of the response. To re-use the connection (if desired) on subsequent requests...
358,870
def parse_section_data_files(self, section_options): parsed = self._parse_section_to_dict(section_options, self._parse_list) self[] = [(k, v) for k, v in parsed.items()]
Parses `data_files` configuration file section. :param dict section_options:
358,871
def start_client(self, language): started = False if language in self.clients: language_client = self.clients[language] queue = self.register_queue[language] for entry in queue: language_client.register_file(*entry) ...
Start an LSP client for a given language.
358,872
def getfile(object): if ismodule(object): if hasattr(object, ): return object.__file__ raise TypeError, if isclass(object): object = sys.modules.get(object.__module__) if hasattr(object, ): return object.__file__ raise TypeError, if isme...
Work out which source or compiled file an object was defined in.
358,873
def calling_convention(self): if self._calling_convention is None: self._calling_convention = \ calldef_types.CALLING_CONVENTION_TYPES.extract(self.attributes) if not self._calling_convention: self._calling_convention = self.guess_calling_conventi...
function calling convention. See :class:CALLING_CONVENTION_TYPES class for possible values
358,874
def rmap(fn, coll, is_iterable=None): result = [] for x in coll: if is_iterable is None: is_iterable = isiterable if is_iterable(x): y = rmap(fn, x) else: y = fn(x) result.append(y) return result
A recursive map :param fn: a function :param coll: a list :param isiterable: a predicate function determining whether a value is iterable. :returns: a list >>> rmap(lambda x: 2*x, [1, 2, [3, 4]]) [2, 4, [6, 8]]
358,875
def decode_coords(ds, gridfile=None): def add_attrs(obj): if in obj.attrs: extra_coords.update(obj.attrs[].split()) obj.encoding[] = obj.attrs.pop() if in obj.attrs: extra_coords.add(obj.attrs[]) if gridfile is not None a...
Sets the coordinates and bounds in a dataset This static method sets those coordinates and bounds that are marked marked in the netCDF attributes as coordinates in :attr:`ds` (without deleting them from the variable attributes because this information is necessary for visualizing the da...
358,876
def fit_mle(self, data, init_vals=(80, 80)): if len(data) > 1: mu = np.mean(data) var = np.var(data) theta0 = var / mu alpha0 = mu / theta0 else: alpha0 = init_vals[0] theta0 = init_vals[1] def mle(params): ...
%(super)s In addition to data, can take init_vals which allows the user to specify initial values for (alpha, theta) during the optimization.
358,877
def is_ssl_error(error=None): if error is None: error = sys.exc_info()[1] from OpenSSL import SSL return isinstance(error, SSL.Error)
Checks if the given error (or the current one) is an SSL error.
358,878
def attach_schema(self, schem): self.tuple_schema = schema.AndSchema.make(self.tuple_schema, schem)
Add a tuple schema to this object (externally imposed)
358,879
def setupHeaderMenu(self, menu, index): if not self.userGroupingEnabled(): return False first_action = menu.actions()[1] column = self.columnOf(index) enable_action = QAction(menu) enable_action.setText() disable_...
Updates the header right-click menu to include grouping options if desired. :param menu | <QMenu> index | <int>
358,880
def add_device(dev): global DEV_IDX, DEFAULT_DEV with DEV_LOCK: for idx in range(len(DEVS)): test_dev = DEVS[idx] if test_dev.dev_name_short == dev.dev_name_short: if test_dev is DEFAULT_DEV: DEFAULT_DEV = None ...
Adds a device to the list of devices we know about.
358,881
def _encode_decode_decorator(func): def wrapper(*args): try: processed_geom = func(*args) return processed_geom except ImportError as err: raise ImportError( .format(err)) return wrappe...
decorator for encoding and decoding geoms
358,882
def key_dict( from_dict ): new_dict = {} old2new = {} new2old = {} for key in from_dict: k = normalizeUnicode(key,) if k != key: i = while new_dict.has_key("%s%s" % (k,i) ): if not i: i = 1 else: i += 1 k = "%s%s" % (k,i) old2new[key] = k new2old[k] = key new_dict[k] = from...
Returns dict from_dict['unicode_save_field'] = 'original key with unicode'
358,883
def close(self): if self._closed: return self._closed = True self._worker_thread.work_queue.put(self.aiohttp_session.close()) self._worker_thread.work_queue.put(self.worker_thread.sentinel) self._worker_thread.join()
Terminates the session. It schedules the ``close()`` coroutine of the underlying aiohttp session and then enqueues a sentinel object to indicate termination. Then it waits until the worker thread to self-terminate by joining.
358,884
def get_heron_dir(): go_above_dirs = 9 path = "/".join(os.path.realpath(__file__).split()[:-go_above_dirs]) return normalized_class_path(path)
This will extract heron directory from .pex file. For example, when __file__ is '/Users/heron-user/bin/heron/heron/tools/common/src/python/utils/config.pyc', and its real path is '/Users/heron-user/.heron/bin/heron/tools/common/src/python/utils/config.pyc', the internal variable ``path`` would be '/Users/heron...
358,885
def get(self, *args, **kwargs): assert not args assert list(kwargs.keys()) == [] pk = kwargs[] model_name = self.model.__name__ object_spec = (model_name, pk, None) instances = self.cache.get_instances((object_spec,)) try: model_data = instanc...
Return the single item from the filtered queryset.
358,886
def has_control_chars(i): if not hasattr(i, ): return False if i.type_ != Type.string: return False if i.token in (, ): return True for c in i.value: if 15 < ord(c) < 22: return True re...
Returns true if the passed token is an unknown string or a constant string having control chars (inverse, etc
358,887
def _calculate_menu_wh(self): w = iw = 50 h = ih = 0 index = self._menu.index(tk.END) index = index if index is not None else 0 count = index + 1 font = self._menu.cget() font = self._get_font(font) for i in range(0, count): ...
Calculate menu widht and height.
358,888
def point_source_list(self, kwargs_ps, kwargs_lens, k=None): ra_list, dec_list = self.image_position(kwargs_ps, kwargs_lens, k=k) amp_list = self.image_amplitude(kwargs_ps, kwargs_lens) ra_array, dec_array, amp_array = [], [], [] for i, ra in enumerate(ra_list): for ...
returns the coordinates and amplitudes of all point sources in a single array :param kwargs_ps: :param kwargs_lens: :return:
358,889
def impulse_deltav_general_curvedstream(v,x,b,w,x0,v0,pot): pot= flatten_potential(pot) if len(v.shape) == 1: v= numpy.reshape(v,(1,3)) if len(x.shape) == 1: x= numpy.reshape(x,(1,3)) b0 = numpy.cross(w,v0) b0 *= b/numpy.sqrt(numpy.sum(b0**2)) b_ = b0+x-x0 return numpy.array(list(map(la...
NAME: impulse_deltav_general_curvedstream PURPOSE: calculate the delta velocity to due an encounter with a general spherical potential in the impulse approximation; allows for arbitrary velocity vectors and arbitrary shaped streams INPUT: v - velocity of the stream (nstar,3) x ...
358,890
def process_IN_CREATE(self, raw_event): if raw_event.mask & IN_ISDIR: watch_ = self._watch_manager.get_watch(raw_event.wd) created_dir = os.path.join(watch_.path, raw_event.name) if watch_.auto_add and not watch_.exclude_filter(created_dir): addw = se...
If the event affects a directory and the auto_add flag of the targetted watch is set to True, a new watch is added on this new directory, with the same attribute values than those of this watch.
358,891
def beacon(config): log.trace() _config = {} list(map(_config.update, config)) ret = [] if not all([_config[], _config[], _config[]]): return ret output = {} output[] = [] client = TwilioRestClient(_config[], _config[]) messages = client...
Emit a dict name "texts" whose value is a list of texts. .. code-block:: yaml beacons: twilio_txt_msg: - account_sid: "<account sid>" - auth_token: "<auth token>" - twilio_number: "+15555555555" - interval: 10
358,892
def DecryptPassword(cipher, key): import base64 import hmac import sha from array import array H = UcsUtils.GetShaHash cipher = cipher + "\n" cipher = base64.decodestring(cipher) n = len(cipher) - 16 - 8 uhash = cipher[:16] passwordStream = cipher[16:-8] + "0000"[n & 3:] auth = cipher[-8:] ...
Decrypts the password using the given key with which the password was encrypted first.
358,893
def _loadFromArray(self, dtype: HdlType, bitAddr: int) -> int: self.itemCnt = evalParam(dtype.size).val self.children = TransTmpl( dtype.elmType, 0, parent=self, origin=self.origin) return bitAddr + self.itemCnt * self.children.bitAddrEnd
Parse HArray type to this transaction template instance :return: address of it's end
358,894
def _move(self, from_state=None, to_state=None, when=None, mode=None): pipeline = self.tiger.connection.pipeline() scripts = self.tiger.scripts _key = self.tiger._key from_state = from_state or self.state queue = self.queue assert from_state assert que...
Internal helper to move a task from one state to another (e.g. from QUEUED to DELAYED). The "when" argument indicates the timestamp of the task in the new state. If no to_state is specified, the task will be simply removed from the original state. The "mode" param can be specified to de...
358,895
def _do_cron(): if not args["cron"]: return if ("enabled" in db and not db["enabled"]) or "enabled" not in db: warn("The CI server is disabled. Exiting.") exit(0) from pyci.server import Server from datetime import datetime attempted =...
Handles the cron request to github to check for new pull requests. If any are found, they are run *sequentially* until they are all completed.
358,896
def mkvirtualenv(): root = .join([deployment_root(),]) path = .join([root,env.project_fullname]) dirs_created = [] if env.verbosity: print env.host,, path if not exists(root): dirs_created += mkdirs(root) with cd(root): run(.join(["virtualenv",env.project_fullname])) wit...
Create the virtualenv project environment
358,897
def upgrade_api(request, client, version): min_ver, max_ver = api_versions._get_server_version_range(client) if min_ver <= api_versions.APIVersion(version) <= max_ver: client = _nova.novaclient(request, version) return client
Ugrade the nova API to the specified version if possible.
358,898
def query(self, hostname, x509): key = self._x509_key(x509) try: pins = self._storage[hostname] except KeyError: return None if key in pins: return True return None
Return true if the given :class:`OpenSSL.crypto.X509` object `x509` has previously been pinned for use with the given `hostname` and :data:`None` otherwise. Returning :data:`None` allows this method to be used with :class:`PinningPKIXCertificateVerifier`.
358,899
def get_normalized_path(path): if platform.system() == "Windows" or platform.system() == "Microsoft": path = os.path.normpath(path).replace("\\", "\\\\") LOGGER.debug("> Path: , normalized path.".format(path)) return path else: path = os.path.normpath(path) LOGGER.d...
Normalizes a path, escaping slashes if needed on Windows. Usage:: >>> get_normalized_path("C:\\Users/johnDoe\\Documents") u'C:\\Users\\JohnDoe\\Documents' :param path: Path to normalize. :type path: unicode :return: Normalized path. :rtype: unicode