positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def pad_width(model, table_padding=0.85, tabs_padding=1.2): """ Computes the width of a model and sets up appropriate padding for Tabs and DataTable types. """ if isinstance(model, Row): vals = [pad_width(child) for child in model.children] width = np.max([v for v in vals if v is not None]) elif isinstance(model, Column): vals = [pad_width(child) for child in model.children] width = np.sum([v for v in vals if v is not None]) elif isinstance(model, Tabs): vals = [pad_width(t) for t in model.tabs] width = np.max([v for v in vals if v is not None]) for model in model.tabs: model.width = width width = int(tabs_padding*width) elif isinstance(model, DataTable): width = model.width model.width = int(table_padding*width) elif isinstance(model, (WidgetBox, Div)): width = model.width elif model: width = model.plot_width else: width = 0 return width
Computes the width of a model and sets up appropriate padding for Tabs and DataTable types.
def services(self): """ returns all the service objects in the admin service's page """ self._services = [] params = {"f": "json"} if not self._url.endswith('/services'): uURL = self._url + "/services" else: uURL = self._url res = self._get(url=uURL, param_dict=params, securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_url) for k, v in res.items(): if k == "foldersDetail": for item in v: if 'isDefault' in item and item['isDefault'] == False: fURL = self._url + "/services/" + item['folderName'] resFolder = self._get(url=fURL, param_dict=params, securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_url) for k1, v1 in resFolder.items(): if k1 == "services": self._checkservice(k1,v1,fURL) elif k == "services": self._checkservice(k,v,uURL) return self._services
returns all the service objects in the admin service's page
def find(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = ()) -> Entry: """ Finds the main entry for the given position or Zobrist hash. The main entry is the (first) entry with the highest weight. By default, entries with weight ``0`` are excluded. This is a common way to delete entries from an opening book without compacting it. Pass *minimum_weight* ``0`` to select all entries. :raises: :exc:`IndexError` if no entries are found. Use :func:`~chess.polyglot.MemoryMappedReader.get()` if you prefer to get ``None`` instead of an exception. """ try: return max(self.find_all(board, minimum_weight=minimum_weight, exclude_moves=exclude_moves), key=lambda entry: entry.weight) except ValueError: raise IndexError()
Finds the main entry for the given position or Zobrist hash. The main entry is the (first) entry with the highest weight. By default, entries with weight ``0`` are excluded. This is a common way to delete entries from an opening book without compacting it. Pass *minimum_weight* ``0`` to select all entries. :raises: :exc:`IndexError` if no entries are found. Use :func:`~chess.polyglot.MemoryMappedReader.get()` if you prefer to get ``None`` instead of an exception.
def find_credentials(): ''' Cycle through all the possible credentials and return the first one that works. ''' # if the username and password were already found don't fo though the # connection process again if 'username' in DETAILS and 'password' in DETAILS: return DETAILS['username'], DETAILS['password'] passwords = DETAILS['passwords'] for password in passwords: DETAILS['password'] = password if not __salt__['vsphere.test_vcenter_connection'](): # We are unable to authenticate continue # If we have data returned from above, we've successfully authenticated. return DETAILS['username'], password # We've reached the end of the list without successfully authenticating. raise salt.exceptions.VMwareConnectionError('Cannot complete login due to ' 'incorrect credentials.')
Cycle through all the possible credentials and return the first one that works.
def cumulative_statistics(self): """ Access the cumulative_statistics :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsList :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsList """ if self._cumulative_statistics is None: self._cumulative_statistics = TaskQueueCumulativeStatisticsList( self._version, workspace_sid=self._solution['workspace_sid'], task_queue_sid=self._solution['sid'], ) return self._cumulative_statistics
Access the cumulative_statistics :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsList :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsList
def get_unicode_str(obj): """Makes sure obj is a unicode string.""" if isinstance(obj, six.text_type): return obj if isinstance(obj, six.binary_type): return obj.decode("utf-8", errors="ignore") return six.text_type(obj)
Makes sure obj is a unicode string.
def get_events(self, user_id, start_date=None): """Gets the event log for a specific user, default start_date is 30 days ago :param int id: User id to view :param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string. The Timezone part has to be HH:MM, notice the : there. :returns: https://softlayer.github.io/reference/datatypes/SoftLayer_Event_Log/ """ if start_date is None: date_object = datetime.datetime.today() - datetime.timedelta(days=30) start_date = date_object.strftime("%Y-%m-%dT00:00:00") object_filter = { 'userId': { 'operation': user_id }, 'eventCreateDate': { 'operation': 'greaterThanDate', 'options': [{'name': 'date', 'value': [start_date]}] } } events = self.client.call('Event_Log', 'getAllObjects', filter=object_filter) if events is None: events = [{'eventName': 'No Events Found'}] return events
Gets the event log for a specific user, default start_date is 30 days ago :param int id: User id to view :param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string. The Timezone part has to be HH:MM, notice the : there. :returns: https://softlayer.github.io/reference/datatypes/SoftLayer_Event_Log/
def get_utm_zone(longitude): """Return utm zone.""" zone = int((math.floor((longitude + 180.0) / 6.0) + 1) % 60) if zone == 0: zone = 60 return zone
Return utm zone.
def start(self): ''' start display :rtype: self ''' if self.use_xauth: self._setup_xauth() EasyProcess.start(self) # https://github.com/ponty/PyVirtualDisplay/issues/2 # https://github.com/ponty/PyVirtualDisplay/issues/14 self.old_display_var = os.environ.get('DISPLAY', None) self.redirect_display(True) # wait until X server is active start_time = time.time() ok = False d = self.new_display_var while time.time() - start_time < X_START_TIMEOUT: try: exit_code = EasyProcess('xdpyinfo').call().return_code except EasyProcessError: log.warn('xdpyinfo was not found, X start can not be checked! Please install xdpyinfo!') time.sleep(X_START_WAIT) # old method ok = True break if exit_code != 0: pass else: log.info('Successfully started X with display "%s".', d) ok = True break time.sleep(X_START_TIME_STEP) if not ok: msg = 'Failed to start X on display "%s" (xdpyinfo check failed).' raise XStartTimeoutError(msg % d) return self
start display :rtype: self
def open_file(infile, verbose=True): """ Open file and return a list of the file's lines. Try to use utf-8 encoding, and if that fails use Latin-1. Parameters ---------- infile : str full path to file Returns ---------- data: list all lines in the file """ try: with codecs.open(infile, "r", "utf-8") as f: lines = list(f.readlines()) # file might not exist except FileNotFoundError: if verbose: print( '-W- You are trying to open a file: {} that does not exist'.format(infile)) return [] # encoding might be wrong except UnicodeDecodeError: try: with codecs.open(infile, "r", "Latin-1") as f: print( '-I- Using less strict decoding for {}, output may have formatting errors'.format(infile)) lines = list(f.readlines()) # if file exists, and encoding is correct, who knows what the problem is except Exception as ex: print("-W- ", type(ex), ex) return [] except Exception as ex: print("-W- ", type(ex), ex) return [] # don't leave a blank line at the end i = 0 while i < 10: if not len(lines[-1].strip("\n").strip("\t")): lines = lines[:-1] i += 1 else: i = 10 return lines
Open file and return a list of the file's lines. Try to use utf-8 encoding, and if that fails use Latin-1. Parameters ---------- infile : str full path to file Returns ---------- data: list all lines in the file
def _wrlog_details_illegal_gaf(self, fout_err, err_cnts): """Print details regarding illegal GAF lines seen to a log file.""" # fout_err = "{}.log".format(fin_gaf) gaf_base = os.path.basename(fout_err) with open(fout_err, 'w') as prt: prt.write("ILLEGAL GAF ERROR SUMMARY:\n\n") for err_cnt in err_cnts: prt.write(err_cnt) prt.write("\n\nILLEGAL GAF ERROR DETAILS:\n\n") for lnum, line in self.ignored: prt.write("**WARNING: GAF LINE IGNORED: {FIN}[{LNUM}]:\n{L}\n".format( FIN=gaf_base, L=line, LNUM=lnum)) self.prt_line_detail(prt, line) prt.write("\n\n") for error, lines in self.illegal_lines.items(): for lnum, line in lines: prt.write("**WARNING: GAF LINE ILLEGAL({ERR}): {FIN}[{LNUM}]:\n{L}\n".format( ERR=error, FIN=gaf_base, L=line, LNUM=lnum)) self.prt_line_detail(prt, line) prt.write("\n\n") return fout_err
Print details regarding illegal GAF lines seen to a log file.
def create_route_func(self, method): """ create_route_func """ def _route(resource, handler, schema=None): """ _route """ route = self.routes.get(resource, Route(resource)) route.__getattribute__(method)(handler, schema) self.routes.update({resource: route}) return self return _route
create_route_func
def aggregated_relevant_items(raw_df): """ Aggragation for calculate mean and std. """ df = ( raw_df[['idSegmento', 'idPlanilhaItens', 'VlUnitarioAprovado']] .groupby(by=['idSegmento', 'idPlanilhaItens']) .agg([np.mean, lambda x: np.std(x, ddof=0)]) ) df.columns = df.columns.droplevel(0) return ( df .rename(columns={'<lambda>': 'std'}) )
Aggragation for calculate mean and std.
def endline_repl(self, inputstring, reformatting=False, **kwargs): """Add end of line comments.""" out = [] ln = 1 # line number for line in inputstring.splitlines(): add_one_to_ln = False try: if line.endswith(lnwrapper): line, index = line[:-1].rsplit("#", 1) new_ln = self.get_ref("ln", index) if new_ln < ln: raise CoconutInternalException("line number decreased", (ln, new_ln)) ln = new_ln line = line.rstrip() add_one_to_ln = True if not reformatting or add_one_to_ln: # add_one_to_ln here is a proxy for whether there was a ln comment or not line += self.comments.get(ln, "") if not reformatting and line.rstrip() and not line.lstrip().startswith("#"): line += self.ln_comment(ln) except CoconutInternalException as err: complain(err) out.append(line) if add_one_to_ln: ln += 1 return "\n".join(out)
Add end of line comments.
def getaddresses (addr): """Return list of email addresses from given field value.""" parsed = [mail for name, mail in AddressList(addr).addresslist if mail] if parsed: addresses = parsed elif addr: # we could not parse any mail addresses, so try with the raw string addresses = [addr] else: addresses = [] return addresses
Return list of email addresses from given field value.
def _generate_SAX_single(self, sections, value): """ Generate SAX representation(Symbolic Aggregate approXimation) for a single data point. Read more about it here: Assumption-Free Anomaly Detection in Time Series(http://alumni.cs.ucr.edu/~ratana/SSDBM05.pdf). :param dict sections: value sections. :param float value: value to be categorized. :return str: a SAX representation. """ sax = 0 for section_number in sections.keys(): section_lower_bound = sections[section_number] if value >= section_lower_bound: sax = section_number else: break return str(sax)
Generate SAX representation(Symbolic Aggregate approXimation) for a single data point. Read more about it here: Assumption-Free Anomaly Detection in Time Series(http://alumni.cs.ucr.edu/~ratana/SSDBM05.pdf). :param dict sections: value sections. :param float value: value to be categorized. :return str: a SAX representation.
def get_resource_value(self, device_id, resource_path, fix_path=True, timeout=None): """Get a resource value for a given device and resource path by blocking thread. Example usage: .. code-block:: python try: v = api.get_resource_value(device_id, path) print("Current value", v) except CloudAsyncError, e: print("Error", e) :param str device_id: The name/id of the device (Required) :param str resource_path: The resource path to get (Required) :param fix_path: if True then the leading /, if found, will be stripped before doing request to backend. This is a requirement for the API to work properly :param timeout: Seconds to request value for before timeout. If not provided, the program might hang indefinitely. :raises: CloudAsyncError, CloudTimeoutError :returns: The resource value for the requested resource path :rtype: str """ return self.get_resource_value_async(device_id, resource_path, fix_path).wait(timeout)
Get a resource value for a given device and resource path by blocking thread. Example usage: .. code-block:: python try: v = api.get_resource_value(device_id, path) print("Current value", v) except CloudAsyncError, e: print("Error", e) :param str device_id: The name/id of the device (Required) :param str resource_path: The resource path to get (Required) :param fix_path: if True then the leading /, if found, will be stripped before doing request to backend. This is a requirement for the API to work properly :param timeout: Seconds to request value for before timeout. If not provided, the program might hang indefinitely. :raises: CloudAsyncError, CloudTimeoutError :returns: The resource value for the requested resource path :rtype: str
def _bird_core(X, scales, n_runs, Lambda_W, max_iter=100, stop_crit=np.mean, selection_rule=np.sum, n_jobs=1, indep=True, random_state=None, memory=Memory(None), verbose=False): """Automatically detect when noise zone has been reached and stop MP at this point Parameters ---------- X : array, shape (n_channels, n_times) The numpy n_channels-vy-N array to be denoised where n_channels is number of sensors and N the dimension scales : list The list of MDCT scales that will be used to built the dictionary Phi n_runs : int the number of runs (n_runs in the paper) Lambda_W : float bound for lambda under which a run will be stopped max_iter : int Maximum number of iterations (serves as alternate stopping criterion) stop_crit : function controls the calculation of Lambda selection_rule : callable controls the way multiple channel projections are combined for atom selection only used if indep=False n_jobs : int number of jobs to run in parallel indep : bool True for BIRD (independent processing of each channel, False for S-BIRD (structured sparsity seeked) random_state : None | int | np.random.RandomState To specify the random generator state (seed). memory : instance of Memory The object to use to cache some computations. If cachedir is None, no caching is performed. verbose : bool verbose mode Returns ------- X_denoise : array, shape (n_channels, n_times) denoised array of same shape as X """ Phi = MDCT(scales) pad = int(1.5 * max(scales)) X_denoise = np.zeros_like(X) approx = [] rng = check_random_state(random_state) seeds = rng.randint(4294967295, size=n_runs) # < max seed value if n_jobs <= 0: n_cores = multiprocessing.cpu_count() n_jobs = min(n_cores + n_jobs + 1, n_cores) if indep: # Independent treat of each channel (plain BIRD) for r, x in zip(X_denoise, X): this_approx = Parallel(n_jobs=n_jobs)( delayed(_denoise)(this_seeds, x, Phi, Lambda_W, max_iter, pad=pad, verbose=verbose, indep=True, memory=memory) for this_seeds in np.array_split(seeds, n_jobs)) this_approx = sum(this_approx[1:], this_approx[0]) r[:] = sum([a[pad:-pad] for a in this_approx]) approx.append(this_approx) else: # data need to be processed jointly this_approx = Parallel(n_jobs=n_jobs)( delayed(_denoise)(this_seeds, X, Phi, Lambda_W, max_iter, pad=pad, verbose=verbose, selection_rule=selection_rule, indep=False, memory=memory, stop_crit=stop_crit) for this_seeds in np.array_split(seeds, n_jobs)) # reconstruction by averaging for jidx in range(len(this_approx)): for ridx in range(len(this_approx[jidx])): X_denoise += this_approx[jidx][ridx] X_denoise /= float(n_runs) return X_denoise
Automatically detect when noise zone has been reached and stop MP at this point Parameters ---------- X : array, shape (n_channels, n_times) The numpy n_channels-vy-N array to be denoised where n_channels is number of sensors and N the dimension scales : list The list of MDCT scales that will be used to built the dictionary Phi n_runs : int the number of runs (n_runs in the paper) Lambda_W : float bound for lambda under which a run will be stopped max_iter : int Maximum number of iterations (serves as alternate stopping criterion) stop_crit : function controls the calculation of Lambda selection_rule : callable controls the way multiple channel projections are combined for atom selection only used if indep=False n_jobs : int number of jobs to run in parallel indep : bool True for BIRD (independent processing of each channel, False for S-BIRD (structured sparsity seeked) random_state : None | int | np.random.RandomState To specify the random generator state (seed). memory : instance of Memory The object to use to cache some computations. If cachedir is None, no caching is performed. verbose : bool verbose mode Returns ------- X_denoise : array, shape (n_channels, n_times) denoised array of same shape as X
def raise_412(instance, msg=None): """Abort the current request with a 412 (Precondition Failed) response code. If the message is given it's output as an error message in the response body (correctly converted to the requested MIME type). :param instance: Resource instance (used to access the response) :type instance: :class:`webob.resource.Resource` :raises: :class:`webob.exceptions.ResponseException` of status 412 """ instance.response.status = 412 if msg: instance.response.body_raw = {'error': msg} raise ResponseException(instance.response)
Abort the current request with a 412 (Precondition Failed) response code. If the message is given it's output as an error message in the response body (correctly converted to the requested MIME type). :param instance: Resource instance (used to access the response) :type instance: :class:`webob.resource.Resource` :raises: :class:`webob.exceptions.ResponseException` of status 412
def list_component_status(self, **kwargs): """ list objects of kind ComponentStatus This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_component_status(async_req=True) >>> result = thread.get() :param async_req bool :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V1ComponentStatusList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.list_component_status_with_http_info(**kwargs) else: (data) = self.list_component_status_with_http_info(**kwargs) return data
list objects of kind ComponentStatus This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_component_status(async_req=True) >>> result = thread.get() :param async_req bool :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V1ComponentStatusList If the method is called asynchronously, returns the request thread.
def check_downloaded(self, path, maybe_downloaded): """Check if files downloaded and return downloaded packages """ downloaded = [] for pkg in maybe_downloaded: if os.path.isfile(path + pkg): downloaded.append(pkg) return downloaded
Check if files downloaded and return downloaded packages
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'pronunciation') and self.pronunciation is not None: _dict['pronunciation'] = self.pronunciation return _dict
Return a json dictionary representing this model.
def lotus_root_geometry(): """Tomographic geometry for the lotus root dataset. Notes ----- See the article `Tomographic X-ray data of a lotus root filled with attenuating objects`_ for further information. See Also -------- lotus_root_geometry References ---------- .. _Tomographic X-ray data of a lotus root filled with attenuating objects: https://arxiv.org/abs/1609.07299 """ # To get the same rotation as in the reference article a_offset = np.pi / 2 apart = uniform_partition(a_offset, a_offset + 2 * np.pi * 366. / 360., 366) # TODO: Find exact value, determined experimentally d_offset = 0.35 dpart = uniform_partition(d_offset - 60, d_offset + 60, 2240) geometry = FanBeamGeometry(apart, dpart, src_radius=540, det_radius=90) return geometry
Tomographic geometry for the lotus root dataset. Notes ----- See the article `Tomographic X-ray data of a lotus root filled with attenuating objects`_ for further information. See Also -------- lotus_root_geometry References ---------- .. _Tomographic X-ray data of a lotus root filled with attenuating objects: https://arxiv.org/abs/1609.07299
def import_mod_attr(path): """ Import string format module, e.g. 'uliweb.orm' or an object return module object and object """ import inspect if isinstance(path, (str, unicode)): v = path.split(':') if len(v) == 1: module, func = path.rsplit('.', 1) else: module, func = v mod = __import__(module, fromlist=['*']) f = mod for x in func.split('.'): try: f = getattr(f, x) except: raise AttributeError("Get %s attribute according %s error" % (x, path)) else: f = path mod = inspect.getmodule(path) return mod, f
Import string format module, e.g. 'uliweb.orm' or an object return module object and object
def add_federation(self, provider, federated_id): """ Add federated login to the current user :param provider: :param federated_id: :return: """ models.AuthUserFederation.new(user=self, provider=provider, federated_id=federated_id)
Add federated login to the current user :param provider: :param federated_id: :return:
def get_replacement_types(titles, reportnumbers, publishers): """Given the indices of the titles and reportnumbers that have been recognised within a reference line, create a dictionary keyed by the replacement position in the line, where the value for each key is a string describing the type of item replaced at that position in the line. The description strings are: 'title' - indicating that the replacement is a periodical title 'reportnumber' - indicating that the replacement is a preprint report number. @param titles: (list) of locations in the string at which periodical titles were found. @param reportnumbers: (list) of locations in the string at which reportnumbers were found. @return: (dictionary) of replacement types at various locations within the string. """ rep_types = {} for item_idx in titles: rep_types[item_idx] = "journal" for item_idx in reportnumbers: rep_types[item_idx] = "reportnumber" for item_idx in publishers: rep_types[item_idx] = "publisher" return rep_types
Given the indices of the titles and reportnumbers that have been recognised within a reference line, create a dictionary keyed by the replacement position in the line, where the value for each key is a string describing the type of item replaced at that position in the line. The description strings are: 'title' - indicating that the replacement is a periodical title 'reportnumber' - indicating that the replacement is a preprint report number. @param titles: (list) of locations in the string at which periodical titles were found. @param reportnumbers: (list) of locations in the string at which reportnumbers were found. @return: (dictionary) of replacement types at various locations within the string.
def operators(self, ignore=0): """ Returns a list of operators for this plugin. :return <str> """ return [k for k, v in self._operatorMap.items() if not v.flags & ignore]
Returns a list of operators for this plugin. :return <str>
def add_badge(self, kind): '''Perform an atomic prepend for a new badge''' badge = self.get_badge(kind) if badge: return badge if kind not in getattr(self, '__badges__', {}): msg = 'Unknown badge type for {model}: {kind}' raise db.ValidationError(msg.format(model=self.__class__.__name__, kind=kind)) badge = Badge(kind=kind) if current_user.is_authenticated: badge.created_by = current_user.id self.update(__raw__={ '$push': { 'badges': { '$each': [badge.to_mongo()], '$position': 0 } } }) self.reload() post_save.send(self.__class__, document=self) on_badge_added.send(self, kind=kind) return self.get_badge(kind)
Perform an atomic prepend for a new badge
def utm_to_pixel(east, north, transform, truncate=True): """ Convert UTM coordinate to image coordinate given a transform :param east: east coordinate of point :type east: float :param north: north coordinate of point :type north: float :param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)` :type transform: tuple or list :param truncate: Whether to truncate pixel coordinates. Default is ``True`` :type truncate: bool :return: row and column pixel image coordinates :rtype: float, float or int, int """ column = (east - transform[0]) / transform[1] row = (north - transform[3]) / transform[5] if truncate: return int(row + ERR), int(column + ERR) return row, column
Convert UTM coordinate to image coordinate given a transform :param east: east coordinate of point :type east: float :param north: north coordinate of point :type north: float :param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)` :type transform: tuple or list :param truncate: Whether to truncate pixel coordinates. Default is ``True`` :type truncate: bool :return: row and column pixel image coordinates :rtype: float, float or int, int
def add_block_widget(self, top=False): """ Return a select widget for blocks which can be added to this column. """ widget = AddBlockSelect(attrs={ 'class': 'glitter-add-block-select', }, choices=self.add_block_options(top=top)) return widget.render(name='', value=None)
Return a select widget for blocks which can be added to this column.
def resources_of_config(config): """ Returns all resources and models from config. """ return set( # unique values sum([ # join lists to flat list list(value) # if value is iter (ex: list of resources) if hasattr(value, '__iter__') else [value, ] # if value is not iter (ex: model or resource) for value in config.values() ], []) )
Returns all resources and models from config.
def _element_keywords(cls, backend, elements=None): "Returns a dictionary of element names to allowed keywords" if backend not in Store.loaded_backends(): return {} mapping = {} backend_options = Store.options(backend) elements = elements if elements is not None else backend_options.keys() for element in elements: if '.' in element: continue element = element if isinstance(element, tuple) else (element,) element_keywords = [] options = backend_options['.'.join(element)] for group in Options._option_groups: element_keywords.extend(options[group].allowed_keywords) mapping[element[0]] = element_keywords return mapping
Returns a dictionary of element names to allowed keywords
def set_mode_px4(self, mode, custom_mode, custom_sub_mode): '''enter arbitrary mode''' if isinstance(mode, str): mode_map = self.mode_mapping() if mode_map is None or mode not in mode_map: print("Unknown mode '%s'" % mode) return # PX4 uses two fields to define modes mode, custom_mode, custom_sub_mode = px4_map[mode] self.mav.command_long_send(self.target_system, self.target_component, mavlink.MAV_CMD_DO_SET_MODE, 0, mode, custom_mode, custom_sub_mode, 0, 0, 0, 0)
enter arbitrary mode
def crypt_salt_is_valid(salt): """ Validate a salt as crypt salt :param str salt: a password salt :return: ``True`` if ``salt`` is a valid crypt salt on this system, ``False`` otherwise :rtype: bool """ if len(salt) < 2: return False else: if salt[0] == '$': if salt[1] == '$': return False else: if '$' not in salt[1:]: return False else: hashed = crypt.crypt("", salt) if not hashed or '$' not in hashed[1:]: return False else: return True else: return True
Validate a salt as crypt salt :param str salt: a password salt :return: ``True`` if ``salt`` is a valid crypt salt on this system, ``False`` otherwise :rtype: bool
def von_neumann_entropy(self, t_max=100): """Calculate Von Neumann Entropy Determines the Von Neumann entropy of the diffusion affinities at varying levels of `t`. The user should select a value of `t` around the "knee" of the entropy curve. We require that 'fit' stores the value of `PHATE.diff_op` in order to calculate the Von Neumann entropy. Parameters ---------- t_max : int, default: 100 Maximum value of `t` to test Returns ------- entropy : array, shape=[t_max] The entropy of the diffusion affinities for each value of `t` """ t = np.arange(t_max) return t, vne.compute_von_neumann_entropy(self.diff_op, t_max=t_max)
Calculate Von Neumann Entropy Determines the Von Neumann entropy of the diffusion affinities at varying levels of `t`. The user should select a value of `t` around the "knee" of the entropy curve. We require that 'fit' stores the value of `PHATE.diff_op` in order to calculate the Von Neumann entropy. Parameters ---------- t_max : int, default: 100 Maximum value of `t` to test Returns ------- entropy : array, shape=[t_max] The entropy of the diffusion affinities for each value of `t`
def add_ip_address(list_name, item_name): ''' Add an IP address to an IP address list. list_name(str): The name of the specific policy IP address list to append to. item_name(str): The IP address to append to the list. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24 ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "add_policy_ip_addresses", "params": [list_name, {"item_name": item_name}]} response = __proxy__['bluecoat_sslv.call'](payload, True) return _validate_change_result(response)
Add an IP address to an IP address list. list_name(str): The name of the specific policy IP address list to append to. item_name(str): The IP address to append to the list. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24
def get_alpha_or_number(number, template): """Returns an Alphanumber that represents the number passed in, expressed as defined in the template. Otherwise, returns the number """ match = re.match(r".*\{alpha:(\d+a\d+d)\}$", template.strip()) if match and match.groups(): format = match.groups()[0] return to_alpha(number, format) return number
Returns an Alphanumber that represents the number passed in, expressed as defined in the template. Otherwise, returns the number
def having(self, expr): """ Add a post-aggregation result filter (like the having argument in `aggregate`), for composability with the group_by API Parameters ---------- expr : ibis.expr.types.Expr Returns ------- grouped : GroupedTableExpr """ exprs = util.promote_list(expr) new_having = self._having + exprs return GroupedTableExpr( self.table, self.by, having=new_having, order_by=self._order_by, window=self._window, )
Add a post-aggregation result filter (like the having argument in `aggregate`), for composability with the group_by API Parameters ---------- expr : ibis.expr.types.Expr Returns ------- grouped : GroupedTableExpr
def rsdl_sn(self, U): """Compute dual residual normalisation term. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not overridden. """ return self.rho * np.linalg.norm(self.cnst_AT(U))
Compute dual residual normalisation term. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not overridden.
def setVisible( self, state ): """ Sets whether or not this node is visible in the scene. :param state | <bool> """ self._visible = state super(XNode, self).setVisible(self.isVisible()) self.dispatch.visibilityChanged.emit(state) self.setDirty()
Sets whether or not this node is visible in the scene. :param state | <bool>
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a participant into this object. ''' if node.getElementsByTagNameNS(RTS_NS, 'Participant').length != 1: raise InvalidParticipantNodeError self.target_component = TargetComponent().parse_xml_node(\ node.getElementsByTagNameNS(RTS_NS, 'Participant')[0]) return self
Parse an xml.dom Node object representing a participant into this object.
def init_submodules(self, cache): """cache = path or bool""" self.cache = CacheService(cache, weakref.proxy(self)) self.mesh = PrecomputedMeshService(weakref.proxy(self)) self.skeleton = PrecomputedSkeletonService(weakref.proxy(self))
cache = path or bool
def save_file(self, path: str, file_id: int = None, file_part: int = 0, progress: callable = None, progress_args: tuple = ()): """Use this method to upload a file onto Telegram servers, without actually sending the message to anyone. This is a utility method intended to be used **only** when working with Raw Functions (i.e: a Telegram API method you wish to use which is not available yet in the Client class as an easy-to-use method), whenever an InputFile type is required. Args: path (``str``): The path of the file you want to upload that exists on your local machine. file_id (``int``, *optional*): In case a file part expired, pass the file_id and the file_part to retry uploading that specific chunk. file_part (``int``, *optional*): In case a file part expired, pass the file_id and the file_part to retry uploading that specific chunk. progress (``callable``, *optional*): Pass a callback function to view the upload progress. The function must take *(client, current, total, \*args)* as positional arguments (look at the section below for a detailed description). progress_args (``tuple``, *optional*): Extra custom arguments for the progress callback function. Useful, for example, if you want to pass a chat_id and a message_id in order to edit a message with the updated progress. Other Parameters: client (:obj:`Client <pyrogram.Client>`): The Client itself, useful when you want to call other API methods inside the callback function. current (``int``): The amount of bytes uploaded so far. total (``int``): The size of the file. *args (``tuple``, *optional*): Extra custom arguments as defined in the *progress_args* parameter. You can either keep *\*args* or add every single extra argument in your function signature. Returns: On success, the uploaded file is returned in form of an InputFile object. Raises: :class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error. """ part_size = 512 * 1024 file_size = os.path.getsize(path) if file_size == 0: raise ValueError("File size equals to 0 B") if file_size > 1500 * 1024 * 1024: raise ValueError("Telegram doesn't support uploading files bigger than 1500 MiB") file_total_parts = int(math.ceil(file_size / part_size)) is_big = True if file_size > 10 * 1024 * 1024 else False is_missing_part = True if file_id is not None else False file_id = file_id or self.rnd_id() md5_sum = md5() if not is_big and not is_missing_part else None session = Session(self, self.dc_id, self.auth_key, is_media=True) session.start() try: with open(path, "rb") as f: f.seek(part_size * file_part) while True: chunk = f.read(part_size) if not chunk: if not is_big: md5_sum = "".join([hex(i)[2:].zfill(2) for i in md5_sum.digest()]) break for _ in range(3): if is_big: rpc = functions.upload.SaveBigFilePart( file_id=file_id, file_part=file_part, file_total_parts=file_total_parts, bytes=chunk ) else: rpc = functions.upload.SaveFilePart( file_id=file_id, file_part=file_part, bytes=chunk ) if session.send(rpc): break else: raise AssertionError("Telegram didn't accept chunk #{} of {}".format(file_part, path)) if is_missing_part: return if not is_big: md5_sum.update(chunk) file_part += 1 if progress: progress(self, min(file_part * part_size, file_size), file_size, *progress_args) except Client.StopTransmission: raise except Exception as e: log.error(e, exc_info=True) else: if is_big: return types.InputFileBig( id=file_id, parts=file_total_parts, name=os.path.basename(path), ) else: return types.InputFile( id=file_id, parts=file_total_parts, name=os.path.basename(path), md5_checksum=md5_sum ) finally: session.stop()
Use this method to upload a file onto Telegram servers, without actually sending the message to anyone. This is a utility method intended to be used **only** when working with Raw Functions (i.e: a Telegram API method you wish to use which is not available yet in the Client class as an easy-to-use method), whenever an InputFile type is required. Args: path (``str``): The path of the file you want to upload that exists on your local machine. file_id (``int``, *optional*): In case a file part expired, pass the file_id and the file_part to retry uploading that specific chunk. file_part (``int``, *optional*): In case a file part expired, pass the file_id and the file_part to retry uploading that specific chunk. progress (``callable``, *optional*): Pass a callback function to view the upload progress. The function must take *(client, current, total, \*args)* as positional arguments (look at the section below for a detailed description). progress_args (``tuple``, *optional*): Extra custom arguments for the progress callback function. Useful, for example, if you want to pass a chat_id and a message_id in order to edit a message with the updated progress. Other Parameters: client (:obj:`Client <pyrogram.Client>`): The Client itself, useful when you want to call other API methods inside the callback function. current (``int``): The amount of bytes uploaded so far. total (``int``): The size of the file. *args (``tuple``, *optional*): Extra custom arguments as defined in the *progress_args* parameter. You can either keep *\*args* or add every single extra argument in your function signature. Returns: On success, the uploaded file is returned in form of an InputFile object. Raises: :class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.
def uniform(graph, vartype, low=0.0, high=1.0, cls=BinaryQuadraticModel, seed=None): """Generate a bqm with random biases and offset. Biases and offset are drawn from a uniform distribution range (low, high). Args: graph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`): The graph to build the bqm loops on. Either an integer n, interpreted as a complete graph of size n, or a nodes/edges pair, or a NetworkX graph. vartype (:class:`.Vartype`/str/set): Variable type for the binary quadratic model. Accepted input values: * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}`` * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}`` low (float, optional, default=0.0): The low end of the range for the random biases. high (float, optional, default=1.0): The high end of the range for the random biases. cls (:class:`.BinaryQuadraticModel`): Binary quadratic model class to build from. seed (int, optional, default=None): Random seed. Returns: :obj:`.BinaryQuadraticModel` """ if seed is None: seed = numpy.random.randint(2**32, dtype=np.uint32) r = numpy.random.RandomState(seed) variables, edges = graph index = {v: idx for idx, v in enumerate(variables)} if edges: irow, icol = zip(*((index[u], index[v]) for u, v in edges)) else: irow = icol = tuple() ldata = r.uniform(low, high, size=len(variables)) qdata = r.uniform(low, high, size=len(irow)) offset = r.uniform(low, high) return cls.from_numpy_vectors(ldata, (irow, icol, qdata), offset, vartype, variable_order=variables)
Generate a bqm with random biases and offset. Biases and offset are drawn from a uniform distribution range (low, high). Args: graph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`): The graph to build the bqm loops on. Either an integer n, interpreted as a complete graph of size n, or a nodes/edges pair, or a NetworkX graph. vartype (:class:`.Vartype`/str/set): Variable type for the binary quadratic model. Accepted input values: * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}`` * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}`` low (float, optional, default=0.0): The low end of the range for the random biases. high (float, optional, default=1.0): The high end of the range for the random biases. cls (:class:`.BinaryQuadraticModel`): Binary quadratic model class to build from. seed (int, optional, default=None): Random seed. Returns: :obj:`.BinaryQuadraticModel`
def synthetic_grad(X, theta, sigma1, sigma2, sigmax, rescale_grad=1.0, grad=None): """Get synthetic gradient value""" if grad is None: grad = nd.empty(theta.shape, theta.context) theta1 = theta.asnumpy()[0] theta2 = theta.asnumpy()[1] v1 = sigma1 ** 2 v2 = sigma2 ** 2 vx = sigmax ** 2 denominator = numpy.exp(-(X - theta1) ** 2 / (2 * vx)) + numpy.exp( -(X - theta1 - theta2) ** 2 / (2 * vx)) grad_npy = numpy.zeros(theta.shape) grad_npy[0] = -rescale_grad * ((numpy.exp(-(X - theta1) ** 2 / (2 * vx)) * (X - theta1) / vx + numpy.exp(-(X - theta1 - theta2) ** 2 / (2 * vx)) * (X - theta1 - theta2) / vx) / denominator).sum() + theta1 / v1 grad_npy[1] = -rescale_grad * ((numpy.exp(-(X - theta1 - theta2) ** 2 / (2 * vx)) * (X - theta1 - theta2) / vx) / denominator).sum() + theta2 / v2 grad[:] = grad_npy return grad
Get synthetic gradient value
def find_packages(path): """ Find all java files matching the "*Package.java" pattern within the given enaml package directory relative to the java source path. """ matches = [] root = join(path, 'src', 'main', 'java') for folder, dirnames, filenames in os.walk(root): for filename in fnmatch.filter(filenames, '*Package.java'): #: Open and make sure it's an EnamlPackage somewhere with open(join(folder, filename)) as f: if "implements EnamlPackage" in f.read(): package = os.path.relpath(folder, root) matches.append(os.path.join(package, filename)) return matches
Find all java files matching the "*Package.java" pattern within the given enaml package directory relative to the java source path.
def export(self, top=True): """Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist objects should be exported with `top`=False Returns: str: The objects string representation """ out = [] if top: out.append(self._internal_name) out.append(self._to_str(self.city)) out.append(self._to_str(self.state_province_region)) out.append(self._to_str(self.country)) out.append(self._to_str(self.source)) out.append(self._to_str(self.wmo)) out.append(self._to_str(self.latitude)) out.append(self._to_str(self.longitude)) out.append(self._to_str(self.timezone)) out.append(self._to_str(self.elevation)) return ",".join(out)
Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist objects should be exported with `top`=False Returns: str: The objects string representation
def dump(self, ret): """ Dumps the return value :param ret: :return: """ if self.args.flatten: ret = drop_none(flatten(ret)) logger.info('Dump: \n' + json.dumps(ret, cls=AutoJSONEncoder, indent=2 if self.args.indent else None))
Dumps the return value :param ret: :return:
def remove_html_tag(input_str='', tag=None): """ Returns a string with the html tag and all its contents from a string """ result = input_str if tag is not None: pattern = re.compile('<{tag}[\s\S]+?/{tag}>'.format(tag=tag)) result = re.sub(pattern, '', str(input_str)) return result
Returns a string with the html tag and all its contents from a string
def _to_ctfile_counts_line(self, key): """Create counts line in ``CTfile`` format. :param str key: Counts line key. :return: Counts line string. :rtype: :py:class:`str` """ counter = OrderedCounter(self.counts_line_format) self[key]['number_of_atoms'] = str(len(self.atoms)) self[key]['number_of_bonds'] = str(len(self.bonds)) counts_line = ''.join([str(value).rjust(spacing) for value, spacing in zip(self[key].values(), counter.values())]) return '{}\n'.format(counts_line)
Create counts line in ``CTfile`` format. :param str key: Counts line key. :return: Counts line string. :rtype: :py:class:`str`
def _make_request(self, params, translation_url, headers): """ This is the final step, where the request is made, the data is retrieved and returned. """ resp = requests.get(translation_url, params=params, headers=headers) resp.encoding = "UTF-8-sig" result = resp.json() return result
This is the final step, where the request is made, the data is retrieved and returned.
def update_user_entitlement(self, document, user_id): """UpdateUserEntitlement. [Preview API] Edit the entitlements (License, Extensions, Projects, Teams etc) for a user. :param :class:`<[JsonPatchOperation]> <azure.devops.v5_0.member_entitlement_management.models.[JsonPatchOperation]>` document: JsonPatchDocument containing the operations to perform on the user. :param str user_id: ID of the user. :rtype: :class:`<UserEntitlementsPatchResponse> <azure.devops.v5_0.member_entitlement_management.models.UserEntitlementsPatchResponse>` """ route_values = {} if user_id is not None: route_values['userId'] = self._serialize.url('user_id', user_id, 'str') content = self._serialize.body(document, '[JsonPatchOperation]') response = self._send(http_method='PATCH', location_id='8480c6eb-ce60-47e9-88df-eca3c801638b', version='5.0-preview.2', route_values=route_values, content=content, media_type='application/json-patch+json') return self._deserialize('UserEntitlementsPatchResponse', response)
UpdateUserEntitlement. [Preview API] Edit the entitlements (License, Extensions, Projects, Teams etc) for a user. :param :class:`<[JsonPatchOperation]> <azure.devops.v5_0.member_entitlement_management.models.[JsonPatchOperation]>` document: JsonPatchDocument containing the operations to perform on the user. :param str user_id: ID of the user. :rtype: :class:`<UserEntitlementsPatchResponse> <azure.devops.v5_0.member_entitlement_management.models.UserEntitlementsPatchResponse>`
def write_task_metadata( self, declaration_datetime=None, flight_date=None, task_number=None, turnpoints=None, text=None): """ Write the task declaration metadata record:: writer.write_task_metadata( datetime.datetime(2014, 4, 13, 12, 53, 02), task_number=42, turnpoints=3, ) # -> C140413125302000000004203 There are sensible defaults in place for all parameters except for the ``turnpoints`` parameter. If you don't pass that parameter the method will raise a :class:`ValueError`. The other parameter defaults are mentioned in the list below. :param declaration_datetime: a :class:`datetime.datetime` instance of the UTC date and time at the time of declaration (default: current date and time) :param flight_date: a :class:`datetime.date` instance of the intended date of the flight (default: ``000000``, which means "use declaration date") :param task_number: task number for the flight date or an integer-based identifier (default: ``0001``) :param turnpoints: the number of turnpoints in the task (not counting start and finish points!) :param text: optional text to append to the metadata record """ if declaration_datetime is None: declaration_datetime = datetime.datetime.utcnow() if isinstance(declaration_datetime, datetime.datetime): declaration_datetime = ( self.format_date(declaration_datetime) + self.format_time(declaration_datetime) ) elif not patterns.DATETIME.match(declaration_datetime): raise ValueError('Invalid declaration datetime: %s' % declaration_datetime) if flight_date is None: flight_date = '000000' else: flight_date = self.format_date(flight_date) if task_number is None: task_number = 1 elif not isinstance(task_number, int): raise ValueError('Invalid task number: %s' % task_number) if not isinstance(turnpoints, int): raise ValueError('Invalid turnpoints: %s' % turnpoints) record = '{0}{1}{2:04d}{3:02d}'.format( declaration_datetime, flight_date, task_number, turnpoints, ) if text: record += text self.write_record('C', record)
Write the task declaration metadata record:: writer.write_task_metadata( datetime.datetime(2014, 4, 13, 12, 53, 02), task_number=42, turnpoints=3, ) # -> C140413125302000000004203 There are sensible defaults in place for all parameters except for the ``turnpoints`` parameter. If you don't pass that parameter the method will raise a :class:`ValueError`. The other parameter defaults are mentioned in the list below. :param declaration_datetime: a :class:`datetime.datetime` instance of the UTC date and time at the time of declaration (default: current date and time) :param flight_date: a :class:`datetime.date` instance of the intended date of the flight (default: ``000000``, which means "use declaration date") :param task_number: task number for the flight date or an integer-based identifier (default: ``0001``) :param turnpoints: the number of turnpoints in the task (not counting start and finish points!) :param text: optional text to append to the metadata record
def insert(conn, qualified_name: str, column_names, records): """Insert a collection of namedtuple records.""" query = create_insert_statement(qualified_name, column_names) with conn: with conn.cursor(cursor_factory=NamedTupleCursor) as cursor: for record in records: cursor.execute(query, record)
Insert a collection of namedtuple records.
def quit(self,verbose=False): """ This command causes Cytoscape to exit. It is typically used at the end of a script file. :param verbose: print more """ response=api(url=self.__url+"/quit", verbose=verbose) return response
This command causes Cytoscape to exit. It is typically used at the end of a script file. :param verbose: print more
def env(self, **kw): ''' Allows adding/overriding env vars in the execution context. :param kw: Key-value pairs :return: self ''' self._original_env = kw if self._env is None: self._env = dict(os.environ) self._env.update({k: unicode(v) for k, v in kw.iteritems()}) return self
Allows adding/overriding env vars in the execution context. :param kw: Key-value pairs :return: self
def has_intercept(estimator): # type: (Any) -> bool """ Return True if an estimator has intercept fit. """ if hasattr(estimator, 'fit_intercept'): return estimator.fit_intercept if hasattr(estimator, 'intercept_'): if estimator.intercept_ is None: return False # scikit-learn sets intercept to zero vector if it is not fit return np.any(estimator.intercept_) return False
Return True if an estimator has intercept fit.
def get(self, roleId): """Get a specific role information""" role = db.Role.find_one(Role.role_id == roleId) if not role: return self.make_response('No such role found', HTTP.NOT_FOUND) return self.make_response({'role': role})
Get a specific role information
def _paramf(ins): """ Pushes 40bit (float) param into the stack """ output = _float_oper(ins.quad[1]) output.extend(_fpush()) return output
Pushes 40bit (float) param into the stack
def which(filename): '''This takes a given filename; tries to find it in the environment path; then checks if it is executable. This returns the full path to the filename if found and executable. Otherwise this returns None. Note ---- This function is taken from the pexpect module, see module doc-string for license. ''' # Special case where filename contains an explicit path. if os.path.dirname(filename) != '' and is_executable_file(filename): return filename if 'PATH' not in os.environ or os.environ['PATH'] == '': p = os.defpath else: p = os.environ['PATH'] pathlist = p.split(os.pathsep) for path in pathlist: ff = os.path.join(path, filename) if pty: if is_executable_file(ff): return ff else: pathext = os.environ.get('Pathext', '.exe;.com;.bat;.cmd') pathext = pathext.split(os.pathsep) + [''] for ext in pathext: if os.access(ff + ext, os.X_OK): return ff + ext return None
This takes a given filename; tries to find it in the environment path; then checks if it is executable. This returns the full path to the filename if found and executable. Otherwise this returns None. Note ---- This function is taken from the pexpect module, see module doc-string for license.
def add_path(self, nodes, t=None): """Add a path at time t. Parameters ---------- nodes : iterable container A container of nodes. t : snapshot id (default=None) See Also -------- add_path, add_cycle Examples -------- >>> G = dn.DynGraph() >>> G.add_path([0,1,2,3], t=0) """ nlist = list(nodes) interaction = zip(nlist[:-1], nlist[1:]) self.add_interactions_from(interaction, t)
Add a path at time t. Parameters ---------- nodes : iterable container A container of nodes. t : snapshot id (default=None) See Also -------- add_path, add_cycle Examples -------- >>> G = dn.DynGraph() >>> G.add_path([0,1,2,3], t=0)
def split_qname(qname): """Split `qname` into namespace URI and local name Return namespace and local name as a tuple. This is a static method.""" res = qname.split(YinParser.ns_sep) if len(res) == 1: # no namespace return None, res[0] else: return res
Split `qname` into namespace URI and local name Return namespace and local name as a tuple. This is a static method.
def filter_geoquiet(sat, maxKp=None, filterTime=None, kpData=None, kp_inst=None): """Filters pysat.Instrument data for given time after Kp drops below gate. Loads Kp data for the same timeframe covered by sat and sets sat.data to NaN for times when Kp > maxKp and for filterTime after Kp drops below maxKp. Parameters ---------- sat : pysat.Instrument Instrument to be filtered maxKp : float Maximum Kp value allowed. Kp values above this trigger sat.data filtering. filterTime : int Number of hours to filter data after Kp drops below maxKp kpData : pysat.Instrument (optional) Kp pysat.Instrument object with data already loaded kp_inst : pysat.Instrument (optional) Kp pysat.Instrument object ready to load Kp data.Overrides kpData. Returns ------- None : NoneType sat Instrument object modified in place """ if kp_inst is not None: kp_inst.load(date=sat.date, verifyPad=True) kpData = kp_inst elif kpData is None: kp = pysat.Instrument('sw', 'kp', pad=pds.DateOffset(days=1)) kp.load(date=sat.date, verifyPad=True) kpData = kp if maxKp is None: maxKp = 3+ 1./3. if filterTime is None: filterTime = 24 # now the defaults are ensured, let's do some filtering # date of satellite data date = sat.date selData = kpData[date-pds.DateOffset(days=1):date+pds.DateOffset(days=1)] ind, = np.where(selData['kp'] >= maxKp) for lind in ind: sat.data[selData.index[lind]:(selData.index[lind]+pds.DateOffset(hours=filterTime) )] = np.NaN sat.data = sat.data.dropna(axis=0, how='all') return
Filters pysat.Instrument data for given time after Kp drops below gate. Loads Kp data for the same timeframe covered by sat and sets sat.data to NaN for times when Kp > maxKp and for filterTime after Kp drops below maxKp. Parameters ---------- sat : pysat.Instrument Instrument to be filtered maxKp : float Maximum Kp value allowed. Kp values above this trigger sat.data filtering. filterTime : int Number of hours to filter data after Kp drops below maxKp kpData : pysat.Instrument (optional) Kp pysat.Instrument object with data already loaded kp_inst : pysat.Instrument (optional) Kp pysat.Instrument object ready to load Kp data.Overrides kpData. Returns ------- None : NoneType sat Instrument object modified in place
def ufloatDict_nominal(self, ufloat_dict): 'This gives us a dictionary of nominal values from a dictionary of uncertainties' return OrderedDict(izip(ufloat_dict.keys(), map(lambda x: x.nominal_value, ufloat_dict.values())))
This gives us a dictionary of nominal values from a dictionary of uncertainties
def setup( cls, app_version: str, app_name: str, config_file_path: str, config_sep_str: str, root_path: typing.Optional[typing.List[str]] = None, ): """ Configures elib_config in one fell swoop :param app_version: version of the application :param app_name:name of the application :param config_file_path: path to the config file to use :param config_sep_str: separator for config values paths :param root_path: list of strings that will be pre-pended to *all* config values paths (useful to setup a prefix for the whole app) """ cls.app_version = app_version cls.app_name = app_name cls.config_file_path = config_file_path cls.config_sep_str = config_sep_str cls.root_path = root_path
Configures elib_config in one fell swoop :param app_version: version of the application :param app_name:name of the application :param config_file_path: path to the config file to use :param config_sep_str: separator for config values paths :param root_path: list of strings that will be pre-pended to *all* config values paths (useful to setup a prefix for the whole app)
def convert_basis(basis_dict, fmt, header=None): ''' Returns the basis set data as a string representing the data in the specified output format ''' # make converters case insensitive fmt = fmt.lower() if fmt not in _converter_map: raise RuntimeError('Unknown basis set format "{}"'.format(fmt)) converter = _converter_map[fmt] # Determine if the converter supports all the types in the basis_dict if converter['valid'] is not None: ftypes = set(basis_dict['function_types']) if ftypes > converter['valid']: raise RuntimeError('Converter {} does not support all function types: {}'.format(fmt, str(ftypes))) # Actually do the conversion ret_str = converter['function'](basis_dict) if header is not None and fmt != 'json': comment_str = _converter_map[fmt]['comment'] header_str = comment_str + comment_str.join(header.splitlines(True)) ret_str = header_str + '\n\n' + ret_str # HACK - Psi4 requires the first non-comment line be spherical/cartesian # so we have to add that before the header if fmt == 'psi4': types = basis_dict['function_types'] harm_type = 'spherical' if 'spherical_gto' in types else 'cartesian' ret_str = harm_type + '\n\n' + ret_str return ret_str
Returns the basis set data as a string representing the data in the specified output format
def menu(self, choices, prompt='Please choose from the provided options:', error='Invalid choice', intro=None, strict=True, default=None, numerator=lambda x: [i + 1 for i in range(x)], formatter=lambda x, y: '{0:>3}) {1}'.format(x, y), clean=utils.safeint): """ Print a menu The choices must be an iterable of two-tuples where the first value is the value of the menu item, and the second is the label for that matches the value. The menu will be printed with numeric choices. For example:: 1) foo 2) bar Formatting of the number is controlled by the formatter function which can be overridden by passing the ``formatter`` argument. The numbers used for the menu are generated using the numerator function which can be specified using the ``numerator`` function. This function must take the number of choices and return the same number of items that will be used as choice characters as a list. The cleaner function is passed to ``pvpl()`` method can be customized using ``clean`` argument. This function should generally be customized whenever ``numerator`` is customized, as default cleaner converts input to integers to match the default numerator. Optional ``intro`` argument can be passed to print a message above the menu. The return value of this method is the value user has chosen. The prompt will keep asking the user for input until a valid choice is selected. Each time an invalid selection is made, error message is printed. This message can be customized using ``error`` argument. If ``strict`` argument is set, then only values in choices are allowed, otherwise any value will be allowed. The ``default`` argument can be used to define what value is returned in case user select an invalid value when strict checking is off. """ numbers = list(numerator(len(choices))) labels = (label for _, label in choices) values = [value for value, _ in choices] # Print intro and menu itself if intro: self.pstd('\n' + utils.rewrap_long(intro)) for n, label in zip(numbers, labels): self.pstd(formatter(n, label)) # Define the validator validator = lambda x: x in numbers val = self.rvpl(prompt, error=error, validator=validator, clean=clean, strict=strict, default=default) if not strict and val == default: return val return values[numbers.index(val)]
Print a menu The choices must be an iterable of two-tuples where the first value is the value of the menu item, and the second is the label for that matches the value. The menu will be printed with numeric choices. For example:: 1) foo 2) bar Formatting of the number is controlled by the formatter function which can be overridden by passing the ``formatter`` argument. The numbers used for the menu are generated using the numerator function which can be specified using the ``numerator`` function. This function must take the number of choices and return the same number of items that will be used as choice characters as a list. The cleaner function is passed to ``pvpl()`` method can be customized using ``clean`` argument. This function should generally be customized whenever ``numerator`` is customized, as default cleaner converts input to integers to match the default numerator. Optional ``intro`` argument can be passed to print a message above the menu. The return value of this method is the value user has chosen. The prompt will keep asking the user for input until a valid choice is selected. Each time an invalid selection is made, error message is printed. This message can be customized using ``error`` argument. If ``strict`` argument is set, then only values in choices are allowed, otherwise any value will be allowed. The ``default`` argument can be used to define what value is returned in case user select an invalid value when strict checking is off.
def __output_see(self, see): """ Convert the argument to a @see tag to rest """ if see.startswith('<a href'): # HTML link -- <a href="...">...</a> return self.__html_to_rst(see) elif '"' in see: # Plain text return see else: # Type reference (default) return ':java:ref:`%s`' % (see.replace('#', '.').replace(' ', ''),)
Convert the argument to a @see tag to rest
def _retrieve_all_teams(self, year): """ Find and create Team instances for all teams in the given season. For a given season, parses the specified NCAAB stats table and finds all requested stats. Each team then has a Team instance created which includes all requested stats and a few identifiers, such as the team's name and abbreviation. All of the individual Team instances are added to a list. Note that this method is called directly once Teams is invoked and does not need to be called manually. Parameters ---------- year : string The requested year to pull stats from. """ team_data_dict = {} if not year: year = utils._find_year_for_season('ncaab') doc = pq(BASIC_STATS_URL % year) teams_list = utils._get_stats_table(doc, 'table#basic_school_stats') doc = pq(BASIC_OPPONENT_STATS_URL % year) opp_list = utils._get_stats_table(doc, 'table#basic_opp_stats') doc = pq(ADVANCED_STATS_URL % year) adv_teams_list = utils._get_stats_table(doc, 'table#adv_school_stats') doc = pq(ADVANCED_OPPONENT_STATS_URL % year) adv_opp_list = utils._get_stats_table(doc, 'table#adv_opp_stats') for stats_list in [teams_list, opp_list, adv_teams_list, adv_opp_list]: team_data_dict = self._add_stats_data(stats_list, team_data_dict) for team_name, team_data in team_data_dict.items(): team = Team(team_data['data'], self._conferences_dict[team_name.lower()], year) self._teams.append(team)
Find and create Team instances for all teams in the given season. For a given season, parses the specified NCAAB stats table and finds all requested stats. Each team then has a Team instance created which includes all requested stats and a few identifiers, such as the team's name and abbreviation. All of the individual Team instances are added to a list. Note that this method is called directly once Teams is invoked and does not need to be called manually. Parameters ---------- year : string The requested year to pull stats from.
def module(command, *args): """Run the modulecmd tool and use its Python-formatted output to set the environment variables.""" if 'MODULESHOME' not in os.environ: print('payu: warning: No Environment Modules found; skipping {0} call.' ''.format(command)) return modulecmd = ('{0}/bin/modulecmd'.format(os.environ['MODULESHOME'])) cmd = '{0} python {1} {2}'.format(modulecmd, command, ' '.join(args)) envs, _ = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE).communicate() exec(envs)
Run the modulecmd tool and use its Python-formatted output to set the environment variables.
def edit_securitygroup_rule(self, group_id, rule_id, remote_ip=None, remote_group=None, direction=None, ethertype=None, port_max=None, port_min=None, protocol=None): """Edit a security group rule. :param int group_id: The ID of the security group the rule belongs to :param int rule_id: The ID of the rule to edit :param str remote_ip: The remote IP or CIDR to enforce the rule on :param int remote_group: The remote security group ID to enforce the rule on :param str direction: The direction to enforce (egress or ingress) :param str ethertype: The ethertype to enforce (IPv4 or IPv6) :param str port_max: The upper port bound to enforce :param str port_min: The lower port bound to enforce :param str protocol: The protocol to enforce (icmp, udp, tcp) """ successful = False obj = {} if remote_ip is not None: obj['remoteIp'] = remote_ip if remote_group is not None: obj['remoteGroupId'] = remote_group if direction is not None: obj['direction'] = direction if ethertype is not None: obj['ethertype'] = ethertype if port_max is not None: obj['portRangeMax'] = port_max if port_min is not None: obj['portRangeMin'] = port_min if protocol is not None: obj['protocol'] = protocol if obj: obj['id'] = rule_id successful = self.security_group.editRules([obj], id=group_id) return successful
Edit a security group rule. :param int group_id: The ID of the security group the rule belongs to :param int rule_id: The ID of the rule to edit :param str remote_ip: The remote IP or CIDR to enforce the rule on :param int remote_group: The remote security group ID to enforce the rule on :param str direction: The direction to enforce (egress or ingress) :param str ethertype: The ethertype to enforce (IPv4 or IPv6) :param str port_max: The upper port bound to enforce :param str port_min: The lower port bound to enforce :param str protocol: The protocol to enforce (icmp, udp, tcp)
def get_ga_query_dict(self): """ Adds user agent and IP to the default hit parameters """ query_dict = super(GARequestErrorReportingMixin, self).get_ga_query_dict() request = self.get_ga_request() if not request: return query_dict user_ip = request.META.get('HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_ADDR', '')) user_ip = user_ip.split(',')[0].strip() user_agent = request.META.get('HTTP_USER_AGENT') user_language = request.META.get('HTTP_ACCEPT_LANGUAGE') if user_ip: query_dict['uip'] = user_ip if user_agent: query_dict['ua'] = user_agent if user_language: query_dict['ul'] = user_language return query_dict
Adds user agent and IP to the default hit parameters
def checker(func: Callable) -> Callable: """ A decorator that will convert AssertionErrors into CiVerificationError. :param func: A function that will raise AssertionError :return: The given function wrapped to raise a CiVerificationError on AssertionError """ def func_wrapper(*args, **kwargs): try: func(*args, **kwargs) return True except AssertionError: raise CiVerificationError( 'The verification check for the environment did not pass.' ) return func_wrapper
A decorator that will convert AssertionErrors into CiVerificationError. :param func: A function that will raise AssertionError :return: The given function wrapped to raise a CiVerificationError on AssertionError
def is_valid(self, tree): """ returns true, iff the order of the tokens in the graph are the same as in the Conano file (converted to plain text). """ conano_plaintext = etree.tostring(tree, encoding='utf8', method='text') token_str_list = conano_plaintext.split() for i, plain_token in enumerate(token_str_list): graph_token = self.node[self.tokens[i]][self.ns+':token'] if ensure_unicode(plain_token) != graph_token: sys.stderr.write( "Conano tokenizations don't match: {0} vs. {1} " "({2})".format(plain_token, graph_token)) return False return True
returns true, iff the order of the tokens in the graph are the same as in the Conano file (converted to plain text).
def correct_means(means, opt_t0s, combs): """Applies optimal t0s to gaussians means. Should be around zero afterwards. Parameters ---------- means: numpy array of means of gaussians of all PMT combinations opt_t0s: numpy array of optimal t0 values for all PMTs combs: pmt combinations used to correct Returns ------- corrected_means: numpy array of corrected gaussian means for all PMT combs """ corrected_means = np.array([(opt_t0s[comb[1]] - opt_t0s[comb[0]]) - mean for mean, comb in zip(means, combs)]) return corrected_means
Applies optimal t0s to gaussians means. Should be around zero afterwards. Parameters ---------- means: numpy array of means of gaussians of all PMT combinations opt_t0s: numpy array of optimal t0 values for all PMTs combs: pmt combinations used to correct Returns ------- corrected_means: numpy array of corrected gaussian means for all PMT combs
def has_quantity(self, quantity, include_native=True): """ Check if *quantity* is available in this catalog Parameters ---------- quantity : str a quantity name to check include_native : bool, optional whether or not to include native quantity names when checking Returns ------- has_quantity : bool True if the quantities are all available; otherwise False """ if include_native: return all(q in self._native_quantities for q in self._translate_quantities({quantity})) return quantity in self._quantity_modifiers
Check if *quantity* is available in this catalog Parameters ---------- quantity : str a quantity name to check include_native : bool, optional whether or not to include native quantity names when checking Returns ------- has_quantity : bool True if the quantities are all available; otherwise False
def _af_filter(data, in_file, out_file): """Soft-filter variants with AF below min_allele_fraction (appends "MinAF" to FILTER) """ min_freq = float(utils.get_in(data["config"], ("algorithm", "min_allele_fraction"), 10)) / 100.0 logger.debug("Filtering MuTect2 calls with allele fraction threshold of %s" % min_freq) ungz_out_file = "%s.vcf" % utils.splitext_plus(out_file)[0] if not utils.file_exists(ungz_out_file) and not utils.file_exists(ungz_out_file + ".gz"): with file_transaction(data, ungz_out_file) as tx_out_file: vcf = cyvcf2.VCF(in_file) vcf.add_filter_to_header({ 'ID': 'MinAF', 'Description': 'Allele frequency is lower than %s%% ' % (min_freq*100) + ( '(configured in bcbio as min_allele_fraction)' if utils.get_in(data["config"], ("algorithm", "min_allele_fraction")) else '(default threshold in bcbio; override with min_allele_fraction in the algorithm section)')}) w = cyvcf2.Writer(tx_out_file, vcf) # GATK 3.x can produce VCFs without sample names for empty VCFs try: tumor_index = vcf.samples.index(dd.get_sample_name(data)) except ValueError: tumor_index = None for rec in vcf: if tumor_index is not None and np.all(rec.format('AF')[tumor_index] < min_freq): vcfutils.cyvcf_add_filter(rec, 'MinAF') w.write_record(rec) w.close() return vcfutils.bgzip_and_index(ungz_out_file, data["config"])
Soft-filter variants with AF below min_allele_fraction (appends "MinAF" to FILTER)
def _protobuf_value_type(value): """Returns the type of the google.protobuf.Value message as an api.DataType. Returns None if the type of 'value' is not one of the types supported in api_pb2.DataType. Args: value: google.protobuf.Value message. """ if value.HasField("number_value"): return api_pb2.DATA_TYPE_FLOAT64 if value.HasField("string_value"): return api_pb2.DATA_TYPE_STRING if value.HasField("bool_value"): return api_pb2.DATA_TYPE_BOOL return None
Returns the type of the google.protobuf.Value message as an api.DataType. Returns None if the type of 'value' is not one of the types supported in api_pb2.DataType. Args: value: google.protobuf.Value message.
def run_checks(self): """ Iterates over the configured ports and runs the checks on each one. Returns a two-element tuple: the first is the set of ports that transitioned from down to up, the second is the set of ports that transitioned from up to down. Also handles the case where a check for a since-removed port is run, marking the port as down regardless of the check's result and removing the check(s) for the port. """ came_up = set() went_down = set() for port in self.ports: checks = self.checks[port].values() if not checks: logger.warn("No checks defined for self: %s", self.name) for check in checks: check.run() checks_pass = all([check.passing for check in checks]) if self.is_up[port] in (False, None) and checks_pass: came_up.add(port) self.is_up[port] = True elif self.is_up[port] in (True, None) and not checks_pass: went_down.add(port) self.is_up[port] = False for unused_port in set(self.checks.keys()) - self.ports: went_down.add(unused_port) del self.checks[unused_port] return came_up, went_down
Iterates over the configured ports and runs the checks on each one. Returns a two-element tuple: the first is the set of ports that transitioned from down to up, the second is the set of ports that transitioned from up to down. Also handles the case where a check for a since-removed port is run, marking the port as down regardless of the check's result and removing the check(s) for the port.
def input_data_ports(self, input_data_ports): """Property for the _input_data_ports field See Property. :param dict input_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type :class:`rafcon.core.state_elements.data_port.InputDataPort` :raises exceptions.TypeError: if the input_data_ports parameter has the wrong type :raises exceptions.AttributeError: if the key of the input dictionary and the id of the data port do not match """ if not isinstance(input_data_ports, dict): raise TypeError("input_data_ports must be of type dict") if [port_id for port_id, port in input_data_ports.items() if not port_id == port.data_port_id]: raise AttributeError("The key of the input dictionary and the id of the data port do not match") # This is a fix for older state machines, which didn't distinguish between input and output ports for port_id, port in input_data_ports.items(): if not isinstance(port, InputDataPort): if isinstance(port, DataPort): port = InputDataPort(port.name, port.data_type, port.default_value, port.data_port_id) input_data_ports[port_id] = port else: raise TypeError("Elements of input_data_ports must be of type InputDataPort, given: {0}".format( type(port).__name__)) old_input_data_ports = self._input_data_ports self._input_data_ports = input_data_ports for port_id, port in input_data_ports.items(): try: port.parent = self except ValueError: self._input_data_ports = old_input_data_ports raise # check that all old_input_data_ports are no more referencing self as there parent for old_input_data_port in old_input_data_ports.values(): if old_input_data_port not in self._input_data_ports.values() and old_input_data_port.parent is self: old_input_data_port.parent = None
Property for the _input_data_ports field See Property. :param dict input_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type :class:`rafcon.core.state_elements.data_port.InputDataPort` :raises exceptions.TypeError: if the input_data_ports parameter has the wrong type :raises exceptions.AttributeError: if the key of the input dictionary and the id of the data port do not match
def delete_node(self, loadbalancer, node): """Removes the node from its load balancer.""" lb = node.parent if not lb: raise exc.UnattachedNode("No parent Load Balancer for this node " "could be determined.") resp, body = self.api.method_delete("/loadbalancers/%s/nodes/%s" % (lb.id, node.id)) return resp, body
Removes the node from its load balancer.
def parameter_vector(self): """An array of all parameters (including frozen parameters)""" return np.array([getattr(self, k) for k in self.parameter_names])
An array of all parameters (including frozen parameters)
def _open(self): """ open input file, optionally with decompression """ if self.fileName.endswith(".gz"): return gzip.open(self.fileName) elif self.fileName.endswith(".bz2"): return bz2.BZ2File(self.fileName) else: return open(self.fileName)
open input file, optionally with decompression
def extract_params(raw): """Extract parameters and return them as a list of 2-tuples. Will successfully extract parameters from urlencoded query strings, dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an empty list of parameters. Any other input will result in a return value of None. """ if isinstance(raw, (bytes, unicode_type)): try: params = urldecode(raw) except ValueError: params = None elif hasattr(raw, '__iter__'): try: dict(raw) except ValueError: params = None except TypeError: params = None else: params = list(raw.items() if isinstance(raw, dict) else raw) params = decode_params_utf8(params) else: params = None return params
Extract parameters and return them as a list of 2-tuples. Will successfully extract parameters from urlencoded query strings, dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an empty list of parameters. Any other input will result in a return value of None.
def low(data, **kwargs): ''' Execute a single low data call This function is mostly intended for testing the state system CLI Example: .. code-block:: bash salt '*' state.low '{"state": "pkg", "fun": "installed", "name": "vi"}' ''' st_kwargs = __salt__.kwargs __opts__['grains'] = __grains__ chunks = [data] st_ = salt.client.ssh.state.SSHHighState( __opts__, __pillar__, __salt__, __context__['fileclient']) for chunk in chunks: chunk['__id__'] = chunk['name'] if not chunk.get('__id__') else chunk['__id__'] err = st_.state.verify_data(data) if err: return err file_refs = salt.client.ssh.state.lowstate_file_refs( chunks, _merge_extra_filerefs( kwargs.get('extra_filerefs', ''), __opts__.get('extra_filerefs', '') ) ) roster = salt.roster.Roster(__opts__, __opts__.get('roster', 'flat')) roster_grains = roster.opts['grains'] # Create the tar containing the state pkg and relevant files. trans_tar = salt.client.ssh.state.prep_trans_tar( __context__['fileclient'], chunks, file_refs, __pillar__, st_kwargs['id_'], roster_grains) trans_tar_sum = salt.utils.hashutils.get_hash(trans_tar, __opts__['hash_type']) cmd = 'state.pkg {0}/salt_state.tgz pkg_sum={1} hash_type={2}'.format( __opts__['thin_dir'], trans_tar_sum, __opts__['hash_type']) single = salt.client.ssh.Single( __opts__, cmd, fsclient=__context__['fileclient'], minion_opts=__salt__.minion_opts, **st_kwargs) single.shell.send( trans_tar, '{0}/salt_state.tgz'.format(__opts__['thin_dir'])) stdout, stderr, _ = single.cmd_block() # Clean up our tar try: os.remove(trans_tar) except (OSError, IOError): pass # Read in the JSON data and return the data structure try: return salt.utils.json.loads(stdout) except Exception as e: log.error("JSON Render failed for: %s\n%s", stdout, stderr) log.error(six.text_type(e)) # If for some reason the json load fails, return the stdout return stdout
Execute a single low data call This function is mostly intended for testing the state system CLI Example: .. code-block:: bash salt '*' state.low '{"state": "pkg", "fun": "installed", "name": "vi"}'
def fire_metric(metric_name, metric_value): """ Fires a metric using the MetricsApiClient """ metric_value = float(metric_value) metric = {metric_name: metric_value} metric_client.fire_metrics(**metric) return "Fired metric <{}> with value <{}>".format(metric_name, metric_value)
Fires a metric using the MetricsApiClient
def _get(self, obj): ''' Internal implementation of instance attribute access for the ``BasicPropertyDescriptor`` getter. If the value has not been explicitly set by a user, return that value. Otherwise, return the default. Args: obj (HasProps) : the instance to get a value of this property for Returns: object Raises: RuntimeError If the |HasProps| instance has not yet been initialized, or if this descriptor is on a class that is not a |HasProps|. ''' if not hasattr(obj, '_property_values'): raise RuntimeError("Cannot get a property value '%s' from a %s instance before HasProps.__init__" % (self.name, obj.__class__.__name__)) if self.name not in obj._property_values: return self._get_default(obj) else: return obj._property_values[self.name]
Internal implementation of instance attribute access for the ``BasicPropertyDescriptor`` getter. If the value has not been explicitly set by a user, return that value. Otherwise, return the default. Args: obj (HasProps) : the instance to get a value of this property for Returns: object Raises: RuntimeError If the |HasProps| instance has not yet been initialized, or if this descriptor is on a class that is not a |HasProps|.
async def get_models(self, all_=False, username=None): """ .. deprecated:: 0.7.0 Use :meth:`.list_models` instead. """ controller_facade = client.ControllerFacade.from_connection( self.connection()) for attempt in (1, 2, 3): try: return await controller_facade.AllModels() except errors.JujuAPIError as e: # retry concurrency error until resolved in Juju # see: https://bugs.launchpad.net/juju/+bug/1721786 if 'has been removed' not in e.message or attempt == 3: raise
.. deprecated:: 0.7.0 Use :meth:`.list_models` instead.
def receive(self): """ :rtype: bytes """ try: return self.socket.recv(self.__recv_bytes) except socket.error: _, e, _ = sys.exc_info() if get_errno(e) in (errno.EAGAIN, errno.EINTR): log.debug("socket read interrupted, restarting") raise exception.InterruptedException() if self.is_connected(): raise
:rtype: bytes
def import_module(path): """ Import a module given a dotted *path* in the form of ``.name(.name)*``, and returns the last module (unlike ``__import__`` which just returns the first module). :param path: The dotted path to the module. """ mod = __import__(path, locals={}, globals={}) for item in path.split('.')[1:]: try: mod = getattr(mod, item) except AttributeError: raise ImportError('No module named %s' % path) return mod
Import a module given a dotted *path* in the form of ``.name(.name)*``, and returns the last module (unlike ``__import__`` which just returns the first module). :param path: The dotted path to the module.
def modify_agent(self, agent_id, **kwargs): ''' modify_agent(self, agent_id, **kwargs) | Modifies agent information (like name) :Parameters: * *agent_id* (`string`) -- Identifier of an existing agent :Example: .. code-block:: python opereto_client = OperetoClient() opereto_client.modify_agent('agentId', name='my new name') ''' request_data = {'id': agent_id} request_data.update(**kwargs) return self._call_rest_api('post', '/agents'+'', data=request_data, error='Failed to modify agent [%s]'%agent_id)
modify_agent(self, agent_id, **kwargs) | Modifies agent information (like name) :Parameters: * *agent_id* (`string`) -- Identifier of an existing agent :Example: .. code-block:: python opereto_client = OperetoClient() opereto_client.modify_agent('agentId', name='my new name')
def beautify_date(inasafe_time, feature, parent): """Given an InaSAFE analysis time, it will convert it to a date with year-month-date format. For instance: * beautify_date( @start_datetime ) -> will convert datetime provided by qgis_variable. """ _ = feature, parent # NOQA datetime_object = parse(inasafe_time) date = datetime_object.strftime('%Y-%m-%d') return date
Given an InaSAFE analysis time, it will convert it to a date with year-month-date format. For instance: * beautify_date( @start_datetime ) -> will convert datetime provided by qgis_variable.
def smartfields_get_field_status(self, field_name): """A way to find out a status of a filed.""" manager = self._smartfields_managers.get(field_name, None) if manager is not None: return manager.get_status(self) return {'state': 'ready'}
A way to find out a status of a filed.
def _regex_strings(self): """ A property to link into IntentEngine's _regex_strings. Warning: this is only for backwards compatiblility and should not be used if you intend on using domains. Returns: the domains _regex_strings from its IntentEngine """ domain = 0 if domain not in self.domains: self.register_domain(domain=domain) return self.domains[domain]._regex_strings
A property to link into IntentEngine's _regex_strings. Warning: this is only for backwards compatiblility and should not be used if you intend on using domains. Returns: the domains _regex_strings from its IntentEngine
def main(argv=None): """ Make a confidence report and save it to disk. """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) print(filepath) make_confidence_report_bundled(filepath=filepath, test_start=FLAGS.test_start, test_end=FLAGS.test_end, which_set=FLAGS.which_set, recipe=FLAGS.recipe, report_path=FLAGS.report_path, batch_size=FLAGS.batch_size)
Make a confidence report and save it to disk.
def get_atlas_peers(hostport, timeout=30, my_hostport=None, proxy=None): """ Get an atlas peer's neighbors. Return {'status': True, 'peers': [peers]} on success. Return {'error': ...} on error """ assert hostport or proxy, 'need either hostport or proxy' peers_schema = { 'type': 'object', 'properties': { 'peers': { 'type': 'array', 'items': { 'type': 'string', 'pattern': '^([^:]+):([1-9][0-9]{1,4})$', }, }, }, 'required': [ 'peers' ], } schema = json_response_schema( peers_schema ) if proxy is None: proxy = connect_hostport(hostport) peers = None try: peer_list_resp = proxy.get_atlas_peers() peer_list_resp = json_validate(schema, peer_list_resp) if json_is_error(peer_list_resp): return peer_list_resp # verify that all strings are host:ports for peer_hostport in peer_list_resp['peers']: peer_host, peer_port = url_to_host_port(peer_hostport) if peer_host is None or peer_port is None: return {'error': 'Server did not return valid Atlas peers', 'http_status': 503} peers = peer_list_resp except ValidationError as ve: if BLOCKSTACK_DEBUG: log.exception(ve) resp = {'error': 'Server response did not match expected schema. You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502} return resp except socket.timeout: log.error("Connection timed out") resp = {'error': 'Connection to remote host timed out.', 'http_status': 503} return resp except socket.error as se: log.error("Connection error {}".format(se.errno)) resp = {'error': 'Connection to remote host failed.', 'http_status': 502} return resp except Exception as ee: if BLOCKSTACK_DEBUG: log.exception(ee) log.error("Caught exception while connecting to Blockstack node: {}".format(ee)) resp = {'error': 'Failed to contact Blockstack node {}. Try again with `--debug`.'.format(hostport), 'http_status': 500} return resp return peers
Get an atlas peer's neighbors. Return {'status': True, 'peers': [peers]} on success. Return {'error': ...} on error
def QA_fetch_get_hkindex_list(ip=None, port=None): """[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) # 港股 HKMARKET 27 5 香港指数 FH 31 2 香港主板 KH 48 2 香港创业板 KG 49 2 香港基金 KT 43 1 B股转H股 HB """ global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_list return extension_market_list.query('market==27')
[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) # 港股 HKMARKET 27 5 香港指数 FH 31 2 香港主板 KH 48 2 香港创业板 KG 49 2 香港基金 KT 43 1 B股转H股 HB
def _servicegroup_get_servers(sg_name, **connection_args): ''' Returns a list of members of a servicegroup or None ''' nitro = _connect(**connection_args) if nitro is None: return None sg = NSServiceGroup() sg.set_servicegroupname(sg_name) try: sg = NSServiceGroup.get_servers(nitro, sg) except NSNitroError as error: log.debug('netscaler module error - NSServiceGroup.get_servers failed(): %s', error) sg = None _disconnect(nitro) return sg
Returns a list of members of a servicegroup or None
def _setup_logging(self): """ This is done in the :class:`Router` constructor for historical reasons. It must be called before ExternalContext logs its first messages, but after logging has been setup. It must also be called when any router is constructed for a consumer app. """ # Here seems as good a place as any. global _v, _vv _v = logging.getLogger().level <= logging.DEBUG _vv = IOLOG.level <= logging.DEBUG
This is done in the :class:`Router` constructor for historical reasons. It must be called before ExternalContext logs its first messages, but after logging has been setup. It must also be called when any router is constructed for a consumer app.
def join(self, file): """Find the named object in this tree's contents :return: ``git.Blob`` or ``git.Tree`` or ``git.Submodule`` :raise KeyError: if given file or tree does not exist in tree""" msg = "Blob or Tree named %r not found" if '/' in file: tree = self item = self tokens = file.split('/') for i, token in enumerate(tokens): item = tree[token] if item.type == 'tree': tree = item else: # safety assertion - blobs are at the end of the path if i != len(tokens) - 1: raise KeyError(msg % file) return item # END handle item type # END for each token of split path if item == self: raise KeyError(msg % file) return item else: for info in self._cache: if info[2] == file: # [2] == name return self._map_id_to_type[info[1] >> 12](self.repo, info[0], info[1], join_path(self.path, info[2])) # END for each obj raise KeyError(msg % file)
Find the named object in this tree's contents :return: ``git.Blob`` or ``git.Tree`` or ``git.Submodule`` :raise KeyError: if given file or tree does not exist in tree