code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
@wraps(function)
def wrapped(*args, **kwargs):
return self.submit(function, *args, **kwargs)
return wrapped | def async_func(self, function) | Decorator for let a normal function return the NewFuture | 3.15855 | 2.635787 | 1.198333 |
try:
from multiprocessing import cpu_count
return cpu_count()
except Exception as e:
Config.main_logger.error("_get_cpu_count failed for %s" % e) | def _get_cpu_count(self) | Get the cpu count. | 5.567839 | 4.735309 | 1.175813 |
with self._shutdown_lock:
if self._shutdown:
raise RuntimeError("cannot schedule new futures after shutdown")
callback = kwargs.pop("callback", self.default_callback)
future = NewFuture(
self._timeout,
args,
... | def submit(self, func, *args, **kwargs) | Submit a function to the pool, `self.submit(function,arg1,arg2,arg3=3)` | 3.941467 | 3.659682 | 1.076997 |
with self._shutdown_lock:
if PY3 and self._broken:
raise BrokenProcessPool(
"A child process terminated "
"abruptly, the process pool is not usable anymore"
)
if self._shutdown_thread:
raise... | def submit(self, func, *args, **kwargs) | Submit a function to the pool, `self.submit(function,arg1,arg2,arg3=3)` | 4.275133 | 4.140925 | 1.03241 |
self.task_end_time = time.time()
self.task_cost_time = self.task_end_time - self.task_start_time
with self._condition:
for callback in self._done_callbacks:
try:
result = callback(self)
if callback in self._user_callbac... | def _invoke_callbacks(self) | Record the task_end_time & task_cost_time, set result for self._callback_result. | 4.103469 | 3.054839 | 1.343269 |
if self._state in [PENDING, RUNNING]:
self.x
if self._user_callbacks:
return self._callback_result
else:
return self.x | def callback_result(self) | Block the main thead until future finish, return the future.callback_result. | 11.025146 | 9.692245 | 1.137523 |
with self._condition:
result = None
if not self.done():
self._condition.wait(self._timeout)
if not self.done():
# timeout
self.set_exception(TimeoutError())
if self._state in [CANCELLED, CANCELLED_AND_NOTIFI... | def x(self) | Block the main thead until future finish, return the future.result(). | 3.146899 | 2.922601 | 1.076746 |
self.session.close()
self.pool.shutdown(wait=wait) | def close(self, wait=False) | Close session, shutdown pool. | 5.954577 | 3.121059 | 1.907871 |
return self.pool.submit(
self._request,
method=method,
url=url,
retry=retry,
callback=callback or self.default_callback,
**kwargs
) | def request(self, method, url, callback=None, retry=0, **kwargs) | Similar to `requests.request`, but return as NewFuture. | 3.219266 | 2.907871 | 1.107087 |
kwargs.setdefault("allow_redirects", True)
return self.request(
"get", url=url, params=params, callback=callback, retry=retry, **kwargs
) | def get(self, url, params=None, callback=None, retry=0, **kwargs) | Similar to `requests.get`, but return as NewFuture. | 2.66657 | 2.519293 | 1.05846 |
return self.request(
"post",
url=url,
data=data,
json=json,
callback=callback,
retry=retry,
**kwargs
) | def post(self, url, data=None, json=None, callback=None, retry=0, **kwargs) | Similar to `requests.post`, but return as NewFuture. | 2.148206 | 2.168335 | 0.990717 |
kwargs.setdefault("allow_redirects", False)
return self.request("head", url=url, callback=callback, retry=retry, **kwargs) | def head(self, url, callback=None, retry=0, **kwargs) | Similar to `requests.head`, but return as NewFuture. | 3.096744 | 2.719355 | 1.138779 |
kwargs.setdefault("allow_redirects", True)
return self.request(
"options", url=url, callback=callback, retry=retry, **kwargs
) | def options(self, url, callback=None, retry=0, **kwargs) | Similar to `requests.options`, but return as NewFuture. | 3.116368 | 2.69455 | 1.156545 |
namespace = Wan.getServiceType("getLinkInfo") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return WanLinkInfo(results) | def getLinkInfo(self, wanInterfaceId=1, timeout=1) | Execute GetInfo action to get basic WAN link information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: basic WAN link information's
:rtype: WanLinkInfo | 9.915908 | 7.921009 | 1.251849 |
namespace = Wan.getServiceType("getLinkProperties") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetCommonLinkProperties", timeout=timeout)
return WanLinkProperties(results) | def getLinkProperties(self, wanInterfaceId=1, timeout=1) | Execute GetCommonLinkProperties action to get WAN link properties.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN link properties
:rtype: WanLinkProperties | 9.484324 | 7.392413 | 1.282981 |
namespace = Wan.getServiceType("getADSLInfo") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return ADSLInfo(results) | def getADSLInfo(self, wanInterfaceId=1, timeout=1) | Execute GetInfo action to get basic ADSL information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: ADSL informations.
:rtype: ADSLInfo | 9.453541 | 8.446429 | 1.119235 |
namespace = Wan.getServiceType("getEthernetLinkStatus") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetEthernetLinkStatus", timeout=timeout)
return results["NewEthernetLinkStatus"] | def getEthernetLinkStatus(self, wanInterfaceId=1, timeout=1) | Execute GetEthernetLinkStatus action to get the status of the ethernet link.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: status of the ethernet link
:rtype: str | 8.562139 | 8.410673 | 1.018009 |
namespace = Wan.getServiceType("getByteStatistic") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetTotalBytesSent", timeout=timeout)
results2 = self.execute(uri, namespace, "GetTotalBytesReceived", timeout=timeout)
r... | def getByteStatistic(self, wanInterfaceId=1, timeout=1) | Execute GetTotalBytesSent&GetTotalBytesReceived actions to get WAN statistics.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: a tuple of two values, total bytes sent and total bytes received
:rtype: li... | 5.485045 | 4.709311 | 1.164723 |
namespace = Wan.getServiceType("getConnectionInfo") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return ConnectionInfo(results) | def getConnectionInfo(self, wanInterfaceId=1, timeout=1) | Execute GetInfo action to get WAN connection information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN connection information's.
:rtype: ConnectionInfo | 10.754452 | 8.905645 | 1.207599 |
namespace = Wan.getServiceType("setEnable") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
if status:
setStatus = 1
else:
setStatus = 0
self.execute(uri, namespace, "SetEnable", timeout=timeout, NewEnable=setStatus) | def setEnable(self, status, wanInterfaceId=1, timeout=1) | Set enable status for a WAN interface, be careful you don't cut yourself off.
:param bool status: enable or disable the interface
:param int wanInterfaceId: the id of the WAN interface
:param float timeout: the timeout to wait for the action to be executed | 7.911127 | 9.640586 | 0.820606 |
namespace = Wan.getServiceType("requestConnection") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
self.execute(uri, namespace, "RequestConnection", timeout=timeout) | def requestConnection(self, wanInterfaceId=1, timeout=1) | Request the connection to be established
:param int wanInterfaceId: the id of the WAN interface
:param float timeout: the timeout to wait for the action to be executed | 12.88423 | 14.452804 | 0.891469 |
'''use configparser to write a config object to filename
'''
with open(filename, mode) as filey:
config.write(filey)
return filename | def write_config(filename, config, mode="w") | use configparser to write a config object to filename | 5.985743 | 4.406259 | 1.358464 |
'''write a temporary file, in base directory with a particular extension.
Parameters
==========
folder: the base directory to write in.
prefix: the prefix to use
ext: the extension to use.
'''
tmp = next(tempfile._get_candidate_names())
return '%s/%s.%... | def generate_temporary_file(folder='/tmp', prefix='helpme', ext='json') | write a temporary file, in base directory with a particular extension.
Parameters
==========
folder: the base directory to write in.
prefix: the prefix to use
ext: the extension to use. | 6.890141 | 2.734618 | 2.519599 |
'''copy a file from a source to its destination.
'''
if os.path.exists(destination) and force is True:
os.remove(destination)
shutil.copyfile(source, destination)
return destination | def copyfile(source, destination, force=True) | copy a file from a source to its destination. | 3.156266 | 3.150574 | 1.001807 |
if self._full_inventory:
return self._full_inventory
resp, inventory = self.get('Inventory')
keys = ['host_id', 'hostname', 'ip_address', 'chassis',
'used_count', 'current_state', 'comment', 'distro',
'rel', 'centos_version', 'architecture',... | def full_inventory(self) | Returns a full inventory
Some additional work required to provide consistent and consumable
output.
Inventory output only contains values, no keys - Add the keys to
the output so that it can be consumed more easily. | 4.537182 | 4.434528 | 1.023149 |
if self.api_key is None:
return {}
if self._self_inventory:
return self._self_inventory
resp, self_inventory = self.get('Inventory?key=%s' % self.api_key)
real_self_inventory = dict()
for host in self_inventory:
real_self_inventory[... | def self_inventory(self) | Inventory output will only contain the server name and the session ID
when a key is provided. Provide the same format as with the full
inventory instead for consistency. | 3.54361 | 3.264574 | 1.085474 |
matching_hosts = {}
for host in inventory:
if inventory[host]['comment'] == ssid:
matching_hosts[host] = inventory[host]
return matching_hosts | def _ssid_inventory(self, inventory, ssid) | Filters an inventory to only return servers matching ssid | 3.803842 | 3.628506 | 1.048322 |
if all or self.api_key is None:
if ssid is not None:
return self._ssid_inventory(self.full_inventory, ssid)
else:
return self.full_inventory
else:
if ssid is not None:
return self._ssid_inventory(self.self_inven... | def inventory(self, all=False, ssid=None) | Returns a node inventory. If an API key is specified, only the nodes
provisioned by this key will be returned.
:return: { inventory } | 2.697411 | 2.748919 | 0.981262 |
if self.api_key is None:
raise exceptions.ApiKeyRequired
args = "key=%s" % self.api_key
if arch is not None:
args += "&arch=%s" % arch
if ver is not None:
args += "&ver=%s" % ver
if flavor is not None:
args += "&flavor=%s"... | def node_get(self, arch=None, ver=None, flavor=None, count=1,
retry_count=1, retry_interval=10) | Requests specified number of nodes with the provided parameters.
:param arch: Server architecture (ex: x86_64)
:param ver: CentOS version (ex: 7)
:param count: Number of servers (ex: 2)
:parma flavor: The flavor of machine to use (multi-arch only)
:param retry_count: Number of t... | 3.235247 | 3.107 | 1.041277 |
if self.api_key is None:
raise exceptions.ApiKeyRequired
if ssid is None:
raise exceptions.SsidRequired
# There is no body replied in this call so at least get the hosts for
# the specified ssid to return them.
requested_hosts = dict()
f... | def node_done(self, ssid=None) | Release the servers for the specified ssid.
The API doesn't provide any kind of output, try to be helpful by
providing the list of servers to be released.
:param ssid: ssid of the server pool
:return: [ requested_hosts ] | 5.960275 | 5.364677 | 1.111022 |
try:
hosts = RedisWrapper.connection_string_parser(
os.environ.get('REDIS_HOSTS'))
except RuntimeError as ex:
LOG.error(ex)
sys.exit(1)
for host in hosts:
LOG.info("connecting to %s:%s", host.host, host.port)
try:
if valid_state(state):
... | def update_redis(project: str, environment: str, feature: str, state: str) \
-> None | Update redis state for a feature flag.
:param project: LaunchDarkly project key.
:param environment: LaunchDarkly environment key.
:param feature: LaunchDarkly feature key.
:param state: State for a feature flag. | 4.132411 | 4.063998 | 1.016834 |
ld_api = LaunchDarklyApi(
os.environ.get('LD_API_KEY'),
project,
environment
)
if valid_state(state):
if state.lower() == 'off':
new_state = False
else:
new_state = True
ld_api.update_flag(new_state, feature)
else:
rai... | def update_ld_api(project: str, environment: str, feature: str, state: str) | Execute command against the LaunchDarkly API.
This command is generally not used directly, instead it is called as a
part of running the ``playback()`` function.
:param project: LaunchDarkly project key.
:param environment: LaunchDarkly environment key.
:param feature: LaunchDarkly feature key.
... | 3.879954 | 4.185173 | 0.927072 |
ld_api = LaunchDarklyApi(
os.environ.get('LD_API_KEY'),
project_key=project
)
config = ConfigGenerator()
envs = ld_api.get_environments(project)
config.generate_relay_config(envs) | def generate_relay_config(project) | Generate Relay Proxy Configuration.
Generate a ld-relay.conf file to quickly spin up a relay proxy.
Right now this is mostly used for integration testing.
:param project: LaunchDarkly project key | 5.037848 | 4.703691 | 1.071041 |
dr = DicomReader(dirpath=dirpath, *args, **kwargs)
info = dr.dicomdirectory.get_stats_of_series_in_dir()
return info | def dicomdir_info(dirpath, *args, **kwargs) | Get information about series in dir | 5.876901 | 5.280477 | 1.112949 |
# Second tries open files
# with dicom module.
retval = False
datapath = op.expanduser(datapath)
for f in os.listdir(datapath):
if f.endswith((".dcm", ".DCM")):
retval = True
return True
# @todo not working and I dont know why
try:
py... | def is_dicom_dir(datapath) | Check if in dir is one or more dicom file. We use two methods.
First is based on dcm extension detection. | 4.090712 | 3.660901 | 1.117406 |
import glob
filelist = []
if startpath is not None:
completedirpath = os.path.join(startpath, dirpath)
else:
completedirpath = dirpath
if os.path.exists(completedirpath):
logger.info('completedirpath = ' + completedirpath)
else:
logger.error('Wrong path:... | def files_in_dir(dirpath, wildcard="*", startpath=None) | Function generates list of files from specific dir
files_in_dir(dirpath, wildcard="*.*", startpath=None)
dirpath: required directory
wilcard: mask for files
startpath: start for relative path
Example
files_in_dir('medical/jatra-kiv','*.dcm', '~/data/') | 2.448822 | 2.505096 | 0.977536 |
slice_location = None
if hasattr(dcmdata, 'SliceLocation'):
# print(dcmdata.SliceLocation)
# print(type(dcmdata.SliceLocation))
try:
slice_location = float(dcmdata.SliceLocation)
except Exception as exc:
logger.info("It is not possible to use SliceLoc... | def get_slice_location(dcmdata, teil=None) | get location of the slice
:param dcmdata: dicom data structure
:param teil: filename. Used when slice location doesnt exist
:return: | 2.561765 | 2.51735 | 1.017643 |
if hasattr(obj, attr):
dct[attr] = getattr(obj, attr)
return dct | def attr_to_dict(obj, attr, dct) | Add attribute to dict if it exists.
:param dct:
:param obj: object
:param attr: object attribute name
:return: dict | 2.073246 | 2.801106 | 0.740153 |
series_info = dcmreader.dicomdirectory.get_stats_of_series_in_dir()
print(dcmreader.print_series_info(series_info))
import pandas as pd
df = pd.DataFrame(list(series_info.values()))
#select CT
df = df[df["Modality"].str.lower().str.contains("ct") == True]
# select just venous
df = ... | def get_series_number_by_guess_for_liver(dcmreader, counts, bins, qt_app=None) | Select the venous series from CT with around 200 images
:param dcmreader:
:param counts:
:param bins:
:param qt_app:
:return: | 3.817934 | 3.652174 | 1.045387 |
overlay = {}
dcmlist = self.files_in_serie
for i in range(len(dcmlist)):
onefile = dcmlist[i]
logger.info("reading '%s'" % onefile)
data = self._read_file(onefile)
if len(overlay) == 0:
# first there is created dictionary... | def get_overlay(self) | Function make 3D data from dicom file slices. There are usualy
more overlays in the data. | 4.350684 | 4.077709 | 1.066943 |
data3d = []
dcmlist = self.files_in_serie
# print('stsp ', start, stop, step)
# raw_max = None
# raw_min = None
# slope = None
# inter = None
# get shape 2d
# sometimes there is render in series
if len(self.files_in_serie) > 1:
... | def get_3Ddata(self, start=0, stop=None, step=1) | Function make 3D data from dicom file slices | 3.200329 | 3.150434 | 1.015838 |
dicomdir_filepath = os.path.join(self.dirpath, self.standard_dicomdir_filename)
if not os.path.exists(dicomdir_filepath):
self.create_standard_dicomdir()
return self.read_standard_dicomdir_info() | def get_standard_dicomdir_info(self) | Read DICOMDIR, crate if necessary.
:return: | 2.308311 | 2.309903 | 0.999311 |
# TODO implement simplier metadata function
# automatic test is prepared
files, files_with_info = self.get_sorted_series_files(series_number=series_number, return_files_with_info=True)
metadata = {
# 'voxelsize_mm': voxelsize_mm,
# 'Modality': data1.Moda... | def get_metadata_new(self, series_number) | Return series metadata.
Output condatin information about voxelsize_mm, series_number and modality.
If it is possible, the ImageComment, AcquisitionDate and few other dicom tags are also in output dict.
:param series_number:
:return: metadata dict with voxelsize_mm, SeriesNumber and othe... | 6.619979 | 5.325105 | 1.243164 |
# if dcmlist is None:
# dcmlist = self.files_in_serie
# number of slice where to extract metadata inforamtion
ifile = 0
if len(dcmlist) == 0:
return {}
logger.debug("Filename: " + dcmlist[ifile])
data1 = self._read_file(dcmlist[ifile])
... | def get_metaData(self, dcmlist, series_number) | Get metadata.
Voxel size is obtained from PixelSpacing and difference of
SliceLocation of two neighboorhoding slices (first have index ifile).
Files in are used. | 2.687826 | 2.59056 | 1.037546 |
if study_id is not None:
logger.error("study_id tag is not implemented yet")
return
import numpy as np
dcmdir = self.files_with_info
# get series number
# vytvoření slovníku, kde je klíčem číslo série a hodnotou jsou všechny
# informace z ... | def get_stats_of_series_in_dir(self, study_id=None) | Dicom series staticstics, input is dcmdir, not dirpath
Information is generated from dicomdir.pkl and first files of series | 5.436257 | 4.950476 | 1.098128 |
strinfo = ''
if len(series_info) > minimal_series_number:
for serie_number in series_info.keys():
strl = get_one_serie_info(series_info, serie_number)
strinfo = strinfo + strl + '\n'
# rint strl
return strinfo | def print_series_info(self, series_info, minimal_series_number=1) | Print series_info from dcmdirstats | 4.503564 | 4.167894 | 1.080537 |
createdcmdir = True
dicomdirfile = os.path.join(self.dirpath, self.dicomdir_filename)
ftype = 'pickle'
# if exist dicomdir file and is in correct version, use it
if os.path.exists(dicomdirfile):
try:
dcmdirplus = misc.obj_from_file(dicomdirfi... | def __prepare_info_from_dicomdir_file(self, writedicomdirfile=True) | Check if exists dicomdir file and load it or cerate it
dcmdir = get_dir(dirpath)
dcmdir: list with filenames, SeriesNumber and SliceLocation | 3.685982 | 3.298055 | 1.117623 |
# none_count = 0
countsd = {}
# dcmdirseries = []
for line in self.files_with_info:
if "SeriesNumber" in line:
sn = line['SeriesNumber']
else:
sn = None
if sn in countsd:
countsd[sn] += 1
... | def series_in_dir(self) | input is dcmdir, not dirpath | 4.284009 | 3.999198 | 1.071217 |
dcmdir = self.files_with_info[:]
# select sublist with SeriesNumber
if series_number is not None:
dcmdir = [
line for line in dcmdir if line['SeriesNumber'] == series_number
]
dcmdir = sort_list_of_dicts(dcmdir, keys=sort_keys)
l... | def get_sorted_series_files(self, startpath="", series_number=None, return_files_with_info=False,
sort_keys="SliceLocation", return_files=True, remove_doubled_slice_locations=True) | 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... | 2.749479 | 2.945516 | 0.933445 |
filelist = files_in_dir(self.dirpath)
files = []
metadataline = {}
for filepath in filelist:
head, teil = os.path.split(filepath)
dcmdata = None
if os.path.isdir(filepath):
logger.debug("Subdirectory found in series dir is ig... | def _create_dicomdir_info(self) | Function crates list of all files in dicom dir with all IDs | 4.938055 | 4.873106 | 1.013328 |
if skip_string_iter and isinstance(seq, (str, unicode, bytes, bytearray)):
return seq
if not seq:
return ''
try:
return next(iter(seq))
except TypeError:
# not hasattr __iter__/__getitem__
return default | def get_one(seq, default=None, skip_string_iter=True) | Return one item from seq or None(by default). | 4.169402 | 4.056377 | 1.027863 |
if not obj:
return []
elif isinstance(obj, (str, unicode, bytes, bytearray)):
return [obj]
elif hasattr(obj, '__iter__') or hasattr(obj, '__getitem__'):
return list(obj)
else:
return [obj] | def ensure_list(obj) | null obj -> return [];
str, unicode, bytes, bytearray -> [obj];
else -> list(obj) | 2.221526 | 1.829256 | 1.214442 |
attr, args = args[0], args[1:]
item = getattr(obj, attr)
if callable(item):
item = item(*args)
return [item] | def python_parser(self, obj, *args) | operate a python obj | 3.70334 | 3.510185 | 1.055027 |
def gen_match(matches, num):
for match in matches:
yield match.group(num)
scode = self.ensure_str(scode)
assert self._re.match(
'^@|^\$\d+', args[1]), ValueError('args1 should match ^@|^\$\d+')
arg1, arg2 = args[1][0], args[1][1:]
... | def re_parser(self, scode, *args) | 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 | 4.972076 | 4.018291 | 1.237361 |
allow_method = ('text', 'html', 'xml')
css_path, method = args
assert method in allow_method or method.startswith(
'@'), 'method allow: %s or @attr' % allow_method
result = self.ensure_list(
self._fromstring(scode,
parser=self... | def html_parser(self, scode, *args) | args[0] = cssselector
args[1] = text / html / xml / @attribute_name | 4.793275 | 4.400939 | 1.089148 |
allow_method = ('text', 'html', 'xml')
xpath_string, method = args
assert method in allow_method, 'method allow: %s' % allow_method
result = self.ensure_list(
self._fromstring(scode,
parser=self._xml_parser).xpath(xpath_string))
r... | def xml_parser(self, scode, *args) | args[0]: xpath
args[1]: text / html / xml | 5.741348 | 5.039433 | 1.139285 |
assert args_chain and isinstance(
args_chain, (list, tuple)
) and isinstance(args_chain[0], (list, tuple)), ValueError(
'args_chain type should be list of list, like: [["1-n", "html", "p", "html"], ["n-n", "html", "p", "text"]].'
)
for arg in args_chain:
... | def parse(self, scode, args_chain=None, join_with=None, default='') | 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']] | 3.962288 | 3.329838 | 1.189934 |
# Build the HTML tree
self.tree = self._build_tree(self.html_contents)
# Parse the CSS contents
self.stylesheet = self.parser.parse_stylesheet(self.css_contents)
# Get the cleaned CSS contents
self.cleaned_css = self._clean_css() | def parse(self) | Parses the CSS contents and returns the cleaned CSS as a string
:returns: The cleaned CSS
:rtype: str | 5.250178 | 4.408712 | 1.190864 |
self.cleaned_css = self.rel_to_abs_re.sub(
lambda match: "url('%s')" % urljoin(
base_url, match.group('path').strip('\'"')),
self.cleaned_css) | def rel_to_abs(self, base_url) | 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 | 4.560069 | 4.396896 | 1.037111 |
# Init the cleaned CSS rules and contents string
css_rules = []
# For every rule in the CSS
for rule in self.stylesheet.rules:
try:
# Clean the CSS rule
cleaned_rule = self._clean_rule(rule)
# Append the rule to matc... | def _clean_css(self) | Returns the cleaned CSS
:param stylesheet: The Stylesheet object to parse
:type stylesheet: tinycss.css21.Stylesheet | 4.87536 | 4.716651 | 1.033649 |
# Always match @ rules
if rule.at_keyword is not None:
return rule
# Clean selectors
cleaned_token_list = []
for token_list in split_on_comma(rule.selector):
# If the token list matches the tree
if self._token_list_matches_tree(toke... | def _clean_rule(self, rule) | 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... | 4.308772 | 3.919353 | 1.099358 |
try:
parsed_selector = cssselect.parse(
''.join(token.as_css() for token in token_list))[0]
return bool(
self.tree.xpath(
self.xpath_translator.selector_to_xpath(parsed_selector)))
except:
# On error, assum... | def _token_list_matches_tree(self, token_list) | 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 | 6.300368 | 5.412863 | 1.163962 |
if isinstance(rule, RuleSet):
# Simple CSS rule : a { color: red; }
return '%s{%s}' % (
self._selector_as_string(rule.selector),
self._declarations_as_string(rule.declarations))
elif isinstance(rule, ImportRule):
# @import rul... | def _rule_as_string(self, rule) | 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 | 2.276894 | 2.279291 | 0.998949 |
return ','.join(
''.join(token.as_css() for token in strip_whitespace(token_list))
for token_list in split_on_comma(selector)) | def _selector_as_string(self, selector) | 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 | 7.571695 | 6.482226 | 1.16807 |
return ''.join('%s:%s%s;' % (
d.name,
d.value.as_css(),
' !' + d.priority if d.priority else '') for d in declarations) | def _declarations_as_string(self, declarations) | 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 | 5.139142 | 4.63881 | 1.107858 |
'''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'),
... | def envars_to_markdown(envars, title = "Environment") | 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'),
(... | 4.312768 | 1.821149 | 2.368157 |
raise NotImplementedError | async def create_vm(self, preset_name: str, image: str, flavor: str, security_groups: List=None,
userdata: Dict=None, key_name: str=None, availability_zone: str=None,
subnets: List=None) -> Any | 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... | 1,039.556396 | 399.574524 | 2.601658 |
commands = Application.get_default_commands(self)
self.add(ConstantsCommand())
self.add(LoaderCommand())
self.add(PyStratumCommand())
self.add(WrapperCommand())
return commands | def get_default_commands(self) | Returns the default commands of this application.
:rtype: list[cleo.Command] | 8.824818 | 8.029061 | 1.09911 |
socket.setdefaulttimeout(timeout)
messages = []
if isinstance(service, str):
services = [service]
elif isinstance(service, list):
services = service
for service in services:
message = 'M-SEARCH * HTTP/1.1\r\nMX: 5\r\nMAN: "ssdp:dis... | def discover(service="ssdp:all", timeout=1, retries=2, ipAddress="239.255.255.250", port=1900) | 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... | 2.62934 | 2.564404 | 1.025322 |
if discoveryResponse is None:
return 0
serviceType = discoveryResponse.service
if serviceType.startswith("urn:dslforum-org:device"):
return 11
if serviceType.startswith("urn:dslforum-org:service"):
return 10
if serviceType.startswith... | def rateServiceTypeInResult(discoveryResponse) | 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... | 2.478223 | 2.395972 | 1.034329 |
'''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
'''
fd, tmp_file = t... | def download(self, url,
file_name,
headers=None,
show_progress=True) | 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 | 5.343961 | 3.548653 | 1.505913 |
'''
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... | def stream_response(self, response, stream_to=None) | 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 ... | 5.739965 | 2.781762 | 2.063428 |
if serviceType in self.__deviceServiceDefinitions.keys():
return self.__deviceServiceDefinitions[serviceType]["scpdURL"]
# check if definitions have been loaded, then dont return the default
if self.__deviceXMLInitialized:
raise ValueError("Device do not support... | def getSCDPURL(self, serviceType, default=None) | 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
... | 9.577024 | 10.326233 | 0.927446 |
if serviceType in self.__deviceServiceDefinitions.keys():
return self.__deviceServiceDefinitions[serviceType]["controlURL"]
# check if definitions have been loaded, then dont return the default
if self.__deviceXMLInitialized:
raise ValueError("Device do not supp... | def getControlURL(self, serviceType, default=None) | 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... | 9.657476 | 10.093364 | 0.956814 |
if serviceType in self.__deviceServiceDefinitions.keys():
return self.__deviceServiceDefinitions[serviceType]["eventSubURL"]
# check if definitions have been loaded, then dont return the default
if self.__deviceXMLInitialized:
raise ValueError("Device do not sup... | def getEventSubURL(self, serviceType, default=None) | 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 ... | 9.886679 | 10.184089 | 0.970797 |
errorStr = ""
tag = None
# noinspection PyBroadException
try:
# parse XML return
root = ET.fromstring(request.text.encode('utf-8'))
tag = root[0][0]
except:
# return an empty string as we can not parse the structure
... | def _extractErrorString(request) | 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 | 3.993793 | 3.946311 | 1.012032 |
# setup proxies
proxies = {}
if self.__httpsProxy:
proxies = {"https": self.__httpsProxy}
if self.__httpProxy:
proxies = {"http": self.__httpProxy}
# some devices response differently without a User-Agent
headers = {"User-Agent": "Mozil... | def loadDeviceDefinitions(self, urlOfXMLDefinition, timeout=3) | 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
... | 4.025838 | 3.543311 | 1.13618 |
# extract the base path of the given XML to make sure any relative URL later will be created correctly
url = urlparse(urlOfXMLDefinition)
baseURIPath = url.path.rpartition('/')[0] + "/"
try:
root = ET.fromstring(xml)
except Exception as e:
raise... | def _loadDeviceDefinitions(self, urlOfXMLDefinition, xml) | 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 | 6.491247 | 6.587801 | 0.985344 |
for child in element.getchildren():
tagName = child.tag.lower()
if tagName.endswith('servicelist'):
self._processServiceList(child,baseURIPath)
elif tagName.endswith('devicetype'):
if "deviceType" not in self.__deviceInformations.keys... | def _iterateToFindSCPDElements(self, element, baseURIPath) | 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 | 1.580829 | 1.60149 | 0.987099 |
# iterate through all children in serviceList XML tag
for service in serviceList.getchildren():
# has to be a service
if not service.tag.lower().endswith("service"):
raise ValueError("Non service tag in servicelist: " + service.tag)
service... | def _processServiceList(self, serviceList, baseURIPath) | 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 | 2.529176 | 2.498748 | 1.012177 |
if serviceType is not None:
self._loadSCPD(serviceType, float(timeout))
else:
self.__deviceSCPD = {}
for serviceType in self.__deviceServiceDefinitions.keys():
# remove any previous error
self.__deviceServiceDefinitions[servic... | def loadSCPD(self, serviceType=None, timeout=3, ignoreFailures=False) | 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... | 4.135567 | 3.911352 | 1.057324 |
if serviceType not in self.__deviceServiceDefinitions.keys():
raise ValueError("Can not load SCPD, no service type defined for: " + serviceType)
if "scpdURL" not in self.__deviceServiceDefinitions[serviceType].keys():
raise ValueError("No SCPD URL defined for: " + serv... | def _loadSCPD(self, serviceType, timeout) | Internal method to load the action definitions.
:param str serviceType: the service type to load
:param int timeout: the timeout for downloading | 3.594016 | 3.580826 | 1.003684 |
# go through all action elements in this list
for actionElement in actionListElement.getchildren():
action = {}
# go through all elements in this action
for inActionElement in actionElement.getchildren():
tagName = inActionElement.tag.lower... | def _parseSCPDActions(self, actionListElement, actions, variableParameterDict) | 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 | 2.914403 | 2.873957 | 1.014073 |
# iterate through all variables
for variableElement in variableListElement.getchildren():
variable = {}
# iterate through the variable definition
for inVariableElement in variableElement.getchildren():
tagName = inVariableElement.tag.lower(... | def _parseSCPDVariableTypes(self, variableListElement, variableTypes) | 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 | 2.43722 | 2.448017 | 0.995589 |
url = urlparse(urlOfXMLDefinition)
if not url.port:
if url.scheme.lower() == "https":
port = 443
else:
port = 80
else:
port = url.port
return Wifi(url.hostname, port, url.scheme) | def createFromURL(urlOfXMLDefinition) | Factory method to create a DeviceTR64 from an URL to the XML device definitions.
:param str urlOfXMLDefinition:
:return: the new object
:rtype: Wifi | 2.8229 | 2.956118 | 0.954935 |
namespace = Wifi.getServiceType("getWifiInfo") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return WifiBasicInfo(results) | def getWifiInfo(self, wifiInterfaceId=1, timeout=1) | 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 | 10.877333 | 8.164668 | 1.332244 |
namespace = Wifi.getServiceType("getTotalAssociations") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetTotalAssociations", timeout=timeout)
return int(results["NewTotalAssociations"]) | def getTotalAssociations(self, wifiInterfaceId=1, timeout=1) | 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:... | 8.531918 | 9.860313 | 0.865279 |
namespace = Wifi.getServiceType("getGenericAssociatedDeviceInfo") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetGenericAssociatedDeviceInfo", timeout=timeout,
NewAssociatedDeviceIndex=index)
... | def getGenericAssociatedDeviceInfo(self, index, wifiInterfaceId=1, timeout=1) | 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... | 9.993903 | 9.724235 | 1.027732 |
namespace = Wifi.getServiceType("getSpecificAssociatedDeviceInfo") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetSpecificAssociatedDeviceInfo", timeout=timeout,
NewAssociatedDeviceMACAddress=macAddre... | def getSpecificAssociatedDeviceInfo(self, macAddress, wifiInterfaceId=1, timeout=1) | 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... | 8.680721 | 8.544903 | 1.015895 |
namespace = Wifi.getServiceType("setEnable") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
if status:
setStatus = 1
else:
setStatus = 0
self.execute(uri, namespace, "SetEnable", timeout=timeout, NewEnable=setStatus) | def setEnable(self, status, wifiInterfaceId=1, timeout=1) | 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 | 7.862259 | 9.198207 | 0.85476 |
namespace = Wifi.getServiceType("setChannel") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
self.execute(uri, namespace, "SetChannel", timeout=timeout, NewChannel=channel) | def setChannel(self, channel, wifiInterfaceId=1, timeout=1) | 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 | 11.572684 | 13.125549 | 0.881691 |
namespace = Wifi.getServiceType("setChannel") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
self.execute(uri, namespace, "SetChannel", timeout=timeout, NewSSID=ssid) | def setSSID(self, ssid, wifiInterfaceId=1, timeout=1) | 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 | 14.535169 | 16.996334 | 0.855194 |
@wraps(func)
def wrap(self, *args, **kwargs):
if self.allowed_methods and isinstance(self.allowed_methods, list) and func.__name__ not in self.allowed_methods:
raise Exception("Method {} is disabled".format(func.__name__))
return func(self, *args, **kwarg... | def enabled_checker(func) | Access decorator which checks if a RPC method is enabled by our configuration | 2.339124 | 2.067629 | 1.131308 |
presets = await self.request.app.vmshepherd.preset_manager.list_presets()
return list(presets.keys()) | async def list_presets(self) | Listing presets
:return: (list of presets)
:rtype: list
Sample response:
``["preset1", "preset2"]`` | 8.798372 | 11.056532 | 0.795762 |
vmshepherd = self.request.app.vmshepherd
preset = vmshepherd.preset_manager.get_preset(preset)
result_vms = {vm.id: {'ip': vm.ip[0], 'state': vm.state.value} for vm in preset.vms}
return preset.count, result_vms | async def list_vms(self, preset) | 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... | 5.055919 | 5.111916 | 0.989046 |
vmshepherd = self.request.app.vmshepherd
preset = vmshepherd.preset_manager.get_preset(preset)
await preset.iaas.terminate_vm(vm_id)
return 'OK' | async def terminate_vm(self, preset, vm_id) | Discard vm in specified preset
:arg string preset: preset name
:arg int vm_id: Virtual Machine id
:return: 'OK'
Sample response:
``OK`` | 5.03227 | 5.633033 | 0.89335 |
vmshepherd = self.request.app.vmshepherd
preset = vmshepherd.preset_manager.get_preset(preset)
vm_info = await preset.iaas.get_vm(vm_id)
ret_info = copy.deepcopy(vm_info.metadata) if vm_info.metadata else {}
ret_info['tags'] = vm_info.tags
ret_info['iaas_shutdown... | async def get_vm_metadata(self, preset, vm_id) | 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' }`` | 4.038976 | 4.393338 | 0.919341 |
def separate_parentheses(s):
start = re_find(r'^\(*', s)
end = re_find(r'\)*$', s)
n = min(len(start), len(end))
if n:
return s[:n], s[n:-n], s[-n:]
else:
return '', s, ''
def link_repl(url, proto='http://'):
opening, url, closing = s... | def linkify(text, attrs={}) | Convert URL-like and email-like strings into links. | 3.457207 | 3.389057 | 1.020109 |
# Handle the common case first, saves 30-40% when s is an instance of
# six.text_type. This function gets called often in that setting.
if isinstance(s, six.text_type):
return s
if not isinstance(s, six.string_types):
if six.PY3:
if isinstance(s, bytes):
... | 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. | 1.563236 | 1.535344 | 1.018166 |
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")
for k, v in rf.items():
h5_rf.create_dataset("/_rec... | def save_dict_to_hdf5(dic, filename) | .... | 3.760128 | 3.767755 | 0.997976 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.