def build_sdist(source_dir, sdist_dir, config_settings=None):

if config_settings is None:<EOL><INDENT>config_settings = {}<EOL><DEDENT>requires, backend = _load_pyproject(source_dir)<EOL>hooks = Pep517HookCaller(source_dir, backend)<EOL>with BuildEnvironment() as env:<EOL><INDENT>env.pip_install(requires)<EOL>reqs = hooks.get_requires_for_build_sdist(config_settings)<EOL>env.pip_install(reqs)<EOL>return hooks.build_sdist(sdist_dir, config_settings)<EOL><DEDENT>

Build an sdist from a source directory using PEP 517 hooks.

    :param str source_dir: Source directory containing pyproject.toml
    :param str sdist_dir: Target directory to place sdist in
    :param dict config_settings: Options to pass to build backend

    This is a blocking function which will run pip in a subprocess to install
    build requirements.


if not reqs:<EOL><INDENT>return<EOL><DEDENT>log.info('<STR_LIT>', reqs)<EOL>check_call([<EOL>sys.executable, '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', self.path] + list(reqs))<EOL>

Install dependencies into this env by calling pip in a subprocess


filename = os.path.normcase(os.path.abspath(filename))<EOL>directory = os.path.normcase(os.path.abspath(directory))<EOL>return os.path.commonprefix([filename, directory]) == directory<EOL>

Test if a file is located within the given directory.


<EOL>backend_path = os.environ.get('<STR_LIT>')<EOL>if backend_path:<EOL><INDENT>extra_pathitems = backend_path.split(os.pathsep)<EOL>sys.path[:<NUM_LIT:0>] = extra_pathitems<EOL><DEDENT>ep = os.environ['<STR_LIT>']<EOL>mod_path, _, obj_path = ep.partition('<STR_LIT::>')<EOL>try:<EOL><INDENT>obj = import_module(mod_path)<EOL><DEDENT>except ImportError:<EOL><INDENT>raise BackendUnavailable(traceback.format_exc())<EOL><DEDENT>if backend_path:<EOL><INDENT>if not any(<EOL>contained_in(obj.__file__, path)<EOL>for path in extra_pathitems<EOL>):<EOL><INDENT>raise BackendInvalid("<STR_LIT>")<EOL><DEDENT><DEDENT>if obj_path:<EOL><INDENT>for path_part in obj_path.split('<STR_LIT:.>'):<EOL><INDENT>obj = getattr(obj, path_part)<EOL><DEDENT><DEDENT>return obj<EOL>


backend = _build_backend()<EOL>try:<EOL><INDENT>hook = backend.get_requires_for_build_wheel<EOL><DEDENT>except AttributeError:<EOL><INDENT>return []<EOL><DEDENT>else:<EOL><INDENT>return hook(config_settings)<EOL><DEDENT>

Invoke the optional get_requires_for_build_wheel hook

    Returns [] if the hook is not defined.


backend = _build_backend()<EOL>try:<EOL><INDENT>hook = backend.prepare_metadata_for_build_wheel<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _get_wheel_metadata_from_wheel(backend, metadata_directory,<EOL>config_settings)<EOL><DEDENT>else:<EOL><INDENT>return hook(metadata_directory, config_settings)<EOL><DEDENT>

Invoke optional prepare_metadata_for_build_wheel

    Implements a fallback by building a wheel if the hook isn't defined.


res = []<EOL>for path in whl_zip.namelist():<EOL><INDENT>m = re.match(r'<STR_LIT>', path)<EOL>if m:<EOL><INDENT>res.append(path)<EOL><DEDENT><DEDENT>if res:<EOL><INDENT>return res<EOL><DEDENT>raise Exception("<STR_LIT>")<EOL>

Identify the .dist-info folder inside a wheel ZipFile.


def _get_wheel_metadata_from_wheel(<EOL>backend, metadata_directory, config_settings):

from zipfile import ZipFile<EOL>whl_basename = backend.build_wheel(metadata_directory, config_settings)<EOL>with open(os.path.join(metadata_directory, WHEEL_BUILT_MARKER), '<STR_LIT:wb>'):<EOL><INDENT>pass  <EOL><DEDENT>whl_file = os.path.join(metadata_directory, whl_basename)<EOL>with ZipFile(whl_file) as zipf:<EOL><INDENT>dist_info = _dist_info_files(zipf)<EOL>zipf.extractall(path=metadata_directory, members=dist_info)<EOL><DEDENT>return dist_info[<NUM_LIT:0>].split('<STR_LIT:/>')[<NUM_LIT:0>]<EOL>

Build a wheel and extract the metadata from it.

    Fallback for when the build backend does not
    define the 'get_wheel_metadata' hook.


if not metadata_directory:<EOL><INDENT>return None<EOL><DEDENT>metadata_parent = os.path.dirname(metadata_directory)<EOL>if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)):<EOL><INDENT>return None<EOL><DEDENT>whl_files = glob(os.path.join(metadata_parent, '<STR_LIT>'))<EOL>if not whl_files:<EOL><INDENT>print('<STR_LIT>')<EOL>return None<EOL><DEDENT>if len(whl_files) > <NUM_LIT:1>:<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>return None<EOL><DEDENT>return whl_files[<NUM_LIT:0>]<EOL>

Check for a wheel already built during the get_wheel_metadata hook.


def build_wheel(wheel_directory, config_settings, metadata_directory=None):

prebuilt_whl = _find_already_built_wheel(metadata_directory)<EOL>if prebuilt_whl:<EOL><INDENT>shutil.copy2(prebuilt_whl, wheel_directory)<EOL>return os.path.basename(prebuilt_whl)<EOL><DEDENT>return _build_backend().build_wheel(wheel_directory, config_settings,<EOL>metadata_directory)<EOL>

Invoke the mandatory build_wheel hook.

    If a wheel was already built in the
    prepare_metadata_for_build_wheel fallback, this
    will copy it rather than rebuilding the wheel.


backend = _build_backend()<EOL>try:<EOL><INDENT>hook = backend.get_requires_for_build_sdist<EOL><DEDENT>except AttributeError:<EOL><INDENT>return []<EOL><DEDENT>else:<EOL><INDENT>return hook(config_settings)<EOL><DEDENT>


backend = _build_backend()<EOL>try:<EOL><INDENT>return backend.build_sdist(sdist_directory, config_settings)<EOL><DEDENT>except getattr(backend, '<STR_LIT>', _DummyException):<EOL><INDENT>raise GotUnsupportedOperation(traceback.format_exc())<EOL><DEDENT>


url = "<STR_LIT>" % position_id<EOL>return self.position_from_json(self._get_resource(url)["<STR_LIT>"])<EOL>

Returns position data.

http://dev.wheniwork.com/#get-existing-position


url = "<STR_LIT>"<EOL>data = self._get_resource(url)<EOL>positions = []<EOL>for entry in data['<STR_LIT>']:<EOL><INDENT>positions.append(self.position_from_json(entry))<EOL><DEDENT>return positions<EOL>

Returns a list of positions.

http://dev.wheniwork.com/#listing-positions


url = "<STR_LIT>"<EOL>body = params<EOL>data = self._post_resource(url, body)<EOL>return self.position_from_json(data["<STR_LIT>"])<EOL>

Creates a position

http://dev.wheniwork.com/#create-update-position


if "<STR_LIT:status>" in params:<EOL><INDENT>params['<STR_LIT:status>'] = '<STR_LIT:U+002C>'.join(map(str, params['<STR_LIT:status>']))<EOL><DEDENT>requests = []<EOL>users = {}<EOL>messages = {}<EOL>params['<STR_LIT>'] = <NUM_LIT:0><EOL>while True:<EOL><INDENT>param_list = [(k, params[k]) for k in sorted(params)]<EOL>url = "<STR_LIT>" % urlencode(param_list)<EOL>data = self._get_resource(url)<EOL>for entry in data["<STR_LIT>"]:<EOL><INDENT>user = Users.user_from_json(entry)<EOL>users[user.user_id] = user<EOL><DEDENT>for entry in data["<STR_LIT>"]:<EOL><INDENT>request = self.request_from_json(entry)<EOL>requests.append(request)<EOL><DEDENT>for entry in data["<STR_LIT>"]:<EOL><INDENT>message = Messages.message_from_json(entry)<EOL>if message.request_id not in messages:<EOL><INDENT>messages[message.request_id] = []<EOL><DEDENT>messages[message.request_id].append(message)<EOL><DEDENT>if not data['<STR_LIT>']:<EOL><INDENT>break<EOL><DEDENT>params['<STR_LIT>'] += <NUM_LIT:1><EOL><DEDENT>for request in requests:<EOL><INDENT>request.user = users.get(request.user_id, None)<EOL>request.messages = messages.get(request.request_id, [])<EOL><DEDENT>return requests<EOL>

List requests

http://dev.wheniwork.com/#listing-requests


url = "<STR_LIT>" % message_id<EOL>return self.message_from_json(self._get_resource(url)["<STR_LIT:message>"])<EOL>

Get Existing Message

http://dev.wheniwork.com/#get-existing-message


param_list = [(k, params[k]) for k in sorted(params)]<EOL>url = "<STR_LIT>" % urlencode(param_list)<EOL>data = self._get_resource(url)<EOL>messages = []<EOL>for entry in data["<STR_LIT>"]:<EOL><INDENT>messages.append(self.message_from_json(entry))<EOL><DEDENT>return messages<EOL>

List messages

http://dev.wheniwork.com/#listing-messages


url = "<STR_LIT>"<EOL>body = params<EOL>data = self._post_resource(url, body)<EOL>return self.message_from_json(data["<STR_LIT:message>"])<EOL>

Creates a message

http://dev.wheniwork.com/#create/update-message


url = "<STR_LIT>" % message.message_id<EOL>data = self._put_resource(url, message.json_data())<EOL>return self.message_from_json(data)<EOL>

Modify an existing message.

http://dev.wheniwork.com/#create/update-message


url = "<STR_LIT>" % urlencode([('<STR_LIT>', "<STR_LIT:U+002C>".join(messages))])<EOL>data = self._delete_resource(url)<EOL>return data<EOL>

Delete existing messages.

http://dev.wheniwork.com/#delete-existing-message


url = "<STR_LIT>" % location_id<EOL>return self.location_from_json(self._get_resource(url)["<STR_LIT:location>"])<EOL>

Returns location data.

http://dev.wheniwork.com/#get-existing-location


url = "<STR_LIT>"<EOL>data = self._get_resource(url)<EOL>locations = []<EOL>for entry in data['<STR_LIT>']:<EOL><INDENT>locations.append(self.location_from_json(entry))<EOL><DEDENT>return locations<EOL>

Returns a list of locations.

http://dev.wheniwork.com/#listing-locations


url = "<STR_LIT>" % site_id<EOL>return self.site_from_json(self._get_resource(url)["<STR_LIT>"])<EOL>

Returns site data.

http://dev.wheniwork.com/#get-existing-site


url = "<STR_LIT>"<EOL>data = self._get_resource(url)<EOL>sites = []<EOL>for entry in data['<STR_LIT>']:<EOL><INDENT>sites.append(self.site_from_json(entry))<EOL><DEDENT>return sites<EOL>

Returns a list of sites.

http://dev.wheniwork.com/#listing-sites


url = "<STR_LIT>"<EOL>body = params<EOL>data = self._post_resource(url, body)<EOL>return self.site_from_json(data["<STR_LIT>"])<EOL>

Creates a site

http://dev.wheniwork.com/#create-update-site


def _get_resource(self, url, data_key=None):

headers = {"<STR_LIT>": "<STR_LIT:application/json>"}<EOL>if self.token:<EOL><INDENT>headers["<STR_LIT>"] = "<STR_LIT:%s>" % self.token<EOL><DEDENT>response = WhenIWork_DAO().getURL(url, headers)<EOL>if response.status != <NUM_LIT:200>:<EOL><INDENT>raise DataFailureException(url, response.status, response.data)<EOL><DEDENT>return json.loads(response.data)<EOL>

When I Work GET method. Return representation of the requested
resource.


headers = {"<STR_LIT:Content-Type>": "<STR_LIT:application/json>",<EOL>"<STR_LIT>": "<STR_LIT:application/json>"}<EOL>if self.token:<EOL><INDENT>headers["<STR_LIT>"] = "<STR_LIT:%s>" % self.token<EOL><DEDENT>response = WhenIWork_DAO().putURL(url, headers, json.dumps(body))<EOL>if not (response.status == <NUM_LIT:200> or response.status == <NUM_LIT> or<EOL>response.status == <NUM_LIT>):<EOL><INDENT>raise DataFailureException(url, response.status, response.data)<EOL><DEDENT>return json.loads(response.data)<EOL>


