code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _to_sqlite3_by_table(self, conn, table_name): """ Saves the sequence to the specified table of sqlite3 database. Each element can be a dictionary, namedtuple, tuple or list. Target table must be created in advance. :param conn: path or sqlite connection, cursor :para...
Saves the sequence to the specified table of sqlite3 database. Each element can be a dictionary, namedtuple, tuple or list. Target table must be created in advance. :param conn: path or sqlite connection, cursor :param table_name: table name string
def add_to_recent(self, notebook): """ Add an entry to recent notebooks. We only maintain the list of the 20 most recent notebooks. """ if notebook not in self.recent_notebooks: self.recent_notebooks.insert(0, notebook) self.recent_notebooks = sel...
Add an entry to recent notebooks. We only maintain the list of the 20 most recent notebooks.
def create(self, width, height): """Create an image of type. Parameters ---------- width: `int` Image width. height: `int` Image height. Returns ------- `PIL.Image.Image` """ return Image.new(self.mode, (width, hei...
Create an image of type. Parameters ---------- width: `int` Image width. height: `int` Image height. Returns ------- `PIL.Image.Image`
def call_from_executor(self, callback, _max_postpone_until=None): """ Call this function in the main event loop. Similar to Twisted's ``callFromThread``. :param _max_postpone_until: `None` or `time.time` value. For interal use. If the eventloop is saturated, consider this ta...
Call this function in the main event loop. Similar to Twisted's ``callFromThread``. :param _max_postpone_until: `None` or `time.time` value. For interal use. If the eventloop is saturated, consider this task to be low priority and postpone maximum until this timestamp. (For inst...
def GetTransPosition(df,field,dic,refCol="transcript_id"): """ Maps a genome position to transcript positon" :param df: a Pandas dataframe :param field: the head of the column containing the genomic position :param dic: a dictionary containing for each transcript the respective bases eg. {ENST23923...
Maps a genome position to transcript positon" :param df: a Pandas dataframe :param field: the head of the column containing the genomic position :param dic: a dictionary containing for each transcript the respective bases eg. {ENST23923910:'234,235,236,1021,..'} :param refCol: header of the reference c...
def onCancelButton(self, event): """ Quit grid with warning if unsaved changes present """ if self.grid.changes: dlg1 = wx.MessageDialog(self, caption="Message:", message="Are you sure you want to exit this grid?\nYour changes will not be s...
Quit grid with warning if unsaved changes present
def examples_section(doc, header_level): """ Generate markdown for Examples section. Parameters ---------- doc : dict Dict from numpydoc header_level : int Number of `#`s to use for header Returns ------- list of str Markdown for examples section """ ...
Generate markdown for Examples section. Parameters ---------- doc : dict Dict from numpydoc header_level : int Number of `#`s to use for header Returns ------- list of str Markdown for examples section
def get_inflators_cn_to_cn(target_year): ''' Calcule l'inflateur de vieillissement à partir des masses de comptabilité nationale. ''' data_year = find_nearest_inferior(data_years, target_year) data_year_cn_aggregates = get_cn_aggregates(data_year)['consoCN_COICOP_{}'.format(data_year)].to_dict()...
Calcule l'inflateur de vieillissement à partir des masses de comptabilité nationale.
def _get_body_instance(self): """Return the body instance.""" simple_body = { MultipartType.OFPMP_FLOW: FlowStatsRequest, MultipartType.OFPMP_AGGREGATE: AggregateStatsRequest, MultipartType.OFPMP_PORT_STATS: PortStatsRequest, MultipartType.OFPMP_QUEUE: Que...
Return the body instance.
def _sumLists(a, b): """ Algorithm to check validity of NBI and NIF. Receives string with a umber to validate. """ val = 0 for i in map(lambda a, b: a * b, a, b): val += i return val
Algorithm to check validity of NBI and NIF. Receives string with a umber to validate.
def add_handler_spec(f, handler_spec, *, kwargs=None): """ Attach a handler specification (see :class:`HandlerSpec`) to a function. :param f: Function to attach the handler specification to. :param handler_spec: Handler specification to attach to the function. :type handler_spec: :class:`HandlerSpe...
Attach a handler specification (see :class:`HandlerSpec`) to a function. :param f: Function to attach the handler specification to. :param handler_spec: Handler specification to attach to the function. :type handler_spec: :class:`HandlerSpec` :param kwargs: additional keyword arguments passed to the fu...
def pick_four_unique_nodes_quickly(n, seed=None): ''' This is equivalent to np.random.choice(n, 4, replace=False) Another fellow suggested np.random.random_sample(n).argpartition(4) which is clever but still substantially slower. ''' rng = get_rng(seed) k = rng.randint(n**4) a = k % n ...
This is equivalent to np.random.choice(n, 4, replace=False) Another fellow suggested np.random.random_sample(n).argpartition(4) which is clever but still substantially slower.
def get_listeners(self, event_type: str) -> List[Callable]: """Get all listeners of a particular type of event.""" if event_type not in self.events: raise ValueError(f'No event {event_type} in system.') return self.events.get_listeners(event_type)
Get all listeners of a particular type of event.
def plotEzJz(self,*args,**kwargs): """ NAME: plotEzJz PURPOSE: plot E_z(.)/sqrt(dens(R)) along the orbit INPUT: pot= Potential instance or list of instances in which the orbit was integrated d1= - plot Ez vs d1: e.g., 't', 'z',...
NAME: plotEzJz PURPOSE: plot E_z(.)/sqrt(dens(R)) along the orbit INPUT: pot= Potential instance or list of instances in which the orbit was integrated d1= - plot Ez vs d1: e.g., 't', 'z', 'R', 'vR', 'vT', 'vz' +bovy_plot.bovy...
def get_adapter_for_persistent_model(self, persistent_model, rest_model=None): """ :param persistent_model: instance of persistent model :param rest_model: specific REST model :return: the matching model adapter :rtype: ModelAdapter """ persistent_signature = self...
:param persistent_model: instance of persistent model :param rest_model: specific REST model :return: the matching model adapter :rtype: ModelAdapter
async def expand_now(self, building: UnitTypeId=None, max_distance: Union[int, float]=10, location: Optional[Point2]=None): """Takes new expansion.""" if not building: # self.race is never Race.Random start_townhall_type = {Race.Protoss: UnitTypeId.NEXUS, Race.Terran: UnitTypeId...
Takes new expansion.
def uri_tree_encode(uri_tree, type_host = HOST_REG_NAME): """ Percent/Query encode a raw URI tree. """ scheme, authority, path, query, fragment = uri_tree if authority: user, passwd, host, port = authority if user: user = pct_encode(user, USER_ENCDCT) if passwd: ...
Percent/Query encode a raw URI tree.
def get_ip(request): """Return the IP address inside the HTTP_X_FORWARDED_FOR var inside the `request` object. The return of this function can be overrided by the `LOCAL_GEOLOCATION_IP` variable in the `conf` module. This function will skip local IPs (starting with 10. and equals to 127.0.0.1)...
Return the IP address inside the HTTP_X_FORWARDED_FOR var inside the `request` object. The return of this function can be overrided by the `LOCAL_GEOLOCATION_IP` variable in the `conf` module. This function will skip local IPs (starting with 10. and equals to 127.0.0.1).
def search_in_dirs(fname, search_dpaths=[], shortcircuit=True, return_tried=False, strict=False): """ search_in_dirs Args: fname (str): file name search_dpaths (list): shortcircuit (bool): return_tried (bool): return tried paths strict (bool): (de...
search_in_dirs Args: fname (str): file name search_dpaths (list): shortcircuit (bool): return_tried (bool): return tried paths strict (bool): (default = False) Returns: fpath: None Example: >>> # DISABLE_DOCTEST >>> import utool as ut ...
def psql_csv_run(sql_command, error_handler=None): """ Runs psql and returns a CSVReader object from the query This CSVReader includes header names as the first record in all situations. The output is fully buffered into Python. """ csv_query = ('COPY ({query}) TO STDOUT WITH CSV HEADER;' ...
Runs psql and returns a CSVReader object from the query This CSVReader includes header names as the first record in all situations. The output is fully buffered into Python.
def release(self, tid, fh): """ Close file. Descriptor is removed from ``self.fds``. Parameters ---------- tid : str Path to file. Ignored. fh : int File descriptor to release. """ try: try: self.fds[f...
Close file. Descriptor is removed from ``self.fds``. Parameters ---------- tid : str Path to file. Ignored. fh : int File descriptor to release.
def containsUid(self, uid): ''' containsUid - Check if the uid (unique internal ID) appears anywhere as a direct child to this node, or the node itself. @param uid <uuid.UUID> - uuid to check @return <bool> - True if #uid is this node's uid, or is the uid of any childre...
containsUid - Check if the uid (unique internal ID) appears anywhere as a direct child to this node, or the node itself. @param uid <uuid.UUID> - uuid to check @return <bool> - True if #uid is this node's uid, or is the uid of any children at any level down
def _post_md5_skip_on_check(self, key, filename, size, md5_match): # type: (Downloader, str, str, int, bool) -> None """Perform post MD5 skip on check :param Downloader self: this :param str key: md5 map key :param str filename: local filename :param int size: size of che...
Perform post MD5 skip on check :param Downloader self: this :param str key: md5 map key :param str filename: local filename :param int size: size of checked data :param bool md5_match: if MD5 matches
def updateEvolution(self): ''' Updates the "population punk proportion" evolution array. Fasion victims believe that the proportion of punks in the subsequent period is a linear function of the proportion of punks this period, subject to a uniform shock. Given attributes of sel...
Updates the "population punk proportion" evolution array. Fasion victims believe that the proportion of punks in the subsequent period is a linear function of the proportion of punks this period, subject to a uniform shock. Given attributes of self pNextIntercept, pNextSlope, pNextCount, ...
def login(context, request): """ Login Route Login route to authenticate a user against Plone. """ # extract the data __ac_name = request.get("__ac_name", None) __ac_password = request.get("__ac_password", None) logger.info("*** LOGIN %s ***" % __ac_name) if __ac_name is None: ...
Login Route Login route to authenticate a user against Plone.
def pp_file_to_dataframe(pp_filename): """ read a pilot point file to a pandas Dataframe Parameters ---------- pp_filename : str pilot point file Returns ------- df : pandas.DataFrame a dataframe with pp_utils.PP_NAMES for columns """ df = pd.read_csv(pp_filename...
read a pilot point file to a pandas Dataframe Parameters ---------- pp_filename : str pilot point file Returns ------- df : pandas.DataFrame a dataframe with pp_utils.PP_NAMES for columns
def _get_dvs(service_instance, dvs_name): ''' Return a reference to a Distributed Virtual Switch object. :param service_instance: PyVmomi service instance :param dvs_name: Name of DVS to return :return: A PyVmomi DVS object ''' switches = list_dvs(service_instance) if dvs_name in switch...
Return a reference to a Distributed Virtual Switch object. :param service_instance: PyVmomi service instance :param dvs_name: Name of DVS to return :return: A PyVmomi DVS object
def example(self) -> str: """ Same as str(self), except the color codes are actually used. """ if self.rgb_mode: colorcode = '\033[38;2;{};{};{}m'.format(*self.rgb) else: colorcode = '\033[38;5;{}m'.format(self.code) return '{code}{s}\033[0m'.format(code=colorcode...
Same as str(self), except the color codes are actually used.
def ajax_count_plus(self, slug): ''' post count plus one via ajax. ''' output = { 'status': 1 if MWiki.view_count_plus(slug) else 0, } return json.dump(output, self)
post count plus one via ajax.
def simBirth(self,which_agents): ''' Makes new consumers for the given indices. Initialized variables include aNrm, as well as time variables t_age and t_cycle. Normalized assets are drawn from a lognormal distributions given by aLvlInitMean and aLvlInitStd. Parameters ...
Makes new consumers for the given indices. Initialized variables include aNrm, as well as time variables t_age and t_cycle. Normalized assets are drawn from a lognormal distributions given by aLvlInitMean and aLvlInitStd. Parameters ---------- which_agents : np.array(Bool) ...
def get_selinux_context(path): ''' Get an SELinux context from a given path CLI Example: .. code-block:: bash salt '*' file.get_selinux_context /etc/hosts ''' out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False) try: ret = re.search(r'\w+:\w+:\w+:\w+', out).g...
Get an SELinux context from a given path CLI Example: .. code-block:: bash salt '*' file.get_selinux_context /etc/hosts
def destroy_balancer(balancer_id, profile, **libcloud_kwargs): ''' Destroy a load balancer :param balancer_id: LoadBalancer ID which should be used :type balancer_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's ...
Destroy a load balancer :param balancer_id: LoadBalancer ID which should be used :type balancer_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's destroy_balancer method :type libcloud_kwargs: ``dict`` :return: ...
def _aggregate_one_result( self, sock_info, slave_ok, cmd, collation=None, session=None): """Internal helper to run an aggregate that returns a single result.""" result = self._command( sock_info, cmd, slave_ok, codec_options=self.__write_respo...
Internal helper to run an aggregate that returns a single result.
def _dataframe_from_csv(reader, delimiter, with_header, skipspace): """Returns csv data as a pandas Dataframe object""" sep = delimiter header = 0 if not with_header: header = None return pd.read_csv( reader, header=header, sep=sep, skipinitialspace=skipspace...
Returns csv data as a pandas Dataframe object
def template(self, key): """ Returns the template associated with this scaffold. :param key | <str> :return <projex.scaffold.Template> || None """ try: return self._templates[key] except KeyError: return Template....
Returns the template associated with this scaffold. :param key | <str> :return <projex.scaffold.Template> || None
def load_parameter_definitions(self, sheet_name: str = None): """ Load variable text from rows in excel file. If no spreadsheet arg is given, all spreadsheets are loaded. The first cell in the first row in a spreadsheet must contain the keyword 'variable' or the sheet is ignored. ...
Load variable text from rows in excel file. If no spreadsheet arg is given, all spreadsheets are loaded. The first cell in the first row in a spreadsheet must contain the keyword 'variable' or the sheet is ignored. Any cells used as titles (with no associated value) are also added to the return...
def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_...
Network lifecycle events handler
def record_make_all_subfields_volatile(rec): """ Turns all subfields to volatile """ for tag in rec.keys(): for field_position, field in enumerate(rec[tag]): for subfield_position, subfield in enumerate(field[0]): if subfield[1][:9] != "VOLATILE:": ...
Turns all subfields to volatile
def _CreateReadAccessHelper(self): """Creates a CheckAccessHelper for controlling read access. This function and _CreateQueryAccessHelper essentially define GRR's ACL policy. Please refer to these 2 functions to either review or modify GRR's ACLs. Read access gives you the ability to open and read...
Creates a CheckAccessHelper for controlling read access. This function and _CreateQueryAccessHelper essentially define GRR's ACL policy. Please refer to these 2 functions to either review or modify GRR's ACLs. Read access gives you the ability to open and read aff4 objects for which you already ha...
def fetch(self): """ Fetch a TaskQueueInstance :returns: Fetched TaskQueueInstance :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, ...
Fetch a TaskQueueInstance :returns: Fetched TaskQueueInstance :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance
def get_top(modality_type, value=None): """Gets default top transformation; if none available, return value.""" if modality_type in (ModalityType.AUDIO, ModalityType.AUDIO_SPECTRAL, ModalityType.GENERIC_L2_LOSS, ModalityType.IDENTITY, ...
Gets default top transformation; if none available, return value.
def register_whoosheer(self, wh): """This will register the given whoosher on `whoosheers`, create the neccessary SQLAlchemy event listeners, replace the `query_class` with our own query class which will provide the search functionality and store the app on the whoosheer, so that we can ...
This will register the given whoosher on `whoosheers`, create the neccessary SQLAlchemy event listeners, replace the `query_class` with our own query class which will provide the search functionality and store the app on the whoosheer, so that we can always work with that. :param...
def tag(self, path, name): ''' Change name associated with path ''' if not path[len(path) - 1] == '/': path += '/' config = self.get_config() folder = self.find_folder({ 'path' : path }, config) if not folder: raise custom_errors.FileNotInConfig(path) old_name...
Change name associated with path
def get_analysis_data_for(self, ar): """Return the Analysis data for this AR """ # Exclude analyses from children (partitions) analyses = ar.objectValues("Analysis") out = [] for an in analyses: info = self.get_base_info(an) info.update({ ...
Return the Analysis data for this AR
def raw(self, query, settings=None, stream=False): ''' Performs a query and returns its output as text. - `query`: the SQL query to execute. - `settings`: query settings to send as HTTP GET parameters - `stream`: if true, the HTTP response from ClickHouse will be streamed. ...
Performs a query and returns its output as text. - `query`: the SQL query to execute. - `settings`: query settings to send as HTTP GET parameters - `stream`: if true, the HTTP response from ClickHouse will be streamed.
def calculate_perf_counter_100ns_queuelen_type(previous, current, property_name): """ PERF_COUNTER_100NS_QUEUELEN_TYPE Average length of a queue to a resource over time in 100 nanosecond units. https://msdn.microsoft.com/en-us/library/aa392905(v=vs.85).aspx Formula (n1 - n0) / (d1 - d0) """ ...
PERF_COUNTER_100NS_QUEUELEN_TYPE Average length of a queue to a resource over time in 100 nanosecond units. https://msdn.microsoft.com/en-us/library/aa392905(v=vs.85).aspx Formula (n1 - n0) / (d1 - d0)
def log_analyzer2(path): """This procedure considers every line which can't be parsed as a line with ERROR level. """ with handle(MalformedLogEntryError, lambda (c): invoke_restart('reparse', 'ERROR: ' + c.text)): for f...
This procedure considers every line which can't be parsed as a line with ERROR level.
def connect(self, *args, **kwargs): """Attempt to establish connection, see :meth:`.CMClient.connect`""" self._bootstrap_cm_list_from_file() CMClient.connect(self, *args, **kwargs)
Attempt to establish connection, see :meth:`.CMClient.connect`
def get_vm(self, resource_group_name, vm_name): ''' you need to retry this just in case the credentials token expires, that's where the decorator comes in this will return all the data about the virtual machine ''' return self.client.virtual_machines.get( reso...
you need to retry this just in case the credentials token expires, that's where the decorator comes in this will return all the data about the virtual machine
def from_string(cls, string, format_=None, fps=None, **kwargs): """ Load subtitle file from string. See :meth:`SSAFile.load()` for full description. Arguments: string (str): Subtitle file in a string. Note that the string must be Unicode (in Python 2). ...
Load subtitle file from string. See :meth:`SSAFile.load()` for full description. Arguments: string (str): Subtitle file in a string. Note that the string must be Unicode (in Python 2). Returns: SSAFile Example: >>> text = ''' ...
def unpack_rows(self, column_types, connection): """Unpack rows for data (from a select statement) from payload and yield a single row at a time. :param column_types: a tuple of column descriptors e.g. (<class 'pyhdb.protocol.types.String'>, <class 'pyhdb.protocol.types.ClobType'>) ...
Unpack rows for data (from a select statement) from payload and yield a single row at a time. :param column_types: a tuple of column descriptors e.g. (<class 'pyhdb.protocol.types.String'>, <class 'pyhdb.protocol.types.ClobType'>) :param connection: a db connection object :returns...
def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for...
Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The ...
def duplicate_files(self): ''' Search for duplicates of submission file uploads for this assignment. This includes the search in other course, whether inactive or not. Returns a list of lists, where each latter is a set of duplicate submissions with at least on of them for this a...
Search for duplicates of submission file uploads for this assignment. This includes the search in other course, whether inactive or not. Returns a list of lists, where each latter is a set of duplicate submissions with at least on of them for this assignment
def insert_pattern(pattern, model, index=0): """ Inserts given pattern into given Model. :param pattern: Pattern. :type pattern: unicode :param model: Model. :type model: PatternsModel :param index: Insertion indes. :type index: int :return: Metho...
Inserts given pattern into given Model. :param pattern: Pattern. :type pattern: unicode :param model: Model. :type model: PatternsModel :param index: Insertion indes. :type index: int :return: Method success. :rtype: bool
def url(context, view, subdomain=UNSET, *args, **kwargs): """ Resolves a URL in a template, using subdomain-based URL resolution. If no subdomain is provided and a ``request`` is in the template context when rendering, the URL will be resolved relative to the current request's subdomain. If no ``re...
Resolves a URL in a template, using subdomain-based URL resolution. If no subdomain is provided and a ``request`` is in the template context when rendering, the URL will be resolved relative to the current request's subdomain. If no ``request`` is provided, the URL will be resolved relative to current ...
def track_progress( measure: MeasureProgress, target: MetricProgress, interval_check: float, capture_maybe: Optional[CaptureProgress] = None ) -> None: """ Tracks progress against a certain end condition of the simulation (for instance, a certain duration on the simulated clock), reporting t...
Tracks progress against a certain end condition of the simulation (for instance, a certain duration on the simulated clock), reporting this progress as the simulation chugs along. Stops the simulation once the target has been reached. By default, the progress is reported as printout on standard output, in a man...
def intersects_segment(self, seg): """ Returns True if any segmentlist in self intersects the segment, otherwise returns False. """ return any(value.intersects_segment(seg) for value in self.itervalues())
Returns True if any segmentlist in self intersects the segment, otherwise returns False.
def load_jupyter_server_extension(nb_server_app): """Called by Jupyter when this module is loaded as a server extension.""" app = nb_server_app.web_app host_pattern = '.*$' app.add_handlers(host_pattern, [ (utils.url_path_join(app.settings['base_url'], '/http_over_websocket'), handlers.HttpOverWeb...
Called by Jupyter when this module is loaded as a server extension.
def makeAnimation(self): """Use pymovie to render (visual+audio)+text overlays. """ aclip=mpy.AudioFileClip("sound.wav") self.iS=self.iS.set_audio(aclip) self.iS.write_videofile("mixedVideo.webm",15,audio=True) print("wrote "+"mixedVideo.webm")
Use pymovie to render (visual+audio)+text overlays.
def fetch(self, category, filter_classified=False, **kwargs): """Fetch items from the repository. The method retrieves items from a repository. To removed classified fields from the resulting items, set the parameter `filter_classified`. Take into account this parameter is inco...
Fetch items from the repository. The method retrieves items from a repository. To removed classified fields from the resulting items, set the parameter `filter_classified`. Take into account this parameter is incompatible with archiving items. Raw client data are archived befor...
def swap(self, core, other): """http://wiki.apache.org/solr/CoreAdmin#head-928b872300f1b66748c85cebb12a59bb574e501b""" params = { 'action': 'SWAP', 'core': core, 'other': other, } return self._get_url(self.url, params=params)
http://wiki.apache.org/solr/CoreAdmin#head-928b872300f1b66748c85cebb12a59bb574e501b
def get_dataset(self, name, multi_instance=0): """ get a specific dataset. example: try: gyro_data = ulog.get_dataset('sensor_gyro') except (KeyError, IndexError, ValueError) as error: print(type(error), "(sensor_gyro):", error) :param name: name of the ...
get a specific dataset. example: try: gyro_data = ulog.get_dataset('sensor_gyro') except (KeyError, IndexError, ValueError) as error: print(type(error), "(sensor_gyro):", error) :param name: name of the dataset :param multi_instance: the multi_id, defaul...
def render(self, template, **kwargs): """ Render a route template and adds information to this route. :param template: Template name. :type template: str :param kwargs: dictionary of named arguments used to be passed to the template :type kwargs: dict :return: Http Respo...
Render a route template and adds information to this route. :param template: Template name. :type template: str :param kwargs: dictionary of named arguments used to be passed to the template :type kwargs: dict :return: Http Response with rendered template :rtype: flask.R...
def scale_up(self, n, pods=None, **kwargs): """ Make sure we have n dask-workers available for this cluster Examples -------- >>> cluster.scale_up(20) # ask for twenty workers """ maximum = dask.config.get('kubernetes.count.max') if maximum is not None a...
Make sure we have n dask-workers available for this cluster Examples -------- >>> cluster.scale_up(20) # ask for twenty workers
def validate_proof(proof: List[Keccak256], root: Keccak256, leaf_element: Keccak256) -> bool: """ Checks that `leaf_element` was contained in the tree represented by `merkleroot`. """ hash_ = leaf_element for pair in proof: hash_ = hash_pair(hash_, pair) return hash_ == root
Checks that `leaf_element` was contained in the tree represented by `merkleroot`.
def get_database_columns(self, tables=None, database=None): """Retrieve a dictionary of columns.""" # Get table data and columns from source database source = database if database else self.database tables = tables if tables else self.tables return {tbl: self.get_columns(tbl) for...
Retrieve a dictionary of columns.
def meta(self): """Value of the bound meta-property on the target.""" if not self._pv.meta_data_property or not self._meta_target: return {} return getattr(self._meta_target, self._pv.meta_data_property)
Value of the bound meta-property on the target.
def vocab_account_type(instance): """Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'user-account': try: acct_type = obj['account_type'...
Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary.
def get_code_language(self): """ This is largely copied from bokeh.sphinxext.bokeh_plot.run """ js_source = self.get_js_source() if self.options.get("include_html", False): resources = get_sphinx_resources(include_bokehjs_api=True) html_source = BJS_HTML.r...
This is largely copied from bokeh.sphinxext.bokeh_plot.run
def _to_json(self, include_references=True): """Convert the model to JSON using the PotionJSONEncode and automatically resolving the resource as needed (`_properties` call handles this). """ if include_references: return json.dumps(self._resource._properties, cls=PotionJSONEn...
Convert the model to JSON using the PotionJSONEncode and automatically resolving the resource as needed (`_properties` call handles this).
def stream_events(self, filter: Callable[[Event], bool] = None, *, max_queue_size: int = 0): """Shortcut for calling :func:`stream_events` with this signal in the first argument.""" return stream_events([self], filter, max_queue_size=max_queue_size)
Shortcut for calling :func:`stream_events` with this signal in the first argument.
def types(**args): """Specifies the types used for the arguments of a published service. @types(a=int, b = str) def f(a, b): pass """ def l(func): if hasattr(func, '__annotations__'): func.__annotations__.update(args) else: func.__annotations__ = args return ...
Specifies the types used for the arguments of a published service. @types(a=int, b = str) def f(a, b): pass
def list_commands(self, ctx): """ list all commands exposed to engineer """ self.connect(ctx) if not hasattr(ctx, "widget"): return super(Engineer, self).list_commands(ctx) return ctx.widget.engineer_list_commands() + super(Engineer, self).list_commands(c...
list all commands exposed to engineer
async def set_property_value(self, turn_context: TurnContext, property_name: str, value: object) -> None: """ Deletes a property from the state cache in the turn context. :param turn_context: The context object for this turn. :param property_name: The value to set on the propert...
Deletes a property from the state cache in the turn context. :param turn_context: The context object for this turn. :param property_name: The value to set on the property. :return: None
def files(self): """Set of found binary files output by StagYY.""" if self._rundir['ls'] is UNDETERMINED: out_stem = pathlib.Path(self.par['ioin']['output_file_stem'] + '_') out_dir = self.path / out_stem.parent if out_dir.is_dir(): self._rundir['ls'] ...
Set of found binary files output by StagYY.
def _rspiral(width, height): """Reversed spiral generator. Parameters ---------- width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Points. """ x0 =...
Reversed spiral generator. Parameters ---------- width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Points.
def main(): """ Check args """ configure_obj = None parser = argparse.ArgumentParser(description='自动化安装') parser.add_argument( '-s', '--server', help='服务器代替名', ) parser.add_argument( '-ba', '--bigdata-app', help='大数据服务应用替代名', ) parser.add_ar...
Check args
def get_item(self, table_name, key_dict, consistent_read=False, expression_attribute_names=None, projection_expression=None, return_consumed_capacity=None): """ Invoke the `GetItem`_ function. :param str table_name: table to re...
Invoke the `GetItem`_ function. :param str table_name: table to retrieve the item from :param dict key_dict: key to use for retrieval. This will be marshalled for you so a native :class:`dict` works. :param bool consistent_read: Determines the read consistency model: If ...
def to_networkx(self, labels=None, edge_labels=False): """ Get a networkx representation of the binary search tree. """ import networkx as nx graph = nx.DiGraph() for node in self._traverse_nodes(): u = node.key graph.add_node(u) # Minor redundancy # ...
Get a networkx representation of the binary search tree.
def decode(self, bytes, raw=False): """decode(bytearray, raw=False) -> value Decodes the given bytearray containing the elapsed time in seconds since the GPS epoch and returns the corresponding Python :class:`datetime`. If the optional parameter ``raw`` is ``True``, the integra...
decode(bytearray, raw=False) -> value Decodes the given bytearray containing the elapsed time in seconds since the GPS epoch and returns the corresponding Python :class:`datetime`. If the optional parameter ``raw`` is ``True``, the integral number of seconds will be returned in...
def _unpack_case(self, case): """ Returns the contents of the case to be used in the OPF. """ base_mva = case.base_mva b = case.connected_buses l = case.online_branches g = case.online_generators nb = len(b) nl = len(l) ng = len(g) return ...
Returns the contents of the case to be used in the OPF.
def _include_file(context, uri, calling_uri, **kwargs): """locate the template from the given uri and include it in the current output.""" template = _lookup_template(context, uri, calling_uri) (callable_, ctx) = _populate_self_namespace( context._clean_inheritance_token...
locate the template from the given uri and include it in the current output.
def write(self, outfile=None, section=None): """Write the current config to a file (defaults to user config). :param str outfile: The path to the file to write to. :param None/str section: The config section to write, or :data:`None` to write the entire config. ...
Write the current config to a file (defaults to user config). :param str outfile: The path to the file to write to. :param None/str section: The config section to write, or :data:`None` to write the entire config.
def get_suitable_slot_for_duplicate(self, src_slot): """Returns the suitable position for a duplicate analysis, taking into account if there is a WorksheetTemplate assigned to this worksheet. By default, returns a new slot at the end of the worksheet unless there is a slot defined for a...
Returns the suitable position for a duplicate analysis, taking into account if there is a WorksheetTemplate assigned to this worksheet. By default, returns a new slot at the end of the worksheet unless there is a slot defined for a duplicate of the src_slot in the worksheet template lay...
def calibration_stimulus(self, mode): """Gets the stimulus model for calibration :param mode: Type of stimulus to get: tone or noise :type mode: str :returns: :class:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel>` """ if mode == 'tone': return self...
Gets the stimulus model for calibration :param mode: Type of stimulus to get: tone or noise :type mode: str :returns: :class:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel>`
def _merge_align_bams(data): """Merge multiple alignment BAMs, including split and discordant reads. """ for key in (["work_bam"], ["work_bam_plus", "disc"], ["work_bam_plus", "sr"], ["umi_bam"]): in_files = tz.get_in(key, data, []) if not isinstance(in_files, (list, tuple)): in_...
Merge multiple alignment BAMs, including split and discordant reads.
def _build_header(self): """Adds the header template to the master template string """ logger.debug("===============") logger.debug("Building header") logger.debug("===============") self.template += hs.header
Adds the header template to the master template string
def segmentlistdict_fromsearchsummary_in(xmldoc, program = None): """ Convenience wrapper for a common case usage of the segmentlistdict class: searches the process table in xmldoc for occurances of a program named program, then scans the search summary table for matching process IDs and constructs a segmentlistd...
Convenience wrapper for a common case usage of the segmentlistdict class: searches the process table in xmldoc for occurances of a program named program, then scans the search summary table for matching process IDs and constructs a segmentlistdict object from the in segments in those rows. Note: the segmentlist...
def draw(self): """Draws the image at the given location.""" if not self.visible: return self.window.blit(self.image, self.loc)
Draws the image at the given location.
def start_health_check(self, recipient): """ Starts a task for healthchecking `recipient` if there is not one yet. It also whitelists the address """ if recipient not in self.addresses_events: self.whitelist(recipient) # noop for now, for compatibility p...
Starts a task for healthchecking `recipient` if there is not one yet. It also whitelists the address
def validate(self): """ Validates the given Amazon S3 file with :attr:`validators`. If errors occur they are appended to :attr:`errors`. If the file is valid and a `AWS_UNVALIDATED_PREFIX` config is present, its value will be removed from the file key. :return: a boolean...
Validates the given Amazon S3 file with :attr:`validators`. If errors occur they are appended to :attr:`errors`. If the file is valid and a `AWS_UNVALIDATED_PREFIX` config is present, its value will be removed from the file key. :return: a boolean indicating if the file vas valid.
def dump(self): """Item as a JSON representation.""" return json.dumps( self.primitive, sort_keys=True, ensure_ascii=False, separators=(',', ':'))
Item as a JSON representation.
def request(self, url, post=None, method="GET"): """ Make the request""" dsid = self.get_dsid() baseurl = "https://auth.api.swedbank.se/TDE_DAP_Portal_REST_WEB/api/v1/%s?dsid=%s" % ( url, dsid) if self.pch is None: self.pch = build_opener(HTTPCookieProcessor(self...
Make the request
def sign(self, issuer_cert, issuer_key, digest): """ Sign the CRL. Signing a CRL enables clients to associate the CRL itself with an issuer. Before a CRL is meaningful to other OpenSSL functions, it must be signed by an issuer. This method implicitly sets the issuer's n...
Sign the CRL. Signing a CRL enables clients to associate the CRL itself with an issuer. Before a CRL is meaningful to other OpenSSL functions, it must be signed by an issuer. This method implicitly sets the issuer's name based on the issuer certificate and private key used to s...
def save_controls(self, parameterstep: 'timetools.PeriodConstrArg' = None, simulationstep: 'timetools.PeriodConstrArg' = None, auxfiler: 'Optional[auxfiletools.Auxfiler]' = None): """Save the control parameters of the |Model| object handled by each |Element| o...
Save the control parameters of the |Model| object handled by each |Element| object and eventually the ones handled by the given |Auxfiler| object.
def Shah(m, x, D, rhol, mul, kl, Cpl, P, Pc): r'''Calculates heat transfer coefficient for condensation of a fluid inside a tube, as presented in [1]_ and again by the same author in [2]_; also given in [3]_. Requires no properties of the gas. Uses the Dittus-Boelter correlation for single phase heat t...
r'''Calculates heat transfer coefficient for condensation of a fluid inside a tube, as presented in [1]_ and again by the same author in [2]_; also given in [3]_. Requires no properties of the gas. Uses the Dittus-Boelter correlation for single phase heat transfer coefficient, with a Reynolds number a...
def push_log(self, info, level, *args, **kwargs): """ Writes logs. To be fully implemented by subclasses. :param info: Log message content. :type info: unicode | str :param level: Logging level. :type level: int :param args: Positional arguments to pass to logger...
Writes logs. To be fully implemented by subclasses. :param info: Log message content. :type info: unicode | str :param level: Logging level. :type level: int :param args: Positional arguments to pass to logger. :param kwargs: Keyword arguments to pass to logger.
def set_trunk_groups(self, intf, value=None, default=False, disable=False): """Configures the switchport trunk group value Args: intf (str): The interface identifier to configure. value (str): The set of values to configure the trunk group default (bool): Configures ...
Configures the switchport trunk group value Args: intf (str): The interface identifier to configure. value (str): The set of values to configure the trunk group default (bool): Configures the trunk group default value disable (bool): Negates all trunk group setti...
def add_videos_to_playlist(self, access_token, playlist_id, video_ids): """doc: http://open.youku.com/docs/doc?id=75 """ url = 'https://openapi.youku.com/v2/playlists/video/add.json' data = { 'client_id': self.client_id, 'access_token': access_token, '...
doc: http://open.youku.com/docs/doc?id=75
def get(self, url=None, params=None, retry=True): ''' Execute HTTP GET ''' headers = self._gen_headers(self.access_token, url) attempts = 1 while attempts <= HTTP_ATTEMPTS_MAX: try: res = requests.get(url, hea...
Execute HTTP GET