text
stringlengths
81
112k
Print series_info from dcmdirstats def print_series_info(self, series_info, minimal_series_number=1): """ Print series_info from dcmdirstats """ strinfo = '' if len(series_info) > minimal_series_number: for serie_number in series_info.keys(): strl = g...
Check if exists dicomdir file and load it or cerate it dcmdir = get_dir(dirpath) dcmdir: list with filenames, SeriesNumber and SliceLocation def __prepare_info_from_dicomdir_file(self, writedicomdirfile=True): """ Check if exists dicomdir file and load it or cerate it dcmdir ...
input is dcmdir, not dirpath def series_in_dir(self): """input is dcmdir, not dirpath """ # none_count = 0 countsd = {} # dcmdirseries = [] for line in self.files_with_info: if "SeriesNumber" in line: sn = line['SeriesNumber'] else: ...
Function returns sorted list of dicom files. File paths are organized by SeriesUID, StudyUID and FrameUID :param startpath: path prefix. E.g. "~/data" :param series_number: ID of series used for filtering the data :param return_files_with_info: return more complex information about sor...
Function crates list of all files in dicom dir with all IDs def _create_dicomdir_info(self): """ Function crates list of all files in dicom dir with all IDs """ filelist = files_in_dir(self.dirpath) files = [] metadataline = {} for filepath in filelist: ...
Return one item from seq or None(by default). def get_one(seq, default=None, skip_string_iter=True): """ Return one item from seq or None(by default). """ if skip_string_iter and isinstance(seq, (str, unicode, bytes, bytearray)): return seq if not seq: return '' try: ret...
null obj -> return []; str, unicode, bytes, bytearray -> [obj]; else -> list(obj) def ensure_list(obj): """ null obj -> return []; str, unicode, bytes, bytearray -> [obj]; else -> list(obj) """ if not obj: return [] elif isinstan...
operate a python obj def python_parser(self, obj, *args): """operate a python obj""" attr, args = args[0], args[1:] item = getattr(obj, attr) if callable(item): item = item(*args) return [item]
args: [arg1, arg2] arg[0] = a valid regex pattern arg[1] : if startswith('@') call sub; if startswith('$') call finditer, $0, $1 means group index. return an ensure_list def re_parser(self, scode, *args): """ args: [arg1, arg2] arg[0] = a valid regex...
args[0] = cssselector args[1] = text / html / xml / @attribute_name def html_parser(self, scode, *args): """ args[0] = cssselector args[1] = text / html / xml / @attribute_name """ allow_method = ('text', 'html', 'xml') css_path, method = args assert me...
args[0]: xpath args[1]: text / html / xml def xml_parser(self, scode, *args): """ args[0]: xpath args[1]: text / html / xml """ allow_method = ('text', 'html', 'xml') xpath_string, method = args assert method in allow_method, 'method allow: %s' % allow_...
single arg: [one_to_many, parser_name, *args] args_chain: [['1-n', 're', 'search', '(<.*?>)', '\\1']] [['1-n', 'html', 'p', 'html'], ['n-n', 'html', 'p', 'text']] def parse(self, scode, args_chain=None, join_with=None, default=''): """ single arg: ...
Parses the CSS contents and returns the cleaned CSS as a string :returns: The cleaned CSS :rtype: str def parse(self): """ Parses the CSS contents and returns the cleaned CSS as a string :returns: The cleaned CSS :rtype: str """ # Build the HTML tree ...
Converts relative links from css contents to absolute links :param base_url: The base page url to use for building absolute links :type base_url: str :param css_contents: The CSS contents to parse :type css_contents: str def rel_to_abs(self, base_url): """ Converts rela...
Returns the cleaned CSS :param stylesheet: The Stylesheet object to parse :type stylesheet: tinycss.css21.Stylesheet def _clean_css(self): """ Returns the cleaned CSS :param stylesheet: The Stylesheet object to parse :type stylesheet: tinycss.css21.Stylesheet "...
Cleans a css Rule by removing Selectors without matches on the tree Returns None if the whole rule do not match :param rule: CSS Rule to check :type rule: A tinycss Rule object :returns: A cleaned tinycss Rule with only Selectors matching the tree or None :rtype: tinycss Rule or...
Returns whether the token list matches the HTML tree :param selector: A Token list to check :type selector: list of Token objects :returns: True if the token list has matches in self.tree :rtype: bool def _token_list_matches_tree(self, token_list): """ Returns whether t...
Converts a tinycss rule to a formatted CSS string :param rule: The rule to format :type rule: tinycss Rule object :returns: The Rule as a CSS string :rtype: str def _rule_as_string(self, rule): """ Converts a tinycss rule to a formatted CSS string :param rule: ...
Returns a selector as a CSS string :param selector: A list of tinycss Tokens :type selector: list :returns: The CSS string for the selector :rtype: str def _selector_as_string(self, selector): """ Returns a selector as a CSS string :param selector: A list of ti...
Returns a list of declarations as a formatted CSS string :param declarations: The list of tinycss Declarations to format :type declarations: list of tinycss.css21.Declaration :returns: The CSS string for the declarations list :rtype: str def _declarations_as_string(self, declarations):...
generate a markdown list of a list of environment variable tuples Parameters ========== title: A title for the section (defaults to "Environment" envars: a list of tuples for the environment, e.g.: [('TERM', 'xterm-256color'), ('SHELL', '/bin/bash'), (...
Create (boot) a new server. :arg string preset_name: Name of vm group where vm is created. :arg string image: Image name. :arg string flavor: Flavor (or instance_type in AWS) name. :arg list security_groups: A list of security group names. :arg dict userdata: A dict of arbitrary...
Returns the default commands of this application. :rtype: list[cleo.Command] def get_default_commands(self): """ Returns the default commands of this application. :rtype: list[cleo.Command] """ commands = Application.get_default_commands(self) self.add(Constan...
Discovers UPnP devices in the local network. Try to discover all devices in the local network which do support UPnP. The discovery process can fail for various reasons and it is recommended to do at least two discoveries, which you can specify with the ``retries`` parameter. The defaul...
Discover a particular host and find the best response. This tries to find the most specific discovery result for the given host. Only the discovery result contains the URL to the XML tree which initializes the device definition. If an URL is already known it should be provided to avoid addition...
Gives a quality rating for a given service type in a result, higher is better. Several UpnP devices reply to a discovery request with multiple responses with different service type announcements. To find the most specific one we need to be able rate the service types against each other. Usually...
stream to a temporary file, rename on successful completion Parameters ========== file_name: the file name to stream to url: the url to stream from headers: additional headers to add force: If the final image exists, don't overwrite def download(self, url, ...
stream response is one level higher up than stream, starting with a response object and then performing the stream without making the requests.get. The expectation is that the request was successful (status code 20*). Parameters ========== response: a response that is ready ...
Returns the SCDP (Service Control Protocol Document) URL for a given service type. When the device definitions have been loaded with :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions` this method returns for a given service type/namespace the associated URL to the SCDP. If the device definitions ...
Returns the control URL for a given service type. When the device definitions have been loaded with :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions` this method returns for a given service type/namespace the associated control URL. If the device definitions have not been loaded a default va...
Returns the event URL for a given service type. When the device definitions have been loaded with :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions` this method returns for a given service type/namespace the associated event URL. If the device definitions have not been loaded a default value ...
Executes a given action with optional arguments. The execution of an action of an UPnP/TR64 device needs more than just the name of an action. It needs the control URI which is called to place the action and also the namespace aka service type is needed. The namespace defines the scope or servi...
Extract error string from a failed UPnP call. :param request: the failed request result :type request: requests.Response :return: an extracted error text or empty str :rtype: str def _extractErrorString(request): """Extract error string from a failed UPnP call. :param ...
Setup actions for known devices. For convenience reasons for some devices there is no need to discover/load device definitions before the pre defined :doc:`tr64` can be used. The following devices are currently supported (please help to extend): * fritz.box - Any AVM Fritz Box with th...
Loads the device definitions from a given URL which points to the root XML in the device. This loads the device definitions which is needed in case you like to: * get additional information's about the device like manufacture, device type, etc * get all support service types of this device ...
Internal call to parse the XML of the device definition. :param urlOfXMLDefinition: the URL to the XML device defintions :param xml: the XML content to parse def _loadDeviceDefinitions(self, urlOfXMLDefinition, xml): """Internal call to parse the XML of the device definition. :param u...
Internal method to iterate through device definition XML tree. :param element: the XML root node of the device definitions :type element: xml.etree.ElementTree.Element :param str baseURIPath: the base URL def _iterateToFindSCPDElements(self, element, baseURIPath): """Internal method to...
Internal method to iterate in the device definition XML tree through the service list. :param serviceList: the XML root node of a service list :type serviceList: xml.etree.ElementTree.Element def _processServiceList(self, serviceList, baseURIPath): """Internal method to iterate in the device d...
Load action definition(s) (Service Control Protocol Document). If the device definitions have been loaded via loadDeviceDefinitions() this method loads actions definitions. The action definitions are needed if you like to execute an action on a UPnP device. The actions definition contains the n...
Internal method to load the action definitions. :param str serviceType: the service type to load :param int timeout: the timeout for downloading def _loadSCPD(self, serviceType, timeout): """Internal method to load the action definitions. :param str serviceType: the service type to lo...
Internal method to parse the SCPD definitions. :param actionListElement: the action xml element :type actionListElement: xml.etree.ElementTree.Element :param dict actions: a container to store all actions :param dict variableParameterDict: remember where a variable gets referenced def ...
Internal method to parse the SCPD definitions. :param variableListElement: the xml root node of the variable list :type variableListElement: xml.etree.ElementTree.Element :param dict variableTypes: a container to store the variables def _parseSCPDVariableTypes(self, variableListElement, variab...
Factory method to create a DeviceTR64 from an URL to the XML device definitions. :param str urlOfXMLDefinition: :return: the new object :rtype: Wifi def createFromURL(urlOfXMLDefinition): """Factory method to create a DeviceTR64 from an URL to the XML device definitions. :para...
Execute GetInfo action to get Wifi basic information's. :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for the action to be executed :return: the basic informations :rtype: WifiBasicInfo def getWifiInfo(self, wifiInterfaceId=1, timeou...
Execute GetTotalAssociations action to get the amount of associated Wifi clients. :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for the action to be executed :return: the amount of Wifi clients :rtype: int .. seealso:: :meth:...
Execute GetGenericAssociatedDeviceInfo action to get detailed information about a Wifi client. :param int index: the number of the client :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for the action to be executed :return: the detaile...
Execute GetSpecificAssociatedDeviceInfo action to get detailed information about a Wifi client. :param str macAddress: MAC address in the form ``38:C9:86:26:7E:38``; be aware that the MAC address might be case sensitive, depending on the router :param int wifiInterfaceId: the id of the Wifi...
Set enable status for a Wifi interface, be careful you don't cut yourself off. :param bool status: enable or disable the interface :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for the action to be executed def setEnable(self, status, wifiIn...
Set the channel of this Wifi interface :param int channel: the channel number :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for the action to be executed def setChannel(self, channel, wifiInterfaceId=1, timeout=1): """Set the channel...
Set the SSID (name of the Wifi network) :param str ssid: the SSID/wifi network name :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for the action to be executed def setSSID(self, ssid, wifiInterfaceId=1, timeout=1): """Set the SSID (n...
Access decorator which checks if a RPC method is enabled by our configuration def enabled_checker(func): """ Access decorator which checks if a RPC method is enabled by our configuration """ @wraps(func) def wrap(self, *args, **kwargs): if self.allowed_methods and isinstance...
Listing presets :return: (list of presets) :rtype: list Sample response: ``["preset1", "preset2"]`` async def list_presets(self): """ Listing presets :return: (list of presets) :rtype: list Sample response: ``["preset1", "p...
Listing virtual machines in a given preset :arg string preset: preset name :return: (Size of a preset, list of virtual machines) - first element of a tuple is a size of virtual machines in a preset - second element is a dict which contains all Virtual Machines, where every ele...
Discard vm in specified preset :arg string preset: preset name :arg int vm_id: Virtual Machine id :return: 'OK' Sample response: ``OK`` async def terminate_vm(self, preset, vm_id): """ Discard vm in specified preset :arg string preset: preset name :...
Get vm metadata :arg string preset: preset name :arg int vm_id: Virtual Machine id :return: Metadata for Virtual Machine :rtype: dict Sample response: ``{ 'time_shutdown' : "12312312321' }`` async def get_vm_metadata(self, preset, vm_id): """ Get vm metadat...
Convert URL-like and email-like strings into links. def linkify(text, attrs={}): """ Convert URL-like and email-like strings into links. """ def separate_parentheses(s): start = re_find(r'^\(*', s) end = re_find(r'\)*$', s) n = min(len(start), len(end)) if n: ...
Similar to smart_text, except that lazy instances are resolved to strings, rather than kept as lazy objects. def force_unicode(s, encoding='utf-8', errors='strict'): """ Similar to smart_text, except that lazy instances are resolved to strings, rather than kept as lazy objects. """ # Handle the...
.... def save_dict_to_hdf5(dic, filename): """ .... """ with h5py.File(filename, 'w') as h5file: rf = recursively_save_dict_contents_to_group(h5file, '/', dic) h5_rf = h5file.create_group("_reconstruction_flags") # h5_rf = h5file.create_group("_reconstruction_key_flags") ...
.... def recursively_save_dict_contents_to_group(h5file, path, dic): """ .... """ reconstruction_flags = {} # reconstruction_key_flags = {} for key, item in dic.items(): if type(key) is not str: # import pickle # key = pickle.dumps(key).decode("ascii") ...
.... def recursively_load_dict_contents_from_group(h5file, path): """ .... """ rf = h5file["_reconstruction_flags"] # rkf = h5file["_reconstruction_key_flags"] ans = {} for key, item in h5file[path].items(): dest_key = key # if key in ("_reconstruction_flags", "_reconstructi...
Parse the arguments for the command def parse_args(*args): """ Parse the arguments for the command """ parser = argparse.ArgumentParser( description="Send push notifications for a feed") parser.add_argument('--version', action='version', version="%(prog)s " + __version__.__...
main entry point def main(): """ main entry point """ args = parse_args() logging.basicConfig(level=LOG_LEVELS[min( args.verbosity, len(LOG_LEVELS) - 1)]) loop = asyncio.get_event_loop() loop.run_until_complete(_run(args))
Retrieve all environments for a given project. Includes name, key, and mobile key. :param project_key: Key for project. :returns: dictionary of environments. def get_environments(self, project_key: str) -> dict: """ Retrieve all environments for a given project. Incl...
Update the flag status for the specified feature flag. :param state: New feature flag state :param featureKey: Feature flag key :returns: FeatureFlag object. def update_flag(self, state: str, feature_key: str) \ -> launchdarkly_api.FeatureFlag: """ Update the flag stat...
Generates code for calling the stored routine in the wrapper method. def _write_result_handler(self, routine): """ Generates code for calling the stored routine in the wrapper method. """ self._write_line('ret = {}') self._write_execute_rows(routine) self._write_line('fo...
Logs the query on the console. :param str query: The query. def _log_query(query): """ Logs the query on the console. :param str query: The query. """ query = query.strip() if os.linesep in query: # Query is a multi line query MetadataD...
send a public key to request a token. When we call this function, we already have an RSA key at self.key board: the discourse board to post to def request_token(self, board): '''send a public key to request a token. When we call this function, we already have an RSA key at self.key bo...
create a Discourse post, given a title, body, board, and token. Parameters ========== title: the issue title body: the issue body board: the discourse board to post to def create_post(self, title, body, board, category, username): '''create a Discourse post, given a title, body,...
Loads stored routines into the current schema. :param str config_filename: The name of the configuration file of the current project :param list[str] file_names: The sources that must be loaded. If empty all sources (if required) will loaded. :rtype: int The status of exit. def main(self, con...
Show info about sources files of stored routines that were not loaded successfully. def __log_overview_errors(self): """ Show info about sources files of stored routines that were not loaded successfully. """ if self.error_file_names: self._io.warning('Routines in the files ...
Adds a replace part to the map of replace pairs. :param name: The name of the replace pair. :param value: The value of value of the replace pair. def _add_replace_pair(self, name, value, quote): """ Adds a replace part to the map of replace pairs. :param name: The name of the ...
Loads all stored routines in a list into the RDBMS instance. :param str config_filename: The filename of the configuration file. :param list[str] file_names: The list of files to be loaded. def __load_list(self, config_filename, file_names): """ Loads all stored routines in a list into...
Loads all stored routines into the RDBMS instance. :param str config_filename: string The filename of the configuration file. def __load_all(self, config_filename): """ Loads all stored routines into the RDBMS instance. :param str config_filename: string The filename of the configurat...
Reads parameters from the configuration file. :param str config_filename: The name of the configuration file. def _read_configuration_file(self, config_filename): """ Reads parameters from the configuration file. :param str config_filename: The name of the configuration file. ...
Searches recursively for all source files in a directory. def __find_source_files(self): """ Searches recursively for all source files in a directory. """ for dir_path, _, files in os.walk(self._source_directory): for name in files: if name.lower().endswith(s...
Reads the metadata of stored routines from the metadata file. def __read_stored_routine_metadata(self): """ Reads the metadata of stored routines from the metadata file. """ if os.path.isfile(self._pystratum_metadata_filename): with open(self._pystratum_metadata_filename, 'r...
Loads all stored routines into the RDBMS instance. def __load_stored_routines(self): """ Loads all stored routines into the RDBMS instance. """ self._io.writeln('') for routine_name in sorted(self._source_file_names): if routine_name in self._pystratum_metadata: ...
Removes obsolete entries from the metadata of all stored routines. def __remove_obsolete_metadata(self): """ Removes obsolete entries from the metadata of all stored routines. """ clean = {} for key, _ in self._source_file_names.items(): if key in self._pystratum_met...
Writes the metadata of all stored routines to the metadata file. def __write_stored_routine_metadata(self): """ Writes the metadata of all stored routines to the metadata file. """ with open(self._pystratum_metadata_filename, 'w') as stream: json.dump(self._pystratum_metadat...
Finds all source files that actually exists from a list of file names. :param list[str] file_names: The list of file names. def find_source_files_from_list(self, file_names): """ Finds all source files that actually exists from a list of file names. :param list[str] file_names: The li...
Gets the constants from the class that acts like a namespace for constants and adds them to the replace pairs. def __get_constants(self): """ Gets the constants from the class that acts like a namespace for constants and adds them to the replace pairs. """ helper = ConstantClass(self._c...
Terminate vm. async def terminate(self): """ Terminate vm. """ logging.debug('Terminate: %s', self) self.state = VmState.TERMINATED return await self.manager.terminate_vm(self.id)
Add a default handler for logger. Args: name = '' or logger obj. handler_path_levels = [['loggerfile.log',13],['','DEBUG'],['','info'],['','notSet']] # [[path,level]] level = the least level for the logger. formatter = logging.Formatter( '%(levelname)-7s %(asctime)s %(name)s (%(file...
Simple print use logger, print with time / file / line_no. :param sep: sep of messages, " " by default. Basic Usage:: print_info(1, 2, 3) print_info(1, 2, 3) print_info(1, 2, 3) # [2018-10-24 19:12:16] temp_code.py(7): 1 2 3 # [2018-10-24 19:12:16] temp_code.py(8):...
Returns a Model's knockout_fields, or the default set of field names. def get_fields(model): """ Returns a Model's knockout_fields, or the default set of field names. """ try: if hasattr(model, "knockout_fields"): fields = model.knockout_fields() else: t...
Given an object and a list of fields, recursively build an object for serialization. Returns a dictionary. def get_object_data(obj, fields, safe): """ Given an object and a list of fields, recursively build an object for serialization. Returns a dictionary. """ temp_dict = dict() for fie...
Given a model, returns the Knockout Model and the Knockout ViewModel. Takes optional field names and data. def ko_model(model, field_names=None, data=None): """ Given a model, returns the Knockout Model and the Knockout ViewModel. Takes optional field names and data. """ try: if isinst...
Given a model, returns the Knockout data bindings. def ko_bindings(model): """ Given a model, returns the Knockout data bindings. """ try: if isinstance(model, str): modelName = model else: modelName = model.__class__.__name__ modelBindingsString = "ko....
Given a QuerySet, return just the serialized representation based on the knockout_fields. Useful for middleware/APIs. Convenience method around ko_data. def ko_json(queryset, field_names=None, name=None, safe=False): """ Given a QuerySet, return just the serialized representation based on the knoc...
Given a QuerySet, return just the serialized representation based on the knockout_fields as JavaScript. def ko_data(queryset, field_names=None, name=None, safe=False, return_json=False): """ Given a QuerySet, return just the serialized representation based on the knockout_fields as JavaScript. """...
Converts a Django QuerySet into a complete Knockout implementation. def ko(queryset, field_names=None): """ Converts a Django QuerySet into a complete Knockout implementation. """ try: koDataString = ko_data(queryset, field_names) koModelString = ko_model(queryset[0].__class__.__name__...
load a keypair from a keypair file. We add attributes key (the raw key) and public_key (the url prepared public key) to the client. Parameters ========== keypair_file: the pem file to load. def load_keypair(keypair_file): '''load a keypair from a keypair file. We add attributes key (th...
generate_keypair is used by some of the helpers that need a keypair. The function should be used if the client doesn't have the attribute self.key. We generate the key and return it. We use pycryptodome (3.7.2) Parameters ========= keypair_file: fullpath to where to s...
Composes the exception message. :param str expected_row_count: The expected row count. :param int actual_row_count: The actual row count. :param str query: The query. :rtype: str def __message(expected_row_count, actual_row_count, query): """ Composes the exception mes...
submit the issue to github. When we get here we should have: {'user_prompt_issue': 'I want to do the thing.', 'user_prompt_repo': 'vsoch/hello-world', 'user_prompt_title': 'Error with this thing', 'record_asciinema': '/tmp/helpme.93o__nt5.json', '...
Resolve JSON references in a given dictionary. OpenAPI spec may contain JSON references to its nodes or external sources, so any attempt to rely that there's some expected attribute in the spec may fail. So we need to resolve JSON references before we use it (i.e. replace with referenced object). For d...
This is the actual driver for the helper. def main(args, extras): '''This is the actual driver for the helper. ''' from helpme.main import get_helper name = args.command if name in HELPME_HELPERS: # Get the helper, do the recording, submit helper = get_helper(name=name) ...
Extracts the cleaned html tree as a string and only css rules matching the cleaned html tree :param html_contents: The HTML contents to parse :type html_contents: str :param css_contents: The CSS contents to parse :type css_contents: str :param base_url: The base page UR...
Adds a Xpath expression to the dest list :param dest: The destination list to add the Xpath :type dest: list :param xpath: The Xpath expression to add :type xpath: str def __add(self, dest, xpath): """ Adds a Xpath expression to the dest list :param dest: The d...
Appends a line of code to the generated code and adjust the indent level of the generated code. :param line: The line of code (with out LF) that must be appended. def _write_line(self, line=None): """ Appends a line of code to the generated code and adjust the indent level of the generated cod...