headers = {"<STR_LIT:Content-Type>": "<STR_LIT:application/json>",<EOL>"<STR_LIT>": "<STR_LIT:application/json>"}<EOL>if self.token:<EOL><INDENT>headers["<STR_LIT>"] = "<STR_LIT:%s>" % self.token<EOL><DEDENT>response = WhenIWork_DAO().postURL(url, headers, json.dumps(body))<EOL>if not (response.status == <NUM_LIT:200> or response.status == <NUM_LIT>):<EOL><INDENT>raise DataFailureException(url, response.status, response.data)<EOL><DEDENT>return json.loads(response.data)<EOL>


headers = {"<STR_LIT:Content-Type>": "<STR_LIT:application/json>",<EOL>"<STR_LIT>": "<STR_LIT:application/json>"}<EOL>if self.token:<EOL><INDENT>headers["<STR_LIT>"] = "<STR_LIT:%s>" % self.token<EOL><DEDENT>response = WhenIWork_DAO().deleteURL(url, headers)<EOL>if not (response.status == <NUM_LIT:200> or response.status == <NUM_LIT> or<EOL>response.status == <NUM_LIT>):<EOL><INDENT>raise DataFailureException(url, response.status, response.data)<EOL><DEDENT>return json.loads(response.data)<EOL>


url = "<STR_LIT>"<EOL>return self.account_from_json(self._get_resource(url)["<STR_LIT>"])<EOL>

Get Existing Account

http://dev.wheniwork.com/#get-existing-account


url = "<STR_LIT>" % user_id<EOL>return self.user_from_json(self._get_resource(url)["<STR_LIT:user>"])<EOL>

Returns user profile data.

http://dev.wheniwork.com/#get-existing-user


param_list = [(k, params[k]) for k in sorted(params)]<EOL>url = "<STR_LIT>" % urlencode(param_list)<EOL>data = self._get_resource(url)<EOL>users = []<EOL>for entry in data["<STR_LIT>"]:<EOL><INDENT>users.append(self.user_from_json(entry))<EOL><DEDENT>return users<EOL>

Returns a list of users.

http://dev.wheniwork.com/#listing-users


param_list = [(k, params[k]) for k in sorted(params)]<EOL>url = "<STR_LIT>" % urlencode(param_list)<EOL>data = self._get_resource(url)<EOL>shifts = []<EOL>locations = {}<EOL>sites = {}<EOL>positions = {}<EOL>users = {}<EOL>for entry in data.get("<STR_LIT>", []):<EOL><INDENT>location = Locations.location_from_json(entry)<EOL>locations[location.location_id] = location<EOL><DEDENT>for entry in data.get("<STR_LIT>", []):<EOL><INDENT>site = Sites.site_from_json(entry)<EOL>sites[site.site_id] = site<EOL><DEDENT>for entry in data.get("<STR_LIT>", []):<EOL><INDENT>position = Positions.position_from_json(entry)<EOL>positions[position.position_id] = position<EOL><DEDENT>for entry in data.get("<STR_LIT>", []):<EOL><INDENT>user = Users.user_from_json(entry)<EOL>users[user.user_id] = user<EOL><DEDENT>for entry in data["<STR_LIT>"]:<EOL><INDENT>shift = self.shift_from_json(entry)<EOL>shifts.append(shift)<EOL><DEDENT>for shift in shifts:<EOL><INDENT>shift.location = locations.get(shift.location_id, None)<EOL>shift.site = sites.get(shift.site_id, None)<EOL>shift.position = positions.get(shift.position_id, None)<EOL>shift.user = users.get(shift.user_id, None)<EOL><DEDENT>return shifts<EOL>

List shifts

http://dev.wheniwork.com/#listing-shifts


url = "<STR_LIT>"<EOL>body = params<EOL>data = self._post_resource(url, body)<EOL>shift = self.shift_from_json(data["<STR_LIT>"])<EOL>return shift<EOL>

Creates a shift

http://dev.wheniwork.com/#create/update-shift


url = "<STR_LIT>" % urlencode(<EOL>{'<STR_LIT>': "<STR_LIT:U+002C>".join(str(s) for s in shifts)})<EOL>data = self._delete_resource(url)<EOL>return data<EOL>

Delete existing shifts.

http://dev.wheniwork.com/#delete-shift


self._is_scanning = False<EOL>self._powered_on = threading.Event()<EOL>self._powered_off = threading.Event()<EOL>

Create an instance of the bluetooth adapter from the provided bluez
        DBus object.


logger.debug('<STR_LIT>'.format(state))<EOL>if state == <NUM_LIT:5>:<EOL><INDENT>self._powered_off.clear()<EOL>self._powered_on.set()<EOL><DEDENT>elif state == <NUM_LIT:4>:<EOL><INDENT>self._powered_on.clear()<EOL>self._powered_off.set()<EOL><DEDENT>


<EOL>return "<STR_LIT>"<EOL>

Return the name of this BLE network adapter.


get_provider()._central_manager.scanForPeripheralsWithServices_options_(None, None)<EOL>self._is_scanning = True<EOL>


get_provider()._central_manager.stopScan()<EOL>self._is_scanning = False<EOL>


return self._is_scanning<EOL>

Return True if the BLE adapter is scanning for devices, otherwise
        return False.


<EOL>self._powered_on.clear()<EOL>IOBluetoothPreferenceSetControllerPowerState(<NUM_LIT:1>)<EOL>if not self._powered_on.wait(timeout_sec):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>


<EOL>self._powered_off.clear()<EOL>IOBluetoothPreferenceSetControllerPowerState(<NUM_LIT:0>)<EOL>if not self._powered_off.wait(timeout_sec):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>


return IOBluetoothPreferenceGetControllerPowerState() == <NUM_LIT:1><EOL>

Return True if the BLE adapter is powered up, otherwise return False.


logger.debug('<STR_LIT>')<EOL>get_provider()._adapter._state_changed(manager.state())<EOL>

Called when the BLE adapter is powered on and ready to scan/connect
        to devices.


def centralManager_didDiscoverPeripheral_advertisementData_RSSI_(self, manager, peripheral, data, rssi):

logger.debug('<STR_LIT>')<EOL>device = device_list().get(peripheral)<EOL>if device is None:<EOL><INDENT>device = device_list().add(peripheral, CoreBluetoothDevice(peripheral))<EOL><DEDENT>device._update_advertised(data)<EOL>

Called when the BLE adapter found a device while scanning, or has
        new advertisement data for a device.


def centralManager_didConnectPeripheral_(self, manager, peripheral):

logger.debug('<STR_LIT>')<EOL>peripheral.setDelegate_(self)<EOL>peripheral.discoverServices_(None)<EOL>device = device_list().get(peripheral)<EOL>if device is not None:<EOL><INDENT>device._set_connected()<EOL><DEDENT>


def centralManager_didDisconnectPeripheral_error_(self, manager, peripheral, error):

logger.debug('<STR_LIT>')<EOL>device = device_list().get(peripheral)<EOL>if device is not None:<EOL><INDENT>device._set_disconnected()<EOL>device_list().remove(peripheral)<EOL><DEDENT>


def peripheral_didDiscoverServices_(self, peripheral, services):

logger.debug('<STR_LIT>')<EOL>for service in peripheral.services():<EOL><INDENT>if service_list().get(service) is None:<EOL><INDENT>service_list().add(service, CoreBluetoothGattService(service))<EOL><DEDENT>peripheral.discoverCharacteristics_forService_(None, service)<EOL><DEDENT>

Called when services are discovered for a device.


def peripheral_didDiscoverCharacteristicsForService_error_(self, peripheral, service, error):

logger.debug('<STR_LIT>')<EOL>if error is not None:<EOL><INDENT>return<EOL><DEDENT>for char in service.characteristics():<EOL><INDENT>if characteristic_list().get(char) is None:<EOL><INDENT>characteristic_list().add(char, CoreBluetoothGattCharacteristic(char))<EOL><DEDENT>peripheral.discoverDescriptorsForCharacteristic_(char)<EOL><DEDENT>device = device_list().get(peripheral)<EOL>if device is not None:<EOL><INDENT>device._characteristics_discovered(service)<EOL><DEDENT>

Called when characteristics are discovered for a service.


def peripheral_didDiscoverDescriptorsForCharacteristic_error_(self, peripheral, characteristic, error):

logger.debug('<STR_LIT>')<EOL>if error is not None:<EOL><INDENT>return<EOL><DEDENT>for desc in characteristic.descriptors():<EOL><INDENT>if descriptor_list().get(desc) is None:<EOL><INDENT>descriptor_list().add(desc, CoreBluetoothGattDescriptor(desc))<EOL><DEDENT><DEDENT>


def peripheral_didUpdateValueForCharacteristic_error_(self, peripheral, characteristic, error):

logger.debug('<STR_LIT>')<EOL>if error is not None:<EOL><INDENT>return<EOL><DEDENT>device = device_list().get(peripheral)<EOL>if device is not None:<EOL><INDENT>device._characteristic_changed(characteristic)<EOL><DEDENT>

Called when characteristic value was read or updated.


def peripheral_didUpdateValueForDescriptor_error_(self, peripheral, descriptor, error):

logger.debug('<STR_LIT>')<EOL>if error is not None:<EOL><INDENT>return<EOL><DEDENT>device = device_list().get(peripheral)<EOL>if device is not None:<EOL><INDENT>device._descriptor_changed(descriptor)<EOL><DEDENT>

Called when descriptor value was read or updated.


def peripheral_didReadRSSI_error_(self, peripheral, rssi, error):

logger.debug('<STR_LIT>')<EOL>if error is not None:<EOL><INDENT>return<EOL><DEDENT>device = device_list().get(peripheral)<EOL>if device is not None:<EOL><INDENT>device._rssi_changed(rssi)<EOL><DEDENT>

Called when a new RSSI value for the peripheral is available.


<EOL>self._central_manager = CBCentralManager.alloc()<EOL>self._central_manager.initWithDelegate_queue_options_(self._central_delegate,<EOL>None, None)<EOL>

Initialize the BLE provider.  Must be called once before any other
        calls are made to the provider.


Start the OS's main loop to process asyncronous BLE events and then
        run the specified target function in a background thread.  Target
        function should be a function that takes no parameters and optionally
        return an integer response code.  When the target function stops
        executing or returns with value then the main loop will be stopped and
        the program will exit with the returned code.

        Note that an OS main loop is required to process asyncronous BLE events
        and this function is provided as a convenience for writing simple tools
        and scripts that don't need to be full-blown GUI applications.  If you
        are writing a GUI application that has a main loop (a GTK glib main loop
        on Linux, or a Cocoa main loop on OSX) then you don't need to call this
        function.


try:<EOL><INDENT>return_code = target()<EOL>if return_code is None:<EOL><INDENT>return_code = <NUM_LIT:0><EOL><DEDENT>AppHelper.callAfter(lambda: sys.exit(return_code))<EOL><DEDENT>except Exception as ex:<EOL><INDENT>AppHelper.callAfter(self._raise_error, sys.exc_info())<EOL><DEDENT>

Main entry point for the thread that will run user's code.


<EOL>raise_(exec_info[<NUM_LIT:1>], None, exec_info[<NUM_LIT:2>])<EOL>

Raise an exception from the provided exception info.  Used to cause
        the main thread to stop with an error.


return [self._adapter]<EOL>

Return a list of BLE adapter objects connected to the system.


return self._devices.list()<EOL>

Return a list of BLE devices known to the system.


<EOL>if self._adapter.is_powered:<EOL><INDENT>self._adapter.power_off()<EOL><DEDENT>with open(os.devnull, '<STR_LIT:w>') as devnull:<EOL><INDENT>subprocess.call('<STR_LIT>',<EOL>shell=True, stdout=devnull, stderr=subprocess.STDOUT)<EOL>subprocess.call('<STR_LIT>',<EOL>shell=True, stdout=devnull, stderr=subprocess.STDOUT)<EOL><DEDENT>

Clear the internal bluetooth device cache.  This is useful if a device
        changes its state like name and it can't be detected with the new state
        anymore.  WARNING: This will delete some files underneath the running user's
        ~/Library/Preferences/ folder!

        See this Stackoverflow question for information on what the function does:
        http://stackoverflow.com/questions/20553957/how-can-i-clear-the-corebluetooth-cache-on-macos


