code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def stop(self): """ Stop the HTTP server thread. """ self.my_server.stop() self.http_thread.join() logging.info("HTTP server: Stopped")
Stop the HTTP server thread.
def do_perf_counter_check(self, instance): """ Fetch the metrics from the sys.dm_os_performance_counters table """ custom_tags = instance.get('tags', []) if custom_tags is None: custom_tags = [] instance_key = self._conn_key(instance, self.DEFAULT_DB_KEY) ...
Fetch the metrics from the sys.dm_os_performance_counters table
def register_extensions(self, exts, force=False): """ Add/register extensions. Args: exts (dict): force (bool): If ``force`` is set to ``True``, simply overwrite existing extensions, otherwise do nothing. If the ``logger`` is set, log a warning about the ...
Add/register extensions. Args: exts (dict): force (bool): If ``force`` is set to ``True``, simply overwrite existing extensions, otherwise do nothing. If the ``logger`` is set, log a warning about the duplicate extension if ``force == False``.
def tangelo_import(*args, **kwargs): """ When we are asked to import a module, if we get an import error and the calling script is one we are serving (not one in the python libraries), try again in the same directory as the script that is calling import. It seems like we should use sys.meta_path...
When we are asked to import a module, if we get an import error and the calling script is one we are serving (not one in the python libraries), try again in the same directory as the script that is calling import. It seems like we should use sys.meta_path and combine our path with the path sent to i...
def update_server_cert(self, cert_name, new_cert_name=None, new_path=None): """ Updates the name and/or the path of the specified server certificate. :type cert_name: string :param cert_name: The name of the server certificate that you want ...
Updates the name and/or the path of the specified server certificate. :type cert_name: string :param cert_name: The name of the server certificate that you want to update. :type new_cert_name: string :param new_cert_name: The new name for the server certificat...
def process_result_value(self, value, dialect): """ Returns a new list of enums.CryptographicUsageMask Enums. This converts the integer value into the list of enums. Args: value(int): The integer value stored in the database that is used to create the list of...
Returns a new list of enums.CryptographicUsageMask Enums. This converts the integer value into the list of enums. Args: value(int): The integer value stored in the database that is used to create the list of enums.CryptographicUsageMask Enums. dialect(string): SQ...
def add_error_marker(text, position, start_line=1): """Add a caret marking a given position in a string of input. Returns (new_text, caret_line). """ indent = " " lines = [] caret_line = start_line for line in text.split("\n"): lines.append(indent + line) if 0 <= positio...
Add a caret marking a given position in a string of input. Returns (new_text, caret_line).
def add_path(self, nodes, **attr): """In replacement for Deprecated add_path method""" if nx.__version__[0] == "1": return super().add_path(nodes, **attr) else: return nx.add_path(self, nodes, **attr)
In replacement for Deprecated add_path method
def varYSizeGaussianFilter(arr, stdyrange, stdx=0, modex='wrap', modey='reflect'): ''' applies gaussian_filter on input array but allowing variable ksize in y stdyrange(int) -> maximum ksize - ksizes will increase from 0 to given value stdyrange(tuple,list) -> ...
applies gaussian_filter on input array but allowing variable ksize in y stdyrange(int) -> maximum ksize - ksizes will increase from 0 to given value stdyrange(tuple,list) -> minimum and maximum size as (mn,mx) stdyrange(np.array) -> all different ksizes in y
def subsets(self): """Subsets that make up each split of the dataset for the language pair.""" source, target = self.builder_config.language_pair filtered_subsets = {} for split, ss_names in self._subsets.items(): filtered_subsets[split] = [] for ss_name in ss_names: ds = DATASET_MAP...
Subsets that make up each split of the dataset for the language pair.
def write(self, sync_map_format, output_file_path, parameters=None): """ Write the current sync map to file in the requested format. Return ``True`` if the call succeeded, ``False`` if an error occurred. :param sync_map_format: the format of the sync map :type sync_map...
Write the current sync map to file in the requested format. Return ``True`` if the call succeeded, ``False`` if an error occurred. :param sync_map_format: the format of the sync map :type sync_map_format: :class:`~aeneas.syncmap.SyncMapFormat` :param string output_file_path: t...
def expand_no_defaults (property_sets): """ Expand the given build request by combining all property_sets which don't specify conflicting non-free features. """ assert is_iterable_typed(property_sets, property_set.PropertySet) # First make all features and subfeatures explicit expanded_prope...
Expand the given build request by combining all property_sets which don't specify conflicting non-free features.
def nack(self, id, subscription, transaction=None, receipt=None): """ Let the server know that a message was not consumed. :param str id: the unique id of the message to nack :param str subscription: the subscription this message is associated with :param str transaction: includ...
Let the server know that a message was not consumed. :param str id: the unique id of the message to nack :param str subscription: the subscription this message is associated with :param str transaction: include this nack in a named transaction
def select(dataspec, testsuite, mode='list', cast=True): """ Select data from [incr tsdb()] profiles. Args: query (str): TSQL select query (e.g., `'i-id i-input mrs'` or `'* from item where readings > 0'`) testsuite (str, TestSuite): testsuite or path to testsuite co...
Select data from [incr tsdb()] profiles. Args: query (str): TSQL select query (e.g., `'i-id i-input mrs'` or `'* from item where readings > 0'`) testsuite (str, TestSuite): testsuite or path to testsuite containing data to select mode (str): see :func:`delphin.itsdb....
def _update_service_current_state(service: ServiceState): """Update the current state of a service. Updates the current state of services after their target state has changed. Args: service (ServiceState): Service state object to update """ LOG.debug("Setting current state from target sta...
Update the current state of a service. Updates the current state of services after their target state has changed. Args: service (ServiceState): Service state object to update
def forkandlog(function, filter='INFO5', debug=False): """Fork a child process and read its CASA log output. function A function to run in the child process filter The CASA log level filter to apply in the child process: less urgent messages will not be shown. Valid values are strings: "D...
Fork a child process and read its CASA log output. function A function to run in the child process filter The CASA log level filter to apply in the child process: less urgent messages will not be shown. Valid values are strings: "DEBUG1", "INFO5", ... "INFO1", "INFO", "WARN", "SEVERE". ...
def _fit_RSA_marginalized_null(self, Y, X_base, scan_onsets): """ The marginalized version of the null model for Bayesian RSA. The null model assumes no task-related response to the design matrix. Note that there is a naming change of variab...
The marginalized version of the null model for Bayesian RSA. The null model assumes no task-related response to the design matrix. Note that there is a naming change of variable. X in fit() is changed to Y here. This is because we follow the tradition that Y c...
def crosscorrfunc(freq, cross): """ Calculate crosscorrelation function(s) for given cross spectra. Parameters ---------- freq : numpy.ndarray 1 dimensional array of frequencies. cross : numpy.ndarray 2 dimensional array of cross spectra, 1st axis units, 2nd axis units, ...
Calculate crosscorrelation function(s) for given cross spectra. Parameters ---------- freq : numpy.ndarray 1 dimensional array of frequencies. cross : numpy.ndarray 2 dimensional array of cross spectra, 1st axis units, 2nd axis units, 3rd axis frequencies. Returns --...
def stop(self, timeout=5): """ Stop the container. The container must have been created. :param timeout: Timeout in seconds to wait for the container to stop before sending a ``SIGKILL``. Default: 5 (half the Docker default) """ self.inner().stop(timeout=...
Stop the container. The container must have been created. :param timeout: Timeout in seconds to wait for the container to stop before sending a ``SIGKILL``. Default: 5 (half the Docker default)
def degToHms(ra): """Converts the ra (in degrees) to HMS three tuple. H and M are in integer and the S part is in float. """ assert (ra >= 0.0), WCSError("RA (%f) is negative" % (ra)) assert ra < 360.0, WCSError("RA (%f) > 360.0" % (ra)) rah = ra / degPerHMSHour ramin = (ra % degPerHMSHour) ...
Converts the ra (in degrees) to HMS three tuple. H and M are in integer and the S part is in float.
def t_text_end(self, t): r'</text>\s*' t.type = 'TEXT' t.value = t.lexer.lexdata[ t.lexer.text_start:t.lexer.lexpos] t.lexer.lineno += t.value.count('\n') t.value = t.value.strip() t.lexer.begin('INITIAL') return t
r'</text>\s*
def DECLARE_key_flag( # pylint: disable=g-bad-name flag_name, flag_values=FLAGS): """Declares one flag as key to the current module. Key flags are flags that are deemed really important for a module. They are important when listing help messages; e.g., if the --helpshort command-line flag is used, then on...
Declares one flag as key to the current module. Key flags are flags that are deemed really important for a module. They are important when listing help messages; e.g., if the --helpshort command-line flag is used, then only the key flags of the main module are listed (instead of all flags, as in the case of ...
def GetPackages(classification,visibility): """Gets a list of Blueprint Packages filtered by classification and visibility. https://t3n.zendesk.com/entries/20411357-Get-Packages :param classification: package type filter (System, Script, Software) :param visibility: package visibility filter (Public, Private,...
Gets a list of Blueprint Packages filtered by classification and visibility. https://t3n.zendesk.com/entries/20411357-Get-Packages :param classification: package type filter (System, Script, Software) :param visibility: package visibility filter (Public, Private, Shared)
def _disconnect(self, error): "done" if self._on_disconnect: self._on_disconnect(str(error)) if self._sender: self._sender.connectionLost(Failure(error)) self._when_done.fire(Failure(error))
done
def add_scalar_data(self, token, community_id, producer_display_name, metric_name, producer_revision, submit_time, value, **kwargs): """ Create a new scalar data point. :param token: A valid token for the user in question. :type token: str...
Create a new scalar data point. :param token: A valid token for the user in question. :type token: string :param community_id: The id of the community that owns the producer. :type community_id: int | long :param producer_display_name: The display name of the producer. :...
def updateResultsView(self, index): """ Update the selection to contain only the result specified by the index. This should be the last index of the model. Finally updade the context menu. The selectionChanged signal is used to trigger the update of the Quanty dock widge...
Update the selection to contain only the result specified by the index. This should be the last index of the model. Finally updade the context menu. The selectionChanged signal is used to trigger the update of the Quanty dock widget and result details dialog. :param index: Inde...
def returns(ts, **kwargs): ''' Compute returns on the given period @param ts : time serie to process @param kwargs.type: gross or simple returns @param delta : period betweend two computed returns @param start : with end, will return the return betweend this elapsed time @param period : del...
Compute returns on the given period @param ts : time serie to process @param kwargs.type: gross or simple returns @param delta : period betweend two computed returns @param start : with end, will return the return betweend this elapsed time @param period : delta is the number of lines/periods provi...
def perlin2(size, units=None, repeat=(10.,)*2, scale=None, shift=(0, 0)): """ 2d perlin noise either scale =(10.,10.) or units (5.,5.) have to be given.... scale is the characteristic length in pixels Parameters ---------- size: units repeat scale shift Ret...
2d perlin noise either scale =(10.,10.) or units (5.,5.) have to be given.... scale is the characteristic length in pixels Parameters ---------- size: units repeat scale shift Returns -------
def format_string(self, fmat_string): """ Takes a string containing 0 or more {variables} and formats it according to this instance's attributes. :param fmat_string: A string, e.g. '{name}-foo.txt' :type fmat_string: ``str`` :return: The string formatted according to th...
Takes a string containing 0 or more {variables} and formats it according to this instance's attributes. :param fmat_string: A string, e.g. '{name}-foo.txt' :type fmat_string: ``str`` :return: The string formatted according to this instance. E.g. 'production-runtime-foo...
def remove_available_work_units(self, work_spec_name, work_unit_names): '''Remove some work units in the available queue. If `work_unit_names` is :const:`None` (which must be passed explicitly), all available work units in `work_spec_name` are removed; otherwise only the specific named ...
Remove some work units in the available queue. If `work_unit_names` is :const:`None` (which must be passed explicitly), all available work units in `work_spec_name` are removed; otherwise only the specific named work units will be. :param str work_spec_name: name of the work spec ...
def resolve(self, _): """ Resolve given variable """ if self.default_value == DUMMY_VALUE: if self.name in os.environ: return os.environ[self.name] else: raise VelException(f"Undefined environment variable: {self.name}") else: r...
Resolve given variable
def transform_paragraph(self, paragraph, epochs=50, ignore_missing=False): """ Transform an iterable of tokens into its vector representation (a paragraph vector). Experimental. This will return something close to a tf-idf weighted average of constituent token vectors by fitting...
Transform an iterable of tokens into its vector representation (a paragraph vector). Experimental. This will return something close to a tf-idf weighted average of constituent token vectors by fitting rare words (with low word bias values) more closely.
def get_contract_from_name(self, contract_name): """ Return a contract from a name Args: contract_name (str): name of the contract Returns: Contract """ return next((c for c in self.contracts if c.name == contract_name), None)
Return a contract from a name Args: contract_name (str): name of the contract Returns: Contract
def resolve_dynamic_values(env): """ Resolve dynamic values inside need data. Rough workflow: #. Parse all needs and their data for a string like [[ my_func(a,b,c) ]] #. Extract function name and call parameters #. Execute registered function name with extracted call parameters #. Replace ...
Resolve dynamic values inside need data. Rough workflow: #. Parse all needs and their data for a string like [[ my_func(a,b,c) ]] #. Extract function name and call parameters #. Execute registered function name with extracted call parameters #. Replace original string with return value :param...
def grid(children=[], sizing_mode=None, nrows=None, ncols=None): """ Conveniently create a grid of layoutable objects. Grids are created by using ``GridBox`` model. This gives the most control over the layout of a grid, but is also tedious and may result in unreadable code in practical applications...
Conveniently create a grid of layoutable objects. Grids are created by using ``GridBox`` model. This gives the most control over the layout of a grid, but is also tedious and may result in unreadable code in practical applications. ``grid()`` function remedies this by reducing the level of control, but...
def status(self, event): """An anonymous client wants to know if we're open for enrollment""" self.log('Registration status requested') response = { 'component': 'hfos.enrol.enrolmanager', 'action': 'status', 'data': self.config.allow_registration } ...
An anonymous client wants to know if we're open for enrollment
def _broker_exit(self): """ Forcefully call :meth:`Stream.on_disconnect` on any streams that failed to shut down gracefully, then discard the :class:`Poller`. """ for _, (side, _) in self.poller.readers + self.poller.writers: LOG.debug('_broker_main() force disconnect...
Forcefully call :meth:`Stream.on_disconnect` on any streams that failed to shut down gracefully, then discard the :class:`Poller`.
def _etree_py26_write(f, tree): """ Compatibility workaround for ElementTree shipped with py2.6 """ f.write("<?xml version='1.0' encoding='utf-8'?>\n".encode('utf-8')) if etree.VERSION[:3] == '1.2': def fixtag(tag, namespaces): if tag == XML_NS + 'lang': return '...
Compatibility workaround for ElementTree shipped with py2.6
def normalized(self): """Return a normalized version of the histogram where the values sum to one. """ total = self.total() result = Histogram() for value, count in iteritems(self): try: result[value] = count / float(total) except ...
Return a normalized version of the histogram where the values sum to one.
def count_nulls(self, field): """ Count the number of null values in a column """ try: n = self.df[field].isnull().sum() except KeyError: self.warning("Can not find column", field) return except Exception as e: self.err(e, "...
Count the number of null values in a column
def logged_exec(cmd): """Execute a command, redirecting the output to the log.""" logger = logging.getLogger('fades.exec') logger.debug("Executing external command: %r", cmd) p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) stdout = [] ...
Execute a command, redirecting the output to the log.
def definitions_help(): """Help message for Definitions. .. versionadded:: 4.0.0 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(content()) return me...
Help message for Definitions. .. versionadded:: 4.0.0 :returns: A message object containing helpful information. :rtype: messaging.message.Message
def get_redis_connection(config, use_strict_redis=False): """ Returns a redis connection from a connection config """ redis_cls = redis.StrictRedis if use_strict_redis else redis.Redis if 'URL' in config: return redis_cls.from_url(config['URL'], db=config.get('DB')) if 'USE_REDIS_CACHE...
Returns a redis connection from a connection config
def collect(self, cert_id, format_type): """ Poll for certificate availability after submission. :param int cert_id: The certificate ID :param str format_type: The format type to use (example: 'X509 PEM Certificate only') :return: The certificate_id or the certificate depending ...
Poll for certificate availability after submission. :param int cert_id: The certificate ID :param str format_type: The format type to use (example: 'X509 PEM Certificate only') :return: The certificate_id or the certificate depending on whether the certificate is ready (check status code) ...
def debug(self, *debugReqs): """send a debug command to control the game state's setup""" return self._client.send(debug=sc2api_pb2.RequestDebug(debug=debugReqs))
send a debug command to control the game state's setup
def port_profile_qos_profile_qos_cos(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") name_key = ET.SubElement(port_profile, "name") name_key.t...
Auto Generated Code
def generate_keypair(curve='secp160r1', randfunc=None): """ Convenience function to generate a random new keypair (passphrase, pubkey). """ if randfunc is None: randfunc = Crypto.Random.new().read curve = Curve.by_name(curve) raw_privkey = randfunc(curve.order_len_bin) privkey = seri...
Convenience function to generate a random new keypair (passphrase, pubkey).
def _tarboton_slopes_directions(self, data, dX, dY): """ Calculate the slopes and directions based on the 8 sections from Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf """ return _tarboton_slopes_directions(data, dX, dY, ...
Calculate the slopes and directions based on the 8 sections from Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf
def get_colmin(data): """ Get rowwise column names with minimum values :param data: pandas dataframe """ data=data.T colmins=[] for col in data: colmins.append(data[col].idxmin()) return colmins
Get rowwise column names with minimum values :param data: pandas dataframe
def clean_column_values(df, inplace=True): r""" Convert dollar value strings, numbers with commas, and percents into floating point values >>> df = get_data('us_gov_deficits_raw') >>> df2 = clean_column_values(df, inplace=False) >>> df2.iloc[0] Fiscal year ...
r""" Convert dollar value strings, numbers with commas, and percents into floating point values >>> df = get_data('us_gov_deficits_raw') >>> df2 = clean_column_values(df, inplace=False) >>> df2.iloc[0] Fiscal year 10/2017-3/2018 Presiden...
def do_login(self, line): "login aws-acces-key aws-secret" if line: args = self.getargs(line) self.connect(args[0], args[1]) else: self.connect() self.do_tables('')
login aws-acces-key aws-secret
def _prepare_connection(**kwargs): ''' Prepare the connection with the remote network device, and clean up the key value pairs, removing the args used for the connection init. ''' init_args = {} fun_kwargs = {} netmiko_kwargs = __salt__['config.get']('netmiko', {}) netmiko_kwargs.update(...
Prepare the connection with the remote network device, and clean up the key value pairs, removing the args used for the connection init.
def GET_query(self, req_hook, req_args): ''' Generic GET query method ''' # GET request methods only require sessionTokens headers = {'content-type': 'application/json', 'sessionToken': self.__session__} # HTTP GET query method using requests module try: ...
Generic GET query method
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_port_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface output = ET.SubElement(fcoe_get_interface, "output"...
Auto Generated Code
def insert(self, fields, values): ''' insert new db entry :param fields: list of fields to insert :param values: list of values to insert :return: row id of the new row ''' if fields: _fields = ' (%s) ' % ','.join(fields) else: _fi...
insert new db entry :param fields: list of fields to insert :param values: list of values to insert :return: row id of the new row
def read(cls, five9, external_id): """Return a record singleton for the ID. Args: five9 (five9.Five9): The authenticated Five9 remote. external_id (mixed): The identified on Five9. This should be the value that is in the ``__uid_field__`` field on the record. ...
Return a record singleton for the ID. Args: five9 (five9.Five9): The authenticated Five9 remote. external_id (mixed): The identified on Five9. This should be the value that is in the ``__uid_field__`` field on the record. Returns: BaseModel: The reco...
def get_by_id(self, id_networkv4): """Get IPv4 network :param id_networkv4: ID for NetworkIPv4 :return: IPv4 Network """ uri = 'api/networkv4/%s/' % id_networkv4 return super(ApiNetworkIPv4, self).get(uri)
Get IPv4 network :param id_networkv4: ID for NetworkIPv4 :return: IPv4 Network
def resolve_admin_type(admin): """Determine admin type.""" if admin is current_user or isinstance(admin, UserMixin): return 'User' else: return admin.__class__.__name__
Determine admin type.
def convert_general(value): """Take a python object and convert it to the format Imgur expects.""" if isinstance(value, bool): return "true" if value else "false" elif isinstance(value, list): value = [convert_general(item) for item in value] value = convert_to_imgur_list(value) ...
Take a python object and convert it to the format Imgur expects.
def rpc_get_name_DID(self, name, **con_info): """ Given a name or subdomain, return its DID. """ did_info = None if check_name(name): did_info = self.get_name_DID_info(name) elif check_subdomain(name): did_info = self.get_subdomain_DID_info(name) ...
Given a name or subdomain, return its DID.
def set_loader(self, loader, destructor, state): """ Override the default disk loader with a custom loader fn. """ return lib.zcertstore_set_loader(self._as_parameter_, loader, destructor, state)
Override the default disk loader with a custom loader fn.
def syllabify(self, unsyllabified_tokens): """Helper class for calling syllabification-related methods. :param unsyllabified_tokens: :return: List of syllables. :rtype : list """ syllables = self.make_syllables(unsyllabified_tokens) qu_fixed_syllables = self._qu_f...
Helper class for calling syllabification-related methods. :param unsyllabified_tokens: :return: List of syllables. :rtype : list
def within_rupture_distance(self, surface, distance, **kwargs): ''' Select events within a rupture distance from a fault surface :param surface: Fault surface as instance of nhlib.geo.surface.base.BaseSurface :param float distance: Rupture distance (km) ...
Select events within a rupture distance from a fault surface :param surface: Fault surface as instance of nhlib.geo.surface.base.BaseSurface :param float distance: Rupture distance (km) :returns: Instance of :class:`openquake.hmtk.seismicity.catalogue.Catal...
def _get_param_names(cls): """Get parameter names for the estimator""" # fetch the constructor or the original constructor before # deprecation wrapping if any init = getattr(cls.__init__, 'deprecated_original', cls.__init__) if init is object.__init__: # No explicit ...
Get parameter names for the estimator
def _handle_relation(self, tokens: ParseResults) -> str: """Handle a relation.""" subject_node_dsl = self.ensure_node(tokens[SUBJECT]) object_node_dsl = self.ensure_node(tokens[OBJECT]) subject_modifier = modifier_po_to_dict(tokens[SUBJECT]) object_modifier = modifier_po_to_dict...
Handle a relation.
def extract_env(self): '''extract the environment from the manifest, or return None. Used by functions env_extract_image, and env_extract_tar ''' environ = self._get_config('Env') if environ is not None: if not isinstance(environ, list): environ = [environ] lines = []...
extract the environment from the manifest, or return None. Used by functions env_extract_image, and env_extract_tar
def _get_resource_id_from_stack(cfn_client, stack_name, logical_id): """ Given the LogicalID of a resource, call AWS CloudFormation to get physical ID of the resource within the specified stack. Parameters ---------- cfn_client CloudFormation client provided ...
Given the LogicalID of a resource, call AWS CloudFormation to get physical ID of the resource within the specified stack. Parameters ---------- cfn_client CloudFormation client provided by AWS SDK stack_name : str Name of the stack to query logi...
def owner(self, owner): """ Sets the owner of this OauthTokenReference. User name of the owner of the OAuth token within data.world. :param owner: The owner of this OauthTokenReference. :type: str """ if owner is None: raise ValueError("Invalid value ...
Sets the owner of this OauthTokenReference. User name of the owner of the OAuth token within data.world. :param owner: The owner of this OauthTokenReference. :type: str
def jinja_env(template_path): """Sets up our Jinja environment, loading the few filters we have""" fs_loader = FileSystemLoader(os.path.dirname(template_path)) env = Environment(loader=fs_loader, autoescape=True, trim_blocks=True, lstrip_bloc...
Sets up our Jinja environment, loading the few filters we have
def check_local() -> None: """ Verify required directories exist. This functions checks the current working directory to ensure that the required directories exist. If they do not exist, it will create them. """ to_check = ['./replay', './replay/toDo', './replay/archive'] for i in to_check...
Verify required directories exist. This functions checks the current working directory to ensure that the required directories exist. If they do not exist, it will create them.
def get_desktop_size(self): """Get the size of the desktop display""" _ptr = ffi.new('SDL_DisplayMode *') check_int_err(lib.SDL_GetDesktopDisplayMode(self._index, _ptr)) return (_ptr.w, _ptr.h)
Get the size of the desktop display
def export_trials_data(args): """export experiment metadata to csv """ nni_config = Config(get_config_filename(args)) rest_port = nni_config.get_config('restServerPort') rest_pid = nni_config.get_config('restServerPid') if not detect_process(rest_pid): print_error('Experiment is not runn...
export experiment metadata to csv
def reopen(self, file_obj): """Reopen the file-like object in a safe manner.""" file_obj.open('U') if sys.version_info[0] <= 2: return file_obj else: return codecs.getreader('utf-8')(file_obj)
Reopen the file-like object in a safe manner.
def p2x(self, p): """ Map parameters ``p`` to vector in x-space. x-space is a vector space of dimension ``p.size``. Its axes are in the directions specified by the eigenvectors of ``p``'s covariance matrix, and distance along an axis is in units of the standard deviation in that...
Map parameters ``p`` to vector in x-space. x-space is a vector space of dimension ``p.size``. Its axes are in the directions specified by the eigenvectors of ``p``'s covariance matrix, and distance along an axis is in units of the standard deviation in that direction.
def checkfilesexist(self, on_missing="warn"): ''' Runs through the entries of the Cache() object and checks each entry if the file which it points to exists or not. If the file does exist then it adds the entry to the Cache() object containing found files, otherwise it adds the entry to the Cache() object co...
Runs through the entries of the Cache() object and checks each entry if the file which it points to exists or not. If the file does exist then it adds the entry to the Cache() object containing found files, otherwise it adds the entry to the Cache() object containing all entries that are missing. It returns b...
def _match_vcs_scheme(url): # type: (str) -> Optional[str] """Look for VCS schemes in the URL. Returns the matched VCS scheme, or None if there's no match. """ from pipenv.patched.notpip._internal.vcs import VcsSupport for scheme in VcsSupport.schemes: if url.lower().startswith(scheme) ...
Look for VCS schemes in the URL. Returns the matched VCS scheme, or None if there's no match.
def query(self, query_samples): """ Query docs with query_samples number of Gibbs sampling iterations. """ self.sampled_topics = np.zeros((self.samples, self.N), dtype=np.int) for s in range(self.samples): ...
Query docs with query_samples number of Gibbs sampling iterations.
def layout_(self, chart_objs, cols=3): """ Returns a Holoview Layout from chart objects """ try: return hv.Layout(chart_objs).cols(cols) except Exception as e: self.err(e, self.layout_, "Can not build layout")
Returns a Holoview Layout from chart objects
def is_suitable(self, request): """ Checks if key is suitable for given request according to key type and request's user agent. """ if self.key_type: validation = KEY_TYPE_VALIDATIONS.get( self.get_type() ) return validation( request ) if validation else None ...
Checks if key is suitable for given request according to key type and request's user agent.
def get_diff(self, commit, other_commit): """Calculates total additions and deletions :param commit: First commit :param other_commit: Second commit :return: dictionary: Dictionary with total additions and deletions """ print(other_commit, "VS", commit) diff = se...
Calculates total additions and deletions :param commit: First commit :param other_commit: Second commit :return: dictionary: Dictionary with total additions and deletions
def generate_semantic_data_key(used_semantic_keys): """ Create a new and unique semantic data key :param list used_semantic_keys: Handed list of keys already in use :rtype: str :return: semantic_data_id """ semantic_data_id_counter = -1 while True: semantic_data_id_counter += 1 ...
Create a new and unique semantic data key :param list used_semantic_keys: Handed list of keys already in use :rtype: str :return: semantic_data_id
def _parse_prop(self, dd, row): """ :param dd: datadict :param _row: (tablename, row) :return: """ key = row['name'] if key.startswith('#'): deprecated = True else: deprecated = False v = dd.get(key) _value = self._g...
:param dd: datadict :param _row: (tablename, row) :return:
def get_sdc_by_name(self, name): """ Get ScaleIO SDC object by its name :param name: Name of SDC :return: ScaleIO SDC object :raise KeyError: No SDC with specified name found :rtype: SDC object """ for sdc in self.sdc: if sdc.name == name: ...
Get ScaleIO SDC object by its name :param name: Name of SDC :return: ScaleIO SDC object :raise KeyError: No SDC with specified name found :rtype: SDC object
def unregister_finders(): """Unregister finders necessary for PEX to function properly.""" global __PREVIOUS_FINDER if not __PREVIOUS_FINDER: return pkg_resources.register_finder(zipimport.zipimporter, __PREVIOUS_FINDER) _remove_finder(pkgutil.ImpImporter, find_wheels_on_path) if importlib_machinery ...
Unregister finders necessary for PEX to function properly.
def update_log(self, *args, **kwargs): """Pass through to provider LogAdminSession.update_log""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.update_bin # OSID spec does not require returning updated catalog return Log( self._provider_mana...
Pass through to provider LogAdminSession.update_log
def QA_fetch_financial_report_adv(code, start, end=None, ltype='EN'): """高级财务查询接口 Arguments: code {[type]} -- [description] start {[type]} -- [description] Keyword Arguments: end {[type]} -- [description] (default: {None}) """ if end is None: return QA_DataStruct_Fi...
高级财务查询接口 Arguments: code {[type]} -- [description] start {[type]} -- [description] Keyword Arguments: end {[type]} -- [description] (default: {None})
def get_metrics(self, reset: bool = False) -> Dict[str, float]: """ We track three metrics here: 1. dpd_acc, which is the percentage of the time that our best output action sequence is in the set of action sequences provided by DPD. This is an easy-to-compute lower bound ...
We track three metrics here: 1. dpd_acc, which is the percentage of the time that our best output action sequence is in the set of action sequences provided by DPD. This is an easy-to-compute lower bound on denotation accuracy for the set of examples where we actually have DPD outp...
def add_to_obj(obj, dictionary, objs=None, exceptions=None, verbose=0): """ Cycles through a dictionary and adds the key-value pairs to an object. :param obj: :param dictionary: :param exceptions: :param verbose: :return: """ if exceptions is None: exceptions = [] for it...
Cycles through a dictionary and adds the key-value pairs to an object. :param obj: :param dictionary: :param exceptions: :param verbose: :return:
def set_field(self, field_name, data): """Set property into the Dataset. Parameters ---------- field_name : string The field name of the information. data : list, numpy 1-D array, pandas Series or None The array of data to be set. Returns ...
Set property into the Dataset. Parameters ---------- field_name : string The field name of the information. data : list, numpy 1-D array, pandas Series or None The array of data to be set. Returns ------- self : Dataset Datase...
def run(self): """ Call this function at the end of your class's `__init__` function. """ stderr = os.path.abspath(os.path.join(self.outdir, self.name + '.log')) if self.pipe: self.args += ('|', self.pipe, '2>>'+stderr) if self.gzip: self.args +=...
Call this function at the end of your class's `__init__` function.
def hold(model: Model, reducer: Optional[Callable] = None) -> Iterator[list]: """Temporarilly withold change events in a modifiable list. All changes that are captured within a "hold" context are forwarded to a list which is yielded to the user before being sent to views of the given ``model``. If desi...
Temporarilly withold change events in a modifiable list. All changes that are captured within a "hold" context are forwarded to a list which is yielded to the user before being sent to views of the given ``model``. If desired, the user may modify the list of events before the context is left in order t...
def _parse(self, stream, context, path): """Parse until a given byte string is found.""" objs = [] while True: start = stream.tell() test = stream.read(len(self.find)) stream.seek(start) if test == self.find: break else:...
Parse until a given byte string is found.
def dwelling_type(self): """ This method returns the dwelling type. :return: """ try: if self._data_from_search: info = self._data_from_search.find( 'ul', {"class": "info"}).text s = info.split('|') r...
This method returns the dwelling type. :return:
def _ppf(self, uloc, dist, length, cache): """ Point percentile function. Example: >>> print(chaospy.Iid(chaospy.Uniform(0, 2), 2).inv( ... [[0.1, 0.2, 0.3], [0.2, 0.2, 0.3]])) [[0.2 0.4 0.6] [0.4 0.4 0.6]] """ output = evalua...
Point percentile function. Example: >>> print(chaospy.Iid(chaospy.Uniform(0, 2), 2).inv( ... [[0.1, 0.2, 0.3], [0.2, 0.2, 0.3]])) [[0.2 0.4 0.6] [0.4 0.4 0.6]]
def unzoom(self, full=False, delay_draw=False): """unzoom display 1 level or all the way""" if full: self.zoom_lims = self.zoom_lims[:1] self.zoom_lims = [] elif len(self.zoom_lims) > 0: self.zoom_lims.pop() self.set_viewlimits() if not delay_d...
unzoom display 1 level or all the way
async def pin_6_pwm_128(my_board): """ Set digital pin 6 as a PWM output and set its output value to 128 @param my_board: A PymataCore instance @return: No Return Value """ # set the pin mode await my_board.set_pin_mode(6, Constants.PWM) # set the pin to 128 await my_board.analog_wr...
Set digital pin 6 as a PWM output and set its output value to 128 @param my_board: A PymataCore instance @return: No Return Value
def prep_vectors_for_gradient(nest_coefs, index_coefs, design, choice_vec, rows_to_obs, rows_to_nests, *args, ...
Parameters ---------- nest_coefs : 1D or 2D ndarray. All elements should by ints, floats, or longs. If 1D, should have 1 element for each nesting coefficient being estimated. If 2D, should have 1 column for each set of nesting coefficients being used to predict the probabilities ...
def enter_cli_mode(self): """Check if at shell prompt root@ and go into CLI.""" delay_factor = self.select_delay_factor(delay_factor=0) count = 0 cur_prompt = "" while count < 50: self.write_channel(self.RETURN) time.sleep(0.1 * delay_factor) c...
Check if at shell prompt root@ and go into CLI.
def _insert_breathe_configs(c, *, project_name, doxygen_xml_dirname): """Add breathe extension configurations to the state. """ if doxygen_xml_dirname is not None: c['breathe_projects'] = {project_name: doxygen_xml_dirname} c['breathe_default_project'] = project_name return c
Add breathe extension configurations to the state.
def make_model(self, grounding_ontology='UN', grounding_threshold=None): """Return a networkx MultiDiGraph representing a causal analysis graph. Parameters ---------- grounding_ontology : Optional[str] The ontology from which the grounding should be taken (e.g. U...
Return a networkx MultiDiGraph representing a causal analysis graph. Parameters ---------- grounding_ontology : Optional[str] The ontology from which the grounding should be taken (e.g. UN, FAO) grounding_threshold : Optional[float] Minimum threshold ...