code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def find_classes(self, name=".*", no_external=False): """ Find classes by name, using regular expression This method will return all ClassAnalysis Object that match the name of the class. :param name: regular expression for class name (default ".*") :param no_external: R...
Find classes by name, using regular expression This method will return all ClassAnalysis Object that match the name of the class. :param name: regular expression for class name (default ".*") :param no_external: Remove external classes from the output (default False) :rtype: gen...
def _ss_matrices(self,beta): """ Creates the state space matrices required Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- T, Z, R, Q : np.array State space matrices use...
Creates the state space matrices required Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- T, Z, R, Q : np.array State space matrices used in KFS algorithm
def linearRegressionAnalysis(series): """ Returns factor and offset of linear regression function by least squares method. """ n = safeLen(series) sumI = sum([i for i, v in enumerate(series) if v is not None]) sumV = sum([v for i, v in enumerate(series) if v is not None]) sumII = sum([i...
Returns factor and offset of linear regression function by least squares method.
def select_elements(self, json_string, expr): """ Return list of elements from _json_string_, matching [ http://jsonselect.org/ | JSONSelect] expression. *DEPRECATED* JSON Select query language is outdated and not supported any more. Use other keywords of this library to query JSON. ...
Return list of elements from _json_string_, matching [ http://jsonselect.org/ | JSONSelect] expression. *DEPRECATED* JSON Select query language is outdated and not supported any more. Use other keywords of this library to query JSON. *Args:*\n _json_string_ - JSON string;\n _ex...
def to_dict(dictish): """ Given something that closely resembles a dictionary, we attempt to coerce it into a propery dictionary. """ if hasattr(dictish, 'iterkeys'): m = dictish.iterkeys elif hasattr(dictish, 'keys'): m = dictish.keys else: raise ValueError(dictish) ...
Given something that closely resembles a dictionary, we attempt to coerce it into a propery dictionary.
def depth_soil_density(self, value=None): """Corresponds to IDD Field `depth_soil_density` Args: value (float): value for IDD Field `depth_soil_density` Unit: kg/m3 if `value` is None it will not be checked against the specification and is ass...
Corresponds to IDD Field `depth_soil_density` Args: value (float): value for IDD Field `depth_soil_density` Unit: kg/m3 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ...
def multi_char_literal(chars): """Emulates character integer literals in C. Given a string "abc", returns the value of the C single-quoted literal 'abc'. """ num = 0 for index, char in enumerate(chars): shift = (len(chars) - index - 1) * 8 num |= ord(char) << shift return num
Emulates character integer literals in C. Given a string "abc", returns the value of the C single-quoted literal 'abc'.
def processIqRegistry(self, entity): """ :type entity: IqProtocolEntity """ if entity.getTag() == "iq": iq_id = entity.getId() if iq_id in self.iqRegistry: originalIq, successClbk, errorClbk = self.iqRegistry[iq_id] del self.iqRegis...
:type entity: IqProtocolEntity
def get_response(cmd, conn): """Return a response""" resp = conn.socket().makefile('rb', -1) resp_dict = dict( code=0, message='', isspam=False, score=0.0, basescore=0.0, report=[], symbols=[], headers={}, ) if cmd == 'TELL': r...
Return a response
def parker_weighting(ray_trafo, q=0.25): """Create parker weighting for a `RayTransform`. Parker weighting is a weighting function that ensures that oversampled fan/cone beam data are weighted such that each line has unit weight. It is useful in analytic reconstruction methods such as FBP to give a mor...
Create parker weighting for a `RayTransform`. Parker weighting is a weighting function that ensures that oversampled fan/cone beam data are weighted such that each line has unit weight. It is useful in analytic reconstruction methods such as FBP to give a more accurate result and can improve convergenc...
def _parse_error(self, error): """ Parses a single GLSL error and extracts the linenr and description Other GLIR implementations may omit this. """ error = str(error) # Nvidia # 0(7): error C1008: undefined variable "MV" m = re.match(r'(\d+)\((\d+)\)\s*:\s(.*)', e...
Parses a single GLSL error and extracts the linenr and description Other GLIR implementations may omit this.
def main() -> None: """Main function of this script""" # Make sure we have access to self if 'self' not in globals(): print("Run 'set locals_in_py true' and then rerun this script") return # Make sure the user passed in an output file if len(sys.argv) != 2: print("Usage: {}...
Main function of this script
def off(self, evnt, func): ''' Remove a previously registered event handler function. Example: base.off( 'foo', onFooFunc ) ''' funcs = self._syn_funcs.get(evnt) if funcs is None: return try: funcs.remove(func) excep...
Remove a previously registered event handler function. Example: base.off( 'foo', onFooFunc )
def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: * 2017-07-01: :mod:`v2017_07_01.models<azure.mgmt.containerservice.v2017_07_01.models>` * 2018-03-31: :mod:`v2018_03_31.models<azure.mgmt.containerservice.v2018_03_31.models>` * 2018-08-01-p...
Module depends on the API version: * 2017-07-01: :mod:`v2017_07_01.models<azure.mgmt.containerservice.v2017_07_01.models>` * 2018-03-31: :mod:`v2018_03_31.models<azure.mgmt.containerservice.v2018_03_31.models>` * 2018-08-01-preview: :mod:`v2018_08_01_preview.models<azure.mgmt.container...
def read_all(self): """Read all remaining data in the packet. (Subsequent read() will return errors.) """ result = self._data[self._position:] self._position = None # ensure no subsequent read() return result
Read all remaining data in the packet. (Subsequent read() will return errors.)
def compute_route_stats_base( trip_stats_subset: DataFrame, headway_start_time: str = "07:00:00", headway_end_time: str = "19:00:00", *, split_directions: bool = False, ) -> DataFrame: """ Compute stats for the given subset of trips stats. Parameters ---------- trip_stats_subset...
Compute stats for the given subset of trips stats. Parameters ---------- trip_stats_subset : DataFrame Subset of the output of :func:`.trips.compute_trip_stats` split_directions : boolean If ``True``, then separate the stats by trip direction (0 or 1); otherwise aggregate trips ...
def decode_escapes(s): '''Unescape libconfig string literals''' def decode_match(match): return codecs.decode(match.group(0), 'unicode-escape') return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
Unescape libconfig string literals
def calculate_check_interval( self, max_interval, ewma_factor, max_days=None, max_updates=None, ewma=0, ewma_ts=None, add_partial=None ): '''Calculate interval for checks as average time (ewma) between updates for specified period.''' if not add_partial: posts_base = self.posts.only('date_modified')....
Calculate interval for checks as average time (ewma) between updates for specified period.
def create(self, name, *args, **kwargs): """ Need to wrap the default call to handle exceptions. """ try: return super(ImageMemberManager, self).create(name, *args, **kwargs) except Exception as e: if e.http_status == 403: raise exc.Unshara...
Need to wrap the default call to handle exceptions.
def create_thing(self, lid): """Create a new Thing with a local id (lid). Returns a [Thing](Thing.m.html#IoticAgent.IOT.Thing.Thing) object if successful or if the Thing already exists Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing...
Create a new Thing with a local id (lid). Returns a [Thing](Thing.m.html#IoticAgent.IOT.Thing.Thing) object if successful or if the Thing already exists Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects...
def from_text(text): """Convert the text format message into a message object. @param text: The text format message. @type text: string @raises UnknownHeaderField: @raises dns.exception.SyntaxError: @rtype: dns.message.Message object""" # 'text' can also be a file, but we don't publish tha...
Convert the text format message into a message object. @param text: The text format message. @type text: string @raises UnknownHeaderField: @raises dns.exception.SyntaxError: @rtype: dns.message.Message object
def check_bom(file): """Determines file codec from from its BOM record. If file starts with BOM record encoded with UTF-8 or UTF-16(BE/LE) then corresponding encoding name is returned, otherwise None is returned. In both cases file current position is set to after-BOM bytes. The file must be open i...
Determines file codec from from its BOM record. If file starts with BOM record encoded with UTF-8 or UTF-16(BE/LE) then corresponding encoding name is returned, otherwise None is returned. In both cases file current position is set to after-BOM bytes. The file must be open in binary mode and positioned...
def valid(): ''' List valid entries in mine configuration. CLI Example: .. code-block:: bash salt '*' mine.valid ''' m_data = __salt__['config.merge']('mine_functions', {}) # If we don't have any mine functions configured, then we should just bail out if not m_data: re...
List valid entries in mine configuration. CLI Example: .. code-block:: bash salt '*' mine.valid
def commits(self): """ Returns the current DataFrame joined with the commits DataFrame. It just returns the last commit in a reference (aka the current state). >>> commits_df = refs_df.commits If you want all commits from the references, use the `all_reference_commits` method, ...
Returns the current DataFrame joined with the commits DataFrame. It just returns the last commit in a reference (aka the current state). >>> commits_df = refs_df.commits If you want all commits from the references, use the `all_reference_commits` method, but take into account that gett...
def make_matepairs(fastafile): """ Assumes the mates are adjacent sequence records """ assert op.exists(fastafile) matefile = fastafile.rsplit(".", 1)[0] + ".mates" if op.exists(matefile): logging.debug("matepairs file `{0}` found".format(matefile)) else: logging.debug("pars...
Assumes the mates are adjacent sequence records
def elapsed_time(self): """ Return elapsed time as min:sec:ms. The .split separates out the millisecond """ td = (datetime.datetime.now() - self.start_time) sec = td.seconds ms = int(td.microseconds / 1000) return '{:02}:{:02}.{:03}'.format(sec % 3600 //...
Return elapsed time as min:sec:ms. The .split separates out the millisecond
def read(self, size): """Read bytes from the stream and block until sample rate is achieved. Args: size: number of bytes to read from the stream. """ now = time.time() missing_dt = self._sleep_until - now if missing_dt > 0: time.sleep(missing_dt) ...
Read bytes from the stream and block until sample rate is achieved. Args: size: number of bytes to read from the stream.
def url_replace_param(url, name, value): """ Replace a GET parameter in an URL """ url_components = urlparse(force_str(url)) query_params = parse_qs(url_components.query) query_params[name] = value query = urlencode(query_params, doseq=True) return force_text( urlunparse( ...
Replace a GET parameter in an URL
def run_per_switch_cmds(self, switch_cmds): """Applies cmds to appropriate switches This takes in a switch->cmds mapping and runs only the set of cmds specified for a switch on that switch. This helper is used for applying/removing ACLs to/from interfaces as this config will vary ...
Applies cmds to appropriate switches This takes in a switch->cmds mapping and runs only the set of cmds specified for a switch on that switch. This helper is used for applying/removing ACLs to/from interfaces as this config will vary from switch to switch.
def _send_size(self): " Report terminal size to server. " rows, cols = _get_size(sys.stdout.fileno()) self._send_packet({ 'cmd': 'size', 'data': [rows, cols] })
Report terminal size to server.
def getReffs(self, textId, level=1, subreference=None): """ Retrieve the siblings of a textual node :param textId: CtsTextMetadata Identifier :type textId: str :param level: Depth for retrieval :type level: int :param subreference: CapitainsCtsPassage Reference :...
Retrieve the siblings of a textual node :param textId: CtsTextMetadata Identifier :type textId: str :param level: Depth for retrieval :type level: int :param subreference: CapitainsCtsPassage Reference :type subreference: str :return: List of references :...
def integer_ceil(a, b): '''Return the ceil integer of a div b.''' quanta, mod = divmod(a, b) if mod: quanta += 1 return quanta
Return the ceil integer of a div b.
def _help_basic(self): """ Help for Workbench Basics """ help = '%sWorkbench: Getting started...' % (color.Yellow) help += '\n%sStore a sample into Workbench:' % (color.Green) help += '\n\t%s$ workbench.store_sample(raw_bytes, filename, type_tag)' % (color.LightBlue) help += '\...
Help for Workbench Basics
def _republish_dropped_message(self, reason): """Republish the original message that was received it is being dropped by the consumer. This for internal use and should not be extended or used directly. :param str reason: The reason the message was dropped """ self.logg...
Republish the original message that was received it is being dropped by the consumer. This for internal use and should not be extended or used directly. :param str reason: The reason the message was dropped
def convert_episode_to_batch_major(episode): """Converts an episode to have the batch dimension in the major (first) dimension. """ episode_batch = {} for key in episode.keys(): val = np.array(episode[key]).copy() # make inputs batch-major instead of time-major episode_batch[...
Converts an episode to have the batch dimension in the major (first) dimension.
def rotate_crop(centerij, sz, angle, img=None, mode='constant', **kwargs): """ rotate and crop if no img, then return crop function :param centerij: :param sz: :param angle: :param img: [h,w,d] :param mode: padding option :return: cropped image or function """ # crop enough s...
rotate and crop if no img, then return crop function :param centerij: :param sz: :param angle: :param img: [h,w,d] :param mode: padding option :return: cropped image or function
def lookup_string(self, keysym): """Return a string corresponding to KEYSYM, or None if no reasonable translation is found. """ s = self.keysym_translations.get(keysym) if s is not None: return s import Xlib.XK return Xlib.XK.keysym_to_string(keysym)
Return a string corresponding to KEYSYM, or None if no reasonable translation is found.
def set_executing(on: bool): """ Toggle whether or not the current thread is executing a step file. This will only apply when the current thread is a CauldronThread. This function has no effect when run on a Main thread. :param on: Whether or not the thread should be annotated as executing ...
Toggle whether or not the current thread is executing a step file. This will only apply when the current thread is a CauldronThread. This function has no effect when run on a Main thread. :param on: Whether or not the thread should be annotated as executing a step file.
def create(cls, *args, **kwargs) -> 'Entity': """Create a new record in the repository. Also performs unique validations before creating the entity :param args: positional arguments for the entity :param kwargs: keyword arguments for the entity """ logger.debug( ...
Create a new record in the repository. Also performs unique validations before creating the entity :param args: positional arguments for the entity :param kwargs: keyword arguments for the entity
def get_config(self, budget): """ Function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled returns: config should return a valid configuration ...
Function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled returns: config should return a valid configuration
def find_program(basename): """ Find program in PATH and return absolute path Try adding .exe or .bat to basename on Windows platforms (return None if not found) """ names = [basename] if os.name == 'nt': # Windows platforms extensions = ('.exe', '.bat', '.cmd') ...
Find program in PATH and return absolute path Try adding .exe or .bat to basename on Windows platforms (return None if not found)
def _make_subvolume(self, **args): """Creates a subvolume, adds it to this class and returns it.""" from imagemounter.volume import Volume v = Volume(disk=self.disk, parent=self.parent, volume_detector=self.volume_detector, **args) # vstype is not passed d...
Creates a subvolume, adds it to this class and returns it.
def resolve(cls, all_known_repos, name): """We require the list of all remote repo paths to be passed in to this because otherwise we would need to import the spec assembler in this module, which would give us circular imports.""" match = None for repo in all_known_repos: ...
We require the list of all remote repo paths to be passed in to this because otherwise we would need to import the spec assembler in this module, which would give us circular imports.
def finish_displayhook(self): """Finish up all displayhook activities.""" io.stdout.write(self.shell.separate_out2) io.stdout.flush()
Finish up all displayhook activities.
def get_cache_mode(service, pool_name): """ Find the current caching mode of the pool_name given. :param service: six.string_types. The Ceph user name to run the command under :param pool_name: six.string_types :return: int or None """ validator(value=service, valid_type=six.string_types) ...
Find the current caching mode of the pool_name given. :param service: six.string_types. The Ceph user name to run the command under :param pool_name: six.string_types :return: int or None
def mnist_tutorial_cw(train_start=0, train_end=60000, test_start=0, test_end=10000, viz_enabled=VIZ_ENABLED, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, source_samples=SOURCE_SAMPLES, learning_rate=LEARNING_RATE, ...
MNIST tutorial for Carlini and Wagner's attack :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param viz_enabled: (boolean) activate plots of adversa...
def create(gandi, resource, flags, algorithm, public_key): """Create DNSSEC key.""" result = gandi.dnssec.create(resource, flags, algorithm, public_key) return result
Create DNSSEC key.
def _get_front_idxs_from_id(fronts, id): """ Return a list of tuples of the form (frequency_idx, sample_idx), corresponding to all the indexes of the given front. """ if id == -1: # This is the only special case. # -1 is the index of the catch-all final column offset front. f...
Return a list of tuples of the form (frequency_idx, sample_idx), corresponding to all the indexes of the given front.
def main(self): """this main routine sets up the signal handlers, the source and destination crashstorage systems at the theaded task manager. That starts a flock of threads that are ready to shepherd crashes from the source to the destination.""" self._setup_task_manager() ...
this main routine sets up the signal handlers, the source and destination crashstorage systems at the theaded task manager. That starts a flock of threads that are ready to shepherd crashes from the source to the destination.
def p_bound_segments(self, p): """bound_segments : bound_segment FORWARD_SLASH bound_segments | bound_segment""" p[0] = p[1] if len(p) > 2: p[0].extend(p[3])
bound_segments : bound_segment FORWARD_SLASH bound_segments | bound_segment
def complete_token_filtered(aliases, prefix, expanded): """Find all starting matches in dictionary *aliases* that start with *prefix*, but filter out any matches already in *expanded*""" complete_ary = aliases.keys() return [cmd for cmd in complete_ary if cmd.startswith(prefix)]
Find all starting matches in dictionary *aliases* that start with *prefix*, but filter out any matches already in *expanded*
def patch(self, request): """ Update the status of a video. """ attrs = ('edx_video_id', 'status') missing = [attr for attr in attrs if attr not in request.data] if missing: return Response( status=status.HTTP_400_BAD_REQUEST, d...
Update the status of a video.
def _validate_edata(self, edata): """Validate edata argument of raise_exception_if method.""" # pylint: disable=R0916 if edata is None: return True if not (isinstance(edata, dict) or _isiterable(edata)): return False edata = [edata] if isinstance(edata, di...
Validate edata argument of raise_exception_if method.
def major(self, major: int) -> None: """ param major Major version number property. Must be a non-negative integer. """ self.filter_negatives(major) self._major = major
param major Major version number property. Must be a non-negative integer.
def configure_extensions(app): """ Configure application extensions """ db.init_app(app) app.wsgi_app = ProxyFix(app.wsgi_app) assets.init_app(app) for asset in bundles: for (name, bundle) in asset.iteritems(): assets.register(name, bundle) login_manager.login_view = 'fro...
Configure application extensions
def _update_marshallers(self): """ Update the full marshaller list and other data structures. Makes a full list of both builtin and user marshallers and rebuilds internal data structures used for looking up which marshaller to use for reading/writing Python objects to/from file....
Update the full marshaller list and other data structures. Makes a full list of both builtin and user marshallers and rebuilds internal data structures used for looking up which marshaller to use for reading/writing Python objects to/from file. Also checks for whether the requi...
def get_json(self, layer, where="1 = 1", fields=[], count_only=False, srid='4326'): """ Gets the JSON file from ArcGIS """ params = { 'where': where, 'outFields': ", ".join(fields), 'returnGeometry': True, 'outSR': srid, ...
Gets the JSON file from ArcGIS
def tag_arxiv(line): """Tag arxiv report numbers We handle arXiv in 2 ways: * starting with arXiv:1022.1111 * this format exactly 9999.9999 We also format the output to the standard arxiv notation: * arXiv:2007.12.1111 * arXiv:2007.12.1111v2 """ def tagger(match): groups = m...
Tag arxiv report numbers We handle arXiv in 2 ways: * starting with arXiv:1022.1111 * this format exactly 9999.9999 We also format the output to the standard arxiv notation: * arXiv:2007.12.1111 * arXiv:2007.12.1111v2
def get_datasets_in_nodes(): """ Get the node associated with each dataset. Some datasets will have an ambiguous node since they exists in more than one node. """ data_dir = os.path.join(scriptdir, "..", "usgs", "data") cwic = map(lambda d: d["datasetName"], api.datasets(None, CWIC_LSI_EXP...
Get the node associated with each dataset. Some datasets will have an ambiguous node since they exists in more than one node.
def _analyze(self): """ Apply the filter to the log file """ for parsed_line in self.parsed_lines: if 'ip' in parsed_line: if parsed_line['ip'] in self.filter['ips']: self.noisy_logs.append(parsed_line) else: ...
Apply the filter to the log file
def contains_pt(self, pt): """Containment test.""" obj1, obj2 = self.objects return obj2.contains_pt(pt) and np.logical_not(obj1.contains_pt(pt))
Containment test.
def setattrs_from_paxos(self, paxos): """ Registers changes of attribute value on Paxos instance. """ changes = {} for name in self.paxos_variables: paxos_value = getattr(paxos, name) if paxos_value != getattr(self, name, None): self.print_...
Registers changes of attribute value on Paxos instance.
def _iter_step_func_decorators(self): """Find functions with step decorator in parsed file.""" for node in self.py_tree.find_all('def'): for decorator in node.decorators: if decorator.name.value == 'step': yield node, decorator break
Find functions with step decorator in parsed file.
def decode_bytes(byt, enc='utf-8'): """Given a string or bytes input, return a string. Args: bytes - bytes or string enc - encoding to use for decoding the byte string. """ try: strg = byt.decode(enc) except UnicodeDecodeError as err: strg = "Unable to decode mess...
Given a string or bytes input, return a string. Args: bytes - bytes or string enc - encoding to use for decoding the byte string.
def tab_complete(self): """ If there is a single option available one tab completes the option. """ opts = self._complete_options() if len(opts) == 1: self.set_current_text(opts[0] + os.sep) self.hide_completer()
If there is a single option available one tab completes the option.
def _advapi32_verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding=False): """ Verifies an RSA, DSA or ECDSA signature via CryptoAPI :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte...
Verifies an RSA, DSA or ECDSA signature via CryptoAPI :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :par...
def figure(path,display=False,close=True): """ Can be used with the **with** statement:: import litus import numpy as np import matplotlib.pylab as plt x = np.arange(0,10,0.1) with litus.figure("some_test.png") as f: plt.plot(x,np.cos(x)) # plots to a firs...
Can be used with the **with** statement:: import litus import numpy as np import matplotlib.pylab as plt x = np.arange(0,10,0.1) with litus.figure("some_test.png") as f: plt.plot(x,np.cos(x)) # plots to a first plot with litus.figure("some_other_test.p...
def secure(func_or_obj, check_permissions_for_obj=None): """ This method secures a method or class depending on invocation. To decorate a method use one argument: @secure(<check_permissions_method>) To secure a class, invoke with two arguments: secure(<obj instance>, <check_permissions...
This method secures a method or class depending on invocation. To decorate a method use one argument: @secure(<check_permissions_method>) To secure a class, invoke with two arguments: secure(<obj instance>, <check_permissions_method>)
def general_settings(): """general settings """ import matplotlib as mpl import matplotlib.pyplot as plt mpl.rcParams['font.size'] = 7.0 mpl.rcParams['axes.labelsize'] = 7.0 mpl.rcParams['xtick.labelsize'] = 7.0 mpl.rcParams['ytick.labelsize'] = 7.0 mpl.rcParams["lines.linewidth"] = ...
general settings
def _commit_change(alias_table, export_path=None, post_commit=True): """ Record changes to the alias table. Also write new alias config hash and collided alias, if any. Args: alias_table: The alias table to commit. export_path: The path to export the aliases to. Default: GLOBAL_ALIAS_PA...
Record changes to the alias table. Also write new alias config hash and collided alias, if any. Args: alias_table: The alias table to commit. export_path: The path to export the aliases to. Default: GLOBAL_ALIAS_PATH. post_commit: True if we want to perform some extra actions after writ...
def create_token(self, user_id, permission_obj): """ 'permission_obj' param should be a string. e.g. '[{"access":"d_u_list","oid":{"id":"1576946496","type":"Domain"}}]' http://docs.exosite.com/portals/#add-user-permission """ headers = { 'User-Agent': s...
'permission_obj' param should be a string. e.g. '[{"access":"d_u_list","oid":{"id":"1576946496","type":"Domain"}}]' http://docs.exosite.com/portals/#add-user-permission
def has_pfn(self, url, site=None): """ Wrapper of the pegasus hasPFN function, that allows it to be called outside of specific pegasus functions. """ curr_pfn = dax.PFN(url, site) return self.hasPFN(curr_pfn)
Wrapper of the pegasus hasPFN function, that allows it to be called outside of specific pegasus functions.
def simple_value(self, elt, ps, mixed=False): '''Get the value of the simple content of this element. Parameters: elt -- the DOM element being parsed ps -- the ParsedSoap object. mixed -- ignore element content, optional text node ''' if not _valid_enc...
Get the value of the simple content of this element. Parameters: elt -- the DOM element being parsed ps -- the ParsedSoap object. mixed -- ignore element content, optional text node
def add_one(self, url: str, url_properties: Optional[URLProperties]=None, url_data: Optional[URLData]=None): '''Add a single URL to the table. Args: url: The URL to be added url_properties: Additional values to be saved url_data: Addit...
Add a single URL to the table. Args: url: The URL to be added url_properties: Additional values to be saved url_data: Additional data to be saved
def plot_prob_profit_trade(round_trips, ax=None): """ Plots a probability distribution for the event of making a profitable trade. Parameters ---------- round_trips : pd.DataFrame DataFrame with one row per round trip trade. - See full explanation in round_trips.extract_round_tr...
Plots a probability distribution for the event of making a profitable trade. Parameters ---------- round_trips : pd.DataFrame DataFrame with one row per round trip trade. - See full explanation in round_trips.extract_round_trips ax : matplotlib.Axes, optional Axes upon which...
def is_prev_free(self): """ Returns a concrete state of the flag indicating whether the previous chunk is free or not. Issues a warning if that flag is symbolic and has multiple solutions, and then assumes that the previous chunk is free. :returns: True if the previous chunk is free; Fa...
Returns a concrete state of the flag indicating whether the previous chunk is free or not. Issues a warning if that flag is symbolic and has multiple solutions, and then assumes that the previous chunk is free. :returns: True if the previous chunk is free; False otherwise
def transform(self, data, test=False): '''Transform image data to latent space. Parameters ---------- data : array-like shape (n_images, image_width, image_height, n_colors) Input numpy array of images. test [optional] : bool ...
Transform image data to latent space. Parameters ---------- data : array-like shape (n_images, image_width, image_height, n_colors) Input numpy array of images. test [optional] : bool Controls the test boolean for batch normaliz...
def sort_values( self, by, axis=0, ascending=True, inplace=False, kind="quicksort", na_position="last", ): """Sorts by a column/row or list of columns/rows. Args: by: A list of labels for the axis to sort over. ...
Sorts by a column/row or list of columns/rows. Args: by: A list of labels for the axis to sort over. axis: The axis to sort. ascending: Sort in ascending or descending order. inplace: If true, do the operation inplace. kind: How to sort. ...
def parse(self, args): """ :param args: arguments :type args: None or string or list of string :return: formatted arguments if specified else ``self.default_args`` :rtype: list of string """ if args is None: args = self._default_args if isinsta...
:param args: arguments :type args: None or string or list of string :return: formatted arguments if specified else ``self.default_args`` :rtype: list of string
def escape(self, text): """Replace characters with their character references. Replace characters by their named entity references. Non-ASCII characters, if they do not have a named entity reference, are replaced by numerical character references. The return value is guaranteed...
Replace characters with their character references. Replace characters by their named entity references. Non-ASCII characters, if they do not have a named entity reference, are replaced by numerical character references. The return value is guaranteed to be ASCII.
def close_session(self): """ Close tensorflow session. Exposes for memory management. """ with self._graph.as_default(): self._sess.close() self._sess = None
Close tensorflow session. Exposes for memory management.
def targetwords(self, index, targetwords, alignment): """Return the aligned targetwords for a specified index in the source words""" return [ targetwords[x] for x in alignment[index] ]
Return the aligned targetwords for a specified index in the source words
def deploy(self): ''' Creates a link at the original path of this target ''' if not os.path.exists(self.path): makedirs(self.path) link(self.vault_path, self.real_path)
Creates a link at the original path of this target
def intersection_box(box1, box2): """ Finds an intersection box that is common to both given boxes. :param box1: Box object 1 :param box2: Box object 2 :return: None if there is no intersection otherwise the new Box """ b1_x2, b1_y2 = box1.bottom_right() ...
Finds an intersection box that is common to both given boxes. :param box1: Box object 1 :param box2: Box object 2 :return: None if there is no intersection otherwise the new Box
def ensure_parent_dir_exists(file_path): """Ensures that the parent directory exists""" parent = os.path.dirname(file_path) if parent: os.makedirs(parent, exist_ok=True)
Ensures that the parent directory exists
def ping_entry(self, entry): """ Ping an entry to a directory. """ entry_url = '%s%s' % (self.ressources.site_url, entry.get_absolute_url()) categories = '|'.join([c.title for c in entry.categories.all()]) try: reply = self.serve...
Ping an entry to a directory.
def main() -> None: """ Command-line handler for the ``pause_process_by_disk_space`` tool. Use the ``--help`` option for help. """ parser = ArgumentParser( description="Pauses and resumes a process by disk space; LINUX ONLY." ) parser.add_argument( "process_id", type=int, ...
Command-line handler for the ``pause_process_by_disk_space`` tool. Use the ``--help`` option for help.
def get_auth_token(self, user): """ Returns the user's authentication token. """ data = [str(user.id), self.security.hashing_context.hash(encode_string(user._password))] return self.security.remember_token_serializer.dumps(data)
Returns the user's authentication token.
def register_actions(self, shortcut_manager): """Register callback methods for triggered actions :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings between shortcuts and actions. """ self.add_callback_to_shortcut_man...
Register callback methods for triggered actions :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings between shortcuts and actions.
def decode(self, data, password): """Decode existing GNTP Registration message :param string data: Message to decode """ self.raw = gntp.shim.u(data) parts = self.raw.split('\r\n\r\n') self.info = self._parse_info(self.raw) self._validate_password(password) self.headers = self._parse_dict(parts[0]) ...
Decode existing GNTP Registration message :param string data: Message to decode
def _get_audio_object_type(self, r): """Raises BitReaderError""" audioObjectType = r.bits(5) if audioObjectType == 31: audioObjectTypeExt = r.bits(6) audioObjectType = 32 + audioObjectTypeExt return audioObjectType
Raises BitReaderError
def create(self, customer_name, street, city, region, postal_code, iso_country, friendly_name=values.unset, emergency_enabled=values.unset, auto_correct_address=values.unset): """ Create a new AddressInstance :param unicode customer_name: The name to associate with...
Create a new AddressInstance :param unicode customer_name: The name to associate with the new address :param unicode street: The number and street address of the new address :param unicode city: The city of the new address :param unicode region: The state or region of the new address ...
def get_all_network_interfaces(self, filters=None): """ Retrieve all of the Elastic Network Interfaces (ENI's) associated with your account. :type filters: dict :param filters: Optional filters that can be used to limit the results returned. Filters are ...
Retrieve all of the Elastic Network Interfaces (ENI's) associated with your account. :type filters: dict :param filters: Optional filters that can be used to limit the results returned. Filters are provided in the form of a dictionary consisting ...
def iter(self, columnnames, order='', sort=True): """Return a tableiter object. :class:`tableiter` lets one iterate over a table by returning in each iteration step a reference table containing equal values for the given columns. By default a sort is done on the given columns to...
Return a tableiter object. :class:`tableiter` lets one iterate over a table by returning in each iteration step a reference table containing equal values for the given columns. By default a sort is done on the given columns to get the correct iteration order. `order` ...
def list_records_for_build_config_set(id, page_size=200, page_index=0, sort="", q=""): """ Get a list of BuildRecords for the given BuildConfigSetRecord """ data = list_records_for_build_config_set_raw(id, page_size, page_index, sort, q) if data: return utils.format_json_list(data)
Get a list of BuildRecords for the given BuildConfigSetRecord
def install_agent(agent_key, agent_version=1): ''' Function downloads Server Density installation agent, and installs sd-agent with agent_key. Optionally the agent_version would select the series to use (defaults on the v1 one). CLI Example: .. code-block:: bash salt '*' serverdensity...
Function downloads Server Density installation agent, and installs sd-agent with agent_key. Optionally the agent_version would select the series to use (defaults on the v1 one). CLI Example: .. code-block:: bash salt '*' serverdensity_device.install_agent c2bbdd6689ff46282bdaa07555641498 ...
def police_priority_map_conform_map_pri7_conform(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer") name_key = ET.SubElement(police_priority_map...
Auto Generated Code
def human2bytes(s): """ >>> human2bytes('1M') 1048576 >>> human2bytes('1G') 1073741824 """ symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') letter = s[-1:].strip().upper() num = s[:-1] assert num.isdigit() and letter in symbols, s num = float(num) prefix = {symbols...
>>> human2bytes('1M') 1048576 >>> human2bytes('1G') 1073741824
def run(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, plugins=None, debug=None, **kargs): """ Start a server instance. This method blocks until the server terminates. :param app: WSGI applica...
Start a server instance. This method blocks until the server terminates. :param app: WSGI application or target string supported by :func:`load_app`. (default: :func:`default_app`) :param server: Server adapter to use. See :data:`server_names` keys for valid names or pass ...
def turn_physical_on(self,ro=None,vo=None): """ NAME: turn_physical_on PURPOSE: turn on automatic returning of outputs in physical units INPUT: ro= reference distance (kpc) vo= reference velocity (km/s) OUTPUT: (none) ...
NAME: turn_physical_on PURPOSE: turn on automatic returning of outputs in physical units INPUT: ro= reference distance (kpc) vo= reference velocity (km/s) OUTPUT: (none) HISTORY: 2016-01-19 - Written - Bovy (UofT)