<EOL>cbuuids = map(uuid_to_cbuuid, service_uuids)<EOL>for device in self._central_manager.retrieveConnectedPeripheralsWithServices_(cbuuids):<EOL><INDENT>self._central_manager.cancelPeripheralConnection_(device)<EOL><DEDENT>

Disconnect any connected devices that have any of the specified
        service UUIDs.


data = cbuuid.data().bytes()<EOL>template = '<STR_LIT>' if len(data) <= <NUM_LIT:4> else '<STR_LIT>'<EOL>value = template.format(hexlify(data.tobytes()[:<NUM_LIT:16>]).decode('<STR_LIT:ascii>'))<EOL>return uuid.UUID(hex=value)<EOL>

Convert Objective-C CBUUID type to native Python UUID type.


return CBUUID.UUIDWithString_(str(uuid))<EOL>

Convert native Python UUID type to Objective-C CBUUID type.


return uuid.UUID(nsuuid.UUIDString())<EOL>

Convert Objective-C NSUUID type to native Python UUID type.


with self._lock:<EOL><INDENT>return self._metadata.values()<EOL><DEDENT>


with self._lock:<EOL><INDENT>return self._metadata.get(cbobject, None)<EOL><DEDENT>

Retrieve the metadata associated with the specified CoreBluetooth
        object.


try:<EOL><INDENT>with self._lock:<EOL><INDENT>return [self._metadata[x] for x in cbobjects]<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>

Retrieve a list of metadata objects associated with the specified
        list of CoreBluetooth objects.  If an object cannot be found then an
        exception is thrown.


with self._lock:<EOL><INDENT>if cbobject not in self._metadata:<EOL><INDENT>self._metadata[cbobject] = metadata<EOL><DEDENT>return self._metadata[cbobject]<EOL><DEDENT>

Add the specified CoreBluetooth item with the associated metadata if
        it doesn't already exist.  Returns the newly created or preexisting
        metadata item.


with self._lock:<EOL><INDENT>if cbobject in self._metadata:<EOL><INDENT>del self._metadata[cbobject]<EOL><DEDENT><DEDENT>

Remove any metadata associated with the provided CoreBluetooth object.


self._service = service<EOL>

Create an instance of the GATT service from the provided CoreBluetooth
        CBService instance.


return cbuuid_to_uuid(self._service.UUID())<EOL>


<EOL>return characteristic_list().get_all(self._service.characteristics())<EOL>

Return list of GATT characteristics that have been discovered for this
        service.


self._characteristic = characteristic<EOL>self._value_read = threading.Event()<EOL>

Create an instance of the GATT characteristic from the provided
        CoreBluetooth CBCharacteristic instance.


return device_list().get(self._characteristic.service().peripheral())<EOL>

Return the parent CoreBluetoothDevice object that owns this
        characteristic.


return cbuuid_to_uuid(self._characteristic.UUID())<EOL>

Return the UUID of this GATT characteristic.


def write_value(self, value, write_type=<NUM_LIT:0>):

data = NSData.dataWithBytes_length_(value, len(value))<EOL>self._device._peripheral.writeValue_forCharacteristic_type_(data,<EOL>self._characteristic,<EOL>write_type)<EOL>

Write the specified value to this characteristic.


<EOL>self._device._notify_characteristic(self._characteristic, on_change)<EOL>self._device._peripheral.setNotifyValue_forCharacteristic_(True,<EOL>self._characteristic)<EOL>

Enable notification of changes for this characteristic on the
        specified on_change callback.  on_change should be a function that takes
        one parameter which is the value (as a string of bytes) of the changed
        characteristic value.


self._device._peripheral.setNotifyValue_forCharacteristic_(False,<EOL>self._characteristic)<EOL>

Disable notification of changes for this characteristic.


<EOL>return descriptor_list().get_all(self._characteristic.descriptors())<EOL>

Return list of GATT descriptors that have been discovered for this
        characteristic.


self._descriptor = descriptor<EOL>self._value_read = threading.Event()<EOL>

Create an instance of the GATT descriptor from the provided
        CoreBluetooth CBDescriptor value.


return device_list().get(self._descriptor.characteristic().service().peripheral())<EOL>


return cbuuid_to_uuid(self._descriptor.UUID())<EOL>

Return the UUID of this GATT descriptor.


pass<EOL>self._value_read.clear()<EOL>self._device._peripheral.readValueForDescriptor(self._descriptor)<EOL>if not self._value_read.wait(timeout_sec):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>return self._value<EOL>


self._peripheral = peripheral<EOL>self._advertised = []<EOL>self._discovered_services = set()<EOL>self._char_on_changed = {}<EOL>self._rssi = None<EOL>self._connected = threading.Event()<EOL>self._disconnected = threading.Event()<EOL>self._discovered = threading.Event()<EOL>self._rssi_read = threading.Event()<EOL>

Create an instance of the CoreBluetooth device from the provided
        CBPeripheral instance.


self._central_manager.connectPeripheral_options_(self._peripheral, None)<EOL>if not self._connected.wait(timeout_sec):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>

Connect to the device.  If not connected within the specified timeout
        then an exception is thrown.


<EOL>for service in self.list_services():<EOL><INDENT>for char in service.list_characteristics():<EOL><INDENT>for desc in char.list_descriptors():<EOL><INDENT>descriptor_list().remove(desc)<EOL><DEDENT>characteristic_list().remove(char)<EOL><DEDENT>service_list().remove(service)<EOL><DEDENT>self._central_manager.cancelPeripheralConnection_(self._peripheral)<EOL>if not self._disconnected.wait(timeout_sec):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>

Disconnect from the device.  If not disconnected within the specified
        timeout then an exception is thrown.


self._disconnected.clear()<EOL>self._connected.set()<EOL>


self._connected.clear()<EOL>self._disconnected.set()<EOL>


<EOL>if '<STR_LIT>' in advertised:<EOL><INDENT>self._advertised = self._advertised + map(cbuuid_to_uuid, advertised['<STR_LIT>'])<EOL><DEDENT>

Called when advertisement data is received.


<EOL>self._discovered_services.add(service)<EOL>if self._discovered_services >= set(self._peripheral.services()):<EOL><INDENT>self._discovered.set()<EOL><DEDENT>

Called when GATT characteristics have been discovered.


def _notify_characteristic(self, characteristic, on_change):

<EOL>self._char_on_changed[characteristic] = on_change<EOL>

Call the specified on_change callback when this characteristic
        changes.


<EOL>on_changed = self._char_on_changed.get(characteristic, None)<EOL>if on_changed is not None:<EOL><INDENT>on_changed(characteristic.value().bytes().tobytes())<EOL><DEDENT>char = characteristic_list().get(characteristic)<EOL>if char is not None:<EOL><INDENT>char._value_read.set()<EOL><DEDENT>

Called when the specified characteristic has changed its value.


<EOL>desc = descriptor_list().get(descriptor)<EOL>if desc is not None:<EOL><INDENT>desc._value_read.set()<EOL><DEDENT>

Called when the specified descriptor has changed its value.


self._rssi = rssi<EOL>self._rssi_read.set()<EOL>

Called when the RSSI signal strength has been read.


return service_list().get_all(self._peripheral.services())<EOL>

Return a list of GattService objects that have been discovered for
        this device.


def discover(self, service_uuids, char_uuids, timeout_sec=TIMEOUT_SEC):

<EOL>if not self._discovered.wait(timeout_sec):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>

Wait up to timeout_sec for the specified services and characteristics
        to be discovered on the device.  If the timeout is exceeded without
        discovering the services and characteristics then an exception is thrown.


return self._advertised<EOL>

Return a list of UUIDs for services that are advertised by this
        device.


return nsuuid_to_uuid(self._peripheral.identifier())<EOL>

Return a unique identifier for this device.  On supported platforms
        this will be the MAC address of the device, however on unsupported
        platforms (Mac OSX) it will be a unique ID like a UUID.


return self._peripheral.name()<EOL>


return self._connected.is_set()<EOL>

Return True if the device is connected to the system, otherwise False.


<EOL>self._rssi_read.clear()<EOL>self._peripheral.readRSSI()<EOL>if not self._rssi_read.wait(timeout_sec):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>return self._rssi<EOL>

Return the RSSI signal strength in decibels.


raise NotImplementedError<EOL>

Return the name of this BLE network adapter.


raise NotImplementedError<EOL>

Start scanning for BLE devices with this adapter.


raise NotImplementedError<EOL>

Stop scanning for BLE devices with this adapter.


raise NotImplementedError<EOL>

Return True if the BLE adapter is scanning for devices, otherwise
        return False.


raise NotImplementedError<EOL>


raise NotImplementedError<EOL>

Return True if the BLE adapter is powered up, otherwise return False.


raise NotImplementedError<EOL>

Initialize the BLE provider.  Must be called once before any other
        calls are made to the provider.


raise NotImplementedError<EOL>

Start the OS's main loop to process asyncronous BLE events and then
        run the specified target function in a background thread.  Target
        function should be a function that takes no parameters and optionally
        return an integer response code.  When the target function stops
        executing or returns with value then the main loop will be stopped and
        the program will exit with the returned code.

        Note that an OS main loop is required to process asyncronous BLE events
        and this function is provided as a convenience for writing simple tools
        and scripts that don't need to be full-blown GUI applications.  If you
        are writing a GUI application that has a main loop (a GTK glib main loop
        on Linux, or a Cocoa main loop on OSX) then you don't need to call this
        function.


raise NotImplementedError<EOL>

Return a list of BLE adapter objects connected to the system.


raise NotImplementedError<EOL>

Return a list of BLE devices known to the system.


raise NotImplementedError<EOL>

Clear any internally cached BLE device data.  Necessary in some cases
        to prevent issues with stale device data getting cached by the OS.


raise NotImplementedError<EOL>

Disconnect any connected devices that have any of the specified
        service UUIDs.


