Dataset Viewer
Auto-converted to Parquet Duplicate
positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def get_original_function_name(self, line, col, minified_name, minified_source): """Given a token location and a minified function name and the minified source file this returns the original function name if it can be found of the minified function in scope. ...
Given a token location and a minified function name and the minified source file this returns the original function name if it can be found of the minified function in scope.
def get_mac_address_table_input_request_type_get_interface_based_request_mac_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_mac_address_table = ET.Element("get_mac_address_table") config = get_mac_address_table input = ET.SubElement(get...
Auto Generated Code
def update_views(self): """Update stats views.""" # Call the father's method super(Plugin, self).update_views() # Add specifics informations # Alert and log self.views['used']['decoration'] = self.get_alert_log(self.stats['used'], maximum=self.stats['total'])
Update stats views.
def contains_geometric_info(var): """ Check whether the passed variable is a tuple with two floats or integers """ return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)
Check whether the passed variable is a tuple with two floats or integers
def save_plain_image_as_file(self, filepath, format='png', quality=90): """Used for generating thumbnails. Does not include overlaid graphics. """ pixbuf = self.get_plain_image_as_pixbuf() options, values = [], [] if format == 'jpeg': options.append('quality'...
Used for generating thumbnails. Does not include overlaid graphics.
def simxClearFloatSignal(clientID, signalName, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' if (sys.version_info[0] == 3) and (type(signalName) is str): signalName=signalName.encode('utf-8') return c_ClearFloatSignal(clientID,...
Please have a look at the function description/documentation in the V-REP user manual
def find_matches(self, content, file_to_handle): """Find all matches of an expression in a file """ # look for all match groups in the content groups = [match.groupdict() for match in self.match_expression.finditer(content)] # filter out content not in the match...
Find all matches of an expression in a file
def create(self): """Creates a token It uses the app_name as the notes and the scopes are the permissions required by the application. See those in github when configuring an app token Raises a TFARequired if a two factor is required after the atempt to create it withou...
Creates a token It uses the app_name as the notes and the scopes are the permissions required by the application. See those in github when configuring an app token Raises a TFARequired if a two factor is required after the atempt to create it without having call tfa before
def combine_pyramid_and_save(g_video, orig_video, enlarge_multiple, fps, save_filename='media/output.avi'): """Combine a gaussian video representation with the original and save to file""" width, height = get_frame_dimensions(orig_video[0]) fourcc = cv2.VideoWriter_fourcc(*'MJPG') print("Outputting to %...
Combine a gaussian video representation with the original and save to file
def PintPars(datablock, araiblock, zijdblock, start, end, accept, **kwargs): """ calculate the paleointensity magic parameters make some definitions """ if 'version' in list(kwargs.keys()) and kwargs['version'] == 3: meth_key = 'method_codes' beta_key = 'int_b_beta' temp_key, m...
calculate the paleointensity magic parameters make some definitions
def epcrparse(self): """ Parse the ePCR text file outputs """ logging.info('Parsing ePCR results') for sample in self.metadata: if sample.general.bestassemblyfile != 'NA': if 'stx' in sample.general.datastore: # Initialise count - t...
Parse the ePCR text file outputs
def get_pointgroup(rotations): """Return point group in international table symbol and number. The symbols are mapped to the numbers as follows: 1 "1 " 2 "-1 " 3 "2 " 4 "m " 5 "2/m " 6 "222 " 7 "mm2 " 8 "mmm " 9 "4 " 10 "-4 " 11...
Return point group in international table symbol and number. The symbols are mapped to the numbers as follows: 1 "1 " 2 "-1 " 3 "2 " 4 "m " 5 "2/m " 6 "222 " 7 "mm2 " 8 "mmm " 9 "4 " 10 "-4 " 11 "4/m " 12 "422 " 13 "4mm...
def start(self): """ starts a Pyro4 nameserver in a separate thread Returns ------- tuple (str, int): the host name and the used port """ if self.host is None: if self.nic_name is None: self.host = 'localhost' else: self.host = nic_name_to_host(self.nic_name) uri, self.pyro_ns,...
starts a Pyro4 nameserver in a separate thread Returns ------- tuple (str, int): the host name and the used port
def grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """ self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) ...
Let the tree grow. Args: times (integer): Indicate how many times the tree will grow.
def kernel_integrity(attrs=None, where=None): ''' Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_integrity', attrs=at...
Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity
def virtualenv(self, virtualenv): ''' Sets the virtual environment for the lambda package If this is not set then package_dependencies will create a new one. Takes a path to a virtualenv or a boolean if the virtualenv creation should be skipped. ''' # If a boole...
Sets the virtual environment for the lambda package If this is not set then package_dependencies will create a new one. Takes a path to a virtualenv or a boolean if the virtualenv creation should be skipped.
def _insert_stmt(self, name, value, timestamp, interval, config): '''Helper to generate the insert statement.''' # Calculate the TTL and abort if inserting into the past expire, ttl = config['expire'], config['ttl'](timestamp) if expire and not ttl: return None i_time = config['i_calc'].to_bu...
Helper to generate the insert statement.
def _determine_dialect(self, lines): """ Expects a non-empty [] of strings; these would normally be the first few lines of a csv file. Returns the most likely Dialect named tuple or None if the data seems to form a single column. Ensures that using the returned dialect, all the lines given will have the sa...
Expects a non-empty [] of strings; these would normally be the first few lines of a csv file. Returns the most likely Dialect named tuple or None if the data seems to form a single column. Ensures that using the returned dialect, all the lines given will have the same number of columns. Helper for the get_d...
def compute_dominance_frontier(graph, domtree): """ Compute a dominance frontier based on the given post-dominator tree. This implementation is based on figure 2 of paper An Efficient Method of Computing Static Single Assignment Form by Ron Cytron, etc. :param graph: The graph where we want to c...
Compute a dominance frontier based on the given post-dominator tree. This implementation is based on figure 2 of paper An Efficient Method of Computing Static Single Assignment Form by Ron Cytron, etc. :param graph: The graph where we want to compute the dominance frontier. :param domtree: The domin...
def isNumber(self, value): """ Validate whether a value is a number or not """ try: str(value) float(value) return True except ValueError: return False
Validate whether a value is a number or not
def survival_table_from_events( death_times, event_observed, birth_times=None, columns=["removed", "observed", "censored", "entrance", "at_risk"], weights=None, collapse=False, intervals=None, ): # pylint: disable=dangerous-default-value,too-many-locals """ Parameters ----------...
Parameters ---------- death_times: (n,) array represent the event times event_observed: (n,) array 1 if observed event, 0 is censored event. birth_times: a (n,) array, optional representing when the subject was first observed. A subject's death event is then at [birth times + duration ...
def render(self, context, instance, placeholder): """ Update the context with plugin's data """ context = super(CMSRandomEntriesPlugin, self).render( context, instance, placeholder) context['template_to_render'] = (str(instance.template_to_render) or ...
Update the context with plugin's data
def SaveGallery(self, name=None, items=None): """Use this to update the gallery name or change sort order. Specify which attribute (name or items or both) you want to change.""" url = 'http://min.us/api/SaveGallery' if not name: if not self.name: name = self...
Use this to update the gallery name or change sort order. Specify which attribute (name or items or both) you want to change.
def setup_logging(filename, log_dir=None, force_setup=False): ''' Try to load logging configuration from a file. Set level to INFO if failed. ''' if not force_setup and ChirpCLI.SETUP_COMPLETED: logging.debug("Master logging has been setup. This call will be ignored.") return if log_dir ...
Try to load logging configuration from a file. Set level to INFO if failed.
def name(self): '''Returns the name of this template (if created from a file) or "string" if not''' if self.mako_template.filename: return os.path.basename(self.mako_template.filename) return 'string'
Returns the name of this template (if created from a file) or "string" if not
def forward(self, X): """Forward function. :param X: The input (batch) of the model contains word sequences for lstm, features and feature weights. :type X: For word sequences: a list of torch.Tensor pair (word sequence and word mask) of shape (batch_size, sequence_lengt...
Forward function. :param X: The input (batch) of the model contains word sequences for lstm, features and feature weights. :type X: For word sequences: a list of torch.Tensor pair (word sequence and word mask) of shape (batch_size, sequence_length). For features: tor...
def CountFlowResultsByType(self, client_id, flow_id, cursor=None): """Returns counts of flow results grouped by result type.""" query = ("SELECT type, COUNT(*) FROM flow_results " "FORCE INDEX (flow_results_by_client_id_flow_id_timestamp) " "WHERE client_id = %s AND flow_id = %s " ...
Returns counts of flow results grouped by result type.
def _ProcessGrepSource(self, source): """Find files fulfilling regex conditions.""" attributes = source.base_source.attributes paths = artifact_utils.InterpolateListKbAttributes( attributes["paths"], self.knowledge_base, self.ignore_interpolation_errors) regex = utils.RegexListDisjunctio...
Find files fulfilling regex conditions.
def manage_extant(self, **kwargs): '''Manage an existing cluster :param kwargs: dict -- keyword args in dict ''' self._check_device_number(kwargs['devices']) self.trust_domain = TrustDomain( devices=kwargs['devices'], partition=kwargs['device_group_parti...
Manage an existing cluster :param kwargs: dict -- keyword args in dict
def _GetFlagsDefinedByModule(self, module): """Returns the list of flags defined by a module. Args: module: A module object or a module name (a string). Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this...
Returns the list of flags defined by a module. Args: module: A module object or a module name (a string). Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object.
def get_labs(format): """Gets Hackerspaces data from hackaday.io.""" hackerspaces_json = data_from_hackaday_io(hackaday_io_labs_map_url) hackerspaces = {} # Load all the Hackerspaces for i in hackerspaces_json: current_lab = Hackerspace() current_lab.id = i["id"] current_la...
Gets Hackerspaces data from hackaday.io.
def upload(ctx): """Upload files to Azure Storage""" settings.add_cli_options(ctx.cli_options, settings.TransferAction.Upload) ctx.initialize(settings.TransferAction.Upload) specs = settings.create_upload_specifications( ctx.cli_options, ctx.config) del ctx.cli_options for spec in specs:...
Upload files to Azure Storage
def get_assignable_bin_ids(self, bin_id): """Gets a list of bins including and under the given bin node in which any resource can be assigned. arg: bin_id (osid.id.Id): the ``Id`` of the ``Bin`` return: (osid.id.IdList) - list of assignable bin ``Ids`` raise: NullArgument - ``bin_id...
Gets a list of bins including and under the given bin node in which any resource can be assigned. arg: bin_id (osid.id.Id): the ``Id`` of the ``Bin`` return: (osid.id.IdList) - list of assignable bin ``Ids`` raise: NullArgument - ``bin_id`` is ``null`` raise: OperationFailed - unab...
def check(self): """ Check that this table is complete, that is, every character of this table can be followed by a new character. :return: True if the table is complete, False otherwise. """ for character, followers in self.items(): for follower in followers...
Check that this table is complete, that is, every character of this table can be followed by a new character. :return: True if the table is complete, False otherwise.
def get_neutron_endpoint(cls, json_resp): """ Parse the service catalog returned by the Identity API for an endpoint matching the Neutron service Sends a CRITICAL service check when none are found registered in the Catalog """ catalog = json_resp.get('token', {}).get('catalog', [...
Parse the service catalog returned by the Identity API for an endpoint matching the Neutron service Sends a CRITICAL service check when none are found registered in the Catalog
def validate_json_schema(self): """Validate the JSON schema. Return list of errors.""" errors = [] for work in self: for task in work: if not task.get_results().validate_json_schema(): errors.append(task) if not work.get_results().vali...
Validate the JSON schema. Return list of errors.
def getRnaQuantificationSetByName(self, name): """ Returns the RnaQuantification set with the specified name, or raises an exception otherwise. """ if name not in self._rnaQuantificationSetNameMap: raise exceptions.RnaQuantificationSetNameNotFoundException(name) ...
Returns the RnaQuantification set with the specified name, or raises an exception otherwise.
def _create_modulename(cdef_sources, source, sys_version): """ This is the same as CFFI's create modulename except we don't include the CFFI version. """ key = '\x00'.join([sys_version[:3], source, cdef_sources]) key = key.encode('utf-8') k1 = hex(binascii.crc32(key[0::2]) & 0xffffffff) ...
This is the same as CFFI's create modulename except we don't include the CFFI version.
def populate_table(self, scenario_directory): """ Populate table with files from scenario_directory directory. :param scenario_directory: Path where .txt & .py reside. :type scenario_directory: QString """ parsed_files = [] unparsed_files = [] self.table.clearCon...
Populate table with files from scenario_directory directory. :param scenario_directory: Path where .txt & .py reside. :type scenario_directory: QString
def logL(self, args): """ routine to compute X2 given variable parameters for a MCMC/PSO chain """ #extract parameters kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, kwargs_cosmo = self.param.args2kwargs(args) #generate image and computes likelihood sel...
routine to compute X2 given variable parameters for a MCMC/PSO chain
def log(row=None, commit=True, *args, **kargs): """Log a dict to the global run's history. If commit is false, enables multiple calls before commiting. Eg. wandb.log({'train-loss': 0.5, 'accuracy': 0.9}) """ if run is None: raise ValueError( "You must call `wandb.init` in the ...
Log a dict to the global run's history. If commit is false, enables multiple calls before commiting. Eg. wandb.log({'train-loss': 0.5, 'accuracy': 0.9})
def login(self, username, password, disableautosave=True, print_response=True): """ :param username: :param password: :param disableautosave: boolean :param print_response: print log if required :return: status code, response data """ if type(username) != ...
:param username: :param password: :param disableautosave: boolean :param print_response: print log if required :return: status code, response data
def detached(name): ''' Ensure zone is detached name : string name of the zone ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} zones = __salt__['zoneadm.list'](installed=True, configured=True) if name in zones: if zon...
Ensure zone is detached name : string name of the zone
def __query(self, query, tagid=None): """ Extracts nodes that match the query from the Response :param query: Xpath Expresion :type query: String :param tagid: Tag ID :type query: String :returns: The queried nodes :rtype: list """ if se...
Extracts nodes that match the query from the Response :param query: Xpath Expresion :type query: String :param tagid: Tag ID :type query: String :returns: The queried nodes :rtype: list
def wrap_deepmind(env, dim=84, framestack=True): """Configure environment for DeepMind-style Atari. Note that we assume reward clipping is done outside the wrapper. Args: dim (int): Dimension to resize observations to (dim x dim). framestack (bool): Whether to framestack observations. ...
Configure environment for DeepMind-style Atari. Note that we assume reward clipping is done outside the wrapper. Args: dim (int): Dimension to resize observations to (dim x dim). framestack (bool): Whether to framestack observations.
def _parse_reactome_association_file( self, file, limit=None, subject_prefix=None, object_prefix=None): """ Parse ensembl gene to reactome pathway file :param file: file path (not handle) :param limit: limit (int, optional) limit the number of rows processed :return: ...
Parse ensembl gene to reactome pathway file :param file: file path (not handle) :param limit: limit (int, optional) limit the number of rows processed :return: None
def build_prior(self, fmt="ascii",filename=None,droptol=None, chunk=None, sparse=False, sigma_range=6): """ build a prior parameter covariance matrix. Parameters ---------- fmt : str the format to save the cov matrix. Options are "ascii","binary"...
build a prior parameter covariance matrix. Parameters ---------- fmt : str the format to save the cov matrix. Options are "ascii","binary","uncfile", "coo". default is "ascii" filename : str the filename to save the prior cov matr...
def get_url_from (base_url, recursion_level, aggregate, parent_url=None, base_ref=None, line=0, column=0, page=0, name=u"", parent_content_type=None, extern=None): """ Get url data from given base data. @param base_url: base url from a link tag @type base_url: string...
Get url data from given base data. @param base_url: base url from a link tag @type base_url: string or None @param recursion_level: current recursion level @type recursion_level: number @param aggregate: aggregate object @type aggregate: aggregate.Consumer @param parent_url: parent url ...
def sendtoaddress(self, recv_addr, amount, comment=""): """send ammount to address, with optional comment. Returns txid. sendtoaddress(ADDRESS, AMMOUNT, COMMENT)""" return self.req("sendtoaddress", [recv_addr, amount, comment])
send ammount to address, with optional comment. Returns txid. sendtoaddress(ADDRESS, AMMOUNT, COMMENT)
def variable_summaries(var): """Attach a lot of summaries to a Tensor (for TensorBoard visualization).""" with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('mean', mean) with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) tf.summary...
Attach a lot of summaries to a Tensor (for TensorBoard visualization).
def _is_unique(self, name, path): """verify if there is a project with given name or path on the database """ project = None try: project = Project.select().where( (Project.name == name) | (Project.path == path) )[0] ...
verify if there is a project with given name or path on the database
def imagetransformer_cifar_tpu_range(rhp): """Range of hyperparameters for vizier.""" # After starting from base, set intervals for some parameters. rhp.set_float("learning_rate", 0.01, 1.0, scale=rhp.LOG_SCALE) rhp.set_discrete("num_decoder_layers", [8, 10, 12, 14, 16]) rhp.set_discrete("hidden_size", [256, ...
Range of hyperparameters for vizier.
def _wait_for_travis_build(url, commit, committed_at): """ Waits for a Travis build to appear with the given commit SHA """ print('Waiting for a Travis build to appear ' 'for `%s` after `%s`...' % (commit, committed_at)) import requests slug = _slug_from_url(url) start_time = time.time() ...
Waits for a Travis build to appear with the given commit SHA
def make_nameko_helper(config): """Create a fake module that provides some convenient access to nameko standalone functionality for interactive shell usage. """ module = ModuleType('nameko') module.__doc__ = """Nameko shell helper for making rpc calls and dispatching events. Usage: >>> n.rpc.se...
Create a fake module that provides some convenient access to nameko standalone functionality for interactive shell usage.
def add(self, name, value, showkey=None, before=None, preserve_spacing=True): """Add a parameter to the template with a given *name* and *value*. *name* and *value* can be anything parsable by :func:`.utils.parse_anything`; pipes and equal signs are automatically escaped fro...
Add a parameter to the template with a given *name* and *value*. *name* and *value* can be anything parsable by :func:`.utils.parse_anything`; pipes and equal signs are automatically escaped from *value* when appropriate. If *name* is already a parameter in the template, we'll replace ...
def register_transport_ready_event(self, user_cb, user_arg): """ Register for transport ready events. The `transport ready` event is raised via a user callback. If the endpoint is configured as a source, then the user may then call :py:meth:`write_transport` in order to send da...
Register for transport ready events. The `transport ready` event is raised via a user callback. If the endpoint is configured as a source, then the user may then call :py:meth:`write_transport` in order to send data to the associated sink. Otherwise, if the endpoint is configur...
def generate_anomaly(self, input_word, list_of_dict_words, num): """ Generate an anomaly. This is done via a Psuedo-random number generator. """ results = [] for i in range(0,num): index = randint(0,len(list_of_dict_words)-1) name = list_of_dict_words[ind...
Generate an anomaly. This is done via a Psuedo-random number generator.
def count(self): """ Returns the number of rows matched by this query """ if self._batch: raise CQLEngineException("Only inserts, updates, and deletes are available in batch mode") if self._result_cache is None: query = self._select_query() query.count = True...
Returns the number of rows matched by this query
def remove(self, interval): """ Removes an interval from the tree, if present. If not, raises ValueError. Completes in O(log n) time. """ #self.verify() if interval not in self: #print(self.all_intervals) raise ValueError self.top_...
Removes an interval from the tree, if present. If not, raises ValueError. Completes in O(log n) time.
def delete_model(self): """Deletes the Amazon SageMaker models backing this predictor. """ request_failed = False failed_models = [] for model_name in self._model_names: try: self.sagemaker_session.delete_model(model_name) except Exception...
Deletes the Amazon SageMaker models backing this predictor.
def assert_raises(expected_exception, extras=None, *args, **kwargs): """Assert that an exception is raised when a function is called. If no exception is raised, test fail. If an exception is raised but not of the expected type, the exception is let through. This should only be used as a context manage...
Assert that an exception is raised when a function is called. If no exception is raised, test fail. If an exception is raised but not of the expected type, the exception is let through. This should only be used as a context manager: with assert_raises(Exception): func() Args: ...
def _http_request(url, headers=None, data=None): ''' Make the HTTP request and return the body as python object. ''' if not headers: headers = _get_headers() session = requests.session() log.debug('Querying %s', url) req = session.post(url, ...
Make the HTTP request and return the body as python object.
def save_load(jid, load, minions=None): ''' Save the load to the specified jid ''' log.debug('sqlite3 returner <save_load> called jid: %s load: %s', jid, load) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''INSERT INTO jids (jid, load) VALUES (:jid, :load)''' cur.execute(sql, ...
Save the load to the specified jid
def get_presig(self, target, source, env, executor=None): """Return the signature contents of this action's command line. This strips $(-$) and everything in between the string, since those parts don't affect signatures. """ return self._generate(target, source, env, 1, executor...
Return the signature contents of this action's command line. This strips $(-$) and everything in between the string, since those parts don't affect signatures.
def getOverlayTransformAbsolute(self, ulOverlayHandle): """Gets the transform if it is absolute. Returns an error if the transform is some other type.""" fn = self.function_table.getOverlayTransformAbsolute peTrackingOrigin = ETrackingUniverseOrigin() pmatTrackingOriginToOverlayTransfor...
Gets the transform if it is absolute. Returns an error if the transform is some other type.
def spherical_to_cartesian(lons, lats, depths=None): """ Return the position vectors (in Cartesian coordinates) of list of spherical coordinates. For equations see: http://mathworld.wolfram.com/SphericalCoordinates.html. Parameters are components of spherical coordinates in a form of scalars, ...
Return the position vectors (in Cartesian coordinates) of list of spherical coordinates. For equations see: http://mathworld.wolfram.com/SphericalCoordinates.html. Parameters are components of spherical coordinates in a form of scalars, lists or numpy arrays. ``depths`` can be ``None`` in which case i...
def show_metrics(metrics, all_branches=False, all_tags=False): """ Args: metrics (list): Where each element is either a `list` if an xpath was specified, otherwise a `str` """ for branch, val in metrics.items(): if all_branches or all_tags: logger.info("{branch}:"...
Args: metrics (list): Where each element is either a `list` if an xpath was specified, otherwise a `str`
def monkeycache(apis): """ Feed this a dictionary of api bananas, it spits out processed cache """ if isinstance(type(apis), type(None)) or apis is None: return {} verbs = set() cache = {} cache['count'] = apis['count'] cache['asyncapis'] = [] apilist = apis['api'] if a...
Feed this a dictionary of api bananas, it spits out processed cache
def download_ftp_url(source_url, target_uri, buffer_size=8192): """Uses urllib. thread safe?""" ensure_file_directory(target_uri) with urllib.request.urlopen(source_url) as source_file: with open(target_uri, 'wb') as target_file: shutil.copyfileobj(source_file, target_file, buffer_size...
Uses urllib. thread safe?
def map_get(self, key, mapkey): """ Retrieve a value from a map. :param str key: The document ID :param str mapkey: Key within the map to retrieve :return: :class:`~.ValueResult` :raise: :exc:`IndexError` if the mapkey does not exist :raise: :cb_exc:`NotFoundErro...
Retrieve a value from a map. :param str key: The document ID :param str mapkey: Key within the map to retrieve :return: :class:`~.ValueResult` :raise: :exc:`IndexError` if the mapkey does not exist :raise: :cb_exc:`NotFoundError` if the document does not exist. .. seeal...
def set_lock_state(self, code, device_label, state): """ Lock or unlock Args: code (str): Lock code device_label (str): device label of lock state (str): 'lock' or 'unlock' """ response = None try: response = requests.put( ...
Lock or unlock Args: code (str): Lock code device_label (str): device label of lock state (str): 'lock' or 'unlock'
def to_event(self): """ get rid of id, sign, tunnel and update message type Notice: this method will return a deepcopy """ msg = copy.deepcopy(self) for _ in ["id", "sign", "tunnel", "query", "param"]: if not hasattr(msg, _): continue ...
get rid of id, sign, tunnel and update message type Notice: this method will return a deepcopy
def destructuring_stmt_handle(self, original, loc, tokens): """Process match assign blocks.""" internal_assert(len(tokens) == 2, "invalid destructuring assignment tokens", tokens) matches, item = tokens out = match_handle(loc, [matches, "in", item, None]) out += self.pattern_erro...
Process match assign blocks.
def knapsack_iterative_int(items, maxweight): r""" Iterative knapsack method Math: maximize \sum_{i \in T} v_i subject to \sum_{i \in T} w_i \leq W Notes: dpmat is the dynamic programming memoization matrix. dpmat[i, w] is the total value of the items with weight at mos...
r""" Iterative knapsack method Math: maximize \sum_{i \in T} v_i subject to \sum_{i \in T} w_i \leq W Notes: dpmat is the dynamic programming memoization matrix. dpmat[i, w] is the total value of the items with weight at most W T is idx_subset, the set of indicies i...
def rpc_get_names(self, filename, source, offset): """Get all possible names """ source = get_source(source) if hasattr(self.backend, "rpc_get_names"): return self.backend.rpc_get_names(filename, source, offset) else: raise Fault("get_names not implemente...
Get all possible names
def fetch_image(client, name): """ Fetch an image if it isn't already present. This works like ``docker pull`` and will pull the tag ``latest`` if no tag is specified in the image name. """ try: image = client.images.get(name) except docker.errors.ImageNotFound: name, tag = ...
Fetch an image if it isn't already present. This works like ``docker pull`` and will pull the tag ``latest`` if no tag is specified in the image name.
def update(self, **kwargs): """Call this to change the configuration of the service on the device. This method uses HTTP PUT to alter the service state on the device. The attributes of the instance will be packaged as a dictionary. That dictionary will be updated with kwargs. It is t...
Call this to change the configuration of the service on the device. This method uses HTTP PUT to alter the service state on the device. The attributes of the instance will be packaged as a dictionary. That dictionary will be updated with kwargs. It is then submitted as JSON to the de...
def binary_gas_search(state: BaseState, transaction: BaseTransaction, tolerance: int=1) -> int: """ Run the transaction with various gas limits, progressively approaching the minimum needed to succeed without an OutOfGas exception. The starting range of possible estimates is: [transaction.intrinsic...
Run the transaction with various gas limits, progressively approaching the minimum needed to succeed without an OutOfGas exception. The starting range of possible estimates is: [transaction.intrinsic_gas, state.gas_limit]. After the first OutOfGas exception, the range is: (largest_limit_out_of_gas, sta...
def read(self, entity=None, attrs=None, ignore=None, params=None): """Provide a default value for ``entity``. By default, ``nailgun.entity_mixins.EntityReadMixin.read provides a default value for ``entity`` like so:: entity = type(self)() However, :class:`ContentViewPuppet...
Provide a default value for ``entity``. By default, ``nailgun.entity_mixins.EntityReadMixin.read provides a default value for ``entity`` like so:: entity = type(self)() However, :class:`ContentViewPuppetModule` requires that an ``content_view`` be provided, so this techniq...
def get_samples_live_last(self, sensor_id): """Get the last sample recorded by the sensor. Args: sensor_id (string): hexadecimal id of the sensor to query, e.g. ``0x0013A20040B65FAD`` Returns: list: dictionary objects containing sample data """ url = "https://api.neur.io/v1/sam...
Get the last sample recorded by the sensor. Args: sensor_id (string): hexadecimal id of the sensor to query, e.g. ``0x0013A20040B65FAD`` Returns: list: dictionary objects containing sample data
def plot_contour( xall, yall, zall, ax=None, cmap=None, ncontours=100, vmin=None, vmax=None, levels=None, cbar=True, cax=None, cbar_label=None, cbar_orientation='vertical', norm=None, nbins=100, method='nearest', mask=False, **kwargs): """Plot a two-dimensional contour map by...
Plot a two-dimensional contour map by interpolating scattered data on a grid. Parameters ---------- xall : ndarray(T) Sample x-coordinates. yall : ndarray(T) Sample y-coordinates. zall : ndarray(T) Sample z-coordinates. ax : matplotlib.Axes object, optional, default=...
def clone_schema(self, base_schema_name, new_schema_name): """ Creates a new schema `new_schema_name` as a clone of an existing schema `old_schema_name`. """ connection.set_schema_to_public() cursor = connection.cursor() # check if the clone_schema function alrea...
Creates a new schema `new_schema_name` as a clone of an existing schema `old_schema_name`.
def get_configuration_file(): """ return jenks configuration file """ path = os.path.abspath(os.curdir) while path != os.sep: config_path = os.path.join(path, CONFIG_FILE_NAME) if os.path.exists(config_path): return config_path path = os.path.dirname(path) return None
return jenks configuration file
def get_asset_form_for_create(self, asset_record_types): """Gets the asset form for creating new assets. A new form should be requested for each create transaction. arg: asset_record_types (osid.type.Type[]): array of asset record types return: (osid.repository.Asset...
Gets the asset form for creating new assets. A new form should be requested for each create transaction. arg: asset_record_types (osid.type.Type[]): array of asset record types return: (osid.repository.AssetForm) - the asset form raise: NullArgument - ``asset_record...
def verify(self, email): """ Verify a single email address. :param str email: Email address to verify. :return: A VerifiedEmail object. """ resp = self._call(endpoint='single', data={'email': email}) return VerifiedEmail(email, resp['result'])
Verify a single email address. :param str email: Email address to verify. :return: A VerifiedEmail object.
def _read_para_hip_signature_2(self, code, cbit, clen, *, desc, length, version): """Read HIP HIP_SIGNATURE_2 parameter. Structure of HIP HIP_SIGNATURE_2 parameter [RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9...
Read HIP HIP_SIGNATURE_2 parameter. Structure of HIP HIP_SIGNATURE_2 parameter [RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
def emit(self, record): """ Emit a record. Override from parent class to handle file locking for the duration of rollover and write. This also does the formatting *before* locks are obtained, in case the format itself does logging calls from within. Rollover also occurs while th...
Emit a record. Override from parent class to handle file locking for the duration of rollover and write. This also does the formatting *before* locks are obtained, in case the format itself does logging calls from within. Rollover also occurs while the lock is held.
def server_version(self): """Attempts to determine the version of Vault that a server is running. Some actions will change on older Vault deployments.""" health_url = "%s/v1/sys/health" % self.vault_addr resp = self.session.request('get', health_url, **self._kwargs) if re...
Attempts to determine the version of Vault that a server is running. Some actions will change on older Vault deployments.
def site(self, **params): """Stream site Accepted params found at: https://dev.twitter.com/docs/api/1.1/get/site """ url = 'https://sitestream.twitter.com/%s/site.json' \ % self.streamer.api_version self.streamer._request(url, params=params)
Stream site Accepted params found at: https://dev.twitter.com/docs/api/1.1/get/site
def _get_expand_input(self, passed_settings): """ If expand value is explicitliy passed, just return it. If parsing from request, ensure that the value complies with the "permitted_expands" list passed into the context from the FlexFieldsMixin. """ ...
If expand value is explicitliy passed, just return it. If parsing from request, ensure that the value complies with the "permitted_expands" list passed into the context from the FlexFieldsMixin.
def update_coordinates(self, new_coordinates): """ new_coordinates : dict """ for k, v in new_coordinates.items(): if k in self.coordinates: self.coordinates[k] = v for svertex in self.spawn_list: verts = tuple([self.coordinates.get(ch, No...
new_coordinates : dict
def _function(self, x, a, b, c, d): """Gaussian PDF function x: coordinate a: peak position b: deviation (sigma) c: area proportional parameter d: base line """ return c/b*np.sqrt(2*np.pi)*np.exp(-(x-a)**2/(2*b**2))+d
Gaussian PDF function x: coordinate a: peak position b: deviation (sigma) c: area proportional parameter d: base line
def _initial_individual(self): """Generates an individual with random parameters within bounds.""" ind = creator.Individual( [random.uniform(-1, 1) for _ in range(len(self.value_means))]) return ind
Generates an individual with random parameters within bounds.
def write_collection_info(self, collection: BioCCollection): """ Writes the collection information: encoding, version, DTD, source, date, key, infons, etc. """ elem = etree.Element('source') elem.text = collection.source self.__writer.send(elem) elem = et...
Writes the collection information: encoding, version, DTD, source, date, key, infons, etc.
def autocorrelation( data, name, maxlags=100, format='png', reflected=False, suffix='-acf', path='./', fontmap=None, new=True, last=True, rows=1, columns=1, num=1, verbose=1): """ Generate bar plot of the autocorrelation function for a series (usually an MCMC trace). :Arguments: data: P...
Generate bar plot of the autocorrelation function for a series (usually an MCMC trace). :Arguments: data: PyMC object, trace or array A trace from an MCMC sample or a PyMC object with one or more traces. name: string The name of the object. maxlags (optional): int ...
def tocimxml(self): """ Return the CIM-XML representation of this CIM property, as an object of an appropriate subclass of :term:`Element`. The returned CIM-XML representation is a `PROPERTY`, `PROPERTY.REFERENCE`, or `PROPERTY.ARRAY` element dependent on the property ty...
Return the CIM-XML representation of this CIM property, as an object of an appropriate subclass of :term:`Element`. The returned CIM-XML representation is a `PROPERTY`, `PROPERTY.REFERENCE`, or `PROPERTY.ARRAY` element dependent on the property type, and consistent with :term:`DSP0201`....
def get_profile_info(self): """Show the accumulated results of how many times each rule was used""" return sorted(self.profile_info.items(), key=lambda kv: kv[1], reverse=False) return
Show the accumulated results of how many times each rule was used
def juliandate(time: datetime) -> float: """ Python datetime to Julian time from D.Vallado Fundamentals of Astrodynamics and Applications p.187 and J. Meeus Astronomical Algorithms 1991 Eqn. 7.1 pg. 61 Parameters ---------- time : datetime.datetime time to convert Results ...
Python datetime to Julian time from D.Vallado Fundamentals of Astrodynamics and Applications p.187 and J. Meeus Astronomical Algorithms 1991 Eqn. 7.1 pg. 61 Parameters ---------- time : datetime.datetime time to convert Results ------- jd : float Julian date
def pose_to_list(pose): """ Convert a Pose or PoseStamped in Python list ((position), (quaternion)) :param pose: geometry_msgs.msg.PoseStamped or geometry_msgs.msg.Pose :return: the equivalent in list ((position), (quaternion)) """ if type(pose) == geometry_msgs.msg.PoseStamped: return [...
Convert a Pose or PoseStamped in Python list ((position), (quaternion)) :param pose: geometry_msgs.msg.PoseStamped or geometry_msgs.msg.Pose :return: the equivalent in list ((position), (quaternion))
def list_device_events(self, **kwargs): """List all device logs. :param int limit: The number of logs to retrieve. :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get logs after/starting at given `device_event_id` :par...
List all device logs. :param int limit: The number of logs to retrieve. :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get logs after/starting at given `device_event_id` :param dict filters: Dictionary of filters to apply. ...
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
10