id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
231,000 | nateshmbhat/pyttsx3 | pyttsx3/driver.py | DriverProxy.notify | def notify(self, topic, **kwargs):
'''
Sends a notification to the engine from the driver.
@param topic: Notification topic
@type topic: str
@param kwargs: Arbitrary keyword arguments
@type kwargs: dict
'''
kwargs['name'] = self._name
self._engine._notify(topic, **kwargs) | python | def notify(self, topic, **kwargs):
'''
Sends a notification to the engine from the driver.
@param topic: Notification topic
@type topic: str
@param kwargs: Arbitrary keyword arguments
@type kwargs: dict
'''
kwargs['name'] = self._name
self._engine._notify(topic, **kwargs) | [
"def",
"notify",
"(",
"self",
",",
"topic",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'name'",
"]",
"=",
"self",
".",
"_name",
"self",
".",
"_engine",
".",
"_notify",
"(",
"topic",
",",
"*",
"*",
"kwargs",
")"
] | Sends a notification to the engine from the driver.
@param topic: Notification topic
@type topic: str
@param kwargs: Arbitrary keyword arguments
@type kwargs: dict | [
"Sends",
"a",
"notification",
"to",
"the",
"engine",
"from",
"the",
"driver",
"."
] | 0f304bff4812d50937393f1e3d7f89c9862a1623 | https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/driver.py#L121-L131 |
231,001 | nateshmbhat/pyttsx3 | pyttsx3/driver.py | DriverProxy.setBusy | def setBusy(self, busy):
'''
Called by the driver to indicate it is busy.
@param busy: True when busy, false when idle
@type busy: bool
'''
self._busy = busy
if not self._busy:
self._pump() | python | def setBusy(self, busy):
'''
Called by the driver to indicate it is busy.
@param busy: True when busy, false when idle
@type busy: bool
'''
self._busy = busy
if not self._busy:
self._pump() | [
"def",
"setBusy",
"(",
"self",
",",
"busy",
")",
":",
"self",
".",
"_busy",
"=",
"busy",
"if",
"not",
"self",
".",
"_busy",
":",
"self",
".",
"_pump",
"(",
")"
] | Called by the driver to indicate it is busy.
@param busy: True when busy, false when idle
@type busy: bool | [
"Called",
"by",
"the",
"driver",
"to",
"indicate",
"it",
"is",
"busy",
"."
] | 0f304bff4812d50937393f1e3d7f89c9862a1623 | https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/driver.py#L133-L142 |
231,002 | nateshmbhat/pyttsx3 | pyttsx3/driver.py | DriverProxy.stop | def stop(self):
'''
Called by the engine to stop the current utterance and clear the queue
of commands.
'''
# clear queue up to first end loop command
while(True):
try:
mtd, args, name = self._queue[0]
except IndexError:
break
if(mtd == self._engine.endLoop):
break
self._queue.pop(0)
self._driver.stop() | python | def stop(self):
'''
Called by the engine to stop the current utterance and clear the queue
of commands.
'''
# clear queue up to first end loop command
while(True):
try:
mtd, args, name = self._queue[0]
except IndexError:
break
if(mtd == self._engine.endLoop):
break
self._queue.pop(0)
self._driver.stop() | [
"def",
"stop",
"(",
"self",
")",
":",
"# clear queue up to first end loop command",
"while",
"(",
"True",
")",
":",
"try",
":",
"mtd",
",",
"args",
",",
"name",
"=",
"self",
".",
"_queue",
"[",
"0",
"]",
"except",
"IndexError",
":",
"break",
"if",
"(",
... | Called by the engine to stop the current utterance and clear the queue
of commands. | [
"Called",
"by",
"the",
"engine",
"to",
"stop",
"the",
"current",
"utterance",
"and",
"clear",
"the",
"queue",
"of",
"commands",
"."
] | 0f304bff4812d50937393f1e3d7f89c9862a1623 | https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/driver.py#L162-L176 |
231,003 | nateshmbhat/pyttsx3 | pyttsx3/driver.py | DriverProxy.setProperty | def setProperty(self, name, value):
'''
Called by the engine to set a driver property value.
@param name: Name of the property
@type name: str
@param value: Property value
@type value: object
'''
self._push(self._driver.setProperty, (name, value)) | python | def setProperty(self, name, value):
'''
Called by the engine to set a driver property value.
@param name: Name of the property
@type name: str
@param value: Property value
@type value: object
'''
self._push(self._driver.setProperty, (name, value)) | [
"def",
"setProperty",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"_push",
"(",
"self",
".",
"_driver",
".",
"setProperty",
",",
"(",
"name",
",",
"value",
")",
")"
] | Called by the engine to set a driver property value.
@param name: Name of the property
@type name: str
@param value: Property value
@type value: object | [
"Called",
"by",
"the",
"engine",
"to",
"set",
"a",
"driver",
"property",
"value",
"."
] | 0f304bff4812d50937393f1e3d7f89c9862a1623 | https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/driver.py#L200-L209 |
231,004 | nateshmbhat/pyttsx3 | pyttsx3/driver.py | DriverProxy.runAndWait | def runAndWait(self):
'''
Called by the engine to start an event loop, process all commands in
the queue at the start of the loop, and then exit the loop.
'''
self._push(self._engine.endLoop, tuple())
self._driver.startLoop() | python | def runAndWait(self):
'''
Called by the engine to start an event loop, process all commands in
the queue at the start of the loop, and then exit the loop.
'''
self._push(self._engine.endLoop, tuple())
self._driver.startLoop() | [
"def",
"runAndWait",
"(",
"self",
")",
":",
"self",
".",
"_push",
"(",
"self",
".",
"_engine",
".",
"endLoop",
",",
"tuple",
"(",
")",
")",
"self",
".",
"_driver",
".",
"startLoop",
"(",
")"
] | Called by the engine to start an event loop, process all commands in
the queue at the start of the loop, and then exit the loop. | [
"Called",
"by",
"the",
"engine",
"to",
"start",
"an",
"event",
"loop",
"process",
"all",
"commands",
"in",
"the",
"queue",
"at",
"the",
"start",
"of",
"the",
"loop",
"and",
"then",
"exit",
"the",
"loop",
"."
] | 0f304bff4812d50937393f1e3d7f89c9862a1623 | https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/driver.py#L211-L217 |
231,005 | nateshmbhat/pyttsx3 | pyttsx3/driver.py | DriverProxy.startLoop | def startLoop(self, useDriverLoop):
'''
Called by the engine to start an event loop.
'''
if useDriverLoop:
self._driver.startLoop()
else:
self._iterator = self._driver.iterate() | python | def startLoop(self, useDriverLoop):
'''
Called by the engine to start an event loop.
'''
if useDriverLoop:
self._driver.startLoop()
else:
self._iterator = self._driver.iterate() | [
"def",
"startLoop",
"(",
"self",
",",
"useDriverLoop",
")",
":",
"if",
"useDriverLoop",
":",
"self",
".",
"_driver",
".",
"startLoop",
"(",
")",
"else",
":",
"self",
".",
"_iterator",
"=",
"self",
".",
"_driver",
".",
"iterate",
"(",
")"
] | Called by the engine to start an event loop. | [
"Called",
"by",
"the",
"engine",
"to",
"start",
"an",
"event",
"loop",
"."
] | 0f304bff4812d50937393f1e3d7f89c9862a1623 | https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/driver.py#L219-L226 |
231,006 | nateshmbhat/pyttsx3 | pyttsx3/driver.py | DriverProxy.endLoop | def endLoop(self, useDriverLoop):
'''
Called by the engine to stop an event loop.
'''
self._queue = []
self._driver.stop()
if useDriverLoop:
self._driver.endLoop()
else:
self._iterator = None
self.setBusy(True) | python | def endLoop(self, useDriverLoop):
'''
Called by the engine to stop an event loop.
'''
self._queue = []
self._driver.stop()
if useDriverLoop:
self._driver.endLoop()
else:
self._iterator = None
self.setBusy(True) | [
"def",
"endLoop",
"(",
"self",
",",
"useDriverLoop",
")",
":",
"self",
".",
"_queue",
"=",
"[",
"]",
"self",
".",
"_driver",
".",
"stop",
"(",
")",
"if",
"useDriverLoop",
":",
"self",
".",
"_driver",
".",
"endLoop",
"(",
")",
"else",
":",
"self",
"... | Called by the engine to stop an event loop. | [
"Called",
"by",
"the",
"engine",
"to",
"stop",
"an",
"event",
"loop",
"."
] | 0f304bff4812d50937393f1e3d7f89c9862a1623 | https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/driver.py#L228-L238 |
231,007 | os/slacker | examples/post.py | post_slack | def post_slack():
"""Post slack message."""
try:
token = os.environ['SLACK_TOKEN']
slack = Slacker(token)
obj = slack.chat.post_message('#general', 'Hello fellow slackers!')
print(obj.successful, obj.__dict__['body']['channel'], obj.__dict__[
'body']['ts'])
except KeyError as ex:
print('Environment variable %s not set.' % str(ex)) | python | def post_slack():
try:
token = os.environ['SLACK_TOKEN']
slack = Slacker(token)
obj = slack.chat.post_message('#general', 'Hello fellow slackers!')
print(obj.successful, obj.__dict__['body']['channel'], obj.__dict__[
'body']['ts'])
except KeyError as ex:
print('Environment variable %s not set.' % str(ex)) | [
"def",
"post_slack",
"(",
")",
":",
"try",
":",
"token",
"=",
"os",
".",
"environ",
"[",
"'SLACK_TOKEN'",
"]",
"slack",
"=",
"Slacker",
"(",
"token",
")",
"obj",
"=",
"slack",
".",
"chat",
".",
"post_message",
"(",
"'#general'",
",",
"'Hello fellow slack... | Post slack message. | [
"Post",
"slack",
"message",
"."
] | 133596971b44a7b3bd07d11afb37745a67f0ec46 | https://github.com/os/slacker/blob/133596971b44a7b3bd07d11afb37745a67f0ec46/examples/post.py#L11-L21 |
231,008 | os/slacker | examples/list.py | list_slack | def list_slack():
"""List channels & users in slack."""
try:
token = os.environ['SLACK_TOKEN']
slack = Slacker(token)
# Get channel list
response = slack.channels.list()
channels = response.body['channels']
for channel in channels:
print(channel['id'], channel['name'])
# if not channel['is_archived']:
# slack.channels.join(channel['name'])
print()
# Get users list
response = slack.users.list()
users = response.body['members']
for user in users:
if not user['deleted']:
print(user['id'], user['name'], user['is_admin'], user[
'is_owner'])
print()
except KeyError as ex:
print('Environment variable %s not set.' % str(ex)) | python | def list_slack():
try:
token = os.environ['SLACK_TOKEN']
slack = Slacker(token)
# Get channel list
response = slack.channels.list()
channels = response.body['channels']
for channel in channels:
print(channel['id'], channel['name'])
# if not channel['is_archived']:
# slack.channels.join(channel['name'])
print()
# Get users list
response = slack.users.list()
users = response.body['members']
for user in users:
if not user['deleted']:
print(user['id'], user['name'], user['is_admin'], user[
'is_owner'])
print()
except KeyError as ex:
print('Environment variable %s not set.' % str(ex)) | [
"def",
"list_slack",
"(",
")",
":",
"try",
":",
"token",
"=",
"os",
".",
"environ",
"[",
"'SLACK_TOKEN'",
"]",
"slack",
"=",
"Slacker",
"(",
"token",
")",
"# Get channel list",
"response",
"=",
"slack",
".",
"channels",
".",
"list",
"(",
")",
"channels",... | List channels & users in slack. | [
"List",
"channels",
"&",
"users",
"in",
"slack",
"."
] | 133596971b44a7b3bd07d11afb37745a67f0ec46 | https://github.com/os/slacker/blob/133596971b44a7b3bd07d11afb37745a67f0ec46/examples/list.py#L11-L35 |
231,009 | getsenic/gatt-python | gatt/gatt_linux.py | DeviceManager.run | def run(self):
"""
Starts the main loop that is necessary to receive Bluetooth events from the Bluetooth adapter.
This call blocks until you call `stop()` to stop the main loop.
"""
if self._main_loop:
return
self._interface_added_signal = self._bus.add_signal_receiver(
self._interfaces_added,
dbus_interface='org.freedesktop.DBus.ObjectManager',
signal_name='InterfacesAdded')
# TODO: Also listen to 'interfaces removed' events?
self._properties_changed_signal = self._bus.add_signal_receiver(
self._properties_changed,
dbus_interface=dbus.PROPERTIES_IFACE,
signal_name='PropertiesChanged',
arg0='org.bluez.Device1',
path_keyword='path')
def disconnect_signals():
for device in self._devices.values():
device.invalidate()
self._properties_changed_signal.remove()
self._interface_added_signal.remove()
self._main_loop = GObject.MainLoop()
try:
self._main_loop.run()
disconnect_signals()
except Exception:
disconnect_signals()
raise | python | def run(self):
if self._main_loop:
return
self._interface_added_signal = self._bus.add_signal_receiver(
self._interfaces_added,
dbus_interface='org.freedesktop.DBus.ObjectManager',
signal_name='InterfacesAdded')
# TODO: Also listen to 'interfaces removed' events?
self._properties_changed_signal = self._bus.add_signal_receiver(
self._properties_changed,
dbus_interface=dbus.PROPERTIES_IFACE,
signal_name='PropertiesChanged',
arg0='org.bluez.Device1',
path_keyword='path')
def disconnect_signals():
for device in self._devices.values():
device.invalidate()
self._properties_changed_signal.remove()
self._interface_added_signal.remove()
self._main_loop = GObject.MainLoop()
try:
self._main_loop.run()
disconnect_signals()
except Exception:
disconnect_signals()
raise | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"_main_loop",
":",
"return",
"self",
".",
"_interface_added_signal",
"=",
"self",
".",
"_bus",
".",
"add_signal_receiver",
"(",
"self",
".",
"_interfaces_added",
",",
"dbus_interface",
"=",
"'org.freedesk... | Starts the main loop that is necessary to receive Bluetooth events from the Bluetooth adapter.
This call blocks until you call `stop()` to stop the main loop. | [
"Starts",
"the",
"main",
"loop",
"that",
"is",
"necessary",
"to",
"receive",
"Bluetooth",
"events",
"from",
"the",
"Bluetooth",
"adapter",
"."
] | e1b147d54ff199571b6c0b43bdd3a9e1ce03850c | https://github.com/getsenic/gatt-python/blob/e1b147d54ff199571b6c0b43bdd3a9e1ce03850c/gatt/gatt_linux.py#L59-L95 |
231,010 | getsenic/gatt-python | gatt/gatt_linux.py | DeviceManager.start_discovery | def start_discovery(self, service_uuids=[]):
"""Starts a discovery for BLE devices with given service UUIDs.
:param service_uuids: Filters the search to only return devices with given UUIDs.
"""
discovery_filter = {'Transport': 'le'}
if service_uuids: # D-Bus doesn't like empty lists, it needs to guess the type
discovery_filter['UUIDs'] = service_uuids
try:
self._adapter.SetDiscoveryFilter(discovery_filter)
self._adapter.StartDiscovery()
except dbus.exceptions.DBusException as e:
if e.get_dbus_name() == 'org.bluez.Error.NotReady':
raise errors.NotReady(
"Bluetooth adapter not ready. "
"Set `is_adapter_powered` to `True` or run 'echo \"power on\" | sudo bluetoothctl'.")
if e.get_dbus_name() == 'org.bluez.Error.InProgress':
# Discovery was already started - ignore exception
pass
else:
raise _error_from_dbus_error(e) | python | def start_discovery(self, service_uuids=[]):
discovery_filter = {'Transport': 'le'}
if service_uuids: # D-Bus doesn't like empty lists, it needs to guess the type
discovery_filter['UUIDs'] = service_uuids
try:
self._adapter.SetDiscoveryFilter(discovery_filter)
self._adapter.StartDiscovery()
except dbus.exceptions.DBusException as e:
if e.get_dbus_name() == 'org.bluez.Error.NotReady':
raise errors.NotReady(
"Bluetooth adapter not ready. "
"Set `is_adapter_powered` to `True` or run 'echo \"power on\" | sudo bluetoothctl'.")
if e.get_dbus_name() == 'org.bluez.Error.InProgress':
# Discovery was already started - ignore exception
pass
else:
raise _error_from_dbus_error(e) | [
"def",
"start_discovery",
"(",
"self",
",",
"service_uuids",
"=",
"[",
"]",
")",
":",
"discovery_filter",
"=",
"{",
"'Transport'",
":",
"'le'",
"}",
"if",
"service_uuids",
":",
"# D-Bus doesn't like empty lists, it needs to guess the type",
"discovery_filter",
"[",
"'... | Starts a discovery for BLE devices with given service UUIDs.
:param service_uuids: Filters the search to only return devices with given UUIDs. | [
"Starts",
"a",
"discovery",
"for",
"BLE",
"devices",
"with",
"given",
"service",
"UUIDs",
"."
] | e1b147d54ff199571b6c0b43bdd3a9e1ce03850c | https://github.com/getsenic/gatt-python/blob/e1b147d54ff199571b6c0b43bdd3a9e1ce03850c/gatt/gatt_linux.py#L127-L149 |
231,011 | getsenic/gatt-python | gatt/gatt_linux.py | DeviceManager.stop_discovery | def stop_discovery(self):
"""
Stops the discovery started with `start_discovery`
"""
try:
self._adapter.StopDiscovery()
except dbus.exceptions.DBusException as e:
if (e.get_dbus_name() == 'org.bluez.Error.Failed') and (e.get_dbus_message() == 'No discovery started'):
pass
else:
raise _error_from_dbus_error(e) | python | def stop_discovery(self):
try:
self._adapter.StopDiscovery()
except dbus.exceptions.DBusException as e:
if (e.get_dbus_name() == 'org.bluez.Error.Failed') and (e.get_dbus_message() == 'No discovery started'):
pass
else:
raise _error_from_dbus_error(e) | [
"def",
"stop_discovery",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_adapter",
".",
"StopDiscovery",
"(",
")",
"except",
"dbus",
".",
"exceptions",
".",
"DBusException",
"as",
"e",
":",
"if",
"(",
"e",
".",
"get_dbus_name",
"(",
")",
"==",
"'org.... | Stops the discovery started with `start_discovery` | [
"Stops",
"the",
"discovery",
"started",
"with",
"start_discovery"
] | e1b147d54ff199571b6c0b43bdd3a9e1ce03850c | https://github.com/getsenic/gatt-python/blob/e1b147d54ff199571b6c0b43bdd3a9e1ce03850c/gatt/gatt_linux.py#L151-L161 |
231,012 | getsenic/gatt-python | gatt/gatt_linux.py | Device.properties_changed | def properties_changed(self, sender, changed_properties, invalidated_properties):
"""
Called when a device property has changed or got invalidated.
"""
if 'Connected' in changed_properties:
if changed_properties['Connected']:
self.connect_succeeded()
else:
self.disconnect_succeeded()
if ('ServicesResolved' in changed_properties and changed_properties['ServicesResolved'] == 1 and
not self.services):
self.services_resolved() | python | def properties_changed(self, sender, changed_properties, invalidated_properties):
if 'Connected' in changed_properties:
if changed_properties['Connected']:
self.connect_succeeded()
else:
self.disconnect_succeeded()
if ('ServicesResolved' in changed_properties and changed_properties['ServicesResolved'] == 1 and
not self.services):
self.services_resolved() | [
"def",
"properties_changed",
"(",
"self",
",",
"sender",
",",
"changed_properties",
",",
"invalidated_properties",
")",
":",
"if",
"'Connected'",
"in",
"changed_properties",
":",
"if",
"changed_properties",
"[",
"'Connected'",
"]",
":",
"self",
".",
"connect_succeed... | Called when a device property has changed or got invalidated. | [
"Called",
"when",
"a",
"device",
"property",
"has",
"changed",
"or",
"got",
"invalidated",
"."
] | e1b147d54ff199571b6c0b43bdd3a9e1ce03850c | https://github.com/getsenic/gatt-python/blob/e1b147d54ff199571b6c0b43bdd3a9e1ce03850c/gatt/gatt_linux.py#L386-L398 |
231,013 | getsenic/gatt-python | gatt/gatt_linux.py | Device.services_resolved | def services_resolved(self):
"""
Called when all device's services and characteristics got resolved.
"""
self._disconnect_service_signals()
services_regex = re.compile(self._device_path + '/service[0-9abcdef]{4}$')
managed_services = [
service for service in self._object_manager.GetManagedObjects().items()
if services_regex.match(service[0])]
self.services = [Service(
device=self,
path=service[0],
uuid=service[1]['org.bluez.GattService1']['UUID']) for service in managed_services]
self._connect_service_signals() | python | def services_resolved(self):
self._disconnect_service_signals()
services_regex = re.compile(self._device_path + '/service[0-9abcdef]{4}$')
managed_services = [
service for service in self._object_manager.GetManagedObjects().items()
if services_regex.match(service[0])]
self.services = [Service(
device=self,
path=service[0],
uuid=service[1]['org.bluez.GattService1']['UUID']) for service in managed_services]
self._connect_service_signals() | [
"def",
"services_resolved",
"(",
"self",
")",
":",
"self",
".",
"_disconnect_service_signals",
"(",
")",
"services_regex",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"_device_path",
"+",
"'/service[0-9abcdef]{4}$'",
")",
"managed_services",
"=",
"[",
"service",
... | Called when all device's services and characteristics got resolved. | [
"Called",
"when",
"all",
"device",
"s",
"services",
"and",
"characteristics",
"got",
"resolved",
"."
] | e1b147d54ff199571b6c0b43bdd3a9e1ce03850c | https://github.com/getsenic/gatt-python/blob/e1b147d54ff199571b6c0b43bdd3a9e1ce03850c/gatt/gatt_linux.py#L400-L415 |
231,014 | getsenic/gatt-python | gatt/gatt_linux.py | Service.characteristics_resolved | def characteristics_resolved(self):
"""
Called when all service's characteristics got resolved.
"""
self._disconnect_characteristic_signals()
characteristics_regex = re.compile(self._path + '/char[0-9abcdef]{4}$')
managed_characteristics = [
char for char in self._object_manager.GetManagedObjects().items()
if characteristics_regex.match(char[0])]
self.characteristics = [Characteristic(
service=self,
path=c[0],
uuid=c[1]['org.bluez.GattCharacteristic1']['UUID']) for c in managed_characteristics]
self._connect_characteristic_signals() | python | def characteristics_resolved(self):
self._disconnect_characteristic_signals()
characteristics_regex = re.compile(self._path + '/char[0-9abcdef]{4}$')
managed_characteristics = [
char for char in self._object_manager.GetManagedObjects().items()
if characteristics_regex.match(char[0])]
self.characteristics = [Characteristic(
service=self,
path=c[0],
uuid=c[1]['org.bluez.GattCharacteristic1']['UUID']) for c in managed_characteristics]
self._connect_characteristic_signals() | [
"def",
"characteristics_resolved",
"(",
"self",
")",
":",
"self",
".",
"_disconnect_characteristic_signals",
"(",
")",
"characteristics_regex",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"_path",
"+",
"'/char[0-9abcdef]{4}$'",
")",
"managed_characteristics",
"=",
... | Called when all service's characteristics got resolved. | [
"Called",
"when",
"all",
"service",
"s",
"characteristics",
"got",
"resolved",
"."
] | e1b147d54ff199571b6c0b43bdd3a9e1ce03850c | https://github.com/getsenic/gatt-python/blob/e1b147d54ff199571b6c0b43bdd3a9e1ce03850c/gatt/gatt_linux.py#L497-L512 |
231,015 | getsenic/gatt-python | gatt/gatt_linux.py | Descriptor.read_value | def read_value(self, offset=0):
"""
Reads the value of this descriptor.
When successful, the value will be returned, otherwise `descriptor_read_value_failed()` of the related
device is invoked.
"""
try:
val = self._object.ReadValue(
{'offset': dbus.UInt16(offset, variant_level=1)},
dbus_interface='org.bluez.GattDescriptor1')
return val
except dbus.exceptions.DBusException as e:
error = _error_from_dbus_error(e)
self.service.device.descriptor_read_value_failed(self, error=error) | python | def read_value(self, offset=0):
try:
val = self._object.ReadValue(
{'offset': dbus.UInt16(offset, variant_level=1)},
dbus_interface='org.bluez.GattDescriptor1')
return val
except dbus.exceptions.DBusException as e:
error = _error_from_dbus_error(e)
self.service.device.descriptor_read_value_failed(self, error=error) | [
"def",
"read_value",
"(",
"self",
",",
"offset",
"=",
"0",
")",
":",
"try",
":",
"val",
"=",
"self",
".",
"_object",
".",
"ReadValue",
"(",
"{",
"'offset'",
":",
"dbus",
".",
"UInt16",
"(",
"offset",
",",
"variant_level",
"=",
"1",
")",
"}",
",",
... | Reads the value of this descriptor.
When successful, the value will be returned, otherwise `descriptor_read_value_failed()` of the related
device is invoked. | [
"Reads",
"the",
"value",
"of",
"this",
"descriptor",
"."
] | e1b147d54ff199571b6c0b43bdd3a9e1ce03850c | https://github.com/getsenic/gatt-python/blob/e1b147d54ff199571b6c0b43bdd3a9e1ce03850c/gatt/gatt_linux.py#L527-L541 |
231,016 | getsenic/gatt-python | gatt/gatt_linux.py | Characteristic.properties_changed | def properties_changed(self, properties, changed_properties, invalidated_properties):
value = changed_properties.get('Value')
"""
Called when a Characteristic property has changed.
"""
if value is not None:
self.service.device.characteristic_value_updated(characteristic=self, value=bytes(value)) | python | def properties_changed(self, properties, changed_properties, invalidated_properties):
value = changed_properties.get('Value')
if value is not None:
self.service.device.characteristic_value_updated(characteristic=self, value=bytes(value)) | [
"def",
"properties_changed",
"(",
"self",
",",
"properties",
",",
"changed_properties",
",",
"invalidated_properties",
")",
":",
"value",
"=",
"changed_properties",
".",
"get",
"(",
"'Value'",
")",
"if",
"value",
"is",
"not",
"None",
":",
"self",
".",
"service... | Called when a Characteristic property has changed. | [
"Called",
"when",
"a",
"Characteristic",
"property",
"has",
"changed",
"."
] | e1b147d54ff199571b6c0b43bdd3a9e1ce03850c | https://github.com/getsenic/gatt-python/blob/e1b147d54ff199571b6c0b43bdd3a9e1ce03850c/gatt/gatt_linux.py#L576-L582 |
231,017 | getsenic/gatt-python | gatt/gatt_linux.py | Characteristic.write_value | def write_value(self, value, offset=0):
"""
Attempts to write a value to the characteristic.
Success or failure will be notified by calls to `write_value_succeeded` or `write_value_failed` respectively.
:param value: array of bytes to be written
:param offset: offset from where to start writing the bytes (defaults to 0)
"""
bytes = [dbus.Byte(b) for b in value]
try:
self._object.WriteValue(
bytes,
{'offset': dbus.UInt16(offset, variant_level=1)},
reply_handler=self._write_value_succeeded,
error_handler=self._write_value_failed,
dbus_interface='org.bluez.GattCharacteristic1')
except dbus.exceptions.DBusException as e:
self._write_value_failed(self, error=e) | python | def write_value(self, value, offset=0):
bytes = [dbus.Byte(b) for b in value]
try:
self._object.WriteValue(
bytes,
{'offset': dbus.UInt16(offset, variant_level=1)},
reply_handler=self._write_value_succeeded,
error_handler=self._write_value_failed,
dbus_interface='org.bluez.GattCharacteristic1')
except dbus.exceptions.DBusException as e:
self._write_value_failed(self, error=e) | [
"def",
"write_value",
"(",
"self",
",",
"value",
",",
"offset",
"=",
"0",
")",
":",
"bytes",
"=",
"[",
"dbus",
".",
"Byte",
"(",
"b",
")",
"for",
"b",
"in",
"value",
"]",
"try",
":",
"self",
".",
"_object",
".",
"WriteValue",
"(",
"bytes",
",",
... | Attempts to write a value to the characteristic.
Success or failure will be notified by calls to `write_value_succeeded` or `write_value_failed` respectively.
:param value: array of bytes to be written
:param offset: offset from where to start writing the bytes (defaults to 0) | [
"Attempts",
"to",
"write",
"a",
"value",
"to",
"the",
"characteristic",
"."
] | e1b147d54ff199571b6c0b43bdd3a9e1ce03850c | https://github.com/getsenic/gatt-python/blob/e1b147d54ff199571b6c0b43bdd3a9e1ce03850c/gatt/gatt_linux.py#L599-L618 |
231,018 | getsenic/gatt-python | gatt/gatt_linux.py | Characteristic._write_value_failed | def _write_value_failed(self, dbus_error):
"""
Called when the write request has failed.
"""
error = _error_from_dbus_error(dbus_error)
self.service.device.characteristic_write_value_failed(characteristic=self, error=error) | python | def _write_value_failed(self, dbus_error):
error = _error_from_dbus_error(dbus_error)
self.service.device.characteristic_write_value_failed(characteristic=self, error=error) | [
"def",
"_write_value_failed",
"(",
"self",
",",
"dbus_error",
")",
":",
"error",
"=",
"_error_from_dbus_error",
"(",
"dbus_error",
")",
"self",
".",
"service",
".",
"device",
".",
"characteristic_write_value_failed",
"(",
"characteristic",
"=",
"self",
",",
"error... | Called when the write request has failed. | [
"Called",
"when",
"the",
"write",
"request",
"has",
"failed",
"."
] | e1b147d54ff199571b6c0b43bdd3a9e1ce03850c | https://github.com/getsenic/gatt-python/blob/e1b147d54ff199571b6c0b43bdd3a9e1ce03850c/gatt/gatt_linux.py#L626-L631 |
231,019 | getsenic/gatt-python | gatt/gatt_linux.py | Characteristic.enable_notifications | def enable_notifications(self, enabled=True):
"""
Enables or disables value change notifications.
Success or failure will be notified by calls to `characteristic_enable_notifications_succeeded`
or `enable_notifications_failed` respectively.
Each time when the device notifies a new value, `characteristic_value_updated()` of the related
device will be called.
"""
try:
if enabled:
self._object.StartNotify(
reply_handler=self._enable_notifications_succeeded,
error_handler=self._enable_notifications_failed,
dbus_interface='org.bluez.GattCharacteristic1')
else:
self._object.StopNotify(
reply_handler=self._enable_notifications_succeeded,
error_handler=self._enable_notifications_failed,
dbus_interface='org.bluez.GattCharacteristic1')
except dbus.exceptions.DBusException as e:
self._enable_notifications_failed(error=e) | python | def enable_notifications(self, enabled=True):
try:
if enabled:
self._object.StartNotify(
reply_handler=self._enable_notifications_succeeded,
error_handler=self._enable_notifications_failed,
dbus_interface='org.bluez.GattCharacteristic1')
else:
self._object.StopNotify(
reply_handler=self._enable_notifications_succeeded,
error_handler=self._enable_notifications_failed,
dbus_interface='org.bluez.GattCharacteristic1')
except dbus.exceptions.DBusException as e:
self._enable_notifications_failed(error=e) | [
"def",
"enable_notifications",
"(",
"self",
",",
"enabled",
"=",
"True",
")",
":",
"try",
":",
"if",
"enabled",
":",
"self",
".",
"_object",
".",
"StartNotify",
"(",
"reply_handler",
"=",
"self",
".",
"_enable_notifications_succeeded",
",",
"error_handler",
"=... | Enables or disables value change notifications.
Success or failure will be notified by calls to `characteristic_enable_notifications_succeeded`
or `enable_notifications_failed` respectively.
Each time when the device notifies a new value, `characteristic_value_updated()` of the related
device will be called. | [
"Enables",
"or",
"disables",
"value",
"change",
"notifications",
"."
] | e1b147d54ff199571b6c0b43bdd3a9e1ce03850c | https://github.com/getsenic/gatt-python/blob/e1b147d54ff199571b6c0b43bdd3a9e1ce03850c/gatt/gatt_linux.py#L633-L655 |
231,020 | getsenic/gatt-python | gatt/gatt_linux.py | Characteristic._enable_notifications_failed | def _enable_notifications_failed(self, dbus_error):
"""
Called when notification enabling has failed.
"""
if ((dbus_error.get_dbus_name() == 'org.bluez.Error.Failed') and
((dbus_error.get_dbus_message() == "Already notifying") or
(dbus_error.get_dbus_message() == "No notify session started"))):
# Ignore cases where notifications where already enabled or already disabled
return
error = _error_from_dbus_error(dbus_error)
self.service.device.characteristic_enable_notifications_failed(characteristic=self, error=error) | python | def _enable_notifications_failed(self, dbus_error):
if ((dbus_error.get_dbus_name() == 'org.bluez.Error.Failed') and
((dbus_error.get_dbus_message() == "Already notifying") or
(dbus_error.get_dbus_message() == "No notify session started"))):
# Ignore cases where notifications where already enabled or already disabled
return
error = _error_from_dbus_error(dbus_error)
self.service.device.characteristic_enable_notifications_failed(characteristic=self, error=error) | [
"def",
"_enable_notifications_failed",
"(",
"self",
",",
"dbus_error",
")",
":",
"if",
"(",
"(",
"dbus_error",
".",
"get_dbus_name",
"(",
")",
"==",
"'org.bluez.Error.Failed'",
")",
"and",
"(",
"(",
"dbus_error",
".",
"get_dbus_message",
"(",
")",
"==",
"\"Alr... | Called when notification enabling has failed. | [
"Called",
"when",
"notification",
"enabling",
"has",
"failed",
"."
] | e1b147d54ff199571b6c0b43bdd3a9e1ce03850c | https://github.com/getsenic/gatt-python/blob/e1b147d54ff199571b6c0b43bdd3a9e1ce03850c/gatt/gatt_linux.py#L663-L673 |
231,021 | davidaurelio/hashids-python | hashids.py | _split | def _split(string, splitters):
"""Splits a string into parts at multiple characters"""
part = ''
for character in string:
if character in splitters:
yield part
part = ''
else:
part += character
yield part | python | def _split(string, splitters):
part = ''
for character in string:
if character in splitters:
yield part
part = ''
else:
part += character
yield part | [
"def",
"_split",
"(",
"string",
",",
"splitters",
")",
":",
"part",
"=",
"''",
"for",
"character",
"in",
"string",
":",
"if",
"character",
"in",
"splitters",
":",
"yield",
"part",
"part",
"=",
"''",
"else",
":",
"part",
"+=",
"character",
"yield",
"par... | Splits a string into parts at multiple characters | [
"Splits",
"a",
"string",
"into",
"parts",
"at",
"multiple",
"characters"
] | 48f92cfd8427a0e434c9ced212fb93e641752db3 | https://github.com/davidaurelio/hashids-python/blob/48f92cfd8427a0e434c9ced212fb93e641752db3/hashids.py#L32-L41 |
231,022 | davidaurelio/hashids-python | hashids.py | _hash | def _hash(number, alphabet):
"""Hashes `number` using the given `alphabet` sequence."""
hashed = ''
len_alphabet = len(alphabet)
while True:
hashed = alphabet[number % len_alphabet] + hashed
number //= len_alphabet
if not number:
return hashed | python | def _hash(number, alphabet):
hashed = ''
len_alphabet = len(alphabet)
while True:
hashed = alphabet[number % len_alphabet] + hashed
number //= len_alphabet
if not number:
return hashed | [
"def",
"_hash",
"(",
"number",
",",
"alphabet",
")",
":",
"hashed",
"=",
"''",
"len_alphabet",
"=",
"len",
"(",
"alphabet",
")",
"while",
"True",
":",
"hashed",
"=",
"alphabet",
"[",
"number",
"%",
"len_alphabet",
"]",
"+",
"hashed",
"number",
"//=",
"... | Hashes `number` using the given `alphabet` sequence. | [
"Hashes",
"number",
"using",
"the",
"given",
"alphabet",
"sequence",
"."
] | 48f92cfd8427a0e434c9ced212fb93e641752db3 | https://github.com/davidaurelio/hashids-python/blob/48f92cfd8427a0e434c9ced212fb93e641752db3/hashids.py#L44-L52 |
231,023 | davidaurelio/hashids-python | hashids.py | _unhash | def _unhash(hashed, alphabet):
"""Restores a number tuple from hashed using the given `alphabet` index."""
number = 0
len_alphabet = len(alphabet)
for character in hashed:
position = alphabet.index(character)
number *= len_alphabet
number += position
return number | python | def _unhash(hashed, alphabet):
number = 0
len_alphabet = len(alphabet)
for character in hashed:
position = alphabet.index(character)
number *= len_alphabet
number += position
return number | [
"def",
"_unhash",
"(",
"hashed",
",",
"alphabet",
")",
":",
"number",
"=",
"0",
"len_alphabet",
"=",
"len",
"(",
"alphabet",
")",
"for",
"character",
"in",
"hashed",
":",
"position",
"=",
"alphabet",
".",
"index",
"(",
"character",
")",
"number",
"*=",
... | Restores a number tuple from hashed using the given `alphabet` index. | [
"Restores",
"a",
"number",
"tuple",
"from",
"hashed",
"using",
"the",
"given",
"alphabet",
"index",
"."
] | 48f92cfd8427a0e434c9ced212fb93e641752db3 | https://github.com/davidaurelio/hashids-python/blob/48f92cfd8427a0e434c9ced212fb93e641752db3/hashids.py#L55-L63 |
231,024 | davidaurelio/hashids-python | hashids.py | _reorder | def _reorder(string, salt):
"""Reorders `string` according to `salt`."""
len_salt = len(salt)
if len_salt != 0:
string = list(string)
index, integer_sum = 0, 0
for i in range(len(string) - 1, 0, -1):
integer = ord(salt[index])
integer_sum += integer
j = (integer + index + integer_sum) % i
string[i], string[j] = string[j], string[i]
index = (index + 1) % len_salt
string = ''.join(string)
return string | python | def _reorder(string, salt):
len_salt = len(salt)
if len_salt != 0:
string = list(string)
index, integer_sum = 0, 0
for i in range(len(string) - 1, 0, -1):
integer = ord(salt[index])
integer_sum += integer
j = (integer + index + integer_sum) % i
string[i], string[j] = string[j], string[i]
index = (index + 1) % len_salt
string = ''.join(string)
return string | [
"def",
"_reorder",
"(",
"string",
",",
"salt",
")",
":",
"len_salt",
"=",
"len",
"(",
"salt",
")",
"if",
"len_salt",
"!=",
"0",
":",
"string",
"=",
"list",
"(",
"string",
")",
"index",
",",
"integer_sum",
"=",
"0",
",",
"0",
"for",
"i",
"in",
"ra... | Reorders `string` according to `salt`. | [
"Reorders",
"string",
"according",
"to",
"salt",
"."
] | 48f92cfd8427a0e434c9ced212fb93e641752db3 | https://github.com/davidaurelio/hashids-python/blob/48f92cfd8427a0e434c9ced212fb93e641752db3/hashids.py#L66-L81 |
231,025 | davidaurelio/hashids-python | hashids.py | _ensure_length | def _ensure_length(encoded, min_length, alphabet, guards, values_hash):
"""Ensures the minimal hash length"""
len_guards = len(guards)
guard_index = (values_hash + ord(encoded[0])) % len_guards
encoded = guards[guard_index] + encoded
if len(encoded) < min_length:
guard_index = (values_hash + ord(encoded[2])) % len_guards
encoded += guards[guard_index]
split_at = len(alphabet) // 2
while len(encoded) < min_length:
alphabet = _reorder(alphabet, alphabet)
encoded = alphabet[split_at:] + encoded + alphabet[:split_at]
excess = len(encoded) - min_length
if excess > 0:
from_index = excess // 2
encoded = encoded[from_index:from_index+min_length]
return encoded | python | def _ensure_length(encoded, min_length, alphabet, guards, values_hash):
len_guards = len(guards)
guard_index = (values_hash + ord(encoded[0])) % len_guards
encoded = guards[guard_index] + encoded
if len(encoded) < min_length:
guard_index = (values_hash + ord(encoded[2])) % len_guards
encoded += guards[guard_index]
split_at = len(alphabet) // 2
while len(encoded) < min_length:
alphabet = _reorder(alphabet, alphabet)
encoded = alphabet[split_at:] + encoded + alphabet[:split_at]
excess = len(encoded) - min_length
if excess > 0:
from_index = excess // 2
encoded = encoded[from_index:from_index+min_length]
return encoded | [
"def",
"_ensure_length",
"(",
"encoded",
",",
"min_length",
",",
"alphabet",
",",
"guards",
",",
"values_hash",
")",
":",
"len_guards",
"=",
"len",
"(",
"guards",
")",
"guard_index",
"=",
"(",
"values_hash",
"+",
"ord",
"(",
"encoded",
"[",
"0",
"]",
")"... | Ensures the minimal hash length | [
"Ensures",
"the",
"minimal",
"hash",
"length"
] | 48f92cfd8427a0e434c9ced212fb93e641752db3 | https://github.com/davidaurelio/hashids-python/blob/48f92cfd8427a0e434c9ced212fb93e641752db3/hashids.py#L89-L108 |
231,026 | davidaurelio/hashids-python | hashids.py | _encode | def _encode(values, salt, min_length, alphabet, separators, guards):
"""Helper function that does the hash building without argument checks."""
len_alphabet = len(alphabet)
len_separators = len(separators)
values_hash = sum(x % (i + 100) for i, x in enumerate(values))
encoded = lottery = alphabet[values_hash % len(alphabet)]
for i, value in enumerate(values):
alphabet_salt = (lottery + salt + alphabet)[:len_alphabet]
alphabet = _reorder(alphabet, alphabet_salt)
last = _hash(value, alphabet)
encoded += last
value %= ord(last[0]) + i
encoded += separators[value % len_separators]
encoded = encoded[:-1] # cut off last separator
return (encoded if len(encoded) >= min_length else
_ensure_length(encoded, min_length, alphabet, guards, values_hash)) | python | def _encode(values, salt, min_length, alphabet, separators, guards):
len_alphabet = len(alphabet)
len_separators = len(separators)
values_hash = sum(x % (i + 100) for i, x in enumerate(values))
encoded = lottery = alphabet[values_hash % len(alphabet)]
for i, value in enumerate(values):
alphabet_salt = (lottery + salt + alphabet)[:len_alphabet]
alphabet = _reorder(alphabet, alphabet_salt)
last = _hash(value, alphabet)
encoded += last
value %= ord(last[0]) + i
encoded += separators[value % len_separators]
encoded = encoded[:-1] # cut off last separator
return (encoded if len(encoded) >= min_length else
_ensure_length(encoded, min_length, alphabet, guards, values_hash)) | [
"def",
"_encode",
"(",
"values",
",",
"salt",
",",
"min_length",
",",
"alphabet",
",",
"separators",
",",
"guards",
")",
":",
"len_alphabet",
"=",
"len",
"(",
"alphabet",
")",
"len_separators",
"=",
"len",
"(",
"separators",
")",
"values_hash",
"=",
"sum",... | Helper function that does the hash building without argument checks. | [
"Helper",
"function",
"that",
"does",
"the",
"hash",
"building",
"without",
"argument",
"checks",
"."
] | 48f92cfd8427a0e434c9ced212fb93e641752db3 | https://github.com/davidaurelio/hashids-python/blob/48f92cfd8427a0e434c9ced212fb93e641752db3/hashids.py#L111-L130 |
231,027 | davidaurelio/hashids-python | hashids.py | _decode | def _decode(hashid, salt, alphabet, separators, guards):
"""Helper method that restores the values encoded in a hashid without
argument checks."""
parts = tuple(_split(hashid, guards))
hashid = parts[1] if 2 <= len(parts) <= 3 else parts[0]
if not hashid:
return
lottery_char = hashid[0]
hashid = hashid[1:]
hash_parts = _split(hashid, separators)
for part in hash_parts:
alphabet_salt = (lottery_char + salt + alphabet)[:len(alphabet)]
alphabet = _reorder(alphabet, alphabet_salt)
yield _unhash(part, alphabet) | python | def _decode(hashid, salt, alphabet, separators, guards):
parts = tuple(_split(hashid, guards))
hashid = parts[1] if 2 <= len(parts) <= 3 else parts[0]
if not hashid:
return
lottery_char = hashid[0]
hashid = hashid[1:]
hash_parts = _split(hashid, separators)
for part in hash_parts:
alphabet_salt = (lottery_char + salt + alphabet)[:len(alphabet)]
alphabet = _reorder(alphabet, alphabet_salt)
yield _unhash(part, alphabet) | [
"def",
"_decode",
"(",
"hashid",
",",
"salt",
",",
"alphabet",
",",
"separators",
",",
"guards",
")",
":",
"parts",
"=",
"tuple",
"(",
"_split",
"(",
"hashid",
",",
"guards",
")",
")",
"hashid",
"=",
"parts",
"[",
"1",
"]",
"if",
"2",
"<=",
"len",
... | Helper method that restores the values encoded in a hashid without
argument checks. | [
"Helper",
"method",
"that",
"restores",
"the",
"values",
"encoded",
"in",
"a",
"hashid",
"without",
"argument",
"checks",
"."
] | 48f92cfd8427a0e434c9ced212fb93e641752db3 | https://github.com/davidaurelio/hashids-python/blob/48f92cfd8427a0e434c9ced212fb93e641752db3/hashids.py#L133-L149 |
231,028 | davidaurelio/hashids-python | hashids.py | _deprecated | def _deprecated(func):
"""A decorator that warns about deprecation when the passed-in function is
invoked."""
@wraps(func)
def with_warning(*args, **kwargs):
warnings.warn(
('The %s method is deprecated and will be removed in v2.*.*' %
func.__name__),
DeprecationWarning
)
return func(*args, **kwargs)
return with_warning | python | def _deprecated(func):
@wraps(func)
def with_warning(*args, **kwargs):
warnings.warn(
('The %s method is deprecated and will be removed in v2.*.*' %
func.__name__),
DeprecationWarning
)
return func(*args, **kwargs)
return with_warning | [
"def",
"_deprecated",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"with_warning",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"(",
"'The %s method is deprecated and will be removed in v2.*.*'",
"%",
"f... | A decorator that warns about deprecation when the passed-in function is
invoked. | [
"A",
"decorator",
"that",
"warns",
"about",
"deprecation",
"when",
"the",
"passed",
"-",
"in",
"function",
"is",
"invoked",
"."
] | 48f92cfd8427a0e434c9ced212fb93e641752db3 | https://github.com/davidaurelio/hashids-python/blob/48f92cfd8427a0e434c9ced212fb93e641752db3/hashids.py#L152-L163 |
231,029 | davidaurelio/hashids-python | hashids.py | Hashids.encode | def encode(self, *values):
"""Builds a hash from the passed `values`.
:param values The values to transform into a hashid
>>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456')
>>> hashids.encode(1, 23, 456)
'1d6216i30h53elk3'
"""
if not (values and all(_is_uint(x) for x in values)):
return ''
return _encode(values, self._salt, self._min_length, self._alphabet,
self._separators, self._guards) | python | def encode(self, *values):
if not (values and all(_is_uint(x) for x in values)):
return ''
return _encode(values, self._salt, self._min_length, self._alphabet,
self._separators, self._guards) | [
"def",
"encode",
"(",
"self",
",",
"*",
"values",
")",
":",
"if",
"not",
"(",
"values",
"and",
"all",
"(",
"_is_uint",
"(",
"x",
")",
"for",
"x",
"in",
"values",
")",
")",
":",
"return",
"''",
"return",
"_encode",
"(",
"values",
",",
"self",
".",... | Builds a hash from the passed `values`.
:param values The values to transform into a hashid
>>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456')
>>> hashids.encode(1, 23, 456)
'1d6216i30h53elk3' | [
"Builds",
"a",
"hash",
"from",
"the",
"passed",
"values",
"."
] | 48f92cfd8427a0e434c9ced212fb93e641752db3 | https://github.com/davidaurelio/hashids-python/blob/48f92cfd8427a0e434c9ced212fb93e641752db3/hashids.py#L217-L230 |
231,030 | davidaurelio/hashids-python | hashids.py | Hashids.decode | def decode(self, hashid):
"""Restore a tuple of numbers from the passed `hashid`.
:param hashid The hashid to decode
>>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456')
>>> hashids.decode('1d6216i30h53elk3')
(1, 23, 456)
"""
if not hashid or not _is_str(hashid):
return ()
try:
numbers = tuple(_decode(hashid, self._salt, self._alphabet,
self._separators, self._guards))
return numbers if hashid == self.encode(*numbers) else ()
except ValueError:
return () | python | def decode(self, hashid):
if not hashid or not _is_str(hashid):
return ()
try:
numbers = tuple(_decode(hashid, self._salt, self._alphabet,
self._separators, self._guards))
return numbers if hashid == self.encode(*numbers) else ()
except ValueError:
return () | [
"def",
"decode",
"(",
"self",
",",
"hashid",
")",
":",
"if",
"not",
"hashid",
"or",
"not",
"_is_str",
"(",
"hashid",
")",
":",
"return",
"(",
")",
"try",
":",
"numbers",
"=",
"tuple",
"(",
"_decode",
"(",
"hashid",
",",
"self",
".",
"_salt",
",",
... | Restore a tuple of numbers from the passed `hashid`.
:param hashid The hashid to decode
>>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456')
>>> hashids.decode('1d6216i30h53elk3')
(1, 23, 456) | [
"Restore",
"a",
"tuple",
"of",
"numbers",
"from",
"the",
"passed",
"hashid",
"."
] | 48f92cfd8427a0e434c9ced212fb93e641752db3 | https://github.com/davidaurelio/hashids-python/blob/48f92cfd8427a0e434c9ced212fb93e641752db3/hashids.py#L232-L249 |
231,031 | PyCQA/prospector | prospector/suppression.py | get_suppressions | def get_suppressions(relative_filepaths, root, messages):
"""
Given every message which was emitted by the tools, and the
list of files to inspect, create a list of files to ignore,
and a map of filepath -> line-number -> codes to ignore
"""
paths_to_ignore = set()
lines_to_ignore = defaultdict(set)
messages_to_ignore = defaultdict(lambda: defaultdict(set))
# first deal with 'noqa' style messages
for filepath in relative_filepaths:
abspath = os.path.join(root, filepath)
try:
file_contents = encoding.read_py_file(abspath).split('\n')
except encoding.CouldNotHandleEncoding as err:
# TODO: this output will break output formats such as JSON
warnings.warn('{0}: {1}'.format(err.path, err.cause), ImportWarning)
continue
ignore_file, ignore_lines = get_noqa_suppressions(file_contents)
if ignore_file:
paths_to_ignore.add(filepath)
lines_to_ignore[filepath] |= ignore_lines
# now figure out which messages were suppressed by pylint
pylint_ignore_files, pylint_ignore_messages = _parse_pylint_informational(messages)
paths_to_ignore |= pylint_ignore_files
for filepath, line in pylint_ignore_messages.items():
for line_number, codes in line.items():
for code in codes:
messages_to_ignore[filepath][line_number].add(('pylint', code))
if code in _PYLINT_EQUIVALENTS:
for equivalent in _PYLINT_EQUIVALENTS[code]:
messages_to_ignore[filepath][line_number].add(equivalent)
return paths_to_ignore, lines_to_ignore, messages_to_ignore | python | def get_suppressions(relative_filepaths, root, messages):
paths_to_ignore = set()
lines_to_ignore = defaultdict(set)
messages_to_ignore = defaultdict(lambda: defaultdict(set))
# first deal with 'noqa' style messages
for filepath in relative_filepaths:
abspath = os.path.join(root, filepath)
try:
file_contents = encoding.read_py_file(abspath).split('\n')
except encoding.CouldNotHandleEncoding as err:
# TODO: this output will break output formats such as JSON
warnings.warn('{0}: {1}'.format(err.path, err.cause), ImportWarning)
continue
ignore_file, ignore_lines = get_noqa_suppressions(file_contents)
if ignore_file:
paths_to_ignore.add(filepath)
lines_to_ignore[filepath] |= ignore_lines
# now figure out which messages were suppressed by pylint
pylint_ignore_files, pylint_ignore_messages = _parse_pylint_informational(messages)
paths_to_ignore |= pylint_ignore_files
for filepath, line in pylint_ignore_messages.items():
for line_number, codes in line.items():
for code in codes:
messages_to_ignore[filepath][line_number].add(('pylint', code))
if code in _PYLINT_EQUIVALENTS:
for equivalent in _PYLINT_EQUIVALENTS[code]:
messages_to_ignore[filepath][line_number].add(equivalent)
return paths_to_ignore, lines_to_ignore, messages_to_ignore | [
"def",
"get_suppressions",
"(",
"relative_filepaths",
",",
"root",
",",
"messages",
")",
":",
"paths_to_ignore",
"=",
"set",
"(",
")",
"lines_to_ignore",
"=",
"defaultdict",
"(",
"set",
")",
"messages_to_ignore",
"=",
"defaultdict",
"(",
"lambda",
":",
"defaultd... | Given every message which was emitted by the tools, and the
list of files to inspect, create a list of files to ignore,
and a map of filepath -> line-number -> codes to ignore | [
"Given",
"every",
"message",
"which",
"was",
"emitted",
"by",
"the",
"tools",
"and",
"the",
"list",
"of",
"files",
"to",
"inspect",
"create",
"a",
"list",
"of",
"files",
"to",
"ignore",
"and",
"a",
"map",
"of",
"filepath",
"-",
">",
"line",
"-",
"numbe... | 7cfc6d587049a786f935a722d6851cd3b72d7972 | https://github.com/PyCQA/prospector/blob/7cfc6d587049a786f935a722d6851cd3b72d7972/prospector/suppression.py#L81-L118 |
231,032 | PyCQA/prospector | prospector/run.py | get_parser | def get_parser():
"""
This is a helper method to return an argparse parser, to
be used with the Sphinx argparse plugin for documentation.
"""
manager = cfg.build_manager()
source = cfg.build_command_line_source(prog='prospector', description=None)
return source.build_parser(manager.settings, None) | python | def get_parser():
manager = cfg.build_manager()
source = cfg.build_command_line_source(prog='prospector', description=None)
return source.build_parser(manager.settings, None) | [
"def",
"get_parser",
"(",
")",
":",
"manager",
"=",
"cfg",
".",
"build_manager",
"(",
")",
"source",
"=",
"cfg",
".",
"build_command_line_source",
"(",
"prog",
"=",
"'prospector'",
",",
"description",
"=",
"None",
")",
"return",
"source",
".",
"build_parser"... | This is a helper method to return an argparse parser, to
be used with the Sphinx argparse plugin for documentation. | [
"This",
"is",
"a",
"helper",
"method",
"to",
"return",
"an",
"argparse",
"parser",
"to",
"be",
"used",
"with",
"the",
"Sphinx",
"argparse",
"plugin",
"for",
"documentation",
"."
] | 7cfc6d587049a786f935a722d6851cd3b72d7972 | https://github.com/PyCQA/prospector/blob/7cfc6d587049a786f935a722d6851cd3b72d7972/prospector/run.py#L150-L157 |
231,033 | PyCQA/prospector | prospector/tools/pylint/__init__.py | PylintTool._combine_w0614 | def _combine_w0614(self, messages):
"""
For the "unused import from wildcard import" messages,
we want to combine all warnings about the same line into
a single message.
"""
by_loc = defaultdict(list)
out = []
for message in messages:
if message.code == 'unused-wildcard-import':
by_loc[message.location].append(message)
else:
out.append(message)
for location, message_list in by_loc.items():
names = []
for msg in message_list:
names.append(
_UNUSED_WILDCARD_IMPORT_RE.match(msg.message).group(1))
msgtxt = 'Unused imports from wildcard import: %s' % ', '.join(
names)
combined_message = Message('pylint', 'unused-wildcard-import',
location, msgtxt)
out.append(combined_message)
return out | python | def _combine_w0614(self, messages):
by_loc = defaultdict(list)
out = []
for message in messages:
if message.code == 'unused-wildcard-import':
by_loc[message.location].append(message)
else:
out.append(message)
for location, message_list in by_loc.items():
names = []
for msg in message_list:
names.append(
_UNUSED_WILDCARD_IMPORT_RE.match(msg.message).group(1))
msgtxt = 'Unused imports from wildcard import: %s' % ', '.join(
names)
combined_message = Message('pylint', 'unused-wildcard-import',
location, msgtxt)
out.append(combined_message)
return out | [
"def",
"_combine_w0614",
"(",
"self",
",",
"messages",
")",
":",
"by_loc",
"=",
"defaultdict",
"(",
"list",
")",
"out",
"=",
"[",
"]",
"for",
"message",
"in",
"messages",
":",
"if",
"message",
".",
"code",
"==",
"'unused-wildcard-import'",
":",
"by_loc",
... | For the "unused import from wildcard import" messages,
we want to combine all warnings about the same line into
a single message. | [
"For",
"the",
"unused",
"import",
"from",
"wildcard",
"import",
"messages",
"we",
"want",
"to",
"combine",
"all",
"warnings",
"about",
"the",
"same",
"line",
"into",
"a",
"single",
"message",
"."
] | 7cfc6d587049a786f935a722d6851cd3b72d7972 | https://github.com/PyCQA/prospector/blob/7cfc6d587049a786f935a722d6851cd3b72d7972/prospector/tools/pylint/__init__.py#L212-L239 |
231,034 | PyCQA/prospector | prospector/tools/pylint/linter.py | ProspectorLinter.config_from_file | def config_from_file(self, config_file=None):
"""Will return `True` if plugins have been loaded. For pylint>=1.5. Else `False`."""
if PYLINT_VERSION >= (1, 5):
self.read_config_file(config_file)
if self.cfgfile_parser.has_option('MASTER', 'load-plugins'):
# pylint: disable=protected-access
plugins = _splitstrip(self.cfgfile_parser.get('MASTER', 'load-plugins'))
self.load_plugin_modules(plugins)
self.load_config_file()
return True
self.load_file_configuration(config_file)
return False | python | def config_from_file(self, config_file=None):
if PYLINT_VERSION >= (1, 5):
self.read_config_file(config_file)
if self.cfgfile_parser.has_option('MASTER', 'load-plugins'):
# pylint: disable=protected-access
plugins = _splitstrip(self.cfgfile_parser.get('MASTER', 'load-plugins'))
self.load_plugin_modules(plugins)
self.load_config_file()
return True
self.load_file_configuration(config_file)
return False | [
"def",
"config_from_file",
"(",
"self",
",",
"config_file",
"=",
"None",
")",
":",
"if",
"PYLINT_VERSION",
">=",
"(",
"1",
",",
"5",
")",
":",
"self",
".",
"read_config_file",
"(",
"config_file",
")",
"if",
"self",
".",
"cfgfile_parser",
".",
"has_option",... | Will return `True` if plugins have been loaded. For pylint>=1.5. Else `False`. | [
"Will",
"return",
"True",
"if",
"plugins",
"have",
"been",
"loaded",
".",
"For",
"pylint",
">",
"=",
"1",
".",
"5",
".",
"Else",
"False",
"."
] | 7cfc6d587049a786f935a722d6851cd3b72d7972 | https://github.com/PyCQA/prospector/blob/7cfc6d587049a786f935a722d6851cd3b72d7972/prospector/tools/pylint/linter.py#L20-L32 |
231,035 | PyCQA/prospector | prospector/postfilter.py | filter_messages | def filter_messages(relative_filepaths, root, messages):
"""
This method post-processes all messages output by all tools, in order to filter
out any based on the overall output.
The main aim currently is to use information about messages suppressed by
pylint due to inline comments, and use that to suppress messages from other
tools representing the same problem.
For example:
import banana # pylint:disable=unused-import
In this situation, pylint will not warn about an unused import as there is
inline configuration to disable the warning. Pyflakes will still raise that
error, however, because it does not understand pylint disabling messages.
This method uses the information about suppressed messages from pylint to
squash the unwanted redundant error from pyflakes and frosted.
"""
paths_to_ignore, lines_to_ignore, messages_to_ignore = get_suppressions(relative_filepaths, root, messages)
filtered = []
for message in messages:
# first get rid of the pylint informational messages
relative_message_path = os.path.relpath(message.location.path)
if message.source == 'pylint' and message.code in ('suppressed-message', 'file-ignored',):
continue
# some files are skipped entirely by messages
if relative_message_path in paths_to_ignore:
continue
# some lines are skipped entirely by messages
if relative_message_path in lines_to_ignore:
if message.location.line in lines_to_ignore[relative_message_path]:
continue
# and some lines have only certain messages explicitly ignored
if relative_message_path in messages_to_ignore:
if message.location.line in messages_to_ignore[relative_message_path]:
if message.code in messages_to_ignore[relative_message_path][message.location.line]:
continue
# otherwise this message was not filtered
filtered.append(message)
return filtered | python | def filter_messages(relative_filepaths, root, messages):
paths_to_ignore, lines_to_ignore, messages_to_ignore = get_suppressions(relative_filepaths, root, messages)
filtered = []
for message in messages:
# first get rid of the pylint informational messages
relative_message_path = os.path.relpath(message.location.path)
if message.source == 'pylint' and message.code in ('suppressed-message', 'file-ignored',):
continue
# some files are skipped entirely by messages
if relative_message_path in paths_to_ignore:
continue
# some lines are skipped entirely by messages
if relative_message_path in lines_to_ignore:
if message.location.line in lines_to_ignore[relative_message_path]:
continue
# and some lines have only certain messages explicitly ignored
if relative_message_path in messages_to_ignore:
if message.location.line in messages_to_ignore[relative_message_path]:
if message.code in messages_to_ignore[relative_message_path][message.location.line]:
continue
# otherwise this message was not filtered
filtered.append(message)
return filtered | [
"def",
"filter_messages",
"(",
"relative_filepaths",
",",
"root",
",",
"messages",
")",
":",
"paths_to_ignore",
",",
"lines_to_ignore",
",",
"messages_to_ignore",
"=",
"get_suppressions",
"(",
"relative_filepaths",
",",
"root",
",",
"messages",
")",
"filtered",
"=",... | This method post-processes all messages output by all tools, in order to filter
out any based on the overall output.
The main aim currently is to use information about messages suppressed by
pylint due to inline comments, and use that to suppress messages from other
tools representing the same problem.
For example:
import banana # pylint:disable=unused-import
In this situation, pylint will not warn about an unused import as there is
inline configuration to disable the warning. Pyflakes will still raise that
error, however, because it does not understand pylint disabling messages.
This method uses the information about suppressed messages from pylint to
squash the unwanted redundant error from pyflakes and frosted. | [
"This",
"method",
"post",
"-",
"processes",
"all",
"messages",
"output",
"by",
"all",
"tools",
"in",
"order",
"to",
"filter",
"out",
"any",
"based",
"on",
"the",
"overall",
"output",
"."
] | 7cfc6d587049a786f935a722d6851cd3b72d7972 | https://github.com/PyCQA/prospector/blob/7cfc6d587049a786f935a722d6851cd3b72d7972/prospector/postfilter.py#L7-L54 |
231,036 | PyCQA/prospector | prospector/finder.py | FoundFiles.get_minimal_syspath | def get_minimal_syspath(self, absolute_paths=True):
"""
Provide a list of directories that, when added to sys.path, would enable
any of the discovered python modules to be found
"""
# firstly, gather a list of the minimum path to each package
package_list = set()
packages = [p[0] for p in self._packages if not p[1]]
for package in sorted(packages, key=len):
parent = os.path.split(package)[0]
if parent not in packages and parent not in package_list:
package_list.add(parent)
# now add the directory containing any modules who are not in packages
module_list = []
modules = [m[0] for m in self._modules if not m[1]]
for module in modules:
dirname = os.path.dirname(module)
if dirname not in packages:
module_list.append(dirname)
full_list = sorted(set(module_list) | package_list | {self.rootpath}, key=len)
if absolute_paths:
full_list = [os.path.join(self.rootpath, p).rstrip(os.path.sep) for p in full_list]
return full_list | python | def get_minimal_syspath(self, absolute_paths=True):
# firstly, gather a list of the minimum path to each package
package_list = set()
packages = [p[0] for p in self._packages if not p[1]]
for package in sorted(packages, key=len):
parent = os.path.split(package)[0]
if parent not in packages and parent not in package_list:
package_list.add(parent)
# now add the directory containing any modules who are not in packages
module_list = []
modules = [m[0] for m in self._modules if not m[1]]
for module in modules:
dirname = os.path.dirname(module)
if dirname not in packages:
module_list.append(dirname)
full_list = sorted(set(module_list) | package_list | {self.rootpath}, key=len)
if absolute_paths:
full_list = [os.path.join(self.rootpath, p).rstrip(os.path.sep) for p in full_list]
return full_list | [
"def",
"get_minimal_syspath",
"(",
"self",
",",
"absolute_paths",
"=",
"True",
")",
":",
"# firstly, gather a list of the minimum path to each package",
"package_list",
"=",
"set",
"(",
")",
"packages",
"=",
"[",
"p",
"[",
"0",
"]",
"for",
"p",
"in",
"self",
"."... | Provide a list of directories that, when added to sys.path, would enable
any of the discovered python modules to be found | [
"Provide",
"a",
"list",
"of",
"directories",
"that",
"when",
"added",
"to",
"sys",
".",
"path",
"would",
"enable",
"any",
"of",
"the",
"discovered",
"python",
"modules",
"to",
"be",
"found"
] | 7cfc6d587049a786f935a722d6851cd3b72d7972 | https://github.com/PyCQA/prospector/blob/7cfc6d587049a786f935a722d6851cd3b72d7972/prospector/finder.py#L116-L140 |
231,037 | PyCQA/prospector | prospector/blender.py | blend_line | def blend_line(messages, blend_combos=None):
"""
Given a list of messages on the same line, blend them together so that we
end up with one message per actual problem. Note that we can still return
more than one message here if there are two or more different errors for
the line.
"""
blend_combos = blend_combos or BLEND_COMBOS
blend_lists = [[] for _ in range(len(blend_combos))]
blended = []
# first we split messages into each of the possible blendable categories
# so that we have a list of lists of messages which can be blended together
for message in messages:
key = (message.source, message.code)
found = False
for blend_combo_idx, blend_combo in enumerate(blend_combos):
if key in blend_combo:
found = True
blend_lists[blend_combo_idx].append(message)
# note: we use 'found=True' here rather than a simple break/for-else
# because this allows the same message to be put into more than one
# 'bucket'. This means that the same message from pep8 can 'subsume'
# two from pylint, for example.
if not found:
# if we get here, then this is not a message which can be blended,
# so by definition is already blended
blended.append(message)
# we should now have a list of messages which all represent the same
# problem on the same line, so we will sort them according to the priority
# in BLEND and pick the first one
for blend_combo_idx, blend_list in enumerate(blend_lists):
if len(blend_list) == 0:
continue
blend_list.sort(
key=lambda msg: blend_combos[blend_combo_idx].index(
(msg.source, msg.code),
),
)
if blend_list[0] not in blended:
# We may have already added this message if it represents
# several messages in other tools which are not being run -
# for example, pylint missing-docstring is blended with pep257 D100, D101
# and D102, but should not appear 3 times!
blended.append(blend_list[0])
# Some messages from a tool point out an error that in another tool is handled by two
# different errors or more. For example, pylint emits the same warning (multiple-statements)
# for "two statements on a line" separated by a colon and a semi-colon, while pep8 has E701
# and E702 for those cases respectively. In this case, the pylint error will not be 'blended' as
# it will appear in two blend_lists. Therefore we mark anything not taken from the blend list
# as "consumed" and then filter later, to avoid such cases.
for now_used in blend_list[1:]:
now_used.used = True
return [m for m in blended if not getattr(m, 'used', False)] | python | def blend_line(messages, blend_combos=None):
blend_combos = blend_combos or BLEND_COMBOS
blend_lists = [[] for _ in range(len(blend_combos))]
blended = []
# first we split messages into each of the possible blendable categories
# so that we have a list of lists of messages which can be blended together
for message in messages:
key = (message.source, message.code)
found = False
for blend_combo_idx, blend_combo in enumerate(blend_combos):
if key in blend_combo:
found = True
blend_lists[blend_combo_idx].append(message)
# note: we use 'found=True' here rather than a simple break/for-else
# because this allows the same message to be put into more than one
# 'bucket'. This means that the same message from pep8 can 'subsume'
# two from pylint, for example.
if not found:
# if we get here, then this is not a message which can be blended,
# so by definition is already blended
blended.append(message)
# we should now have a list of messages which all represent the same
# problem on the same line, so we will sort them according to the priority
# in BLEND and pick the first one
for blend_combo_idx, blend_list in enumerate(blend_lists):
if len(blend_list) == 0:
continue
blend_list.sort(
key=lambda msg: blend_combos[blend_combo_idx].index(
(msg.source, msg.code),
),
)
if blend_list[0] not in blended:
# We may have already added this message if it represents
# several messages in other tools which are not being run -
# for example, pylint missing-docstring is blended with pep257 D100, D101
# and D102, but should not appear 3 times!
blended.append(blend_list[0])
# Some messages from a tool point out an error that in another tool is handled by two
# different errors or more. For example, pylint emits the same warning (multiple-statements)
# for "two statements on a line" separated by a colon and a semi-colon, while pep8 has E701
# and E702 for those cases respectively. In this case, the pylint error will not be 'blended' as
# it will appear in two blend_lists. Therefore we mark anything not taken from the blend list
# as "consumed" and then filter later, to avoid such cases.
for now_used in blend_list[1:]:
now_used.used = True
return [m for m in blended if not getattr(m, 'used', False)] | [
"def",
"blend_line",
"(",
"messages",
",",
"blend_combos",
"=",
"None",
")",
":",
"blend_combos",
"=",
"blend_combos",
"or",
"BLEND_COMBOS",
"blend_lists",
"=",
"[",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"blend_combos",
")",
")",
"]",
"bl... | Given a list of messages on the same line, blend them together so that we
end up with one message per actual problem. Note that we can still return
more than one message here if there are two or more different errors for
the line. | [
"Given",
"a",
"list",
"of",
"messages",
"on",
"the",
"same",
"line",
"blend",
"them",
"together",
"so",
"that",
"we",
"end",
"up",
"with",
"one",
"message",
"per",
"actual",
"problem",
".",
"Note",
"that",
"we",
"can",
"still",
"return",
"more",
"than",
... | 7cfc6d587049a786f935a722d6851cd3b72d7972 | https://github.com/PyCQA/prospector/blob/7cfc6d587049a786f935a722d6851cd3b72d7972/prospector/blender.py#L19-L77 |
231,038 | mattloper/opendr | opendr/renderer.py | draw_boundary_images | def draw_boundary_images(glf, glb, v, f, vpe, fpe, camera):
"""Assumes camera is set up correctly, and that glf has any texmapping on necessary."""
glf.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glb.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
# Figure out which edges are on pairs of differently visible triangles
from opendr.geometry import TriNormals
tn = TriNormals(v, f).r.reshape((-1,3))
campos = -cv2.Rodrigues(camera.rt.r)[0].T.dot(camera.t.r)
rays_to_verts = v.reshape((-1,3)) - row(campos)
rays_to_faces = rays_to_verts[f[:,0]] + rays_to_verts[f[:,1]] + rays_to_verts[f[:,2]]
dps = np.sum(rays_to_faces * tn, axis=1)
dps = dps[fpe[:,0]] * dps[fpe[:,1]]
silhouette_edges = np.asarray(np.nonzero(dps<=0)[0], np.uint32)
non_silhouette_edges = np.nonzero(dps>0)[0]
lines_e = vpe[silhouette_edges]
lines_v = v
visibility = draw_edge_visibility(glb, lines_v, lines_e, f, hidden_wireframe=True)
shape = visibility.shape
visibility = visibility.ravel()
visible = np.nonzero(visibility.ravel() != 4294967295)[0]
visibility[visible] = silhouette_edges[visibility[visible]]
result = visibility.reshape(shape)
return result | python | def draw_boundary_images(glf, glb, v, f, vpe, fpe, camera):
glf.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glb.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
# Figure out which edges are on pairs of differently visible triangles
from opendr.geometry import TriNormals
tn = TriNormals(v, f).r.reshape((-1,3))
campos = -cv2.Rodrigues(camera.rt.r)[0].T.dot(camera.t.r)
rays_to_verts = v.reshape((-1,3)) - row(campos)
rays_to_faces = rays_to_verts[f[:,0]] + rays_to_verts[f[:,1]] + rays_to_verts[f[:,2]]
dps = np.sum(rays_to_faces * tn, axis=1)
dps = dps[fpe[:,0]] * dps[fpe[:,1]]
silhouette_edges = np.asarray(np.nonzero(dps<=0)[0], np.uint32)
non_silhouette_edges = np.nonzero(dps>0)[0]
lines_e = vpe[silhouette_edges]
lines_v = v
visibility = draw_edge_visibility(glb, lines_v, lines_e, f, hidden_wireframe=True)
shape = visibility.shape
visibility = visibility.ravel()
visible = np.nonzero(visibility.ravel() != 4294967295)[0]
visibility[visible] = silhouette_edges[visibility[visible]]
result = visibility.reshape(shape)
return result | [
"def",
"draw_boundary_images",
"(",
"glf",
",",
"glb",
",",
"v",
",",
"f",
",",
"vpe",
",",
"fpe",
",",
"camera",
")",
":",
"glf",
".",
"Clear",
"(",
"GL_COLOR_BUFFER_BIT",
"|",
"GL_DEPTH_BUFFER_BIT",
")",
"glb",
".",
"Clear",
"(",
"GL_COLOR_BUFFER_BIT",
... | Assumes camera is set up correctly, and that glf has any texmapping on necessary. | [
"Assumes",
"camera",
"is",
"set",
"up",
"correctly",
"and",
"that",
"glf",
"has",
"any",
"texmapping",
"on",
"necessary",
"."
] | bc16a6a51771d6e062d088ba5cede66649b7c7ec | https://github.com/mattloper/opendr/blob/bc16a6a51771d6e062d088ba5cede66649b7c7ec/opendr/renderer.py#L623-L647 |
231,039 | m32/endesive | endesive/pdf/fpdf/php.py | UTF8ToUTF16BE | def UTF8ToUTF16BE(instr, setbom=True):
"Converts UTF-8 strings to UTF16-BE."
outstr = "".encode()
if (setbom):
outstr += "\xFE\xFF".encode("latin1")
if not isinstance(instr, unicode):
instr = instr.decode('UTF-8')
outstr += instr.encode('UTF-16BE')
# convert bytes back to fake unicode string until PEP461-like is implemented
if PY3K:
outstr = outstr.decode("latin1")
return outstr | python | def UTF8ToUTF16BE(instr, setbom=True):
"Converts UTF-8 strings to UTF16-BE."
outstr = "".encode()
if (setbom):
outstr += "\xFE\xFF".encode("latin1")
if not isinstance(instr, unicode):
instr = instr.decode('UTF-8')
outstr += instr.encode('UTF-16BE')
# convert bytes back to fake unicode string until PEP461-like is implemented
if PY3K:
outstr = outstr.decode("latin1")
return outstr | [
"def",
"UTF8ToUTF16BE",
"(",
"instr",
",",
"setbom",
"=",
"True",
")",
":",
"outstr",
"=",
"\"\"",
".",
"encode",
"(",
")",
"if",
"(",
"setbom",
")",
":",
"outstr",
"+=",
"\"\\xFE\\xFF\"",
".",
"encode",
"(",
"\"latin1\"",
")",
"if",
"not",
"isinstance... | Converts UTF-8 strings to UTF16-BE. | [
"Converts",
"UTF",
"-",
"8",
"strings",
"to",
"UTF16",
"-",
"BE",
"."
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/php.py#L21-L32 |
231,040 | m32/endesive | endesive/pdf/fpdf/template.py | Template.load_elements | def load_elements(self, elements):
"Initialize the internal element structures"
self.pg_no = 0
self.elements = elements
self.keys = [v['name'].lower() for v in self.elements] | python | def load_elements(self, elements):
"Initialize the internal element structures"
self.pg_no = 0
self.elements = elements
self.keys = [v['name'].lower() for v in self.elements] | [
"def",
"load_elements",
"(",
"self",
",",
"elements",
")",
":",
"self",
".",
"pg_no",
"=",
"0",
"self",
".",
"elements",
"=",
"elements",
"self",
".",
"keys",
"=",
"[",
"v",
"[",
"'name'",
"]",
".",
"lower",
"(",
")",
"for",
"v",
"in",
"self",
".... | Initialize the internal element structures | [
"Initialize",
"the",
"internal",
"element",
"structures"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/template.py#L31-L35 |
231,041 | m32/endesive | endesive/pdf/fpdf/template.py | Template.parse_csv | def parse_csv(self, infile, delimiter=",", decimal_sep="."):
"Parse template format csv file and create elements dict"
keys = ('name','type','x1','y1','x2','y2','font','size',
'bold','italic','underline','foreground','background',
'align','text','priority', 'multiline')
self.elements = []
self.pg_no = 0
if not PY3K:
f = open(infile, 'rb')
else:
f = open(infile)
for row in csv.reader(f, delimiter=delimiter):
kargs = {}
for i,v in enumerate(row):
if not v.startswith("'") and decimal_sep!=".":
v = v.replace(decimal_sep,".")
else:
v = v
if v=='':
v = None
else:
v = eval(v.strip())
kargs[keys[i]] = v
self.elements.append(kargs)
self.keys = [v['name'].lower() for v in self.elements] | python | def parse_csv(self, infile, delimiter=",", decimal_sep="."):
"Parse template format csv file and create elements dict"
keys = ('name','type','x1','y1','x2','y2','font','size',
'bold','italic','underline','foreground','background',
'align','text','priority', 'multiline')
self.elements = []
self.pg_no = 0
if not PY3K:
f = open(infile, 'rb')
else:
f = open(infile)
for row in csv.reader(f, delimiter=delimiter):
kargs = {}
for i,v in enumerate(row):
if not v.startswith("'") and decimal_sep!=".":
v = v.replace(decimal_sep,".")
else:
v = v
if v=='':
v = None
else:
v = eval(v.strip())
kargs[keys[i]] = v
self.elements.append(kargs)
self.keys = [v['name'].lower() for v in self.elements] | [
"def",
"parse_csv",
"(",
"self",
",",
"infile",
",",
"delimiter",
"=",
"\",\"",
",",
"decimal_sep",
"=",
"\".\"",
")",
":",
"keys",
"=",
"(",
"'name'",
",",
"'type'",
",",
"'x1'",
",",
"'y1'",
",",
"'x2'",
",",
"'y2'",
",",
"'font'",
",",
"'size'",
... | Parse template format csv file and create elements dict | [
"Parse",
"template",
"format",
"csv",
"file",
"and",
"create",
"elements",
"dict"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/template.py#L37-L61 |
231,042 | m32/endesive | endesive/pdf/fpdf/html.py | HTMLMixin.write_html | def write_html(self, text, image_map=None):
"Parse HTML and convert it to PDF"
h2p = HTML2FPDF(self, image_map)
text = h2p.unescape(text) # To deal with HTML entities
h2p.feed(text) | python | def write_html(self, text, image_map=None):
"Parse HTML and convert it to PDF"
h2p = HTML2FPDF(self, image_map)
text = h2p.unescape(text) # To deal with HTML entities
h2p.feed(text) | [
"def",
"write_html",
"(",
"self",
",",
"text",
",",
"image_map",
"=",
"None",
")",
":",
"h2p",
"=",
"HTML2FPDF",
"(",
"self",
",",
"image_map",
")",
"text",
"=",
"h2p",
".",
"unescape",
"(",
"text",
")",
"# To deal with HTML entities",
"h2p",
".",
"feed"... | Parse HTML and convert it to PDF | [
"Parse",
"HTML",
"and",
"convert",
"it",
"to",
"PDF"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/html.py#L397-L401 |
231,043 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.check_page | def check_page(fn):
"Decorator to protect drawing methods"
@wraps(fn)
def wrapper(self, *args, **kwargs):
if not self.page and not kwargs.get('split_only'):
self.error("No page open, you need to call add_page() first")
else:
return fn(self, *args, **kwargs)
return wrapper | python | def check_page(fn):
"Decorator to protect drawing methods"
@wraps(fn)
def wrapper(self, *args, **kwargs):
if not self.page and not kwargs.get('split_only'):
self.error("No page open, you need to call add_page() first")
else:
return fn(self, *args, **kwargs)
return wrapper | [
"def",
"check_page",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"page",
"and",
"not",
"kwargs",
".",
"get",
"(",
"'split_only'",... | Decorator to protect drawing methods | [
"Decorator",
"to",
"protect",
"drawing",
"methods"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L143-L151 |
231,044 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.set_margins | def set_margins(self, left,top,right=-1):
"Set left, top and right margins"
self.l_margin=left
self.t_margin=top
if(right==-1):
right=left
self.r_margin=right | python | def set_margins(self, left,top,right=-1):
"Set left, top and right margins"
self.l_margin=left
self.t_margin=top
if(right==-1):
right=left
self.r_margin=right | [
"def",
"set_margins",
"(",
"self",
",",
"left",
",",
"top",
",",
"right",
"=",
"-",
"1",
")",
":",
"self",
".",
"l_margin",
"=",
"left",
"self",
".",
"t_margin",
"=",
"top",
"if",
"(",
"right",
"==",
"-",
"1",
")",
":",
"right",
"=",
"left",
"s... | Set left, top and right margins | [
"Set",
"left",
"top",
"and",
"right",
"margins"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L153-L159 |
231,045 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.set_left_margin | def set_left_margin(self, margin):
"Set left margin"
self.l_margin=margin
if(self.page>0 and self.x<margin):
self.x=margin | python | def set_left_margin(self, margin):
"Set left margin"
self.l_margin=margin
if(self.page>0 and self.x<margin):
self.x=margin | [
"def",
"set_left_margin",
"(",
"self",
",",
"margin",
")",
":",
"self",
".",
"l_margin",
"=",
"margin",
"if",
"(",
"self",
".",
"page",
">",
"0",
"and",
"self",
".",
"x",
"<",
"margin",
")",
":",
"self",
".",
"x",
"=",
"margin"
] | Set left margin | [
"Set",
"left",
"margin"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L161-L165 |
231,046 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.set_auto_page_break | def set_auto_page_break(self, auto,margin=0):
"Set auto page break mode and triggering margin"
self.auto_page_break=auto
self.b_margin=margin
self.page_break_trigger=self.h-margin | python | def set_auto_page_break(self, auto,margin=0):
"Set auto page break mode and triggering margin"
self.auto_page_break=auto
self.b_margin=margin
self.page_break_trigger=self.h-margin | [
"def",
"set_auto_page_break",
"(",
"self",
",",
"auto",
",",
"margin",
"=",
"0",
")",
":",
"self",
".",
"auto_page_break",
"=",
"auto",
"self",
".",
"b_margin",
"=",
"margin",
"self",
".",
"page_break_trigger",
"=",
"self",
".",
"h",
"-",
"margin"
] | Set auto page break mode and triggering margin | [
"Set",
"auto",
"page",
"break",
"mode",
"and",
"triggering",
"margin"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L175-L179 |
231,047 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.set_display_mode | def set_display_mode(self, zoom,layout='continuous'):
"""Set display mode in viewer
The "zoom" argument may be 'fullpage', 'fullwidth', 'real',
'default', or a number, interpreted as a percentage."""
if(zoom=='fullpage' or zoom=='fullwidth' or zoom=='real' or zoom=='default' or not isinstance(zoom,basestring)):
self.zoom_mode=zoom
else:
self.error('Incorrect zoom display mode: '+zoom)
if(layout=='single' or layout=='continuous' or layout=='two' or layout=='default'):
self.layout_mode=layout
else:
self.error('Incorrect layout display mode: '+layout) | python | def set_display_mode(self, zoom,layout='continuous'):
if(zoom=='fullpage' or zoom=='fullwidth' or zoom=='real' or zoom=='default' or not isinstance(zoom,basestring)):
self.zoom_mode=zoom
else:
self.error('Incorrect zoom display mode: '+zoom)
if(layout=='single' or layout=='continuous' or layout=='two' or layout=='default'):
self.layout_mode=layout
else:
self.error('Incorrect layout display mode: '+layout) | [
"def",
"set_display_mode",
"(",
"self",
",",
"zoom",
",",
"layout",
"=",
"'continuous'",
")",
":",
"if",
"(",
"zoom",
"==",
"'fullpage'",
"or",
"zoom",
"==",
"'fullwidth'",
"or",
"zoom",
"==",
"'real'",
"or",
"zoom",
"==",
"'default'",
"or",
"not",
"isin... | Set display mode in viewer
The "zoom" argument may be 'fullpage', 'fullwidth', 'real',
'default', or a number, interpreted as a percentage. | [
"Set",
"display",
"mode",
"in",
"viewer",
"The",
"zoom",
"argument",
"may",
"be",
"fullpage",
"fullwidth",
"real",
"default",
"or",
"a",
"number",
"interpreted",
"as",
"a",
"percentage",
"."
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L181-L194 |
231,048 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.add_page | def add_page(self, orientation=''):
"Start a new page"
if(self.state==0):
self.open()
family=self.font_family
if self.underline:
style = self.font_style + 'U'
else:
style = self.font_style
size=self.font_size_pt
lw=self.line_width
dc=self.draw_color
fc=self.fill_color
tc=self.text_color
cf=self.color_flag
if(self.page>0):
#Page footer
self.in_footer=1
self.footer()
self.in_footer=0
#close page
self._endpage()
#Start new page
self._beginpage(orientation)
#Set line cap style to square
self._out('2 J')
#Set line width
self.line_width=lw
self._out(sprintf('%.2f w',lw*self.k))
#Set font
if(family):
self.set_font(family,style,size)
#Set colors
self.draw_color=dc
if(dc!='0 G'):
self._out(dc)
self.fill_color=fc
if(fc!='0 g'):
self._out(fc)
self.text_color=tc
self.color_flag=cf
#Page header
self.header()
#Restore line width
if(self.line_width!=lw):
self.line_width=lw
self._out(sprintf('%.2f w',lw*self.k))
#Restore font
if(family):
self.set_font(family,style,size)
#Restore colors
if(self.draw_color!=dc):
self.draw_color=dc
self._out(dc)
if(self.fill_color!=fc):
self.fill_color=fc
self._out(fc)
self.text_color=tc
self.color_flag=cf | python | def add_page(self, orientation=''):
"Start a new page"
if(self.state==0):
self.open()
family=self.font_family
if self.underline:
style = self.font_style + 'U'
else:
style = self.font_style
size=self.font_size_pt
lw=self.line_width
dc=self.draw_color
fc=self.fill_color
tc=self.text_color
cf=self.color_flag
if(self.page>0):
#Page footer
self.in_footer=1
self.footer()
self.in_footer=0
#close page
self._endpage()
#Start new page
self._beginpage(orientation)
#Set line cap style to square
self._out('2 J')
#Set line width
self.line_width=lw
self._out(sprintf('%.2f w',lw*self.k))
#Set font
if(family):
self.set_font(family,style,size)
#Set colors
self.draw_color=dc
if(dc!='0 G'):
self._out(dc)
self.fill_color=fc
if(fc!='0 g'):
self._out(fc)
self.text_color=tc
self.color_flag=cf
#Page header
self.header()
#Restore line width
if(self.line_width!=lw):
self.line_width=lw
self._out(sprintf('%.2f w',lw*self.k))
#Restore font
if(family):
self.set_font(family,style,size)
#Restore colors
if(self.draw_color!=dc):
self.draw_color=dc
self._out(dc)
if(self.fill_color!=fc):
self.fill_color=fc
self._out(fc)
self.text_color=tc
self.color_flag=cf | [
"def",
"add_page",
"(",
"self",
",",
"orientation",
"=",
"''",
")",
":",
"if",
"(",
"self",
".",
"state",
"==",
"0",
")",
":",
"self",
".",
"open",
"(",
")",
"family",
"=",
"self",
".",
"font_family",
"if",
"self",
".",
"underline",
":",
"style",
... | Start a new page | [
"Start",
"a",
"new",
"page"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L248-L306 |
231,049 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.set_draw_color | def set_draw_color(self, r,g=-1,b=-1):
"Set color for all stroking operations"
if((r==0 and g==0 and b==0) or g==-1):
self.draw_color=sprintf('%.3f G',r/255.0)
else:
self.draw_color=sprintf('%.3f %.3f %.3f RG',r/255.0,g/255.0,b/255.0)
if(self.page>0):
self._out(self.draw_color) | python | def set_draw_color(self, r,g=-1,b=-1):
"Set color for all stroking operations"
if((r==0 and g==0 and b==0) or g==-1):
self.draw_color=sprintf('%.3f G',r/255.0)
else:
self.draw_color=sprintf('%.3f %.3f %.3f RG',r/255.0,g/255.0,b/255.0)
if(self.page>0):
self._out(self.draw_color) | [
"def",
"set_draw_color",
"(",
"self",
",",
"r",
",",
"g",
"=",
"-",
"1",
",",
"b",
"=",
"-",
"1",
")",
":",
"if",
"(",
"(",
"r",
"==",
"0",
"and",
"g",
"==",
"0",
"and",
"b",
"==",
"0",
")",
"or",
"g",
"==",
"-",
"1",
")",
":",
"self",
... | Set color for all stroking operations | [
"Set",
"color",
"for",
"all",
"stroking",
"operations"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L320-L327 |
231,050 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.set_fill_color | def set_fill_color(self,r,g=-1,b=-1):
"Set color for all filling operations"
if((r==0 and g==0 and b==0) or g==-1):
self.fill_color=sprintf('%.3f g',r/255.0)
else:
self.fill_color=sprintf('%.3f %.3f %.3f rg',r/255.0,g/255.0,b/255.0)
self.color_flag=(self.fill_color!=self.text_color)
if(self.page>0):
self._out(self.fill_color) | python | def set_fill_color(self,r,g=-1,b=-1):
"Set color for all filling operations"
if((r==0 and g==0 and b==0) or g==-1):
self.fill_color=sprintf('%.3f g',r/255.0)
else:
self.fill_color=sprintf('%.3f %.3f %.3f rg',r/255.0,g/255.0,b/255.0)
self.color_flag=(self.fill_color!=self.text_color)
if(self.page>0):
self._out(self.fill_color) | [
"def",
"set_fill_color",
"(",
"self",
",",
"r",
",",
"g",
"=",
"-",
"1",
",",
"b",
"=",
"-",
"1",
")",
":",
"if",
"(",
"(",
"r",
"==",
"0",
"and",
"g",
"==",
"0",
"and",
"b",
"==",
"0",
")",
"or",
"g",
"==",
"-",
"1",
")",
":",
"self",
... | Set color for all filling operations | [
"Set",
"color",
"for",
"all",
"filling",
"operations"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L329-L337 |
231,051 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.set_text_color | def set_text_color(self, r,g=-1,b=-1):
"Set color for text"
if((r==0 and g==0 and b==0) or g==-1):
self.text_color=sprintf('%.3f g',r/255.0)
else:
self.text_color=sprintf('%.3f %.3f %.3f rg',r/255.0,g/255.0,b/255.0)
self.color_flag=(self.fill_color!=self.text_color) | python | def set_text_color(self, r,g=-1,b=-1):
"Set color for text"
if((r==0 and g==0 and b==0) or g==-1):
self.text_color=sprintf('%.3f g',r/255.0)
else:
self.text_color=sprintf('%.3f %.3f %.3f rg',r/255.0,g/255.0,b/255.0)
self.color_flag=(self.fill_color!=self.text_color) | [
"def",
"set_text_color",
"(",
"self",
",",
"r",
",",
"g",
"=",
"-",
"1",
",",
"b",
"=",
"-",
"1",
")",
":",
"if",
"(",
"(",
"r",
"==",
"0",
"and",
"g",
"==",
"0",
"and",
"b",
"==",
"0",
")",
"or",
"g",
"==",
"-",
"1",
")",
":",
"self",
... | Set color for text | [
"Set",
"color",
"for",
"text"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L339-L345 |
231,052 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.get_string_width | def get_string_width(self, s):
"Get width of a string in the current font"
s = self.normalize_text(s)
cw=self.current_font['cw']
w=0
l=len(s)
if self.unifontsubset:
for char in s:
char = ord(char)
if len(cw) > char:
w += cw[char] # ord(cw[2*char])<<8 + ord(cw[2*char+1])
#elif (char>0 and char<128 and isset($cw[chr($char)])) { $w += $cw[chr($char)]; }
elif (self.current_font['desc']['MissingWidth']) :
w += self.current_font['desc']['MissingWidth']
#elif (isset($this->CurrentFont['MissingWidth'])) { $w += $this->CurrentFont['MissingWidth']; }
else:
w += 500
else:
for i in range(0, l):
w += cw.get(s[i],0)
return w*self.font_size/1000.0 | python | def get_string_width(self, s):
"Get width of a string in the current font"
s = self.normalize_text(s)
cw=self.current_font['cw']
w=0
l=len(s)
if self.unifontsubset:
for char in s:
char = ord(char)
if len(cw) > char:
w += cw[char] # ord(cw[2*char])<<8 + ord(cw[2*char+1])
#elif (char>0 and char<128 and isset($cw[chr($char)])) { $w += $cw[chr($char)]; }
elif (self.current_font['desc']['MissingWidth']) :
w += self.current_font['desc']['MissingWidth']
#elif (isset($this->CurrentFont['MissingWidth'])) { $w += $this->CurrentFont['MissingWidth']; }
else:
w += 500
else:
for i in range(0, l):
w += cw.get(s[i],0)
return w*self.font_size/1000.0 | [
"def",
"get_string_width",
"(",
"self",
",",
"s",
")",
":",
"s",
"=",
"self",
".",
"normalize_text",
"(",
"s",
")",
"cw",
"=",
"self",
".",
"current_font",
"[",
"'cw'",
"]",
"w",
"=",
"0",
"l",
"=",
"len",
"(",
"s",
")",
"if",
"self",
".",
"uni... | Get width of a string in the current font | [
"Get",
"width",
"of",
"a",
"string",
"in",
"the",
"current",
"font"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L347-L367 |
231,053 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.set_line_width | def set_line_width(self, width):
"Set line width"
self.line_width=width
if(self.page>0):
self._out(sprintf('%.2f w',width*self.k)) | python | def set_line_width(self, width):
"Set line width"
self.line_width=width
if(self.page>0):
self._out(sprintf('%.2f w',width*self.k)) | [
"def",
"set_line_width",
"(",
"self",
",",
"width",
")",
":",
"self",
".",
"line_width",
"=",
"width",
"if",
"(",
"self",
".",
"page",
">",
"0",
")",
":",
"self",
".",
"_out",
"(",
"sprintf",
"(",
"'%.2f w'",
",",
"width",
"*",
"self",
".",
"k",
... | Set line width | [
"Set",
"line",
"width"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L369-L373 |
231,054 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.ellipse | def ellipse(self, x,y,w,h,style=''):
"Draw a ellipse"
if(style=='F'):
op='f'
elif(style=='FD' or style=='DF'):
op='B'
else:
op='S'
cx = x + w/2.0
cy = y + h/2.0
rx = w/2.0
ry = h/2.0
lx = 4.0/3.0*(math.sqrt(2)-1)*rx
ly = 4.0/3.0*(math.sqrt(2)-1)*ry
self._out(sprintf('%.2f %.2f m %.2f %.2f %.2f %.2f %.2f %.2f c',
(cx+rx)*self.k, (self.h-cy)*self.k,
(cx+rx)*self.k, (self.h-(cy-ly))*self.k,
(cx+lx)*self.k, (self.h-(cy-ry))*self.k,
cx*self.k, (self.h-(cy-ry))*self.k))
self._out(sprintf('%.2f %.2f %.2f %.2f %.2f %.2f c',
(cx-lx)*self.k, (self.h-(cy-ry))*self.k,
(cx-rx)*self.k, (self.h-(cy-ly))*self.k,
(cx-rx)*self.k, (self.h-cy)*self.k))
self._out(sprintf('%.2f %.2f %.2f %.2f %.2f %.2f c',
(cx-rx)*self.k, (self.h-(cy+ly))*self.k,
(cx-lx)*self.k, (self.h-(cy+ry))*self.k,
cx*self.k, (self.h-(cy+ry))*self.k))
self._out(sprintf('%.2f %.2f %.2f %.2f %.2f %.2f c %s',
(cx+lx)*self.k, (self.h-(cy+ry))*self.k,
(cx+rx)*self.k, (self.h-(cy+ly))*self.k,
(cx+rx)*self.k, (self.h-cy)*self.k,
op)) | python | def ellipse(self, x,y,w,h,style=''):
"Draw a ellipse"
if(style=='F'):
op='f'
elif(style=='FD' or style=='DF'):
op='B'
else:
op='S'
cx = x + w/2.0
cy = y + h/2.0
rx = w/2.0
ry = h/2.0
lx = 4.0/3.0*(math.sqrt(2)-1)*rx
ly = 4.0/3.0*(math.sqrt(2)-1)*ry
self._out(sprintf('%.2f %.2f m %.2f %.2f %.2f %.2f %.2f %.2f c',
(cx+rx)*self.k, (self.h-cy)*self.k,
(cx+rx)*self.k, (self.h-(cy-ly))*self.k,
(cx+lx)*self.k, (self.h-(cy-ry))*self.k,
cx*self.k, (self.h-(cy-ry))*self.k))
self._out(sprintf('%.2f %.2f %.2f %.2f %.2f %.2f c',
(cx-lx)*self.k, (self.h-(cy-ry))*self.k,
(cx-rx)*self.k, (self.h-(cy-ly))*self.k,
(cx-rx)*self.k, (self.h-cy)*self.k))
self._out(sprintf('%.2f %.2f %.2f %.2f %.2f %.2f c',
(cx-rx)*self.k, (self.h-(cy+ly))*self.k,
(cx-lx)*self.k, (self.h-(cy+ry))*self.k,
cx*self.k, (self.h-(cy+ry))*self.k))
self._out(sprintf('%.2f %.2f %.2f %.2f %.2f %.2f c %s',
(cx+lx)*self.k, (self.h-(cy+ry))*self.k,
(cx+rx)*self.k, (self.h-(cy+ly))*self.k,
(cx+rx)*self.k, (self.h-cy)*self.k,
op)) | [
"def",
"ellipse",
"(",
"self",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"style",
"=",
"''",
")",
":",
"if",
"(",
"style",
"==",
"'F'",
")",
":",
"op",
"=",
"'f'",
"elif",
"(",
"style",
"==",
"'FD'",
"or",
"style",
"==",
"'DF'",
")",
":"... | Draw a ellipse | [
"Draw",
"a",
"ellipse"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L408-L442 |
231,055 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.set_font | def set_font(self, family,style='',size=0):
"Select a font; size given in points"
family=family.lower()
if(family==''):
family=self.font_family
if(family=='arial'):
family='helvetica'
elif(family=='symbol' or family=='zapfdingbats'):
style=''
style=style.upper()
if('U' in style):
self.underline=1
style=style.replace('U','')
else:
self.underline=0
if(style=='IB'):
style='BI'
if(size==0):
size=self.font_size_pt
#Test if font is already selected
if(self.font_family==family and self.font_style==style and self.font_size_pt==size):
return
#Test if used for the first time
fontkey=family+style
if fontkey not in self.fonts:
#Check if one of the standard fonts
if fontkey in self.core_fonts:
if fontkey not in fpdf_charwidths:
#Load metric file
name=os.path.join(FPDF_FONT_DIR,family)
if(family=='times' or family=='helvetica'):
name+=style.lower()
exec(compile(open(name+'.font').read(), name+'.font', 'exec'))
if fontkey not in fpdf_charwidths:
self.error('Could not include font metric file for'+fontkey)
i=len(self.fonts)+1
self.fonts[fontkey]={'i':i,'type':'core','name':self.core_fonts[fontkey],'up':-100,'ut':50,'cw':fpdf_charwidths[fontkey]}
else:
self.error('Undefined font: '+family+' '+style)
#Select it
self.font_family=family
self.font_style=style
self.font_size_pt=size
self.font_size=size/self.k
self.current_font=self.fonts[fontkey]
self.unifontsubset = (self.fonts[fontkey]['type'] == 'TTF')
if(self.page>0):
self._out(sprintf('BT /F%d %.2f Tf ET',self.current_font['i'],self.font_size_pt)) | python | def set_font(self, family,style='',size=0):
"Select a font; size given in points"
family=family.lower()
if(family==''):
family=self.font_family
if(family=='arial'):
family='helvetica'
elif(family=='symbol' or family=='zapfdingbats'):
style=''
style=style.upper()
if('U' in style):
self.underline=1
style=style.replace('U','')
else:
self.underline=0
if(style=='IB'):
style='BI'
if(size==0):
size=self.font_size_pt
#Test if font is already selected
if(self.font_family==family and self.font_style==style and self.font_size_pt==size):
return
#Test if used for the first time
fontkey=family+style
if fontkey not in self.fonts:
#Check if one of the standard fonts
if fontkey in self.core_fonts:
if fontkey not in fpdf_charwidths:
#Load metric file
name=os.path.join(FPDF_FONT_DIR,family)
if(family=='times' or family=='helvetica'):
name+=style.lower()
exec(compile(open(name+'.font').read(), name+'.font', 'exec'))
if fontkey not in fpdf_charwidths:
self.error('Could not include font metric file for'+fontkey)
i=len(self.fonts)+1
self.fonts[fontkey]={'i':i,'type':'core','name':self.core_fonts[fontkey],'up':-100,'ut':50,'cw':fpdf_charwidths[fontkey]}
else:
self.error('Undefined font: '+family+' '+style)
#Select it
self.font_family=family
self.font_style=style
self.font_size_pt=size
self.font_size=size/self.k
self.current_font=self.fonts[fontkey]
self.unifontsubset = (self.fonts[fontkey]['type'] == 'TTF')
if(self.page>0):
self._out(sprintf('BT /F%d %.2f Tf ET',self.current_font['i'],self.font_size_pt)) | [
"def",
"set_font",
"(",
"self",
",",
"family",
",",
"style",
"=",
"''",
",",
"size",
"=",
"0",
")",
":",
"family",
"=",
"family",
".",
"lower",
"(",
")",
"if",
"(",
"family",
"==",
"''",
")",
":",
"family",
"=",
"self",
".",
"font_family",
"if",
... | Select a font; size given in points | [
"Select",
"a",
"font",
";",
"size",
"given",
"in",
"points"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L565-L612 |
231,056 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.set_font_size | def set_font_size(self, size):
"Set font size in points"
if(self.font_size_pt==size):
return
self.font_size_pt=size
self.font_size=size/self.k
if(self.page>0):
self._out(sprintf('BT /F%d %.2f Tf ET',self.current_font['i'],self.font_size_pt)) | python | def set_font_size(self, size):
"Set font size in points"
if(self.font_size_pt==size):
return
self.font_size_pt=size
self.font_size=size/self.k
if(self.page>0):
self._out(sprintf('BT /F%d %.2f Tf ET',self.current_font['i'],self.font_size_pt)) | [
"def",
"set_font_size",
"(",
"self",
",",
"size",
")",
":",
"if",
"(",
"self",
".",
"font_size_pt",
"==",
"size",
")",
":",
"return",
"self",
".",
"font_size_pt",
"=",
"size",
"self",
".",
"font_size",
"=",
"size",
"/",
"self",
".",
"k",
"if",
"(",
... | Set font size in points | [
"Set",
"font",
"size",
"in",
"points"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L614-L621 |
231,057 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.add_link | def add_link(self):
"Create a new internal link"
n=len(self.links)+1
self.links[n]=(0,0)
return n | python | def add_link(self):
"Create a new internal link"
n=len(self.links)+1
self.links[n]=(0,0)
return n | [
"def",
"add_link",
"(",
"self",
")",
":",
"n",
"=",
"len",
"(",
"self",
".",
"links",
")",
"+",
"1",
"self",
".",
"links",
"[",
"n",
"]",
"=",
"(",
"0",
",",
"0",
")",
"return",
"n"
] | Create a new internal link | [
"Create",
"a",
"new",
"internal",
"link"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L623-L627 |
231,058 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.set_link | def set_link(self, link,y=0,page=-1):
"Set destination of internal link"
if(y==-1):
y=self.y
if(page==-1):
page=self.page
self.links[link]=[page,y] | python | def set_link(self, link,y=0,page=-1):
"Set destination of internal link"
if(y==-1):
y=self.y
if(page==-1):
page=self.page
self.links[link]=[page,y] | [
"def",
"set_link",
"(",
"self",
",",
"link",
",",
"y",
"=",
"0",
",",
"page",
"=",
"-",
"1",
")",
":",
"if",
"(",
"y",
"==",
"-",
"1",
")",
":",
"y",
"=",
"self",
".",
"y",
"if",
"(",
"page",
"==",
"-",
"1",
")",
":",
"page",
"=",
"self... | Set destination of internal link | [
"Set",
"destination",
"of",
"internal",
"link"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L629-L635 |
231,059 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.link | def link(self, x,y,w,h,link):
"Put a link on the page"
if not self.page in self.page_links:
self.page_links[self.page] = []
self.page_links[self.page] += [(x*self.k,self.h_pt-y*self.k,w*self.k,h*self.k,link),] | python | def link(self, x,y,w,h,link):
"Put a link on the page"
if not self.page in self.page_links:
self.page_links[self.page] = []
self.page_links[self.page] += [(x*self.k,self.h_pt-y*self.k,w*self.k,h*self.k,link),] | [
"def",
"link",
"(",
"self",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"link",
")",
":",
"if",
"not",
"self",
".",
"page",
"in",
"self",
".",
"page_links",
":",
"self",
".",
"page_links",
"[",
"self",
".",
"page",
"]",
"=",
"[",
"]",
"self"... | Put a link on the page | [
"Put",
"a",
"link",
"on",
"the",
"page"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L637-L641 |
231,060 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.text | def text(self, x, y, txt=''):
"Output a string"
txt = self.normalize_text(txt)
if (self.unifontsubset):
txt2 = self._escape(UTF8ToUTF16BE(txt, False))
for uni in UTF8StringToArray(txt):
self.current_font['subset'].append(uni)
else:
txt2 = self._escape(txt)
s=sprintf('BT %.2f %.2f Td (%s) Tj ET',x*self.k,(self.h-y)*self.k, txt2)
if(self.underline and txt!=''):
s+=' '+self._dounderline(x,y,txt)
if(self.color_flag):
s='q '+self.text_color+' '+s+' Q'
self._out(s) | python | def text(self, x, y, txt=''):
"Output a string"
txt = self.normalize_text(txt)
if (self.unifontsubset):
txt2 = self._escape(UTF8ToUTF16BE(txt, False))
for uni in UTF8StringToArray(txt):
self.current_font['subset'].append(uni)
else:
txt2 = self._escape(txt)
s=sprintf('BT %.2f %.2f Td (%s) Tj ET',x*self.k,(self.h-y)*self.k, txt2)
if(self.underline and txt!=''):
s+=' '+self._dounderline(x,y,txt)
if(self.color_flag):
s='q '+self.text_color+' '+s+' Q'
self._out(s) | [
"def",
"text",
"(",
"self",
",",
"x",
",",
"y",
",",
"txt",
"=",
"''",
")",
":",
"txt",
"=",
"self",
".",
"normalize_text",
"(",
"txt",
")",
"if",
"(",
"self",
".",
"unifontsubset",
")",
":",
"txt2",
"=",
"self",
".",
"_escape",
"(",
"UTF8ToUTF16... | Output a string | [
"Output",
"a",
"string"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L644-L658 |
231,061 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.write | def write(self, h, txt='', link=''):
"Output text in flowing mode"
txt = self.normalize_text(txt)
cw=self.current_font['cw']
w=self.w-self.r_margin-self.x
wmax=(w-2*self.c_margin)*1000.0/self.font_size
s=txt.replace("\r",'')
nb=len(s)
sep=-1
i=0
j=0
l=0
nl=1
while(i<nb):
#Get next character
c=s[i]
if(c=="\n"):
#Explicit line break
self.cell(w,h,substr(s,j,i-j),0,2,'',0,link)
i+=1
sep=-1
j=i
l=0
if(nl==1):
self.x=self.l_margin
w=self.w-self.r_margin-self.x
wmax=(w-2*self.c_margin)*1000.0/self.font_size
nl+=1
continue
if(c==' '):
sep=i
if self.unifontsubset:
l += self.get_string_width(c) / self.font_size*1000.0
else:
l += cw.get(c,0)
if(l>wmax):
#Automatic line break
if(sep==-1):
if(self.x>self.l_margin):
#Move to next line
self.x=self.l_margin
self.y+=h
w=self.w-self.r_margin-self.x
wmax=(w-2*self.c_margin)*1000.0/self.font_size
i+=1
nl+=1
continue
if(i==j):
i+=1
self.cell(w,h,substr(s,j,i-j),0,2,'',0,link)
else:
self.cell(w,h,substr(s,j,sep-j),0,2,'',0,link)
i=sep+1
sep=-1
j=i
l=0
if(nl==1):
self.x=self.l_margin
w=self.w-self.r_margin-self.x
wmax=(w-2*self.c_margin)*1000.0/self.font_size
nl+=1
else:
i+=1
#Last chunk
if(i!=j):
self.cell(l/1000.0*self.font_size,h,substr(s,j),0,0,'',0,link) | python | def write(self, h, txt='', link=''):
"Output text in flowing mode"
txt = self.normalize_text(txt)
cw=self.current_font['cw']
w=self.w-self.r_margin-self.x
wmax=(w-2*self.c_margin)*1000.0/self.font_size
s=txt.replace("\r",'')
nb=len(s)
sep=-1
i=0
j=0
l=0
nl=1
while(i<nb):
#Get next character
c=s[i]
if(c=="\n"):
#Explicit line break
self.cell(w,h,substr(s,j,i-j),0,2,'',0,link)
i+=1
sep=-1
j=i
l=0
if(nl==1):
self.x=self.l_margin
w=self.w-self.r_margin-self.x
wmax=(w-2*self.c_margin)*1000.0/self.font_size
nl+=1
continue
if(c==' '):
sep=i
if self.unifontsubset:
l += self.get_string_width(c) / self.font_size*1000.0
else:
l += cw.get(c,0)
if(l>wmax):
#Automatic line break
if(sep==-1):
if(self.x>self.l_margin):
#Move to next line
self.x=self.l_margin
self.y+=h
w=self.w-self.r_margin-self.x
wmax=(w-2*self.c_margin)*1000.0/self.font_size
i+=1
nl+=1
continue
if(i==j):
i+=1
self.cell(w,h,substr(s,j,i-j),0,2,'',0,link)
else:
self.cell(w,h,substr(s,j,sep-j),0,2,'',0,link)
i=sep+1
sep=-1
j=i
l=0
if(nl==1):
self.x=self.l_margin
w=self.w-self.r_margin-self.x
wmax=(w-2*self.c_margin)*1000.0/self.font_size
nl+=1
else:
i+=1
#Last chunk
if(i!=j):
self.cell(l/1000.0*self.font_size,h,substr(s,j),0,0,'',0,link) | [
"def",
"write",
"(",
"self",
",",
"h",
",",
"txt",
"=",
"''",
",",
"link",
"=",
"''",
")",
":",
"txt",
"=",
"self",
".",
"normalize_text",
"(",
"txt",
")",
"cw",
"=",
"self",
".",
"current_font",
"[",
"'cw'",
"]",
"w",
"=",
"self",
".",
"w",
... | Output text in flowing mode | [
"Output",
"text",
"in",
"flowing",
"mode"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L890-L955 |
231,062 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.image | def image(self, name, x=None, y=None, w=0,h=0,type='',link=''):
"Put an image on the page"
if not name in self.images:
#First use of image, get info
if(type==''):
pos=name.rfind('.')
if(not pos):
self.error('image file has no extension and no type was specified: '+name)
type=substr(name,pos+1)
type=type.lower()
if(type=='jpg' or type=='jpeg'):
info=self._parsejpg(name)
elif(type=='png'):
info=self._parsepng(name)
else:
#Allow for additional formats
#maybe the image is not showing the correct extension,
#but the header is OK,
succeed_parsing = False
#try all the parsing functions
parsing_functions = [self._parsejpg,self._parsepng,self._parsegif]
for pf in parsing_functions:
try:
info = pf(name)
succeed_parsing = True
break;
except:
pass
#last resource
if not succeed_parsing:
mtd='_parse'+type
if not hasattr(self,mtd):
self.error('Unsupported image type: '+type)
info=getattr(self, mtd)(name)
mtd='_parse'+type
if not hasattr(self,mtd):
self.error('Unsupported image type: '+type)
info=getattr(self, mtd)(name)
info['i']=len(self.images)+1
self.images[name]=info
else:
info=self.images[name]
#Automatic width and height calculation if needed
if(w==0 and h==0):
#Put image at 72 dpi
w=info['w']/self.k
h=info['h']/self.k
elif(w==0):
w=h*info['w']/info['h']
elif(h==0):
h=w*info['h']/info['w']
# Flowing mode
if y is None:
if (self.y + h > self.page_break_trigger and not self.in_footer and self.accept_page_break()):
#Automatic page break
x = self.x
self.add_page(self.cur_orientation)
self.x = x
y = self.y
self.y += h
if x is None:
x = self.x
self._out(sprintf('q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q',w*self.k,h*self.k,x*self.k,(self.h-(y+h))*self.k,info['i']))
if(link):
self.link(x,y,w,h,link) | python | def image(self, name, x=None, y=None, w=0,h=0,type='',link=''):
"Put an image on the page"
if not name in self.images:
#First use of image, get info
if(type==''):
pos=name.rfind('.')
if(not pos):
self.error('image file has no extension and no type was specified: '+name)
type=substr(name,pos+1)
type=type.lower()
if(type=='jpg' or type=='jpeg'):
info=self._parsejpg(name)
elif(type=='png'):
info=self._parsepng(name)
else:
#Allow for additional formats
#maybe the image is not showing the correct extension,
#but the header is OK,
succeed_parsing = False
#try all the parsing functions
parsing_functions = [self._parsejpg,self._parsepng,self._parsegif]
for pf in parsing_functions:
try:
info = pf(name)
succeed_parsing = True
break;
except:
pass
#last resource
if not succeed_parsing:
mtd='_parse'+type
if not hasattr(self,mtd):
self.error('Unsupported image type: '+type)
info=getattr(self, mtd)(name)
mtd='_parse'+type
if not hasattr(self,mtd):
self.error('Unsupported image type: '+type)
info=getattr(self, mtd)(name)
info['i']=len(self.images)+1
self.images[name]=info
else:
info=self.images[name]
#Automatic width and height calculation if needed
if(w==0 and h==0):
#Put image at 72 dpi
w=info['w']/self.k
h=info['h']/self.k
elif(w==0):
w=h*info['w']/info['h']
elif(h==0):
h=w*info['h']/info['w']
# Flowing mode
if y is None:
if (self.y + h > self.page_break_trigger and not self.in_footer and self.accept_page_break()):
#Automatic page break
x = self.x
self.add_page(self.cur_orientation)
self.x = x
y = self.y
self.y += h
if x is None:
x = self.x
self._out(sprintf('q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q',w*self.k,h*self.k,x*self.k,(self.h-(y+h))*self.k,info['i']))
if(link):
self.link(x,y,w,h,link) | [
"def",
"image",
"(",
"self",
",",
"name",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"w",
"=",
"0",
",",
"h",
"=",
"0",
",",
"type",
"=",
"''",
",",
"link",
"=",
"''",
")",
":",
"if",
"not",
"name",
"in",
"self",
".",
"images",
":... | Put an image on the page | [
"Put",
"an",
"image",
"on",
"the",
"page"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L958-L1022 |
231,063 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.ln | def ln(self, h=''):
"Line Feed; default value is last cell height"
self.x=self.l_margin
if(isinstance(h, basestring)):
self.y+=self.lasth
else:
self.y+=h | python | def ln(self, h=''):
"Line Feed; default value is last cell height"
self.x=self.l_margin
if(isinstance(h, basestring)):
self.y+=self.lasth
else:
self.y+=h | [
"def",
"ln",
"(",
"self",
",",
"h",
"=",
"''",
")",
":",
"self",
".",
"x",
"=",
"self",
".",
"l_margin",
"if",
"(",
"isinstance",
"(",
"h",
",",
"basestring",
")",
")",
":",
"self",
".",
"y",
"+=",
"self",
".",
"lasth",
"else",
":",
"self",
"... | Line Feed; default value is last cell height | [
"Line",
"Feed",
";",
"default",
"value",
"is",
"last",
"cell",
"height"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L1025-L1031 |
231,064 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.set_x | def set_x(self, x):
"Set x position"
if(x>=0):
self.x=x
else:
self.x=self.w+x | python | def set_x(self, x):
"Set x position"
if(x>=0):
self.x=x
else:
self.x=self.w+x | [
"def",
"set_x",
"(",
"self",
",",
"x",
")",
":",
"if",
"(",
"x",
">=",
"0",
")",
":",
"self",
".",
"x",
"=",
"x",
"else",
":",
"self",
".",
"x",
"=",
"self",
".",
"w",
"+",
"x"
] | Set x position | [
"Set",
"x",
"position"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L1037-L1042 |
231,065 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.set_y | def set_y(self, y):
"Set y position and reset x"
self.x=self.l_margin
if(y>=0):
self.y=y
else:
self.y=self.h+y | python | def set_y(self, y):
"Set y position and reset x"
self.x=self.l_margin
if(y>=0):
self.y=y
else:
self.y=self.h+y | [
"def",
"set_y",
"(",
"self",
",",
"y",
")",
":",
"self",
".",
"x",
"=",
"self",
".",
"l_margin",
"if",
"(",
"y",
">=",
"0",
")",
":",
"self",
".",
"y",
"=",
"y",
"else",
":",
"self",
".",
"y",
"=",
"self",
".",
"h",
"+",
"y"
] | Set y position and reset x | [
"Set",
"y",
"position",
"and",
"reset",
"x"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L1048-L1054 |
231,066 | m32/endesive | endesive/pdf/fpdf/fpdf.py | FPDF.output | def output(self, name='',dest=''):
"Output PDF to some destination"
#Finish document if necessary
if(self.state<3):
self.close()
dest=dest.upper()
if(dest==''):
if(name==''):
name='doc.pdf'
dest='I'
else:
dest='F'
if dest=='I':
print(self.buffer)
elif dest=='D':
print(self.buffer)
elif dest=='F':
#Save to local file
f=open(name,'wb')
if(not f):
self.error('Unable to create output file: '+name)
if PY3K:
# manage binary data as latin1 until PEP461 or similar is implemented
f.write(self.buffer.encode("latin1"))
else:
f.write(self.buffer)
f.close()
elif dest=='S':
#Return as a string
return self.buffer
else:
self.error('Incorrect output destination: '+dest)
return '' | python | def output(self, name='',dest=''):
"Output PDF to some destination"
#Finish document if necessary
if(self.state<3):
self.close()
dest=dest.upper()
if(dest==''):
if(name==''):
name='doc.pdf'
dest='I'
else:
dest='F'
if dest=='I':
print(self.buffer)
elif dest=='D':
print(self.buffer)
elif dest=='F':
#Save to local file
f=open(name,'wb')
if(not f):
self.error('Unable to create output file: '+name)
if PY3K:
# manage binary data as latin1 until PEP461 or similar is implemented
f.write(self.buffer.encode("latin1"))
else:
f.write(self.buffer)
f.close()
elif dest=='S':
#Return as a string
return self.buffer
else:
self.error('Incorrect output destination: '+dest)
return '' | [
"def",
"output",
"(",
"self",
",",
"name",
"=",
"''",
",",
"dest",
"=",
"''",
")",
":",
"#Finish document if necessary",
"if",
"(",
"self",
".",
"state",
"<",
"3",
")",
":",
"self",
".",
"close",
"(",
")",
"dest",
"=",
"dest",
".",
"upper",
"(",
... | Output PDF to some destination | [
"Output",
"PDF",
"to",
"some",
"destination"
] | 973091dc69847fe2df594c80ac9235a8d08460ff | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L1061-L1093 |
231,067 | kyper-data/python-highcharts | highcharts/highstock/highstock_helper.py | JSONPDecoder.decode | def decode(self, json_string):
"""
json_string is basicly string that you give to json.loads method
"""
default_obj = super(JSONPDecoder, self).decode(json_string)
return list(self._iterdecode(default_obj))[0] | python | def decode(self, json_string):
default_obj = super(JSONPDecoder, self).decode(json_string)
return list(self._iterdecode(default_obj))[0] | [
"def",
"decode",
"(",
"self",
",",
"json_string",
")",
":",
"default_obj",
"=",
"super",
"(",
"JSONPDecoder",
",",
"self",
")",
".",
"decode",
"(",
"json_string",
")",
"return",
"list",
"(",
"self",
".",
"_iterdecode",
"(",
"default_obj",
")",
")",
"[",
... | json_string is basicly string that you give to json.loads method | [
"json_string",
"is",
"basicly",
"string",
"that",
"you",
"give",
"to",
"json",
".",
"loads",
"method"
] | a4c488ae5c2e125616efad5a722f3dfd8a9bc450 | https://github.com/kyper-data/python-highcharts/blob/a4c488ae5c2e125616efad5a722f3dfd8a9bc450/highcharts/highstock/highstock_helper.py#L59-L66 |
231,068 | kyper-data/python-highcharts | highcharts/highmaps/highmaps.py | Highmap.add_data_set | def add_data_set(self, data, series_type="map", name=None, is_coordinate = False, **kwargs):
"""set data for series option in highmaps """
self.data_set_count += 1
if not name:
name = "Series %d" % self.data_set_count
kwargs.update({'name':name})
if is_coordinate:
self.data_is_coordinate = True
self.add_JSsource('https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.6/proj4.js')
if self.map and not self.data_temp:
series_data = Series([], series_type='map', **{'mapData': self.map})
series_data.__options__().update(SeriesOptions(series_type='map', **{'mapData': self.map}).__options__())
self.data_temp.append(series_data)
if self.map and 'mapData' in kwargs.keys():
kwargs.update({'mapData': self.map})
series_data = Series(data, series_type=series_type, **kwargs)
series_data.__options__().update(SeriesOptions(series_type=series_type, **kwargs).__options__())
self.data_temp.append(series_data) | python | def add_data_set(self, data, series_type="map", name=None, is_coordinate = False, **kwargs):
self.data_set_count += 1
if not name:
name = "Series %d" % self.data_set_count
kwargs.update({'name':name})
if is_coordinate:
self.data_is_coordinate = True
self.add_JSsource('https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.6/proj4.js')
if self.map and not self.data_temp:
series_data = Series([], series_type='map', **{'mapData': self.map})
series_data.__options__().update(SeriesOptions(series_type='map', **{'mapData': self.map}).__options__())
self.data_temp.append(series_data)
if self.map and 'mapData' in kwargs.keys():
kwargs.update({'mapData': self.map})
series_data = Series(data, series_type=series_type, **kwargs)
series_data.__options__().update(SeriesOptions(series_type=series_type, **kwargs).__options__())
self.data_temp.append(series_data) | [
"def",
"add_data_set",
"(",
"self",
",",
"data",
",",
"series_type",
"=",
"\"map\"",
",",
"name",
"=",
"None",
",",
"is_coordinate",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"data_set_count",
"+=",
"1",
"if",
"not",
"name",
":",
... | set data for series option in highmaps | [
"set",
"data",
"for",
"series",
"option",
"in",
"highmaps"
] | a4c488ae5c2e125616efad5a722f3dfd8a9bc450 | https://github.com/kyper-data/python-highcharts/blob/a4c488ae5c2e125616efad5a722f3dfd8a9bc450/highcharts/highmaps/highmaps.py#L201-L223 |
231,069 | kyper-data/python-highcharts | highcharts/highmaps/highmaps.py | Highmap.add_drilldown_data_set | def add_drilldown_data_set(self, data, series_type, id, **kwargs):
"""set data for drilldown option in highmaps
id must be input and corresponding to drilldown arguments in data series
"""
self.drilldown_data_set_count += 1
if self.drilldown_flag == False:
self.drilldown_flag = True
kwargs.update({'id':id})
series_data = Series(data, series_type=series_type, **kwargs)
series_data.__options__().update(SeriesOptions(series_type=series_type, **kwargs).__options__())
self.drilldown_data_temp.append(series_data) | python | def add_drilldown_data_set(self, data, series_type, id, **kwargs):
self.drilldown_data_set_count += 1
if self.drilldown_flag == False:
self.drilldown_flag = True
kwargs.update({'id':id})
series_data = Series(data, series_type=series_type, **kwargs)
series_data.__options__().update(SeriesOptions(series_type=series_type, **kwargs).__options__())
self.drilldown_data_temp.append(series_data) | [
"def",
"add_drilldown_data_set",
"(",
"self",
",",
"data",
",",
"series_type",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"drilldown_data_set_count",
"+=",
"1",
"if",
"self",
".",
"drilldown_flag",
"==",
"False",
":",
"self",
".",
"drilldow... | set data for drilldown option in highmaps
id must be input and corresponding to drilldown arguments in data series | [
"set",
"data",
"for",
"drilldown",
"option",
"in",
"highmaps",
"id",
"must",
"be",
"input",
"and",
"corresponding",
"to",
"drilldown",
"arguments",
"in",
"data",
"series"
] | a4c488ae5c2e125616efad5a722f3dfd8a9bc450 | https://github.com/kyper-data/python-highcharts/blob/a4c488ae5c2e125616efad5a722f3dfd8a9bc450/highcharts/highmaps/highmaps.py#L226-L237 |
231,070 | kyper-data/python-highcharts | highcharts/highmaps/highmaps.py | Highmap.add_data_from_jsonp | def add_data_from_jsonp(self, data_src, data_name = 'json_data', series_type="map", name=None, **kwargs):
"""add data directly from a https source
the data_src is the https link for data using jsonp
"""
self.jsonp_data_flag = True
self.jsonp_data_url = json.dumps(data_src)
if data_name == 'data':
data_name = 'json_'+ data_name
self.jsonp_data = data_name
self.add_data_set(RawJavaScriptText(data_name), series_type, name=name, **kwargs) | python | def add_data_from_jsonp(self, data_src, data_name = 'json_data', series_type="map", name=None, **kwargs):
self.jsonp_data_flag = True
self.jsonp_data_url = json.dumps(data_src)
if data_name == 'data':
data_name = 'json_'+ data_name
self.jsonp_data = data_name
self.add_data_set(RawJavaScriptText(data_name), series_type, name=name, **kwargs) | [
"def",
"add_data_from_jsonp",
"(",
"self",
",",
"data_src",
",",
"data_name",
"=",
"'json_data'",
",",
"series_type",
"=",
"\"map\"",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"jsonp_data_flag",
"=",
"True",
"self",
".",
"... | add data directly from a https source
the data_src is the https link for data using jsonp | [
"add",
"data",
"directly",
"from",
"a",
"https",
"source",
"the",
"data_src",
"is",
"the",
"https",
"link",
"for",
"data",
"using",
"jsonp"
] | a4c488ae5c2e125616efad5a722f3dfd8a9bc450 | https://github.com/kyper-data/python-highcharts/blob/a4c488ae5c2e125616efad5a722f3dfd8a9bc450/highcharts/highmaps/highmaps.py#L240-L249 |
231,071 | kyper-data/python-highcharts | highcharts/highmaps/highmaps.py | Highmap._get_jsmap_name | def _get_jsmap_name(self, url):
"""return 'name' of the map in .js format"""
ret = urlopen(url)
return ret.read().decode('utf-8').split('=')[0].replace(" ", "") | python | def _get_jsmap_name(self, url):
ret = urlopen(url)
return ret.read().decode('utf-8').split('=')[0].replace(" ", "") | [
"def",
"_get_jsmap_name",
"(",
"self",
",",
"url",
")",
":",
"ret",
"=",
"urlopen",
"(",
"url",
")",
"return",
"ret",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"split",
"(",
"'='",
")",
"[",
"0",
"]",
".",
"replace",
"(",
... | return 'name' of the map in .js format | [
"return",
"name",
"of",
"the",
"map",
"in",
".",
"js",
"format"
] | a4c488ae5c2e125616efad5a722f3dfd8a9bc450 | https://github.com/kyper-data/python-highcharts/blob/a4c488ae5c2e125616efad5a722f3dfd8a9bc450/highcharts/highmaps/highmaps.py#L347-L351 |
231,072 | kyper-data/python-highcharts | highcharts/highmaps/highmaps.py | Highmap.buildcontainer | def buildcontainer(self):
"""generate HTML div"""
if self.container:
return
# Create HTML div with style
if self.options['chart'].width:
if str(self.options['chart'].width)[-1] != '%':
self.div_style += 'width:%spx;' % self.options['chart'].width
else:
self.div_style += 'width:%s;' % self.options['chart'].width
if self.options['chart'].height:
if str(self.options['chart'].height)[-1] != '%':
self.div_style += 'height:%spx;' % self.options['chart'].height
else:
self.div_style += 'height:%s;' % self.options['chart'].height
self.div_name = self.options['chart'].__dict__['renderTo'] # recheck div name
self.container = self.containerheader + \
'<div id="%s" style="%s">%s</div>\n' % (self.div_name, self.div_style, self.loading) | python | def buildcontainer(self):
if self.container:
return
# Create HTML div with style
if self.options['chart'].width:
if str(self.options['chart'].width)[-1] != '%':
self.div_style += 'width:%spx;' % self.options['chart'].width
else:
self.div_style += 'width:%s;' % self.options['chart'].width
if self.options['chart'].height:
if str(self.options['chart'].height)[-1] != '%':
self.div_style += 'height:%spx;' % self.options['chart'].height
else:
self.div_style += 'height:%s;' % self.options['chart'].height
self.div_name = self.options['chart'].__dict__['renderTo'] # recheck div name
self.container = self.containerheader + \
'<div id="%s" style="%s">%s</div>\n' % (self.div_name, self.div_style, self.loading) | [
"def",
"buildcontainer",
"(",
"self",
")",
":",
"if",
"self",
".",
"container",
":",
"return",
"# Create HTML div with style",
"if",
"self",
".",
"options",
"[",
"'chart'",
"]",
".",
"width",
":",
"if",
"str",
"(",
"self",
".",
"options",
"[",
"'chart'",
... | generate HTML div | [
"generate",
"HTML",
"div"
] | a4c488ae5c2e125616efad5a722f3dfd8a9bc450 | https://github.com/kyper-data/python-highcharts/blob/a4c488ae5c2e125616efad5a722f3dfd8a9bc450/highcharts/highmaps/highmaps.py#L400-L418 |
231,073 | kyper-data/python-highcharts | highcharts/highcharts/highcharts.py | Highchart.add_data_set | def add_data_set(self, data, series_type="line", name=None, **kwargs):
"""set data for series option in highcharts"""
self.data_set_count += 1
if not name:
name = "Series %d" % self.data_set_count
kwargs.update({'name':name})
if series_type == 'treemap':
self.add_JSsource('http://code.highcharts.com/modules/treemap.js')
series_data = Series(data, series_type=series_type, **kwargs)
series_data.__options__().update(SeriesOptions(series_type=series_type, **kwargs).__options__())
self.data_temp.append(series_data) | python | def add_data_set(self, data, series_type="line", name=None, **kwargs):
self.data_set_count += 1
if not name:
name = "Series %d" % self.data_set_count
kwargs.update({'name':name})
if series_type == 'treemap':
self.add_JSsource('http://code.highcharts.com/modules/treemap.js')
series_data = Series(data, series_type=series_type, **kwargs)
series_data.__options__().update(SeriesOptions(series_type=series_type, **kwargs).__options__())
self.data_temp.append(series_data) | [
"def",
"add_data_set",
"(",
"self",
",",
"data",
",",
"series_type",
"=",
"\"line\"",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"data_set_count",
"+=",
"1",
"if",
"not",
"name",
":",
"name",
"=",
"\"Series %d\"",
"%",
... | set data for series option in highcharts | [
"set",
"data",
"for",
"series",
"option",
"in",
"highcharts"
] | a4c488ae5c2e125616efad5a722f3dfd8a9bc450 | https://github.com/kyper-data/python-highcharts/blob/a4c488ae5c2e125616efad5a722f3dfd8a9bc450/highcharts/highcharts/highcharts.py#L201-L215 |
231,074 | kyper-data/python-highcharts | highcharts/highmaps/highmap_helper.py | JSONPDecoder.json2datetime | def json2datetime(json):
"""Convert JSON representation to date or datetime object depending on
the argument count. Requires UTC datetime representation.
Raises ValueError if the string cannot be parsed.
"""
json_m = re.search(r'([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9]+)?(,[0-9]+)?', json)
args=json_m.group(0).split(',')
try:
args=map(int, args)
except ValueError:
raise ValueError('Invalid arguments: %s'%json)
if len(args)==3:
return datetime.datetime(args[0], args[1]+1, args[2])
elif len(args)==6:
return datetime.datetime(args[0], args[1]+1, args[2],
args[3], args[4], args[5], tzinfo=UTC())
elif len(args)==7:
args[6]*=1000
return datetime.datetime(args[0], args[1]+1, args[2],
args[3], args[4], args[5], args[6], tzinfo=UTC())
raise ValueError('Invalid number of arguments: %s'%json) | python | def json2datetime(json):
json_m = re.search(r'([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9]+)?(,[0-9]+)?', json)
args=json_m.group(0).split(',')
try:
args=map(int, args)
except ValueError:
raise ValueError('Invalid arguments: %s'%json)
if len(args)==3:
return datetime.datetime(args[0], args[1]+1, args[2])
elif len(args)==6:
return datetime.datetime(args[0], args[1]+1, args[2],
args[3], args[4], args[5], tzinfo=UTC())
elif len(args)==7:
args[6]*=1000
return datetime.datetime(args[0], args[1]+1, args[2],
args[3], args[4], args[5], args[6], tzinfo=UTC())
raise ValueError('Invalid number of arguments: %s'%json) | [
"def",
"json2datetime",
"(",
"json",
")",
":",
"json_m",
"=",
"re",
".",
"search",
"(",
"r'([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9]+)?(,[0-9]+)?'",
",",
"json",
")",
"args",
"=",
"json_m",
".",
"group",
"(",
"0",
")",
".",
"split",
"(",
"','",
")",
"try",... | Convert JSON representation to date or datetime object depending on
the argument count. Requires UTC datetime representation.
Raises ValueError if the string cannot be parsed. | [
"Convert",
"JSON",
"representation",
"to",
"date",
"or",
"datetime",
"object",
"depending",
"on",
"the",
"argument",
"count",
".",
"Requires",
"UTC",
"datetime",
"representation",
".",
"Raises",
"ValueError",
"if",
"the",
"string",
"cannot",
"be",
"parsed",
"."
... | a4c488ae5c2e125616efad5a722f3dfd8a9bc450 | https://github.com/kyper-data/python-highcharts/blob/a4c488ae5c2e125616efad5a722f3dfd8a9bc450/highcharts/highmaps/highmap_helper.py#L216-L239 |
231,075 | kyper-data/python-highcharts | highcharts/highstock/highstock.py | Highstock.set_options | def set_options(self, option_type, option_dict, force_options=False):
"""set plot options """
if force_options:
self.options[option_type].update(option_dict)
elif (option_type == 'yAxis' or option_type == 'xAxis') and isinstance(option_dict, list):
# For multi-Axis
self.options[option_type] = MultiAxis(option_type)
for each_dict in option_dict:
self.options[option_type].update(**each_dict)
elif option_type == 'colors':
self.options["colors"].set_colors(option_dict) # option_dict should be a list
elif option_type in ["global" , "lang"]: #Highcharts.setOptions:
self.setOptions[option_type].update_dict(**option_dict)
else:
self.options[option_type].update_dict(**option_dict) | python | def set_options(self, option_type, option_dict, force_options=False):
if force_options:
self.options[option_type].update(option_dict)
elif (option_type == 'yAxis' or option_type == 'xAxis') and isinstance(option_dict, list):
# For multi-Axis
self.options[option_type] = MultiAxis(option_type)
for each_dict in option_dict:
self.options[option_type].update(**each_dict)
elif option_type == 'colors':
self.options["colors"].set_colors(option_dict) # option_dict should be a list
elif option_type in ["global" , "lang"]: #Highcharts.setOptions:
self.setOptions[option_type].update_dict(**option_dict)
else:
self.options[option_type].update_dict(**option_dict) | [
"def",
"set_options",
"(",
"self",
",",
"option_type",
",",
"option_dict",
",",
"force_options",
"=",
"False",
")",
":",
"if",
"force_options",
":",
"self",
".",
"options",
"[",
"option_type",
"]",
".",
"update",
"(",
"option_dict",
")",
"elif",
"(",
"opti... | set plot options | [
"set",
"plot",
"options"
] | a4c488ae5c2e125616efad5a722f3dfd8a9bc450 | https://github.com/kyper-data/python-highcharts/blob/a4c488ae5c2e125616efad5a722f3dfd8a9bc450/highcharts/highstock/highstock.py#L265-L279 |
231,076 | kyper-data/python-highcharts | highcharts/highstock/highstock.py | Highstock.save_file | def save_file(self, filename = 'StockChart'):
""" save htmlcontent as .html file """
filename = filename + '.html'
with open(filename, 'w') as f:
#self.buildhtml()
f.write(self.htmlcontent)
f.closed | python | def save_file(self, filename = 'StockChart'):
filename = filename + '.html'
with open(filename, 'w') as f:
#self.buildhtml()
f.write(self.htmlcontent)
f.closed | [
"def",
"save_file",
"(",
"self",
",",
"filename",
"=",
"'StockChart'",
")",
":",
"filename",
"=",
"filename",
"+",
"'.html'",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"#self.buildhtml()",
"f",
".",
"write",
"(",
"self",
".",
"h... | save htmlcontent as .html file | [
"save",
"htmlcontent",
"as",
".",
"html",
"file"
] | a4c488ae5c2e125616efad5a722f3dfd8a9bc450 | https://github.com/kyper-data/python-highcharts/blob/a4c488ae5c2e125616efad5a722f3dfd8a9bc450/highcharts/highstock/highstock.py#L388-L396 |
231,077 | smoqadam/PyFladesk | pyfladesk/__init__.py | WebPage.acceptNavigationRequest | def acceptNavigationRequest(self, url, kind, is_main_frame):
"""Open external links in browser and internal links in the webview"""
ready_url = url.toEncoded().data().decode()
is_clicked = kind == self.NavigationTypeLinkClicked
if is_clicked and self.root_url not in ready_url:
QtGui.QDesktopServices.openUrl(url)
return False
return super(WebPage, self).acceptNavigationRequest(url, kind, is_main_frame) | python | def acceptNavigationRequest(self, url, kind, is_main_frame):
ready_url = url.toEncoded().data().decode()
is_clicked = kind == self.NavigationTypeLinkClicked
if is_clicked and self.root_url not in ready_url:
QtGui.QDesktopServices.openUrl(url)
return False
return super(WebPage, self).acceptNavigationRequest(url, kind, is_main_frame) | [
"def",
"acceptNavigationRequest",
"(",
"self",
",",
"url",
",",
"kind",
",",
"is_main_frame",
")",
":",
"ready_url",
"=",
"url",
".",
"toEncoded",
"(",
")",
".",
"data",
"(",
")",
".",
"decode",
"(",
")",
"is_clicked",
"=",
"kind",
"==",
"self",
".",
... | Open external links in browser and internal links in the webview | [
"Open",
"external",
"links",
"in",
"browser",
"and",
"internal",
"links",
"in",
"the",
"webview"
] | 48ce79ab3d4350a1b5c72abc49b3d00383f7b9cd | https://github.com/smoqadam/PyFladesk/blob/48ce79ab3d4350a1b5c72abc49b3d00383f7b9cd/pyfladesk/__init__.py#L27-L34 |
231,078 | cdgriffith/Box | box.py | _safe_attr | def _safe_attr(attr, camel_killer=False, replacement_char='x'):
"""Convert a key into something that is accessible as an attribute"""
allowed = string.ascii_letters + string.digits + '_'
attr = _safe_key(attr)
if camel_killer:
attr = _camel_killer(attr)
attr = attr.replace(' ', '_')
out = ''
for character in attr:
out += character if character in allowed else "_"
out = out.strip("_")
try:
int(out[0])
except (ValueError, IndexError):
pass
else:
out = '{0}{1}'.format(replacement_char, out)
if out in kwlist:
out = '{0}{1}'.format(replacement_char, out)
return re.sub('_+', '_', out) | python | def _safe_attr(attr, camel_killer=False, replacement_char='x'):
allowed = string.ascii_letters + string.digits + '_'
attr = _safe_key(attr)
if camel_killer:
attr = _camel_killer(attr)
attr = attr.replace(' ', '_')
out = ''
for character in attr:
out += character if character in allowed else "_"
out = out.strip("_")
try:
int(out[0])
except (ValueError, IndexError):
pass
else:
out = '{0}{1}'.format(replacement_char, out)
if out in kwlist:
out = '{0}{1}'.format(replacement_char, out)
return re.sub('_+', '_', out) | [
"def",
"_safe_attr",
"(",
"attr",
",",
"camel_killer",
"=",
"False",
",",
"replacement_char",
"=",
"'x'",
")",
":",
"allowed",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"+",
"'_'",
"attr",
"=",
"_safe_key",
"(",
"attr",
")",
"if"... | Convert a key into something that is accessible as an attribute | [
"Convert",
"a",
"key",
"into",
"something",
"that",
"is",
"accessible",
"as",
"an",
"attribute"
] | 5f09df824022127e7e335e3d993f7ddc1ed97fce | https://github.com/cdgriffith/Box/blob/5f09df824022127e7e335e3d993f7ddc1ed97fce/box.py#L137-L163 |
231,079 | cdgriffith/Box | box.py | _camel_killer | def _camel_killer(attr):
"""
CamelKiller, qu'est-ce que c'est?
Taken from http://stackoverflow.com/a/1176023/3244542
"""
try:
attr = str(attr)
except UnicodeEncodeError:
attr = attr.encode("utf-8", "ignore")
s1 = _first_cap_re.sub(r'\1_\2', attr)
s2 = _all_cap_re.sub(r'\1_\2', s1)
return re.sub('_+', '_', s2.casefold() if hasattr(s2, 'casefold')
else s2.lower()) | python | def _camel_killer(attr):
try:
attr = str(attr)
except UnicodeEncodeError:
attr = attr.encode("utf-8", "ignore")
s1 = _first_cap_re.sub(r'\1_\2', attr)
s2 = _all_cap_re.sub(r'\1_\2', s1)
return re.sub('_+', '_', s2.casefold() if hasattr(s2, 'casefold')
else s2.lower()) | [
"def",
"_camel_killer",
"(",
"attr",
")",
":",
"try",
":",
"attr",
"=",
"str",
"(",
"attr",
")",
"except",
"UnicodeEncodeError",
":",
"attr",
"=",
"attr",
".",
"encode",
"(",
"\"utf-8\"",
",",
"\"ignore\"",
")",
"s1",
"=",
"_first_cap_re",
".",
"sub",
... | CamelKiller, qu'est-ce que c'est?
Taken from http://stackoverflow.com/a/1176023/3244542 | [
"CamelKiller",
"qu",
"est",
"-",
"ce",
"que",
"c",
"est?"
] | 5f09df824022127e7e335e3d993f7ddc1ed97fce | https://github.com/cdgriffith/Box/blob/5f09df824022127e7e335e3d993f7ddc1ed97fce/box.py#L166-L180 |
231,080 | cdgriffith/Box | box.py | _conversion_checks | def _conversion_checks(item, keys, box_config, check_only=False,
pre_check=False):
"""
Internal use for checking if a duplicate safe attribute already exists
:param item: Item to see if a dup exists
:param keys: Keys to check against
:param box_config: Easier to pass in than ask for specfic items
:param check_only: Don't bother doing the conversion work
:param pre_check: Need to add the item to the list of keys to check
:return: the original unmodified key, if exists and not check_only
"""
if box_config['box_duplicates'] != 'ignore':
if pre_check:
keys = list(keys) + [item]
key_list = [(k,
_safe_attr(k, camel_killer=box_config['camel_killer_box'],
replacement_char=box_config['box_safe_prefix']
)) for k in keys]
if len(key_list) > len(set(x[1] for x in key_list)):
seen = set()
dups = set()
for x in key_list:
if x[1] in seen:
dups.add("{0}({1})".format(x[0], x[1]))
seen.add(x[1])
if box_config['box_duplicates'].startswith("warn"):
warnings.warn('Duplicate conversion attributes exist: '
'{0}'.format(dups))
else:
raise BoxError('Duplicate conversion attributes exist: '
'{0}'.format(dups))
if check_only:
return
# This way will be slower for warnings, as it will have double work
# But faster for the default 'ignore'
for k in keys:
if item == _safe_attr(k, camel_killer=box_config['camel_killer_box'],
replacement_char=box_config['box_safe_prefix']):
return k | python | def _conversion_checks(item, keys, box_config, check_only=False,
pre_check=False):
if box_config['box_duplicates'] != 'ignore':
if pre_check:
keys = list(keys) + [item]
key_list = [(k,
_safe_attr(k, camel_killer=box_config['camel_killer_box'],
replacement_char=box_config['box_safe_prefix']
)) for k in keys]
if len(key_list) > len(set(x[1] for x in key_list)):
seen = set()
dups = set()
for x in key_list:
if x[1] in seen:
dups.add("{0}({1})".format(x[0], x[1]))
seen.add(x[1])
if box_config['box_duplicates'].startswith("warn"):
warnings.warn('Duplicate conversion attributes exist: '
'{0}'.format(dups))
else:
raise BoxError('Duplicate conversion attributes exist: '
'{0}'.format(dups))
if check_only:
return
# This way will be slower for warnings, as it will have double work
# But faster for the default 'ignore'
for k in keys:
if item == _safe_attr(k, camel_killer=box_config['camel_killer_box'],
replacement_char=box_config['box_safe_prefix']):
return k | [
"def",
"_conversion_checks",
"(",
"item",
",",
"keys",
",",
"box_config",
",",
"check_only",
"=",
"False",
",",
"pre_check",
"=",
"False",
")",
":",
"if",
"box_config",
"[",
"'box_duplicates'",
"]",
"!=",
"'ignore'",
":",
"if",
"pre_check",
":",
"keys",
"=... | Internal use for checking if a duplicate safe attribute already exists
:param item: Item to see if a dup exists
:param keys: Keys to check against
:param box_config: Easier to pass in than ask for specfic items
:param check_only: Don't bother doing the conversion work
:param pre_check: Need to add the item to the list of keys to check
:return: the original unmodified key, if exists and not check_only | [
"Internal",
"use",
"for",
"checking",
"if",
"a",
"duplicate",
"safe",
"attribute",
"already",
"exists"
] | 5f09df824022127e7e335e3d993f7ddc1ed97fce | https://github.com/cdgriffith/Box/blob/5f09df824022127e7e335e3d993f7ddc1ed97fce/box.py#L196-L236 |
231,081 | cdgriffith/Box | box.py | Box.box_it_up | def box_it_up(self):
"""
Perform value lookup for all items in current dictionary,
generating all sub Box objects, while also running `box_it_up` on
any of those sub box objects.
"""
for k in self:
_conversion_checks(k, self.keys(), self._box_config,
check_only=True)
if self[k] is not self and hasattr(self[k], 'box_it_up'):
self[k].box_it_up() | python | def box_it_up(self):
for k in self:
_conversion_checks(k, self.keys(), self._box_config,
check_only=True)
if self[k] is not self and hasattr(self[k], 'box_it_up'):
self[k].box_it_up() | [
"def",
"box_it_up",
"(",
"self",
")",
":",
"for",
"k",
"in",
"self",
":",
"_conversion_checks",
"(",
"k",
",",
"self",
".",
"keys",
"(",
")",
",",
"self",
".",
"_box_config",
",",
"check_only",
"=",
"True",
")",
"if",
"self",
"[",
"k",
"]",
"is",
... | Perform value lookup for all items in current dictionary,
generating all sub Box objects, while also running `box_it_up` on
any of those sub box objects. | [
"Perform",
"value",
"lookup",
"for",
"all",
"items",
"in",
"current",
"dictionary",
"generating",
"all",
"sub",
"Box",
"objects",
"while",
"also",
"running",
"box_it_up",
"on",
"any",
"of",
"those",
"sub",
"box",
"objects",
"."
] | 5f09df824022127e7e335e3d993f7ddc1ed97fce | https://github.com/cdgriffith/Box/blob/5f09df824022127e7e335e3d993f7ddc1ed97fce/box.py#L336-L346 |
231,082 | cdgriffith/Box | box.py | Box.to_dict | def to_dict(self):
"""
Turn the Box and sub Boxes back into a native
python dictionary.
:return: python dictionary of this Box
"""
out_dict = dict(self)
for k, v in out_dict.items():
if v is self:
out_dict[k] = out_dict
elif hasattr(v, 'to_dict'):
out_dict[k] = v.to_dict()
elif hasattr(v, 'to_list'):
out_dict[k] = v.to_list()
return out_dict | python | def to_dict(self):
out_dict = dict(self)
for k, v in out_dict.items():
if v is self:
out_dict[k] = out_dict
elif hasattr(v, 'to_dict'):
out_dict[k] = v.to_dict()
elif hasattr(v, 'to_list'):
out_dict[k] = v.to_list()
return out_dict | [
"def",
"to_dict",
"(",
"self",
")",
":",
"out_dict",
"=",
"dict",
"(",
"self",
")",
"for",
"k",
",",
"v",
"in",
"out_dict",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"self",
":",
"out_dict",
"[",
"k",
"]",
"=",
"out_dict",
"elif",
"hasattr",
... | Turn the Box and sub Boxes back into a native
python dictionary.
:return: python dictionary of this Box | [
"Turn",
"the",
"Box",
"and",
"sub",
"Boxes",
"back",
"into",
"a",
"native",
"python",
"dictionary",
"."
] | 5f09df824022127e7e335e3d993f7ddc1ed97fce | https://github.com/cdgriffith/Box/blob/5f09df824022127e7e335e3d993f7ddc1ed97fce/box.py#L628-L643 |
231,083 | cdgriffith/Box | box.py | Box.to_json | def to_json(self, filename=None,
encoding="utf-8", errors="strict", **json_kwargs):
"""
Transform the Box object into a JSON string.
:param filename: If provided will save to file
:param encoding: File encoding
:param errors: How to handle encoding errors
:param json_kwargs: additional arguments to pass to json.dump(s)
:return: string of JSON or return of `json.dump`
"""
return _to_json(self.to_dict(), filename=filename,
encoding=encoding, errors=errors, **json_kwargs) | python | def to_json(self, filename=None,
encoding="utf-8", errors="strict", **json_kwargs):
return _to_json(self.to_dict(), filename=filename,
encoding=encoding, errors=errors, **json_kwargs) | [
"def",
"to_json",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"\"strict\"",
",",
"*",
"*",
"json_kwargs",
")",
":",
"return",
"_to_json",
"(",
"self",
".",
"to_dict",
"(",
")",
",",
"filename",
"=",... | Transform the Box object into a JSON string.
:param filename: If provided will save to file
:param encoding: File encoding
:param errors: How to handle encoding errors
:param json_kwargs: additional arguments to pass to json.dump(s)
:return: string of JSON or return of `json.dump` | [
"Transform",
"the",
"Box",
"object",
"into",
"a",
"JSON",
"string",
"."
] | 5f09df824022127e7e335e3d993f7ddc1ed97fce | https://github.com/cdgriffith/Box/blob/5f09df824022127e7e335e3d993f7ddc1ed97fce/box.py#L675-L687 |
231,084 | cdgriffith/Box | box.py | Box.from_json | def from_json(cls, json_string=None, filename=None,
encoding="utf-8", errors="strict", **kwargs):
"""
Transform a json object string into a Box object. If the incoming
json is a list, you must use BoxList.from_json.
:param json_string: string to pass to `json.loads`
:param filename: filename to open and pass to `json.load`
:param encoding: File encoding
:param errors: How to handle encoding errors
:param kwargs: parameters to pass to `Box()` or `json.loads`
:return: Box object from json data
"""
bx_args = {}
for arg in kwargs.copy():
if arg in BOX_PARAMETERS:
bx_args[arg] = kwargs.pop(arg)
data = _from_json(json_string, filename=filename,
encoding=encoding, errors=errors, **kwargs)
if not isinstance(data, dict):
raise BoxError('json data not returned as a dictionary, '
'but rather a {0}'.format(type(data).__name__))
return cls(data, **bx_args) | python | def from_json(cls, json_string=None, filename=None,
encoding="utf-8", errors="strict", **kwargs):
bx_args = {}
for arg in kwargs.copy():
if arg in BOX_PARAMETERS:
bx_args[arg] = kwargs.pop(arg)
data = _from_json(json_string, filename=filename,
encoding=encoding, errors=errors, **kwargs)
if not isinstance(data, dict):
raise BoxError('json data not returned as a dictionary, '
'but rather a {0}'.format(type(data).__name__))
return cls(data, **bx_args) | [
"def",
"from_json",
"(",
"cls",
",",
"json_string",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"\"strict\"",
",",
"*",
"*",
"kwargs",
")",
":",
"bx_args",
"=",
"{",
"}",
"for",
"arg",
"in",
"kwar... | Transform a json object string into a Box object. If the incoming
json is a list, you must use BoxList.from_json.
:param json_string: string to pass to `json.loads`
:param filename: filename to open and pass to `json.load`
:param encoding: File encoding
:param errors: How to handle encoding errors
:param kwargs: parameters to pass to `Box()` or `json.loads`
:return: Box object from json data | [
"Transform",
"a",
"json",
"object",
"string",
"into",
"a",
"Box",
"object",
".",
"If",
"the",
"incoming",
"json",
"is",
"a",
"list",
"you",
"must",
"use",
"BoxList",
".",
"from_json",
"."
] | 5f09df824022127e7e335e3d993f7ddc1ed97fce | https://github.com/cdgriffith/Box/blob/5f09df824022127e7e335e3d993f7ddc1ed97fce/box.py#L690-L714 |
231,085 | cdgriffith/Box | box.py | BoxList.to_json | def to_json(self, filename=None,
encoding="utf-8", errors="strict",
multiline=False, **json_kwargs):
"""
Transform the BoxList object into a JSON string.
:param filename: If provided will save to file
:param encoding: File encoding
:param errors: How to handle encoding errors
:param multiline: Put each item in list onto it's own line
:param json_kwargs: additional arguments to pass to json.dump(s)
:return: string of JSON or return of `json.dump`
"""
if filename and multiline:
lines = [_to_json(item, filename=False, encoding=encoding,
errors=errors, **json_kwargs) for item in self]
with open(filename, 'w', encoding=encoding, errors=errors) as f:
f.write("\n".join(lines).decode('utf-8') if
sys.version_info < (3, 0) else "\n".join(lines))
else:
return _to_json(self.to_list(), filename=filename,
encoding=encoding, errors=errors, **json_kwargs) | python | def to_json(self, filename=None,
encoding="utf-8", errors="strict",
multiline=False, **json_kwargs):
if filename and multiline:
lines = [_to_json(item, filename=False, encoding=encoding,
errors=errors, **json_kwargs) for item in self]
with open(filename, 'w', encoding=encoding, errors=errors) as f:
f.write("\n".join(lines).decode('utf-8') if
sys.version_info < (3, 0) else "\n".join(lines))
else:
return _to_json(self.to_list(), filename=filename,
encoding=encoding, errors=errors, **json_kwargs) | [
"def",
"to_json",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"\"strict\"",
",",
"multiline",
"=",
"False",
",",
"*",
"*",
"json_kwargs",
")",
":",
"if",
"filename",
"and",
"multiline",
":",
"lines",
... | Transform the BoxList object into a JSON string.
:param filename: If provided will save to file
:param encoding: File encoding
:param errors: How to handle encoding errors
:param multiline: Put each item in list onto it's own line
:param json_kwargs: additional arguments to pass to json.dump(s)
:return: string of JSON or return of `json.dump` | [
"Transform",
"the",
"BoxList",
"object",
"into",
"a",
"JSON",
"string",
"."
] | 5f09df824022127e7e335e3d993f7ddc1ed97fce | https://github.com/cdgriffith/Box/blob/5f09df824022127e7e335e3d993f7ddc1ed97fce/box.py#L871-L892 |
231,086 | cdgriffith/Box | box.py | ConfigBox.bool | def bool(self, item, default=None):
""" Return value of key as a boolean
:param item: key of value to transform
:param default: value to return if item does not exist
:return: approximated bool of value
"""
try:
item = self.__getattr__(item)
except AttributeError as err:
if default is not None:
return default
raise err
if isinstance(item, (bool, int)):
return bool(item)
if (isinstance(item, str) and
item.lower() in ('n', 'no', 'false', 'f', '0')):
return False
return True if item else False | python | def bool(self, item, default=None):
try:
item = self.__getattr__(item)
except AttributeError as err:
if default is not None:
return default
raise err
if isinstance(item, (bool, int)):
return bool(item)
if (isinstance(item, str) and
item.lower() in ('n', 'no', 'false', 'f', '0')):
return False
return True if item else False | [
"def",
"bool",
"(",
"self",
",",
"item",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"item",
"=",
"self",
".",
"__getattr__",
"(",
"item",
")",
"except",
"AttributeError",
"as",
"err",
":",
"if",
"default",
"is",
"not",
"None",
":",
"return",
... | Return value of key as a boolean
:param item: key of value to transform
:param default: value to return if item does not exist
:return: approximated bool of value | [
"Return",
"value",
"of",
"key",
"as",
"a",
"boolean"
] | 5f09df824022127e7e335e3d993f7ddc1ed97fce | https://github.com/cdgriffith/Box/blob/5f09df824022127e7e335e3d993f7ddc1ed97fce/box.py#L1006-L1027 |
231,087 | cdgriffith/Box | box.py | ConfigBox.int | def int(self, item, default=None):
""" Return value of key as an int
:param item: key of value to transform
:param default: value to return if item does not exist
:return: int of value
"""
try:
item = self.__getattr__(item)
except AttributeError as err:
if default is not None:
return default
raise err
return int(item) | python | def int(self, item, default=None):
try:
item = self.__getattr__(item)
except AttributeError as err:
if default is not None:
return default
raise err
return int(item) | [
"def",
"int",
"(",
"self",
",",
"item",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"item",
"=",
"self",
".",
"__getattr__",
"(",
"item",
")",
"except",
"AttributeError",
"as",
"err",
":",
"if",
"default",
"is",
"not",
"None",
":",
"return",
... | Return value of key as an int
:param item: key of value to transform
:param default: value to return if item does not exist
:return: int of value | [
"Return",
"value",
"of",
"key",
"as",
"an",
"int"
] | 5f09df824022127e7e335e3d993f7ddc1ed97fce | https://github.com/cdgriffith/Box/blob/5f09df824022127e7e335e3d993f7ddc1ed97fce/box.py#L1029-L1042 |
231,088 | cdgriffith/Box | box.py | ConfigBox.float | def float(self, item, default=None):
""" Return value of key as a float
:param item: key of value to transform
:param default: value to return if item does not exist
:return: float of value
"""
try:
item = self.__getattr__(item)
except AttributeError as err:
if default is not None:
return default
raise err
return float(item) | python | def float(self, item, default=None):
try:
item = self.__getattr__(item)
except AttributeError as err:
if default is not None:
return default
raise err
return float(item) | [
"def",
"float",
"(",
"self",
",",
"item",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"item",
"=",
"self",
".",
"__getattr__",
"(",
"item",
")",
"except",
"AttributeError",
"as",
"err",
":",
"if",
"default",
"is",
"not",
"None",
":",
"return",... | Return value of key as a float
:param item: key of value to transform
:param default: value to return if item does not exist
:return: float of value | [
"Return",
"value",
"of",
"key",
"as",
"a",
"float"
] | 5f09df824022127e7e335e3d993f7ddc1ed97fce | https://github.com/cdgriffith/Box/blob/5f09df824022127e7e335e3d993f7ddc1ed97fce/box.py#L1044-L1057 |
231,089 | ultrabug/py3status | py3status/module.py | Module.load_from_file | def load_from_file(filepath):
"""
Return user-written class object from given path.
"""
class_inst = None
expected_class = "Py3status"
module_name, file_ext = os.path.splitext(os.path.split(filepath)[-1])
if file_ext.lower() == ".py":
py_mod = imp.load_source(module_name, filepath)
if hasattr(py_mod, expected_class):
class_inst = py_mod.Py3status()
return class_inst | python | def load_from_file(filepath):
class_inst = None
expected_class = "Py3status"
module_name, file_ext = os.path.splitext(os.path.split(filepath)[-1])
if file_ext.lower() == ".py":
py_mod = imp.load_source(module_name, filepath)
if hasattr(py_mod, expected_class):
class_inst = py_mod.Py3status()
return class_inst | [
"def",
"load_from_file",
"(",
"filepath",
")",
":",
"class_inst",
"=",
"None",
"expected_class",
"=",
"\"Py3status\"",
"module_name",
",",
"file_ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"split",
"(",
"filepath",
")",
"[",... | Return user-written class object from given path. | [
"Return",
"user",
"-",
"written",
"class",
"object",
"from",
"given",
"path",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/module.py#L105-L116 |
231,090 | ultrabug/py3status | py3status/module.py | Module.load_from_namespace | def load_from_namespace(module_name):
"""
Load a py3status bundled module.
"""
class_inst = None
name = "py3status.modules.{}".format(module_name)
py_mod = __import__(name)
components = name.split(".")
for comp in components[1:]:
py_mod = getattr(py_mod, comp)
class_inst = py_mod.Py3status()
return class_inst | python | def load_from_namespace(module_name):
class_inst = None
name = "py3status.modules.{}".format(module_name)
py_mod = __import__(name)
components = name.split(".")
for comp in components[1:]:
py_mod = getattr(py_mod, comp)
class_inst = py_mod.Py3status()
return class_inst | [
"def",
"load_from_namespace",
"(",
"module_name",
")",
":",
"class_inst",
"=",
"None",
"name",
"=",
"\"py3status.modules.{}\"",
".",
"format",
"(",
"module_name",
")",
"py_mod",
"=",
"__import__",
"(",
"name",
")",
"components",
"=",
"name",
".",
"split",
"(",... | Load a py3status bundled module. | [
"Load",
"a",
"py3status",
"bundled",
"module",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/module.py#L119-L130 |
231,091 | ultrabug/py3status | py3status/module.py | Module.prepare_module | def prepare_module(self):
"""
Ready the module to get it ready to start.
"""
# Modules can define a post_config_hook() method which will be run
# after the module has had it config settings applied and before it has
# its main method(s) called for the first time. This allows modules to
# perform any necessary setup.
if self.has_post_config_hook:
try:
self.module_class.post_config_hook()
except Exception as e:
# An exception has been thrown in post_config_hook() disable
# the module and show error in module output
self.terminated = True
self.error_index = 0
self.error_messages = [
self.module_nice_name,
u"{}: {}".format(
self.module_nice_name, str(e) or e.__class__.__name__
),
]
self.error_output(self.error_messages[0])
msg = "Exception in `%s` post_config_hook()" % self.module_full_name
self._py3_wrapper.report_exception(msg, notify_user=False)
self._py3_wrapper.log("terminating module %s" % self.module_full_name)
self.enabled = True | python | def prepare_module(self):
# Modules can define a post_config_hook() method which will be run
# after the module has had it config settings applied and before it has
# its main method(s) called for the first time. This allows modules to
# perform any necessary setup.
if self.has_post_config_hook:
try:
self.module_class.post_config_hook()
except Exception as e:
# An exception has been thrown in post_config_hook() disable
# the module and show error in module output
self.terminated = True
self.error_index = 0
self.error_messages = [
self.module_nice_name,
u"{}: {}".format(
self.module_nice_name, str(e) or e.__class__.__name__
),
]
self.error_output(self.error_messages[0])
msg = "Exception in `%s` post_config_hook()" % self.module_full_name
self._py3_wrapper.report_exception(msg, notify_user=False)
self._py3_wrapper.log("terminating module %s" % self.module_full_name)
self.enabled = True | [
"def",
"prepare_module",
"(",
"self",
")",
":",
"# Modules can define a post_config_hook() method which will be run",
"# after the module has had it config settings applied and before it has",
"# its main method(s) called for the first time. This allows modules to",
"# perform any necessary setup... | Ready the module to get it ready to start. | [
"Ready",
"the",
"module",
"to",
"get",
"it",
"ready",
"to",
"start",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/module.py#L132-L159 |
231,092 | ultrabug/py3status | py3status/module.py | Module.runtime_error | def runtime_error(self, msg, method):
"""
Show the error in the bar
"""
if self.testing:
self._py3_wrapper.report_exception(msg)
raise KeyboardInterrupt
if self.error_hide:
self.hide_errors()
return
# only show first line of error
msg = msg.splitlines()[0]
errors = [self.module_nice_name, u"{}: {}".format(self.module_nice_name, msg)]
# if we have shown this error then keep in the same state
if self.error_messages != errors:
self.error_messages = errors
self.error_index = 0
self.error_output(self.error_messages[self.error_index], method) | python | def runtime_error(self, msg, method):
if self.testing:
self._py3_wrapper.report_exception(msg)
raise KeyboardInterrupt
if self.error_hide:
self.hide_errors()
return
# only show first line of error
msg = msg.splitlines()[0]
errors = [self.module_nice_name, u"{}: {}".format(self.module_nice_name, msg)]
# if we have shown this error then keep in the same state
if self.error_messages != errors:
self.error_messages = errors
self.error_index = 0
self.error_output(self.error_messages[self.error_index], method) | [
"def",
"runtime_error",
"(",
"self",
",",
"msg",
",",
"method",
")",
":",
"if",
"self",
".",
"testing",
":",
"self",
".",
"_py3_wrapper",
".",
"report_exception",
"(",
"msg",
")",
"raise",
"KeyboardInterrupt",
"if",
"self",
".",
"error_hide",
":",
"self",
... | Show the error in the bar | [
"Show",
"the",
"error",
"in",
"the",
"bar"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/module.py#L161-L182 |
231,093 | ultrabug/py3status | py3status/module.py | Module.error_output | def error_output(self, message, method_affected=None):
"""
Something is wrong with the module so we want to output the error to
the i3bar
"""
color_fn = self._py3_wrapper.get_config_attribute
color = color_fn(self.module_full_name, "color_error")
if hasattr(color, "none_setting"):
color = color_fn(self.module_full_name, "color_bad")
if hasattr(color, "none_setting"):
color = None
error = {
"full_text": message,
"color": color,
"instance": self.module_inst,
"name": self.module_name,
}
for method in self.methods.values():
if method_affected and method["method"] != method_affected:
continue
method["last_output"] = [error]
self.allow_config_clicks = False
self.set_updated() | python | def error_output(self, message, method_affected=None):
color_fn = self._py3_wrapper.get_config_attribute
color = color_fn(self.module_full_name, "color_error")
if hasattr(color, "none_setting"):
color = color_fn(self.module_full_name, "color_bad")
if hasattr(color, "none_setting"):
color = None
error = {
"full_text": message,
"color": color,
"instance": self.module_inst,
"name": self.module_name,
}
for method in self.methods.values():
if method_affected and method["method"] != method_affected:
continue
method["last_output"] = [error]
self.allow_config_clicks = False
self.set_updated() | [
"def",
"error_output",
"(",
"self",
",",
"message",
",",
"method_affected",
"=",
"None",
")",
":",
"color_fn",
"=",
"self",
".",
"_py3_wrapper",
".",
"get_config_attribute",
"color",
"=",
"color_fn",
"(",
"self",
".",
"module_full_name",
",",
"\"color_error\"",
... | Something is wrong with the module so we want to output the error to
the i3bar | [
"Something",
"is",
"wrong",
"with",
"the",
"module",
"so",
"we",
"want",
"to",
"output",
"the",
"error",
"to",
"the",
"i3bar"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/module.py#L184-L209 |
231,094 | ultrabug/py3status | py3status/module.py | Module.hide_errors | def hide_errors(self):
"""
hide the module in the i3bar
"""
for method in self.methods.values():
method["last_output"] = {}
self.allow_config_clicks = False
self.error_hide = True
self.set_updated() | python | def hide_errors(self):
for method in self.methods.values():
method["last_output"] = {}
self.allow_config_clicks = False
self.error_hide = True
self.set_updated() | [
"def",
"hide_errors",
"(",
"self",
")",
":",
"for",
"method",
"in",
"self",
".",
"methods",
".",
"values",
"(",
")",
":",
"method",
"[",
"\"last_output\"",
"]",
"=",
"{",
"}",
"self",
".",
"allow_config_clicks",
"=",
"False",
"self",
".",
"error_hide",
... | hide the module in the i3bar | [
"hide",
"the",
"module",
"in",
"the",
"i3bar"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/module.py#L211-L220 |
231,095 | ultrabug/py3status | py3status/module.py | Module.start_module | def start_module(self):
"""
Start the module running.
"""
self.prepare_module()
if not (self.disabled or self.terminated):
# Start the module and call its output method(s)
self._py3_wrapper.log("starting module %s" % self.module_full_name)
self._py3_wrapper.timeout_queue_add(self) | python | def start_module(self):
self.prepare_module()
if not (self.disabled or self.terminated):
# Start the module and call its output method(s)
self._py3_wrapper.log("starting module %s" % self.module_full_name)
self._py3_wrapper.timeout_queue_add(self) | [
"def",
"start_module",
"(",
"self",
")",
":",
"self",
".",
"prepare_module",
"(",
")",
"if",
"not",
"(",
"self",
".",
"disabled",
"or",
"self",
".",
"terminated",
")",
":",
"# Start the module and call its output method(s)",
"self",
".",
"_py3_wrapper",
".",
"... | Start the module running. | [
"Start",
"the",
"module",
"running",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/module.py#L222-L230 |
231,096 | ultrabug/py3status | py3status/module.py | Module.force_update | def force_update(self):
"""
Forces an update of the module.
"""
if self.disabled or self.terminated or not self.enabled:
return
# clear cached_until for each method to allow update
for meth in self.methods:
self.methods[meth]["cached_until"] = time()
if self.config["debug"]:
self._py3_wrapper.log("clearing cache for method {}".format(meth))
# set module to update
self._py3_wrapper.timeout_queue_add(self) | python | def force_update(self):
if self.disabled or self.terminated or not self.enabled:
return
# clear cached_until for each method to allow update
for meth in self.methods:
self.methods[meth]["cached_until"] = time()
if self.config["debug"]:
self._py3_wrapper.log("clearing cache for method {}".format(meth))
# set module to update
self._py3_wrapper.timeout_queue_add(self) | [
"def",
"force_update",
"(",
"self",
")",
":",
"if",
"self",
".",
"disabled",
"or",
"self",
".",
"terminated",
"or",
"not",
"self",
".",
"enabled",
":",
"return",
"# clear cached_until for each method to allow update",
"for",
"meth",
"in",
"self",
".",
"methods",... | Forces an update of the module. | [
"Forces",
"an",
"update",
"of",
"the",
"module",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/module.py#L232-L244 |
231,097 | ultrabug/py3status | py3status/module.py | Module.set_updated | def set_updated(self):
"""
Mark the module as updated.
We check if the actual content has changed and if so we trigger an
update in py3status.
"""
# get latest output
output = []
for method in self.methods.values():
data = method["last_output"]
if isinstance(data, list):
if self.testing and data:
data[0]["cached_until"] = method.get("cached_until")
output.extend(data)
else:
# if the output is not 'valid' then don't add it.
if data.get("full_text") or "separator" in data:
if self.testing:
data["cached_until"] = method.get("cached_until")
output.append(data)
# if changed store and force display update.
if output != self.last_output:
# has the modules output become urgent?
# we only care the update that this happens
# not any after then.
urgent = True in [x.get("urgent") for x in output]
if urgent != self.urgent:
self.urgent = urgent
else:
urgent = False
self.last_output = output
self._py3_wrapper.notify_update(self.module_full_name, urgent) | python | def set_updated(self):
# get latest output
output = []
for method in self.methods.values():
data = method["last_output"]
if isinstance(data, list):
if self.testing and data:
data[0]["cached_until"] = method.get("cached_until")
output.extend(data)
else:
# if the output is not 'valid' then don't add it.
if data.get("full_text") or "separator" in data:
if self.testing:
data["cached_until"] = method.get("cached_until")
output.append(data)
# if changed store and force display update.
if output != self.last_output:
# has the modules output become urgent?
# we only care the update that this happens
# not any after then.
urgent = True in [x.get("urgent") for x in output]
if urgent != self.urgent:
self.urgent = urgent
else:
urgent = False
self.last_output = output
self._py3_wrapper.notify_update(self.module_full_name, urgent) | [
"def",
"set_updated",
"(",
"self",
")",
":",
"# get latest output",
"output",
"=",
"[",
"]",
"for",
"method",
"in",
"self",
".",
"methods",
".",
"values",
"(",
")",
":",
"data",
"=",
"method",
"[",
"\"last_output\"",
"]",
"if",
"isinstance",
"(",
"data",... | Mark the module as updated.
We check if the actual content has changed and if so we trigger an
update in py3status. | [
"Mark",
"the",
"module",
"as",
"updated",
".",
"We",
"check",
"if",
"the",
"actual",
"content",
"has",
"changed",
"and",
"if",
"so",
"we",
"trigger",
"an",
"update",
"in",
"py3status",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/module.py#L270-L301 |
231,098 | ultrabug/py3status | py3status/module.py | Module._params_type | def _params_type(self, method_name, instance):
"""
Check to see if this is a legacy method or shiny new one
legacy update method:
def update(self, i3s_output_list, i3s_config):
...
new update method:
def update(self):
...
Returns False if the method does not exist,
else PARAMS_NEW or PARAMS_LEGACY
"""
method = getattr(instance, method_name, None)
if not method:
return False
# Check the parameters we simply count the number of args and don't
# allow any extras like keywords.
arg_count = 1
# on_click method has extra events parameter
if method_name == "on_click":
arg_count = 2
args, vargs, kw, defaults = inspect.getargspec(method)
if len(args) == arg_count and not vargs and not kw:
return self.PARAMS_NEW
else:
return self.PARAMS_LEGACY | python | def _params_type(self, method_name, instance):
method = getattr(instance, method_name, None)
if not method:
return False
# Check the parameters we simply count the number of args and don't
# allow any extras like keywords.
arg_count = 1
# on_click method has extra events parameter
if method_name == "on_click":
arg_count = 2
args, vargs, kw, defaults = inspect.getargspec(method)
if len(args) == arg_count and not vargs and not kw:
return self.PARAMS_NEW
else:
return self.PARAMS_LEGACY | [
"def",
"_params_type",
"(",
"self",
",",
"method_name",
",",
"instance",
")",
":",
"method",
"=",
"getattr",
"(",
"instance",
",",
"method_name",
",",
"None",
")",
"if",
"not",
"method",
":",
"return",
"False",
"# Check the parameters we simply count the number of... | Check to see if this is a legacy method or shiny new one
legacy update method:
def update(self, i3s_output_list, i3s_config):
...
new update method:
def update(self):
...
Returns False if the method does not exist,
else PARAMS_NEW or PARAMS_LEGACY | [
"Check",
"to",
"see",
"if",
"this",
"is",
"a",
"legacy",
"method",
"or",
"shiny",
"new",
"one"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/module.py#L550-L580 |
231,099 | ultrabug/py3status | py3status/module.py | Module.click_event | def click_event(self, event):
"""
Execute the 'on_click' method of this module with the given event.
"""
# we can prevent request that a refresh after the event has happened
# by setting this to True. Modules should do this via
# py3.prevent_refresh()
self.prevent_refresh = False
try:
if self.error_messages:
# we have error messages
button = event["button"]
if button == 1:
# cycle through to next message
self.error_index = (self.error_index + 1) % len(self.error_messages)
error = self.error_messages[self.error_index]
self.error_output(error)
if button == 3:
self.hide_errors()
if button != 2 or (self.terminated or self.disabled):
self.prevent_refresh = True
elif self.click_events:
click_method = getattr(self.module_class, "on_click")
if self.click_events == self.PARAMS_NEW:
# new style modules
click_method(event)
else:
# legacy modules had extra parameters passed
click_method(
self.i3status_thread.json_list,
self.config["py3_config"]["general"],
event,
)
self.set_updated()
else:
# nothing has happened so no need for refresh
self.prevent_refresh = True
except Exception:
msg = "on_click event in `{}` failed".format(self.module_full_name)
self._py3_wrapper.report_exception(msg) | python | def click_event(self, event):
# we can prevent request that a refresh after the event has happened
# by setting this to True. Modules should do this via
# py3.prevent_refresh()
self.prevent_refresh = False
try:
if self.error_messages:
# we have error messages
button = event["button"]
if button == 1:
# cycle through to next message
self.error_index = (self.error_index + 1) % len(self.error_messages)
error = self.error_messages[self.error_index]
self.error_output(error)
if button == 3:
self.hide_errors()
if button != 2 or (self.terminated or self.disabled):
self.prevent_refresh = True
elif self.click_events:
click_method = getattr(self.module_class, "on_click")
if self.click_events == self.PARAMS_NEW:
# new style modules
click_method(event)
else:
# legacy modules had extra parameters passed
click_method(
self.i3status_thread.json_list,
self.config["py3_config"]["general"],
event,
)
self.set_updated()
else:
# nothing has happened so no need for refresh
self.prevent_refresh = True
except Exception:
msg = "on_click event in `{}` failed".format(self.module_full_name)
self._py3_wrapper.report_exception(msg) | [
"def",
"click_event",
"(",
"self",
",",
"event",
")",
":",
"# we can prevent request that a refresh after the event has happened",
"# by setting this to True. Modules should do this via",
"# py3.prevent_refresh()",
"self",
".",
"prevent_refresh",
"=",
"False",
"try",
":",
"if",
... | Execute the 'on_click' method of this module with the given event. | [
"Execute",
"the",
"on_click",
"method",
"of",
"this",
"module",
"with",
"the",
"given",
"event",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/module.py#L850-L890 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.