adapters = self.list_adapters()<EOL>if len(adapters) > <NUM_LIT:0>:<EOL><INDENT>return adapters[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Return the first BLE adapter found, or None if no adapters are
        available.


def find_devices(self, service_uuids=[], name=None):

<EOL>expected = set(service_uuids)<EOL>devices = self.list_devices()<EOL>found = []<EOL>for device in devices:<EOL><INDENT>if name is not None:<EOL><INDENT>if device.name == name:<EOL><INDENT>found.append(device)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>actual = set(device.advertised)<EOL>if actual >= expected:<EOL><INDENT>found.append(device)<EOL><DEDENT><DEDENT><DEDENT>return found<EOL>

Return devices that advertise the specified service UUIDs and/or have
        the specified name.  Service_uuids should be a list of Python uuid.UUID
        objects and is optional.  Name is a string device name to look for and is
        also optional.  Will not block, instead it returns immediately with a
        list of found devices (which might be empty).


def find_device(self, service_uuids=[], name=None, timeout_sec=TIMEOUT_SEC):

start = time.time()<EOL>while True:<EOL><INDENT>found = self.find_devices(service_uuids, name)<EOL>if len(found) > <NUM_LIT:0>:<EOL><INDENT>return found[<NUM_LIT:0>]<EOL><DEDENT>if time.time()-start >= timeout_sec:<EOL><INDENT>return None<EOL><DEDENT>time.sleep(<NUM_LIT:1>)<EOL><DEDENT>

Return the first device that advertises the specified service UUIDs or
        has the specified name. Will wait up to timeout_sec seconds for the device
        to be found, and if the timeout is zero then it will not wait at all and
        immediately return a result.  When no device is found a value of None is
        returned.


raise NotImplementedError<EOL>

Return list of GATT characteristics that have been discovered for this
        service.


for char in self.list_characteristics():<EOL><INDENT>if char.uuid == uuid:<EOL><INDENT>return char<EOL><DEDENT><DEDENT>return None<EOL>

Return the first child characteristic found that has the specified
        UUID.  Will return None if no characteristic that matches is found.


raise NotImplementedError<EOL>

Return the UUID of this GATT characteristic.


raise NotImplementedError<EOL>

Write the specified value to this characteristic.


raise NotImplementedError<EOL>

Enable notification of changes for this characteristic on the
        specified on_change callback.  on_change should be a function that takes
        one parameter which is the value (as a string of bytes) of the changed
        characteristic value.


raise NotImplementedError<EOL>

Disable notification of changes for this characteristic.


raise NotImplementedError<EOL>

Return list of GATT descriptors that have been discovered for this
        characteristic.


for desc in self.list_descriptors():<EOL><INDENT>if desc.uuid == uuid:<EOL><INDENT>return desc<EOL><DEDENT><DEDENT>return None<EOL>

Return the first child descriptor found that has the specified
        UUID.  Will return None if no descriptor that matches is found.


raise NotImplementedError<EOL>

Return the UUID of this GATT descriptor.


raise NotImplementedError<EOL>


raise NotImplementedError<EOL>

Return a list of GattService objects that have been discovered for
        this device.


@abc.abstractproperty<EOL><INDENT>def discover(self, service_uuids, char_uuids, timeout_sec=<NUM_LIT:30>):<DEDENT>

raise NotImplementedError<EOL>

Wait up to timeout_sec for the specified services and characteristics
        to be discovered on the device.  If the timeout is exceeded without
        discovering the services and characteristics then an exception is thrown.


raise NotImplementedError<EOL>

Return a list of UUIDs for services that are advertised by this
        device.


raise NotImplementedError<EOL>

Return a unique identifier for this device.  On supported platforms
        this will be the MAC address of the device, however on unsupported
        platforms (Mac OSX) it will be a unique ID like a UUID.


raise NotImplementedError<EOL>

Return True if the device is connected to the system, otherwise False.


raise NotImplementedError<EOL>

Return the RSSI signal strength in decibels.


for service in self.list_services():<EOL><INDENT>if service.uuid == uuid:<EOL><INDENT>return service<EOL><DEDENT><DEDENT>return None<EOL>

Return the first child service found that has the specified
        UUID.  Will return None if no service that matches is found.


return self.id == other.id<EOL>

Test if this device is the same as the provided device.


return self.id != other.id<EOL>

Test if this device is not the same as the provided device.


return hash(self.id)<EOL>

Hash function implementation that allows device instances to be put
        inside dictionaries and other containers.


global _provider<EOL>if _provider is None:<EOL><INDENT>if sys.platform.startswith('<STR_LIT>'):<EOL><INDENT>from .bluez_dbus.provider import BluezProvider<EOL>_provider = BluezProvider()<EOL><DEDENT>elif sys.platform == '<STR_LIT>':<EOL><INDENT>from .corebluetooth.provider import CoreBluetoothProvider<EOL>_provider = CoreBluetoothProvider()<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>'.format(sys.platform))<EOL><DEDENT><DEDENT>return _provider<EOL>

Return an instance of the BLE provider for the current platform.


<EOL>self._uart = device.find_service(UART_SERVICE_UUID)<EOL>if self._uart is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>self._tx = self._uart.find_characteristic(TX_CHAR_UUID)<EOL>self._rx = self._uart.find_characteristic(RX_CHAR_UUID)<EOL>if self._tx is None or self._rx is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>self._queue = queue.Queue()<EOL>self._rx.start_notify(self._rx_received)<EOL>

Initialize UART from provided bluez device.


Write a string of data to the UART device.


try:<EOL><INDENT>return self._queue.get(timeout=timeout_sec)<EOL><DEDENT>except queue.Empty:<EOL><INDENT>return None<EOL><DEDENT>

Block until data is available to read from the UART.  Will return a
        string of data that has been received.  Timeout_sec specifies how many
        seconds to wait for data to be available and will block forever if None
        (the default).  If the timeout is exceeded and no data is found then
        None is returned.


<EOL>self._colorific = device.find_service(COLOR_SERVICE_UUID)<EOL>self._color = self._colorific.find_characteristic(COLOR_CHAR_UUID)<EOL>

Initialize device information from provided bluez device.


<EOL>command = '<STR_LIT>'.format(chr(r & <NUM_LIT>),<EOL>chr(g & <NUM_LIT>),<EOL>chr(b & <NUM_LIT>))<EOL>self._color.write_value(command)<EOL>

Set the red, green, blue color of the bulb.


<EOL>self._dis = device.find_service(DIS_SERVICE_UUID)<EOL>self._manufacturer = self._dis.find_characteristic(MANUFACTURER_CHAR_UUID)<EOL>self._model = self._dis.find_characteristic(MODEL_CHAR_UUID)<EOL>self._serial = self._dis.find_characteristic(SERIAL_CHAR_UUID)<EOL>self._hw_revision = self._dis.find_characteristic(HW_REVISION_CHAR_UUID)<EOL>self._sw_revision = self._dis.find_characteristic(SW_REVISION_CHAR_UUID)<EOL>self._fw_revision = self._dis.find_characteristic(FW_REVISION_CHAR_UUID)<EOL>self._sys_id = self._dis.find_characteristic(SYS_ID_CHAR_UUID)<EOL>self._reg_cert = self._dis.find_characteristic(REG_CERT_CHAR_UUID)<EOL>self._pnp_id = self._dis.find_characteristic(PNP_ID_CHAR_UUID)<EOL>


return get_provider().find_device(service_uuids=cls.ADVERTISED, timeout_sec=timeout_sec)<EOL>

Find the first available device that supports this service and return
        it, or None if no device is found.  Will wait for up to timeout_sec
        seconds to find the device.


return get_provider().find_devices(cls.ADVERTISED)<EOL>

Find all the available devices that support this service and
        returns a list of them.  Does not poll and will return immediately.


return get_provider().disconnect_devices(service_uuids=cls.ADVERTISED)<EOL>

Disconnect any currently connected devices that implement this
        service.


@classmethod<EOL><INDENT>def discover(cls, device, timeout_sec=TIMEOUT_SEC):<DEDENT>

device.discover(cls.SERVICES, cls.CHARACTERISTICS, timeout_sec)<EOL>

Wait until the specified device has discovered the expected services
        and characteristics for this service.  Should be called once before other
        calls are made on the service.  Returns true if the service has been
        discovered in the specified timeout, or false if not discovered.


self._adapter = dbus.Interface(dbus_obj, _INTERFACE)<EOL>self._props = dbus.Interface(dbus_obj, '<STR_LIT>')<EOL>self._scan_started = threading.Event()<EOL>self._scan_stopped = threading.Event()<EOL>self._props.connect_to_signal('<STR_LIT>', self._prop_changed)<EOL>

Create an instance of the bluetooth adapter from the provided bluez
        DBus object.


return self._props.Get(_INTERFACE, '<STR_LIT:Name>')<EOL>

Return the name of this BLE network adapter.


self._scan_started.clear()<EOL>self._adapter.StartDiscovery()<EOL>if not self._scan_started.wait(timeout_sec):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>

Start scanning for BLE devices with this adapter.


self._scan_stopped.clear()<EOL>self._adapter.StopDiscovery()<EOL>if not self._scan_stopped.wait(timeout_sec):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>

Stop scanning for BLE devices with this adapter.


return self._props.Get(_INTERFACE, '<STR_LIT>')<EOL>

Return True if the BLE adapter is scanning for devices, otherwise
        return False.


return self._props.Set(_INTERFACE, '<STR_LIT>', True)<EOL>


return self._props.Set(_INTERFACE, '<STR_LIT>', False)<EOL>


Return True if the BLE adapter is powered up, otherwise return False.


<EOL>GObject.threads_init()<EOL>dbus.mainloop.glib.threads_init()<EOL>self._mainloop = dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)<EOL>self._bus = dbus.SystemBus()<EOL>self._bluez = dbus.Interface(self._bus.get_object('<STR_LIT>', '<STR_LIT:/>'),<EOL>'<STR_LIT>')<EOL>

Initialize bluez DBus communication.  Must be called before any other
        calls are made!


<EOL>self._user_thread = threading.Thread(target=self._user_thread_main, args=(target,))<EOL>self._user_thread.daemon = True  <EOL>self._user_thread.start()<EOL>self._gobject_mainloop = GObject.MainLoop()<EOL>try:<EOL><INDENT>self._gobject_mainloop.run()  <EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>self._gobject_mainloop.quit()<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>if self._exception is not None:<EOL><INDENT>raise_(self._exception[<NUM_LIT:1>], None, self._exception[<NUM_LIT:2>])<EOL><DEDENT>else:<EOL><INDENT>sys.exit(self._return_code)<EOL><DEDENT>

Start the OS's main loop to process asyncronous BLE events and then
        run the specified target function in a background thread.  Target
        function should be a function that takes no parameters and optionally
        return an integer response code.  When the target function stops
        executing or returns with value then the main loop will be stopped and
        the program will exit with the returned code.

        Note that an OS main loop is required to process asyncronous BLE events
        and this function is provided as a convenience for writing simple tools
        and scripts that don't need to be full-blown GUI applications.  If you
        are writing a GUI application that has a main loop (a GTK glib main loop
        on Linux, or a Cocoa main loop on OSX) then you don't need to call this
        function.


try:<EOL><INDENT>while True:<EOL><INDENT>if self._gobject_mainloop is not None and self._gobject_mainloop.is_running():<EOL><INDENT>break<EOL><DEDENT>time.sleep(<NUM_LIT:0>)<EOL><DEDENT>self._return_code = target()<EOL>if self._return_code is None:<EOL><INDENT>self._return_code = <NUM_LIT:0><EOL><DEDENT>self._gobject_mainloop.quit()<EOL><DEDENT>except Exception as ex:<EOL><INDENT>self._exception = sys.exc_info()<EOL>self._gobject_mainloop.quit()<EOL><DEDENT>

Main entry point for the thread that will run user's code.


<EOL>for device in self.list_devices():<EOL><INDENT>if device.is_connected:<EOL><INDENT>continue<EOL><DEDENT>adapter = dbus.Interface(self._bus.get_object('<STR_LIT>', device._adapter),<EOL>_ADAPTER_INTERFACE)<EOL>adapter.RemoveDevice(device._device.object_path)<EOL><DEDENT>

Clear any internally cached BLE device data.  Necessary in some cases
        to prevent issues with stale device data getting cached by the OS.


service_uuids = set(service_uuids)<EOL>for device in self.list_devices():<EOL><INDENT>if not device.is_connected:<EOL><INDENT>continue<EOL><DEDENT>device_uuids = set(map(lambda x: x.uuid, device.list_services()))<EOL>if device_uuids >= service_uuids:<EOL><INDENT>device.disconnect()<EOL><DEDENT><DEDENT>

Disconnect any connected devices that have the specified list of
        service UUIDs.  The default is an empty list which means all devices
        are disconnected.


return map(BluezAdapter, self._get_objects('<STR_LIT>'))<EOL>

Return a list of BLE adapter objects connected to the system.


return map(BluezDevice, self._get_objects('<STR_LIT>'))<EOL>

Return a list of BLE devices known to the system.


def _get_objects(self, interface, parent_path='<STR_LIT>'):

<EOL>parent_path = parent_path.lower()<EOL>objects = []<EOL>for opath, interfaces in iteritems(self._bluez.GetManagedObjects()):<EOL><INDENT>if interface in interfaces.keys() and opath.lower().startswith(parent_path):<EOL><INDENT>objects.append(self._bus.get_object('<STR_LIT>', opath))<EOL><DEDENT><DEDENT>return objects<EOL>

Return a list of all bluez DBus objects that implement the requested
        interface name and are under the specified path.  The default is to
        search devices under the root of all bluez objects.


return map(lambda x: self._bus.get_object('<STR_LIT>', x), paths)<EOL>

Return a list of all bluez DBus objects from the provided list of paths.


<EOL>objects = self._bluez.GetManagedObjects()<EOL>for path in objects.keys():<EOL><INDENT>print("<STR_LIT>" % (path))<EOL>interfaces = objects[path]<EOL>for interface in interfaces.keys():<EOL><INDENT>if interface in ["<STR_LIT>",<EOL>"<STR_LIT>"]:<EOL><INDENT>continue<EOL><DEDENT>print("<STR_LIT>" % (interface))<EOL>properties = interfaces[interface]<EOL>for key in properties.keys():<EOL><INDENT>print("<STR_LIT>" % (key, properties[key]))<EOL><DEDENT><DEDENT><DEDENT>

Print tree of all bluez objects, useful for debugging.


self._props = dbus.Interface(dbus_obj, '<STR_LIT>')<EOL>

Create an instance of the GATT service from the provided bluez
        DBus object.


return uuid.UUID(str(self._props.Get(_SERVICE_INTERFACE, '<STR_LIT>')))<EOL>


paths = self._props.Get(_SERVICE_INTERFACE, '<STR_LIT>')<EOL>return map(BluezGattCharacteristic,<EOL>get_provider()._get_objects_by_path(paths))<EOL>

Return list of GATT characteristics that have been discovered for this
        service.


self._characteristic = dbus.Interface(dbus_obj, _CHARACTERISTIC_INTERFACE)<EOL>self._props = dbus.Interface(dbus_obj, '<STR_LIT>')<EOL>

Create an instance of the GATT characteristic from the provided bluez
        DBus object.


