code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
''' Use geolocation to get the station ID ''' extra_opts = '/pws:0' if not self.use_pws else '' api_url = GEOLOOKUP_URL % (self.api_key, extra_opts, self.location_code) response = self.api_request(api_url) station_type = 'pws' if self.use_pws else 'airport' try: stations = response['location']['nearby_weather_stations'] nearest = stations[station_type]['station'][0] except (KeyError, IndexError): raise Exception( 'No locations matched location_code %s' % self.location_code) self.logger.error('nearest = %s', nearest) if self.use_pws: nearest_pws = nearest.get('id', '') if not nearest_pws: raise Exception('No id entry for nearest PWS') self.station_id = 'pws:%s' % nearest_pws else: nearest_airport = nearest.get('icao', '') if not nearest_airport: raise Exception('No icao entry for nearest airport') self.station_id = 'icao:%s' % nearest_airport
def get_station_id(self)
Use geolocation to get the station ID
3.518897
3.273939
1.07482
''' Query the configured/queried station and return the weather data ''' if self.station_id is None: # Failed to get the nearest station ID when first launched, so # retry it. self.get_station_id() self.data['update_error'] = '' try: query_url = STATION_QUERY_URL % (self.api_key, 'conditions', self.station_id) try: response = self.api_request(query_url)['current_observation'] self.forecast_url = response.pop('ob_url', None) except KeyError: self.logger.error('No weather data found for %s', self.station_id) self.data['update_error'] = self.update_error return if self.forecast: query_url = STATION_QUERY_URL % (self.api_key, 'forecast', self.station_id) try: forecast = self.api_request(query_url)['forecast'] forecast = forecast['simpleforecast']['forecastday'][0] except (KeyError, IndexError, TypeError): self.logger.error( 'No forecast data found for %s', self.station_id) # This is a non-fatal error, so don't return but do set the # error flag. self.data['update_error'] = self.update_error unit = 'celsius' if self.units == 'metric' else 'fahrenheit' low_temp = forecast.get('low', {}).get(unit, '') high_temp = forecast.get('high', {}).get(unit, '') else: low_temp = high_temp = '' if self.units == 'metric': temp_unit = 'c' speed_unit = 'kph' distance_unit = 'km' pressure_unit = 'mb' else: temp_unit = 'f' speed_unit = 'mph' distance_unit = 'mi' pressure_unit = 'in' def _find(key, data=None, default=''): if data is None: data = response return str(data.get(key, default)) try: observation_epoch = _find('observation_epoch') or _find('local_epoch') observation_time = datetime.fromtimestamp(int(observation_epoch)) except (TypeError, ValueError): log.debug( 'Observation time \'%s\' is not a UNIX timestamp', observation_epoch ) observation_time = datetime.fromtimestamp(0) self.data['city'] = _find('city', response['observation_location']) self.data['condition'] = _find('weather') self.data['observation_time'] = observation_time self.data['current_temp'] = _find('temp_' + temp_unit).split('.')[0] self.data['low_temp'] = low_temp self.data['high_temp'] = high_temp self.data['temp_unit'] = '°' + temp_unit.upper() self.data['feelslike'] = _find('feelslike_' + temp_unit) self.data['dewpoint'] = _find('dewpoint_' + temp_unit) self.data['wind_speed'] = _find('wind_' + speed_unit) self.data['wind_unit'] = speed_unit self.data['wind_direction'] = _find('wind_dir') self.data['wind_gust'] = _find('wind_gust_' + speed_unit) self.data['pressure'] = _find('pressure_' + pressure_unit) self.data['pressure_unit'] = pressure_unit self.data['pressure_trend'] = _find('pressure_trend') self.data['visibility'] = _find('visibility_' + distance_unit) self.data['visibility_unit'] = distance_unit self.data['humidity'] = _find('relative_humidity').rstrip('%') self.data['uv_index'] = _find('UV') except Exception: # Don't let an uncaught exception kill the update thread self.logger.error( 'Uncaught error occurred while checking weather. ' 'Exception follows:', exc_info=True ) self.data['update_error'] = self.update_error
def check_weather(self)
Query the configured/queried station and return the weather data
2.238503
2.140733
1.045671
''' Figure out the date to use for API requests. Assumes yesterday's date if between midnight and 10am Eastern time. Override this function in a subclass to change how the API date is calculated. ''' # NOTE: If you are writing your own function to get the date, make sure # to include the first if block below to allow for the ``date`` # parameter to hard-code a date. api_date = None if self.date is not None and not isinstance(self.date, datetime): try: api_date = datetime.strptime(self.date, '%Y-%m-%d') except (TypeError, ValueError): self.logger.warning('Invalid date \'%s\'', self.date) if api_date is None: utc_time = pytz.utc.localize(datetime.utcnow()) eastern = pytz.timezone('US/Eastern') api_date = eastern.normalize(utc_time.astimezone(eastern)) if api_date.hour < 10: # The scores on NHL.com change at 10am Eastern, if it's before # that time of day then we will use yesterday's date. api_date -= timedelta(days=1) self.date = api_date
def get_api_date(self)
Figure out the date to use for API requests. Assumes yesterday's date if between midnight and 10am Eastern time. Override this function in a subclass to change how the API date is calculated.
4.141969
3.008043
1.376965
''' Sometimes the weather data is set under an attribute of the "window" DOM object. Sometimes it appears as part of a javascript function. Catch either possibility. ''' if self.weather_data is not None: # We've already found weather data, no need to continue parsing return content = content.strip().rstrip(';') try: tag_text = self.get_starttag_text().lower() except AttributeError: tag_text = '' if tag_text.startswith('<script'): # Look for feed information embedded as a javascript variable begin = content.find('window.__data') if begin != -1: self.logger.debug('Located window.__data') # Look for end of JSON dict and end of javascript statement end = content.find('};', begin) if end == -1: self.logger.debug('Failed to locate end of javascript statement') else: # Strip the "window.__data=" from the beginning json_data = self.load_json( content[begin:end + 1].split('=', 1)[1].lstrip() ) if json_data is not None: def _find_weather_data(data): ''' Helper designed to minimize impact of potential structural changes to this data. ''' if isinstance(data, dict): if 'Observation' in data and 'DailyForecast' in data: return data else: for key in data: ret = _find_weather_data(data[key]) if ret is not None: return ret return None weather_data = _find_weather_data(json_data) if weather_data is None: self.logger.debug( 'Failed to locate weather data in the ' 'following data structure: %s', json_data ) else: self.weather_data = weather_data return for line in content.splitlines(): line = line.strip().rstrip(';') if line.startswith('var adaptorParams'): # Strip off the "var adaptorParams = " from the beginning, # and the javascript semicolon from the end. This will give # us JSON that we can load. weather_data = self.load_json(line.split('=', 1)[1].lstrip()) if weather_data is not None: self.weather_data = weather_data return
def handle_data(self, content)
Sometimes the weather data is set under an attribute of the "window" DOM object. Sometimes it appears as part of a javascript function. Catch either possibility.
3.907178
3.197824
1.221824
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) port = int(getattr(self, 'port', 1738)) sock.bind(('127.0.0.1', port)) while True: data, addr = sock.recvfrom(512) color = data.decode().strip() self.color = self.colors.get(color, color)
def main_loop(self)
Mainloop blocks so we thread it.
2.71327
2.661764
1.01935
if not self._suspended.is_set(): return True workload = unwrap_workload(workload) return hasattr(workload, 'keep_alive') and getattr(workload, 'keep_alive')
def should_execute(self, workload)
If we have been suspended by i3bar, only execute those modules that set the keep_alive flag to a truthy value. See the docs on the suspend_signal_handler method of the io module for more information.
6.195977
3.498252
1.771164
import sensors found_sensors = list() def get_subfeature_value(feature, subfeature_type): subfeature = chip.get_subfeature(feature, subfeature_type) if subfeature: return chip.get_value(subfeature.number) for chip in sensors.get_detected_chips(): for feature in chip.get_features(): if feature.type == sensors.FEATURE_TEMP: try: name = chip.get_label(feature) max = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_MAX) current = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_INPUT) critical = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_CRIT) if critical: found_sensors.append(Sensor(name=name, current=current, maximum=max, critical=critical)) except sensors.SensorsException: continue return found_sensors
def get_sensors()
Detect and return a list of Sensor objects
3.166288
3.053921
1.036795
with open(self.file, "r") as f: temp = float(f.read().strip()) / 1000 if self.dynamic_color: perc = int(self.percentage(int(temp), self.alert_temp)) if (perc > 99): perc = 99 color = self.colors[perc] else: color = self.color if temp < self.alert_temp else self.alert_color return { "full_text": self.format.format(temp=temp), "color": color, }
def get_output_original(self)
Build the output the original way. Requires no third party libraries.
3.995537
3.825988
1.044315
data = dict() found_sensors = get_sensors() if len(found_sensors) == 0: raise Exception("No sensors detected! " "Ensure lm-sensors is installed and check the output of the `sensors` command.") for sensor in found_sensors: data[sensor.name] = self.format_sensor(sensor) data["{}_bar".format(sensor.name)] = self.format_sensor_bar(sensor) data['temp'] = max((s.current for s in found_sensors)) return { 'full_text': self.format.format(**data), 'urgent': self.get_urgent(found_sensors), 'color': self.color if not self.dynamic_color else None, }
def get_output_sensors(self)
Build the output using lm_sensors. Requires sensors Python module (see docs).
4.768729
4.27314
1.115978
if self.urgent_on not in ('warning', 'critical'): raise Exception("urgent_on must be one of (warning, critical)") for sensor in sensors: if self.urgent_on == 'warning' and sensor.is_warning(): return True elif self.urgent_on == 'critical' and sensor.is_critical(): return True return False
def get_urgent(self, sensors)
Determine if any sensors should set the urgent flag.
2.592646
2.396363
1.081909
current_val = sensor.current if self.pango_enabled: percentage = self.percentage(sensor.current, sensor.critical) if self.dynamic_color: color = self.colors[int(percentage)] return self.format_pango(color, current_val) return current_val
def format_sensor(self, sensor)
Format a sensor value. If pango is enabled color is per sensor.
6.361612
4.395571
1.447278
percentage = self.percentage(sensor.current, sensor.critical) bar = make_vertical_bar(int(percentage)) if self.pango_enabled: if self.dynamic_color: color = self.colors[int(percentage)] return self.format_pango(color, bar) return bar
def format_sensor_bar(self, sensor)
Build and format a sensor bar. If pango is enabled bar color is per sensor.
6.744357
4.970742
1.356811
unread = 0 current_unread = 0 for id, backend in enumerate(self.backends): temp = backend.unread or 0 unread = unread + temp if id == self.current_backend: current_unread = temp if not unread: color = self.color urgent = "false" if self.hide_if_null: self.output = None return else: color = self.color_unread urgent = "true" format = self.format if unread > 1: format = self.format_plural account_name = getattr(self.backends[self.current_backend], "account", "No name") self.output = { "full_text": format.format(unread=unread, current_unread=current_unread, account=account_name), "urgent": urgent, "color": color, }
def run(self)
Returns the sum of unread messages across all registered backends
3.846626
3.625942
1.060862
try: key, value = line.split(":") self.update_value(key.strip(), value.strip()) except ValueError: pass
def parse_output(self, line)
Convert output to key value pairs
3.813903
3.23348
1.179504
if key == "Status": self._inhibited = value != "Enabled" elif key == "Color temperature": self._temperature = int(value.rstrip("K"), 10) elif key == "Period": self._period = value elif key == "Brightness": self._brightness = value elif key == "Location": location = [] for x in value.split(", "): v, d = x.split(" ") location.append(float(v) * (1 if d in "NE" else -1)) self._location = (location)
def update_value(self, key, value)
Parse key value pairs to update their values
3.979069
4.001741
0.994334
if self._pid and inhibit != self._inhibited: os.kill(self._pid, signal.SIGUSR1) self._inhibited = inhibit
def set_inhibit(self, inhibit)
Set inhibition state
4.05702
4.768843
0.850735
if self.inhibit: self._controller.set_inhibit(False) self.inhibit = False else: self._controller.set_inhibit(True) self.inhibit = True
def toggle_inhibit(self)
Enable/disable redshift
2.12097
2.253587
0.941153
if not enable_shell and isinstance(command, str): command = shlex.split(command) returncode = None stderr = None try: proc = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=enable_shell) out, stderr = proc.communicate() out = out.decode("UTF-8") stderr = stderr.decode("UTF-8") returncode = proc.returncode except OSError as e: out = e.strerror stderr = e.strerror logging.getLogger("i3pystatus.core.command").exception("") except subprocess.CalledProcessError as e: out = e.output logging.getLogger("i3pystatus.core.command").exception("") return CommandResult(returncode, out, stderr)
def run_through_shell(command, enable_shell=False)
Retrieve output of a command. Returns a named tuple with three elements: * ``rc`` (integer) Return code of command. * ``out`` (string) Everything that was printed to stdout. * ``err`` (string) Everything that was printed to stderr. Don't use this function with programs that outputs lots of data since the output is saved in one variable. :param command: A string or a list of strings containing the name and arguments of the program. :param enable_shell: If set ot `True` users default shell will be invoked and given ``command`` to execute. The ``command`` should obviously be a string since shell does all the parsing.
2.234398
2.255664
0.990572
if detach: if not isinstance(command, str): msg = "Detached mode expects a string as command, not {}".format( command) logging.getLogger("i3pystatus.core.command").error(msg) raise AttributeError(msg) command = ["i3-msg", "exec", command] else: if isinstance(command, str): command = shlex.split(command) try: subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except OSError: logging.getLogger("i3pystatus.core.command").exception("") except subprocess.CalledProcessError: logging.getLogger("i3pystatus.core.command").exception("")
def execute(command, detach=False)
Runs a command in background. No output is retrieved. Useful for running GUI applications that would block click events. :param command: A string or a list of strings containing the name and arguments of the program. :param detach: If set to `True` the program will be executed using the `i3-msg` command. As a result the program is executed independent of i3pystatus as a child of i3 process. Because of how i3-msg parses its arguments the type of `command` is limited to string in this mode.
2.579935
2.266894
1.138092
raw_colors = [c.hex for c in list(Color(start_color).range_to(Color(end_color), quantity))] colors = [] for color in raw_colors: # i3bar expects the full Hex value but for some colors the colour # module only returns partial values. So we need to convert these colors to the full # Hex value. if len(color) == 4: fixed_color = "#" for c in color[1:]: fixed_color += c * 2 colors.append(fixed_color) else: colors.append(color) return colors
def get_hex_color_range(start_color, end_color, quantity)
Generates a list of quantity Hex colors from start_color to end_color. :param start_color: Hex or plain English color for start of range :param end_color: Hex or plain English color for end of range :param quantity: Number of colours to return :return: A list of Hex color values
4.689645
4.766494
0.983877
index = int(self.percentage(value, upper_limit)) if index >= len(colors): return colors[-1] elif index < 0: return colors[0] else: return colors[index]
def get_gradient(self, value, colors, upper_limit=100)
Map a value to a color :param value: Some value :return: A Hex color code
2.729441
3.000662
0.909613
if not callable(method) or not hasattr(method, "__name__"): return False if inspect.ismethod(method): return method.__self__ is object for cls in inspect.getmro(object.__class__): if cls.__dict__.get(method.__name__, None) is method: return True return False
def is_method_of(method, object)
Decide whether ``method`` is contained within the MRO of ``object``.
2.084105
1.980882
1.052109
actions = ['leftclick', 'middleclick', 'rightclick', 'upscroll', 'downscroll'] try: action = actions[button - 1] except (TypeError, IndexError): self.__log_button_event(button, None, None, "Other button") action = "otherclick" m_click = self.__multi_click with m_click.lock: double = m_click.check_double(button) double_action = 'double%s' % action if double: action = double_action # Get callback function cb = getattr(self, 'on_%s' % action, None) double_handler = getattr(self, 'on_%s' % double_action, None) delay_execution = (not double and double_handler) if delay_execution: m_click.set_timer(button, cb, **kwargs) else: self.__button_callback_handler(button, cb, **kwargs)
def on_click(self, button, **kwargs)
Maps a click event with its associated callback. Currently implemented events are: ============ ================ ========= Event Callback setting Button ID ============ ================ ========= Left click on_leftclick 1 Middle click on_middleclick 2 Right click on_rightclick 3 Scroll up on_upscroll 4 Scroll down on_downscroll 5 Others on_otherclick > 5 ============ ================ ========= The action is determined by the nature (type and value) of the callback setting in the following order: 1. If null callback (``None``), no action is taken. 2. If it's a `python function`, call it and pass any additional arguments. 3. If it's name of a `member method` of current module (string), call it and pass any additional arguments. 4. If the name does not match with `member method` name execute program with such name. .. seealso:: :ref:`callbacks` for more information about callback settings and examples. :param button: The ID of button event received from i3bar. :param kwargs: Further information received from i3bar like the positions of the mouse where the click occured. :return: Returns ``True`` if a valid callback action was executed. ``False`` otherwise.
4.692181
4.181059
1.122247
def replace(s): s = s.split("&") out = s[0] for i in range(len(s) - 1): if s[i + 1].startswith("amp;"): out += "&" + s[i + 1] else: out += "&amp;" + s[i + 1] return out if "full_text" in self.output.keys(): self.output["full_text"] = replace(self.output["full_text"]) if "short_text" in self.output.keys(): self.output["short_text"] = replace(self.output["short_text"])
def text_to_pango(self)
Replaces all ampersands in `full_text` and `short_text` attributes of `self.output` with `&amp;`. It is called internally when pango markup is used. Can be called multiple times (`&amp;` won't change to `&amp;amp;`).
2.2605
1.873642
1.206474
unit = 'bps' kilo = 1000 mega = 1000000 giga = 1000000000 bps = 0 if self.units == 'bytes' or self.units == 'B': unit = 'Bps' kilo = 8000 mega = 8000000 giga = 8000000000 if n < kilo: bps = float(n) if n >= kilo and n < mega: unit = "K" + unit bps = float(n / 1024.0) if n >= mega and n < giga: unit = "M" + unit bps = float(n / (1024.0 * 1024.0)) if n >= giga: unit = "G" + unit bps = float(n / (1024.0 * 1024.0 * 1024.0)) return bps, unit
def form_b(self, n: float)->tuple
formats a bps as bps/kbps/mbps/gbps etc handles whether its meant to be in bytes :param n: input float :rtype tuple: :return: tuple of float-number of mbps etc, str-units
1.816188
1.707698
1.06353
user_backend = settings_source.get('keyring_backend') found_settings = dict() for setting_name in self.__PROTECTED_SETTINGS: # Nothing to do if the setting is already defined. if settings_source.get(setting_name): continue setting = None identifier = "%s.%s" % (self.__name__, setting_name) if hasattr(self, 'required') and setting_name in getattr(self, 'required'): setting = self.get_setting_from_keyring(identifier, user_backend) elif hasattr(self, setting_name): setting = self.get_setting_from_keyring(identifier, user_backend) if setting: found_settings.update({setting_name: setting}) return found_settings
def get_protected_settings(self, settings_source)
Attempt to retrieve protected settings from keyring if they are not already set.
3.098937
2.923457
1.060025
# If a custom keyring backend has been defined, use it. if keyring_backend: return keyring_backend.get_password(setting_identifier, getpass.getuser()) # Otherwise try and use default keyring. try: import keyring except ImportError: pass else: return keyring.get_password(setting_identifier, getpass.getuser())
def get_setting_from_keyring(self, setting_identifier, keyring_backend=None)
Retrieves a protected setting from keyring :param setting_identifier: must be in the format package.module.Class.setting
2.472275
2.615744
0.945152
from i3pystatus.text import Text if not module: return # Merge the module's hints with the default hints # and overwrite any duplicates with the hint from the module hints = self.default_hints.copy() if self.default_hints else {} hints.update(kwargs.get('hints', {})) if hints: kwargs['hints'] = hints try: return self.modules.append(module, *args, **kwargs) except Exception as e: log.exception(e) return self.modules.append(Text( color="#FF0000", text="{i3py_mod}: Fatal Error - {ex}({msg})".format( i3py_mod=module, ex=e.__class__.__name__, msg=e ) ))
def register(self, module, *args, **kwargs)
Register a new module. :param module: Either a string module name, or a module class, or a module instance (in which case args and kwargs are invalid). :param kwargs: Settings for the module. :returns: module instance
3.944804
4.095493
0.963206
if self.click_events: self.command_endpoint.start() for j in io.JSONIO(self.io).read(): for module in self.modules: module.inject(j)
def run(self)
Run main loop.
16.34692
15.580559
1.049187
cpus_offline = 0 if self.file == '/sys': with open('/sys/devices/system/cpu/online') as f: line = f.readline() cpus_online = [int(cpu) for cpu in line.split(',') if cpu.find('-') < 0] cpus_online_range = [cpu_range for cpu_range in line.split(',') if cpu_range.find('-') > 0] for cpu_range in cpus_online_range: cpus_online += [cpu for cpu in range(int(cpu_range.split('-')[0]), int(cpu_range.split('-')[1]) + 1)] mhz_values = [0.0 for cpu in range(max(cpus_online) + 1)] ghz_values = [0.0 for cpu in range(max(cpus_online) + 1)] for cpu in cpus_online: with open('/sys/devices/system/cpu/cpu{}/cpufreq/scaling_cur_freq'.format(cpu)) as f: line = f.readline() mhz_values[cpu] = float(line.rstrip()) / 1000.0 ghz_values[cpu] = float(line.rstrip()) / 1000000.0 cpus_offline = mhz_values.count(0.0) else: with open(self.file) as f: mhz_values = [float(line.split(':')[1]) for line in f if line.startswith('cpu MHz')] ghz_values = [value / 1000.0 for value in mhz_values] mhz = {"core{}".format(key): "{0:4.3f}".format(value) for key, value in enumerate(mhz_values)} ghz = {"core{}g".format(key): "{0:1.2f}".format(value) for key, value in enumerate(ghz_values)} cdict = mhz.copy() cdict.update(ghz) cdict['avg'] = "{0:4.3f}".format(sum(mhz_values) / (len(mhz_values) - cpus_offline)) cdict['avgg'] = "{0:1.2f}".format(sum(ghz_values) / (len(ghz_values) - cpus_offline), 2) return cdict
def createvaluesdict(self)
function processes the /proc/cpuinfo file, use file=/sys to use kernel >=4.13 location :return: dictionary used as the full-text output for the module
2.020411
1.933139
1.045145
self.url = self.url.format(host=self.host, port=self.port, api_key=self.api_key)
def init(self)
Initialize the URL used to connect to SABnzbd.
3.874202
3.019638
1.283002
try: answer = urlopen(self.url + "&mode=queue").read().decode() except (HTTPError, URLError) as error: self.output = { "full_text": str(error.reason), "color": "#FF0000" } return answer = json.loads(answer) # if answer["status"] exists and is False, an error occured if not answer.get("status", True): self.output = { "full_text": answer["error"], "color": "#FF0000" } return queue = answer["queue"] self.status = queue["status"] if self.is_paused(): color = self.color_paused elif self.is_downloading(): color = self.color_downloading else: color = self.color if self.is_downloading(): full_text = self.format.format(**queue) else: full_text = self.format_paused.format(**queue) self.output = { "full_text": full_text, "color": color }
def run(self)
Connect to SABnzbd and get the data.
2.600592
2.45015
1.061401
if self.is_paused(): urlopen(self.url + "&mode=resume") else: urlopen(self.url + "&mode=pause")
def pause_resume(self)
Toggle between pausing or resuming downloading.
4.211478
3.484768
1.208539
webbrowser.open( "http://{host}:{port}/".format(host=self.host, port=self.port))
def open_browser(self)
Open the URL of SABnzbd inside a browser.
3.841782
3.770305
1.018958
params = ["memory.total", "memory.free", "memory.used", "temperature.gpu", "fan.speed", "utilization.gpu", "utilization.memory"] try: output = subprocess.check_output(["nvidia-smi", "--query-gpu={}".format(','.join(params)), "--format=csv,noheader,nounits"]) except FileNotFoundError: raise Exception("No nvidia-smi") except subprocess.CalledProcessError: raise Exception("nvidia-smi call failed") output = output.decode('utf-8').split("\n")[gpu_number].strip() values = output.split(", ") # If value contains 'not' - it is not supported for this GPU (in fact, for now nvidia-smi returns '[Not Supported]') values = [None if ("not" in value.lower()) else int(value) for value in values] return GPUUsageInfo(*values)
def query_nvidia_smi(gpu_number) -> GPUUsageInfo
:return: all memory fields are in megabytes, temperature in degrees celsius, fan speed is integer percent from 0 to 100 inclusive, usage_gpu and usage_mem are integer percents from 0 to 100 inclusive (usage_mem != used_mem, usage_mem is about read/write access load) read more in 'nvidia-smi --help-query-gpu'. Any field can be None if such information is not supported by nvidia-smi for current GPU Returns None if call failed (no nvidia-smi or query format was changed) Raises exception with readable comment
3.45948
3.250893
1.064163
if button in (4, 5): return super().on_click(button, **kwargs) else: activemodule = self.get_active_module() if not activemodule: return return activemodule.on_click(button, **kwargs)
def on_click(self, button, **kwargs)
Capture scrollup and scorlldown to move in groups Pass everthing else to the module itself
3.445566
2.834815
1.215446
''' Get the system timezone for use when no timezone is explicitly provided Requires pytz, if not available then no timezone will be set when not explicitly provided. ''' if not HAS_PYTZ: return None def _etc_localtime(): try: with open('/etc/localtime', 'rb') as fp: return pytz.tzfile.build_tzinfo('system', fp) except OSError as exc: if exc.errno != errno.ENOENT: self.logger.error( 'Unable to read from /etc/localtime: %s', exc.strerror ) except pytz.UnknownTimeZoneError: self.logger.error( '/etc/localtime contains unrecognized tzinfo' ) return None def _etc_timezone(): try: with open('/etc/timezone', 'r') as fp: tzname = fp.read().strip() return pytz.timezone(tzname) except OSError as exc: if exc.errno != errno.ENOENT: self.logger.error( 'Unable to read from /etc/localtime: %s', exc.strerror ) except pytz.UnknownTimeZoneError: self.logger.error( '/etc/timezone contains unrecognized timezone \'%s\'', tzname ) return None return _etc_localtime() or _etc_timezone()
def _get_system_tz(self)
Get the system timezone for use when no timezone is explicitly provided Requires pytz, if not available then no timezone will be set when not explicitly provided.
2.484309
1.961627
1.266453
''' Check the weather using the configured backend ''' self.output['full_text'] = \ self.refresh_icon + self.output.get('full_text', '') self.backend.check_weather() self.refresh_display()
def check_weather(self)
Check the weather using the configured backend
10.200718
6.597403
1.546172
''' Disambiguate similarly-named weather conditions, and return the icon and color that match. ''' if condition not in self.color_icons: # Check for similarly-named conditions if no exact match found condition_lc = condition.lower() if 'cloudy' in condition_lc or 'clouds' in condition_lc: if 'partly' in condition_lc: condition = 'Partly Cloudy' else: condition = 'Cloudy' elif condition_lc == 'overcast': condition = 'Cloudy' elif 'thunder' in condition_lc or 't-storm' in condition_lc: condition = 'Thunderstorm' elif 'snow' in condition_lc: condition = 'Snow' elif 'rain' in condition_lc or 'showers' in condition_lc: condition = 'Rainy' elif 'sunny' in condition_lc: condition = 'Sunny' elif 'clear' in condition_lc or 'fair' in condition_lc: condition = 'Fair' elif 'fog' in condition_lc: condition = 'Fog' return self.color_icons['default'] \ if condition not in self.color_icons \ else self.color_icons[condition]
def get_color_data(self, condition)
Disambiguate similarly-named weather conditions, and return the icon and color that match.
2.660882
2.157565
1.23328
timings = {} with open('/proc/stat', 'r') as file_obj: for line in file_obj: if 'cpu' in line: line = line.strip().split() timings[line[0]] = [int(x) for x in line[1:]] return timings
def get_cpu_timings(self)
reads and parses /proc/stat returns dictionary with all available cores including global average
2.450121
2.269473
1.079599
diff_total = total - self.prev_total[cpu] diff_busy = busy - self.prev_busy[cpu] self.prev_total[cpu] = total self.prev_busy[cpu] = busy if diff_total == 0: return 0 else: return int(diff_busy / diff_total * 100)
def calculate_usage(self, cpu, total, busy)
calculates usage
1.995601
2.002212
0.996699
format_string = " " core_strings = [] for core, usage in usage.items(): if core == 'usage_cpu' and self.exclude_average: continue elif core == 'usage': continue core = core.replace('usage_', '') string = self.formatter.format(self.format_all, core=core, usage=usage) core_strings.append(string) core_strings = sorted(core_strings) return format_string.join(core_strings)
def gen_format_all(self, usage)
generates string for format all
4.676499
4.591169
1.018586
usage = {} for cpu, timings in self.get_cpu_timings().items(): cpu_total = sum(timings) del timings[3:5] cpu_busy = sum(timings) cpu_usage = self.calculate_usage(cpu, cpu_total, cpu_busy) usage['usage_' + cpu] = cpu_usage # for backward compatibility usage['usage'] = usage['usage_cpu'] return usage
def get_usage(self)
parses /proc/stat and calcualtes total and busy time (more specific USER_HZ see man 5 proc for further informations )
4.189617
3.528592
1.187334
now = datetime.datetime.now(tz=pytz.UTC) try: now, later = self.get_timerange_formatted(now) events_result = self.service.events().list( calendarId='primary', timeMin=now, timeMax=later, maxResults=10, singleEvents=True, orderBy='startTime', timeZone='utc' ).execute() self.events.clear() for event in events_result.get('items', []): self.events.append(GoogleCalendarEvent(event)) except HttpError as e: if e.resp.status in (500, 503): self.logger.warn("GoogleCalendar received %s while retrieving events" % e.resp.status) else: raise
def refresh_events(self)
Retrieve the next N events from Google.
2.673429
2.587193
1.033332
later = now + datetime.timedelta(days=self.days) return now.isoformat(), later.isoformat()
def get_timerange_formatted(self, now)
Return two ISO8601 formatted date strings, one for timeMin, the other for timeMax (to be consumed by get_events)
5.049756
3.611017
1.39843
if string.startswith(prefix): return string[len(prefix):] return string
def lchop(string, prefix)
Removes a prefix from string :param string: String, possibly prefixed with prefix :param prefix: Prefix to remove from string :returns: string without the prefix
2.425826
3.89094
0.623455
while iterable: item = iterable.pop() if predicate(item): yield item else: break
def popwhile(predicate, iterable)
Generator function yielding items of iterable while predicate holds for each item :param predicate: function taking an item returning bool :param iterable: iterable :returns: iterable (generator function)
2.788182
4.657202
0.598682
if places is None: for key, value in dic.items(): dic[key] = round(value) else: for key, value in dic.items(): dic[key] = round(value, places)
def round_dict(dic, places)
Rounds all values in a dict containing only numeric types to `places` decimal places. If places is None, round to INT.
1.757688
1.66704
1.054377
l = list(l) i = 0 while i < len(l): while isinstance(l[i], list): if not l[i]: l.pop(i) i -= 1 break else: l[i:i + 1] = l[i] i += 1 return l
def flatten(l)
Flattens a hierarchy of nested lists into a single list containing all elements in order :param l: list of arbitrary types and lists :returns: list of arbitrary types
1.841384
2.382604
0.772845
def build_stack(string): class Token: string = "" class OpeningBracket(Token): pass class ClosingBracket(Token): pass class String(Token): def __init__(self, str): self.string = str TOKENS = { "[": OpeningBracket, "]": ClosingBracket, } stack = [] # Index of next unconsumed char next = 0 # Last consumed char prev = "" # Current char char = "" # Current level level = 0 while next < len(string): prev = char char = string[next] next += 1 if prev != "\\" and char in TOKENS: token = TOKENS[char]() token.index = next if char == "]": level -= 1 token.level = level if char == "[": level += 1 stack.append(token) else: if stack and isinstance(stack[-1], String): stack[-1].string += char else: token = String(char) token.level = level stack.append(token) return stack def build_tree(items, level=0): subtree = [] while items: nested = [] while items[0].level > level: nested.append(items.pop(0)) if nested: subtree.append(build_tree(nested, level + 1)) item = items.pop(0) if item.string: string = item.string if level == 0: subtree.append(string.format(**kwargs)) else: fields = re.findall(r"({(\w+)[^}]*})", string) successful_fields = 0 for fieldspec, fieldname in fields: if kwargs.get(fieldname, False): successful_fields += 1 if successful_fields == len(fields): subtree.append(string.format(**kwargs)) else: return [] return subtree def merge_tree(items): return "".join(flatten(items)).replace(r"\]", "]").replace(r"\[", "[") stack = build_stack(string) tree = build_tree(stack, 0) return merge_tree(tree)
def formatp(string, **kwargs)
Function for advanced format strings with partial formatting This function consumes format strings with groups enclosed in brackets. A group enclosed in brackets will only become part of the result if all fields inside the group evaluate True in boolean contexts. Groups can be nested. The fields in a nested group do not count as fields in the enclosing group, i.e. the enclosing group will evaluate to an empty string even if a nested group would be eligible for formatting. Nesting is thus equivalent to a logical or of all enclosing groups with the enclosed group. Escaped brackets, i.e. \\\\[ and \\\\] are copied verbatim to output. :param string: Format string :param kwargs: keyword arguments providing data for the format string :returns: Formatted string
2.711257
2.662728
1.018226
def decorator(method): @functools.wraps(method) def wrapper(*args, **kwargs): if predicate(): return method(*args, **kwargs) return None return wrapper return decorator
def require(predicate)
Decorator factory for methods requiring a predicate. If the predicate is not fulfilled during a method call, the method call is skipped and None is returned. :param predicate: A callable returning a truth value :returns: Method decorator .. seealso:: :py:class:`internet`
2.68141
2.900826
0.924361
values = [float(n) for n in values] mn, mx = min(values), max(values) mn = mn if lower_limit is None else min(mn, float(lower_limit)) mx = mx if upper_limit is None else max(mx, float(upper_limit)) extent = mx - mn if style == 'blocks': bar = '_▁▂▃▄▅▆▇█' bar_count = len(bar) - 1 if extent == 0: graph = '_' * len(values) else: graph = ''.join(bar[int((n - mn) / extent * bar_count)] for n in values) elif style in ['braille-fill', 'braille-peak', 'braille-snake']: # idea from https://github.com/asciimoo/drawille # unicode values from http://en.wikipedia.org/wiki/Braille vpad = values if len(values) % 2 == 0 else values + [mn] vscale = [round(4 * (vp - mn) / extent) for vp in vpad] l = len(vscale) // 2 # do the 2-character collapse separately for clarity if 'fill' in style: vbits = [[0, 0x40, 0x44, 0x46, 0x47][vs] for vs in vscale] elif 'peak' in style: vbits = [[0, 0x40, 0x04, 0x02, 0x01][vs] for vs in vscale] else: assert('snake' in style) # there are a few choices for what to put last in vb2. # arguable vscale[-1] from the _previous_ call is best. vb2 = [vscale[0]] + vscale + [0] vbits = [] for i in range(1, l + 1): c = 0 for j in range(min(vb2[i - 1], vb2[i], vb2[i + 1]), vb2[i] + 1): c |= [0, 0x40, 0x04, 0x02, 0x01][j] vbits.append(c) # 2-character collapse graph = '' for i in range(0, l, 2): b1 = vbits[i] b2 = vbits[i + 1] if b2 & 0x40: b2 = b2 - 0x30 b2 = b2 << 3 graph += chr(0x2800 + b1 + b2) else: raise NotImplementedError("Graph drawing style '%s' unimplemented." % style) return graph
def make_graph(values, lower_limit=0.0, upper_limit=100.0, style="blocks")
Draws a graph made of unicode characters. :param values: An array of values to graph. :param lower_limit: Minimum value for the y axis (or None for dynamic). :param upper_limit: Maximum value for the y axis (or None for dynamic). :param style: Drawing style ('blocks', 'braille-fill', 'braille-peak', or 'braille-snake'). :returns: Bar as a string
3.306405
3.101898
1.06593
bar = ' _▁▂▃▄▅▆▇█' percentage //= 10 percentage = int(percentage) if percentage < 0: output = bar[0] elif percentage >= len(bar): output = bar[-1] else: output = bar[percentage] return output * width
def make_vertical_bar(percentage, width=1)
Draws a vertical bar made of unicode characters. :param value: A value between 0 and 100 :param width: How many characters wide the bar should be. :returns: Bar as a String
3.11636
3.617886
0.861376
bars = [' ', '▏', '▎', '▍', '▌', '▋', '▋', '▊', '▊', '█'] tens = int(percentage / 10) ones = int(percentage) - tens * 10 result = tens * '█' if(ones >= 1): result = result + bars[ones] result = result + (10 - len(result)) * ' ' return result
def make_bar(percentage)
Draws a bar made of unicode box characters. :param percentage: A value between 0 and 100 :returns: Bar as a string
2.920274
2.880047
1.013968
# Handle edge cases first if lower_bound >= upper_bound: raise Exception("Invalid upper/lower bounds") elif number <= lower_bound: return glyphs[0] elif number >= upper_bound: return glyphs[-1] if enable_boundary_glyphs: # Trim first and last items from glyphs as boundary conditions already # handled glyphs = glyphs[1:-1] # Determine a value 0 - 1 that represents the position in the range adjusted_value = (number - lower_bound) / (upper_bound - lower_bound) # Determine the closest glyph to show # As we have positive indices, we can use int for floor rounding # Adjusted_value should always be < 1 glyph_index = int(len(glyphs) * adjusted_value) return glyphs[glyph_index]
def make_glyph(number, glyphs="▁▂▃▄▅▆▇█", lower_bound=0, upper_bound=100, enable_boundary_glyphs=False)
Returns a single glyph from the list of glyphs provided relative to where the number is in the range (by default a percentage value is expected). This can be used to create an icon based representation of a value with an arbitrary number of glyphs (e.g. 4 different battery status glyphs for battery percentage level). :param number: The number being represented. By default a percentage value\ between 0 and 100 (but any range can be defined with lower_bound and\ upper_bound). :param glyphs: Either a string of glyphs, or an array of strings. Using an array\ of strings allows for additional pango formatting to be applied such that\ different colors could be shown for each glyph). :param lower_bound: A custom lower bound value for the range. :param upper_bound: A custom upper bound value for the range. :param enable_boundary_glyphs: Whether the first and last glyphs should be used\ for the special case of the number being <= lower_bound or >= upper_bound\ respectively. :returns: The glyph found to represent the number
4.201514
4.236536
0.991733
from urllib.parse import urlparse scheme = urlparse(url_or_command).scheme if scheme == 'http' or scheme == 'https': import webbrowser import os # webbrowser.open() sometimes prints a message for some reason and confuses i3 # Redirect stdout briefly to prevent this from happening. savout = os.dup(1) os.close(1) os.open(os.devnull, os.O_RDWR) try: webbrowser.open(url_or_command) finally: os.dup2(savout, 1) else: import subprocess subprocess.Popen(url_or_command, shell=True)
def user_open(url_or_command)
Open the specified paramater in the web browser if a URL is detected, othewrise pass the paramater to the shell as a subprocess. This function is inteded to bu used in on_leftclick/on_rightclick callbacks. :param url_or_command: String containing URL or command
3.008421
3.20529
0.93858
@functools.wraps(function) def call_wrapper(*args, **kwargs): stack = inspect.stack() caller_frame_info = stack[1] self = caller_frame_info[0].f_locals["self"] # not completly sure whether this is necessary # see note in Python docs about stack frames del stack function(self, *args, **kwargs) return call_wrapper
def get_module(function)
Function decorator for retrieving the ``self`` argument from the stack. Intended for use with callbacks that need access to a modules variables, for example: .. code:: python from i3pystatus import Status, get_module from i3pystatus.core.command import execute status = Status(...) # other modules etc. @get_module def display_ip_verbose(module): execute('sh -c "ip addr show dev {dev} | xmessage -file -"'.format(dev=module.interface)) status.register("network", interface="wlan1", on_leftclick=display_ip_verbose)
4.165334
4.118412
1.011393
for _id in range(2, 25): setattr(self, TypeKind.from_id(_id).name, self._handle_fundamental_types)
def init_fundamental_types(self)
Registers all fundamental typekind handlers
9.771449
5.863558
1.666471
ctypesname = self.get_ctypes_name(typ.kind) if typ.kind == TypeKind.VOID: size = align = 1 else: size = typ.get_size() align = typ.get_align() return typedesc.FundamentalType(ctypesname, size, align)
def _handle_fundamental_types(self, typ)
Handles POD types nodes. see init_fundamental_types for the registration.
4.739443
4.443765
1.066538
_decl = _cursor_type.get_declaration() name = self.get_unique_name(_decl) if self.is_registered(name): obj = self.get_registered(name) else: log.debug('Was in TYPEDEF but had to parse record declaration for %s', name) obj = self.parse_cursor(_decl) return obj
def TYPEDEF(self, _cursor_type)
Handles TYPEDEF statement.
6.171538
6.103506
1.011146
_decl = _cursor_type.get_declaration() name = self.get_unique_name(_decl) if self.is_registered(name): obj = self.get_registered(name) else: log.warning('Was in ENUM but had to parse record declaration ') obj = self.parse_cursor(_decl) return obj
def ENUM(self, _cursor_type)
Handles ENUM typedef.
7.347728
7.289503
1.007988
# # FIXME catch InvalidDefinitionError and return a void * # # # we shortcut to canonical typedefs and to pointee canonical defs comment = None _type = _cursor_type.get_pointee().get_canonical() _p_type_name = self.get_unique_name(_type) # get pointer size size = _cursor_type.get_size() # not size of pointee align = _cursor_type.get_align() log.debug( "POINTER: size:%d align:%d typ:%s", size, align, _type.kind) if self.is_fundamental_type(_type): p_type = self.parse_cursor_type(_type) elif self.is_pointer_type(_type) or self.is_array_type(_type): p_type = self.parse_cursor_type(_type) elif _type.kind == TypeKind.FUNCTIONPROTO: p_type = self.parse_cursor_type(_type) elif _type.kind == TypeKind.FUNCTIONNOPROTO: p_type = self.parse_cursor_type(_type) else: # elif _type.kind == TypeKind.RECORD: # check registration decl = _type.get_declaration() decl_name = self.get_unique_name(decl) # Type is already defined OR will be defined later. if self.is_registered(decl_name): p_type = self.get_registered(decl_name) else: # forward declaration, without looping log.debug( 'POINTER: %s type was not previously declared', decl_name) try: p_type = self.parse_cursor(decl) except InvalidDefinitionError as e: # no declaration in source file. Fake a void * p_type = typedesc.FundamentalType('None', 1, 1) comment = "InvalidDefinitionError" log.debug("POINTER: pointee type_name:'%s'", _p_type_name) # return the pointer obj = typedesc.PointerType(p_type, size, align) obj.location = p_type.location if comment is not None: obj.comment = comment return obj
def POINTER(self, _cursor_type)
Handles POINTER types.
4.359155
4.355593
1.000818
# The element type has been previously declared # we need to get the canonical typedef, in some cases _type = _cursor_type.get_canonical() size = _type.get_array_size() if size == -1 and _type.kind == TypeKind.INCOMPLETEARRAY: size = 0 # FIXME: Incomplete Array handling at end of record. # https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html # FIXME VARIABLEARRAY DEPENDENTSIZEDARRAY _array_type = _type.get_array_element_type() # .get_canonical() if self.is_fundamental_type(_array_type): _subtype = self.parse_cursor_type(_array_type) elif self.is_pointer_type(_array_type): # code.interact(local=locals()) # pointers to POD have no declaration ?? # FIXME test_struct_with_pointer x_n_t g[1] _subtype = self.parse_cursor_type(_array_type) elif self.is_array_type(_array_type): _subtype = self.parse_cursor_type(_array_type) else: _subtype_decl = _array_type.get_declaration() _subtype = self.parse_cursor(_subtype_decl) # if _subtype_decl.kind == CursorKind.NO_DECL_FOUND: # pass #_subtype_name = self.get_unique_name(_subtype_decl) #_subtype = self.get_registered(_subtype_name) obj = typedesc.ArrayType(_subtype, size) obj.location = _subtype.location return obj
def _array_handler(self, _cursor_type)
Handles all array types. Resolves it's element type and makes a Array typedesc.
5.118005
4.968554
1.030079
# id, returns, attributes returns = _cursor_type.get_result() # if self.is_fundamental_type(returns): returns = self.parse_cursor_type(returns) attributes = [] obj = typedesc.FunctionType(returns, attributes) for i, _attr_type in enumerate(_cursor_type.argument_types()): arg = typedesc.Argument( "a%d" % (i), self.parse_cursor_type(_attr_type)) obj.add_argument(arg) self.set_location(obj, None) return obj
def FUNCTIONPROTO(self, _cursor_type)
Handles function prototype.
4.93395
4.865825
1.014001
# id, returns, attributes returns = _cursor_type.get_result() # if self.is_fundamental_type(returns): returns = self.parse_cursor_type(returns) attributes = [] obj = typedesc.FunctionType(returns, attributes) # argument_types cant be asked. no arguments. self.set_location(obj, None) return obj
def FUNCTIONNOPROTO(self, _cursor_type)
Handles function with no prototype.
11.115332
10.86456
1.023082
_decl = _cursor_type.get_declaration() name = self.get_unique_name(_decl) # _cursor) if self.is_registered(name): obj = self.get_registered(name) else: obj = self.parse_cursor(_decl) return obj
def UNEXPOSED(self, _cursor_type)
Handles unexposed types. Returns the canonical type instead.
5.574167
5.580581
0.998851
values = [self.parse_cursor(child) for child in list(cursor.get_children())] return values
def INIT_LIST_EXPR(self, cursor)
Returns a list of literal values.
7.559251
6.211029
1.217069
name = cursor.displayname value = cursor.enum_value pname = self.get_unique_name(cursor.semantic_parent) parent = self.get_registered(pname) obj = typedesc.EnumValue(name, value, parent) parent.add_value(obj) return obj
def ENUM_CONSTANT_DECL(self, cursor)
Gets the enumeration values
5.742336
6.121973
0.937988
name = self.get_unique_name(cursor) if self.is_registered(name): return self.get_registered(name) align = cursor.type.get_align() size = cursor.type.get_size() obj = self.register(name, typedesc.Enumeration(name, size, align)) self.set_location(obj, cursor) self.set_comment(obj, cursor) # parse all children for child in cursor.get_children(): self.parse_cursor(child) # FIXME, where is the starElement return obj
def ENUM_DECL(self, cursor)
Gets the enumeration declaration.
4.880236
4.606656
1.059388
# FIXME to UT name = self.get_unique_name(cursor) if self.is_registered(name): return self.get_registered(name) returns = self.parse_cursor_type(cursor.type.get_result()) attributes = [] extern = False obj = typedesc.Function(name, returns, attributes, extern) for arg in cursor.get_arguments(): arg_obj = self.parse_cursor(arg) # if arg_obj is None: # code.interact(local=locals()) obj.add_argument(arg_obj) # code.interact(local=locals()) self.register(name, obj) self.set_location(obj, cursor) self.set_comment(obj, cursor) return obj
def FUNCTION_DECL(self, cursor)
Handles function declaration
3.814564
3.772104
1.011256
# try and get the type. If unexposed, The canonical type will work. _type = cursor.type _name = cursor.spelling if (self.is_array_type(_type) or self.is_fundamental_type(_type) or self.is_pointer_type(_type) or self.is_unexposed_type(_type)): _argtype = self.parse_cursor_type(_type) else: # FIXME: Which UT/case ? size_t in stdio.h for example. _argtype_decl = _type.get_declaration() _argtype_name = self.get_unique_name(_argtype_decl) if not self.is_registered(_argtype_name): log.info('This param type is not declared: %s', _argtype_name) _argtype = self.parse_cursor_type(_type) else: _argtype = self.get_registered(_argtype_name) obj = typedesc.Argument(_name, _argtype) self.set_location(obj, cursor) self.set_comment(obj, cursor) return obj
def PARM_DECL(self, cursor)
Handles parameter declarations.
4.518559
4.527758
0.997968
name = self.get_unique_name(cursor) # if the typedef is known, get it from cache if self.is_registered(name): return self.get_registered(name) # use the canonical type directly. _type = cursor.type.get_canonical() log.debug("TYPEDEF_DECL: name:%s", name) log.debug("TYPEDEF_DECL: typ.kind.displayname:%s", _type.kind) # For all types (array, fundament, pointer, others), get the type p_type = self.parse_cursor_type(_type) if not isinstance(p_type, typedesc.T): log.error( 'Bad TYPEREF parsing in TYPEDEF_DECL: %s', _type.spelling) # import code # code.interact(local=locals()) raise TypeError( 'Bad TYPEREF parsing in TYPEDEF_DECL: %s' % (_type.spelling)) # register the type obj = self.register(name, typedesc.Typedef(name, p_type)) self.set_location(obj, cursor) self.set_comment(obj, cursor) return obj
def TYPEDEF_DECL(self, cursor)
Handles typedef statements. Gets Type from cache if we known it. Add it to cache otherwise. # typedef of an enum
5.106736
4.88504
1.045383
# get the name name = self.get_unique_name(cursor) log.debug('VAR_DECL: name: %s', name) # Check for a previous declaration in the register if self.is_registered(name): return self.get_registered(name) # get the typedesc object _type = self._VAR_DECL_type(cursor) # transform the ctypes values into ctypeslib init_value = self._VAR_DECL_value(cursor, _type) # finished log.debug('VAR_DECL: _type:%s', _type.name) log.debug('VAR_DECL: _init:%s', init_value) log.debug('VAR_DECL: location:%s', getattr(cursor, 'location')) obj = self.register(name, typedesc.Variable(name, _type, init_value)) self.set_location(obj, cursor) self.set_comment(obj, cursor) return True
def VAR_DECL(self, cursor)
Handles Variable declaration.
4.430629
4.437717
0.998403
# Get the type _ctype = cursor.type.get_canonical() log.debug('VAR_DECL: _ctype: %s ', _ctype.kind) # FIXME: Need working int128, long_double, etc. if self.is_fundamental_type(_ctype): ctypesname = self.get_ctypes_name(_ctype.kind) _type = typedesc.FundamentalType(ctypesname, 0, 0) elif self.is_unexposed_type(_ctype): st = 'PATCH NEEDED: %s type is not exposed by clang' % ( self.get_unique_name(cursor)) log.error(st) raise RuntimeError(st) elif self.is_array_type(_ctype) or _ctype.kind == TypeKind.RECORD: _type = self.parse_cursor_type(_ctype) elif self.is_pointer_type(_ctype): # for example, extern Function pointer if self.is_unexposed_type(_ctype.get_pointee()): _type = self.parse_cursor_type( _ctype.get_canonical().get_pointee()) elif _ctype.get_pointee().kind == TypeKind.FUNCTIONPROTO: # Function pointers # Arguments are handled in here _type = self.parse_cursor_type(_ctype.get_pointee()) else: # Pointer to Fundamental types, structs.... _type = self.parse_cursor_type(_ctype) else: # What else ? raise NotImplementedError( 'What other type of variable? %s' % (_ctype.kind)) log.debug('VAR_DECL: _type: %s ', _type) return _type
def _VAR_DECL_type(self, cursor)
Generates a typedesc object from a Variable declaration.
4.09681
4.08815
1.002119
# always expect list [(k,v)] as init value.from list(cursor.get_children()) # get the init_value and special cases init_value = self._get_var_decl_init_value(cursor.type, list(cursor.get_children())) _ctype = cursor.type.get_canonical() if self.is_unexposed_type(_ctype): # string are not exposed init_value = '%s # UNEXPOSED TYPE. PATCH NEEDED.' % (init_value) elif (self.is_pointer_type(_ctype) and _ctype.get_pointee().kind == TypeKind.FUNCTIONPROTO): # Function pointers argument are handled at type creation time # but we need to put a CFUNCTYPE as a value of the name variable init_value = _type elif self.is_array_type(_ctype): # an integer litteral will be the size # an string litteral will be the value # any list member will be children of a init_list_expr # FIXME Move that code into typedesc def countof(k, l): return [item[0] for item in l].count(k) if (countof(CursorKind.INIT_LIST_EXPR, init_value) == 1): init_value = dict(init_value)[CursorKind.INIT_LIST_EXPR] elif (countof(CursorKind.STRING_LITERAL, init_value) == 1): # we have a initialised c_array init_value = dict(init_value)[CursorKind.STRING_LITERAL] else: # ignore size alone init_value = [] # check the array size versus elements. if _type.size < len(init_value): _type.size = len(init_value) elif init_value == []: # catch case. init_value = None else: log.debug('VAR_DECL: default init_value: %s', init_value) if len(init_value) > 0: init_value = init_value[0][1] return init_value
def _VAR_DECL_value(self, cursor, _type)
Handles Variable value initialization.
6.162146
6.012398
1.024906
# FIXME TU for INIT_LIST_EXPR # FIXME: always return [(child.kind,child.value),...] # FIXME: simplify this redondant code. init_value = [] children = list(children) # weird requirement, list iterator error. log.debug('_get_var_decl_init_value: children #: %d', len(children)) for child in children: # early stop cases. _tmp = None try: _tmp = self._get_var_decl_init_value_single(_ctype, child) except CursorKindException: log.debug( '_get_var_decl_init_value: children init value skip on %s', child.kind) continue if _tmp is not None: init_value.append(_tmp) return init_value
def _get_var_decl_init_value(self, _ctype, children)
Gathers initialisation values by parsing children nodes of a VAR_DECL.
6.565611
6.196085
1.059639
init_value = None # FIXME: always return (child.kind, child.value) log.debug( '_get_var_decl_init_value_single: _ctype: %s Child.kind: %s', _ctype.kind, child.kind) # shorcuts. if not child.kind.is_expression() and not child.kind.is_declaration(): raise CursorKindException(child.kind) if child.kind == CursorKind.CALL_EXPR: raise CursorKindException(child.kind) # POD init values handling. # As of clang 3.3, int, double literals are exposed. # float, long double, char , char* are not exposed directly in level1. # but really it depends... if child.kind.is_unexposed(): # recurse until we find a literal kind init_value = self._get_var_decl_init_value(_ctype, child.get_children()) if len(init_value) == 0: init_value = None elif len(init_value) == 1: init_value = init_value[0] else: log.error('_get_var_decl_init_value_single: Unhandled case') assert len(init_value) <= 1 else: # literal or others _v = self.parse_cursor(child) if isinstance( _v, list) and child.kind not in [CursorKind.INIT_LIST_EXPR, CursorKind.STRING_LITERAL]: log.warning( '_get_var_decl_init_value_single: TOKENIZATION BUG CHECK: %s', _v) _v = _v[0] init_value = (child.kind, _v) log.debug( '_get_var_decl_init_value_single: returns %s', str(init_value)) return init_value
def _get_var_decl_init_value_single(self, _ctype, child)
Handling of a single child for initialization value. Accepted types are expressions and declarations
4.312562
4.273625
1.009111
values = self._literal_handling(cursor) retval = ''.join([str(val) for val in values]) return retval
def _operator_handling(self, cursor)
Returns a string with the literal that are part of the operation.
7.641662
5.59537
1.365712
return self._record_decl(cursor, typedesc.Structure, num)
def STRUCT_DECL(self, cursor, num=None)
Handles Structure declaration. Its a wrapper to _record_decl.
14.450234
7.380996
1.957762
return self._record_decl(cursor, typedesc.Union, num)
def UNION_DECL(self, cursor, num=None)
Handles Union declaration. Its a wrapper to _record_decl.
16.295851
8.082224
2.016258
log.debug('FIXUP_STRUCT: %s %d bits', s.name, s.size * 8) if s.members is None: log.debug('FIXUP_STRUCT: no members') s.members = [] return if s.size == 0: log.debug('FIXUP_STRUCT: struct has size %d', s.size) return # try to fix bitfields without padding first self._fixup_record_bitfields_type(s) # No need to lookup members in a global var. # Just fix the padding members = [] member = None offset = 0 padding_nb = 0 member = None prev_member = None # create padding fields # DEBUG FIXME: why are s.members already typedesc objet ? # fields = self.fields[s.name] for m in s.members: # s.members are strings - NOT # we need to check total size of bitfield, so to choose the right # bitfield type member = m log.debug('Fixup_struct: Member:%s offsetbits:%d->%d expecting offset:%d', member.name, member.offset, member.offset + member.bits, offset) if member.offset < 0: # FIXME INCOMPLETEARRAY (clang bindings?) # All fields have offset == -2. No padding will be done. # But the fields are ordered and code will be produces with typed info. # so in most cases, it will work. if there is a structure with incompletearray # and padding or alignement issue, it will produce wrong results # just exit return if member.offset > offset: # create padding length = member.offset - offset log.debug( 'Fixup_struct: create padding for %d bits %d bytes', length, length // 8) padding_nb = self._make_padding( members, padding_nb, offset, length, prev_member) if member.type is None: log.error('FIXUP_STRUCT: %s.type is None', member.name) members.append(member) offset = member.offset + member.bits prev_member = member # tail padding if necessary if s.size * 8 != offset: length = s.size * 8 - offset log.debug( 'Fixup_struct: s:%d create tail padding for %d bits %d bytes', s.size, length, length // 8) padding_nb = self._make_padding( members, padding_nb, offset, length, prev_member) if len(members) > 0: offset = members[-1].offset + members[-1].bits # go s.members = members log.debug("FIXUP_STRUCT: size:%d offset:%d", s.size * 8, offset) # if member and not member.is_bitfield: ## self._fixup_record_bitfields_type(s) # , assert that the last field stop at the size limit assert offset == s.size * 8 return
def _fixup_record(self, s)
Fixup padding on a record
5.54805
5.474159
1.013498
name = 'PADDING_%d' % padding_nb padding_nb += 1 log.debug("_make_padding: for %d bits", length) if (length % 8) != 0 or (prev_member is not None and prev_member.is_bitfield): # add a padding to align with the bitfield type # then multiple bytes if required. # pad_length = (length % 8) typename = prev_member.type.name padding = typedesc.Field(name, typedesc.FundamentalType(typename, 1, 1), # offset, pad_length, is_bitfield=True) offset, length, is_bitfield=True, is_padding=True) members.append(padding) # check for multiple bytes # if (length//8) > 0: # padding_nb = self._make_padding(members, padding_nb, offset+pad_length, # (length//8)*8, prev_member=padding) return padding_nb elif length > 8: pad_bytes = length // 8 padding = typedesc.Field(name, typedesc.ArrayType( typedesc.FundamentalType( self.get_ctypes_name(TypeKind.CHAR_U), length, 1), pad_bytes), offset, length, is_padding=True) members.append(padding) return padding_nb # simple char padding padding = typedesc.Field(name, typedesc.FundamentalType( self.get_ctypes_name( TypeKind.CHAR_U), 1, 1), offset, length, is_padding=True) members.append(padding) return padding_nb
def _make_padding( self, members, padding_nb, offset, length, prev_member=None)
Make padding Fields for a specifed size.
3.305482
3.264123
1.012671
# TODO: optionalize macro parsing. It takes a LOT of time. # ignore system macro if (not hasattr(cursor, 'location') or cursor.location is None or cursor.location.file is None): return False name = self.get_unique_name(cursor) # if name == 'A': # code.interact(local=locals()) # Tokens !!! .kind = {IDENTIFIER, KEYWORD, LITERAL, PUNCTUATION, # COMMENT ? } etc. see TokenKinds.def comment = None tokens = self._literal_handling(cursor) # Macro name is tokens[0] # get Macro value(s) value = True if isinstance(tokens, list): if len(tokens) == 2: value = tokens[1] else: # just merge the list of tokens value = ''.join(tokens[1:]) # macro comment maybe in tokens. Not in cursor.raw_comment for t in cursor.get_tokens(): if t.kind == TokenKind.COMMENT: comment = t.spelling # special case. internal __null # FIXME, there are probable a lot of others. # why not Cursor.kind GNU_NULL_EXPR child instead of a token ? if name == 'NULL' or value == '__null': value = None log.debug('MACRO: #define %s %s', tokens[0], value) obj = typedesc.Macro(name, None, value) try: self.register(name, obj) except DuplicateDefinitionException: log.info( 'Redefinition of %s %s->%s', name, self.parser.all[name].args, value) # HACK self.parser.all[name] = obj self.set_location(obj, cursor) # set the comment in the obj obj.comment = comment return True
def MACRO_DEFINITION(self, cursor)
Parse MACRO_DEFINITION, only present if the TranslationUnit is used with TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD.
8.44255
8.230061
1.025819
if (hasattr(cursor, 'location') and cursor.location is not None and cursor.location.file is not None): obj.location = (cursor.location.file.name, cursor.location.line) return
def set_location(self, obj, cursor)
Location is also used for codegeneration ordering.
3.199654
2.625462
1.218701
if isinstance(obj, typedesc.T): obj.comment = cursor.brief_comment return
def set_comment(self, obj, cursor)
If a comment is available, add it to the typedesc.
22.925632
10.692947
2.143996
# FIXME see cindex.SpellingCache for k, v in [('<', '_'), ('>', '_'), ('::', '__'), (',', ''), (' ', ''), ("$", "DOLLAR"), (".", "DOT"), ("@", "_"), (":", "_"), ('-', '_')]: if k in name: # template name = name.replace(k, v) # FIXME: test case ? I want this func to be neutral on C valid # names. if name.startswith("__"): return "_X" + name if len(name) == 0: pass elif name[0] in "01234567879": return "_" + name return name
def make_python_name(self, name)
Transforms an USR into a valid python name.
7.508698
7.461586
1.006314
'''Creates a name for unname type''' parent = cursor.lexical_parent pname = self.get_unique_name(parent) log.debug('_make_unknown_name: Got parent get_unique_name %s',pname) # we only look at types declarations _cursor_decl = cursor.type.get_declaration() # we had the field index from the parent record, as to differenciate # between unnamed siblings of a same struct _i = 0 found = False # Look at the parent fields to find myself for m in parent.get_children(): # FIXME: make the good indices for fields log.debug('_make_unknown_name child %d %s %s %s',_i,m.kind, m.type.kind,m.location) if m.kind not in [CursorKind.STRUCT_DECL,CursorKind.UNION_DECL, CursorKind.CLASS_DECL]:#, #CursorKind.FIELD_DECL]: continue if m == _cursor_decl: found = True break _i+=1 if not found: raise NotImplementedError("_make_unknown_name BUG %s"%cursor.location) # truncate parent name to remove the first part (union or struct) _premainer = '_'.join(pname.split('_')[1:]) name = '%s_%d'%(_premainer,_i) return name
def _make_unknown_name(self, cursor)
Creates a name for unname type
7.173289
6.797233
1.055325
name = '' if cursor.kind in [CursorKind.UNEXPOSED_DECL]: return '' # covers most cases name = cursor.spelling # if its a record decl or field decl and its type is unnamed if cursor.spelling == '': # a unnamed object at the root TU if (cursor.semantic_parent and cursor.semantic_parent.kind == CursorKind.TRANSLATION_UNIT): name = self.make_python_name(cursor.get_usr()) log.debug('get_unique_name: root unnamed type kind %s',cursor.kind) elif cursor.kind in [CursorKind.STRUCT_DECL,CursorKind.UNION_DECL, CursorKind.CLASS_DECL,CursorKind.FIELD_DECL]: name = self._make_unknown_name(cursor) log.debug('Unnamed cursor type, got name %s',name) else: log.debug('Unnamed cursor, No idea what to do') #import code #code.interact(local=locals()) return '' if cursor.kind in [CursorKind.STRUCT_DECL,CursorKind.UNION_DECL, CursorKind.CLASS_DECL]: names= {CursorKind.STRUCT_DECL: 'struct', CursorKind.UNION_DECL: 'union', CursorKind.CLASS_DECL: 'class', CursorKind.TYPE_REF: ''} name = '%s_%s'%(names[cursor.kind],name) log.debug('get_unique_name: name "%s"',name) return name
def get_unique_name(self, cursor)
get the spelling or create a unique name for a cursor
3.831498
3.668438
1.044449
''' return the list of fundamental types that are adequate for which this literal_kind is adequate''' if literal_kind == CursorKind.INTEGER_LITERAL: return [TypeKind.USHORT, TypeKind.UINT, TypeKind.ULONG, TypeKind.ULONGLONG, TypeKind.UINT128, TypeKind.SHORT, TypeKind.INT, TypeKind.LONG, TypeKind.LONGLONG, TypeKind.INT128, ] elif literal_kind == CursorKind.STRING_LITERAL: return [TypeKind.CHAR16, TypeKind.CHAR32, TypeKind.CHAR_S, TypeKind.SCHAR, TypeKind.WCHAR] # DEBUG elif literal_kind == CursorKind.CHARACTER_LITERAL: return [TypeKind.CHAR_U, TypeKind.UCHAR] elif literal_kind == CursorKind.FLOATING_LITERAL: return [TypeKind.FLOAT, TypeKind.DOUBLE, TypeKind.LONGDOUBLE] elif literal_kind == CursorKind.IMAGINARY_LITERAL: return [] return []
def get_literal_kind_affinity(self, literal_kind)
return the list of fundamental types that are adequate for which this literal_kind is adequate
2.642451
2.156956
1.225083
compilerflags = compilerflags or ["-c"] # create a hash for the code, and use that as basename for the # files we have to create fullcode = "/* compilerflags: %r */\n%s" % (compilerflags, code) hashval = md5(fullcode).hexdigest() fnm = os.path.abspath(os.path.join(gen_dir, hashval)) h_file = fnm + ".h" xml_file = fnm + ".xml" tdesc_file = fnm + ".typedesc.bz2" if not os.path.exists(h_file): open(h_file, "w").write(fullcode) if is_newer(h_file, tdesc_file): if is_newer(h_file, xml_file): print("# Compiling into...", xml_file, file=sys.stderr) from ctypeslib import h2xml h2xml.compile_to_xml(["h2xml", "-I", os.path.dirname(fnm), "-q", h_file, "-o", xml_file] + list(compilerflags)) if is_newer(xml_file, tdesc_file): print("# Parsing XML file and compressing type descriptions...", file=sys.stderr) decls = gccxmlparser.parse(xml_file) ofi = bz2.BZ2File(tdesc_file, "w") data = cPickle.dump(decls, ofi, -1) os.remove(xml_file) # not needed any longer. frame = sys._getframe(1) glob = frame.f_globals name = glob["__name__"] mod = sys.modules[name] sys.modules[name] = DynamicModule(mod, tdesc_file, persist=persist)
def include(code, persist=True, compilerflags=None)
This function replaces the *calling module* with a dynamic module that generates code on demand. The code is generated from type descriptions that are created by gccxml compiling the C code 'code'. If <persist> is True, generated code is appended to the module's source code, otherwise the generated code is executed and then thrown away. The calling module must load all the shared libraries that it uses *BEFORE* this function is called. NOTE: - the calling module MUST contain 'from ctypes import *', and, on windows, also 'from ctypes.wintypes import *'.
4.114164
4.146528
0.992195
if not os.path.exists(source): raise ValueError("file '%s' does not exist" % source) if not os.path.exists(target): return 1 from stat import ST_MTIME mtime1 = os.stat(source)[ST_MTIME] mtime2 = os.stat(target)[ST_MTIME] return mtime1 > mtime2
def is_newer(source, target)
Return true if 'source' exists and is more recently modified than 'target', or if 'source' exists and 'target' doesn't. Return false if both exist and 'target' is the same age or younger than 'source'. Raise ValueError if 'source' does not exist.
1.992587
2.020712
0.986082
index = Index.create() self.tu = index.parse(filename, self.flags, options=self.tu_options) if not self.tu: log.warning("unable to load input") return if len(self.tu.diagnostics) > 0: for x in self.tu.diagnostics: log.warning(x.spelling) if x.severity > 2: log.warning("Source code has some error. Please fix.") log.warning(x.spelling) # code.interact(local=locals()) break root = self.tu.cursor for node in root.get_children(): self.startElement(node) return
def parse(self, filename)
. reads 1 file . if there is a compilation error, print a warning . get root cursor and recurse . for each STRUCT_DECL, register a new struct type . for each UNION_DECL, register a new union type . for each TYPEDEF_DECL, register a new alias/typdef to the underlying type - underlying type is cursor.type.get_declaration() for Record . for each VAR_DECL, register a Variable . for each TYPEREF ??
4.289901
4.447412
0.964584
if node is None: return if self.__filter_location is not None: # dont even parse includes. # FIXME: go back on dependencies ? if node.location.file is None: return elif node.location.file.name not in self.__filter_location: return # find and call the handler for this element log.debug( '%s:%d: Found a %s|%s|%s', node.location.file, node.location.line, node.kind.name, node.displayname, node.spelling) # build stuff. try: stop_recurse = self.parse_cursor(node) # Signature of parse_cursor is: # if the fn returns True, do not recurse into children. # anything else will be ignored. if stop_recurse is not False: # True: return # if fn returns something, if this element has children, treat # them. for child in node.get_children(): self.startElement(child) except InvalidDefinitionError: # if the definition is invalid pass # startElement returns None. return None
def startElement(self, node)
Recurses in children of this node
7.781415
7.530344
1.033341
if name in self.all: log.debug('register: %s already existed: %s', name, obj.name) # code.interact(local=locals()) raise DuplicateDefinitionException( 'register: %s already existed: %s' % (name, obj.name)) log.debug('register: %s ', name) self.all[name] = obj return obj
def register(self, name, obj)
Registers an unique type description
3.385272
3.383429
1.000545
tu = util.get_tu(''' typedef short short_t; typedef int int_t; typedef long long_t; typedef long long longlong_t; typedef float float_t; typedef double double_t; typedef long double longdouble_t; typedef void* pointer_t;''', flags=_flags) size = util.get_cursor(tu, 'short_t').type.get_size() * 8 self.ctypes_typename[TypeKind.SHORT] = 'c_int%d' % (size) self.ctypes_typename[TypeKind.USHORT] = 'c_uint%d' % (size) self.ctypes_sizes[TypeKind.SHORT] = size self.ctypes_sizes[TypeKind.USHORT] = size size = util.get_cursor(tu, 'int_t').type.get_size() * 8 self.ctypes_typename[TypeKind.INT] = 'c_int%d' % (size) self.ctypes_typename[TypeKind.UINT] = 'c_uint%d' % (size) self.ctypes_sizes[TypeKind.INT] = size self.ctypes_sizes[TypeKind.UINT] = size size = util.get_cursor(tu, 'long_t').type.get_size() * 8 self.ctypes_typename[TypeKind.LONG] = 'c_int%d' % (size) self.ctypes_typename[TypeKind.ULONG] = 'c_uint%d' % (size) self.ctypes_sizes[TypeKind.LONG] = size self.ctypes_sizes[TypeKind.ULONG] = size size = util.get_cursor(tu, 'longlong_t').type.get_size() * 8 self.ctypes_typename[TypeKind.LONGLONG] = 'c_int%d' % (size) self.ctypes_typename[TypeKind.ULONGLONG] = 'c_uint%d' % (size) self.ctypes_sizes[TypeKind.LONGLONG] = size self.ctypes_sizes[TypeKind.ULONGLONG] = size # FIXME : Float && http://en.wikipedia.org/wiki/Long_double size0 = util.get_cursor(tu, 'float_t').type.get_size() * 8 size1 = util.get_cursor(tu, 'double_t').type.get_size() * 8 size2 = util.get_cursor(tu, 'longdouble_t').type.get_size() * 8 # 2014-01 stop generating crap. # 2015-01 reverse until better solution is found # the idea is that a you cannot assume a c_double will be same format as a c_long_double. # at least this pass size TU if size1 != size2: self.ctypes_typename[TypeKind.LONGDOUBLE] = 'c_long_double_t' else: self.ctypes_typename[TypeKind.LONGDOUBLE] = 'c_double' self.ctypes_sizes[TypeKind.FLOAT] = size0 self.ctypes_sizes[TypeKind.DOUBLE] = size1 self.ctypes_sizes[TypeKind.LONGDOUBLE] = size2 # save the target pointer size. size = util.get_cursor(tu, 'pointer_t').type.get_size() * 8 self.ctypes_sizes[TypeKind.POINTER] = size self.ctypes_sizes[TypeKind.NULLPTR] = size log.debug('ARCH sizes: long:%s longdouble:%s', self.ctypes_typename[TypeKind.LONG], self.ctypes_typename[TypeKind.LONGDOUBLE]) return
def make_ctypes_convertor(self, _flags)
Fix clang types to ctypes convertion for this parsing isntance. Some architecture dependent size types ahve to be changed if the target architecture is not the same as local
2.09172
2.072943
1.009058
args = list(flags or []) name = 't.c' if lang == 'cpp': name = 't.cpp' args.append('-std=c++11') elif lang == 'objc': name = 't.m' elif lang != 'c': raise Exception('Unknown language: %s' % lang) if all_warnings: args += ['-Wall', '-Wextra'] return TranslationUnit.from_source(name, args, unsaved_files=[(name, source)])
def get_tu(source, lang='c', all_warnings=False, flags=None)
Obtain a translation unit from source and language. By default, the translation unit is created from source file "t.<ext>" where <ext> is the default file extension for the specified language. By default it is C, so "t.c" is the default file name. Supported languages are {c, cpp, objc}. all_warnings is a convenience argument to enable all compiler warnings.
3.142241
3.088861
1.017282
children = [] if isinstance(source, Cursor): children = source.get_children() else: # Assume TU children = source.cursor.get_children() for cursor in children: if cursor.spelling == spelling: return cursor # Recurse into children. result = get_cursor(cursor, spelling) if result is not None: return result return None
def get_cursor(source, spelling)
Obtain a cursor from a source object. This provides a convenient search mechanism to find a cursor with specific spelling within a source. The first argument can be either a TranslationUnit or Cursor instance. If the cursor is not found, None is returned.
2.779969
2.425363
1.146207
cursors = [] children = [] if isinstance(source, Cursor): children = source.get_children() else: # Assume TU children = source.cursor.get_children() for cursor in children: if cursor.spelling == spelling: cursors.append(cursor) # Recurse into children. cursors.extend(get_cursors(cursor, spelling)) return cursors
def get_cursors(source, spelling)
Obtain all cursors from a source object with a specific spelling. This provides a convenient search mechanism to find all cursors with specific spelling within a source. The first argument can be either a TranslationUnit or Cursor instance. If no cursors are found, an empty list is returned.
2.745132
2.520334
1.089194
# 2015-01 reactivating header templates #log.warning('enable_fundamental_type_wrappers deprecated - replaced by generate_headers') # return # FIXME ignore self.enable_fundamental_type_wrappers = lambda: True import pkgutil headers = pkgutil.get_data( 'ctypeslib', 'data/fundamental_type_name.tpl').decode() from clang.cindex import TypeKind size = str(self.parser.get_ctypes_size(TypeKind.LONGDOUBLE) // 8) headers = headers.replace('__LONG_DOUBLE_SIZE__', size) print(headers, file=self.imports) return
def enable_fundamental_type_wrappers(self)
If a type is a int128, a long_double_t or a void, some placeholders need to be in the generated code to be valid.
8.465102
7.738235
1.093932
# 2015-01 reactivating header templates #log.warning('enable_pointer_type deprecated - replaced by generate_headers') # return # FIXME ignore self.enable_pointer_type = lambda: True import pkgutil headers = pkgutil.get_data('ctypeslib', 'data/pointer_type.tpl').decode() import ctypes from clang.cindex import TypeKind # assuming a LONG also has the same sizeof than a pointer. word_size = self.parser.get_ctypes_size(TypeKind.POINTER) // 8 word_type = self.parser.get_ctypes_name(TypeKind.ULONG) # pylint: disable=protected-access word_char = getattr(ctypes, word_type)._type_ # replacing template values headers = headers.replace('__POINTER_SIZE__', str(word_size)) headers = headers.replace('__REPLACEMENT_TYPE__', word_type) headers = headers.replace('__REPLACEMENT_TYPE_CHAR__', word_char) print(headers, file=self.imports) return
def enable_pointer_type(self)
If a type is a pointer, a platform-independent POINTER_T type needs to be in the generated code.
6.830453
6.498297
1.051114