code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''Ask the user for a text entry that matches a regular expression Parameters ========== prompt: the prompt to ask the user regexp: the regular expression to match. defaults to anything. ''' get_input = getattr(__builtins__, 'raw_input', input) while not re.search(regex...
def regexp_prompt(prompt, regexp='.', answer='')
Ask the user for a text entry that matches a regular expression Parameters ========== prompt: the prompt to ask the user regexp: the regular expression to match. defaults to anything.
6.646656
4.759513
1.396499
'''get_install will return the path to where an executable is installed. ''' if software is None: software = "singularity" cmd = ['which', software ] try: result = run_command(cmd) if strip_newline is True: result['message'] = result['message'].strip('\n') ...
def which(software, strip_newline=True)
get_install will return the path to where an executable is installed.
6.426755
4.615689
1.392372
ctype = request.headers.get('content-type') if not ctype: # we don't have a content-type, somehow, so... LOGGER.warning("%s: no content-type; headers are %s", request.url, request.headers) return 'utf-8' # explicit declaration match = re.search(r'char...
def guess_encoding(request)
Try to guess the encoding of a request without going through the slow chardet process
3.91772
3.987346
0.982538
headers = kwargs.get('headers') headers = headers.copy() if headers is not None else {} headers['User-Agent'] = config.args.user_agent kwargs = kwargs.copy() kwargs['headers'] = headers return kwargs
def _make_headers(config, kwargs)
Replace the kwargs with one where the headers include our user-agent
3.139332
2.609553
1.203015
return await _retry_do(config.session.get, url, *args, **_make_headers(config, kwargs))
async def retry_get(config, url, *args, **kwargs)
aiohttp wrapper for GET
7.746277
6.16439
1.256617
return await _retry_do(config.session.post, url, *args, **_make_headers(config, kwargs))
async def retry_post(config, url, *args, **kwargs)
aiohttp wrapper for POST
8.107458
6.287611
1.289434
'''run the entire helper procedure, including: - start: initialize the helper, collection preferences - record: record any relevant features for the environment / session - interact: interact with the user for additional informatoin - submit: submit the compl...
def run(self, positionals=None)
run the entire helper procedure, including: - start: initialize the helper, collection preferences - record: record any relevant features for the environment / session - interact: interact with the user for additional informatoin - submit: submit the completed reques...
21.507559
4.600368
4.675182
'''start the helper flow. We check helper system configurations to determine components that should be collected for the submission. This is where the client can also pass on any extra (positional) arguments in a list from the user. ''' bot.info('[helpme|%s]' %(s...
def start(self, positionals=None)
start the helper flow. We check helper system configurations to determine components that should be collected for the submission. This is where the client can also pass on any extra (positional) arguments in a list from the user.
43.939629
5.041989
8.714741
'''given a name of a configuration key and the provided content, collect the required metadata from the user. Parameters ========== step: the key in the configuration. Can be one of: user_message_<name> runtime_arg_<name> ...
def collect(self, step, content)
given a name of a configuration key and the provided content, collect the required metadata from the user. Parameters ========== step: the key in the configuration. Can be one of: user_message_<name> runtime_arg_<name> ...
7.807106
2.611389
2.989637
'''given a key in the configuration, collect the runtime argument if provided. Otherwise, prompt the user for the value. Parameters ========== step: the name of the step, should be 'runtime_arg_<name>' message: the content of the step, the message to show ...
def collect_argument(self, step, message)
given a key in the configuration, collect the runtime argument if provided. Otherwise, prompt the user for the value. Parameters ========== step: the name of the step, should be 'runtime_arg_<name>' message: the content of the step, the message to show the user if...
12.39597
2.079376
5.96139
'''collect a limited set of environment variables based on the list under record_envirionment in the configuration file. ''' # whitelist is a newline separated list under record_environment envars = self._get_setting(name='whitelist', sect...
def record_environment(self)
collect a limited set of environment variables based on the list under record_envirionment in the configuration file.
10.857641
7.665356
1.416456
'''record an asciinema from the user session, saving the file to a temporary file and showing the user so if he/she needs to do it again, the file can be provided. The flow of events below makes the following checks: 1. The user confirms it is ok to record ...
def record_asciinema(self)
record an asciinema from the user session, saving the file to a temporary file and showing the user so if he/she needs to do it again, the file can be provided. The flow of events below makes the following checks: 1. The user confirms it is ok to record 2. The rec...
9.27843
3.885569
2.38792
''' a function for the helper to announce him or herself, depending on the level specified. If you want your client to have additional announced things here, then implement the class `_speak` for your client. ''' if self.quiet is False: bo...
def speak(self)
a function for the helper to announce him or herself, depending on the level specified. If you want your client to have additional announced things here, then implement the class `_speak` for your client.
30.121254
3.584569
8.403034
self._read_configuration_file(config_filename) if self._constants_filename: self._io.title('Constants') self.connect() self._get_old_columns() self._get_columns() self._enhance_columns() self._merge_columns() ...
def main(self, config_filename, regex)
:param str config_filename: The config filename. :param str regex: The regular expression for columns which we want to use. :rtype: int
6.315281
6.34711
0.994985
n_id = len(self._labels) n_widths = len(self._constants) - n_id self._io.writeln('') self._io.text('Number of constants based on column widths: {0}'.format(n_widths)) self._io.text('Number of constants based on database IDs : {0}'.format(n_id))
def __log_number_of_constants(self)
Logs the number of constants generated.
6.327631
5.845879
1.082409
config = configparser.ConfigParser() config.read(config_filename) self._constants_filename = config.get('constants', 'columns') self._prefix = config.get('constants', 'prefix') self._class_name = config.get('constants', 'class')
def _read_configuration_file(self, config_filename)
Reads parameters from the configuration file. :param str config_filename: The name of the configuration file.
3.314772
3.780508
0.876806
helper = ConstantClass(self._class_name, self._io) content = helper.source_with_constants(self._constants) Util.write_two_phases(helper.file_name(), content, self._io)
def __write_constant_class(self)
Inserts new and replaces old (if any) constant declaration statements in the class that acts like a namespace for constants.
11.434361
10.894071
1.049595
if os.getenv(envvar) is None: raise KeyError( "Required ENVVAR: {0} is not set".format(envvar)) if not os.getenv(envvar): # test if env var is empty raise KeyError( "Required ENVVAR: {0} is empty".format(envvar)) return True
def _check_env_var(envvar: str) -> bool
Check Environment Variable to verify that it is set and not empty. :param envvar: Environment Variable to Check. :returns: True if Environment Variable is set and not empty. :raises: KeyError if Environment Variable is not set or is empty. .. versionadded:: 0.0.12
3.086499
2.965377
1.040845
lower_case_state = state.lower() if lower_case_state in _VALID_STATES: return True return False
def valid_state(state: str) -> bool
Validate State Argument Checks that either 'on' or 'off' was entered as an argument to the CLI and make it lower case. :param state: state to validate. :returns: True if state is valid. .. versionchanged:: 0.0.12 This moethod was renamed from validateState to valid_state to conform ...
4.40924
4.152001
1.061956
for envvar in _REQUIRED_ENV_VARS: try: _check_env_var(envvar) except KeyError as ex: LOG.error(ex) sys.exit(1) return True
def valid_env_vars() -> bool
Validate that required env vars exist. :returns: True if required env vars exist. .. versionadded:: 0.0.12
3.944649
4.285831
0.920393
webroot = os.path.dirname(__file__) self.template_path = os.path.join(webroot, 'templates') aiohttp_jinja2.setup( self, loader=jinja2.FileSystemLoader(self.template_path), filters={'sorted': sorted, 'int': int} ) self['static_root_url'] = '/stat...
def configure_panel(self)
Configure templates and routing
3.360864
3.141237
1.069917
logging.info('Starting server, listening on %s.', self.port) runner = web.AppRunner(self) await runner.setup() site = web.TCPSite(runner, '', self.port) await site.start()
async def start(self)
Initialize and start WebServer
3.394137
3.076935
1.10309
shepherd = self.request.app.vmshepherd data = {'presets': {}, 'config': shepherd.config} presets = await shepherd.preset_manager.list_presets() runtime = shepherd.runtime_manager for name in presets: preset = shepherd.preset_manager.get_preset(name) ...
async def get(self)
Inject all preset data to Panel and Render a Home Page
3.907479
3.667082
1.065555
data = [] for key, value in dictionary.items(): data.append('{0}="{1}"'.format(key, value)) return ', '.join(data)
def serialize(dictionary)
Turn dictionary into argument like string.
3.072987
2.570248
1.195599
namespace = Lan.getServiceType("getAmountOfHostsConnected") + str(lanInterfaceId) uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetHostNumberOfEntries", timeout=timeout) return int(results["NewHostNumberOfEntries"])
def getAmountOfHostsConnected(self, lanInterfaceId=1, timeout=1)
Execute NewHostNumberOfEntries action to get the amount of known hosts. :param int lanInterfaceId: the id of the LAN interface :param float timeout: the timeout to wait for the action to be executed :return: the amount of known hosts. :rtype: int .. seealso:: :meth:`~simpletr64...
10.14977
7.786653
1.303483
namespace = Lan.getServiceType("getHostDetailsByIndex") + str(lanInterfaceId) uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetGenericHostEntry", timeout=timeout, NewIndex=index) return HostDetails(results)
def getHostDetailsByIndex(self, index, lanInterfaceId=1, timeout=1)
Execute GetGenericHostEntry action to get detailed information's of a connected host. :param index: the index of the host :param int lanInterfaceId: the id of the LAN interface :param float timeout: the timeout to wait for the action to be executed :return: the detailed information's of...
14.463124
10.49095
1.378629
namespace = Lan.getServiceType("getHostDetailsByMACAddress") + str(lanInterfaceId) uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetSpecificHostEntry", timeout=timeout, NewMACAddress=macAddress) return HostDetails(results, macAddress=macAddress)
def getHostDetailsByMACAddress(self, macAddress, lanInterfaceId=1, timeout=1)
Get host details for a host specified by its MAC address. :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 lanInterfaceId: the id of the LAN interface :param float timeout:...
10.204288
11.315853
0.901769
namespace = Lan.getServiceType("getEthernetInfo") + str(lanInterfaceId) uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetInfo", timeout=timeout) return EthernetInfo(results)
def getEthernetInfo(self, lanInterfaceId=1, timeout=1)
Execute GetInfo action to get information's about the Ethernet interface. :param int lanInterfaceId: the id of the LAN interface :param float timeout: the timeout to wait for the action to be executed :return: information's about the Ethernet interface. :rtype: EthernetInfo
11.843979
10.142441
1.167764
namespace = Lan.getServiceType("getEthernetStatistic") + str(lanInterfaceId) uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetStatistics", timeout=timeout) return EthernetStatistic(results)
def getEthernetStatistic(self, lanInterfaceId=1, timeout=1)
Execute GetStatistics action to get statistics of the Ethernet interface. :param int lanInterfaceId: the id of the LAN interface :param float timeout: the timeout to wait for the action to be executed :return: statisticss of the Ethernet interface. :rtype: EthernetStatistic
12.214252
10.472567
1.166309
namespace = Lan.getServiceType("setEnable") + str(lanInterfaceId) uri = self.getControlURL(namespace) if status: setStatus = 1 else: setStatus = 0 self.execute(uri, namespace, "SetEnable", timeout=timeout, NewEnable=setStatus)
def setEnable(self, status, lanInterfaceId=1, timeout=1)
Set enable status for a LAN interface, be careful you don't cut yourself off. :param bool status: enable or disable the interface :param int lanInterfaceId: the id of the LAN interface :param float timeout: the timeout to wait for the action to be executed
8.065413
9.94267
0.811192
'''submit a uservoice ticket. When we get here we should have: {'user_prompt_issue': 'I want to do the thing.', 'record_asciinema': '/tmp/helpme.93o__nt5.json', 'record_environment': ((1,1),(2,2)...(N,N))} Required Client Variables self.api_...
def _submit(self)
submit a uservoice ticket. When we get here we should have: {'user_prompt_issue': 'I want to do the thing.', 'record_asciinema': '/tmp/helpme.93o__nt5.json', 'record_environment': ((1,1),(2,2)...(N,N))} Required Client Variables self.api_key ...
7.008887
2.836243
2.471187
'''authenticate with uservoice by creating a client.''' if not hasattr(self, 'client'): self.client = uservoice.Client(self.subdomain, self.api_key, self.api_secret)
def authenticate(self)
authenticate with uservoice by creating a client.
7.862863
4.322043
1.819247
'''post_ticket will post a ticket to the uservoice helpdesk Parameters ========== title: the title (subject) of the issue body: the message to send ''' # Populate the ticket ticket = {'subject': title, 'message': body } ...
def post_ticket(self, title, body)
post_ticket will post a ticket to the uservoice helpdesk Parameters ========== title: the title (subject) of the issue body: the message to send
8.352218
4.318237
1.934173
dr = DataReader() return dr.Get3DData(datapath=datapath, qt_app=qt_app, dataplus_format=dataplus_format, gui=gui, start=start, stop=stop, step=step, convert_to_gray=convert_to_gray, series_number=series_number, use_economic_dtype=True, dicom_expected=dicom_ex...
def read(datapath, qt_app=None, dataplus_format=True, gui=False, start=0, stop=None, step=1, convert_to_gray=True, series_number=None, dicom_expected=None, **kwargs)
Simple read function. Internally calls DataReader.Get3DData()
2.742379
2.186136
1.254441
metadata = {'series_number': 0, 'datadir': datapath} spacing = image.GetSpacing() metadata['voxelsize_mm'] = [ spacing[2], spacing[0], spacing[1], ] return metadata
def _metadata(image, datapath)
Function which returns metadata dict. :param image: image to get spacing from :param datapath: path to data :return: {'series_number': '', 'datadir': '', 'voxelsize_mm': ''}
4.867256
3.42708
1.420234
self.orig_datapath = datapath datapath = os.path.expanduser(datapath) if series_number is not None and type(series_number) != int: series_number = int(series_number) if not os.path.exists(datapath): logger.error("Path '" + datapath + "' does not exist")...
def Get3DData(self, datapath, qt_app=None, dataplus_format=True, gui=False, start=0, stop=None, step=1, convert_to_gray=True, series_number=None, use_economic_dtype=True, dicom_expected=None, **kwargs)
Returns 3D data and its metadata. # NOTE(:param qt_app:) If it is set to None (as default) all dialogs for series selection are performed in terminal. If qt_app is set to QtGui.QApplication() dialogs are in Qt. :param datapath: directory with input data :param qt_app: Dialog destinatio...
2.434
2.433594
1.000167
start = self.start stop = self.stop step = self.step kwargs = self.kwargs gui = self.gui if (dicom_expected is not False) and (dcmr.is_dicom_dir(datapath)): # reading dicom logger.debug('Dir - DICOM') logger.debug("dicom_expected " + str...
def __ReadFromDirectory(self, datapath, dicom_expected=None)
This function is actually the ONE, which reads 3D data from file :param datapath: path to file :return: tuple (data3d, metadata)
3.700787
3.550781
1.042246
def _create_meta(_datapath): meta = { 'series_number': 0, 'datadir': _datapath } return meta path, ext = os.path.splitext(datapath) ext = ext[1:] if ext in ('pklz', 'pkl'): logger.debug...
def __ReadFromFile(self, datapath)
Reads file and returns containing 3D data and its metadata. Supported formats: pklz, pkl, hdf5, idx, dcm, Dcm, dicom, bz2 and "raw files" :param datapath: path to file to read :return: tuple (data3d, metadata)
3.634891
3.185209
1.141178
try: import SimpleITK as Sitk except ImportError as e: logger.error("Unable to import SimpleITK. On Windows try version 1.0.1") image = Sitk.ReadImage(datapath) data3d = dcmtools.get_pixel_array_from_sitk(image) # data3d, original_dtype = dcmreadd...
def _read_with_sitk(datapath)
Reads file using SimpleITK. Returns array of pixels (image located in datapath) and its metadata. :param datapath: path to file (img or dicom) :return: tuple (data3d, metadata), where data3d is array of pixels
5.538289
5.296023
1.045745
ds = dicom.read_file(path) try: metadata["voxelsize_mm"][0] = ds.SpacingBetweenSlices except Exception as e: logger.warning("Read dicom 'SpacingBetweenSlices' failed: ", e) return metadata
def _fix_sitk_bug(path, metadata)
There is a bug in simple ITK for Z axis in 3D images. This is a fix. :param path: path to dicom file to read :param metadata: metadata to correct :return: corrected metadata
5.074219
5.450749
0.930921
'''get_pid will return a pid of interest. First we use given variable, then environmental variable PID, and then PID of running process ''' if pid == None: if os.environ.get("PID",None) != None: pid = int(os.environ.get("PID")) # Then use current running script as process ...
def get_pid(pid=None)
get_pid will return a pid of interest. First we use given variable, then environmental variable PID, and then PID of running process
7.159608
3.093147
2.314668
'''get_memory_usage returns a dictionary of resident set size (rss) and virtual memory size (vms) for a process of interest, for as long as the process is running :param pid: the pid to use: :param timeout: the timeout :: notes example: sleep 3 & exec python -m memory "$!" ...
def get_memory_usage(pid=None,timeout=1)
get_memory_usage returns a dictionary of resident set size (rss) and virtual memory size (vms) for a process of interest, for as long as the process is running :param pid: the pid to use: :param timeout: the timeout :: notes example: sleep 3 & exec python -m memory "$!"
5.567968
2.341418
2.378033
try: self._routine_name = os.path.splitext(os.path.basename(self._source_filename))[0] if os.path.exists(self._source_filename): if os.path.isfile(self._source_filename): self._m_time = int(os.path.getmtime(self._source_filename)) ...
def load_stored_routine(self)
Loads the stored routine into the instance of MySQL. Returns the metadata of the stored routine if the stored routine is loaded successfully. Otherwise returns False. :rtype: dict[str,str]|bool
4.133733
4.071751
1.015222
with open(self._source_filename, 'r', encoding=self._routine_file_encoding) as file: self._routine_source_code = file.read() self._routine_source_code_lines = self._routine_source_code.split("\n")
def __read_source_file(self)
Reads the file with the source of the stored routine.
3.097147
2.795599
1.107865
if not self.shadow_directory: return destination_filename = os.path.join(self.shadow_directory, self._routine_name) + '.sql' if os.path.realpath(destination_filename) == os.path.realpath(self._source_filename): raise LoaderException("Shadow copy will override r...
def __save_shadow_copy(self)
Saves a copy of the stored routine source with pure SQL (if shadow directory is set).
2.90836
2.500356
1.163178
self._set_magic_constants() routine_source = [] i = 0 for line in self._routine_source_code_lines: self._replace['__LINE__'] = "'%d'" % (i + 1) for search, replace in self._replace.items(): tmp = re.findall(search, line, re.IGNORECASE) ...
def __substitute_replace_pairs(self)
Substitutes all replace pairs in the source of the stored routine.
3.325008
3.095871
1.074014
self._io.error(str(exception).strip().split(os.linesep))
def _log_exception(self, exception)
Logs an exception. :param Exception exception: The exception. :rtype: None
12.436357
14.998624
0.829167
ret = True pattern = re.compile('(@[A-Za-z0-9_.]+(%(max-)?type)?@)') matches = pattern.findall(self._routine_source_code) placeholders = [] if len(matches) != 0: for tmp in matches: placeholder = tmp[0] if placeholder.lower(...
def __get_placeholders(self)
Extracts the placeholders from the stored routine source.
4.791332
4.218734
1.135727
positions = self._get_specification_positions() if positions[0] != -1 and positions[1] != -1: pattern = re.compile(r'^\s*--\s+type\s*:\s*(\w+)\s*(.+)?\s*', re.IGNORECASE) for line_number in range(positions[0], positions[1] + 1): matches = pattern.findall(...
def _get_designation_type(self)
Extracts the designation type of the stored routine.
3.062881
2.776866
1.102999
start = -1 for (i, line) in enumerate(self._routine_source_code_lines): if self._is_start_of_stored_routine(line): start = i end = -1 for (i, line) in enumerate(self._routine_source_code_lines): if self._is_start_of_stored_routine_body(li...
def _get_specification_positions(self)
Returns a tuple with the start and end line numbers of the stored routine specification. :rtype: tuple
3.227786
2.890431
1.116715
line1 = None line2 = None i = 0 for line in self._routine_source_code_lines: if re.match(r'\s*/\*\*', line): line1 = i if re.match(r'\s*\*/', line): line2 = i if self._is_start_of_stored_routine(line): ...
def __get_doc_block_lines(self)
Returns the start and end line of the DOcBlock of the stored routine code.
3.782004
2.779011
1.360917
line1, line2 = self.__get_doc_block_lines() if line1 is not None and line2 is not None and line1 <= line2: doc_block = self._routine_source_code_lines[line1:line2 - line1 + 1] else: doc_block = list() reflection = DocBlockReflection(doc_block) ...
def __get_doc_block_parts_source(self)
Extracts the DocBlock (in parts) from the source of the stored routine source.
3.258752
2.980272
1.093441
self.__get_doc_block_parts_source() helper = self._get_data_type_helper() parameters = list() for parameter_info in self._parameters: parameters.append( {'parameter_name': parameter_info['name'], 'python_type': helper...
def __get_doc_block_parts_wrapper(self)
Generates the DocBlock parts to be used by the wrapper generator.
3.300193
3.120839
1.05747
self._pystratum_metadata['routine_name'] = self._routine_name self._pystratum_metadata['designation'] = self._designation_type self._pystratum_metadata['table_name'] = self._table_name self._pystratum_metadata['parameters'] = self._parameters self._pystratum_metadata['co...
def _update_metadata(self)
Updates the metadata of the stored routine.
2.999808
2.820814
1.063455
real_path = os.path.realpath(self._source_filename) self._replace['__FILE__'] = "'%s'" % real_path self._replace['__ROUTINE__'] = "'%s'" % self._routine_name self._replace['__DIR__'] = "'%s'" % os.path.dirname(real_path)
def _set_magic_constants(self)
Adds magic constants to replace list.
3.595588
2.942294
1.222036
if '__FILE__' in self._replace: del self._replace['__FILE__'] if '__ROUTINE__' in self._replace: del self._replace['__ROUTINE__'] if '__DIR__' in self._replace: del self._replace['__DIR__'] if '__LINE__' in self._replace: del se...
def _unset_magic_constants(self)
Removes magic constants from current replace list.
2.403264
2.065137
1.163731
if os.linesep in sql: lines = sql.split(os.linesep) digits = math.ceil(math.log(len(lines) + 1, 10)) i = 1 for line in lines: if i == error_line: self._io.text('<error>{0:{width}} {1}</error>'.format(i, line, width=digi...
def _print_sql_with_error(self, sql, error_line)
Writes a SQL statement with an syntax error to the output. The line where the error occurs is highlighted. :param str sql: The SQL statement. :param int error_line: The line where the error occurs.
2.569198
2.754071
0.932873
keeped = [] for item in lst: keep = False if startswith is not None: if item.startswith(startswith): keep = True if notstartswith is not None: if not item.startswith(notstartswith): keep = True if contain is not None: ...
def list_filter(lst, startswith=None, notstartswith=None, contain=None, notcontain=None)
Keep in list items according to filter parameters. :param lst: item list :param startswith: keep items starting with :param notstartswith: remove items starting with :return:
1.719799
1.703374
1.009643
if type(dct) == collections.OrderedDict: dict_in = collections.OrderedDict() dict_out = collections.OrderedDict() else: dict_in = {} dict_out = {} for key, value in dct.items: if key in keys: dict_in[key] = value else: dict_out[ke...
def split_dict(dct, keys)
Split dict into two subdicts based on keys. :param dct: :param keys: :return: dict_in, dict_out
2.0271
1.834655
1.104895
for k, v in u.iteritems(): if isinstance(v, collections.Mapping): r = recursive_update(d.get(k, {}), v) d[k] = r else: d[k] = u[k] return d
def recursive_update(d, u)
Dict recursive update. Based on Alex Martelli code on stackoverflow http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth?answertab=votes#tab-top :param d: dict to update :param u: dict with new data :return:
1.389476
1.67776
0.828174
return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )
def flatten_dict_join_keys(dct, join_symbol=" ")
Flatten dict with defined key join symbol. :param dct: dict to flatten :param join_symbol: default value is " " :return:
5.741539
9.875997
0.581363
key_tf = [keyi.find(substring) != -1 for keyi in list_of_strings] if return_true_false_array: return key_tf keys_to_remove = list_of_strings[key_tf] return keys_to_remove
def list_contains(list_of_strings, substring, return_true_false_array=False)
Get strings in list which contains substring.
3.657308
3.606141
1.014189
keys_to_remove = list_contains(df.keys(), ignore_key_pattern) #key_tf = [key.find(noinfo_key_pattern) != -1 for key in df.keys()] # keys_to_remove # remove duplicates ks = copy.copy(list(df.keys())) for key in keys_to_remove: ks.remove(key) df = df.drop_duplicates(ks) retu...
def df_drop_duplicates(df, ignore_key_pattern="time")
Drop duplicates from dataframe ignore columns with keys containing defined pattern. :param df: :param noinfo_key_pattern: :return:
5.153972
4.271152
1.206694
tp = type(item) if tp == np.ndarray: if squeeze: item = item.squeeze() item = item.tolist() elif tp == list: for i in range(len(item)): item[i] = ndarray_to_list_in_structure(item[i]) elif tp == dict: for lab in item: item[lab] = ...
def ndarray_to_list_in_structure(item, squeeze=True)
Change ndarray in structure of lists and dicts into lists.
1.850481
1.794421
1.031241
key = next(key for key, val in dd.items() if val == value) return key
def dict_find_key(dd, value)
Find first suitable key in dict. :param dd: :param value: :return:
2.994916
5.131961
0.583581
if type(keys) != list: keys = [keys] # dcmdir = lst_of_dct[:] # lst_of_dct.sort(key=lambda x: [x[key] for key in keys], reverse=reverse, **sort_args) lst_of_dct.sort(key=lambda x: [((False, x[key]) if key in x else (True, 0)) for key in keys], reverse=reverse, **sort_args) return lst_o...
def sort_list_of_dicts(lst_of_dct, keys, reverse=False, **sort_args)
Sort list of dicts by one or multiple keys. If the key is not available, sort these to the end. :param lst_of_dct: input structure. List of dicts. :param keys: one or more keys in list :param reverse: :param sort_args: :return:
2.817256
2.969874
0.948611
if type(config) == collections.OrderedDict: config = dict(config) if type(config) == list: for i in range(0, len(config)): config[i] = ordered_dict_to_dict(config[i]) elif type(config) == dict: for key in config: config[key] = ordered_dict_to_dict(config...
def ordered_dict_to_dict(config)
Use dict instead of ordered dict in structure.
1.722086
1.626395
1.058836
config = configparser.ConfigParser() config.read(config_file) rdbms = config.get('database', 'rdbms').lower() wrapper = self.create_routine_wrapper_generator(rdbms) wrapper.main(config_file)
def run_command(self, config_file)
:param str config_file: The name of config file.
5.12878
4.818199
1.06446
# Note: We load modules and classes dynamically such that on the end user's system only the required modules # and other dependencies for the targeted RDBMS must be installed (and required modules and other # dependencies for the other RDBMSs are not required). if r...
def create_routine_wrapper_generator(self, rdbms)
Factory for creating a Constants objects (i.e. objects for generating a class with wrapper methods for calling stored routines in a database). :param str rdbms: The target RDBMS (i.e. mysql, mssql or pgsql). :rtype: pystratum.RoutineWrapperGenerator.RoutineWrapperGenerator
4.0096
3.596389
1.114896
if supplement: return_value = supplement.get(section, option, fallback=config.get(section, option, fallback=fallback)) else: return_value = config.get(section, option, fallback=fallback) if fallback is None and return_value is None: raise KeyError("O...
def _get_option(config, supplement, section, option, fallback=None)
Reads an option for a configuration file. :param configparser.ConfigParser config: The main config file. :param configparser.ConfigParser supplement: The supplement config file. :param str section: The name of the section op the option. :param str option: The name of the option. ...
2.371242
2.610343
0.908402
config = ConfigParser() config.read(config_filename) if 'supplement' in config['database']: path = os.path.dirname(config_filename) + '/' + config.get('database', 'supplement') config_supplement = ConfigParser() config_supplement.read(path) e...
def _read_configuration(config_filename)
Checks the supplement file. :param str config_filename: The name of the configuration file. :rtype: (configparser.ConfigParser,configparser.ConfigParser)
2.710056
2.477293
1.093958
'''a wrapper around generation of an asciinema.api.Api and a custom recorder to pull out the input arguments to the Record from argparse. The function generates a filename in advance and a return code so we can check the final status. ''' import asciinema.config as aconfig from a...
def record_asciinema()
a wrapper around generation of an asciinema.api.Api and a custom recorder to pull out the input arguments to the Record from argparse. The function generates a filename in advance and a return code so we can check the final status.
11.937379
4.054871
2.94396
namespace = Fritz.getServiceType("sendWakeOnLan") + str(lanInterfaceId) uri = self.getControlURL(namespace) self.execute(uri, namespace, "X_AVM-DE_WakeOnLANByMACAddress", timeout=timeout, NewMACAddress=macAddress)
def sendWakeOnLan(self, macAddress, lanInterfaceId=1, timeout=1)
Send a wake up package to a device specified by its MAC address. :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 lanInterfaceId: the id of the LAN interface :param float t...
9.720334
10.648531
0.912833
namespace = Fritz.getServiceType("doUpdate") uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "X_AVM-DE_DoUpdate", timeout=timeout) return results["NewUpgradeAvailable"], results["NewX_AVM-DE_UpdateState"]
def doUpdate(self, timeout=1)
Do a software update of the Fritz Box if available. :param float timeout: the timeout to wait for the action to be executed :return: a list of if an update was available and the update state (bool, str) :rtype: tuple(bool, str)
8.83462
6.936697
1.273606
namespace = Fritz.getServiceType("isOptimizedForIPTV") + str(wifiInterfaceId) uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "X_AVM-DE_GetIPTVOptimized", timeout=timeout) return bool(int(results["NewX_AVM-DE_IPTVoptimize"]))
def isOptimizedForIPTV(self, wifiInterfaceId=1, timeout=1)
Return if the Wifi interface is optimized for IP TV :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for the action to be executed :return: if the Wifi interface is optimized for IP TV :rtype: bool .. seealso:: :meth:`~simpletr6...
6.581538
6.691541
0.983561
namespace = Fritz.getServiceType("setOptimizedForIPTV") + str(wifiInterfaceId) uri = self.getControlURL(namespace) if status: setStatus = 1 else: setStatus = 0 arguments = {"timeout": timeout, "NewX_AVM-DE_IPTVoptimize": setStatus} self...
def setOptimizedForIPTV(self, status, wifiInterfaceId=1, timeout=1)
Set if the Wifi interface is optimized for IP TV :param bool status: set if Wifi interface should be optimized :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for the action to be executed .. seealso:: :meth:`~simpletr64.actions.Fritz....
7.207764
7.41292
0.972325
namespace = Fritz.getServiceType("getCallList") uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetCallList") # setup proxies proxies = {} if self.httpProxy: proxies = {"https": self.httpProxy} if self.httpsProxy...
def getCallList(self, timeout=1)
Get the list of phone calls made Example of a phone call result: :: [{'Count': None, 'Name': None, 'CalledNumber': '030868709971', 'Numbertype': 'sip', 'Duration': '0:01', 'Caller': '015155255399', 'Called': 'SIP: 030868729971', 'Date': '02.01.14 13:14', 'Device': ...
3.384718
3.472488
0.974724
_rpio.add_tcp_callback(port, callback, threaded_callback)
def add_tcp_callback(port, callback, threaded_callback=False)
Adds a unix socket server callback, which will be invoked when values arrive from a connected socket client. The callback must accept two parameters, eg. ``def callback(socket, msg)``.
6.021321
7.265941
0.828705
_rpio.add_interrupt_callback(gpio_id, callback, edge, pull_up_down, \ threaded_callback, debounce_timeout_ms)
def add_interrupt_callback(gpio_id, callback, edge='both', \ pull_up_down=PUD_OFF, threaded_callback=False, \ debounce_timeout_ms=None)
Add a callback to be executed when the value on 'gpio_id' changes to the edge specified via the 'edge' parameter (default='both'). `pull_up_down` can be set to `RPIO.PUD_UP`, `RPIO.PUD_DOWN`, and `RPIO.PUD_OFF`. If `threaded_callback` is True, the callback will be started inside a Thread. If ...
2.307346
3.529542
0.653724
if threaded: t = Thread(target=_rpio.wait_for_interrupts, args=(epoll_timeout,)) t.daemon = True t.start() else: _rpio.wait_for_interrupts(epoll_timeout)
def wait_for_interrupts(threaded=False, epoll_timeout=1)
Blocking loop to listen for GPIO interrupts and distribute them to associated callbacks. epoll_timeout is an easy way to shutdown the blocking function. Per default the timeout is set to 1 second; if `_is_waiting_for_interrupts` is set to False the loop will exit. If an exception occurs while waiting f...
2.211769
2.741737
0.806703
with cd("/tmp/source/c_gpio"): test = "import _GPIO; print(_GPIO.VERSION_GPIO)" run("make gpio2.7 && cp build/_GPIO.so .") run('sudo python2.7 -c "%s"' % test) run("cp _GPIO.so ../RPIO/") run("cp _GPIO.so ../RPIO/_GPIO27.so") run("make gpio3.2 && cp build/_GPIO.s...
def build_gpio()
Builds source with Python 2.7 and 3.2, and tests import
5.551179
4.34068
1.278873
with cd("/tmp/source/c_pwm"): test = "import _PWM; print(_PWM.VERSION)" run("make py2.7") run('sudo python2.7 -c "%s"' % test) run("cp _PWM.so ../RPIO/PWM/") run("mv _PWM.so ../RPIO/PWM/_PWM27.so") run("make py3.2") run('python3.2 -c "%s"' % test) ...
def build_pwm()
Builds source with Python 2.7 and 3.2, and tests import
5.315235
4.296607
1.237077
# One more safety input and then we are ready to go :) x = prompt("Are you sure to upload the current version to pypi?") if not x or not x.lower() in ["y", "yes"]: return local("rm -rf dist") local("python setup.py sdist") version = _get_cur_version() fn = "RPIO-%s.tar.gz" % ve...
def upload_to_pypi()
Upload sdist and bdist_eggs to pypi
3.654453
3.638649
1.004343
t = Thread(target=callback, args=args) t.daemon = True t.start()
def _threaded_callback(callback, *args)
Internal wrapper to start a callback in threaded mode. Using the daemon mode to not block the main thread from exiting.
2.674113
2.809608
0.951774
if not callback: raise AttributeError("No callback") serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serversocket.bind((_TCP_SOCKET_HOST, port)) serversocket.listen(1) ...
def add_tcp_callback(self, port, callback, threaded_callback=False)
Adds a unix socket server callback, which will be invoked when values arrive from a connected socket client. The callback must accept two parameters, eg. ``def callback(socket, msg)``.
3.230617
3.184224
1.01457
debug("- removing interrupts on gpio %s" % gpio_id) gpio_id = _GPIO.channel_to_gpio(gpio_id) fileno = self._map_gpioid_to_fileno[gpio_id] # 1. Remove from epoll self._epoll.unregister(fileno) # 2. Cache the file f = self._map_fileno_to_file[fileno] ...
def del_interrupt_callback(self, gpio_id)
Delete all interrupt callbacks from a certain gpio
2.932938
2.974275
0.986102
val = int(val) # Filter invalid edge values (sometimes 1 comes in when edge=falling) edge = self._map_fileno_to_options[fileno]["edge"] if (edge == 'rising' and val == 0) or (edge == 'falling' and val == 1): return # If user activated debounce for this call...
def _handle_interrupt(self, fileno, val)
Internally distributes interrupts to all attached callbacks
3.744087
3.64488
1.027218
self._is_waiting_for_interrupts = True while self._is_waiting_for_interrupts: events = self._epoll.poll(epoll_timeout) for fileno, event in events: debug("- epoll event on fd %s: %s" % (fileno, event)) if fileno in self._tcp_server_sockets...
def wait_for_interrupts(self, epoll_timeout=1)
Blocking loop to listen for GPIO interrupts and distribute them to associated callbacks. epoll_timeout is an easy way to shutdown the blocking function. Per default the timeout is set to 1 second; if `_is_waiting_for_interrupts` is set to False the loop will exit. If an exception occurs...
3.283326
3.266512
1.005147
debug("Cleaning up interfaces...") for gpio_id in self._gpio_kernel_interfaces_created: # Close the value-file and remove interrupt bindings self.del_interrupt_callback(gpio_id) # Remove the kernel GPIO interface debug("- unexporting GPIO %s" % g...
def cleanup_interfaces(self)
Removes all /sys/class/gpio/gpioN interfaces that this script created, and deletes callback bindings. Should be used after using interrupts.
7.537365
5.991206
1.258071
for fileno in self._tcp_client_sockets.keys(): self.close_tcp_client(fileno) for fileno, items in self._tcp_server_sockets.items(): socket, cb = items debug("- _cleanup server socket connection (fd %s)" % fileno) self._epoll.unregister(fileno) ...
def cleanup_tcpsockets(self)
Closes all TCP connections and then the socket servers
5.429459
5.498614
0.987423
return _PWM.add_channel_pulse(dma_channel, gpio, start, width)
def add_channel_pulse(dma_channel, gpio, start, width)
Add a pulse for a specific GPIO to a dma channel subcycle. `start` and `width` are multiples of the pulse-width increment granularity.
3.827827
5.670001
0.675102
# Make sure we can set the exact pulse_width_us _pulse_incr_us = _PWM.get_pulse_incr_us() if pulse_width_us % _pulse_incr_us: # No clean division possible raise AttributeError(("Pulse width increment granularity %sus " "cannot divide a pulse-t...
def set_servo(self, gpio, pulse_width_us)
Sets a pulse-width on a gpio to repeat every subcycle (by default every 20ms).
4.538918
4.496015
1.009543
ret = [] for item in _list: if item not in ret: ret.append(item) return ret
def unique(_list)
Makes the list have unique items only and maintains the order list(set()) won't provide that :type _list list :rtype: list
2.726999
2.951854
0.923826
# 1. remove aliases # FROM `dimension_wikis` `dw` # INNER JOIN `fact_wam_scores` `fwN` query = re.sub(r'(\s(FROM|JOIN)\s`[^`]+`)\s`[^`]+`', r'\1', query, flags=re.IGNORECASE) # 2. `database`.`table` notation -> database.table query = re.sub(r'`([^`]+)`\.`([^`]+)`', r'\1.\2', query) # ...
def preprocess_query(query)
Perform initial query cleanup :type query str :rtype str
4.247983
4.247173
1.000191
query = preprocess_query(query) parsed = sqlparse.parse(query) # handle empty queries (#12) if not parsed: return [] tokens = TokenList(parsed[0].tokens).flatten() # print([(token.value, token.ttype) for token in tokens]) return [token for token in tokens if token.ttype is no...
def get_query_tokens(query)
:type query str :rtype: list[sqlparse.sql.Token]
4.446803
3.977794
1.117907
columns = [] last_keyword = None last_token = None # print(preprocess_query(query)) # these keywords should not change the state of a parser # and not "reset" previously found SELECT keyword keywords_ignored = ['AS', 'AND', 'OR', 'IN', 'IS', 'NOT', 'NOT NULL', 'LIKE', 'CASE', 'WHEN'] ...
def get_query_columns(query)
:type query str :rtype: list[str]
4.205946
4.214524
0.997965
tables = [] last_keyword = None last_token = None table_syntax_keywords = [ # SELECT queries 'FROM', 'WHERE', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'ON', # INSERT queries 'INTO', 'VALUES', # UPDATE queries 'UPDATE', 'SET', # Hive q...
def get_query_tables(query)
:type query str :rtype: list[str]
4.11244
4.145047
0.992133
limit = None offset = None last_keyword = None last_token = None # print(query) for token in get_query_tokens(query): # print([token, token.ttype, last_keyword]) if token.is_keyword and token.value.upper() in ['LIMIT', 'OFFSET']: last_keyword = token.value.uppe...
def get_query_limit_and_offset(query)
:type query str :rtype: (int, int)
2.748263
2.808751
0.978464
sql = sql.replace('%', '') # LIKE '%bot' sql = re.sub(r"LIKE '[^\']+'", 'LIKE X', sql) # or all_groups LIKE X or all_groups LIKE X matches = re.finditer(r'(or|and) [^\s]+ LIKE X', sql, flags=re.IGNORECASE) matches = [match.group(0) for match in matches] if matches else None if matche...
def normalize_likes(sql)
Normalize and wrap LIKE statements :type sql str :rtype: str
4.696352
5.074991
0.925391
if sql is None: return None # multiple spaces sql = re.sub(r'\s{2,}', ' ', sql) # MW comments # e.g. /* CategoryDataService::getMostVisited N.N.N.N */ sql = remove_comments_from_sql(sql) # handle LIKE statements sql = normalize_likes(sql) sql = re.sub(r"\\\\", '', sq...
def generalize_sql(sql)
Removes most variables from an SQL query and replaces them with X or N for numbers. Based on Mediawiki's DatabaseBase::generalizeSQL :type sql str|None :rtype: str
4.882612
4.863461
1.003938