positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def _CalculateStorageCounters(self, storage_reader): """Calculates the counters of the entire storage. Args: storage_reader (StorageReader): storage reader. Returns: dict[str,collections.Counter]: storage counters. """ analysis_reports_counter = collections.Counter() analysis_repor...
Calculates the counters of the entire storage. Args: storage_reader (StorageReader): storage reader. Returns: dict[str,collections.Counter]: storage counters.
def _exec(cmd): """Execute command using subprocess.Popen :param cmd: :return: (code, stdout, stderr) """ process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE) # pylint: disable=unexpected-keyword-arg (stdout, stderr) = process.communica...
Execute command using subprocess.Popen :param cmd: :return: (code, stdout, stderr)
def _load_diff(args, extra_opts): """ :param args: :class:`argparse.Namespace` object :param extra_opts: Map object given to API.load as extra options """ try: diff = API.load(args.inputs, args.itype, ac_ignore_missing=args.ignore_missing, ac_m...
:param args: :class:`argparse.Namespace` object :param extra_opts: Map object given to API.load as extra options
def lru_cache(maxsize=100, typed=False): """Least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) will be treated...
Least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) will be treated as distinct calls with distinct results. ...
def close(self): """ Closes all resources/backends associated with this queue manager. """ self.log.info("Shutting down queue manager.") if hasattr(self.store, 'close'): self.store.close() if hasattr(self.subscriber_scheduler, 'close'): self.subsc...
Closes all resources/backends associated with this queue manager.
def archive_filenames(self): """Return the list of files inside an archive file.""" try: return _bfd.archive_list_filenames(self._ptr) except TypeError, err: raise BfdException(err)
Return the list of files inside an archive file.
def transition_counts(alpha, beta, A, pobs, T=None, out=None): """ Sum for all t the probability to transition from state i to state j. Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((...
Sum for all t the probability to transition from state i to state j. Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the...
def setedge(delta, is_multigraph, graph, orig, dest, idx, exists): """Change a delta to say that an edge was created or deleted""" if is_multigraph(graph): delta.setdefault(graph, {}).setdefault('edges', {})\ .setdefault(orig, {}).setdefault(dest, {})[idx] = bool(exists) else: de...
Change a delta to say that an edge was created or deleted
def download_attachments(self, dataset_identifier, content_type="json", download_dir="~/sodapy_downloads"): ''' Download all of the attachments associated with a dataset. Return the paths of downloaded files. ''' metadata = self.get_metadata(dataset_i...
Download all of the attachments associated with a dataset. Return the paths of downloaded files.
def get_password(vm_): r''' Return the password to use for a VM. vm\_ The configuration to obtain the password from. ''' return config.get_cloud_config_value( 'password', vm_, __opts__, default=config.get_cloud_config_value( 'passwd', vm_, __opts__, s...
r''' Return the password to use for a VM. vm\_ The configuration to obtain the password from.
def _smart_separate_groups(groups, key, total): """Given a list of group objects, and a function to extract the number of elements for each of them, return the list of groups that have an excessive number of elements (when compared to a uniform distribution), a list of groups with insufficient elements,...
Given a list of group objects, and a function to extract the number of elements for each of them, return the list of groups that have an excessive number of elements (when compared to a uniform distribution), a list of groups with insufficient elements, and a list of groups that already have the optimal...
def connected(self, msg): """Once I've connected I want to subscribe to my the message queue. """ stomper.Engine.connected(self, msg) self.log.info("Connected: session %s. Beginning say hello." % msg['headers']['session']) def setup_looping_call(): lc = Loop...
Once I've connected I want to subscribe to my the message queue.
def get_random_hex(length): """ Return random hex string of a given length """ if length <= 0: return '' return hexify(random.randint(pow(2, length*2), pow(2, length*4)))[0:length]
Return random hex string of a given length
def wait_time(self, value): """ Setter for **self.__wait_time** attribute. :param value: Attribute value. :type value: int or float """ if value is not None: assert type(value) in (int, float), "'{0}' attribute: '{1}' type is not 'int' or 'float'!".format( ...
Setter for **self.__wait_time** attribute. :param value: Attribute value. :type value: int or float
def get_objective_requisite_assignment_session(self, proxy): """Gets the session for managing objective requisites. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ObjectiveRequisiteAssignmentSession) - an ``ObjectiveRequisiteAssignmentSession`` raise: ...
Gets the session for managing objective requisites. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ObjectiveRequisiteAssignmentSession) - an ``ObjectiveRequisiteAssignmentSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - u...
def get_wake_on_network(): ''' Displays whether 'wake on network' is on or off if supported :return: A string value representing the "wake on network" settings :rtype: string CLI Example: .. code-block:: bash salt '*' power.get_wake_on_network ''' ret = salt.utils.mac_utils.e...
Displays whether 'wake on network' is on or off if supported :return: A string value representing the "wake on network" settings :rtype: string CLI Example: .. code-block:: bash salt '*' power.get_wake_on_network
def execute(self, request, target_route): """ :meth:`.WWebServiceProto.execute` method implementation """ presenter = self.create_presenter(request, target_route) presenter_name = target_route.presenter_name() action_name = target_route.presenter_action() presenter_args = target_route.presenter_args() if...
:meth:`.WWebServiceProto.execute` method implementation
def final_bounces(fetches, url): """ Resolves redirect chains in `fetches` and returns a list of fetches representing the final redirect destinations of the given url. There could be more than one if for example youtube-dl hit the same url with HEAD and then GET requests. """ redirects = {} ...
Resolves redirect chains in `fetches` and returns a list of fetches representing the final redirect destinations of the given url. There could be more than one if for example youtube-dl hit the same url with HEAD and then GET requests.
def _ReadUUIDDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads an UUID data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, obje...
Reads an UUID data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): name of the definition. is_member (Optional[bool]): True if the data type ...
def get_unset_inputs(self): """ Return a set of unset inputs """ return set([k for k, v in self._inputs.items() if v.is_empty(False)])
Return a set of unset inputs
def set_cache_url (self): """Set the URL to be used for caching.""" # remove anchor from cached target url since we assume # URLs with different anchors to have the same content self.cache_url = urlutil.urlunsplit(self.urlparts[:4]+[u'']) if self.cache_url is not None: ...
Set the URL to be used for caching.
def _instance_parser(self, plugins): """ internal method to parse instances of plugins. Determines if each class is a class instance or object instance and calls the appropiate handler method. """ plugins = util.return_list(plugins) for instance in plugin...
internal method to parse instances of plugins. Determines if each class is a class instance or object instance and calls the appropiate handler method.
def stride(self): """Step per axis between neighboring points of a uniform grid. If the grid contains axes that are not uniform, ``stride`` has a ``NaN`` entry. For degenerate (length 1) axes, ``stride`` has value ``0.0``. Returns ------- stride : numpy.array ...
Step per axis between neighboring points of a uniform grid. If the grid contains axes that are not uniform, ``stride`` has a ``NaN`` entry. For degenerate (length 1) axes, ``stride`` has value ``0.0``. Returns ------- stride : numpy.array Array of dtype ``f...
def left(ctx, text, num_chars): """ Returns the first characters in a text string """ num_chars = conversions.to_integer(num_chars, ctx) if num_chars < 0: raise ValueError("Number of chars can't be negative") return conversions.to_string(text, ctx)[0:num_chars]
Returns the first characters in a text string
def shrink(self, src, width=0, max_value=0, filter_method=None, path=None, flags=0): """Shrink sketch Params: <Sketch> src_sketch <int> width <int> max_value <lambda> | <function> filter <str> path <int> flags ...
Shrink sketch Params: <Sketch> src_sketch <int> width <int> max_value <lambda> | <function> filter <str> path <int> flags
def retrieve_order(self, order_id): """Retrieve details on a single order.""" response = self.request(E.retrieveOrderSslCertRequest( E.id(order_id) )) return response.as_model(SSLOrder)
Retrieve details on a single order.
def delete(self, request, id=None): """ Handles delete requests. """ if id: obj = get_object_or_404(self.queryset(request), id=id) if not self.has_delete_permission(request, obj): return HttpResponseForbidden(_('You do not have permission to perfor...
Handles delete requests.
def ReadClientLastPings(self, min_last_ping=None, max_last_ping=None, fleetspeak_enabled=None, cursor=None): """Reads client ids for all clients in the database.""" query = "SELECT client_id, UNIX_TIMESTAMP(l...
Reads client ids for all clients in the database.
def require_option(current_ctx: click.Context, param_name: str) -> None: """Throw an exception if an option wasn't required. This is useful when its optional in some contexts but required for a subcommand""" ctx = current_ctx param_definition = None while ctx is not None: # ctx.command.para...
Throw an exception if an option wasn't required. This is useful when its optional in some contexts but required for a subcommand
def _copy_flaky_attributes(cls, test, test_class): """ Copy flaky attributes from the test callable or class to the test. :param test: The test that is being prepared to run :type test: :class:`nose.case.Test` """ test_callable = cls._get_test_cal...
Copy flaky attributes from the test callable or class to the test. :param test: The test that is being prepared to run :type test: :class:`nose.case.Test`
def _get_expiry_timestamp(cls, session_server): """ :type session_server: core.SessionServer :rtype: datetime.datetime """ timeout_seconds = cls._get_session_timeout_seconds(session_server) time_now = datetime.datetime.now() return time_now + datetime.timedelta...
:type session_server: core.SessionServer :rtype: datetime.datetime
def convert_to_sympy_matrix(expr, full_space=None): """Convert a QNET expression to an explicit ``n x n`` instance of `sympy.Matrix`, where ``n`` is the dimension of `full_space`. The entries of the matrix may contain symbols. Parameters: expr: a QNET expression full_space (qnet.algebra...
Convert a QNET expression to an explicit ``n x n`` instance of `sympy.Matrix`, where ``n`` is the dimension of `full_space`. The entries of the matrix may contain symbols. Parameters: expr: a QNET expression full_space (qnet.algebra.hilbert_space_algebra.HilbertSpace): The Hilbe...
def add_shared_configs(p, base_dir=''): """Add configargparser/argparse configs for shared argument. Arguments: p - configargparse.ArgParser object base_dir - base directory for file/path defaults. """ p.add('--host', default='localhost', help="Service host") p.add('--port...
Add configargparser/argparse configs for shared argument. Arguments: p - configargparse.ArgParser object base_dir - base directory for file/path defaults.
def policy_map_class_cl_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") policy_map = ET.SubElement(config, "policy-map", xmlns="urn:brocade.com:mgmt:brocade-policer") po_name_key = ET.SubElement(policy_map, "po-name") po_name_key.text = kwar...
Auto Generated Code
def load_tf_weights_in_openai_gpt(model, openai_checkpoint_folder_path): """ Load tf pre-trained weights in a pytorch model (from NumPy arrays here) """ import re import numpy as np print("Loading weights...") names = json.load(open(openai_checkpoint_folder_path + '/parameters_names.json', "r", ...
Load tf pre-trained weights in a pytorch model (from NumPy arrays here)
def listDevices(self, interface_id): """The CCU / Homegear asks for devices known to our XML-RPC server. We respond to that request using this method.""" LOG.debug("RPCFunctions.listDevices: interface_id = %s, _devices_raw = %s" % ( interface_id, str(self._devices_raw))) remote = int...
The CCU / Homegear asks for devices known to our XML-RPC server. We respond to that request using this method.
def live_log_child(self): '''Start the logging child process if it died.''' if not (self.log_child and self.pid_is_alive(self.log_child)): self.start_log_child()
Start the logging child process if it died.
def preprocess( self, nb: "NotebookNode", resources: dict ) -> Tuple["NotebookNode", dict]: """Remove any raw cells from the Notebook. By default, exclude raw cells from the output. Change this by including global_content_filter->include_raw = True in the resources dictionary. ...
Remove any raw cells from the Notebook. By default, exclude raw cells from the output. Change this by including global_content_filter->include_raw = True in the resources dictionary. This preprocessor is necessary because the NotebookExporter doesn't include the exclude_raw config.
def write_to_path(self, path=None): """Write configuration to a file on disk.""" if path is None: path = self.path f = GitFile(path, 'wb') try: self.write_to_file(f) finally: f.close()
Write configuration to a file on disk.
def get_interfaces(device_name=None, **kwargs): ''' .. versionadded:: 2019.2.0 Returns interfaces for a specific device using arbitrary netbox filters device_name The name of the device, e.g., ``edge_router`` kwargs Optional arguments to be used for filtering CLI Example: ...
.. versionadded:: 2019.2.0 Returns interfaces for a specific device using arbitrary netbox filters device_name The name of the device, e.g., ``edge_router`` kwargs Optional arguments to be used for filtering CLI Example: .. code-block:: bash salt myminion netbox.get_inte...
def rank(self, score): '''Return the 0-based index (rank) of ``score``. If the score is not available it returns a negative integer which absolute score is the right most closest index with score less than ``score``. ''' node = self._head rank = 0 for i i...
Return the 0-based index (rank) of ``score``. If the score is not available it returns a negative integer which absolute score is the right most closest index with score less than ``score``.
def _maybe_init_tags(self, run_id, tag_to_metadata): """Returns a tag-to-ID map for the given tags, creating rows if needed. Args: run_id: the ID of the run to which these tags belong. tag_to_metadata: map of tag name to SummaryMetadata for the tag. """ cursor = self._db.cursor() # TODO...
Returns a tag-to-ID map for the given tags, creating rows if needed. Args: run_id: the ID of the run to which these tags belong. tag_to_metadata: map of tag name to SummaryMetadata for the tag.
def chunked(sentence): """ Returns a list of Chunk and Chink objects from the given sentence. Chink is a subclass of Chunk used for words that have Word.chunk == None (e.g., punctuation marks, conjunctions). """ # For example, to construct a training vector with the head of previous chunks a...
Returns a list of Chunk and Chink objects from the given sentence. Chink is a subclass of Chunk used for words that have Word.chunk == None (e.g., punctuation marks, conjunctions).
def _get_aws_variables(self): """ Returns the AWS specific environment variables that should be available in the Lambda runtime. They are prefixed it "AWS_*". :return dict: Name and value of AWS environment variable """ result = { # Variable that says this f...
Returns the AWS specific environment variables that should be available in the Lambda runtime. They are prefixed it "AWS_*". :return dict: Name and value of AWS environment variable
def setup_segment_generation(workflow, out_dir, tag=None): """ This function is the gateway for setting up the segment generation steps in a workflow. It is designed to be able to support multiple ways of obtaining these segments and to combine/edit such files as necessary for analysis. The current ...
This function is the gateway for setting up the segment generation steps in a workflow. It is designed to be able to support multiple ways of obtaining these segments and to combine/edit such files as necessary for analysis. The current modules have the capability to generate files at runtime or to gene...
def send_key(self, key): """Send a key command to the TV.""" if isinstance(key, Keys): key = key.value params = '<X_KeyEvent>{}</X_KeyEvent>'.format(key) self.soap_request(URL_CONTROL_NRC, URN_REMOTE_CONTROL, 'X_SendKey', params)
Send a key command to the TV.
async def jsk_shutdown(self, ctx: commands.Context): """ Logs this bot out. """ await ctx.send("Logging out now..") await ctx.bot.logout()
Logs this bot out.
def _identity(self, *args, **kwargs): ''' Local users and groups. accounts Can be either 'local', 'remote' or 'all' (equal to "local,remote"). Remote accounts cannot be resolved on all systems, but only those, which supports 'passwd -S -a'. disabled ...
Local users and groups. accounts Can be either 'local', 'remote' or 'all' (equal to "local,remote"). Remote accounts cannot be resolved on all systems, but only those, which supports 'passwd -S -a'. disabled True (or False, default) to return only disabl...
def parse_vtrgb(path='/etc/vtrgb'): ''' Parse the color table for the Linux console. ''' palette = () table = [] try: with open(path) as infile: for i, line in enumerate(infile): row = tuple(int(val) for val in line.split(',')) table.append(row) ...
Parse the color table for the Linux console.
def _run_sm_scale_in(self, C_out, scale_sm=91.1876): """Get the SM parameters at the EW scale, using an estimate `C_out` of the Wilson coefficients at that scale, and run them to the input scale.""" # initialize an empty SMEFT instance smeft_sm = SMEFT(wc=None) C_in_sm = ...
Get the SM parameters at the EW scale, using an estimate `C_out` of the Wilson coefficients at that scale, and run them to the input scale.
def pydoc_cli_monkey_patched(port): """In Python 3, run pydoc.cli with builtins.input monkey-patched so that pydoc can be run as a process. """ # Monkey-patch input so that input does not raise EOFError when # called by pydoc.cli def input(_): # pylint: disable=W0622 """Monkey-patched ...
In Python 3, run pydoc.cli with builtins.input monkey-patched so that pydoc can be run as a process.
def _calculateSegmentActivity(connections, activeInput, connectedPermanence, activationThreshold, minThreshold, reducedThreshold, reducedThresholdCells = ()): """ Calculate the active and matching basal segments for ...
Calculate the active and matching basal segments for this timestep. @param connections (SparseMatrixConnections) @param activeInput (numpy array) @return (tuple) - activeSegments (numpy array) Dendrite segments with enough active connected synapses to cause a dendritic spike - matchin...
def get_error(response): """Gets Error by HTTP Status Code""" errors = { 400: BadRequestError, 401: UnauthorizedError, 403: AccessDeniedError, 404: NotFoundError, 429: RateLimitExceededError, 500: ServerError, 502: BadGatewayError, 503: ServiceUna...
Gets Error by HTTP Status Code
def build_project(self): """ Build IAR project """ # > IarBuild [project_path] -build [project_name] proj_path = join(getcwd(), self.workspace['files']['ewp']) if proj_path.split('.')[-1] != 'ewp': proj_path += '.ewp' if not os.path.exists(proj_path): logg...
Build IAR project
def get_descriptives(data): """Get mean, SD, and mean and SD of log values. Parameters ---------- data : ndarray Data with segment as first dimension and all other dimensions raveled into second dimension. Returns ------- dict of ndarray each entry is a 1-D vector o...
Get mean, SD, and mean and SD of log values. Parameters ---------- data : ndarray Data with segment as first dimension and all other dimensions raveled into second dimension. Returns ------- dict of ndarray each entry is a 1-D vector of descriptives over segment dimensi...
def flatten(self): """Create a flattened version by putting output first and then states.""" ls = [self.output] ls.extend(self.state) return ls
Create a flattened version by putting output first and then states.
def send_stun(self, message, addr): """ Send a STUN message. """ self.__log_debug('> %s %s', addr, message) self.transport.sendto(bytes(message), addr)
Send a STUN message.
def make_sentence(list_words): """ Return a sentence from list of words. :param list list_words: list of words :returns: sentence :rtype: str """ lw_len = len(list_words) if lw_len > 6: list_words.insert(lw_len // 2 + random.choice(range(-2, ...
Return a sentence from list of words. :param list list_words: list of words :returns: sentence :rtype: str
def _from_dict(cls, _dict): """Initialize a Corpora object from a json dictionary.""" args = {} if 'corpora' in _dict: args['corpora'] = [ Corpus._from_dict(x) for x in (_dict.get('corpora')) ] else: raise ValueError( 'R...
Initialize a Corpora object from a json dictionary.
def ignore_after(seconds, coro=None, *args, timeout_result=None): '''Execute the specified coroutine and return its result. Issue a cancellation request after seconds have elapsed. When a timeout occurs, no exception is raised. Instead, timeout_result is returned. If coro is None, the result is an ...
Execute the specified coroutine and return its result. Issue a cancellation request after seconds have elapsed. When a timeout occurs, no exception is raised. Instead, timeout_result is returned. If coro is None, the result is an asynchronous context manager that applies a timeout to a block of sta...
def get_unspents(self): """Fetches all available unspent transaction outputs. :rtype: ``list`` of :class:`~bitcash.network.meta.Unspent` """ self.unspents[:] = NetworkAPI.get_unspent(self.address) self.balance = sum(unspent.amount for unspent in self.unspents) return sel...
Fetches all available unspent transaction outputs. :rtype: ``list`` of :class:`~bitcash.network.meta.Unspent`
def _get_filename(self, key, filename): """Write key to file. Either this method or :meth:`~simplekv.KeyValueStore._get_file` will be called by :meth:`~simplekv.KeyValueStore.get_file`. This method only accepts filenames and will open the file with a mode of ``wb``, then call :me...
Write key to file. Either this method or :meth:`~simplekv.KeyValueStore._get_file` will be called by :meth:`~simplekv.KeyValueStore.get_file`. This method only accepts filenames and will open the file with a mode of ``wb``, then call :meth:`~simplekv.KeyValueStore._get_file`. :p...
def _compile_int_f(self): """Time Domain Simulation - update differential equations""" string = '"""\n' string += 'system.dae.init_f()\n' # evaluate differential equations f for fcall, call in zip(self.fcall, self.fcalls): if fcall: string += call ...
Time Domain Simulation - update differential equations
def poll(self, timeout=-1, maxevents=-1): """ Poll for events :param timeout: The amount of seconds to wait for events before giving up. The default value, -1, represents infinity. Note that unlike the underlying ``epoll_wait()`` timeout is a fractional numbe...
Poll for events :param timeout: The amount of seconds to wait for events before giving up. The default value, -1, represents infinity. Note that unlike the underlying ``epoll_wait()`` timeout is a fractional number representing **seconds**. :param maxeven...
def datapath(self): """ Get an item's data path. """ path = self._fields['path'] if not path: # stopped item with no base_dir? path = self.fetch('directory') if path and not self._fields['is_multi_file']: path = os.path.join(path, self._fields['na...
Get an item's data path.
def after(f, chain=False): """Runs f with the result of the decorated function.""" def decorator(g): @wraps(g) def h(*args, **kargs): if chain: return f(g(*args, **kargs)) else: r = g(*args, **kargs) f(*args, **kargs) ...
Runs f with the result of the decorated function.
def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret...
Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb
def garbage(): """ Collect garbage and return an :class:`~refcycle.object_graph.ObjectGraph` based on collected garbage. The collected elements are removed from ``gc.garbage``, but are still kept alive by the references in the graph. Deleting the :class:`~refcycle.object_graph.ObjectGraph` ins...
Collect garbage and return an :class:`~refcycle.object_graph.ObjectGraph` based on collected garbage. The collected elements are removed from ``gc.garbage``, but are still kept alive by the references in the graph. Deleting the :class:`~refcycle.object_graph.ObjectGraph` instance and doing another ...
def _seg_to_vcf(vals): """Convert GATK CNV calls seg output to a VCF line. """ call_to_cn = {"+": 3, "-": 1} call_to_type = {"+": "DUP", "-": "DEL"} if vals["CALL"] not in ["0"]: info = ["FOLD_CHANGE_LOG=%s" % vals["MEAN_LOG2_COPY_RATIO"], "PROBES=%s" % vals["NUM_POINTS_COPY_...
Convert GATK CNV calls seg output to a VCF line.
def pack(self, value=None): """Pack the struct in a binary representation. Iterate over the class attributes, according to the order of definition, and then convert each attribute to its byte representation using its own ``pack`` method. Returns: bytes: Binary repre...
Pack the struct in a binary representation. Iterate over the class attributes, according to the order of definition, and then convert each attribute to its byte representation using its own ``pack`` method. Returns: bytes: Binary representation of the struct object. ...
def removeSinglePixels(img): ''' img - boolean array remove all pixels that have no neighbour ''' gx = img.shape[0] gy = img.shape[1] for i in range(gx): for j in range(gy): if img[i, j]: found_neighbour = False for ii in...
img - boolean array remove all pixels that have no neighbour
async def shutdown(self, container, force=False): ''' Shutdown all connections. Exclusive connections created by get_connection will shutdown after release() ''' p = self._connpool self._connpool = [] self._shutdown = True if self._defaultconn: p.appen...
Shutdown all connections. Exclusive connections created by get_connection will shutdown after release()
def gaussian_filter1d_ppxf(spec, sig): """ Convolve a spectrum by a Gaussian with different sigma for every pixel. If all sigma are the same this routine produces the same output as scipy.ndimage.gaussian_filter1d, except for the border treatment. Here the first/last p pixels are filled with zeros. ...
Convolve a spectrum by a Gaussian with different sigma for every pixel. If all sigma are the same this routine produces the same output as scipy.ndimage.gaussian_filter1d, except for the border treatment. Here the first/last p pixels are filled with zeros. When creating a template library for SDSS data,...
def _golbub_welsch(orders, coeff1, coeff2): """Recurrence coefficients to abscisas and weights.""" abscisas, weights = [], [] for dim, order in enumerate(orders): if order: bands = numpy.zeros((2, order)) bands[0] = coeff1[dim, :order] bands[1, :-1] = numpy.sqrt(...
Recurrence coefficients to abscisas and weights.
def _del_thread(self, dwThreadId): """ Private method to remove a thread object from the snapshot. @type dwThreadId: int @param dwThreadId: Global thread ID. """ try: aThread = self.__threadDict[dwThreadId] del self.__threadDict[dwThreadId] ...
Private method to remove a thread object from the snapshot. @type dwThreadId: int @param dwThreadId: Global thread ID.
def get_vlan_brief_input_request_type_get_request_vlan_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vlan_brief = ET.Element("get_vlan_brief") config = get_vlan_brief input = ET.SubElement(get_vlan_brief, "input") request_type = ...
Auto Generated Code
def Connect(self, Username, WaitConnected=False): """Connects application to user. :Parameters: Username : str Name of the user to connect to. WaitConnected : bool If True, causes the method to wait until the connection is established. :return: If ``...
Connects application to user. :Parameters: Username : str Name of the user to connect to. WaitConnected : bool If True, causes the method to wait until the connection is established. :return: If ``WaitConnected`` is True, returns the stream which can be used...
def count_string_diff(a,b): """Return the number of characters in two strings that don't exactly match""" shortest = min(len(a), len(b)) return sum(a[i] != b[i] for i in range(shortest))
Return the number of characters in two strings that don't exactly match
def _check_distributed_corpora_file(self): """Check '~/cltk_data/distributed_corpora.yaml' for any custom, distributed corpora that the user wants to load locally. TODO: write check or try if `cltk_data` dir is not present """ if self.testing: distributed_corpora_fp ...
Check '~/cltk_data/distributed_corpora.yaml' for any custom, distributed corpora that the user wants to load locally. TODO: write check or try if `cltk_data` dir is not present
def parseCmdline(rh, posOpsList, keyOpsList): """ Parse the request command input. Input: Request Handle Positional Operands List. This is a dictionary that contains an array for each subfunction. The array contains a entry (itself an array) for each positional operand. ...
Parse the request command input. Input: Request Handle Positional Operands List. This is a dictionary that contains an array for each subfunction. The array contains a entry (itself an array) for each positional operand. That array contains: - Human readable name of t...
def create_instance(self, image_id, pem_file, group_ids, instance_type, volume_type='gp2', ebs_optimized=False, instance_monitoring=False, iam_profile='', tag_list=None, auction_bid=0.0): ''' a method for starting an instance on AWS EC2 :param image_id: string with aws id of im...
a method for starting an instance on AWS EC2 :param image_id: string with aws id of image for instance :param pem_file: string with path to pem file to access image :param group_ids: list with aws id of security group(s) to attach to instance :param instance_type: string wi...
def stop(self): """Stop the publisher. """ self.publish.setsockopt(zmq.LINGER, 1) self.publish.close() return self
Stop the publisher.
def cVectorToPython(x): """ Convert the c vector data into the correct python data type (numpy arrays or strings) :param x: :return: """ if isinstance(x[0], bool): return numpy.frombuffer(x, dtype=numpy.bool).copy() elif isinstance(x[0], int): return numpy.frombuffer(x, d...
Convert the c vector data into the correct python data type (numpy arrays or strings) :param x: :return:
def _get_init_args(self): """Creates dict with properties marked as readonly""" args = {} for rop in self.ro_properties: if rop in self.properties: args[rop] = self.properties[rop] return args
Creates dict with properties marked as readonly
def CopyToDict(self): """Copies the event tag to a dictionary. Returns: dict[str, object]: event tag attributes. """ result_dict = { 'labels': self.labels } if self.comment: result_dict['comment'] = self.comment return result_dict
Copies the event tag to a dictionary. Returns: dict[str, object]: event tag attributes.
def install(cert, password, keychain="/Library/Keychains/System.keychain", allow_any=False, keychain_password=None): ''' Install a certificate cert The certificate to install password The password for the certificate being installed forma...
Install a certificate cert The certificate to install password The password for the certificate being installed formatted in the way described for openssl command in the PASS PHRASE ARGUMENTS section. Note: The password given here will show up as plaintext in the job returned ...
def event_types(self): """ Raises ------ IndexError When there is no selected rater """ try: events = self.rater.find('events') except AttributeError: raise IndexError('You need to have at least one rater') return [x.ge...
Raises ------ IndexError When there is no selected rater
def find_frequencies(data, freq=44100, bits=16): """Convert audio data into a frequency-amplitude table using fast fourier transformation. Return a list of tuples (frequency, amplitude). Data should only contain one channel of audio. """ # Fast fourier transform n = len(data) p = _fft(...
Convert audio data into a frequency-amplitude table using fast fourier transformation. Return a list of tuples (frequency, amplitude). Data should only contain one channel of audio.
def finalizePrivateLessonRegistration(sender,**kwargs): ''' Once a private lesson registration is finalized, mark the slots that were used to book the private lesson as booked and associate them with the final registration. No need to notify students in this instance because they are already r...
Once a private lesson registration is finalized, mark the slots that were used to book the private lesson as booked and associate them with the final registration. No need to notify students in this instance because they are already receiving a notification of their registration.
def _delta_kt_prime_dirint(kt_prime, use_delta_kt_prime, times): """ Calculate delta_kt_prime (Perez eqn 2 and eqn 3), or return a default value for use with :py:func:`_dirint_bins`. """ if use_delta_kt_prime: # Perez eqn 2 kt_next = kt_prime.shift(-1) kt_previous = kt_prime....
Calculate delta_kt_prime (Perez eqn 2 and eqn 3), or return a default value for use with :py:func:`_dirint_bins`.
def initSeasonFactors(self, timeSeries): """ Computes the initial season smoothing factors. :return: Returns a list of season vectors of length "seasonLength". :rtype: list """ seasonLength = self.get_parameter("seasonLength") try: seasonValues = self.get...
Computes the initial season smoothing factors. :return: Returns a list of season vectors of length "seasonLength". :rtype: list
def apply(self, fn, dtype=None, seed=None): """ Transform each row to an :class:`~turicreate.SArray` according to a specified function. Returns a new SArray of ``dtype`` where each element in this SArray is transformed by `fn(x)` where `x` is a single row in the sframe represente...
Transform each row to an :class:`~turicreate.SArray` according to a specified function. Returns a new SArray of ``dtype`` where each element in this SArray is transformed by `fn(x)` where `x` is a single row in the sframe represented as a dictionary. The ``fn`` should return exactly one...
def get_conn(profile): ''' Return a client object for accessing consul ''' params = {} for key in ('host', 'port', 'token', 'scheme', 'consistency', 'dc', 'verify'): if key in profile: params[key] = profile[key] if HAS_CONSUL: return consul.Consul(**params) else:...
Return a client object for accessing consul
def _get_indexing_dispatch_code(key): """Returns a dispatch code for calling basic or advanced indexing functions.""" if isinstance(key, (NDArray, np.ndarray)): return _NDARRAY_ADVANCED_INDEXING elif isinstance(key, list): # TODO(junwu): Add support for nested lists besides integer list ...
Returns a dispatch code for calling basic or advanced indexing functions.
def attach_socket(self, **kwargs): """ Like :py:meth:`attach`, but returns the underlying socket-like object for the HTTP request. Args: params (dict): Dictionary of request parameters (e.g. ``stdout``, ``stderr``, ``stream``). ws (bool): Use webs...
Like :py:meth:`attach`, but returns the underlying socket-like object for the HTTP request. Args: params (dict): Dictionary of request parameters (e.g. ``stdout``, ``stderr``, ``stream``). ws (bool): Use websockets instead of raw HTTP. Raises: ...
def wait_for_term(): """ Wait until we get killed by a TERM signal (from someone else). """ class Waiter: def __init__(self): self.sleeping = True import signal #@Reimport self.oldhandler = signal.signal(signal.SIGTERM, ...
Wait until we get killed by a TERM signal (from someone else).
def redirect(self, pid): """Redirect persistent identifier to another persistent identifier. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` where redirect the PID. :raises invenio_pidstore.errors.PIDInvalidAction: If the PID is not registered or is...
Redirect persistent identifier to another persistent identifier. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` where redirect the PID. :raises invenio_pidstore.errors.PIDInvalidAction: If the PID is not registered or is not already redirecting to another ...
def encrypt(self, data): """ Encrypt the data. Also, update the cipher iv. This is needed for SSLv3 and TLS 1.0. For TLS 1.1/1.2, it is overwritten in TLS.post_build(). """ if False in six.itervalues(self.ready): raise CipherError(data) encryptor = self._ciphe...
Encrypt the data. Also, update the cipher iv. This is needed for SSLv3 and TLS 1.0. For TLS 1.1/1.2, it is overwritten in TLS.post_build().
def use_schema(schema, list_view=False, locations=None): """View decorator for using a marshmallow schema to (1) parse a request's input and (2) serializing the view's output to a JSON response. """ def decorator(func): @functools.wraps(func) def wrapped(*args, **kwargs): ...
View decorator for using a marshmallow schema to (1) parse a request's input and (2) serializing the view's output to a JSON response.
def _find_interfaces_ip(mac): ''' Helper to search the interfaces IPs using the MAC address. ''' try: mac = napalm_helpers.convert(napalm_helpers.mac, mac) except AddrFormatError: return ('', '', []) all_interfaces = _get_mine('net.interfaces') all_ipaddrs = _get_mine('net.i...
Helper to search the interfaces IPs using the MAC address.