return uuid.UUID(str(self._props.Get(_CHARACTERISTIC_INTERFACE, '<STR_LIT>')))<EOL>

Return the UUID of this GATT characteristic.


return self._characteristic.ReadValue()<EOL>


self._characteristic.WriteValue(value)<EOL>

Write the specified value to this characteristic.


<EOL>def characteristic_changed(iface, changed_props, invalidated_props):<EOL><INDENT>if iface != _CHARACTERISTIC_INTERFACE:<EOL><INDENT>return<EOL><DEDENT>if '<STR_LIT>' not in changed_props:<EOL><INDENT>return<EOL><DEDENT>on_change('<STR_LIT>'.join(map(chr, changed_props['<STR_LIT>'])))<EOL><DEDENT>self._props.connect_to_signal('<STR_LIT>', characteristic_changed)<EOL>self._characteristic.StartNotify()<EOL>

Enable notification of changes for this characteristic on the
        specified on_change callback.  on_change should be a function that takes
        one parameter which is the value (as a string of bytes) of the changed
        characteristic value.


Disable notification of changes for this characteristic.


paths = self._props.Get(_CHARACTERISTIC_INTERFACE, '<STR_LIT>')<EOL>return map(BluezGattDescriptor,<EOL>get_provider()._get_objects_by_path(paths))<EOL>

Return list of GATT descriptors that have been discovered for this
        characteristic.


self._descriptor = dbus.Interface(dbus_obj, _DESCRIPTOR_INTERFACE)<EOL>self._props = dbus.Interface(dbus_obj, '<STR_LIT>')<EOL>

Create an instance of the GATT descriptor from the provided bluez
        DBus object.


return uuid.UUID(str(self._props.Get(_DESCRIPTOR_INTERFACE, '<STR_LIT>')))<EOL>

Return the UUID of this GATT descriptor.


return self._descriptor.ReadValue()<EOL>


self._device = dbus.Interface(dbus_obj, _INTERFACE)<EOL>self._props = dbus.Interface(dbus_obj, '<STR_LIT>')<EOL>self._connected = threading.Event()<EOL>self._disconnected = threading.Event()<EOL>self._props.connect_to_signal('<STR_LIT>', self._prop_changed)<EOL>

Create an instance of the bluetooth device from the provided bluez
        DBus object.


self._connected.clear()<EOL>self._device.Connect()<EOL>if not self._connected.wait(timeout_sec):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>

Connect to the device.  If not connected within the specified timeout
        then an exception is thrown.


self._disconnected.clear()<EOL>self._device.Disconnect()<EOL>if not self._disconnected.wait(timeout_sec):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>

Disconnect from the device.  If not disconnected within the specified
        timeout then an exception is thrown.


return map(BluezGattService,<EOL>get_provider()._get_objects(_SERVICE_INTERFACE,<EOL>self._device.object_path))<EOL>

Return a list of GattService objects that have been discovered for
        this device.


<EOL>expected_services = set(service_uuids)<EOL>expected_chars = set(char_uuids)<EOL>start = time.time()<EOL>while True:<EOL><INDENT>actual_services = set(self.advertised)<EOL>chars = map(BluezGattCharacteristic,<EOL>get_provider()._get_objects(_CHARACTERISTIC_INTERFACE,<EOL>self._device.object_path))<EOL>actual_chars = set(map(lambda x: x.uuid, chars))<EOL>if actual_services >= expected_services and actual_chars >= expected_chars:<EOL><INDENT>return True<EOL><DEDENT>if time.time()-start >= timeout_sec:<EOL><INDENT>return False<EOL><DEDENT>time.sleep(<NUM_LIT:1>)<EOL><DEDENT>

Wait up to timeout_sec for the specified services and characteristics
        to be discovered on the device.  If the timeout is exceeded without
        discovering the services and characteristics then an exception is thrown.


uuids = []<EOL>try:<EOL><INDENT>uuids = self._props.Get(_INTERFACE, '<STR_LIT>')<EOL><DEDENT>except dbus.exceptions.DBusException as ex:<EOL><INDENT>if ex.get_dbus_name() != '<STR_LIT>':<EOL><INDENT>raise ex<EOL><DEDENT><DEDENT>return [uuid.UUID(str(x)) for x in uuids]<EOL>

Return a list of UUIDs for services that are advertised by this
        device.


return self._props.Get(_INTERFACE, '<STR_LIT>')<EOL>

Return a unique identifier for this device.  On supported platforms
        this will be the MAC address of the device, however on unsupported
        platforms (Mac OSX) it will be a unique ID like a UUID.


return self._props.Get(_INTERFACE, '<STR_LIT:Name>')<EOL>


Return True if the device is connected to the system, otherwise False.


Return the RSSI signal strength in decibels.


Return the DBus path to the adapter that owns this device.


self._jobs = []<EOL>if not hasattr(app, '<STR_LIT>'):<EOL><INDENT>app.extensions = {}<EOL><DEDENT>app.extensions['<STR_LIT>'] = self<EOL>app.restpoints_instance = self<EOL>app.add_url_rule('<STR_LIT>', '<STR_LIT>', ping)<EOL>app.add_url_rule('<STR_LIT>', '<STR_LIT:time>', time)<EOL>app.add_url_rule('<STR_LIT>', '<STR_LIT:status>', status(self._jobs))<EOL>

Initialize a :class:`~flask.Flask` application for use with
        this extension.


def add_status_job(self, job_func, name=None, timeout=<NUM_LIT:3>):

job_name = job_func.__name__ if name is None else name<EOL>job = (job_name, timeout, job_func)<EOL>self._jobs.append(job)<EOL>

Adds a job to be included during calls to the `/status` endpoint.

        :param job_func: the status function.
        :param name: the name used in the JSON response for the given status
                     function. The name of the function is the default.
        :param timeout: the time limit before the job status is set to
                        "timeout exceeded".


def status_job(self, fn=None, name=None, timeout=<NUM_LIT:3>):

if fn is None:<EOL><INDENT>def decorator(fn):<EOL><INDENT>self.add_status_job(fn, name, timeout)<EOL><DEDENT>return decorator<EOL><DEDENT>else:<EOL><INDENT>self.add_status_job(fn, name, timeout)<EOL><DEDENT>

Decorator that invokes `add_status_job`.

        ::

            @app.status_job
            def postgresql():
                # query/ping postgres

            @app.status_job(name="Active Directory")
            def active_directory():
                # query active directory

            @app.status_job(timeout=5)
            def paypal():
                # query paypal, timeout after 5 seconds


def status_handler():<EOL><INDENT>endpoints = []<EOL>stats = {"<STR_LIT>": None}<EOL>executor = concurrent.futures.ThreadPoolExecutor(max_workers=<NUM_LIT:5>)<EOL>for job, future in [(job, executor.submit(timeit, job[<NUM_LIT:2>], number=<NUM_LIT:1>)) for job in jobs]:<EOL><INDENT>name, timeout, _ = job<EOL>endpoint = {"<STR_LIT>": name}<EOL>try:<EOL><INDENT>data = future.result(timeout=timeout)<EOL>endpoint["<STR_LIT>"] = data<EOL><DEDENT>except concurrent.futures.TimeoutError:<EOL><INDENT>endpoint["<STR_LIT:error>"] = "<STR_LIT>"<EOL><DEDENT>except Exception as ex:<EOL><INDENT>endpoint["<STR_LIT:error>"] = str(ex)<EOL><DEDENT>endpoints.append(endpoint)<EOL><DEDENT>if len(endpoints) > <NUM_LIT:0>:<EOL><INDENT>stats["<STR_LIT>"] = endpoints<EOL><DEDENT>executor.shutdown(wait=False)<EOL>return jsonify(**stats)<EOL><DEDENT>return status_handler<EOL>

Handler that calls each status job in a worker pool, attempting to timeout.
    The resulting durations/errors are written to the response
    as JSON.

    eg.

    `{
        "endpoints": [
            { "endpoint": "Jenny's Database", "duration": 1.002556324005127 },
            { "endpoint": "Hotmail", "duration": -1, "error": "Host is down" },
        ]
     }`


return "<STR_LIT>"<EOL>

Handler that simply returns `pong` from a GET.


<EOL>green_exe = get_green_exe()<EOL>if argd['<STR_LIT>'] or argd['<STR_LIT>']:<EOL><INDENT>return list_tests(full=argd['<STR_LIT>'])<EOL><DEDENT>green_args = parse_test_names(argd['<STR_LIT>']) or ['<STR_LIT:test>']<EOL>if argd['<STR_LIT>']:<EOL><INDENT>return print_test_names(green_args)<EOL><DEDENT>cmd = [green_exe, '<STR_LIT>']<EOL>if not argd['<STR_LIT>']:<EOL><INDENT>cmd.append('<STR_LIT>')<EOL><DEDENT>cmd.extend(green_args)<EOL>print_header(cmd)<EOL>return subprocess.run(cmd).returncode<EOL>

Main entry point, expects doctopt arg dict as argd.


paths = set(<EOL>s for s in os.environ.get('<STR_LIT>', '<STR_LIT>').split('<STR_LIT::>')<EOL>if s and os.path.isdir(s)<EOL>)<EOL>pyver = '<STR_LIT>'.format(v=sys.version_info)<EOL>greenmajorexe = '<STR_LIT>'.format(sys.version_info.major)<EOL>greenexe = '<STR_LIT>'.format(pyver)<EOL>for trypath in paths:<EOL><INDENT>greenpath = os.path.join(trypath, greenexe)<EOL>greenmajorpath = os.path.join(trypath, greenmajorexe)<EOL>if os.path.exists(greenpath):<EOL><INDENT>return greenpath<EOL><DEDENT>elif os.path.exists(greenmajorpath):<EOL><INDENT>return greenmajorpath<EOL><DEDENT><DEDENT>raise MissingDependency('<STR_LIT>')<EOL>

Get the green executable for this Python version.


if kwargs.get('<STR_LIT:file>', None) is None:<EOL><INDENT>kwargs['<STR_LIT:file>'] = sys.stderr<EOL><DEDENT>print(*args, **kwargs)<EOL>

A wrapper for print() that uses stderr by default.


