code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def update_looks(self): """ Updates the looks of the gate depending on state. """ if self.state == 'active': style = {'color': 'red', 'linestyle': 'solid'} else: style = {'color': 'black'} for artist in self.artist_list: artist.update(style)
Updates the looks of the gate depending on state.
def get_object(self, queryset=None): """ Returns the considered object. """ profile, dummy = ForumProfile.objects.get_or_create(user=self.request.user) return profile
Returns the considered object.
def _empty_cache(self, termlist=None): """Empty the cache associated with each `Term` instance. This method is called when merging Ontologies or including new terms in the Ontology to make sure the cache of each term is cleaned and avoid returning wrong memoized values (such as ...
Empty the cache associated with each `Term` instance. This method is called when merging Ontologies or including new terms in the Ontology to make sure the cache of each term is cleaned and avoid returning wrong memoized values (such as Term.rchildren() TermLists, which get memoized for...
def layer_definition_type(layer): """Returned relevant layer definition based on layer purpose. Returned the the correct definition of layer based on its purpose. For example, if a layer have layer_purpose: exposure, and exposure: roads then it will return definition for exposure_roads. That's why...
Returned relevant layer definition based on layer purpose. Returned the the correct definition of layer based on its purpose. For example, if a layer have layer_purpose: exposure, and exposure: roads then it will return definition for exposure_roads. That's why it only supports hazard layer or exposur...
def find_zone_name(data, zone_id): """ Find on the HTML document the zone name. # expected result <span class="more_info" \ title="Zone can be renamed on Setup tab">1 - zone1</span>, :param data: BeautifulSoup object :param zone: zone id :return: zone name :rtype: string :r...
Find on the HTML document the zone name. # expected result <span class="more_info" \ title="Zone can be renamed on Setup tab">1 - zone1</span>, :param data: BeautifulSoup object :param zone: zone id :return: zone name :rtype: string :raises TypeError: if data is not a BeautifulSoup...
def string(self, *args): """ return string stored in node """ data = self.bytes(*args) if data is not None: return data.rstrip(b"\x00").decode('utf-8')
return string stored in node
def get_transfer_history(self, from_block: int, to_block: Optional[int] = None, from_address: Optional[str] = None, to_address: Optional[str] = None, token_address: Optional[str] = None) -> List[Dict[str, any]]: """ Get events for erc20 transfers...
Get events for erc20 transfers. At least one of `from_address`, `to_address` or `token_address` must be defined An example of event: { "args": { "from": "0x1Ce67Ea59377A163D47DFFc9BaAB99423BE6EcF1", "to": "0xaE9E15896fd32E59C7d89ce7a95a9352D6ebD70E", ...
def generate_sections(self): """Return all hubs, slugs, and upload counts.""" datasets = Dataset.objects.values( 'hub_slug' ).annotate( upload_count=Count( 'hub_slug' ) ).order_by('-upload_count') return [ { ...
Return all hubs, slugs, and upload counts.
def evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, output_file, debug=False): """Evaluate parser on a data set Parameters ---------- parser : BiaffineParser biaffine parser vocab : ParserVocabulary vocabulary built ...
Evaluate parser on a data set Parameters ---------- parser : BiaffineParser biaffine parser vocab : ParserVocabulary vocabulary built from data set num_buckets_test : int size of buckets (cluster sentences into this number of clusters) test_batch_size : int batch...
def _parse_body(self, robj, response, expected_statuses): """ Parse the body of an object response and populate the object. """ # If no response given, then return. if response is None: return None status, headers, data = response # Check if the serv...
Parse the body of an object response and populate the object.
def spkw15(handle, body, center, inframe, first, last, segid, epoch, tp, pa, p, ecc, j2flg, pv, gm, j2, radius): """ Write an SPK segment of type 15 given a type 15 data record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw15_c.html :param handle: Handle of an SPK file open f...
Write an SPK segment of type 15 given a type 15 data record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw15_c.html :param handle: Handle of an SPK file open for writing. :type handle: int :param body: Body code for ephemeris object. :type body: int :param center: Body code for ...
def on_service_arrival(self, svc_ref): """ Called when a service has been registered in the framework :param svc_ref: A service reference """ with self._lock: if self.reference is None: # Inject the service service = self._context.get_...
Called when a service has been registered in the framework :param svc_ref: A service reference
def cmd_delete(args): """Deletes a node""" major = args.get(0) minor = args.get(1) if major is not None: if major in penStore.data: if minor is None: if len(penStore.data[major]) > 0: if raw_input("are you sure (y/n)? ") not in ['y', 'Y', 'yes', 'Y...
Deletes a node
def check_default_values(section, key, validator=None): """Raise an MissingDefaultError if a value in section does not have a default values :param section: the section of a configspec :type section: section :param key: a key of the section :type key: str :param validator: a Validator object to...
Raise an MissingDefaultError if a value in section does not have a default values :param section: the section of a configspec :type section: section :param key: a key of the section :type key: str :param validator: a Validator object to get the default values :type validator: Validator :ret...
def quic_graph_lasso_ebic(X, gamma=0): """Run QuicGraphicalLassoEBIC with gamma. QuicGraphicalLassoEBIC is a convenience class. Results should be identical to those obtained via quic_graph_lasso_ebic_manual. """ print("QuicGraphicalLassoEBIC with:") print(" mode: path") print(" gamma: ...
Run QuicGraphicalLassoEBIC with gamma. QuicGraphicalLassoEBIC is a convenience class. Results should be identical to those obtained via quic_graph_lasso_ebic_manual.
def GetMessages(self, formatter_mediator, event): """Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. eve...
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
def close(self): """Close the stream. If *autoclose* was passed to the constructor then the underlying transport will be closed as well. """ if self._closed: return if self._autoclose: self._transport.close() self._transport._closed.wa...
Close the stream. If *autoclose* was passed to the constructor then the underlying transport will be closed as well.
def copyWorkitem(self, copied_from, title=None, description=None, prefix=None): """Create a workitem by copying from an existing one :param copied_from: the to-be-copied workitem id :param title: the new workitem title/summary. If `None`, will copy that from a t...
Create a workitem by copying from an existing one :param copied_from: the to-be-copied workitem id :param title: the new workitem title/summary. If `None`, will copy that from a to-be-copied workitem :param description: the new workitem description. If `None`, will copy ...
def reportSuspiciousNode(self, nodeName: str, reason=None, code: int = None, offendingMsg=None): """ Report suspicion on a node and add it to this node's blacklist. :param nodeNam...
Report suspicion on a node and add it to this node's blacklist. :param nodeName: name of the node to report suspicion on :param reason: the reason for suspicion
def set_rules(self, rules): """ Sets the rules to be run or ignored for the audit. Args: rules: a dictionary of the format `{"ignore": [], "apply": []}`. See https://github.com/GoogleChrome/accessibility-developer-tools/tree/master/src/audits Passing `{"apply": []...
Sets the rules to be run or ignored for the audit. Args: rules: a dictionary of the format `{"ignore": [], "apply": []}`. See https://github.com/GoogleChrome/accessibility-developer-tools/tree/master/src/audits Passing `{"apply": []}` or `{}` means to check for all available rule...
def prev(self, name=None): """ Returns the previous sibling of this node. :param name: If specified, only consider elements with this tag name :rtype: :class:`XmlElement` """ if self.parent is None or self.index is None: return None for idx in xrange(...
Returns the previous sibling of this node. :param name: If specified, only consider elements with this tag name :rtype: :class:`XmlElement`
def dispatch(self, *args, **kwargs): """This decorator sets this view to have restricted permissions.""" return super(StrainDelete, self).dispatch(*args, **kwargs)
This decorator sets this view to have restricted permissions.
def _GetLink(self): """Retrieves the link. Returns: str: path of the linked file. """ if self._link is None: self._link = '' if self.entry_type != definitions.FILE_ENTRY_TYPE_LINK: return self._link link = self._fsapfs_file_entry.symbolic_link_target if link and l...
Retrieves the link. Returns: str: path of the linked file.
def derive_child_context(self, whence): """Derives a scalar context as a child of the current context.""" return _HandlerContext( container=self.container, queue=self.queue, field_name=None, annotations=None, depth=self.depth, whenc...
Derives a scalar context as a child of the current context.
def transit_decrypt_data(self, name, ciphertext, context=None, nonce=None, batch_input=None, mount_point='transit'): """POST /<mount_point>/decrypt/<name> :param name: :type name: :param ciphertext: :type ciphertext: :param context: :type context: :param ...
POST /<mount_point>/decrypt/<name> :param name: :type name: :param ciphertext: :type ciphertext: :param context: :type context: :param nonce: :type nonce: :param batch_input: :type batch_input: :param mount_point: :type mou...
def proximal(self): """Return the ``proximal factory`` of the functional. See Also -------- odl.solvers.nonsmooth.proximal_operators.proximal_l1 : `proximal factory` for the L1-norm. """ if self.pointwise_norm.exponent == 1: return proximal_l1(spa...
Return the ``proximal factory`` of the functional. See Also -------- odl.solvers.nonsmooth.proximal_operators.proximal_l1 : `proximal factory` for the L1-norm.
def find_dupes(paths, exact=False, ignores=None, min_size=0): """High-level code to walk a set of paths and find duplicate groups. :param exact: Whether to compare file contents by hash or by reading chunks in parallel. :type exact: :class:`~__builtins__.bool` :param paths: See :meth...
High-level code to walk a set of paths and find duplicate groups. :param exact: Whether to compare file contents by hash or by reading chunks in parallel. :type exact: :class:`~__builtins__.bool` :param paths: See :meth:`~fastdupes.getPaths` :param ignores: See :meth:`~fastdupes.getP...
def transformer(data, label): """ data preparation """ data = mx.image.imresize(data, IMAGE_SIZE, IMAGE_SIZE) data = mx.nd.transpose(data, (2, 0, 1)) data = data.astype(np.float32) / 128.0 - 1 return data, label
data preparation
def plotOverlaps(vList, w, base="random", k=20): """ Given a list of vectors v, compute the overlap of each with the weight matrix w and plot the overlap curves. """ for i,v in enumerate(vList): if i==0: col = "m" label = "Random vector" else: col="c" label = "" if i==1: ...
Given a list of vectors v, compute the overlap of each with the weight matrix w and plot the overlap curves.
def get_code(self): """ Returns the new ReCaptcha code :return: """ return "" if not self.is_enabled else (""" <script src='//www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" data-sitekey="{SITE_KEY}" data-theme="{THEME}" data-type="{TYPE}" data...
Returns the new ReCaptcha code :return:
def get_beam(self, ra, dec): """ Determine the beam at the given sky location. Parameters ---------- ra, dec : float The sky coordinates at which the beam is determined. Returns ------- beam : :class:`AegeanTools.fits_image.Beam` ...
Determine the beam at the given sky location. Parameters ---------- ra, dec : float The sky coordinates at which the beam is determined. Returns ------- beam : :class:`AegeanTools.fits_image.Beam` A beam object, with a/b/pa in sky coordinates
def set_peer_authenticated(self, peer, restart_stream = False): """Mark the other side of the stream authenticated as `peer` :Parameters: - `peer`: local JID just authenticated - `restart_stream`: `True` when stream should be restarted (needed after SASL authentica...
Mark the other side of the stream authenticated as `peer` :Parameters: - `peer`: local JID just authenticated - `restart_stream`: `True` when stream should be restarted (needed after SASL authentication) :Types: - `peer`: `JID` - `restart_st...
def no_loop_in_parents(self, attr1, attr2): # pylint: disable=too-many-branches """ Find loop in dependencies. For now, used with the following attributes : :(self, parents): host dependencies from host object :(host_name, dependent_host_name):\ ho...
Find loop in dependencies. For now, used with the following attributes : :(self, parents): host dependencies from host object :(host_name, dependent_host_name):\ host dependencies from hostdependencies object :(service_description, dependent_service_description): ...
def add_molfile(self, molfile, data): """Add ``Molfile`` and data to ``SDfile`` object. :param molfile: ``Molfile`` instance. :type molfile: :class:`~ctfile.ctfile.Molfile`. :param dict data: Data associated with ``Molfile`` instance. :return: None. :rtype: :py:obj:`Non...
Add ``Molfile`` and data to ``SDfile`` object. :param molfile: ``Molfile`` instance. :type molfile: :class:`~ctfile.ctfile.Molfile`. :param dict data: Data associated with ``Molfile`` instance. :return: None. :rtype: :py:obj:`None`.
def initialize(log_file, project_dir=None, debug=False): ''' Initializes an AbTools pipeline. Initialization includes printing the AbTools splash, setting up logging, creating the project directory, and logging both the project directory and the log location. Args: log_file (str): Pat...
Initializes an AbTools pipeline. Initialization includes printing the AbTools splash, setting up logging, creating the project directory, and logging both the project directory and the log location. Args: log_file (str): Path to the log file. Required. project_dir (str): Path to the ...
def setup(self): """ *setup the workspace in the requested location* **Return:** - ``None`` """ self.log.info('starting the ``setup`` method') # RECURSIVELY CREATE MISSING DIRECTORIES if not os.path.exists(self.pathToWorkspace): os.makedi...
*setup the workspace in the requested location* **Return:** - ``None``
def add(self, message): """Add a MessageElement to the end of the queue. Strings can be passed and are automatically converted in to item.Text() :param message: An element to add to the message queue. :type message: safe.messaging.Message, MessageElement, str """ ...
Add a MessageElement to the end of the queue. Strings can be passed and are automatically converted in to item.Text() :param message: An element to add to the message queue. :type message: safe.messaging.Message, MessageElement, str
def new_file(self): """ Creates a new editor file. :return: File name. :rtype: unicode """ file = self.get_untitled_file_name() LOGGER.debug("> Creating '{0}' file.".format(file)) self.set_file(file, is_modified=False, is_untitled=True) self.__se...
Creates a new editor file. :return: File name. :rtype: unicode
def get_pointer(self, name, timeout=None): """Get a pointer to a named object in the Octave workspace. Parameters ---------- name: str The name of the object in the Octave workspace. timemout: float, optional. Time to wait for response from Octave...
Get a pointer to a named object in the Octave workspace. Parameters ---------- name: str The name of the object in the Octave workspace. timemout: float, optional. Time to wait for response from Octave (per line). Examples -------- ...
def _assertion(self, matcher, value): """ Perform the actual assertion for the given matcher and value. Override this method to apply a special configuration when performing the assertion. If the assertion fails it should raise an AssertionError. """ # To support the synt...
Perform the actual assertion for the given matcher and value. Override this method to apply a special configuration when performing the assertion. If the assertion fails it should raise an AssertionError.
def read_buffer(io, print_output=False, print_func=None): ''' Reads a file-like buffer object into lines and optionally prints the output. ''' # TODO: research this further - some steps towards handling stdin (ie password requests # from programs that don't notice there's no TTY to accept passwords...
Reads a file-like buffer object into lines and optionally prints the output.
def array_to_encoded(array, dtype=None, encoding='base64'): """ Export a numpy array to a compact serializable dictionary. Parameters ------------ array : array Any numpy array dtype : str or None Optional dtype to encode array encoding : str 'base64' or 'binary' Retu...
Export a numpy array to a compact serializable dictionary. Parameters ------------ array : array Any numpy array dtype : str or None Optional dtype to encode array encoding : str 'base64' or 'binary' Returns --------- encoded : dict Has keys: 'dtype': str...
def _prints_status_screen(self): """ Logic behind the printing (on screen) when generating status file. """ if not PyFunceble.CONFIGURATION["quiet"]: # The quiet mode is not activated. if PyFunceble.CONFIGURATION["less"]: # We have to print less ...
Logic behind the printing (on screen) when generating status file.
def create_objective(self, objective_form): """Creates a new ``Objective``. arg: objective_form (osid.learning.ObjectiveForm): the form for this ``Objective`` return: (osid.learning.Objective) - the new ``Objective`` raise: IllegalState - ``objective_form`` already u...
Creates a new ``Objective``. arg: objective_form (osid.learning.ObjectiveForm): the form for this ``Objective`` return: (osid.learning.Objective) - the new ``Objective`` raise: IllegalState - ``objective_form`` already used in a create transaction rai...
def call_with_search_field(self, name, callback): """ Calls a piece of code with the DOM element that corresponds to a search field of the table. If the callback causes a ``StaleElementReferenceException``, this method will refetch the search fields and try again. Conseq...
Calls a piece of code with the DOM element that corresponds to a search field of the table. If the callback causes a ``StaleElementReferenceException``, this method will refetch the search fields and try again. Consequently **the callback should be designed to be callable multip...
def changeSize(self, fromLayerSize, toLayerSize): """ Changes the size of the connection depending on the size change of either source or destination layer. Should only be called through Network.changeLayerSize(). """ if toLayerSize <= 0 or fromLayerSize <= 0: ...
Changes the size of the connection depending on the size change of either source or destination layer. Should only be called through Network.changeLayerSize().
def play(self): """ Start the playback of the video. The playback loop is run in a separate thread, so this function returns immediately. This allows one to implement things such as event handling loops (e.g. check for key presses) elsewhere. """ ### First do some status checks # Make sure a file is l...
Start the playback of the video. The playback loop is run in a separate thread, so this function returns immediately. This allows one to implement things such as event handling loops (e.g. check for key presses) elsewhere.
def getDeviceList(self, skip_on_access_error=False, skip_on_error=False): """ Return a list of all USB devices currently plugged in, as USBDevice instances. skip_on_error (bool) If True, ignore devices which raise USBError. skip_on_access_error (bool) DE...
Return a list of all USB devices currently plugged in, as USBDevice instances. skip_on_error (bool) If True, ignore devices which raise USBError. skip_on_access_error (bool) DEPRECATED. Alias for skip_on_error.
def predict_expectation(self, X, ancillary_X=None): """ Predict the expectation of lifetimes, :math:`E[T | x]`. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a...
Predict the expectation of lifetimes, :math:`E[T | x]`. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a numpy array, columns must be in the same order as the train...
def paths_list(): """ Gets a folder list of possibly available QEMU binaries on the host. :returns: List of folders where Qemu binaries MAY reside. """ paths = set() try: paths.add(os.getcwd()) except FileNotFoundError: log.warning("The c...
Gets a folder list of possibly available QEMU binaries on the host. :returns: List of folders where Qemu binaries MAY reside.
def generate(): """Generates a random REQID for request""" data_bytes = bytearray(random.getrandbits(8) for i in range(REQID.REQID_SIZE)) return REQID(data_bytes)
Generates a random REQID for request
def redirect_output(fileobj): """Redirect standard out to file.""" old = sys.stdout sys.stdout = fileobj try: yield fileobj finally: sys.stdout = old
Redirect standard out to file.
def Ntubes_Perrys(DBundle, Do, Ntp, angle=30): r'''A rough equation presented in Perry's Handbook [1]_ for estimating the number of tubes in a tube bundle of differing geometries and tube sizes. Claimed accuracy of 24 tubes. Parameters ---------- DBundle : float Outer diameter of tube b...
r'''A rough equation presented in Perry's Handbook [1]_ for estimating the number of tubes in a tube bundle of differing geometries and tube sizes. Claimed accuracy of 24 tubes. Parameters ---------- DBundle : float Outer diameter of tube bundle, [m] Do : int Tube outer diameter...
def _calcCTRBUF(self): """Calculates one block of CTR keystream""" self.ctr_cks = self.encrypt(struct.pack("Q", self.ctr_iv)) # keystream block self.ctr_iv += 1 self.ctr_pos = 0
Calculates one block of CTR keystream
def indices_removed(lst, idxs): '''Returns a copy of lst with each index in idxs removed.''' ret = [item for k,item in enumerate(lst) if k not in idxs] return type(lst)(ret)
Returns a copy of lst with each index in idxs removed.
def resolve_from_dictionary(dictionary, key_list, default_value=None): """Take value from a given key list from dictionary. Example: given dictionary d, key_list = ['foo', 'bar'], it will try to resolve d['foo']['bar']. If not possible, return default_value. :param dictionary: A dictionary to reso...
Take value from a given key list from dictionary. Example: given dictionary d, key_list = ['foo', 'bar'], it will try to resolve d['foo']['bar']. If not possible, return default_value. :param dictionary: A dictionary to resolve. :type dictionary: dict :param key_list: A list of key to resolve...
def admin_required(obj): """ Requires that the user be logged AND be set as a superuser """ decorator = request_passes_test(lambda r, *args, **kwargs: r.user.is_superuser) return wrap_object(obj, decorator)
Requires that the user be logged AND be set as a superuser
def linkify_s_by_module(self, modules): """ Link modules to items :param modules: Modules object (list of all the modules found in the configuration) :type modules: alignak.objects.module.Modules :return: None """ for i in self: links_list = strip_an...
Link modules to items :param modules: Modules object (list of all the modules found in the configuration) :type modules: alignak.objects.module.Modules :return: None
def getstatsdict(self, names, default=numpy.nan): """Get the requested stats as a dictionary. If a requested stat is not an attribute (implying it hasn't been stored), then the default value is returned for that stat. Parameters ---------- names : list of str ...
Get the requested stats as a dictionary. If a requested stat is not an attribute (implying it hasn't been stored), then the default value is returned for that stat. Parameters ---------- names : list of str The names of the stats to get. default : float, opt...
def decode_network_packet(buf): """Decodes a network packet in collectd format. """ off = 0 blen = len(buf) while off < blen: ptype, plen = header.unpack_from(buf, off) if plen > blen - off: raise ValueError("Packet longer than amount of data in buffer") if pty...
Decodes a network packet in collectd format.
def _init_map(self): """stub""" QuestionTextFormRecord._init_map(self) self.my_osid_object_form._my_map['choices'] = \ self._choices_metadata['default_object_values'][0]
stub
def die(msg, errlvl=1, prefix="Error: "): """Convenience function to write short message to stderr and quit.""" stderr("%s%s\n" % (prefix, msg)) sys.exit(errlvl)
Convenience function to write short message to stderr and quit.
def ion_or_solid_comp_object(formula): """ Returns either an ion object or composition object given a formula. Args: formula: String formula. Eg. of ion: NaOH(aq), Na[+]; Eg. of solid: Fe2O3(s), Fe(s), Na2O Returns: Composition/Ion object """ m = re.search(r"\[(...
Returns either an ion object or composition object given a formula. Args: formula: String formula. Eg. of ion: NaOH(aq), Na[+]; Eg. of solid: Fe2O3(s), Fe(s), Na2O Returns: Composition/Ion object
def _take_action(self): """Determines whether to perform the action or not. Checks whether or not an action should be taken. This is determined by the truthy value for the unless parameter. If unless is a callback method, it will be invoked with no parameters in order to determine ...
Determines whether to perform the action or not. Checks whether or not an action should be taken. This is determined by the truthy value for the unless parameter. If unless is a callback method, it will be invoked with no parameters in order to determine whether or not the action should...
def imagetransformer_base_10l_8h_big_uncond_dr03_dan_64_2d(): """big 1d model for unconditional generation on imagenet.""" hparams = image_transformer2d_base() hparams.unconditional = True hparams.hidden_size = 512 hparams.batch_size = 1 hparams.img_len = 64 hparams.num_heads = 8 hparams.filter_size = 2...
big 1d model for unconditional generation on imagenet.
def current_ioloop(io_loop): ''' A context manager that will set the current ioloop to io_loop for the context ''' orig_loop = tornado.ioloop.IOLoop.current() io_loop.make_current() try: yield finally: orig_loop.make_current()
A context manager that will set the current ioloop to io_loop for the context
def is_invalid_date(d): """Return boolean to indicate whether date is invalid, None if valid, False if not a date >>> import datetime >>> is_invalid_date(datetime.datetime(1970, 1, 1, 0, 0, 1)) >>> is_invalid_date(datetime.datetime(1970, 1, 1)) >>> is_invalid_date(datetime.datetime(1969, 12, 31, 23...
Return boolean to indicate whether date is invalid, None if valid, False if not a date >>> import datetime >>> is_invalid_date(datetime.datetime(1970, 1, 1, 0, 0, 1)) >>> is_invalid_date(datetime.datetime(1970, 1, 1)) >>> is_invalid_date(datetime.datetime(1969, 12, 31, 23, 59, 59, 999999)) True ...
def trim_disconnected_blobs(im, inlets): r""" Removes foreground voxels not connected to specified inlets Parameters ---------- im : ND-array The array to be trimmed inlets : ND-array of tuple of indices The locations of the inlets. Any voxels *not* connected directly to ...
r""" Removes foreground voxels not connected to specified inlets Parameters ---------- im : ND-array The array to be trimmed inlets : ND-array of tuple of indices The locations of the inlets. Any voxels *not* connected directly to the inlets will be trimmed Returns ...
def update_athlete(self, city=None, state=None, country=None, sex=None, weight=None): """ Updates the properties of the authorized athlete. http://strava.github.io/api/v3/athlete/#update :param city: City the athlete lives in :param state: State the athlete lives in :pa...
Updates the properties of the authorized athlete. http://strava.github.io/api/v3/athlete/#update :param city: City the athlete lives in :param state: State the athlete lives in :param country: Country the athlete lives in :param sex: Sex of the athlete :param weight: We...
def setup_from_yamlfile(self, yamlfile, output_shell=False): """ Setup from yaml config @param yamlfile: path to yaml config file @type yamlfile: str @param output_shell: write output from this connection to standard output @type output_shel...
Setup from yaml config @param yamlfile: path to yaml config file @type yamlfile: str @param output_shell: write output from this connection to standard output @type output_shell: bool
def to_fasta_str(self, line_width=50, include_coords=True): """ :return: string representation of this sequence object in fasta format """ res = ">" + self.name if include_coords: res += ":" + str(self.start) + "-" + str(self.end) res += " (" + str(self.remaining) + ")" m_str = self....
:return: string representation of this sequence object in fasta format
def fail(self, key, **kwargs): """A helper method that simply raises a `ValidationError`. """ try: msg = self.error_messages[key] except KeyError: class_name = self.__class__.__name__ msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, ...
A helper method that simply raises a `ValidationError`.
def rectify_partial_form_field(base_field, partial_form_fields): """ In base_field reset the attributes label and help_text, since they are overriden by the partial field. Additionally, from the list, or list of lists of partial_form_fields append the bound validator methods to the given base field. ...
In base_field reset the attributes label and help_text, since they are overriden by the partial field. Additionally, from the list, or list of lists of partial_form_fields append the bound validator methods to the given base field.
async def series(self): '''list of series in the collection |force| |coro| Returns ------- list of type :class:`embypy.objects.Series` ''' items = [] for i in await self.items: if i.type == 'Series': items.append(i) elif hasattr(i, 'series'): item...
list of series in the collection |force| |coro| Returns ------- list of type :class:`embypy.objects.Series`
def ret(self, retn_target=None): """ Pop one or many call frames from the stack. This method is called when returning from a function in CFG recovery. :param int retn_target: The target to return to. :return: None """ if retn_target is None: return s...
Pop one or many call frames from the stack. This method is called when returning from a function in CFG recovery. :param int retn_target: The target to return to. :return: None
def _default_transpose_size(input_shape, stride, kernel_shape=None, padding=SAME): """Returns default (maximal) output shape for a transpose convolution. In general, there are multiple possible output shapes that a transpose convolution with a given `input_shape` can map to. This func...
Returns default (maximal) output shape for a transpose convolution. In general, there are multiple possible output shapes that a transpose convolution with a given `input_shape` can map to. This function returns the output shape which evenly divides the stride to produce the input shape in a forward convolutio...
def chmod(path, mode, operator='=', recursive=False): ''' Change file mode bits. When recursively chmodding a directory, executable bits in ``mode`` are ignored when applying to a regular file. E.g. ``chmod(path, mode=0o777, recursive=True)`` would apply ``mode=0o666`` to regular files. Symlin...
Change file mode bits. When recursively chmodding a directory, executable bits in ``mode`` are ignored when applying to a regular file. E.g. ``chmod(path, mode=0o777, recursive=True)`` would apply ``mode=0o666`` to regular files. Symlinks are ignored. Parameters ---------- path : ~pathlib...
def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None): """Constructs a :class:`Request <Request>`, prepares it and...
Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the...
def _return_response_and_status_code(response): """ Output the requests response JSON and status code :rtype : dict :param response: requests response object :return: dict containing the JSON response and/or the status code with error string. """ if response.status_code == requests.codes.ok: ...
Output the requests response JSON and status code :rtype : dict :param response: requests response object :return: dict containing the JSON response and/or the status code with error string.
def drop_database(self, name, force=False): """Drop an Impala database. Parameters ---------- name : string Database name force : bool, default False If False and there are any tables in this database, raises an IntegrityError """ i...
Drop an Impala database. Parameters ---------- name : string Database name force : bool, default False If False and there are any tables in this database, raises an IntegrityError
def peak_signal_to_noise_ratio(true, pred): """Image quality metric based on maximal signal power vs. power of the noise. Args: true: the ground truth image. pred: the predicted image. Returns: peak signal to noise ratio (PSNR) """ return 10.0 * tf.log(1.0 / mean_squared_error(true, pred)) / tf.l...
Image quality metric based on maximal signal power vs. power of the noise. Args: true: the ground truth image. pred: the predicted image. Returns: peak signal to noise ratio (PSNR)
def _handle_usecols(self, columns, usecols_key): """ Sets self._col_indices usecols_key is used if there are string usecols. """ if self.usecols is not None: if callable(self.usecols): col_indices = _evaluate_usecols(self.usecols, usecols_key) ...
Sets self._col_indices usecols_key is used if there are string usecols.
def Run(self, unused_arg): """This kills us with no cleanups.""" logging.debug("Disabling service") win32serviceutil.ChangeServiceConfig( None, config.CONFIG["Nanny.service_name"], startType=win32service.SERVICE_DISABLED) svc_config = QueryService(config.CONFIG["Nanny.service_na...
This kills us with no cleanups.
def get_params_and_defaults(param_list, db): """ Deduce [parameter, default] pairs from simulations available in the db. Args: param_list (list): List of parameters to query for. db (DatabaseManager): Database where to query for defaults. """ return [[p, d] for p, d in db.get_all_values...
Deduce [parameter, default] pairs from simulations available in the db. Args: param_list (list): List of parameters to query for. db (DatabaseManager): Database where to query for defaults.
def find_missing_modules(): """ look for dependency that setuptools cannot check or that are too painful to install with setuptools """ missing_modules = [] for module in MODULES: try: __import__(module[1]) except ImportError: missing_modules.append(modul...
look for dependency that setuptools cannot check or that are too painful to install with setuptools
def to_graphml(graph: BELGraph, path: Union[str, BinaryIO]) -> None: """Write this graph to GraphML XML file using :func:`networkx.write_graphml`. The .graphml file extension is suggested so Cytoscape can recognize it. """ rv = nx.MultiDiGraph() for node in graph: rv.add_node(node.as_bel()...
Write this graph to GraphML XML file using :func:`networkx.write_graphml`. The .graphml file extension is suggested so Cytoscape can recognize it.
def set_image(self, user, image_path): """Sets a custom image for the game. `image_path` should refer to an image file on disk""" _, ext = os.path.splitext(image_path) shutil.copy(image_path, self._custom_image_path(user, ext))
Sets a custom image for the game. `image_path` should refer to an image file on disk
def _render_list(self, items, empty='<pre>&lt;empty&gt;</pre>'): """Renders an HTML list with the specified list of strings. Args: items: the iterable collection of objects to render. empty: what to render if the list is None or empty. """ if not items or len(items) == 0: self._segmen...
Renders an HTML list with the specified list of strings. Args: items: the iterable collection of objects to render. empty: what to render if the list is None or empty.
def directories(self): """ Get a generator that yields all subdirectories in the directory. """ dirlist_p = new_gp_object("CameraList") lib.gp_camera_folder_list_folders(self._cam._cam, self.path.encode(), dirlist_p, self._cam._ctx) for i...
Get a generator that yields all subdirectories in the directory.
def FD(self): """ Set-up for the finite difference solution method """ if self.Verbose: print("Finite Difference Solution Technique") # Used to check for coeff_matrix here, but now doing so in self.bc_check() # called by f1d and f2d at the start # # Define a stress-based qs = q0 ...
Set-up for the finite difference solution method
def acquire(self,blocking=True,timeout=None,shared=False): """Acquire the lock in shared or exclusive mode.""" with self._lock: if shared: self._acquire_shared(blocking,timeout) else: self._acquire_exclusive(blocking,timeout) assert not...
Acquire the lock in shared or exclusive mode.
def _pyproj_inv(self, other, ellipse = 'WGS84'): ''' Perform Pyproj's inv operation on two LatLon objects Returns the initial heading and reverse heading in degrees, and the distance in km. ''' lat1, lon1 = self.lat.decimal_degree, self.lon.decimal_degree lat2, lo...
Perform Pyproj's inv operation on two LatLon objects Returns the initial heading and reverse heading in degrees, and the distance in km.
def perform_request(self, method, url, params=None, body=None): """ Perform the actual request. Retrieve a connection. Pass all the information to it's perform_request method and return the data. :arg method: HTTP method to use :arg url: absolute url (without host) to ta...
Perform the actual request. Retrieve a connection. Pass all the information to it's perform_request method and return the data. :arg method: HTTP method to use :arg url: absolute url (without host) to target :arg params: dictionary of query parameters, will be handed over to the...
def present(name, grant=None, database=None, user=None, host='localhost', grant_option=False, escape=True, revoke_first=False, ssl_option=False, **connection_args): ''' Ensure that the grant is present wi...
Ensure that the grant is present with the specified properties name The name (key) of the grant to add grant The grant priv_type (i.e. select,insert,update OR all privileges) database The database priv_level (i.e. db.tbl OR db.*) user The user to apply the grant to ...
def validate_search_space_content(experiment_config): '''Validate searchspace content, if the searchspace file is not json format or its values does not contain _type and _value which must be specified, it will not be a valid searchspace file''' try: search_space_content = json.load(open...
Validate searchspace content, if the searchspace file is not json format or its values does not contain _type and _value which must be specified, it will not be a valid searchspace file
def add_node(self, node_name, dataframe=False): """ Add a single node to the network. """ if node_name is None: return None return self.add_nodes([node_name], dataframe=dataframe)
Add a single node to the network.
def _set_get_mpls_autobw_template_brief(self, v, load=False): """ Setter method for get_mpls_autobw_template_brief, mapped from YANG variable /brocade_mpls_rpc/get_mpls_autobw_template_brief (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_mpls_autobw_template_b...
Setter method for get_mpls_autobw_template_brief, mapped from YANG variable /brocade_mpls_rpc/get_mpls_autobw_template_brief (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_mpls_autobw_template_brief is considered as a private method. Backends looking to populate t...
def make_timestamp(el_time): """ Generate an hour-minutes-seconds timestamp from an interval in seconds. Assumes numeric input of a time interval in seconds. Converts this interval to a string of the format "#h #m #s", indicating the number of hours, minutes, and seconds in the interval. Intervals gr...
Generate an hour-minutes-seconds timestamp from an interval in seconds. Assumes numeric input of a time interval in seconds. Converts this interval to a string of the format "#h #m #s", indicating the number of hours, minutes, and seconds in the interval. Intervals greater than 24h are unproblematic....
def _flat_columns_in_table(self, table): """An iterator over the flattened columns for a given schema and table. Resolves child columns as having the name "parent.child". """ for col in self._get_dbt_columns_from_bq_table(table): flattened = col.flatten() for subc...
An iterator over the flattened columns for a given schema and table. Resolves child columns as having the name "parent.child".
def compare(args): """ %prog compare NA12878_array_hg38.bed *.seg Compare cnv output to known ground truths. """ p = OptionParser(compare.__doc__) p.set_cpus() opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) truths = args[0] cnvoutputs = ...
%prog compare NA12878_array_hg38.bed *.seg Compare cnv output to known ground truths.