textcolors = {'<STR_LIT>': '<STR_LIT>'}<EOL>libcolors = {'<STR_LIT>': '<STR_LIT>', '<STR_LIT>': '<STR_LIT>'}<EOL>vercolors = {'<STR_LIT>': '<STR_LIT>'}<EOL>execolors = {'<STR_LIT>': '<STR_LIT>', '<STR_LIT>': '<STR_LIT>'}<EOL>argcolors = {'<STR_LIT>': '<STR_LIT>'}<EOL>def fmt_app_info(name, ver):<EOL><INDENT>"""<STR_LIT>"""<EOL>return C('<STR_LIT>', **textcolors).join(<EOL>C(name, **libcolors),<EOL>C(ver, **vercolors)<EOL>)<EOL><DEDENT>def fmt_cmd_args(cmdargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>return C('<STR_LIT:U+0020>').join(<EOL>C(cmdargs[<NUM_LIT:0>], **execolors),<EOL>C('<STR_LIT:U+0020>').join(C(s, **argcolors) for s in cmdargs[<NUM_LIT:1>:]),<EOL>).join('<STR_LIT:(>', '<STR_LIT:)>', style='<STR_LIT>')<EOL><DEDENT>print('<STR_LIT>'.format(<EOL>C('<STR_LIT:U+0020>').join(<EOL>C('<STR_LIT>', **textcolors),<EOL>fmt_app_info(APPNAME, APPVERSION),<EOL>C('<STR_LIT>', **textcolors),<EOL>fmt_app_info('<STR_LIT>', green_version),<EOL>fmt_cmd_args(cmd),<EOL>)<EOL>))<EOL>print(<EOL>C('<STR_LIT>').join(<EOL>C('<STR_LIT>', '<STR_LIT>'),<EOL>C(os.getcwd(), '<STR_LIT>', style='<STR_LIT>'),<EOL>),<EOL>)<EOL>

Print some info about the Colr and Green versions being used.


global DEBUG<EOL>argd = docopt(USAGESTR, version=VERSIONSTR, script=SCRIPT)<EOL>DEBUG = argd['<STR_LIT>']<EOL>width = parse_int(argd['<STR_LIT>'] or DEFAULT_WIDTH) or <NUM_LIT:1><EOL>indent = parse_int(argd['<STR_LIT>'] or (argd['<STR_LIT>'] or <NUM_LIT:0>))<EOL>prepend = '<STR_LIT:U+0020>' * (indent * <NUM_LIT:4>)<EOL>if prepend and argd['<STR_LIT>']:<EOL><INDENT>width -= len(prepend)<EOL><DEDENT>userprepend = argd['<STR_LIT>'] or (argd['<STR_LIT>'] or '<STR_LIT>')<EOL>prepend = '<STR_LIT>'.join((prepend, userprepend))<EOL>if argd['<STR_LIT>']:<EOL><INDENT>width -= len(userprepend)<EOL><DEDENT>userappend = argd['<STR_LIT>'] or (argd['<STR_LIT>'] or '<STR_LIT>')<EOL>if argd['<STR_LIT>']:<EOL><INDENT>width -= len(userappend)<EOL><DEDENT>if argd['<STR_LIT>']:<EOL><INDENT>argd['<STR_LIT>'] = (<EOL>(try_read_file(w) if len(w) < <NUM_LIT> else w)<EOL>for w in argd['<STR_LIT>']<EOL>)<EOL>words = '<STR_LIT:U+0020>'.join((w for w in argd['<STR_LIT>'] if w))<EOL><DEDENT>else:<EOL><INDENT>words = read_stdin()<EOL><DEDENT>block = FormatBlock(words).iter_format_block(<EOL>chars=argd['<STR_LIT>'],<EOL>fill=argd['<STR_LIT>'],<EOL>prepend=prepend,<EOL>strip_first=argd['<STR_LIT>'],<EOL>append=userappend,<EOL>strip_last=argd['<STR_LIT>'],<EOL>width=width,<EOL>newlines=argd['<STR_LIT>'],<EOL>lstrip=argd['<STR_LIT>'],<EOL>)<EOL>for i, line in enumerate(block):<EOL><INDENT>if argd['<STR_LIT>']:<EOL><INDENT>print('<STR_LIT>'.format(i + <NUM_LIT:1>, line))<EOL><DEDENT>else:<EOL><INDENT>print(line)<EOL><DEDENT><DEDENT>return <NUM_LIT:0><EOL>


if not (DEBUG and args):<EOL><INDENT>return None<EOL><DEDENT>parent = kwargs.get('<STR_LIT>', None)<EOL>with suppress(KeyError):<EOL><INDENT>kwargs.pop('<STR_LIT>')<EOL><DEDENT>backlevel = kwargs.get('<STR_LIT>', <NUM_LIT:1>)<EOL>with suppress(KeyError):<EOL><INDENT>kwargs.pop('<STR_LIT>')<EOL><DEDENT>frame = inspect.currentframe()<EOL>while backlevel > <NUM_LIT:0>:<EOL><INDENT>frame = frame.f_back<EOL>backlevel -= <NUM_LIT:1><EOL><DEDENT>fname = os.path.split(frame.f_code.co_filename)[-<NUM_LIT:1>]<EOL>lineno = frame.f_lineno<EOL>if parent:<EOL><INDENT>func = '<STR_LIT>'.format(parent.__class__.__name__, frame.f_code.co_name)<EOL><DEDENT>else:<EOL><INDENT>func = frame.f_code.co_name<EOL><DEDENT>lineinfo = '<STR_LIT>'.format(<EOL>C(fname, '<STR_LIT>'),<EOL>C(str(lineno).ljust(<NUM_LIT:4>), '<STR_LIT>'),<EOL>C().join(C(func, '<STR_LIT>'), '<STR_LIT>').ljust(<NUM_LIT:20>)<EOL>)<EOL>pargs = list(C(a, '<STR_LIT>').str() for a in args)<EOL>pargs[<NUM_LIT:0>] = '<STR_LIT>'.join((lineinfo, pargs[<NUM_LIT:0>]))<EOL>print_err(*pargs, **kwargs)<EOL>

Print a message only if DEBUG is truthy.


try:<EOL><INDENT>val = int(s)<EOL><DEDENT>except ValueError:<EOL><INDENT>print_err('<STR_LIT>'.format(s))<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>return val<EOL>

Parse a string as an integer.
        Exit with a message on failure.


if sys.stdin.isatty() and sys.stdout.isatty():<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>return sys.stdin.read()<EOL>

Read from stdin, but print a helpful message if it's a tty.


try:<EOL><INDENT>with open(s, '<STR_LIT:r>') as f:<EOL><INDENT>data = f.read()<EOL><DEDENT><DEDENT>except FileNotFoundError:<EOL><INDENT>return s<EOL><DEDENT>except EnvironmentError as ex:<EOL><INDENT>print_err('<STR_LIT>'.format(s, ex))<EOL>return None<EOL><DEDENT>return data<EOL>

If `s` is a file name, read the file and return it's content.
        Otherwise, return the original string.
        Returns None if the file was opened, but errored during reading.


def expand_words(self, line, width=<NUM_LIT>):

if not line.strip():<EOL><INDENT>return line<EOL><DEDENT>wordi = <NUM_LIT:1><EOL>while len(strip_codes(line)) < width:<EOL><INDENT>wordendi = self.find_word_end(line, wordi)<EOL>if wordendi < <NUM_LIT:0>:<EOL><INDENT>wordi = <NUM_LIT:1><EOL>wordendi = self.find_word_end(line, wordi)<EOL><DEDENT>if wordendi < <NUM_LIT:0>:<EOL><INDENT>line = '<STR_LIT>'.join(('<STR_LIT:U+0020>', line))<EOL><DEDENT>else:<EOL><INDENT>line = '<STR_LIT:U+0020>'.join((line[:wordendi], line[wordendi:]))<EOL>wordi += <NUM_LIT:1><EOL><DEDENT><DEDENT>if '<STR_LIT:U+0020>' not in strip_codes(line).strip():<EOL><INDENT>return line.replace('<STR_LIT:U+0020>', '<STR_LIT>')<EOL><DEDENT>return line<EOL>

Insert spaces between words until it is wide enough for `width`.


if not text:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>elif '<STR_LIT:U+0020>' not in text:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>elif not text.strip():<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>count = count or <NUM_LIT:1><EOL>found = <NUM_LIT:0><EOL>foundindex = -<NUM_LIT:1><EOL>inword = False<EOL>indices = get_indices(str(text))<EOL>sortedindices = sorted(indices)<EOL>for i in sortedindices:<EOL><INDENT>c = indices[i]<EOL>if inword and c.isspace():<EOL><INDENT>inword = False<EOL>foundindex = i<EOL>found += <NUM_LIT:1><EOL>testindex = i<EOL>while testindex > <NUM_LIT:0>:<EOL><INDENT>testindex -= <NUM_LIT:1><EOL>s = indices.get(testindex, None)<EOL>if s is None:<EOL><INDENT>continue<EOL><DEDENT>if len(s) == <NUM_LIT:1>:<EOL><INDENT>foundindex = testindex + <NUM_LIT:1><EOL>break<EOL><DEDENT><DEDENT>if found == count:<EOL><INDENT>return foundindex<EOL><DEDENT><DEDENT>elif not c.isspace():<EOL><INDENT>inword = True<EOL><DEDENT><DEDENT>lastindex = sortedindices[-<NUM_LIT:1>]<EOL>if len(indices[lastindex]) > <NUM_LIT:1>:<EOL><INDENT>while lastindex > <NUM_LIT:0>:<EOL><INDENT>lastindex -= <NUM_LIT:1><EOL>s = indices.get(lastindex, None)<EOL>if s is None:<EOL><INDENT>continue<EOL><DEDENT>if len(s) == <NUM_LIT:1>:<EOL><INDENT>return lastindex + <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>return -<NUM_LIT:1> if inword else foundindex<EOL>

This is a helper method for self.expand_words().
            Finds the index of word endings (default is first word).
            The last word doesn't count.
            If there are no words, or there are no spaces in the word, it
            returns -1.

            This method ignores escape codes.
            Example:
                s = 'this is a test'
                i = find_word_end(s, count=1)
                print('-'.join((s[:i], s[i:])))
                # 'this- is a test'
                i = find_word_end(s, count=2)
                print('-'.join((s[:i], s[i:])))
                # 'this is- a test'


def format(<EOL>self, text=None,<EOL>width=<NUM_LIT>, chars=False, fill=False, newlines=False,<EOL>prepend=None, append=None, strip_first=False, strip_last=False,<EOL>lstrip=False):

<EOL>return '<STR_LIT:\n>'.join(<EOL>self.iter_format_block(<EOL>(self.text if text is None else text) or '<STR_LIT>',<EOL>prepend=prepend,<EOL>append=append,<EOL>strip_first=strip_first,<EOL>strip_last=strip_last,<EOL>width=width,<EOL>chars=chars,<EOL>fill=fill,<EOL>newlines=newlines,<EOL>lstrip=lstrip<EOL>)<EOL>)<EOL>

Format a long string into a block of newline seperated text.
            Arguments:
                See iter_format_block().


def iter_add_text(self, lines, prepend=None, append=None):

if (prepend is None) and (append is None):<EOL><INDENT>yield from lines<EOL><DEDENT>else:<EOL><INDENT>fmtpcs = ['<STR_LIT>'] if prepend else []<EOL>fmtpcs.append('<STR_LIT>')<EOL>if append:<EOL><INDENT>fmtpcs.append('<STR_LIT>')<EOL><DEDENT>fmtstr = '<STR_LIT>'.join(fmtpcs)<EOL>yield from (<EOL>fmtstr.format(prepend=prepend, line=line, append=append)<EOL>for line in lines<EOL>)<EOL><DEDENT>

Prepend or append text to lines. Yields each line.


def iter_block(<EOL>self, text=None,<EOL>width=<NUM_LIT>, chars=False, newlines=False, lstrip=False):

text = (self.text if text is None else text) or '<STR_LIT>'<EOL>if width < <NUM_LIT:1>:<EOL><INDENT>width = <NUM_LIT:1><EOL><DEDENT>fmtline = str.lstrip if lstrip else str<EOL>if chars and (not newlines):<EOL><INDENT>yield from self.iter_char_block(<EOL>text,<EOL>width=width,<EOL>fmtfunc=fmtline<EOL>)<EOL><DEDENT>elif newlines:<EOL><INDENT>for line in text.split('<STR_LIT:\n>'):<EOL><INDENT>yield from self.iter_block(<EOL>line,<EOL>width=width,<EOL>chars=chars,<EOL>lstrip=lstrip,<EOL>newlines=False,<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield from self.iter_space_block(<EOL>text,<EOL>width=width,<EOL>fmtfunc=fmtline,<EOL>)<EOL><DEDENT>

Iterator that turns a long string into lines no greater than
            'width' in length.
            It can wrap on spaces or characters. It only does basic blocks.
            For prepending see `iter_format_block()`.

            Arguments:
                text     : String to format.
                width    : Maximum width for each line.
                           Default: 60
                chars    : Wrap on characters if true, otherwise on spaces.
                           Default: False
                newlines : Preserve newlines when True.
                           Default: False
                lstrip   : Whether to remove leading spaces from each line.
                           Default: False


def iter_char_block(self, text=None, width=<NUM_LIT>, fmtfunc=str):

if width < <NUM_LIT:1>:<EOL><INDENT>width = <NUM_LIT:1><EOL><DEDENT>text = (self.text if text is None else text) or '<STR_LIT>'<EOL>text = '<STR_LIT:U+0020>'.join(text.split('<STR_LIT:\n>'))<EOL>escapecodes = get_codes(text)<EOL>if not escapecodes:<EOL><INDENT>yield from (<EOL>fmtfunc(text[i:i + width])<EOL>for i in range(<NUM_LIT:0>, len(text), width)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>blockwidth = <NUM_LIT:0><EOL>block = []<EOL>for i, s in enumerate(get_indices_list(text)):<EOL><INDENT>block.append(s)<EOL>if len(s) == <NUM_LIT:1>:<EOL><INDENT>blockwidth += <NUM_LIT:1><EOL><DEDENT>if blockwidth == width:<EOL><INDENT>yield '<STR_LIT>'.join(block)<EOL>block = []<EOL>blockwidth = <NUM_LIT:0><EOL><DEDENT><DEDENT>if block:<EOL><INDENT>yield '<STR_LIT>'.join(block)<EOL><DEDENT><DEDENT>

Format block by splitting on individual characters.


def iter_format_block(<EOL>self, text=None,<EOL>width=<NUM_LIT>, chars=False, fill=False, newlines=False,<EOL>append=None, prepend=None, strip_first=False, strip_last=False,<EOL>lstrip=False):

if fill:<EOL><INDENT>chars = False<EOL><DEDENT>iterlines = self.iter_block(<EOL>(self.text if text is None else text) or '<STR_LIT>',<EOL>width=width,<EOL>chars=chars,<EOL>newlines=newlines,<EOL>lstrip=lstrip,<EOL>)<EOL>if not (prepend or append):<EOL><INDENT>if fill:<EOL><INDENT>yield from (<EOL>self.expand_words(l, width=width) for l in iterlines<EOL>)<EOL><DEDENT>else:<EOL><INDENT>yield from iterlines<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if prepend:<EOL><INDENT>prependlen = len(prepend)<EOL><DEDENT>else:<EOL><INDENT>strip_first = False<EOL>prependlen = <NUM_LIT:0><EOL><DEDENT>if append:<EOL><INDENT>lines = list(iterlines)<EOL>lasti = len(lines) - <NUM_LIT:1><EOL>iterlines = (l for l in lines)<EOL>appendlen = len(append)<EOL><DEDENT>else:<EOL><INDENT>strip_last = False<EOL>appendlen = <NUM_LIT:0><EOL>lasti = -<NUM_LIT:1><EOL><DEDENT>for i, l in enumerate(self.iter_add_text(<EOL>iterlines,<EOL>prepend=prepend,<EOL>append=append)):<EOL><INDENT>if strip_first and (i == <NUM_LIT:0>):<EOL><INDENT>l = l[prependlen:]<EOL><DEDENT>elif strip_last and (i == lasti):<EOL><INDENT>l = l[:-appendlen]<EOL><DEDENT>if fill:<EOL><INDENT>yield self.expand_words(l, width=width)<EOL><DEDENT>else:<EOL><INDENT>yield l<EOL><DEDENT><DEDENT><DEDENT>

Iterate over lines in a formatted block of text.
            This iterator allows you to prepend to each line.
            For basic blocks see iter_block().

            Arguments:
                text        : String to format.

                width       : Maximum width for each line. The prepend string
                              is not included in this calculation.
                              Default: 60

                chars       : Whether to wrap on characters instead of spaces.
                              Default: False
                fill        : Insert spaces between words so that each line is
                              the same width. This overrides `chars`.
                              Default: False

                newlines    : Whether to preserve newlines in the original
                              string.
                              Default: False

                append      : String to append after each line.

                prepend     : String to prepend before each line.

                strip_first : Whether to omit the prepend string for the first
                              line.
                              Default: False

                              Example (when using prepend='$'):
                               Without strip_first -> '$this', '$that'
                               With strip_first -> 'this', '$that'

                strip_last  : Whether to omit the append string for the last
                              line (like strip_first does for prepend).
                              Default: False

                lstrip      : Whether to remove leading spaces from each line.
                              This doesn't include any spaces in `prepend`.
                              Default: False


def iter_space_block(self, text=None, width=<NUM_LIT>, fmtfunc=str):

if width < <NUM_LIT:1>:<EOL><INDENT>width = <NUM_LIT:1><EOL><DEDENT>curline = '<STR_LIT>'<EOL>text = (self.text if text is None else text) or '<STR_LIT>'<EOL>for word in text.split():<EOL><INDENT>possibleline = '<STR_LIT:U+0020>'.join((curline, word)) if curline else word<EOL>codelen = sum(len(s) for s in get_codes(possibleline))<EOL>reallen = len(possibleline) - codelen<EOL>if reallen > width:<EOL><INDENT>yield fmtfunc(curline)<EOL>curline = word<EOL><DEDENT>else:<EOL><INDENT>curline = possibleline<EOL><DEDENT><DEDENT>if curline:<EOL><INDENT>yield fmtfunc(curline)<EOL><DEDENT>


<EOL>while ('<STR_LIT:U+0020>' in line) and (len(line) > width):<EOL><INDENT>head, _, tail = line.rpartition('<STR_LIT:U+0020>')<EOL>line = '<STR_LIT:U+0020>'.join((head, tail))<EOL><DEDENT>return line<EOL>

Remove spaces in between words until it is small enough for
            `width`.
            This will always leave at least one space between words,
            so it may not be able to get below `width` characters.


return codegrabpat.findall(str(s))<EOL>

Grab all escape codes from a string.
        Returns a list of all escape codes.


def get_code_indices(s: Any) -> Dict[int, str]:

indices = {}<EOL>i = <NUM_LIT:0><EOL>codes = get_codes(s)<EOL>for code in codes:<EOL><INDENT>codeindex = s.index(code)<EOL>realindex = i + codeindex<EOL>indices[realindex] = code<EOL>codelen = len(code)<EOL>i = realindex + codelen<EOL>s = s[codeindex + codelen:]<EOL><DEDENT>return indices<EOL>

Retrieve a dict of {index: escape_code} for a given string.
        If no escape codes are found, an empty dict is returned.


def get_indices(s: Any) -> Dict[int, str]:

codes = get_code_indices(s)<EOL>if not codes:<EOL><INDENT>return {i: c for i, c in enumerate(s)}<EOL><DEDENT>indices = {}<EOL>for codeindex in sorted(codes):<EOL><INDENT>code = codes[codeindex]<EOL>if codeindex == <NUM_LIT:0>:<EOL><INDENT>indices[codeindex] = code<EOL>continue<EOL><DEDENT>start = max(indices or {<NUM_LIT:0>: '<STR_LIT>'}, key=int)<EOL>startcode = indices.get(start, '<STR_LIT>')<EOL>startlen = start + len(startcode)<EOL>indices.update({i: s[i] for i in range(startlen, codeindex)})<EOL>indices[codeindex] = code<EOL><DEDENT>if not indices:<EOL><INDENT>return {i: c for i, c in enumerate(s)}<EOL><DEDENT>lastindex = max(indices, key=int)<EOL>lastitem = indices[lastindex]<EOL>start = lastindex + len(lastitem)<EOL>textlen = len(s)<EOL>if start < (textlen - <NUM_LIT:1>):<EOL><INDENT>indices.update({i: s[i] for i in range(start, textlen)})<EOL><DEDENT>return indices<EOL>

Retrieve a dict of characters and escape codes with their real index
        into the string as the key.


def get_indices_list(s: Any) -> List[str]:

indices = get_indices(s)<EOL>return [<EOL>indices[i] for i in sorted(indices, key=int)<EOL>]<EOL>

Retrieve a list of characters and escape codes where each escape
        code uses only one index. The indexes will not match up with the
        indexes in the original string.


return codepat.match(str(s)) is not None<EOL>

Returns True if `s` appears to be any kind of escape code.


return codepat.sub('<STR_LIT>', str(s) if (s or (s == <NUM_LIT:0>)) else '<STR_LIT>')<EOL>

Strip all color codes from a string.
        Returns empty string for "falsey" inputs.


cwd = os.getcwd()<EOL>settings_filename = '<STR_LIT>' % (<EOL>settings_module.split('<STR_LIT:.>')[-<NUM_LIT:1>]<EOL>)<EOL>while cwd:<EOL><INDENT>if settings_filename in os.listdir(cwd):<EOL><INDENT>break<EOL><DEDENT>cwd = os.path.split(cwd)[<NUM_LIT:0>]<EOL>if os.name == '<STR_LIT>' and NT_ROOT.match(cwd):<EOL><INDENT>return None<EOL><DEDENT>elif cwd == '<STR_LIT:/>':<EOL><INDENT>return None<EOL><DEDENT><DEDENT>return cwd<EOL>

Hunt down the settings.py module by going up the FS path


return<EOL>

Dummy function that replaces the transaction functions


for plugin in self.nose_config.plugins.plugins:<EOL><INDENT>if getattr(plugin, '<STR_LIT>', False):<EOL><INDENT>self.django_plugins.append(plugin)<EOL><DEDENT><DEDENT>os.environ['<STR_LIT>'] = self.settings_module<EOL>if self.conf.addPaths:<EOL><INDENT>map(add_path, self.conf.where)<EOL><DEDENT>try:<EOL><INDENT>__import__(self.settings_module)<EOL>self.settings_path = self.settings_module<EOL><DEDENT>except ImportError:<EOL><INDENT>self.settings_path = get_settings_path(self.settings_module)<EOL>if not self.settings_path:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>add_path(self.settings_path)<EOL>sys.path.append(self.settings_path)<EOL><DEDENT>from django.conf import settings<EOL>settings.DEBUG = False<EOL>self.call_plugins_method('<STR_LIT>', settings)<EOL>from django.core import management<EOL>from django.test.utils import setup_test_environment<EOL>if hasattr(settings, '<STR_LIT>'):<EOL><INDENT>self.old_db = settings.DATABASES['<STR_LIT:default>']['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>self.old_db = settings.DATABASE_NAME<EOL><DEDENT>from django.db import connections<EOL>self._monkeypatch_test_classes()<EOL>for connection in connections.all():<EOL><INDENT>self.call_plugins_method(<EOL>'<STR_LIT>', settings, setup_test_environment,<EOL>connection)<EOL><DEDENT>try:<EOL><INDENT>setup_test_environment()<EOL><DEDENT>except RuntimeError:  <EOL><INDENT>pass<EOL><DEDENT>import django<EOL>if hasattr(django, '<STR_LIT>'):<EOL><INDENT>django.setup()<EOL><DEDENT>self.call_plugins_method('<STR_LIT>', settings)<EOL>management.get_commands()<EOL>if self.django_version < self.DJANGO_1_7:<EOL><INDENT>management._commands['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>for connection in connections.all():<EOL><INDENT>self.call_plugins_method(<EOL>'<STR_LIT>', settings, connection, management)<EOL>connection.creation.create_test_db(<EOL>verbosity=self.verbosity,<EOL>autoclobber=True,<EOL>)<EOL>logger.debug("<STR_LIT>")<EOL>self._num_syncdb_calls += <NUM_LIT:1><EOL>self.call_plugins_method('<STR_LIT>', settings, connection)<EOL><DEDENT>self.store_original_transaction_methods()<EOL>

Create the test database and schema, if needed, and switch the
connection over to that database. Then call install() to install
all apps listed in the loaded settings module.


if not self.settings_path:<EOL><INDENT>return<EOL><DEDENT>from django.test.utils import teardown_test_environment<EOL>from django.db import connection<EOL>from django.conf import settings<EOL>self.call_plugins_method('<STR_LIT>', settings, connection)<EOL>try:<EOL><INDENT>connection.creation.destroy_test_db(<EOL>self.old_db,<EOL>verbosity=self.verbosity,<EOL>)<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>self.call_plugins_method('<STR_LIT>', settings, connection)<EOL>self.call_plugins_method(<EOL>'<STR_LIT>', settings, teardown_test_environment)<EOL>teardown_test_environment()<EOL>self.call_plugins_method('<STR_LIT>', settings)<EOL>

Clean up any created database and schema.


if self._unique_token is None:<EOL><INDENT>self._unique_token = self._random_token()<EOL><DEDENT>return self._unique_token<EOL>

Get a unique token for usage in differentiating test runs that need to
run in parallel.


alphabet = string.ascii_letters + string.digits + '<STR_LIT>'<EOL>num_letters = int(math.ceil(bits / <NUM_LIT>))<EOL>return '<STR_LIT>'.join(random.choice(alphabet) for i in range(num_letters))<EOL>

Generates a random token, using the url-safe base64 alphabet.
The "bits" argument specifies the bits of randomness to use.


After every test, we want to empty the media directory so that media
left over from one test doesn't affect a later test.


if env is None:<EOL><INDENT>env = os.environ<EOL><DEDENT>parser.add_option(<EOL>'<STR_LIT>',<EOL>help='<STR_LIT>',<EOL>)<EOL>super(SphinxSearchPlugin, self).options(parser, env)<EOL>

Sphinx config file that can optionally take the following python
template string arguments:

``database_name``
``database_password``
``database_username``
``database_host``
``database_port``
``sphinx_search_data_dir``
``searchd_log_dir``


connected = False<EOL>max_tries = <NUM_LIT:10><EOL>num_tries = <NUM_LIT:0><EOL>wait_time = <NUM_LIT:0.5><EOL>while not connected or num_tries >= max_tries:<EOL><INDENT>time.sleep(wait_time)<EOL>try:<EOL><INDENT>af = socket.AF_INET<EOL>addr = ('<STR_LIT:127.0.0.1>', port)<EOL>sock = socket.socket(af, socket.SOCK_STREAM)<EOL>sock.connect(addr)<EOL><DEDENT>except socket.error:<EOL><INDENT>if sock:<EOL><INDENT>sock.close()<EOL><DEDENT>num_tries += <NUM_LIT:1><EOL>continue<EOL><DEDENT>connected = True<EOL><DEDENT>if not connected:<EOL><INDENT>print("<STR_LIT>", file=sys.stderr)<EOL><DEDENT>

Wait until we can make a socket connection to sphinx.


pass<EOL>


return self.name<EOL>


if not isinstance(name, str):<EOL><INDENT>return False<EOL><DEDENT>if '<STR_LIT:\n>' in name:<EOL><INDENT>return False<EOL><DEDENT>if name.strip() != name:<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>code = compile('<STR_LIT>'.format(name), filename='<STR_LIT>', mode='<STR_LIT>')<EOL>exec(code)<EOL>return True<EOL><DEDENT>except SyntaxError:<EOL><INDENT>return False<EOL><DEDENT>

Pedantic yet imperfect. Test to see if "name" is a valid python identifier


<EOL>e = PaletteEntry(mono = default_fg,<EOL>foreground=default_fg,<EOL>background=default_bg,<EOL>foreground_high=default_fg_hi,<EOL>background_high=default_bg_hi)<EOL>if isinstance(cfg, str):<EOL><INDENT>e.foreground_high = cfg<EOL>if e.allowed(cfg, <NUM_LIT:16>):<EOL><INDENT>e.foreground = cfg<EOL><DEDENT>else:<EOL><INDENT>rgb = AttrSpec(fg=cfg, bg="<STR_LIT>", colors=max_colors).get_rgb_values()[<NUM_LIT:0>:<NUM_LIT:3>]<EOL>e.foreground = nearest_basic_color(rgb)<EOL><DEDENT><DEDENT>elif isinstance(cfg, dict):<EOL><INDENT>bg = cfg.get("<STR_LIT>", None)<EOL>if isinstance(bg, str):<EOL><INDENT>e.background_high = bg<EOL>if e.allowed(bg, <NUM_LIT:16>):<EOL><INDENT>e.background = bg<EOL><DEDENT>else:<EOL><INDENT>rgb = AttrSpec(fg=bg, bg="<STR_LIT>", colors=max_colors).get_rgb_values()[<NUM_LIT:0>:<NUM_LIT:3>]<EOL>e.background = nearest_basic_color(rgb)<EOL><DEDENT><DEDENT>elif isinstance(bg, dict):<EOL><INDENT>e.background_high = bg.get("<STR_LIT>", default_bg_hi)<EOL>if "<STR_LIT>" in bg:<EOL><INDENT>if e.allowed(bg["<STR_LIT>"], <NUM_LIT:16>):<EOL><INDENT>e.background = bg["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>rgb = AttrSpec(fg=bg["<STR_LIT>"], bg="<STR_LIT>", colors=max_colors).get_rgb_values()[<NUM_LIT:0>:<NUM_LIT:3>]<EOL>e.background = nearest_basic_color(rgb)<EOL><DEDENT><DEDENT><DEDENT>fg = cfg.get("<STR_LIT>", cfg)<EOL>if isinstance(fg, str):<EOL><INDENT>e.foreground_high = fg<EOL>if e.allowed(fg, <NUM_LIT:16>):<EOL><INDENT>e.foreground = fg<EOL><DEDENT>else:<EOL><INDENT>rgb = AttrSpec(fg=fg, bg="<STR_LIT>", colors=max_colors).get_rgb_values()[<NUM_LIT:0>:<NUM_LIT:3>]<EOL>e.foreground = nearest_basic_color(rgb)<EOL><DEDENT><DEDENT>elif isinstance(fg, dict):<EOL><INDENT>e.foreground_high = fg.get("<STR_LIT>", default_fg_hi)<EOL>if "<STR_LIT>" in fg:<EOL><INDENT>if e.allowed(fg["<STR_LIT>"], <NUM_LIT:16>):<EOL><INDENT>e.foreground = fg["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>rgb = AttrSpec(fg=fg["<STR_LIT>"], bg="<STR_LIT>", colors=max_colors).get_rgb_values()[<NUM_LIT:0>:<NUM_LIT:3>]<EOL>e.foreground = nearest_basic_color(rgb)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return e<EOL>

Build a palette definition from either a simple string or a dictionary,
filling in defaults for items not specified.

e.g.:
    "dark green"
        dark green foreground, black background

    {lo: dark gray, hi: "#666"}
        dark gray on 16-color terminals, #666 for 256+ color


def check_import_dashboard_stackexchange(elastic_url, import_file, es_index=None,<EOL>data_sources=None, add_vis_studies=False, strict=False):

if "<STR_LIT>" in data_sources and "<STR_LIT>" not in data_sources:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>

Check that stackexchange data sources adds also stackoverflow
        data source which is the name used in panels


def __init__(self, conf_file, conf_list=[]):

self.conf_list = [conf_file] + conf_list<EOL>self.raw_conf = None<EOL>self.__read_conf_files()<EOL>

Initialize object.

        The object can be initialized with a configuration file,
        and, optionally, with a list of other configuration files.
        If the list of other configuration files exist, it will
        be read, in order, after the configuration file.
        Values set in a file read later will overwrite values set
        in files read earlier. Values not set by any file will
        be set to the default values, when possible.

        :param conf_file; configuration file name
        :param conf_list: list of other configuration files (default: empty)


params = {}<EOL>params_general = {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": <NUM_LIT>,<EOL>"<STR_LIT:type>": int,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": False,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": True,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": "<STR_LIT:file>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": <NUM_LIT>,  <EOL>"<STR_LIT:type>": int,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": <NUM_LIT:5>,<EOL>"<STR_LIT:type>": int,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": <NUM_LIT:1000>,<EOL>"<STR_LIT:type>": int,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": <NUM_LIT:100>,<EOL>"<STR_LIT:type>": int,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": ALIASES_JSON,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": MENU_YAML,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": None,<EOL>"<STR_LIT:type>": int,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>}<EOL>}<EOL>}<EOL>params_projects = {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": PROJECTS_JSON,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": None,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": False,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>}<EOL>}<EOL>}<EOL>params_phases = {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": True,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": True,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": True,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": True,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": False,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": False,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>}<EOL>}<EOL>}<EOL>general_config_params = [params_general, params_projects, params_phases]<EOL>for section_params in general_config_params:<EOL><INDENT>params.update(section_params)<EOL><DEDENT>params_collection = {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:password>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": None,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT:user>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": None,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT:url>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": False,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": None,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": None,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>}<EOL>}<EOL>}<EOL>params_enrichment = {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:url>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": True,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": <NUM_LIT:2>,<EOL>"<STR_LIT:type>": int,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT:user>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": None,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT:password>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": None,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>}<EOL>}<EOL>}<EOL>params_panels = {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:strict>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": True,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": None,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": None,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": True,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": False,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": False,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": False,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": False,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": False,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>}<EOL>}<EOL>}<EOL>params_report = {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": [],<EOL>"<STR_LIT:type>": list,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": None,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>}<EOL>}<EOL>}<EOL>params_sortinghat = {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT:True>",<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": ["<STR_LIT:email>"],<EOL>"<STR_LIT:type>": list,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": <NUM_LIT>,<EOL>"<STR_LIT:type>": int,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT:host>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT:user>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT:root>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT:password>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>"<STR_LIT:type>": list,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": False,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": True,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>"<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": False,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": None,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": [],<EOL>"<STR_LIT:type>": list,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": None,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": None,<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": [],<EOL>"<STR_LIT:type>": list,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": [],<EOL>"<STR_LIT:type>": list,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT:default>": False,<EOL>"<STR_LIT:type>": bool,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>}<EOL>}<EOL>}<EOL>params_track_items = {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT:default>": "<STR_LIT>",<EOL>"<STR_LIT:type>": str,<EOL>"<STR_LIT:description>": "<STR_LIT>"<EOL>}<EOL>}<EOL>}<EOL>tasks_config_params = [params_collection, params_enrichment, params_panels,<EOL>params_report, params_sortinghat, params_track_items]<EOL>for section_params in tasks_config_params:<EOL><INDENT>params.update(section_params)<EOL><DEDENT>return params<EOL>


def set_param(self, section, param, value):

if section not in self.conf or param not in self.conf[section]:<EOL><INDENT>logger.error('<STR_LIT>', section, param)<EOL><DEDENT>else:<EOL><INDENT>self.conf[section][param] = value<EOL><DEDENT>


typed_conf = {}<EOL>for s in raw_conf.keys():<EOL><INDENT>typed_conf[s] = {}<EOL>for option in raw_conf[s]:<EOL><INDENT>val = raw_conf[s][option]<EOL>if len(val) > <NUM_LIT:1> and (val[<NUM_LIT:0>] == '<STR_LIT:">' and val[-<NUM_LIT:1>] == '<STR_LIT:">'):<EOL><INDENT>typed_conf[s][option] = val[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL><DEDENT>elif len(val) > <NUM_LIT:1> and (val[<NUM_LIT:0>] == '<STR_LIT:[>' and val[-<NUM_LIT:1>] == '<STR_LIT:]>'):<EOL><INDENT>typed_conf[s][option] = val[<NUM_LIT:1>:-<NUM_LIT:1>].replace('<STR_LIT:U+0020>', '<STR_LIT>').split('<STR_LIT:U+002C>')<EOL><DEDENT>elif val.lower() in ['<STR_LIT:true>', '<STR_LIT:false>']:<EOL><INDENT>typed_conf[s][option] = True if val.lower() == '<STR_LIT:true>' else False<EOL><DEDENT>elif val.lower() == '<STR_LIT:none>':<EOL><INDENT>typed_conf[s][option] = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>typed_conf[s][option] = int(val)<EOL><DEDENT>except ValueError:<EOL><INDENT>typed_conf[s][option] = val<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return typed_conf<EOL>

Convert to int, boolean, list, None types config items


for section in new_conf:<EOL><INDENT>if section not in self.conf:<EOL><INDENT>self.conf[section] = new_conf[section]<EOL><DEDENT>else:<EOL><INDENT>for param in new_conf[section]:<EOL><INDENT>self.conf[section][param] = new_conf[section][param]<EOL><DEDENT><DEDENT><DEDENT>

Add new configuration to self.conf.

        Adds configuration parameters in new_con to self.conf.
        If they already existed in conf, overwrite them.

        :param new_conf: new configuration, to add


@classmethod<EOL><INDENT>def sha_github_file(cls, config, repo_file, repository_api, repository_branch):<DEDENT>

repo_file_sha = None<EOL>cfg = config.get_conf()<EOL>github_token = cfg['<STR_LIT>']['<STR_LIT>']<EOL>headers = {"<STR_LIT>": "<STR_LIT>" + github_token}<EOL>url_dir = repository_api + "<STR_LIT>" + repository_branch<EOL>logger.debug("<STR_LIT>", url_dir)<EOL>raw_repo_file_info = requests.get(url_dir, headers=headers)<EOL>raw_repo_file_info.raise_for_status()<EOL>for rfile in raw_repo_file_info.json()['<STR_LIT>']:<EOL><INDENT>if rfile['<STR_LIT:path>'] == repo_file:<EOL><INDENT>logger.debug("<STR_LIT>", rfile["<STR_LIT>"])<EOL>repo_file_sha = rfile["<STR_LIT>"]<EOL>break<EOL><DEDENT><DEDENT>return repo_file_sha<EOL>

Return the GitHub SHA for a file in the repository


uuids = []<EOL>with self.db.connect() as session:<EOL><INDENT>query = session.query(Profile).filter(Profile.name == profile_name)<EOL>profiles = query.all()<EOL>if profiles:<EOL><INDENT>for p in profiles:<EOL><INDENT>uuids.append(p.uuid)<EOL><DEDENT><DEDENT><DEDENT>return uuids<EOL>


@classmethod<EOL><INDENT>def measure_memory(cls, obj, seen=None):<DEDENT>

size = sys.getsizeof(obj)<EOL>if seen is None:<EOL><INDENT>seen = set()<EOL><DEDENT>obj_id = id(obj)<EOL>if obj_id in seen:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>seen.add(obj_id)<EOL>if isinstance(obj, dict):<EOL><INDENT>size += sum([cls.measure_memory(v, seen) for v in obj.values()])<EOL>size += sum([cls.measure_memory(k, seen) for k in obj.keys()])<EOL><DEDENT>elif hasattr(obj, '<STR_LIT>'):<EOL><INDENT>size += cls.measure_memory(obj.__dict__, seen)<EOL><DEDENT>elif hasattr(obj, '<STR_LIT>') and not isinstance(obj, (str, bytes, bytearray)):<EOL><INDENT>size += sum([cls.measure_memory(i, seen) for i in obj])<EOL><DEDENT>return size<EOL>