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 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
250,100 | rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_change_device | async def async_change_device(
self, device_id: int, group_number: int, unit_number: int,
enable_status: ESFlags, switches: SwitchFlags) -> None:
"""
Change settings for a device on the base unit.
:param device_id: unique identifier for the device to be changed
:param group_number: group number the device is to be assigned to
:param unit_number: unit number the device is to be assigned to
:param enable_status: flags indicating settings to enable
:param switches: indicates switches that will be activated when device is triggered
"""
# Lookup device using zone to obtain an accurate index and current
# values, which will be needed to perform the change command
device = self._devices[device_id]
# If it is a Special device, automatically use the other function
# instead (without changing any of the special fields)
if isinstance(device, SpecialDevice):
await self.async_change_special_device(
device_id, group_number, unit_number, enable_status, switches,
device.special_status, device.high_limit, device.low_limit,
device.control_high_limit, device.control_low_limit)
return
response = await self._protocol.async_execute(
GetDeviceCommand(device.category, device.group_number, device.unit_number))
if isinstance(response, DeviceInfoResponse):
response = await self._protocol.async_execute(
ChangeDeviceCommand(
device.category, response.index, group_number, unit_number,
enable_status, switches))
if isinstance(response, DeviceSettingsResponse):
device._handle_response(response) # pylint: disable=protected-access
if isinstance(response, DeviceNotFoundResponse):
raise ValueError("Device to be changed was not found") | python | async def async_change_device(
self, device_id: int, group_number: int, unit_number: int,
enable_status: ESFlags, switches: SwitchFlags) -> None:
"""
Change settings for a device on the base unit.
:param device_id: unique identifier for the device to be changed
:param group_number: group number the device is to be assigned to
:param unit_number: unit number the device is to be assigned to
:param enable_status: flags indicating settings to enable
:param switches: indicates switches that will be activated when device is triggered
"""
# Lookup device using zone to obtain an accurate index and current
# values, which will be needed to perform the change command
device = self._devices[device_id]
# If it is a Special device, automatically use the other function
# instead (without changing any of the special fields)
if isinstance(device, SpecialDevice):
await self.async_change_special_device(
device_id, group_number, unit_number, enable_status, switches,
device.special_status, device.high_limit, device.low_limit,
device.control_high_limit, device.control_low_limit)
return
response = await self._protocol.async_execute(
GetDeviceCommand(device.category, device.group_number, device.unit_number))
if isinstance(response, DeviceInfoResponse):
response = await self._protocol.async_execute(
ChangeDeviceCommand(
device.category, response.index, group_number, unit_number,
enable_status, switches))
if isinstance(response, DeviceSettingsResponse):
device._handle_response(response) # pylint: disable=protected-access
if isinstance(response, DeviceNotFoundResponse):
raise ValueError("Device to be changed was not found") | [
"async",
"def",
"async_change_device",
"(",
"self",
",",
"device_id",
":",
"int",
",",
"group_number",
":",
"int",
",",
"unit_number",
":",
"int",
",",
"enable_status",
":",
"ESFlags",
",",
"switches",
":",
"SwitchFlags",
")",
"->",
"None",
":",
"# Lookup device using zone to obtain an accurate index and current",
"# values, which will be needed to perform the change command",
"device",
"=",
"self",
".",
"_devices",
"[",
"device_id",
"]",
"# If it is a Special device, automatically use the other function",
"# instead (without changing any of the special fields)",
"if",
"isinstance",
"(",
"device",
",",
"SpecialDevice",
")",
":",
"await",
"self",
".",
"async_change_special_device",
"(",
"device_id",
",",
"group_number",
",",
"unit_number",
",",
"enable_status",
",",
"switches",
",",
"device",
".",
"special_status",
",",
"device",
".",
"high_limit",
",",
"device",
".",
"low_limit",
",",
"device",
".",
"control_high_limit",
",",
"device",
".",
"control_low_limit",
")",
"return",
"response",
"=",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"GetDeviceCommand",
"(",
"device",
".",
"category",
",",
"device",
".",
"group_number",
",",
"device",
".",
"unit_number",
")",
")",
"if",
"isinstance",
"(",
"response",
",",
"DeviceInfoResponse",
")",
":",
"response",
"=",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"ChangeDeviceCommand",
"(",
"device",
".",
"category",
",",
"response",
".",
"index",
",",
"group_number",
",",
"unit_number",
",",
"enable_status",
",",
"switches",
")",
")",
"if",
"isinstance",
"(",
"response",
",",
"DeviceSettingsResponse",
")",
":",
"device",
".",
"_handle_response",
"(",
"response",
")",
"# pylint: disable=protected-access",
"if",
"isinstance",
"(",
"response",
",",
"DeviceNotFoundResponse",
")",
":",
"raise",
"ValueError",
"(",
"\"Device to be changed was not found\"",
")"
] | Change settings for a device on the base unit.
:param device_id: unique identifier for the device to be changed
:param group_number: group number the device is to be assigned to
:param unit_number: unit number the device is to be assigned to
:param enable_status: flags indicating settings to enable
:param switches: indicates switches that will be activated when device is triggered | [
"Change",
"settings",
"for",
"a",
"device",
"on",
"the",
"base",
"unit",
"."
] | 62360fbab2e90bf04d52b547093bdab2d4e389b4 | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L335-L371 |
250,101 | rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_change_special_device | async def async_change_special_device(
self, device_id: int, group_number: int, unit_number: int,
enable_status: ESFlags, switches: SwitchFlags,
special_status: SSFlags, high_limit: Optional[Union[int, float]],
low_limit: Optional[Union[int, float]],
control_high_limit: Optional[Union[int, float]],
control_low_limit: Optional[Union[int, float]]) -> None:
"""
Change settings for a 'Special' device on the base unit.
:param device_id: unique identifier for the device to be changed
:param group_number: group number the device is to be assigned to
:param unit_number: unit number the device is to be assigned to
:param enable_status: flags indicating settings to enable
:param switches: indicates switches that will be activated when device is triggered
:param special_status: flags indicating 'Special' settings to enable
:param high_limit: triggers on readings higher than value
:param low_limit: triggers on readings lower than value
:param control_high_limit: trigger switch for readings higher than value
:param control_low_limit: trigger switch for readings lower than value
"""
# Lookup device using zone to obtain an accurate index and current
# values, which will be needed to perform the change command
device = self._devices[device_id]
# Verify it is a Special device
if not isinstance(device, SpecialDevice):
raise ValueError("Device to be changed is not a Special device")
response = await self._protocol.async_execute(
GetDeviceCommand(device.category, device.group_number, device.unit_number))
if isinstance(response, DeviceInfoResponse):
# Control limits only specified when they are supported
if response.control_limit_fields_exist:
command = ChangeSpecial2DeviceCommand(
device.category, response.index, group_number, unit_number,
enable_status, switches, response.current_status, response.down_count,
response.message_attribute, response.current_reading, special_status,
high_limit, low_limit, control_high_limit, control_low_limit)
else:
command = ChangeSpecialDeviceCommand(
device.category, response.index, group_number, unit_number,
enable_status, switches, response.current_status, response.down_count,
response.message_attribute, response.current_reading, special_status,
high_limit, low_limit)
response = await self._protocol.async_execute(command)
if isinstance(response, DeviceSettingsResponse):
device._handle_response(response) # pylint: disable=protected-access
if isinstance(response, DeviceNotFoundResponse):
raise ValueError("Device to be changed was not found") | python | async def async_change_special_device(
self, device_id: int, group_number: int, unit_number: int,
enable_status: ESFlags, switches: SwitchFlags,
special_status: SSFlags, high_limit: Optional[Union[int, float]],
low_limit: Optional[Union[int, float]],
control_high_limit: Optional[Union[int, float]],
control_low_limit: Optional[Union[int, float]]) -> None:
"""
Change settings for a 'Special' device on the base unit.
:param device_id: unique identifier for the device to be changed
:param group_number: group number the device is to be assigned to
:param unit_number: unit number the device is to be assigned to
:param enable_status: flags indicating settings to enable
:param switches: indicates switches that will be activated when device is triggered
:param special_status: flags indicating 'Special' settings to enable
:param high_limit: triggers on readings higher than value
:param low_limit: triggers on readings lower than value
:param control_high_limit: trigger switch for readings higher than value
:param control_low_limit: trigger switch for readings lower than value
"""
# Lookup device using zone to obtain an accurate index and current
# values, which will be needed to perform the change command
device = self._devices[device_id]
# Verify it is a Special device
if not isinstance(device, SpecialDevice):
raise ValueError("Device to be changed is not a Special device")
response = await self._protocol.async_execute(
GetDeviceCommand(device.category, device.group_number, device.unit_number))
if isinstance(response, DeviceInfoResponse):
# Control limits only specified when they are supported
if response.control_limit_fields_exist:
command = ChangeSpecial2DeviceCommand(
device.category, response.index, group_number, unit_number,
enable_status, switches, response.current_status, response.down_count,
response.message_attribute, response.current_reading, special_status,
high_limit, low_limit, control_high_limit, control_low_limit)
else:
command = ChangeSpecialDeviceCommand(
device.category, response.index, group_number, unit_number,
enable_status, switches, response.current_status, response.down_count,
response.message_attribute, response.current_reading, special_status,
high_limit, low_limit)
response = await self._protocol.async_execute(command)
if isinstance(response, DeviceSettingsResponse):
device._handle_response(response) # pylint: disable=protected-access
if isinstance(response, DeviceNotFoundResponse):
raise ValueError("Device to be changed was not found") | [
"async",
"def",
"async_change_special_device",
"(",
"self",
",",
"device_id",
":",
"int",
",",
"group_number",
":",
"int",
",",
"unit_number",
":",
"int",
",",
"enable_status",
":",
"ESFlags",
",",
"switches",
":",
"SwitchFlags",
",",
"special_status",
":",
"SSFlags",
",",
"high_limit",
":",
"Optional",
"[",
"Union",
"[",
"int",
",",
"float",
"]",
"]",
",",
"low_limit",
":",
"Optional",
"[",
"Union",
"[",
"int",
",",
"float",
"]",
"]",
",",
"control_high_limit",
":",
"Optional",
"[",
"Union",
"[",
"int",
",",
"float",
"]",
"]",
",",
"control_low_limit",
":",
"Optional",
"[",
"Union",
"[",
"int",
",",
"float",
"]",
"]",
")",
"->",
"None",
":",
"# Lookup device using zone to obtain an accurate index and current",
"# values, which will be needed to perform the change command",
"device",
"=",
"self",
".",
"_devices",
"[",
"device_id",
"]",
"# Verify it is a Special device",
"if",
"not",
"isinstance",
"(",
"device",
",",
"SpecialDevice",
")",
":",
"raise",
"ValueError",
"(",
"\"Device to be changed is not a Special device\"",
")",
"response",
"=",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"GetDeviceCommand",
"(",
"device",
".",
"category",
",",
"device",
".",
"group_number",
",",
"device",
".",
"unit_number",
")",
")",
"if",
"isinstance",
"(",
"response",
",",
"DeviceInfoResponse",
")",
":",
"# Control limits only specified when they are supported",
"if",
"response",
".",
"control_limit_fields_exist",
":",
"command",
"=",
"ChangeSpecial2DeviceCommand",
"(",
"device",
".",
"category",
",",
"response",
".",
"index",
",",
"group_number",
",",
"unit_number",
",",
"enable_status",
",",
"switches",
",",
"response",
".",
"current_status",
",",
"response",
".",
"down_count",
",",
"response",
".",
"message_attribute",
",",
"response",
".",
"current_reading",
",",
"special_status",
",",
"high_limit",
",",
"low_limit",
",",
"control_high_limit",
",",
"control_low_limit",
")",
"else",
":",
"command",
"=",
"ChangeSpecialDeviceCommand",
"(",
"device",
".",
"category",
",",
"response",
".",
"index",
",",
"group_number",
",",
"unit_number",
",",
"enable_status",
",",
"switches",
",",
"response",
".",
"current_status",
",",
"response",
".",
"down_count",
",",
"response",
".",
"message_attribute",
",",
"response",
".",
"current_reading",
",",
"special_status",
",",
"high_limit",
",",
"low_limit",
")",
"response",
"=",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"command",
")",
"if",
"isinstance",
"(",
"response",
",",
"DeviceSettingsResponse",
")",
":",
"device",
".",
"_handle_response",
"(",
"response",
")",
"# pylint: disable=protected-access",
"if",
"isinstance",
"(",
"response",
",",
"DeviceNotFoundResponse",
")",
":",
"raise",
"ValueError",
"(",
"\"Device to be changed was not found\"",
")"
] | Change settings for a 'Special' device on the base unit.
:param device_id: unique identifier for the device to be changed
:param group_number: group number the device is to be assigned to
:param unit_number: unit number the device is to be assigned to
:param enable_status: flags indicating settings to enable
:param switches: indicates switches that will be activated when device is triggered
:param special_status: flags indicating 'Special' settings to enable
:param high_limit: triggers on readings higher than value
:param low_limit: triggers on readings lower than value
:param control_high_limit: trigger switch for readings higher than value
:param control_low_limit: trigger switch for readings lower than value | [
"Change",
"settings",
"for",
"a",
"Special",
"device",
"on",
"the",
"base",
"unit",
"."
] | 62360fbab2e90bf04d52b547093bdab2d4e389b4 | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L373-L423 |
250,102 | rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_delete_device | async def async_delete_device(self, device_id: int) -> None:
"""
Delete an enrolled device.
:param device_id: unique identifier for the device to be deleted
"""
# Lookup device using zone to obtain an accurate index, which is
# needed to perform the delete command
device = self._devices[device_id]
response = await self._protocol.async_execute(
GetDeviceCommand(device.category, device.group_number, device.unit_number))
if isinstance(response, DeviceInfoResponse):
response = await self._protocol.async_execute(
DeleteDeviceCommand(device.category, response.index))
if isinstance(response, DeviceDeletedResponse):
self._devices._delete(device) # pylint: disable=protected-access
if self._on_device_deleted:
try:
self._on_device_deleted(self, device) # pylint: disable=protected-access
except Exception: # pylint: disable=broad-except
_LOGGER.error(
"Unhandled exception in on_device_deleted callback",
exc_info=True)
if isinstance(response, DeviceNotFoundResponse):
raise ValueError("Device to be deleted was not found") | python | async def async_delete_device(self, device_id: int) -> None:
"""
Delete an enrolled device.
:param device_id: unique identifier for the device to be deleted
"""
# Lookup device using zone to obtain an accurate index, which is
# needed to perform the delete command
device = self._devices[device_id]
response = await self._protocol.async_execute(
GetDeviceCommand(device.category, device.group_number, device.unit_number))
if isinstance(response, DeviceInfoResponse):
response = await self._protocol.async_execute(
DeleteDeviceCommand(device.category, response.index))
if isinstance(response, DeviceDeletedResponse):
self._devices._delete(device) # pylint: disable=protected-access
if self._on_device_deleted:
try:
self._on_device_deleted(self, device) # pylint: disable=protected-access
except Exception: # pylint: disable=broad-except
_LOGGER.error(
"Unhandled exception in on_device_deleted callback",
exc_info=True)
if isinstance(response, DeviceNotFoundResponse):
raise ValueError("Device to be deleted was not found") | [
"async",
"def",
"async_delete_device",
"(",
"self",
",",
"device_id",
":",
"int",
")",
"->",
"None",
":",
"# Lookup device using zone to obtain an accurate index, which is",
"# needed to perform the delete command",
"device",
"=",
"self",
".",
"_devices",
"[",
"device_id",
"]",
"response",
"=",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"GetDeviceCommand",
"(",
"device",
".",
"category",
",",
"device",
".",
"group_number",
",",
"device",
".",
"unit_number",
")",
")",
"if",
"isinstance",
"(",
"response",
",",
"DeviceInfoResponse",
")",
":",
"response",
"=",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"DeleteDeviceCommand",
"(",
"device",
".",
"category",
",",
"response",
".",
"index",
")",
")",
"if",
"isinstance",
"(",
"response",
",",
"DeviceDeletedResponse",
")",
":",
"self",
".",
"_devices",
".",
"_delete",
"(",
"device",
")",
"# pylint: disable=protected-access",
"if",
"self",
".",
"_on_device_deleted",
":",
"try",
":",
"self",
".",
"_on_device_deleted",
"(",
"self",
",",
"device",
")",
"# pylint: disable=protected-access",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"_LOGGER",
".",
"error",
"(",
"\"Unhandled exception in on_device_deleted callback\"",
",",
"exc_info",
"=",
"True",
")",
"if",
"isinstance",
"(",
"response",
",",
"DeviceNotFoundResponse",
")",
":",
"raise",
"ValueError",
"(",
"\"Device to be deleted was not found\"",
")"
] | Delete an enrolled device.
:param device_id: unique identifier for the device to be deleted | [
"Delete",
"an",
"enrolled",
"device",
"."
] | 62360fbab2e90bf04d52b547093bdab2d4e389b4 | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L425-L450 |
250,103 | rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_get_event_log | async def async_get_event_log(self, index: int) -> Optional[EventLogResponse]:
"""
Get an entry from the event log.
:param index: Index for the event log entry to be obtained.
:return: Response containing the event log entry, or None if not found.
"""
response = await self._protocol.async_execute(
GetEventLogCommand(index))
if isinstance(response, EventLogResponse):
return response
return None | python | async def async_get_event_log(self, index: int) -> Optional[EventLogResponse]:
"""
Get an entry from the event log.
:param index: Index for the event log entry to be obtained.
:return: Response containing the event log entry, or None if not found.
"""
response = await self._protocol.async_execute(
GetEventLogCommand(index))
if isinstance(response, EventLogResponse):
return response
return None | [
"async",
"def",
"async_get_event_log",
"(",
"self",
",",
"index",
":",
"int",
")",
"->",
"Optional",
"[",
"EventLogResponse",
"]",
":",
"response",
"=",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"GetEventLogCommand",
"(",
"index",
")",
")",
"if",
"isinstance",
"(",
"response",
",",
"EventLogResponse",
")",
":",
"return",
"response",
"return",
"None"
] | Get an entry from the event log.
:param index: Index for the event log entry to be obtained.
:return: Response containing the event log entry, or None if not found. | [
"Get",
"an",
"entry",
"from",
"the",
"event",
"log",
"."
] | 62360fbab2e90bf04d52b547093bdab2d4e389b4 | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L465-L477 |
250,104 | rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_get_sensor_log | async def async_get_sensor_log(self, index: int) -> Optional[SensorLogResponse]:
"""
Get an entry from the Special sensor log.
:param index: Index for the sensor log entry to be obtained.
:return: Response containing the sensor log entry, or None if not found.
"""
response = await self._protocol.async_execute(
GetSensorLogCommand(index))
if isinstance(response, SensorLogResponse):
return response
return None | python | async def async_get_sensor_log(self, index: int) -> Optional[SensorLogResponse]:
"""
Get an entry from the Special sensor log.
:param index: Index for the sensor log entry to be obtained.
:return: Response containing the sensor log entry, or None if not found.
"""
response = await self._protocol.async_execute(
GetSensorLogCommand(index))
if isinstance(response, SensorLogResponse):
return response
return None | [
"async",
"def",
"async_get_sensor_log",
"(",
"self",
",",
"index",
":",
"int",
")",
"->",
"Optional",
"[",
"SensorLogResponse",
"]",
":",
"response",
"=",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"GetSensorLogCommand",
"(",
"index",
")",
")",
"if",
"isinstance",
"(",
"response",
",",
"SensorLogResponse",
")",
":",
"return",
"response",
"return",
"None"
] | Get an entry from the Special sensor log.
:param index: Index for the sensor log entry to be obtained.
:return: Response containing the sensor log entry, or None if not found. | [
"Get",
"an",
"entry",
"from",
"the",
"Special",
"sensor",
"log",
"."
] | 62360fbab2e90bf04d52b547093bdab2d4e389b4 | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L479-L491 |
250,105 | rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_set_operation_mode | async def async_set_operation_mode(
self, operation_mode: OperationMode, password: str = '') -> None:
"""
Set the operation mode on the base unit.
:param operation_mode: the operation mode to change to
:param password: if specified, will be used instead of the password
property when issuing the command
"""
await self._protocol.async_execute(
SetOpModeCommand(operation_mode),
password=password) | python | async def async_set_operation_mode(
self, operation_mode: OperationMode, password: str = '') -> None:
"""
Set the operation mode on the base unit.
:param operation_mode: the operation mode to change to
:param password: if specified, will be used instead of the password
property when issuing the command
"""
await self._protocol.async_execute(
SetOpModeCommand(operation_mode),
password=password) | [
"async",
"def",
"async_set_operation_mode",
"(",
"self",
",",
"operation_mode",
":",
"OperationMode",
",",
"password",
":",
"str",
"=",
"''",
")",
"->",
"None",
":",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"SetOpModeCommand",
"(",
"operation_mode",
")",
",",
"password",
"=",
"password",
")"
] | Set the operation mode on the base unit.
:param operation_mode: the operation mode to change to
:param password: if specified, will be used instead of the password
property when issuing the command | [
"Set",
"the",
"operation",
"mode",
"on",
"the",
"base",
"unit",
"."
] | 62360fbab2e90bf04d52b547093bdab2d4e389b4 | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L504-L516 |
250,106 | rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.async_set_switch_state | async def async_set_switch_state(
self, switch_number: SwitchNumber, state: bool) -> None:
"""
Turn a switch on or off.
:param switch_number: the switch to be set.
:param state: True to turn on, False to turn off.
"""
await self._protocol.async_execute(
SetSwitchCommand(
switch_number,
SwitchState.On if state else SwitchState.Off)) | python | async def async_set_switch_state(
self, switch_number: SwitchNumber, state: bool) -> None:
"""
Turn a switch on or off.
:param switch_number: the switch to be set.
:param state: True to turn on, False to turn off.
"""
await self._protocol.async_execute(
SetSwitchCommand(
switch_number,
SwitchState.On if state else SwitchState.Off)) | [
"async",
"def",
"async_set_switch_state",
"(",
"self",
",",
"switch_number",
":",
"SwitchNumber",
",",
"state",
":",
"bool",
")",
"->",
"None",
":",
"await",
"self",
".",
"_protocol",
".",
"async_execute",
"(",
"SetSwitchCommand",
"(",
"switch_number",
",",
"SwitchState",
".",
"On",
"if",
"state",
"else",
"SwitchState",
".",
"Off",
")",
")"
] | Turn a switch on or off.
:param switch_number: the switch to be set.
:param state: True to turn on, False to turn off. | [
"Turn",
"a",
"switch",
"on",
"or",
"off",
"."
] | 62360fbab2e90bf04d52b547093bdab2d4e389b4 | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L518-L530 |
250,107 | rorr73/LifeSOSpy | lifesospy/baseunit.py | BaseUnit.as_dict | def as_dict(self) -> Dict[str, Any]:
"""Converts to a dict of attributes for easier serialization."""
def _on_filter(obj: Any, name: str) -> bool:
# Filter out any callbacks
if isinstance(obj, BaseUnit):
if name.startswith('on_'):
return False
return True
return serializable(self, on_filter=_on_filter) | python | def as_dict(self) -> Dict[str, Any]:
"""Converts to a dict of attributes for easier serialization."""
def _on_filter(obj: Any, name: str) -> bool:
# Filter out any callbacks
if isinstance(obj, BaseUnit):
if name.startswith('on_'):
return False
return True
return serializable(self, on_filter=_on_filter) | [
"def",
"as_dict",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"def",
"_on_filter",
"(",
"obj",
":",
"Any",
",",
"name",
":",
"str",
")",
"->",
"bool",
":",
"# Filter out any callbacks",
"if",
"isinstance",
"(",
"obj",
",",
"BaseUnit",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'on_'",
")",
":",
"return",
"False",
"return",
"True",
"return",
"serializable",
"(",
"self",
",",
"on_filter",
"=",
"_on_filter",
")"
] | Converts to a dict of attributes for easier serialization. | [
"Converts",
"to",
"a",
"dict",
"of",
"attributes",
"for",
"easier",
"serialization",
"."
] | 62360fbab2e90bf04d52b547093bdab2d4e389b4 | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/baseunit.py#L539-L548 |
250,108 | pschmitt/zhue | zhue/model/basemodel.py | HueBaseObject.update | def update(self):
'''
Update our object's data
'''
self._json = self._request(
method='GET',
url=self.API
)._json | python | def update(self):
'''
Update our object's data
'''
self._json = self._request(
method='GET',
url=self.API
)._json | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_json",
"=",
"self",
".",
"_request",
"(",
"method",
"=",
"'GET'",
",",
"url",
"=",
"self",
".",
"API",
")",
".",
"_json"
] | Update our object's data | [
"Update",
"our",
"object",
"s",
"data"
] | 4a3f4ddf12ceeedcb2157f92d93ff1c6438a7d59 | https://github.com/pschmitt/zhue/blob/4a3f4ddf12ceeedcb2157f92d93ff1c6438a7d59/zhue/model/basemodel.py#L38-L45 |
250,109 | pschmitt/zhue | zhue/model/basemodel.py | HueObject.address | def address(self):
'''
Return the address of this "object", minus the scheme, hostname
and port of the bridge
'''
return self.API.replace(
'http://{}:{}'.format(
self._bridge.hostname,
self._bridge.port
), ''
) | python | def address(self):
'''
Return the address of this "object", minus the scheme, hostname
and port of the bridge
'''
return self.API.replace(
'http://{}:{}'.format(
self._bridge.hostname,
self._bridge.port
), ''
) | [
"def",
"address",
"(",
"self",
")",
":",
"return",
"self",
".",
"API",
".",
"replace",
"(",
"'http://{}:{}'",
".",
"format",
"(",
"self",
".",
"_bridge",
".",
"hostname",
",",
"self",
".",
"_bridge",
".",
"port",
")",
",",
"''",
")"
] | Return the address of this "object", minus the scheme, hostname
and port of the bridge | [
"Return",
"the",
"address",
"of",
"this",
"object",
"minus",
"the",
"scheme",
"hostname",
"and",
"port",
"of",
"the",
"bridge"
] | 4a3f4ddf12ceeedcb2157f92d93ff1c6438a7d59 | https://github.com/pschmitt/zhue/blob/4a3f4ddf12ceeedcb2157f92d93ff1c6438a7d59/zhue/model/basemodel.py#L65-L75 |
250,110 | Clarify/clarify_brightcove_sync | clarify_brightcove_sync/clarify_brightcove_bridge.py | ClarifyBrightcoveBridge._load_bundle_map | def _load_bundle_map(self):
'''
Return a map of all bundles in the Clarify app that have an external_id set for them.
The bundles with external_ids set are assumed to be the ones we have inserted from Brightcove.
The external_id contains the Brightcove video id.
'''
bundle_map = {}
next_href = None
has_next = True
while has_next:
bundles = self.clarify_client.get_bundle_list(href=next_href, embed_items=True)
items = get_embedded_items(bundles)
for item in items:
bc_video_id = item.get('external_id')
if bc_video_id is not None and len(bc_video_id) > 0:
bundle_map[bc_video_id] = item
next_href = get_link_href(bundles, 'next')
if next_href is None:
has_next = False
return bundle_map | python | def _load_bundle_map(self):
'''
Return a map of all bundles in the Clarify app that have an external_id set for them.
The bundles with external_ids set are assumed to be the ones we have inserted from Brightcove.
The external_id contains the Brightcove video id.
'''
bundle_map = {}
next_href = None
has_next = True
while has_next:
bundles = self.clarify_client.get_bundle_list(href=next_href, embed_items=True)
items = get_embedded_items(bundles)
for item in items:
bc_video_id = item.get('external_id')
if bc_video_id is not None and len(bc_video_id) > 0:
bundle_map[bc_video_id] = item
next_href = get_link_href(bundles, 'next')
if next_href is None:
has_next = False
return bundle_map | [
"def",
"_load_bundle_map",
"(",
"self",
")",
":",
"bundle_map",
"=",
"{",
"}",
"next_href",
"=",
"None",
"has_next",
"=",
"True",
"while",
"has_next",
":",
"bundles",
"=",
"self",
".",
"clarify_client",
".",
"get_bundle_list",
"(",
"href",
"=",
"next_href",
",",
"embed_items",
"=",
"True",
")",
"items",
"=",
"get_embedded_items",
"(",
"bundles",
")",
"for",
"item",
"in",
"items",
":",
"bc_video_id",
"=",
"item",
".",
"get",
"(",
"'external_id'",
")",
"if",
"bc_video_id",
"is",
"not",
"None",
"and",
"len",
"(",
"bc_video_id",
")",
">",
"0",
":",
"bundle_map",
"[",
"bc_video_id",
"]",
"=",
"item",
"next_href",
"=",
"get_link_href",
"(",
"bundles",
",",
"'next'",
")",
"if",
"next_href",
"is",
"None",
":",
"has_next",
"=",
"False",
"return",
"bundle_map"
] | Return a map of all bundles in the Clarify app that have an external_id set for them.
The bundles with external_ids set are assumed to be the ones we have inserted from Brightcove.
The external_id contains the Brightcove video id. | [
"Return",
"a",
"map",
"of",
"all",
"bundles",
"in",
"the",
"Clarify",
"app",
"that",
"have",
"an",
"external_id",
"set",
"for",
"them",
".",
"The",
"bundles",
"with",
"external_ids",
"set",
"are",
"assumed",
"to",
"be",
"the",
"ones",
"we",
"have",
"inserted",
"from",
"Brightcove",
".",
"The",
"external_id",
"contains",
"the",
"Brightcove",
"video",
"id",
"."
] | cda4443a40e72f1fb02af3d671d8f3f5f9644d24 | https://github.com/Clarify/clarify_brightcove_sync/blob/cda4443a40e72f1fb02af3d671d8f3f5f9644d24/clarify_brightcove_sync/clarify_brightcove_bridge.py#L29-L49 |
250,111 | Clarify/clarify_brightcove_sync | clarify_brightcove_sync/clarify_brightcove_bridge.py | ClarifyBrightcoveBridge._metadata_from_video | def _metadata_from_video(self, video):
'''Generate the searchable metadata that we'll store in the bundle for the video'''
long_desc = video['long_description']
if long_desc is not None:
long_desc = long_desc[:MAX_METADATA_STRING_LEN]
tags = video.get('tags')
metadata = {
'name': default_to_empty_string(video.get('name')),
'description': default_to_empty_string(video.get('description')),
'long_description': default_to_empty_string(long_desc),
'tags': tags if tags is not None else [],
'updated_at': video.get('updated_at'),
'created_at': video.get('created_at'),
'state': video.get('state')
}
return metadata | python | def _metadata_from_video(self, video):
'''Generate the searchable metadata that we'll store in the bundle for the video'''
long_desc = video['long_description']
if long_desc is not None:
long_desc = long_desc[:MAX_METADATA_STRING_LEN]
tags = video.get('tags')
metadata = {
'name': default_to_empty_string(video.get('name')),
'description': default_to_empty_string(video.get('description')),
'long_description': default_to_empty_string(long_desc),
'tags': tags if tags is not None else [],
'updated_at': video.get('updated_at'),
'created_at': video.get('created_at'),
'state': video.get('state')
}
return metadata | [
"def",
"_metadata_from_video",
"(",
"self",
",",
"video",
")",
":",
"long_desc",
"=",
"video",
"[",
"'long_description'",
"]",
"if",
"long_desc",
"is",
"not",
"None",
":",
"long_desc",
"=",
"long_desc",
"[",
":",
"MAX_METADATA_STRING_LEN",
"]",
"tags",
"=",
"video",
".",
"get",
"(",
"'tags'",
")",
"metadata",
"=",
"{",
"'name'",
":",
"default_to_empty_string",
"(",
"video",
".",
"get",
"(",
"'name'",
")",
")",
",",
"'description'",
":",
"default_to_empty_string",
"(",
"video",
".",
"get",
"(",
"'description'",
")",
")",
",",
"'long_description'",
":",
"default_to_empty_string",
"(",
"long_desc",
")",
",",
"'tags'",
":",
"tags",
"if",
"tags",
"is",
"not",
"None",
"else",
"[",
"]",
",",
"'updated_at'",
":",
"video",
".",
"get",
"(",
"'updated_at'",
")",
",",
"'created_at'",
":",
"video",
".",
"get",
"(",
"'created_at'",
")",
",",
"'state'",
":",
"video",
".",
"get",
"(",
"'state'",
")",
"}",
"return",
"metadata"
] | Generate the searchable metadata that we'll store in the bundle for the video | [
"Generate",
"the",
"searchable",
"metadata",
"that",
"we",
"ll",
"store",
"in",
"the",
"bundle",
"for",
"the",
"video"
] | cda4443a40e72f1fb02af3d671d8f3f5f9644d24 | https://github.com/Clarify/clarify_brightcove_sync/blob/cda4443a40e72f1fb02af3d671d8f3f5f9644d24/clarify_brightcove_sync/clarify_brightcove_bridge.py#L51-L68 |
250,112 | Clarify/clarify_brightcove_sync | clarify_brightcove_sync/clarify_brightcove_bridge.py | ClarifyBrightcoveBridge._src_media_url_for_video | def _src_media_url_for_video(self, video):
'''Get the url for the video media that we can send to Clarify'''
src_url = None
best_height = 0
best_source = None
# TODO: This assumes we have ingested videos. For remote videos, check if the remote flag is True
# and if so, use the src url from the Asset endpoint.
video_sources = self.bc_client.get_video_sources(video['id'])
# Look for codec H264 with good resolution
for source in video_sources:
height = source.get('height', 0)
codec = source.get('codec')
if source.get('src') and codec and codec.upper() == 'H264' and height <= 1080 and height > best_height:
best_source = source
if best_source is not None:
src_url = best_source['src']
return src_url | python | def _src_media_url_for_video(self, video):
'''Get the url for the video media that we can send to Clarify'''
src_url = None
best_height = 0
best_source = None
# TODO: This assumes we have ingested videos. For remote videos, check if the remote flag is True
# and if so, use the src url from the Asset endpoint.
video_sources = self.bc_client.get_video_sources(video['id'])
# Look for codec H264 with good resolution
for source in video_sources:
height = source.get('height', 0)
codec = source.get('codec')
if source.get('src') and codec and codec.upper() == 'H264' and height <= 1080 and height > best_height:
best_source = source
if best_source is not None:
src_url = best_source['src']
return src_url | [
"def",
"_src_media_url_for_video",
"(",
"self",
",",
"video",
")",
":",
"src_url",
"=",
"None",
"best_height",
"=",
"0",
"best_source",
"=",
"None",
"# TODO: This assumes we have ingested videos. For remote videos, check if the remote flag is True",
"# and if so, use the src url from the Asset endpoint.",
"video_sources",
"=",
"self",
".",
"bc_client",
".",
"get_video_sources",
"(",
"video",
"[",
"'id'",
"]",
")",
"# Look for codec H264 with good resolution",
"for",
"source",
"in",
"video_sources",
":",
"height",
"=",
"source",
".",
"get",
"(",
"'height'",
",",
"0",
")",
"codec",
"=",
"source",
".",
"get",
"(",
"'codec'",
")",
"if",
"source",
".",
"get",
"(",
"'src'",
")",
"and",
"codec",
"and",
"codec",
".",
"upper",
"(",
")",
"==",
"'H264'",
"and",
"height",
"<=",
"1080",
"and",
"height",
">",
"best_height",
":",
"best_source",
"=",
"source",
"if",
"best_source",
"is",
"not",
"None",
":",
"src_url",
"=",
"best_source",
"[",
"'src'",
"]",
"return",
"src_url"
] | Get the url for the video media that we can send to Clarify | [
"Get",
"the",
"url",
"for",
"the",
"video",
"media",
"that",
"we",
"can",
"send",
"to",
"Clarify"
] | cda4443a40e72f1fb02af3d671d8f3f5f9644d24 | https://github.com/Clarify/clarify_brightcove_sync/blob/cda4443a40e72f1fb02af3d671d8f3f5f9644d24/clarify_brightcove_sync/clarify_brightcove_bridge.py#L70-L88 |
250,113 | Clarify/clarify_brightcove_sync | clarify_brightcove_sync/clarify_brightcove_bridge.py | ClarifyBrightcoveBridge._update_metadata_for_video | def _update_metadata_for_video(self, metadata_href, video):
'''
Update the metadata for the video if video has been updated in Brightcove since the bundle
metadata was last updated.
'''
current_metadata = self.clarify_client.get_metadata(metadata_href)
cur_data = current_metadata.get('data')
if cur_data.get('updated_at') != video['updated_at']:
self.log('Updating metadata for video {0}'.format(video['id']))
if not self.dry_run:
metadata = self._metadata_from_video(video)
self.clarify_client.update_metadata(metadata_href, metadata=metadata)
self.sync_stats['updated'] += 1 | python | def _update_metadata_for_video(self, metadata_href, video):
'''
Update the metadata for the video if video has been updated in Brightcove since the bundle
metadata was last updated.
'''
current_metadata = self.clarify_client.get_metadata(metadata_href)
cur_data = current_metadata.get('data')
if cur_data.get('updated_at') != video['updated_at']:
self.log('Updating metadata for video {0}'.format(video['id']))
if not self.dry_run:
metadata = self._metadata_from_video(video)
self.clarify_client.update_metadata(metadata_href, metadata=metadata)
self.sync_stats['updated'] += 1 | [
"def",
"_update_metadata_for_video",
"(",
"self",
",",
"metadata_href",
",",
"video",
")",
":",
"current_metadata",
"=",
"self",
".",
"clarify_client",
".",
"get_metadata",
"(",
"metadata_href",
")",
"cur_data",
"=",
"current_metadata",
".",
"get",
"(",
"'data'",
")",
"if",
"cur_data",
".",
"get",
"(",
"'updated_at'",
")",
"!=",
"video",
"[",
"'updated_at'",
"]",
":",
"self",
".",
"log",
"(",
"'Updating metadata for video {0}'",
".",
"format",
"(",
"video",
"[",
"'id'",
"]",
")",
")",
"if",
"not",
"self",
".",
"dry_run",
":",
"metadata",
"=",
"self",
".",
"_metadata_from_video",
"(",
"video",
")",
"self",
".",
"clarify_client",
".",
"update_metadata",
"(",
"metadata_href",
",",
"metadata",
"=",
"metadata",
")",
"self",
".",
"sync_stats",
"[",
"'updated'",
"]",
"+=",
"1"
] | Update the metadata for the video if video has been updated in Brightcove since the bundle
metadata was last updated. | [
"Update",
"the",
"metadata",
"for",
"the",
"video",
"if",
"video",
"has",
"been",
"updated",
"in",
"Brightcove",
"since",
"the",
"bundle",
"metadata",
"was",
"last",
"updated",
"."
] | cda4443a40e72f1fb02af3d671d8f3f5f9644d24 | https://github.com/Clarify/clarify_brightcove_sync/blob/cda4443a40e72f1fb02af3d671d8f3f5f9644d24/clarify_brightcove_sync/clarify_brightcove_bridge.py#L107-L120 |
250,114 | storborg/replaylib | replaylib/noseplugin.py | ReplayLibPlugin.options | def options(self, parser, env=os.environ):
"Add options to nosetests."
parser.add_option("--%s-record" % self.name,
action="store",
metavar="FILE",
dest="record_filename",
help="Record actions to this file.")
parser.add_option("--%s-playback" % self.name,
action="store",
metavar="FILE",
dest="playback_filename",
help="Playback actions from this file.") | python | def options(self, parser, env=os.environ):
"Add options to nosetests."
parser.add_option("--%s-record" % self.name,
action="store",
metavar="FILE",
dest="record_filename",
help="Record actions to this file.")
parser.add_option("--%s-playback" % self.name,
action="store",
metavar="FILE",
dest="playback_filename",
help="Playback actions from this file.") | [
"def",
"options",
"(",
"self",
",",
"parser",
",",
"env",
"=",
"os",
".",
"environ",
")",
":",
"parser",
".",
"add_option",
"(",
"\"--%s-record\"",
"%",
"self",
".",
"name",
",",
"action",
"=",
"\"store\"",
",",
"metavar",
"=",
"\"FILE\"",
",",
"dest",
"=",
"\"record_filename\"",
",",
"help",
"=",
"\"Record actions to this file.\"",
")",
"parser",
".",
"add_option",
"(",
"\"--%s-playback\"",
"%",
"self",
".",
"name",
",",
"action",
"=",
"\"store\"",
",",
"metavar",
"=",
"\"FILE\"",
",",
"dest",
"=",
"\"playback_filename\"",
",",
"help",
"=",
"\"Playback actions from this file.\"",
")"
] | Add options to nosetests. | [
"Add",
"options",
"to",
"nosetests",
"."
] | 16bc3752bb992e3fb364fce9bd7c3f95e887a42d | https://github.com/storborg/replaylib/blob/16bc3752bb992e3fb364fce9bd7c3f95e887a42d/replaylib/noseplugin.py#L14-L25 |
250,115 | westerncapelabs/django-messaging-subscription | subscription/tasks.py | ensure_one_subscription | def ensure_one_subscription():
"""
Fixes issues caused by upstream failures
that lead to users having multiple active subscriptions
Runs daily
"""
cursor = connection.cursor()
cursor.execute("UPDATE subscription_subscription SET active = False \
WHERE id NOT IN \
(SELECT MAX(id) as id FROM \
subscription_subscription GROUP BY to_addr)")
affected = cursor.rowcount
vumi_fire_metric.delay(
metric="subscription.duplicates", value=affected, agg="last")
return affected | python | def ensure_one_subscription():
"""
Fixes issues caused by upstream failures
that lead to users having multiple active subscriptions
Runs daily
"""
cursor = connection.cursor()
cursor.execute("UPDATE subscription_subscription SET active = False \
WHERE id NOT IN \
(SELECT MAX(id) as id FROM \
subscription_subscription GROUP BY to_addr)")
affected = cursor.rowcount
vumi_fire_metric.delay(
metric="subscription.duplicates", value=affected, agg="last")
return affected | [
"def",
"ensure_one_subscription",
"(",
")",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"UPDATE subscription_subscription SET active = False \\\n WHERE id NOT IN \\\n (SELECT MAX(id) as id FROM \\\n subscription_subscription GROUP BY to_addr)\"",
")",
"affected",
"=",
"cursor",
".",
"rowcount",
"vumi_fire_metric",
".",
"delay",
"(",
"metric",
"=",
"\"subscription.duplicates\"",
",",
"value",
"=",
"affected",
",",
"agg",
"=",
"\"last\"",
")",
"return",
"affected"
] | Fixes issues caused by upstream failures
that lead to users having multiple active subscriptions
Runs daily | [
"Fixes",
"issues",
"caused",
"by",
"upstream",
"failures",
"that",
"lead",
"to",
"users",
"having",
"multiple",
"active",
"subscriptions",
"Runs",
"daily"
] | 7af7021cdd6c02b0dfd4b617b9274401972dbaf8 | https://github.com/westerncapelabs/django-messaging-subscription/blob/7af7021cdd6c02b0dfd4b617b9274401972dbaf8/subscription/tasks.py#L43-L57 |
250,116 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py | _get_encoding | def _get_encoding(dom, default="utf-8"):
"""
Try to look for meta tag in given `dom`.
Args:
dom (obj): pyDHTMLParser dom of HTML elements.
default (default "utr-8"): What to use if encoding is not found in
`dom`.
Returns:
str/default: Given encoding or `default` parameter if not found.
"""
encoding = dom.find("meta", {"http-equiv": "Content-Type"})
if not encoding:
return default
encoding = encoding[0].params.get("content", None)
if not encoding:
return default
return encoding.lower().split("=")[-1] | python | def _get_encoding(dom, default="utf-8"):
"""
Try to look for meta tag in given `dom`.
Args:
dom (obj): pyDHTMLParser dom of HTML elements.
default (default "utr-8"): What to use if encoding is not found in
`dom`.
Returns:
str/default: Given encoding or `default` parameter if not found.
"""
encoding = dom.find("meta", {"http-equiv": "Content-Type"})
if not encoding:
return default
encoding = encoding[0].params.get("content", None)
if not encoding:
return default
return encoding.lower().split("=")[-1] | [
"def",
"_get_encoding",
"(",
"dom",
",",
"default",
"=",
"\"utf-8\"",
")",
":",
"encoding",
"=",
"dom",
".",
"find",
"(",
"\"meta\"",
",",
"{",
"\"http-equiv\"",
":",
"\"Content-Type\"",
"}",
")",
"if",
"not",
"encoding",
":",
"return",
"default",
"encoding",
"=",
"encoding",
"[",
"0",
"]",
".",
"params",
".",
"get",
"(",
"\"content\"",
",",
"None",
")",
"if",
"not",
"encoding",
":",
"return",
"default",
"return",
"encoding",
".",
"lower",
"(",
")",
".",
"split",
"(",
"\"=\"",
")",
"[",
"-",
"1",
"]"
] | Try to look for meta tag in given `dom`.
Args:
dom (obj): pyDHTMLParser dom of HTML elements.
default (default "utr-8"): What to use if encoding is not found in
`dom`.
Returns:
str/default: Given encoding or `default` parameter if not found. | [
"Try",
"to",
"look",
"for",
"meta",
"tag",
"in",
"given",
"dom",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py#L41-L63 |
250,117 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py | handle_encodnig | def handle_encodnig(html):
"""
Look for encoding in given `html`. Try to convert `html` to utf-8.
Args:
html (str): HTML code as string.
Returns:
str: HTML code encoded in UTF.
"""
encoding = _get_encoding(
dhtmlparser.parseString(
html.split("</head>")[0]
)
)
if encoding == "utf-8":
return html
return html.decode(encoding).encode("utf-8") | python | def handle_encodnig(html):
"""
Look for encoding in given `html`. Try to convert `html` to utf-8.
Args:
html (str): HTML code as string.
Returns:
str: HTML code encoded in UTF.
"""
encoding = _get_encoding(
dhtmlparser.parseString(
html.split("</head>")[0]
)
)
if encoding == "utf-8":
return html
return html.decode(encoding).encode("utf-8") | [
"def",
"handle_encodnig",
"(",
"html",
")",
":",
"encoding",
"=",
"_get_encoding",
"(",
"dhtmlparser",
".",
"parseString",
"(",
"html",
".",
"split",
"(",
"\"</head>\"",
")",
"[",
"0",
"]",
")",
")",
"if",
"encoding",
"==",
"\"utf-8\"",
":",
"return",
"html",
"return",
"html",
".",
"decode",
"(",
"encoding",
")",
".",
"encode",
"(",
"\"utf-8\"",
")"
] | Look for encoding in given `html`. Try to convert `html` to utf-8.
Args:
html (str): HTML code as string.
Returns:
str: HTML code encoded in UTF. | [
"Look",
"for",
"encoding",
"in",
"given",
"html",
".",
"Try",
"to",
"convert",
"html",
"to",
"utf",
"-",
"8",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py#L66-L85 |
250,118 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py | is_equal_tag | def is_equal_tag(element, tag_name, params, content):
"""
Check is `element` object match rest of the parameters.
All checks are performed only if proper attribute is set in the HTMLElement.
Args:
element (obj): HTMLElement instance.
tag_name (str): Tag name.
params (dict): Parameters of the tag.
content (str): Content of the tag.
Returns:
bool: True if everyhing matchs, False otherwise.
"""
if tag_name and tag_name != element.getTagName():
return False
if params and not element.containsParamSubset(params):
return False
if content is not None and content.strip() != element.getContent().strip():
return False
return True | python | def is_equal_tag(element, tag_name, params, content):
"""
Check is `element` object match rest of the parameters.
All checks are performed only if proper attribute is set in the HTMLElement.
Args:
element (obj): HTMLElement instance.
tag_name (str): Tag name.
params (dict): Parameters of the tag.
content (str): Content of the tag.
Returns:
bool: True if everyhing matchs, False otherwise.
"""
if tag_name and tag_name != element.getTagName():
return False
if params and not element.containsParamSubset(params):
return False
if content is not None and content.strip() != element.getContent().strip():
return False
return True | [
"def",
"is_equal_tag",
"(",
"element",
",",
"tag_name",
",",
"params",
",",
"content",
")",
":",
"if",
"tag_name",
"and",
"tag_name",
"!=",
"element",
".",
"getTagName",
"(",
")",
":",
"return",
"False",
"if",
"params",
"and",
"not",
"element",
".",
"containsParamSubset",
"(",
"params",
")",
":",
"return",
"False",
"if",
"content",
"is",
"not",
"None",
"and",
"content",
".",
"strip",
"(",
")",
"!=",
"element",
".",
"getContent",
"(",
")",
".",
"strip",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | Check is `element` object match rest of the parameters.
All checks are performed only if proper attribute is set in the HTMLElement.
Args:
element (obj): HTMLElement instance.
tag_name (str): Tag name.
params (dict): Parameters of the tag.
content (str): Content of the tag.
Returns:
bool: True if everyhing matchs, False otherwise. | [
"Check",
"is",
"element",
"object",
"match",
"rest",
"of",
"the",
"parameters",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py#L88-L112 |
250,119 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py | has_neigh | def has_neigh(tag_name, params=None, content=None, left=True):
"""
This function generates functions, which matches all tags with neighbours
defined by parameters.
Args:
tag_name (str): Tag has to have neighbour with this tagname.
params (dict): Tag has to have neighbour with this parameters.
params (str): Tag has to have neighbour with this content.
left (bool, default True): Tag has to have neigbour on the left, or
right (set to ``False``).
Returns:
bool: True for every matching tag.
Note:
This function can be used as parameter for ``.find()`` method in
HTMLElement.
"""
def has_neigh_closure(element):
if not element.parent \
or not (element.isTag() and not element.isEndTag()):
return False
# filter only visible tags/neighbours
childs = element.parent.childs
childs = filter(
lambda x: (x.isTag() and not x.isEndTag()) \
or x.getContent().strip() or x is element,
childs
)
if len(childs) <= 1:
return False
ioe = childs.index(element)
if left and ioe > 0:
return is_equal_tag(childs[ioe - 1], tag_name, params, content)
if not left and ioe + 1 < len(childs):
return is_equal_tag(childs[ioe + 1], tag_name, params, content)
return False
return has_neigh_closure | python | def has_neigh(tag_name, params=None, content=None, left=True):
"""
This function generates functions, which matches all tags with neighbours
defined by parameters.
Args:
tag_name (str): Tag has to have neighbour with this tagname.
params (dict): Tag has to have neighbour with this parameters.
params (str): Tag has to have neighbour with this content.
left (bool, default True): Tag has to have neigbour on the left, or
right (set to ``False``).
Returns:
bool: True for every matching tag.
Note:
This function can be used as parameter for ``.find()`` method in
HTMLElement.
"""
def has_neigh_closure(element):
if not element.parent \
or not (element.isTag() and not element.isEndTag()):
return False
# filter only visible tags/neighbours
childs = element.parent.childs
childs = filter(
lambda x: (x.isTag() and not x.isEndTag()) \
or x.getContent().strip() or x is element,
childs
)
if len(childs) <= 1:
return False
ioe = childs.index(element)
if left and ioe > 0:
return is_equal_tag(childs[ioe - 1], tag_name, params, content)
if not left and ioe + 1 < len(childs):
return is_equal_tag(childs[ioe + 1], tag_name, params, content)
return False
return has_neigh_closure | [
"def",
"has_neigh",
"(",
"tag_name",
",",
"params",
"=",
"None",
",",
"content",
"=",
"None",
",",
"left",
"=",
"True",
")",
":",
"def",
"has_neigh_closure",
"(",
"element",
")",
":",
"if",
"not",
"element",
".",
"parent",
"or",
"not",
"(",
"element",
".",
"isTag",
"(",
")",
"and",
"not",
"element",
".",
"isEndTag",
"(",
")",
")",
":",
"return",
"False",
"# filter only visible tags/neighbours",
"childs",
"=",
"element",
".",
"parent",
".",
"childs",
"childs",
"=",
"filter",
"(",
"lambda",
"x",
":",
"(",
"x",
".",
"isTag",
"(",
")",
"and",
"not",
"x",
".",
"isEndTag",
"(",
")",
")",
"or",
"x",
".",
"getContent",
"(",
")",
".",
"strip",
"(",
")",
"or",
"x",
"is",
"element",
",",
"childs",
")",
"if",
"len",
"(",
"childs",
")",
"<=",
"1",
":",
"return",
"False",
"ioe",
"=",
"childs",
".",
"index",
"(",
"element",
")",
"if",
"left",
"and",
"ioe",
">",
"0",
":",
"return",
"is_equal_tag",
"(",
"childs",
"[",
"ioe",
"-",
"1",
"]",
",",
"tag_name",
",",
"params",
",",
"content",
")",
"if",
"not",
"left",
"and",
"ioe",
"+",
"1",
"<",
"len",
"(",
"childs",
")",
":",
"return",
"is_equal_tag",
"(",
"childs",
"[",
"ioe",
"+",
"1",
"]",
",",
"tag_name",
",",
"params",
",",
"content",
")",
"return",
"False",
"return",
"has_neigh_closure"
] | This function generates functions, which matches all tags with neighbours
defined by parameters.
Args:
tag_name (str): Tag has to have neighbour with this tagname.
params (dict): Tag has to have neighbour with this parameters.
params (str): Tag has to have neighbour with this content.
left (bool, default True): Tag has to have neigbour on the left, or
right (set to ``False``).
Returns:
bool: True for every matching tag.
Note:
This function can be used as parameter for ``.find()`` method in
HTMLElement. | [
"This",
"function",
"generates",
"functions",
"which",
"matches",
"all",
"tags",
"with",
"neighbours",
"defined",
"by",
"parameters",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py#L115-L158 |
250,120 | mitakas/wallpaper | wallpaper/wallpaper.py | Wallpaper.paint | def paint(self):
"""
Saves the wallpaper as the specified filename.
"""
# nice blue color
self.image = Image.new(mode='RGB', size=(self.width, self.height),
color=(47, 98, 135))
self.paint_pattern()
self.image.save(fp=self.filename) | python | def paint(self):
"""
Saves the wallpaper as the specified filename.
"""
# nice blue color
self.image = Image.new(mode='RGB', size=(self.width, self.height),
color=(47, 98, 135))
self.paint_pattern()
self.image.save(fp=self.filename) | [
"def",
"paint",
"(",
"self",
")",
":",
"# nice blue color",
"self",
".",
"image",
"=",
"Image",
".",
"new",
"(",
"mode",
"=",
"'RGB'",
",",
"size",
"=",
"(",
"self",
".",
"width",
",",
"self",
".",
"height",
")",
",",
"color",
"=",
"(",
"47",
",",
"98",
",",
"135",
")",
")",
"self",
".",
"paint_pattern",
"(",
")",
"self",
".",
"image",
".",
"save",
"(",
"fp",
"=",
"self",
".",
"filename",
")"
] | Saves the wallpaper as the specified filename. | [
"Saves",
"the",
"wallpaper",
"as",
"the",
"specified",
"filename",
"."
] | 83d90f56cf888d39c98aeb84e0e64d1289e4d0c0 | https://github.com/mitakas/wallpaper/blob/83d90f56cf888d39c98aeb84e0e64d1289e4d0c0/wallpaper/wallpaper.py#L37-L46 |
250,121 | seryl/Python-Cotendo | cotendo/__init__.py | Cotendo.cdn_get_conf | def cdn_get_conf(self, cname, environment):
"""
Returns the existing origin configuration and token from the CDN
"""
response = self.client.service.cdn_get_conf(cname, environment)
cdn_config = CotendoCDN(response)
return cdn_config | python | def cdn_get_conf(self, cname, environment):
"""
Returns the existing origin configuration and token from the CDN
"""
response = self.client.service.cdn_get_conf(cname, environment)
cdn_config = CotendoCDN(response)
return cdn_config | [
"def",
"cdn_get_conf",
"(",
"self",
",",
"cname",
",",
"environment",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"service",
".",
"cdn_get_conf",
"(",
"cname",
",",
"environment",
")",
"cdn_config",
"=",
"CotendoCDN",
"(",
"response",
")",
"return",
"cdn_config"
] | Returns the existing origin configuration and token from the CDN | [
"Returns",
"the",
"existing",
"origin",
"configuration",
"and",
"token",
"from",
"the",
"CDN"
] | a55e034f0845332319859f6276adc6ba35f5a121 | https://github.com/seryl/Python-Cotendo/blob/a55e034f0845332319859f6276adc6ba35f5a121/cotendo/__init__.py#L67-L73 |
250,122 | seryl/Python-Cotendo | cotendo/__init__.py | Cotendo.dns_get_conf | def dns_get_conf(self, domainName, environment):
"""
Returns the existing domain configuration and token from the ADNS
"""
response = self.client.service.dns_get_conf(domainName, environment)
dns_config = CotendoDNS(response)
return dns_config | python | def dns_get_conf(self, domainName, environment):
"""
Returns the existing domain configuration and token from the ADNS
"""
response = self.client.service.dns_get_conf(domainName, environment)
dns_config = CotendoDNS(response)
return dns_config | [
"def",
"dns_get_conf",
"(",
"self",
",",
"domainName",
",",
"environment",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"service",
".",
"dns_get_conf",
"(",
"domainName",
",",
"environment",
")",
"dns_config",
"=",
"CotendoDNS",
"(",
"response",
")",
"return",
"dns_config"
] | Returns the existing domain configuration and token from the ADNS | [
"Returns",
"the",
"existing",
"domain",
"configuration",
"and",
"token",
"from",
"the",
"ADNS"
] | a55e034f0845332319859f6276adc6ba35f5a121 | https://github.com/seryl/Python-Cotendo/blob/a55e034f0845332319859f6276adc6ba35f5a121/cotendo/__init__.py#L95-L101 |
250,123 | seryl/Python-Cotendo | cotendo/__init__.py | Cotendo.doFlush | def doFlush(self, cname, flushExpression, flushType):
"""
doFlush method enables specific content to be "flushed" from the
cache servers.
* Note: The flush API is limited to 1,000 flush invocations per hour
(each flush invocation may include several objects). *
"""
return self.client.service.doFlush(
cname, flushExpression, flushType) | python | def doFlush(self, cname, flushExpression, flushType):
"""
doFlush method enables specific content to be "flushed" from the
cache servers.
* Note: The flush API is limited to 1,000 flush invocations per hour
(each flush invocation may include several objects). *
"""
return self.client.service.doFlush(
cname, flushExpression, flushType) | [
"def",
"doFlush",
"(",
"self",
",",
"cname",
",",
"flushExpression",
",",
"flushType",
")",
":",
"return",
"self",
".",
"client",
".",
"service",
".",
"doFlush",
"(",
"cname",
",",
"flushExpression",
",",
"flushType",
")"
] | doFlush method enables specific content to be "flushed" from the
cache servers.
* Note: The flush API is limited to 1,000 flush invocations per hour
(each flush invocation may include several objects). * | [
"doFlush",
"method",
"enables",
"specific",
"content",
"to",
"be",
"flushed",
"from",
"the",
"cache",
"servers",
"."
] | a55e034f0845332319859f6276adc6ba35f5a121 | https://github.com/seryl/Python-Cotendo/blob/a55e034f0845332319859f6276adc6ba35f5a121/cotendo/__init__.py#L129-L138 |
250,124 | seryl/Python-Cotendo | cotendo/__init__.py | CotendoHelper.UpdateDNS | def UpdateDNS(self, domain, environment):
"""Pushes DNS updates"""
self.dns_set_conf(domain, self.dns.config,
environment, self.dns.token) | python | def UpdateDNS(self, domain, environment):
"""Pushes DNS updates"""
self.dns_set_conf(domain, self.dns.config,
environment, self.dns.token) | [
"def",
"UpdateDNS",
"(",
"self",
",",
"domain",
",",
"environment",
")",
":",
"self",
".",
"dns_set_conf",
"(",
"domain",
",",
"self",
".",
"dns",
".",
"config",
",",
"environment",
",",
"self",
".",
"dns",
".",
"token",
")"
] | Pushes DNS updates | [
"Pushes",
"DNS",
"updates"
] | a55e034f0845332319859f6276adc6ba35f5a121 | https://github.com/seryl/Python-Cotendo/blob/a55e034f0845332319859f6276adc6ba35f5a121/cotendo/__init__.py#L193-L196 |
250,125 | seryl/Python-Cotendo | cotendo/__init__.py | CotendoHelper.ImportDNS | def ImportDNS(self, config, token=None):
"""
Import a dns configuration file into the helper
Note: This requires that you have the latest token.
To get the latest token, run the GrabDNS command first.
"""
if not token:
raise Exception("You must have the dns token set first.")
self.dns = CotendoDNS([token, config])
return True | python | def ImportDNS(self, config, token=None):
"""
Import a dns configuration file into the helper
Note: This requires that you have the latest token.
To get the latest token, run the GrabDNS command first.
"""
if not token:
raise Exception("You must have the dns token set first.")
self.dns = CotendoDNS([token, config])
return True | [
"def",
"ImportDNS",
"(",
"self",
",",
"config",
",",
"token",
"=",
"None",
")",
":",
"if",
"not",
"token",
":",
"raise",
"Exception",
"(",
"\"You must have the dns token set first.\"",
")",
"self",
".",
"dns",
"=",
"CotendoDNS",
"(",
"[",
"token",
",",
"config",
"]",
")",
"return",
"True"
] | Import a dns configuration file into the helper
Note: This requires that you have the latest token.
To get the latest token, run the GrabDNS command first. | [
"Import",
"a",
"dns",
"configuration",
"file",
"into",
"the",
"helper"
] | a55e034f0845332319859f6276adc6ba35f5a121 | https://github.com/seryl/Python-Cotendo/blob/a55e034f0845332319859f6276adc6ba35f5a121/cotendo/__init__.py#L198-L208 |
250,126 | henrysher/kotocore | kotocore/cache.py | ServiceCache.get_connection | def get_connection(self, service_name):
"""
Retrieves a connection class from the cache, if available.
:param service_name: The service a given ``Connection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:returns: A <kotocore.connection.Connection> subclass
"""
service = self.services.get(service_name, {})
connection_class = service.get('connection', None)
if not connection_class:
msg = "Connection for '{0}' is not present in the cache."
raise NotCached(msg.format(
service_name
))
return connection_class | python | def get_connection(self, service_name):
"""
Retrieves a connection class from the cache, if available.
:param service_name: The service a given ``Connection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:returns: A <kotocore.connection.Connection> subclass
"""
service = self.services.get(service_name, {})
connection_class = service.get('connection', None)
if not connection_class:
msg = "Connection for '{0}' is not present in the cache."
raise NotCached(msg.format(
service_name
))
return connection_class | [
"def",
"get_connection",
"(",
"self",
",",
"service_name",
")",
":",
"service",
"=",
"self",
".",
"services",
".",
"get",
"(",
"service_name",
",",
"{",
"}",
")",
"connection_class",
"=",
"service",
".",
"get",
"(",
"'connection'",
",",
"None",
")",
"if",
"not",
"connection_class",
":",
"msg",
"=",
"\"Connection for '{0}' is not present in the cache.\"",
"raise",
"NotCached",
"(",
"msg",
".",
"format",
"(",
"service_name",
")",
")",
"return",
"connection_class"
] | Retrieves a connection class from the cache, if available.
:param service_name: The service a given ``Connection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:returns: A <kotocore.connection.Connection> subclass | [
"Retrieves",
"a",
"connection",
"class",
"from",
"the",
"cache",
"if",
"available",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/cache.py#L47-L66 |
250,127 | henrysher/kotocore | kotocore/cache.py | ServiceCache.set_connection | def set_connection(self, service_name, to_cache):
"""
Sets a connection class within the cache.
:param service_name: The service a given ``Connection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param to_cache: The class to be cached for the service.
:type to_cache: class
"""
self.services.setdefault(service_name, {})
self.services[service_name]['connection'] = to_cache | python | def set_connection(self, service_name, to_cache):
"""
Sets a connection class within the cache.
:param service_name: The service a given ``Connection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param to_cache: The class to be cached for the service.
:type to_cache: class
"""
self.services.setdefault(service_name, {})
self.services[service_name]['connection'] = to_cache | [
"def",
"set_connection",
"(",
"self",
",",
"service_name",
",",
"to_cache",
")",
":",
"self",
".",
"services",
".",
"setdefault",
"(",
"service_name",
",",
"{",
"}",
")",
"self",
".",
"services",
"[",
"service_name",
"]",
"[",
"'connection'",
"]",
"=",
"to_cache"
] | Sets a connection class within the cache.
:param service_name: The service a given ``Connection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param to_cache: The class to be cached for the service.
:type to_cache: class | [
"Sets",
"a",
"connection",
"class",
"within",
"the",
"cache",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/cache.py#L68-L80 |
250,128 | henrysher/kotocore | kotocore/cache.py | ServiceCache.get_resource | def get_resource(self, service_name, resource_name, base_class=None):
"""
Retrieves a resource class from the cache, if available.
:param service_name: The service a given ``Resource`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param resource_name: The name of the ``Resource``. Ex.
``Queue``, ``Notification``, ``Table``, etc.
:type resource_name: string
:param base_class: (Optional) The base class of the object. Prevents
"magically" loading the wrong class (one with a different base).
Default is ``default``.
:type base_class: class
:returns: A <kotocore.resources.Resource> subclass
"""
classpath = self.build_classpath(base_class)
service = self.services.get(service_name, {})
resources = service.get('resources', {})
resource_options = resources.get(resource_name, {})
resource_class = resource_options.get(classpath, None)
if not resource_class:
msg = "Resource '{0}' for {1} is not present in the cache."
raise NotCached(msg.format(
resource_name,
service_name
))
return resource_class | python | def get_resource(self, service_name, resource_name, base_class=None):
"""
Retrieves a resource class from the cache, if available.
:param service_name: The service a given ``Resource`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param resource_name: The name of the ``Resource``. Ex.
``Queue``, ``Notification``, ``Table``, etc.
:type resource_name: string
:param base_class: (Optional) The base class of the object. Prevents
"magically" loading the wrong class (one with a different base).
Default is ``default``.
:type base_class: class
:returns: A <kotocore.resources.Resource> subclass
"""
classpath = self.build_classpath(base_class)
service = self.services.get(service_name, {})
resources = service.get('resources', {})
resource_options = resources.get(resource_name, {})
resource_class = resource_options.get(classpath, None)
if not resource_class:
msg = "Resource '{0}' for {1} is not present in the cache."
raise NotCached(msg.format(
resource_name,
service_name
))
return resource_class | [
"def",
"get_resource",
"(",
"self",
",",
"service_name",
",",
"resource_name",
",",
"base_class",
"=",
"None",
")",
":",
"classpath",
"=",
"self",
".",
"build_classpath",
"(",
"base_class",
")",
"service",
"=",
"self",
".",
"services",
".",
"get",
"(",
"service_name",
",",
"{",
"}",
")",
"resources",
"=",
"service",
".",
"get",
"(",
"'resources'",
",",
"{",
"}",
")",
"resource_options",
"=",
"resources",
".",
"get",
"(",
"resource_name",
",",
"{",
"}",
")",
"resource_class",
"=",
"resource_options",
".",
"get",
"(",
"classpath",
",",
"None",
")",
"if",
"not",
"resource_class",
":",
"msg",
"=",
"\"Resource '{0}' for {1} is not present in the cache.\"",
"raise",
"NotCached",
"(",
"msg",
".",
"format",
"(",
"resource_name",
",",
"service_name",
")",
")",
"return",
"resource_class"
] | Retrieves a resource class from the cache, if available.
:param service_name: The service a given ``Resource`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param resource_name: The name of the ``Resource``. Ex.
``Queue``, ``Notification``, ``Table``, etc.
:type resource_name: string
:param base_class: (Optional) The base class of the object. Prevents
"magically" loading the wrong class (one with a different base).
Default is ``default``.
:type base_class: class
:returns: A <kotocore.resources.Resource> subclass | [
"Retrieves",
"a",
"resource",
"class",
"from",
"the",
"cache",
"if",
"available",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/cache.py#L110-L142 |
250,129 | henrysher/kotocore | kotocore/cache.py | ServiceCache.set_resource | def set_resource(self, service_name, resource_name, to_cache):
"""
Sets the resource class within the cache.
:param service_name: The service a given ``Resource`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param resource_name: The name of the ``Resource``. Ex.
``Queue``, ``Notification``, ``Table``, etc.
:type resource_name: string
:param to_cache: The class to be cached for the service.
:type to_cache: class
"""
self.services.setdefault(service_name, {})
self.services[service_name].setdefault('resources', {})
self.services[service_name]['resources'].setdefault(resource_name, {})
options = self.services[service_name]['resources'][resource_name]
classpath = self.build_classpath(to_cache.__bases__[0])
if classpath == 'kotocore.resources.Resource':
classpath = 'default'
options[classpath] = to_cache | python | def set_resource(self, service_name, resource_name, to_cache):
"""
Sets the resource class within the cache.
:param service_name: The service a given ``Resource`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param resource_name: The name of the ``Resource``. Ex.
``Queue``, ``Notification``, ``Table``, etc.
:type resource_name: string
:param to_cache: The class to be cached for the service.
:type to_cache: class
"""
self.services.setdefault(service_name, {})
self.services[service_name].setdefault('resources', {})
self.services[service_name]['resources'].setdefault(resource_name, {})
options = self.services[service_name]['resources'][resource_name]
classpath = self.build_classpath(to_cache.__bases__[0])
if classpath == 'kotocore.resources.Resource':
classpath = 'default'
options[classpath] = to_cache | [
"def",
"set_resource",
"(",
"self",
",",
"service_name",
",",
"resource_name",
",",
"to_cache",
")",
":",
"self",
".",
"services",
".",
"setdefault",
"(",
"service_name",
",",
"{",
"}",
")",
"self",
".",
"services",
"[",
"service_name",
"]",
".",
"setdefault",
"(",
"'resources'",
",",
"{",
"}",
")",
"self",
".",
"services",
"[",
"service_name",
"]",
"[",
"'resources'",
"]",
".",
"setdefault",
"(",
"resource_name",
",",
"{",
"}",
")",
"options",
"=",
"self",
".",
"services",
"[",
"service_name",
"]",
"[",
"'resources'",
"]",
"[",
"resource_name",
"]",
"classpath",
"=",
"self",
".",
"build_classpath",
"(",
"to_cache",
".",
"__bases__",
"[",
"0",
"]",
")",
"if",
"classpath",
"==",
"'kotocore.resources.Resource'",
":",
"classpath",
"=",
"'default'",
"options",
"[",
"classpath",
"]",
"=",
"to_cache"
] | Sets the resource class within the cache.
:param service_name: The service a given ``Resource`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param resource_name: The name of the ``Resource``. Ex.
``Queue``, ``Notification``, ``Table``, etc.
:type resource_name: string
:param to_cache: The class to be cached for the service.
:type to_cache: class | [
"Sets",
"the",
"resource",
"class",
"within",
"the",
"cache",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/cache.py#L144-L168 |
250,130 | henrysher/kotocore | kotocore/cache.py | ServiceCache.del_resource | def del_resource(self, service_name, resource_name, base_class=None):
"""
Deletes a resource class for a given service.
Fails silently if no connection is found in the cache.
:param service_name: The service a given ``Resource`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param base_class: (Optional) The base class of the object. Prevents
"magically" loading the wrong class (one with a different base).
Default is ``default``.
:type base_class: class
"""
# Unlike ``get_resource``, this should be fire & forget.
# We don't really care, as long as it's not in the cache any longer.
try:
classpath = self.build_classpath(base_class)
opts = self.services[service_name]['resources'][resource_name]
del opts[classpath]
except KeyError:
pass | python | def del_resource(self, service_name, resource_name, base_class=None):
"""
Deletes a resource class for a given service.
Fails silently if no connection is found in the cache.
:param service_name: The service a given ``Resource`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param base_class: (Optional) The base class of the object. Prevents
"magically" loading the wrong class (one with a different base).
Default is ``default``.
:type base_class: class
"""
# Unlike ``get_resource``, this should be fire & forget.
# We don't really care, as long as it's not in the cache any longer.
try:
classpath = self.build_classpath(base_class)
opts = self.services[service_name]['resources'][resource_name]
del opts[classpath]
except KeyError:
pass | [
"def",
"del_resource",
"(",
"self",
",",
"service_name",
",",
"resource_name",
",",
"base_class",
"=",
"None",
")",
":",
"# Unlike ``get_resource``, this should be fire & forget.",
"# We don't really care, as long as it's not in the cache any longer.",
"try",
":",
"classpath",
"=",
"self",
".",
"build_classpath",
"(",
"base_class",
")",
"opts",
"=",
"self",
".",
"services",
"[",
"service_name",
"]",
"[",
"'resources'",
"]",
"[",
"resource_name",
"]",
"del",
"opts",
"[",
"classpath",
"]",
"except",
"KeyError",
":",
"pass"
] | Deletes a resource class for a given service.
Fails silently if no connection is found in the cache.
:param service_name: The service a given ``Resource`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param base_class: (Optional) The base class of the object. Prevents
"magically" loading the wrong class (one with a different base).
Default is ``default``.
:type base_class: class | [
"Deletes",
"a",
"resource",
"class",
"for",
"a",
"given",
"service",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/cache.py#L170-L192 |
250,131 | henrysher/kotocore | kotocore/cache.py | ServiceCache.get_collection | def get_collection(self, service_name, collection_name, base_class=None):
"""
Retrieves a collection class from the cache, if available.
:param service_name: The service a given ``Collection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param collection_name: The name of the ``Collection``. Ex.
``QueueCollection``, ``NotificationCollection``,
``TableCollection``, etc.
:type collection_name: string
:param base_class: (Optional) The base class of the object. Prevents
"magically" loading the wrong class (one with a different base).
Default is ``default``.
:type base_class: class
:returns: A <kotocore.collections.Collection> subclass
"""
classpath = self.build_classpath(base_class)
service = self.services.get(service_name, {})
collections = service.get('collections', {})
collection_options = collections.get(collection_name, {})
collection_class = collection_options.get(classpath, None)
if not collection_class:
msg = "Collection '{0}' for {1} is not present in the cache."
raise NotCached(msg.format(
collection_name,
service_name
))
return collection_class | python | def get_collection(self, service_name, collection_name, base_class=None):
"""
Retrieves a collection class from the cache, if available.
:param service_name: The service a given ``Collection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param collection_name: The name of the ``Collection``. Ex.
``QueueCollection``, ``NotificationCollection``,
``TableCollection``, etc.
:type collection_name: string
:param base_class: (Optional) The base class of the object. Prevents
"magically" loading the wrong class (one with a different base).
Default is ``default``.
:type base_class: class
:returns: A <kotocore.collections.Collection> subclass
"""
classpath = self.build_classpath(base_class)
service = self.services.get(service_name, {})
collections = service.get('collections', {})
collection_options = collections.get(collection_name, {})
collection_class = collection_options.get(classpath, None)
if not collection_class:
msg = "Collection '{0}' for {1} is not present in the cache."
raise NotCached(msg.format(
collection_name,
service_name
))
return collection_class | [
"def",
"get_collection",
"(",
"self",
",",
"service_name",
",",
"collection_name",
",",
"base_class",
"=",
"None",
")",
":",
"classpath",
"=",
"self",
".",
"build_classpath",
"(",
"base_class",
")",
"service",
"=",
"self",
".",
"services",
".",
"get",
"(",
"service_name",
",",
"{",
"}",
")",
"collections",
"=",
"service",
".",
"get",
"(",
"'collections'",
",",
"{",
"}",
")",
"collection_options",
"=",
"collections",
".",
"get",
"(",
"collection_name",
",",
"{",
"}",
")",
"collection_class",
"=",
"collection_options",
".",
"get",
"(",
"classpath",
",",
"None",
")",
"if",
"not",
"collection_class",
":",
"msg",
"=",
"\"Collection '{0}' for {1} is not present in the cache.\"",
"raise",
"NotCached",
"(",
"msg",
".",
"format",
"(",
"collection_name",
",",
"service_name",
")",
")",
"return",
"collection_class"
] | Retrieves a collection class from the cache, if available.
:param service_name: The service a given ``Collection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param collection_name: The name of the ``Collection``. Ex.
``QueueCollection``, ``NotificationCollection``,
``TableCollection``, etc.
:type collection_name: string
:param base_class: (Optional) The base class of the object. Prevents
"magically" loading the wrong class (one with a different base).
Default is ``default``.
:type base_class: class
:returns: A <kotocore.collections.Collection> subclass | [
"Retrieves",
"a",
"collection",
"class",
"from",
"the",
"cache",
"if",
"available",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/cache.py#L194-L227 |
250,132 | henrysher/kotocore | kotocore/cache.py | ServiceCache.set_collection | def set_collection(self, service_name, collection_name, to_cache):
"""
Sets a collection class within the cache.
:param service_name: The service a given ``Collection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param collection_name: The name of the ``Collection``. Ex.
``QueueCollection``, ``NotificationCollection``,
``TableCollection``, etc.
:type collection_name: string
:param to_cache: The class to be cached for the service.
:type to_cache: class
"""
self.services.setdefault(service_name, {})
self.services[service_name].setdefault('collections', {})
self.services[service_name]['collections'].setdefault(collection_name, {})
options = self.services[service_name]['collections'][collection_name]
classpath = self.build_classpath(to_cache.__bases__[0])
if classpath == 'kotocore.collections.Collection':
classpath = 'default'
options[classpath] = to_cache | python | def set_collection(self, service_name, collection_name, to_cache):
"""
Sets a collection class within the cache.
:param service_name: The service a given ``Collection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param collection_name: The name of the ``Collection``. Ex.
``QueueCollection``, ``NotificationCollection``,
``TableCollection``, etc.
:type collection_name: string
:param to_cache: The class to be cached for the service.
:type to_cache: class
"""
self.services.setdefault(service_name, {})
self.services[service_name].setdefault('collections', {})
self.services[service_name]['collections'].setdefault(collection_name, {})
options = self.services[service_name]['collections'][collection_name]
classpath = self.build_classpath(to_cache.__bases__[0])
if classpath == 'kotocore.collections.Collection':
classpath = 'default'
options[classpath] = to_cache | [
"def",
"set_collection",
"(",
"self",
",",
"service_name",
",",
"collection_name",
",",
"to_cache",
")",
":",
"self",
".",
"services",
".",
"setdefault",
"(",
"service_name",
",",
"{",
"}",
")",
"self",
".",
"services",
"[",
"service_name",
"]",
".",
"setdefault",
"(",
"'collections'",
",",
"{",
"}",
")",
"self",
".",
"services",
"[",
"service_name",
"]",
"[",
"'collections'",
"]",
".",
"setdefault",
"(",
"collection_name",
",",
"{",
"}",
")",
"options",
"=",
"self",
".",
"services",
"[",
"service_name",
"]",
"[",
"'collections'",
"]",
"[",
"collection_name",
"]",
"classpath",
"=",
"self",
".",
"build_classpath",
"(",
"to_cache",
".",
"__bases__",
"[",
"0",
"]",
")",
"if",
"classpath",
"==",
"'kotocore.collections.Collection'",
":",
"classpath",
"=",
"'default'",
"options",
"[",
"classpath",
"]",
"=",
"to_cache"
] | Sets a collection class within the cache.
:param service_name: The service a given ``Collection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param collection_name: The name of the ``Collection``. Ex.
``QueueCollection``, ``NotificationCollection``,
``TableCollection``, etc.
:type collection_name: string
:param to_cache: The class to be cached for the service.
:type to_cache: class | [
"Sets",
"a",
"collection",
"class",
"within",
"the",
"cache",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/cache.py#L229-L254 |
250,133 | henrysher/kotocore | kotocore/cache.py | ServiceCache.del_collection | def del_collection(self, service_name, collection_name, base_class=None):
"""
Deletes a collection for a given service.
Fails silently if no collection is found in the cache.
:param service_name: The service a given ``Collection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param collection_name: The name of the ``Collection``. Ex.
``QueueCollection``, ``NotificationCollection``,
``TableCollection``, etc.
:type collection_name: string
:param base_class: (Optional) The base class of the object. Prevents
"magically" loading the wrong class (one with a different base).
Default is ``default``.
:type base_class: class
"""
# Unlike ``get_collection``, this should be fire & forget.
# We don't really care, as long as it's not in the cache any longer.
try:
classpath = self.build_classpath(base_class)
opts = self.services[service_name]['collections'][collection_name]
del opts[classpath]
except KeyError:
pass | python | def del_collection(self, service_name, collection_name, base_class=None):
"""
Deletes a collection for a given service.
Fails silently if no collection is found in the cache.
:param service_name: The service a given ``Collection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param collection_name: The name of the ``Collection``. Ex.
``QueueCollection``, ``NotificationCollection``,
``TableCollection``, etc.
:type collection_name: string
:param base_class: (Optional) The base class of the object. Prevents
"magically" loading the wrong class (one with a different base).
Default is ``default``.
:type base_class: class
"""
# Unlike ``get_collection``, this should be fire & forget.
# We don't really care, as long as it's not in the cache any longer.
try:
classpath = self.build_classpath(base_class)
opts = self.services[service_name]['collections'][collection_name]
del opts[classpath]
except KeyError:
pass | [
"def",
"del_collection",
"(",
"self",
",",
"service_name",
",",
"collection_name",
",",
"base_class",
"=",
"None",
")",
":",
"# Unlike ``get_collection``, this should be fire & forget.",
"# We don't really care, as long as it's not in the cache any longer.",
"try",
":",
"classpath",
"=",
"self",
".",
"build_classpath",
"(",
"base_class",
")",
"opts",
"=",
"self",
".",
"services",
"[",
"service_name",
"]",
"[",
"'collections'",
"]",
"[",
"collection_name",
"]",
"del",
"opts",
"[",
"classpath",
"]",
"except",
"KeyError",
":",
"pass"
] | Deletes a collection for a given service.
Fails silently if no collection is found in the cache.
:param service_name: The service a given ``Collection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param collection_name: The name of the ``Collection``. Ex.
``QueueCollection``, ``NotificationCollection``,
``TableCollection``, etc.
:type collection_name: string
:param base_class: (Optional) The base class of the object. Prevents
"magically" loading the wrong class (one with a different base).
Default is ``default``.
:type base_class: class | [
"Deletes",
"a",
"collection",
"for",
"a",
"given",
"service",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/cache.py#L256-L283 |
250,134 | amadev/doan | doan/util.py | chunk | def chunk(seq, n):
# http://stackoverflow.com/a/312464/190597 (Ned Batchelder)
""" Yield successive n-sized chunks from seq."""
for i in range(0, len(seq), n):
yield seq[i:i + n] | python | def chunk(seq, n):
# http://stackoverflow.com/a/312464/190597 (Ned Batchelder)
""" Yield successive n-sized chunks from seq."""
for i in range(0, len(seq), n):
yield seq[i:i + n] | [
"def",
"chunk",
"(",
"seq",
",",
"n",
")",
":",
"# http://stackoverflow.com/a/312464/190597 (Ned Batchelder)",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"seq",
")",
",",
"n",
")",
":",
"yield",
"seq",
"[",
"i",
":",
"i",
"+",
"n",
"]"
] | Yield successive n-sized chunks from seq. | [
"Yield",
"successive",
"n",
"-",
"sized",
"chunks",
"from",
"seq",
"."
] | 5adfa983ac547007a688fe7517291a432919aa3e | https://github.com/amadev/doan/blob/5adfa983ac547007a688fe7517291a432919aa3e/doan/util.py#L15-L19 |
250,135 | RayCrafter/clusterlogger | src/clusterlogger/logfilter.py | HazelHenFilter.filter | def filter(self, record):
"""Add contextual information to the log record
:param record: the log record
:type record: :class:`logging.LogRecord`
:returns: True, if log should get sent
:rtype: :class:`bool`
:raises: None
"""
record.sitename = self.sitename
record.platform = self.platform
record.jobid = self.jobid
record.submitter = self.logname
record.jobname = self.jobname
record.queue = self.queue
record.fqdn = self.fqdn
return True | python | def filter(self, record):
"""Add contextual information to the log record
:param record: the log record
:type record: :class:`logging.LogRecord`
:returns: True, if log should get sent
:rtype: :class:`bool`
:raises: None
"""
record.sitename = self.sitename
record.platform = self.platform
record.jobid = self.jobid
record.submitter = self.logname
record.jobname = self.jobname
record.queue = self.queue
record.fqdn = self.fqdn
return True | [
"def",
"filter",
"(",
"self",
",",
"record",
")",
":",
"record",
".",
"sitename",
"=",
"self",
".",
"sitename",
"record",
".",
"platform",
"=",
"self",
".",
"platform",
"record",
".",
"jobid",
"=",
"self",
".",
"jobid",
"record",
".",
"submitter",
"=",
"self",
".",
"logname",
"record",
".",
"jobname",
"=",
"self",
".",
"jobname",
"record",
".",
"queue",
"=",
"self",
".",
"queue",
"record",
".",
"fqdn",
"=",
"self",
".",
"fqdn",
"return",
"True"
] | Add contextual information to the log record
:param record: the log record
:type record: :class:`logging.LogRecord`
:returns: True, if log should get sent
:rtype: :class:`bool`
:raises: None | [
"Add",
"contextual",
"information",
"to",
"the",
"log",
"record"
] | c67a833a0b9d0c007d4054358702462706933df3 | https://github.com/RayCrafter/clusterlogger/blob/c67a833a0b9d0c007d4054358702462706933df3/src/clusterlogger/logfilter.py#L39-L55 |
250,136 | mk-fg/txboxdotnet | txboxdotnet/api_v2.py | BoxAuthMixin.auth_user_get_url | def auth_user_get_url(self):
'Build authorization URL for User Agent.'
if not self.client_id: raise AuthenticationError('No client_id specified')
return '{}?{}'.format(self.auth_url_user, urllib.urlencode(dict(
client_id=self.client_id, state=self.auth_state_check,
response_type='code', redirect_uri=self.auth_redirect_uri ))) | python | def auth_user_get_url(self):
'Build authorization URL for User Agent.'
if not self.client_id: raise AuthenticationError('No client_id specified')
return '{}?{}'.format(self.auth_url_user, urllib.urlencode(dict(
client_id=self.client_id, state=self.auth_state_check,
response_type='code', redirect_uri=self.auth_redirect_uri ))) | [
"def",
"auth_user_get_url",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"client_id",
":",
"raise",
"AuthenticationError",
"(",
"'No client_id specified'",
")",
"return",
"'{}?{}'",
".",
"format",
"(",
"self",
".",
"auth_url_user",
",",
"urllib",
".",
"urlencode",
"(",
"dict",
"(",
"client_id",
"=",
"self",
".",
"client_id",
",",
"state",
"=",
"self",
".",
"auth_state_check",
",",
"response_type",
"=",
"'code'",
",",
"redirect_uri",
"=",
"self",
".",
"auth_redirect_uri",
")",
")",
")"
] | Build authorization URL for User Agent. | [
"Build",
"authorization",
"URL",
"for",
"User",
"Agent",
"."
] | 4a3e48fbe1388c5e2a17e808aaaf6b2460e61f48 | https://github.com/mk-fg/txboxdotnet/blob/4a3e48fbe1388c5e2a17e808aaaf6b2460e61f48/txboxdotnet/api_v2.py#L102-L107 |
250,137 | mk-fg/txboxdotnet | txboxdotnet/api_v2.py | BoxAPIWrapper.listdir | def listdir(self, folder_id='0', offset=None, limit=None, fields=None):
'Get Box object, representing list of objects in a folder.'
if fields is not None\
and not isinstance(fields, types.StringTypes): fields = ','.join(fields)
return self(
join('folders', folder_id, 'items'),
dict(offset=offset, limit=limit, fields=fields) ) | python | def listdir(self, folder_id='0', offset=None, limit=None, fields=None):
'Get Box object, representing list of objects in a folder.'
if fields is not None\
and not isinstance(fields, types.StringTypes): fields = ','.join(fields)
return self(
join('folders', folder_id, 'items'),
dict(offset=offset, limit=limit, fields=fields) ) | [
"def",
"listdir",
"(",
"self",
",",
"folder_id",
"=",
"'0'",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"fields",
"=",
"None",
")",
":",
"if",
"fields",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"fields",
",",
"types",
".",
"StringTypes",
")",
":",
"fields",
"=",
"','",
".",
"join",
"(",
"fields",
")",
"return",
"self",
"(",
"join",
"(",
"'folders'",
",",
"folder_id",
",",
"'items'",
")",
",",
"dict",
"(",
"offset",
"=",
"offset",
",",
"limit",
"=",
"limit",
",",
"fields",
"=",
"fields",
")",
")"
] | Get Box object, representing list of objects in a folder. | [
"Get",
"Box",
"object",
"representing",
"list",
"of",
"objects",
"in",
"a",
"folder",
"."
] | 4a3e48fbe1388c5e2a17e808aaaf6b2460e61f48 | https://github.com/mk-fg/txboxdotnet/blob/4a3e48fbe1388c5e2a17e808aaaf6b2460e61f48/txboxdotnet/api_v2.py#L213-L219 |
250,138 | mk-fg/txboxdotnet | txboxdotnet/api_v2.py | BoxAPIWrapper.mkdir | def mkdir(self, name=None, folder_id='0'):
'''Create a folder with a specified "name" attribute.
folder_id allows to specify a parent folder.'''
return self( 'folders', method='post', encode='json',
data=dict(name=name, parent=dict(id=folder_id)) ) | python | def mkdir(self, name=None, folder_id='0'):
'''Create a folder with a specified "name" attribute.
folder_id allows to specify a parent folder.'''
return self( 'folders', method='post', encode='json',
data=dict(name=name, parent=dict(id=folder_id)) ) | [
"def",
"mkdir",
"(",
"self",
",",
"name",
"=",
"None",
",",
"folder_id",
"=",
"'0'",
")",
":",
"return",
"self",
"(",
"'folders'",
",",
"method",
"=",
"'post'",
",",
"encode",
"=",
"'json'",
",",
"data",
"=",
"dict",
"(",
"name",
"=",
"name",
",",
"parent",
"=",
"dict",
"(",
"id",
"=",
"folder_id",
")",
")",
")"
] | Create a folder with a specified "name" attribute.
folder_id allows to specify a parent folder. | [
"Create",
"a",
"folder",
"with",
"a",
"specified",
"name",
"attribute",
".",
"folder_id",
"allows",
"to",
"specify",
"a",
"parent",
"folder",
"."
] | 4a3e48fbe1388c5e2a17e808aaaf6b2460e61f48 | https://github.com/mk-fg/txboxdotnet/blob/4a3e48fbe1388c5e2a17e808aaaf6b2460e61f48/txboxdotnet/api_v2.py#L269-L273 |
250,139 | mk-fg/txboxdotnet | txboxdotnet/api_v2.py | txBoxAPI.auth_get_token | def auth_get_token(self, check_state=True):
'Refresh or acquire access_token.'
res = self.auth_access_data_raw = yield self._auth_token_request()
defer.returnValue(self._auth_token_process(res, check_state=check_state)) | python | def auth_get_token(self, check_state=True):
'Refresh or acquire access_token.'
res = self.auth_access_data_raw = yield self._auth_token_request()
defer.returnValue(self._auth_token_process(res, check_state=check_state)) | [
"def",
"auth_get_token",
"(",
"self",
",",
"check_state",
"=",
"True",
")",
":",
"res",
"=",
"self",
".",
"auth_access_data_raw",
"=",
"yield",
"self",
".",
"_auth_token_request",
"(",
")",
"defer",
".",
"returnValue",
"(",
"self",
".",
"_auth_token_process",
"(",
"res",
",",
"check_state",
"=",
"check_state",
")",
")"
] | Refresh or acquire access_token. | [
"Refresh",
"or",
"acquire",
"access_token",
"."
] | 4a3e48fbe1388c5e2a17e808aaaf6b2460e61f48 | https://github.com/mk-fg/txboxdotnet/blob/4a3e48fbe1388c5e2a17e808aaaf6b2460e61f48/txboxdotnet/api_v2.py#L704-L707 |
250,140 | coghost/izen | izen/dec.py | retry | def retry(tries, delay=0, back_off=1, raise_msg=''):
"""Retries a function or method until it got True.
- ``delay`` sets the initial delay in seconds
- ``back_off`` sets the factor by which
- ``raise_msg`` if not '', it'll raise an Exception
"""
if back_off < 1:
raise ValueError('back_off must be 1 or greater')
tries = math.floor(tries)
if tries < 0:
raise ValueError('tries must be 0 or greater')
if delay < 0:
raise ValueError('delay must be 0 or greater')
def deco_retry(f):
def f_retry(*args, **kwargs):
max_tries, max_delay = tries, delay # make mutable
while max_tries > 0:
rv = f(*args, **kwargs) # first attempt
if rv: # Done on success
return rv
max_tries -= 1 # consume an attempt
time.sleep(max_delay) # wait...
max_delay *= back_off # make future wait longer
else:
if raise_msg:
raise Exception(raise_msg)
return
return f_retry # true decorator -> decorated function
return deco_retry | python | def retry(tries, delay=0, back_off=1, raise_msg=''):
"""Retries a function or method until it got True.
- ``delay`` sets the initial delay in seconds
- ``back_off`` sets the factor by which
- ``raise_msg`` if not '', it'll raise an Exception
"""
if back_off < 1:
raise ValueError('back_off must be 1 or greater')
tries = math.floor(tries)
if tries < 0:
raise ValueError('tries must be 0 or greater')
if delay < 0:
raise ValueError('delay must be 0 or greater')
def deco_retry(f):
def f_retry(*args, **kwargs):
max_tries, max_delay = tries, delay # make mutable
while max_tries > 0:
rv = f(*args, **kwargs) # first attempt
if rv: # Done on success
return rv
max_tries -= 1 # consume an attempt
time.sleep(max_delay) # wait...
max_delay *= back_off # make future wait longer
else:
if raise_msg:
raise Exception(raise_msg)
return
return f_retry # true decorator -> decorated function
return deco_retry | [
"def",
"retry",
"(",
"tries",
",",
"delay",
"=",
"0",
",",
"back_off",
"=",
"1",
",",
"raise_msg",
"=",
"''",
")",
":",
"if",
"back_off",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'back_off must be 1 or greater'",
")",
"tries",
"=",
"math",
".",
"floor",
"(",
"tries",
")",
"if",
"tries",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'tries must be 0 or greater'",
")",
"if",
"delay",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'delay must be 0 or greater'",
")",
"def",
"deco_retry",
"(",
"f",
")",
":",
"def",
"f_retry",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"max_tries",
",",
"max_delay",
"=",
"tries",
",",
"delay",
"# make mutable",
"while",
"max_tries",
">",
"0",
":",
"rv",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# first attempt",
"if",
"rv",
":",
"# Done on success",
"return",
"rv",
"max_tries",
"-=",
"1",
"# consume an attempt",
"time",
".",
"sleep",
"(",
"max_delay",
")",
"# wait...",
"max_delay",
"*=",
"back_off",
"# make future wait longer",
"else",
":",
"if",
"raise_msg",
":",
"raise",
"Exception",
"(",
"raise_msg",
")",
"return",
"return",
"f_retry",
"# true decorator -> decorated function",
"return",
"deco_retry"
] | Retries a function or method until it got True.
- ``delay`` sets the initial delay in seconds
- ``back_off`` sets the factor by which
- ``raise_msg`` if not '', it'll raise an Exception | [
"Retries",
"a",
"function",
"or",
"method",
"until",
"it",
"got",
"True",
"."
] | 432db017f99dd2ba809e1ba1792145ab6510263d | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/dec.py#L80-L117 |
250,141 | drowse314-dev-ymat/xmlpumpkin | xmlpumpkin/__init__.py | parse_to_tree | def parse_to_tree(text):
"""Parse text using CaboCha, then return Tree instance."""
xml_text = cabocha.as_xml(text)
tree = Tree(xml_text)
return tree | python | def parse_to_tree(text):
"""Parse text using CaboCha, then return Tree instance."""
xml_text = cabocha.as_xml(text)
tree = Tree(xml_text)
return tree | [
"def",
"parse_to_tree",
"(",
"text",
")",
":",
"xml_text",
"=",
"cabocha",
".",
"as_xml",
"(",
"text",
")",
"tree",
"=",
"Tree",
"(",
"xml_text",
")",
"return",
"tree"
] | Parse text using CaboCha, then return Tree instance. | [
"Parse",
"text",
"using",
"CaboCha",
"then",
"return",
"Tree",
"instance",
"."
] | 6ccf5c5408a741e5b4a29f0e47849435cb3a6556 | https://github.com/drowse314-dev-ymat/xmlpumpkin/blob/6ccf5c5408a741e5b4a29f0e47849435cb3a6556/xmlpumpkin/__init__.py#L11-L15 |
250,142 | kervi/kervi-core | kervi/displays/__init__.py | Display.add_page | def add_page(self, page, default = True):
r"""
Add a display page to the display.
:param page: Page to be added
:type display_id: ``DisplayPage``
:param default: True if this page should be shown upon initialization.
:type name: ``bool``
"""
self._pages[page.page_id] = page
page._add_display(self)
if default or not self._active_page:
self._active_page = page | python | def add_page(self, page, default = True):
r"""
Add a display page to the display.
:param page: Page to be added
:type display_id: ``DisplayPage``
:param default: True if this page should be shown upon initialization.
:type name: ``bool``
"""
self._pages[page.page_id] = page
page._add_display(self)
if default or not self._active_page:
self._active_page = page | [
"def",
"add_page",
"(",
"self",
",",
"page",
",",
"default",
"=",
"True",
")",
":",
"self",
".",
"_pages",
"[",
"page",
".",
"page_id",
"]",
"=",
"page",
"page",
".",
"_add_display",
"(",
"self",
")",
"if",
"default",
"or",
"not",
"self",
".",
"_active_page",
":",
"self",
".",
"_active_page",
"=",
"page"
] | r"""
Add a display page to the display.
:param page: Page to be added
:type display_id: ``DisplayPage``
:param default: True if this page should be shown upon initialization.
:type name: ``bool`` | [
"r",
"Add",
"a",
"display",
"page",
"to",
"the",
"display",
"."
] | 3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23 | https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/displays/__init__.py#L69-L83 |
250,143 | kervi/kervi-core | kervi/displays/__init__.py | Display.activate_page | def activate_page(self, page_id):
r"""
Activates a display page. Content of the active page is shown in the display.
:param page_id: Id of page to activate
:type page_id: ``str``
"""
if page_id == "next":
page_keys = list(self._pages.keys())
key_count = len(page_keys)
if key_count > 0:
idx = page_keys.index(self._active_page.page_id)
if idx >= key_count-1:
idx = 0
else:
idx += 1
self._active_page = self._pages[page_keys[idx]]
self._active_page._render()
self._page_changed(self._active_page)
elif page_id in self._pages:
self._active_page = self._pages[page_id]
self._page_changed(self._active_page)
else:
raise ValueError("Page with {page_id} not found in page list".format(page_id = page_id)) | python | def activate_page(self, page_id):
r"""
Activates a display page. Content of the active page is shown in the display.
:param page_id: Id of page to activate
:type page_id: ``str``
"""
if page_id == "next":
page_keys = list(self._pages.keys())
key_count = len(page_keys)
if key_count > 0:
idx = page_keys.index(self._active_page.page_id)
if idx >= key_count-1:
idx = 0
else:
idx += 1
self._active_page = self._pages[page_keys[idx]]
self._active_page._render()
self._page_changed(self._active_page)
elif page_id in self._pages:
self._active_page = self._pages[page_id]
self._page_changed(self._active_page)
else:
raise ValueError("Page with {page_id} not found in page list".format(page_id = page_id)) | [
"def",
"activate_page",
"(",
"self",
",",
"page_id",
")",
":",
"if",
"page_id",
"==",
"\"next\"",
":",
"page_keys",
"=",
"list",
"(",
"self",
".",
"_pages",
".",
"keys",
"(",
")",
")",
"key_count",
"=",
"len",
"(",
"page_keys",
")",
"if",
"key_count",
">",
"0",
":",
"idx",
"=",
"page_keys",
".",
"index",
"(",
"self",
".",
"_active_page",
".",
"page_id",
")",
"if",
"idx",
">=",
"key_count",
"-",
"1",
":",
"idx",
"=",
"0",
"else",
":",
"idx",
"+=",
"1",
"self",
".",
"_active_page",
"=",
"self",
".",
"_pages",
"[",
"page_keys",
"[",
"idx",
"]",
"]",
"self",
".",
"_active_page",
".",
"_render",
"(",
")",
"self",
".",
"_page_changed",
"(",
"self",
".",
"_active_page",
")",
"elif",
"page_id",
"in",
"self",
".",
"_pages",
":",
"self",
".",
"_active_page",
"=",
"self",
".",
"_pages",
"[",
"page_id",
"]",
"self",
".",
"_page_changed",
"(",
"self",
".",
"_active_page",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Page with {page_id} not found in page list\"",
".",
"format",
"(",
"page_id",
"=",
"page_id",
")",
")"
] | r"""
Activates a display page. Content of the active page is shown in the display.
:param page_id: Id of page to activate
:type page_id: ``str`` | [
"r",
"Activates",
"a",
"display",
"page",
".",
"Content",
"of",
"the",
"active",
"page",
"is",
"shown",
"in",
"the",
"display",
"."
] | 3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23 | https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/displays/__init__.py#L108-L133 |
250,144 | kervi/kervi-core | kervi/displays/__init__.py | Display._get_font | def _get_font(self, size=8, name="PressStart2P.ttf"):
"""
Returns a font that can be used by pil image functions.
This default font is "SourceSansVariable-Roman" that is available on all platforms.
"""
import kervi.vision as vision
from PIL import ImageFont
vision_path = os.path.dirname(vision.__file__)
fontpath = os.path.join(vision_path, "fonts", name)
font = ImageFont.truetype(fontpath, size)
return font | python | def _get_font(self, size=8, name="PressStart2P.ttf"):
"""
Returns a font that can be used by pil image functions.
This default font is "SourceSansVariable-Roman" that is available on all platforms.
"""
import kervi.vision as vision
from PIL import ImageFont
vision_path = os.path.dirname(vision.__file__)
fontpath = os.path.join(vision_path, "fonts", name)
font = ImageFont.truetype(fontpath, size)
return font | [
"def",
"_get_font",
"(",
"self",
",",
"size",
"=",
"8",
",",
"name",
"=",
"\"PressStart2P.ttf\"",
")",
":",
"import",
"kervi",
".",
"vision",
"as",
"vision",
"from",
"PIL",
"import",
"ImageFont",
"vision_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"vision",
".",
"__file__",
")",
"fontpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"vision_path",
",",
"\"fonts\"",
",",
"name",
")",
"font",
"=",
"ImageFont",
".",
"truetype",
"(",
"fontpath",
",",
"size",
")",
"return",
"font"
] | Returns a font that can be used by pil image functions.
This default font is "SourceSansVariable-Roman" that is available on all platforms. | [
"Returns",
"a",
"font",
"that",
"can",
"be",
"used",
"by",
"pil",
"image",
"functions",
".",
"This",
"default",
"font",
"is",
"SourceSansVariable",
"-",
"Roman",
"that",
"is",
"available",
"on",
"all",
"platforms",
"."
] | 3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23 | https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/displays/__init__.py#L188-L198 |
250,145 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/ben_cz.py | _parse_publisher | def _parse_publisher(details):
"""
Parse publisher of the book.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
str/None: Publisher's name as string or None if not found.
"""
publisher = _get_td_or_none(
details,
"ctl00_ContentPlaceHolder1_tblRowNakladatel"
)
# publisher is not specified
if not publisher:
return None
publisher = dhtmlparser.removeTags(publisher).strip()
# return None instead of blank string
if not publisher:
return None
return publisher | python | def _parse_publisher(details):
"""
Parse publisher of the book.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
str/None: Publisher's name as string or None if not found.
"""
publisher = _get_td_or_none(
details,
"ctl00_ContentPlaceHolder1_tblRowNakladatel"
)
# publisher is not specified
if not publisher:
return None
publisher = dhtmlparser.removeTags(publisher).strip()
# return None instead of blank string
if not publisher:
return None
return publisher | [
"def",
"_parse_publisher",
"(",
"details",
")",
":",
"publisher",
"=",
"_get_td_or_none",
"(",
"details",
",",
"\"ctl00_ContentPlaceHolder1_tblRowNakladatel\"",
")",
"# publisher is not specified",
"if",
"not",
"publisher",
":",
"return",
"None",
"publisher",
"=",
"dhtmlparser",
".",
"removeTags",
"(",
"publisher",
")",
".",
"strip",
"(",
")",
"# return None instead of blank string",
"if",
"not",
"publisher",
":",
"return",
"None",
"return",
"publisher"
] | Parse publisher of the book.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
str/None: Publisher's name as string or None if not found. | [
"Parse",
"publisher",
"of",
"the",
"book",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/ben_cz.py#L143-L168 |
250,146 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/ben_cz.py | _parse_pages_binding | def _parse_pages_binding(details):
"""
Parse number of pages and binding of the book.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
(pages, binding): Tuple with two string or two None.
"""
pages = _get_td_or_none(
details,
"ctl00_ContentPlaceHolder1_tblRowRozsahVazba"
)
if not pages:
return None, None
binding = None # binding info and number of pages is stored in same string
if "/" in pages:
binding = pages.split("/")[1].strip()
pages = pages.split("/")[0].strip()
if not pages:
pages = None
return pages, binding | python | def _parse_pages_binding(details):
"""
Parse number of pages and binding of the book.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
(pages, binding): Tuple with two string or two None.
"""
pages = _get_td_or_none(
details,
"ctl00_ContentPlaceHolder1_tblRowRozsahVazba"
)
if not pages:
return None, None
binding = None # binding info and number of pages is stored in same string
if "/" in pages:
binding = pages.split("/")[1].strip()
pages = pages.split("/")[0].strip()
if not pages:
pages = None
return pages, binding | [
"def",
"_parse_pages_binding",
"(",
"details",
")",
":",
"pages",
"=",
"_get_td_or_none",
"(",
"details",
",",
"\"ctl00_ContentPlaceHolder1_tblRowRozsahVazba\"",
")",
"if",
"not",
"pages",
":",
"return",
"None",
",",
"None",
"binding",
"=",
"None",
"# binding info and number of pages is stored in same string",
"if",
"\"/\"",
"in",
"pages",
":",
"binding",
"=",
"pages",
".",
"split",
"(",
"\"/\"",
")",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"pages",
"=",
"pages",
".",
"split",
"(",
"\"/\"",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"if",
"not",
"pages",
":",
"pages",
"=",
"None",
"return",
"pages",
",",
"binding"
] | Parse number of pages and binding of the book.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
(pages, binding): Tuple with two string or two None. | [
"Parse",
"number",
"of",
"pages",
"and",
"binding",
"of",
"the",
"book",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/ben_cz.py#L189-L215 |
250,147 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/ben_cz.py | _parse_ISBN_EAN | def _parse_ISBN_EAN(details):
"""
Parse ISBN and EAN.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
(ISBN, EAN): Tuple with two string or two None.
"""
isbn_ean = _get_td_or_none(
details,
"ctl00_ContentPlaceHolder1_tblRowIsbnEan"
)
if not isbn_ean:
return None, None
ean = None
isbn = None
if "/" in isbn_ean: # ISBN and EAN are stored in same string
isbn, ean = isbn_ean.split("/")
isbn = isbn.strip()
ean = ean.strip()
else:
isbn = isbn_ean.strip()
if not isbn:
isbn = None
return isbn, ean | python | def _parse_ISBN_EAN(details):
"""
Parse ISBN and EAN.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
(ISBN, EAN): Tuple with two string or two None.
"""
isbn_ean = _get_td_or_none(
details,
"ctl00_ContentPlaceHolder1_tblRowIsbnEan"
)
if not isbn_ean:
return None, None
ean = None
isbn = None
if "/" in isbn_ean: # ISBN and EAN are stored in same string
isbn, ean = isbn_ean.split("/")
isbn = isbn.strip()
ean = ean.strip()
else:
isbn = isbn_ean.strip()
if not isbn:
isbn = None
return isbn, ean | [
"def",
"_parse_ISBN_EAN",
"(",
"details",
")",
":",
"isbn_ean",
"=",
"_get_td_or_none",
"(",
"details",
",",
"\"ctl00_ContentPlaceHolder1_tblRowIsbnEan\"",
")",
"if",
"not",
"isbn_ean",
":",
"return",
"None",
",",
"None",
"ean",
"=",
"None",
"isbn",
"=",
"None",
"if",
"\"/\"",
"in",
"isbn_ean",
":",
"# ISBN and EAN are stored in same string",
"isbn",
",",
"ean",
"=",
"isbn_ean",
".",
"split",
"(",
"\"/\"",
")",
"isbn",
"=",
"isbn",
".",
"strip",
"(",
")",
"ean",
"=",
"ean",
".",
"strip",
"(",
")",
"else",
":",
"isbn",
"=",
"isbn_ean",
".",
"strip",
"(",
")",
"if",
"not",
"isbn",
":",
"isbn",
"=",
"None",
"return",
"isbn",
",",
"ean"
] | Parse ISBN and EAN.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
(ISBN, EAN): Tuple with two string or two None. | [
"Parse",
"ISBN",
"and",
"EAN",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/ben_cz.py#L218-L248 |
250,148 | kervi/kervi-core | kervi/core/utility/settings.py | Settings.store_value | def store_value(self, name, value):
"""Store a value to DB"""
self.spine.send_command("storeSetting", self.group, name, value) | python | def store_value(self, name, value):
"""Store a value to DB"""
self.spine.send_command("storeSetting", self.group, name, value) | [
"def",
"store_value",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"spine",
".",
"send_command",
"(",
"\"storeSetting\"",
",",
"self",
".",
"group",
",",
"name",
",",
"value",
")"
] | Store a value to DB | [
"Store",
"a",
"value",
"to",
"DB"
] | 3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23 | https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/core/utility/settings.py#L22-L24 |
250,149 | kervi/kervi-core | kervi/core/utility/settings.py | Settings.retrieve_value | def retrieve_value(self, name, default_value=None):
"""Retrieve a value from DB"""
value = self.spine.send_query("retrieveSetting", self.group, name, processes=["kervi-main"])
if value is None:
return default_value
elif isinstance(value, list) and len(value) == 0:
return default_value
elif isinstance(default_value, int):
return int(value)
elif isinstance(default_value, float):
return float(value)
else:
return value | python | def retrieve_value(self, name, default_value=None):
"""Retrieve a value from DB"""
value = self.spine.send_query("retrieveSetting", self.group, name, processes=["kervi-main"])
if value is None:
return default_value
elif isinstance(value, list) and len(value) == 0:
return default_value
elif isinstance(default_value, int):
return int(value)
elif isinstance(default_value, float):
return float(value)
else:
return value | [
"def",
"retrieve_value",
"(",
"self",
",",
"name",
",",
"default_value",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"spine",
".",
"send_query",
"(",
"\"retrieveSetting\"",
",",
"self",
".",
"group",
",",
"name",
",",
"processes",
"=",
"[",
"\"kervi-main\"",
"]",
")",
"if",
"value",
"is",
"None",
":",
"return",
"default_value",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
"and",
"len",
"(",
"value",
")",
"==",
"0",
":",
"return",
"default_value",
"elif",
"isinstance",
"(",
"default_value",
",",
"int",
")",
":",
"return",
"int",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"default_value",
",",
"float",
")",
":",
"return",
"float",
"(",
"value",
")",
"else",
":",
"return",
"value"
] | Retrieve a value from DB | [
"Retrieve",
"a",
"value",
"from",
"DB"
] | 3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23 | https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/core/utility/settings.py#L27-L39 |
250,150 | cogniteev/docido-python-sdk | docido_sdk/toolbox/rate_limits.py | teb_retry | def teb_retry(exc=RequestException,
when=dict(response__status_code=429),
delay='response__headers__Retry-After',
max_collisions=MAX_COLLISIONS,
default_retry=DEFAULT_RETRY):
"""Decorator catching rate limits exceed events during a crawl task.
It retries the task later on, following a truncated exponential backoff.
"""
def wrap(f):
@functools.wraps(f)
def wrapped_f(*args, **kwargs):
attempt = kwargs.pop('teb_retry_attempt', 0)
try:
return f(*args, **kwargs)
except exc as e:
if kwargsql.and_(e, **when):
try:
retry_after = kwargsql.get(e, delay)
except:
retry_after = default_retry
else:
if retry_after is not None:
retry_after = int(retry_after)
else:
retry_after = default_retry
countdown = retry_after + truncated_exponential_backoff(
retry_after, attempt % max_collisions)
raise Retry(kwargs=dict(attempt=attempt + 1),
countdown=countdown)
else:
raise e, None, sys.exc_info()[2] # flake8: noqa.
return wrapped_f
return wrap | python | def teb_retry(exc=RequestException,
when=dict(response__status_code=429),
delay='response__headers__Retry-After',
max_collisions=MAX_COLLISIONS,
default_retry=DEFAULT_RETRY):
"""Decorator catching rate limits exceed events during a crawl task.
It retries the task later on, following a truncated exponential backoff.
"""
def wrap(f):
@functools.wraps(f)
def wrapped_f(*args, **kwargs):
attempt = kwargs.pop('teb_retry_attempt', 0)
try:
return f(*args, **kwargs)
except exc as e:
if kwargsql.and_(e, **when):
try:
retry_after = kwargsql.get(e, delay)
except:
retry_after = default_retry
else:
if retry_after is not None:
retry_after = int(retry_after)
else:
retry_after = default_retry
countdown = retry_after + truncated_exponential_backoff(
retry_after, attempt % max_collisions)
raise Retry(kwargs=dict(attempt=attempt + 1),
countdown=countdown)
else:
raise e, None, sys.exc_info()[2] # flake8: noqa.
return wrapped_f
return wrap | [
"def",
"teb_retry",
"(",
"exc",
"=",
"RequestException",
",",
"when",
"=",
"dict",
"(",
"response__status_code",
"=",
"429",
")",
",",
"delay",
"=",
"'response__headers__Retry-After'",
",",
"max_collisions",
"=",
"MAX_COLLISIONS",
",",
"default_retry",
"=",
"DEFAULT_RETRY",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"attempt",
"=",
"kwargs",
".",
"pop",
"(",
"'teb_retry_attempt'",
",",
"0",
")",
"try",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"exc",
"as",
"e",
":",
"if",
"kwargsql",
".",
"and_",
"(",
"e",
",",
"*",
"*",
"when",
")",
":",
"try",
":",
"retry_after",
"=",
"kwargsql",
".",
"get",
"(",
"e",
",",
"delay",
")",
"except",
":",
"retry_after",
"=",
"default_retry",
"else",
":",
"if",
"retry_after",
"is",
"not",
"None",
":",
"retry_after",
"=",
"int",
"(",
"retry_after",
")",
"else",
":",
"retry_after",
"=",
"default_retry",
"countdown",
"=",
"retry_after",
"+",
"truncated_exponential_backoff",
"(",
"retry_after",
",",
"attempt",
"%",
"max_collisions",
")",
"raise",
"Retry",
"(",
"kwargs",
"=",
"dict",
"(",
"attempt",
"=",
"attempt",
"+",
"1",
")",
",",
"countdown",
"=",
"countdown",
")",
"else",
":",
"raise",
"e",
",",
"None",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
"# flake8: noqa.",
"return",
"wrapped_f",
"return",
"wrap"
] | Decorator catching rate limits exceed events during a crawl task.
It retries the task later on, following a truncated exponential backoff. | [
"Decorator",
"catching",
"rate",
"limits",
"exceed",
"events",
"during",
"a",
"crawl",
"task",
".",
"It",
"retries",
"the",
"task",
"later",
"on",
"following",
"a",
"truncated",
"exponential",
"backoff",
"."
] | 58ecb6c6f5757fd40c0601657ab18368da7ddf33 | https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/rate_limits.py#L39-L71 |
250,151 | cogniteev/docido-python-sdk | docido_sdk/toolbox/rate_limits.py | RateLimiter.get_configs | def get_configs(cls):
"""Get rate limiters configuration
specified at application level
:rtype: dict of configurations
"""
import docido_sdk.config
http_config = docido_sdk.config.get('http') or {}
session_config = http_config.get('session') or {}
rate_limits = session_config.get('rate_limit') or {}
return rate_limits | python | def get_configs(cls):
"""Get rate limiters configuration
specified at application level
:rtype: dict of configurations
"""
import docido_sdk.config
http_config = docido_sdk.config.get('http') or {}
session_config = http_config.get('session') or {}
rate_limits = session_config.get('rate_limit') or {}
return rate_limits | [
"def",
"get_configs",
"(",
"cls",
")",
":",
"import",
"docido_sdk",
".",
"config",
"http_config",
"=",
"docido_sdk",
".",
"config",
".",
"get",
"(",
"'http'",
")",
"or",
"{",
"}",
"session_config",
"=",
"http_config",
".",
"get",
"(",
"'session'",
")",
"or",
"{",
"}",
"rate_limits",
"=",
"session_config",
".",
"get",
"(",
"'rate_limit'",
")",
"or",
"{",
"}",
"return",
"rate_limits"
] | Get rate limiters configuration
specified at application level
:rtype: dict of configurations | [
"Get",
"rate",
"limiters",
"configuration",
"specified",
"at",
"application",
"level"
] | 58ecb6c6f5757fd40c0601657ab18368da7ddf33 | https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/rate_limits.py#L247-L257 |
250,152 | cogniteev/docido-python-sdk | docido_sdk/toolbox/rate_limits.py | RateLimiter.get_config | def get_config(cls, service, config=None):
"""Get get configuration of the specified rate limiter
:param str service:
rate limiter name
:param config:
optional global rate limiters configuration.
If not specified, then use rate limiters configuration
specified at application level
"""
config = config or cls.get_configs()
return config[service] | python | def get_config(cls, service, config=None):
"""Get get configuration of the specified rate limiter
:param str service:
rate limiter name
:param config:
optional global rate limiters configuration.
If not specified, then use rate limiters configuration
specified at application level
"""
config = config or cls.get_configs()
return config[service] | [
"def",
"get_config",
"(",
"cls",
",",
"service",
",",
"config",
"=",
"None",
")",
":",
"config",
"=",
"config",
"or",
"cls",
".",
"get_configs",
"(",
")",
"return",
"config",
"[",
"service",
"]"
] | Get get configuration of the specified rate limiter
:param str service:
rate limiter name
:param config:
optional global rate limiters configuration.
If not specified, then use rate limiters configuration
specified at application level | [
"Get",
"get",
"configuration",
"of",
"the",
"specified",
"rate",
"limiter"
] | 58ecb6c6f5757fd40c0601657ab18368da7ddf33 | https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/rate_limits.py#L260-L272 |
250,153 | cogniteev/docido-python-sdk | docido_sdk/toolbox/rate_limits.py | RateLimiter.get | def get(cls, service, config=None, persistence_kwargs=None, **context):
"""Load a rate-limiter from configuration
:param str service:
rate limiter name to retrieve
:param dict config:
alternate configuration object to use. If `None`, then use the global
application configuration
:context:
Uniquely describe the consumed resource. Used by the persistence layer
to forge the URI describing the resource.
:rtype: :py:class:`RateLimiter` or :py:class:`MultiRateLimiter`
"""
rl_config = cls.get_config(service, config)
context.update(service=service)
if isinstance(rl_config, (dict, Mapping)):
if persistence_kwargs is not None:
rl_config.update(persistence_kwargs=persistence_kwargs)
return RateLimiter(context, **rl_config)
else:
def _rl(conf):
conf.setdefault('persistence_kwargs',
persistence_kwargs or {})
return RateLimiter(context, **conf)
return MultiRateLimiter(
[_rl(config) for config in rl_config]
) | python | def get(cls, service, config=None, persistence_kwargs=None, **context):
"""Load a rate-limiter from configuration
:param str service:
rate limiter name to retrieve
:param dict config:
alternate configuration object to use. If `None`, then use the global
application configuration
:context:
Uniquely describe the consumed resource. Used by the persistence layer
to forge the URI describing the resource.
:rtype: :py:class:`RateLimiter` or :py:class:`MultiRateLimiter`
"""
rl_config = cls.get_config(service, config)
context.update(service=service)
if isinstance(rl_config, (dict, Mapping)):
if persistence_kwargs is not None:
rl_config.update(persistence_kwargs=persistence_kwargs)
return RateLimiter(context, **rl_config)
else:
def _rl(conf):
conf.setdefault('persistence_kwargs',
persistence_kwargs or {})
return RateLimiter(context, **conf)
return MultiRateLimiter(
[_rl(config) for config in rl_config]
) | [
"def",
"get",
"(",
"cls",
",",
"service",
",",
"config",
"=",
"None",
",",
"persistence_kwargs",
"=",
"None",
",",
"*",
"*",
"context",
")",
":",
"rl_config",
"=",
"cls",
".",
"get_config",
"(",
"service",
",",
"config",
")",
"context",
".",
"update",
"(",
"service",
"=",
"service",
")",
"if",
"isinstance",
"(",
"rl_config",
",",
"(",
"dict",
",",
"Mapping",
")",
")",
":",
"if",
"persistence_kwargs",
"is",
"not",
"None",
":",
"rl_config",
".",
"update",
"(",
"persistence_kwargs",
"=",
"persistence_kwargs",
")",
"return",
"RateLimiter",
"(",
"context",
",",
"*",
"*",
"rl_config",
")",
"else",
":",
"def",
"_rl",
"(",
"conf",
")",
":",
"conf",
".",
"setdefault",
"(",
"'persistence_kwargs'",
",",
"persistence_kwargs",
"or",
"{",
"}",
")",
"return",
"RateLimiter",
"(",
"context",
",",
"*",
"*",
"conf",
")",
"return",
"MultiRateLimiter",
"(",
"[",
"_rl",
"(",
"config",
")",
"for",
"config",
"in",
"rl_config",
"]",
")"
] | Load a rate-limiter from configuration
:param str service:
rate limiter name to retrieve
:param dict config:
alternate configuration object to use. If `None`, then use the global
application configuration
:context:
Uniquely describe the consumed resource. Used by the persistence layer
to forge the URI describing the resource.
:rtype: :py:class:`RateLimiter` or :py:class:`MultiRateLimiter` | [
"Load",
"a",
"rate",
"-",
"limiter",
"from",
"configuration"
] | 58ecb6c6f5757fd40c0601657ab18368da7ddf33 | https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/rate_limits.py#L275-L302 |
250,154 | uw-it-aca/uw-restclients-gradepage | uw_gradepage/grading_status.py | get_grading_status | def get_grading_status(section_id, act_as=None):
"""
Return a restclients.models.gradepage.GradePageStatus object
on the given course
"""
url = "{}/{}".format(url_prefix, quote(section_id))
headers = {}
if act_as is not None:
headers["X-UW-Act-as"] = act_as
response = get_resource(url, headers)
return _object_from_json(url, response) | python | def get_grading_status(section_id, act_as=None):
"""
Return a restclients.models.gradepage.GradePageStatus object
on the given course
"""
url = "{}/{}".format(url_prefix, quote(section_id))
headers = {}
if act_as is not None:
headers["X-UW-Act-as"] = act_as
response = get_resource(url, headers)
return _object_from_json(url, response) | [
"def",
"get_grading_status",
"(",
"section_id",
",",
"act_as",
"=",
"None",
")",
":",
"url",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"url_prefix",
",",
"quote",
"(",
"section_id",
")",
")",
"headers",
"=",
"{",
"}",
"if",
"act_as",
"is",
"not",
"None",
":",
"headers",
"[",
"\"X-UW-Act-as\"",
"]",
"=",
"act_as",
"response",
"=",
"get_resource",
"(",
"url",
",",
"headers",
")",
"return",
"_object_from_json",
"(",
"url",
",",
"response",
")"
] | Return a restclients.models.gradepage.GradePageStatus object
on the given course | [
"Return",
"a",
"restclients",
".",
"models",
".",
"gradepage",
".",
"GradePageStatus",
"object",
"on",
"the",
"given",
"course"
] | 207ae8aa5e58f979b77aeb2c5a1772b56bd57e90 | https://github.com/uw-it-aca/uw-restclients-gradepage/blob/207ae8aa5e58f979b77aeb2c5a1772b56bd57e90/uw_gradepage/grading_status.py#L19-L31 |
250,155 | PushAMP/strictdict3 | strictdict/strictbase/strictdict.py | StrictDict.to_dict | def to_dict(self):
"""
For backwards compatibility
"""
plain_dict = dict()
for k, v in self.items():
if self.__fields__[k].is_list:
if isinstance(self.__fields__[k], ViewModelField):
plain_dict[k] = tuple(vt.to_dict() for vt in v)
continue
plain_dict[k] = tuple(copy.deepcopy(vt) for vt in v)
continue
if isinstance(self.__fields__[k], ViewModelField):
plain_dict[k] = v.to_dict()
continue
plain_dict[k] = copy.deepcopy(v)
return plain_dict | python | def to_dict(self):
"""
For backwards compatibility
"""
plain_dict = dict()
for k, v in self.items():
if self.__fields__[k].is_list:
if isinstance(self.__fields__[k], ViewModelField):
plain_dict[k] = tuple(vt.to_dict() for vt in v)
continue
plain_dict[k] = tuple(copy.deepcopy(vt) for vt in v)
continue
if isinstance(self.__fields__[k], ViewModelField):
plain_dict[k] = v.to_dict()
continue
plain_dict[k] = copy.deepcopy(v)
return plain_dict | [
"def",
"to_dict",
"(",
"self",
")",
":",
"plain_dict",
"=",
"dict",
"(",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
":",
"if",
"self",
".",
"__fields__",
"[",
"k",
"]",
".",
"is_list",
":",
"if",
"isinstance",
"(",
"self",
".",
"__fields__",
"[",
"k",
"]",
",",
"ViewModelField",
")",
":",
"plain_dict",
"[",
"k",
"]",
"=",
"tuple",
"(",
"vt",
".",
"to_dict",
"(",
")",
"for",
"vt",
"in",
"v",
")",
"continue",
"plain_dict",
"[",
"k",
"]",
"=",
"tuple",
"(",
"copy",
".",
"deepcopy",
"(",
"vt",
")",
"for",
"vt",
"in",
"v",
")",
"continue",
"if",
"isinstance",
"(",
"self",
".",
"__fields__",
"[",
"k",
"]",
",",
"ViewModelField",
")",
":",
"plain_dict",
"[",
"k",
"]",
"=",
"v",
".",
"to_dict",
"(",
")",
"continue",
"plain_dict",
"[",
"k",
"]",
"=",
"copy",
".",
"deepcopy",
"(",
"v",
")",
"return",
"plain_dict"
] | For backwards compatibility | [
"For",
"backwards",
"compatibility"
] | 8b7b91c097ecc57232871137db6135c71fc33a9e | https://github.com/PushAMP/strictdict3/blob/8b7b91c097ecc57232871137db6135c71fc33a9e/strictdict/strictbase/strictdict.py#L174-L194 |
250,156 | PushAMP/strictdict3 | strictdict/strictbase/strictdict.py | StrictDict.restore | def restore(cls, data_dict):
"""
Restore from previously simplified data. Data is supposed to be valid,
no checks are performed!
"""
obj = cls.__new__(cls) # Avoid calling constructor
object.__setattr__(obj, '_simplified', data_dict)
object.__setattr__(obj, '_storage', dict())
return obj | python | def restore(cls, data_dict):
"""
Restore from previously simplified data. Data is supposed to be valid,
no checks are performed!
"""
obj = cls.__new__(cls) # Avoid calling constructor
object.__setattr__(obj, '_simplified', data_dict)
object.__setattr__(obj, '_storage', dict())
return obj | [
"def",
"restore",
"(",
"cls",
",",
"data_dict",
")",
":",
"obj",
"=",
"cls",
".",
"__new__",
"(",
"cls",
")",
"# Avoid calling constructor",
"object",
".",
"__setattr__",
"(",
"obj",
",",
"'_simplified'",
",",
"data_dict",
")",
"object",
".",
"__setattr__",
"(",
"obj",
",",
"'_storage'",
",",
"dict",
"(",
")",
")",
"return",
"obj"
] | Restore from previously simplified data. Data is supposed to be valid,
no checks are performed! | [
"Restore",
"from",
"previously",
"simplified",
"data",
".",
"Data",
"is",
"supposed",
"to",
"be",
"valid",
"no",
"checks",
"are",
"performed!"
] | 8b7b91c097ecc57232871137db6135c71fc33a9e | https://github.com/PushAMP/strictdict3/blob/8b7b91c097ecc57232871137db6135c71fc33a9e/strictdict/strictbase/strictdict.py#L197-L205 |
250,157 | daknuett/py_register_machine2 | engine_tools/output/gpu_alike/http.py | HTTPOutputServer.interrupt | def interrupt(self):
"""
Invoked by the renderering.Renderer, if the image has changed.
"""
self.image = io.BytesIO()
self.renderer.screen.save(self.image, "png") | python | def interrupt(self):
"""
Invoked by the renderering.Renderer, if the image has changed.
"""
self.image = io.BytesIO()
self.renderer.screen.save(self.image, "png") | [
"def",
"interrupt",
"(",
"self",
")",
":",
"self",
".",
"image",
"=",
"io",
".",
"BytesIO",
"(",
")",
"self",
".",
"renderer",
".",
"screen",
".",
"save",
"(",
"self",
".",
"image",
",",
"\"png\"",
")"
] | Invoked by the renderering.Renderer, if the image has changed. | [
"Invoked",
"by",
"the",
"renderering",
".",
"Renderer",
"if",
"the",
"image",
"has",
"changed",
"."
] | 599c53cd7576297d0d7a53344ed5d9aa98acc751 | https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/engine_tools/output/gpu_alike/http.py#L49-L54 |
250,158 | jut-io/jut-python-tools | jut/config.py | show | def show():
"""
print the available configurations directly to stdout
"""
if not is_configured():
raise JutException('No configurations available, please run: `jut config add`')
info('Available jut configurations:')
index = 0
for configuration in _CONFIG.sections():
username = _CONFIG.get(configuration, 'username')
app_url = _CONFIG.get(configuration, 'app_url')
if app_url != defaults.APP_URL:
if _CONFIG.has_option(configuration, 'default'):
info(' %d: %s@%s (default)', index + 1, username, app_url)
else:
info(' %d: %s@%s', index + 1, username, app_url)
else:
if _CONFIG.has_option(configuration, 'default'):
info(' %d: %s (default)' % (index + 1, username))
else:
info(' %d: %s' % (index + 1, username))
index += 1 | python | def show():
"""
print the available configurations directly to stdout
"""
if not is_configured():
raise JutException('No configurations available, please run: `jut config add`')
info('Available jut configurations:')
index = 0
for configuration in _CONFIG.sections():
username = _CONFIG.get(configuration, 'username')
app_url = _CONFIG.get(configuration, 'app_url')
if app_url != defaults.APP_URL:
if _CONFIG.has_option(configuration, 'default'):
info(' %d: %s@%s (default)', index + 1, username, app_url)
else:
info(' %d: %s@%s', index + 1, username, app_url)
else:
if _CONFIG.has_option(configuration, 'default'):
info(' %d: %s (default)' % (index + 1, username))
else:
info(' %d: %s' % (index + 1, username))
index += 1 | [
"def",
"show",
"(",
")",
":",
"if",
"not",
"is_configured",
"(",
")",
":",
"raise",
"JutException",
"(",
"'No configurations available, please run: `jut config add`'",
")",
"info",
"(",
"'Available jut configurations:'",
")",
"index",
"=",
"0",
"for",
"configuration",
"in",
"_CONFIG",
".",
"sections",
"(",
")",
":",
"username",
"=",
"_CONFIG",
".",
"get",
"(",
"configuration",
",",
"'username'",
")",
"app_url",
"=",
"_CONFIG",
".",
"get",
"(",
"configuration",
",",
"'app_url'",
")",
"if",
"app_url",
"!=",
"defaults",
".",
"APP_URL",
":",
"if",
"_CONFIG",
".",
"has_option",
"(",
"configuration",
",",
"'default'",
")",
":",
"info",
"(",
"' %d: %s@%s (default)'",
",",
"index",
"+",
"1",
",",
"username",
",",
"app_url",
")",
"else",
":",
"info",
"(",
"' %d: %s@%s'",
",",
"index",
"+",
"1",
",",
"username",
",",
"app_url",
")",
"else",
":",
"if",
"_CONFIG",
".",
"has_option",
"(",
"configuration",
",",
"'default'",
")",
":",
"info",
"(",
"' %d: %s (default)'",
"%",
"(",
"index",
"+",
"1",
",",
"username",
")",
")",
"else",
":",
"info",
"(",
"' %d: %s'",
"%",
"(",
"index",
"+",
"1",
",",
"username",
")",
")",
"index",
"+=",
"1"
] | print the available configurations directly to stdout | [
"print",
"the",
"available",
"configurations",
"directly",
"to",
"stdout"
] | 65574d23f51a7bbced9bb25010d02da5ca5d906f | https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/config.py#L41-L67 |
250,159 | jut-io/jut-python-tools | jut/config.py | set_default | def set_default(name=None, index=None):
"""
set the default configuration by name
"""
default_was_set = False
count = 1
for configuration in _CONFIG.sections():
if index != None:
if count == index:
_CONFIG.set(configuration, 'default', True)
default_was_set = True
else:
_CONFIG.remove_option(configuration, 'default')
if name != None:
if configuration == name:
_CONFIG.set(configuration, 'default', True)
default_was_set = True
else:
_CONFIG.remove_option(configuration, 'default')
count += 1
if not default_was_set:
raise JutException('Unable to find %s configuration' % name)
with open(_CONFIG_FILEPATH, 'w') as configfile:
_CONFIG.write(configfile)
info('Configuration updated at %s' % _JUT_HOME) | python | def set_default(name=None, index=None):
"""
set the default configuration by name
"""
default_was_set = False
count = 1
for configuration in _CONFIG.sections():
if index != None:
if count == index:
_CONFIG.set(configuration, 'default', True)
default_was_set = True
else:
_CONFIG.remove_option(configuration, 'default')
if name != None:
if configuration == name:
_CONFIG.set(configuration, 'default', True)
default_was_set = True
else:
_CONFIG.remove_option(configuration, 'default')
count += 1
if not default_was_set:
raise JutException('Unable to find %s configuration' % name)
with open(_CONFIG_FILEPATH, 'w') as configfile:
_CONFIG.write(configfile)
info('Configuration updated at %s' % _JUT_HOME) | [
"def",
"set_default",
"(",
"name",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"default_was_set",
"=",
"False",
"count",
"=",
"1",
"for",
"configuration",
"in",
"_CONFIG",
".",
"sections",
"(",
")",
":",
"if",
"index",
"!=",
"None",
":",
"if",
"count",
"==",
"index",
":",
"_CONFIG",
".",
"set",
"(",
"configuration",
",",
"'default'",
",",
"True",
")",
"default_was_set",
"=",
"True",
"else",
":",
"_CONFIG",
".",
"remove_option",
"(",
"configuration",
",",
"'default'",
")",
"if",
"name",
"!=",
"None",
":",
"if",
"configuration",
"==",
"name",
":",
"_CONFIG",
".",
"set",
"(",
"configuration",
",",
"'default'",
",",
"True",
")",
"default_was_set",
"=",
"True",
"else",
":",
"_CONFIG",
".",
"remove_option",
"(",
"configuration",
",",
"'default'",
")",
"count",
"+=",
"1",
"if",
"not",
"default_was_set",
":",
"raise",
"JutException",
"(",
"'Unable to find %s configuration'",
"%",
"name",
")",
"with",
"open",
"(",
"_CONFIG_FILEPATH",
",",
"'w'",
")",
"as",
"configfile",
":",
"_CONFIG",
".",
"write",
"(",
"configfile",
")",
"info",
"(",
"'Configuration updated at %s'",
"%",
"_JUT_HOME",
")"
] | set the default configuration by name | [
"set",
"the",
"default",
"configuration",
"by",
"name"
] | 65574d23f51a7bbced9bb25010d02da5ca5d906f | https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/config.py#L78-L109 |
250,160 | jut-io/jut-python-tools | jut/config.py | add | def add(name, **kwargs):
"""
add a new configuration with the name specified and all of the keywords
as attributes of that configuration.
"""
_CONFIG.add_section(name)
for (key, value) in kwargs.items():
_CONFIG.set(name, key, value)
with open(_CONFIG_FILEPATH, 'w') as configfile:
_CONFIG.write(configfile)
info('Configuration updated at %s' % _JUT_HOME) | python | def add(name, **kwargs):
"""
add a new configuration with the name specified and all of the keywords
as attributes of that configuration.
"""
_CONFIG.add_section(name)
for (key, value) in kwargs.items():
_CONFIG.set(name, key, value)
with open(_CONFIG_FILEPATH, 'w') as configfile:
_CONFIG.write(configfile)
info('Configuration updated at %s' % _JUT_HOME) | [
"def",
"add",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"_CONFIG",
".",
"add_section",
"(",
"name",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"_CONFIG",
".",
"set",
"(",
"name",
",",
"key",
",",
"value",
")",
"with",
"open",
"(",
"_CONFIG_FILEPATH",
",",
"'w'",
")",
"as",
"configfile",
":",
"_CONFIG",
".",
"write",
"(",
"configfile",
")",
"info",
"(",
"'Configuration updated at %s'",
"%",
"_JUT_HOME",
")"
] | add a new configuration with the name specified and all of the keywords
as attributes of that configuration. | [
"add",
"a",
"new",
"configuration",
"with",
"the",
"name",
"specified",
"and",
"all",
"of",
"the",
"keywords",
"as",
"attributes",
"of",
"that",
"configuration",
"."
] | 65574d23f51a7bbced9bb25010d02da5ca5d906f | https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/config.py#L116-L130 |
250,161 | jut-io/jut-python-tools | jut/config.py | get_default | def get_default():
"""
return the attributes associated with the default configuration
"""
if not is_configured():
raise JutException('No configurations available, please run `jut config add`')
for configuration in _CONFIG.sections():
if _CONFIG.has_option(configuration, 'default'):
return dict(_CONFIG.items(configuration)) | python | def get_default():
"""
return the attributes associated with the default configuration
"""
if not is_configured():
raise JutException('No configurations available, please run `jut config add`')
for configuration in _CONFIG.sections():
if _CONFIG.has_option(configuration, 'default'):
return dict(_CONFIG.items(configuration)) | [
"def",
"get_default",
"(",
")",
":",
"if",
"not",
"is_configured",
"(",
")",
":",
"raise",
"JutException",
"(",
"'No configurations available, please run `jut config add`'",
")",
"for",
"configuration",
"in",
"_CONFIG",
".",
"sections",
"(",
")",
":",
"if",
"_CONFIG",
".",
"has_option",
"(",
"configuration",
",",
"'default'",
")",
":",
"return",
"dict",
"(",
"_CONFIG",
".",
"items",
"(",
"configuration",
")",
")"
] | return the attributes associated with the default configuration | [
"return",
"the",
"attributes",
"associated",
"with",
"the",
"default",
"configuration"
] | 65574d23f51a7bbced9bb25010d02da5ca5d906f | https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/config.py#L133-L144 |
250,162 | jut-io/jut-python-tools | jut/config.py | remove | def remove(name=None, index=None):
"""
remove the specified configuration
"""
removed = False
count = 1
for configuration in _CONFIG.sections():
if index != None:
if count == index:
_CONFIG.remove_section(configuration)
removed = True
break
if name != None:
if configuration == name:
_CONFIG.remove_section(configuration)
removed = True
break
count += 1
if not removed:
raise JutException('Unable to find %s configuration' % name)
with open(_CONFIG_FILEPATH, 'w') as configfile:
_CONFIG.write(configfile) | python | def remove(name=None, index=None):
"""
remove the specified configuration
"""
removed = False
count = 1
for configuration in _CONFIG.sections():
if index != None:
if count == index:
_CONFIG.remove_section(configuration)
removed = True
break
if name != None:
if configuration == name:
_CONFIG.remove_section(configuration)
removed = True
break
count += 1
if not removed:
raise JutException('Unable to find %s configuration' % name)
with open(_CONFIG_FILEPATH, 'w') as configfile:
_CONFIG.write(configfile) | [
"def",
"remove",
"(",
"name",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"removed",
"=",
"False",
"count",
"=",
"1",
"for",
"configuration",
"in",
"_CONFIG",
".",
"sections",
"(",
")",
":",
"if",
"index",
"!=",
"None",
":",
"if",
"count",
"==",
"index",
":",
"_CONFIG",
".",
"remove_section",
"(",
"configuration",
")",
"removed",
"=",
"True",
"break",
"if",
"name",
"!=",
"None",
":",
"if",
"configuration",
"==",
"name",
":",
"_CONFIG",
".",
"remove_section",
"(",
"configuration",
")",
"removed",
"=",
"True",
"break",
"count",
"+=",
"1",
"if",
"not",
"removed",
":",
"raise",
"JutException",
"(",
"'Unable to find %s configuration'",
"%",
"name",
")",
"with",
"open",
"(",
"_CONFIG_FILEPATH",
",",
"'w'",
")",
"as",
"configfile",
":",
"_CONFIG",
".",
"write",
"(",
"configfile",
")"
] | remove the specified configuration | [
"remove",
"the",
"specified",
"configuration"
] | 65574d23f51a7bbced9bb25010d02da5ca5d906f | https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/config.py#L147-L174 |
250,163 | jut-io/jut-python-tools | jut/config.py | is_default | def is_default(name=None, index=None):
"""
returns True if the specified configuration is the default one
"""
if not is_configured():
raise JutException('No configurations available, please run `jut config add`')
count = 1
for configuration in _CONFIG.sections():
if index != None:
if _CONFIG.has_option(configuration, 'default') and count == index:
return True
if name != None:
if _CONFIG.has_option(configuration, 'default') and configuration == name:
return True
count += 1
return False | python | def is_default(name=None, index=None):
"""
returns True if the specified configuration is the default one
"""
if not is_configured():
raise JutException('No configurations available, please run `jut config add`')
count = 1
for configuration in _CONFIG.sections():
if index != None:
if _CONFIG.has_option(configuration, 'default') and count == index:
return True
if name != None:
if _CONFIG.has_option(configuration, 'default') and configuration == name:
return True
count += 1
return False | [
"def",
"is_default",
"(",
"name",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"if",
"not",
"is_configured",
"(",
")",
":",
"raise",
"JutException",
"(",
"'No configurations available, please run `jut config add`'",
")",
"count",
"=",
"1",
"for",
"configuration",
"in",
"_CONFIG",
".",
"sections",
"(",
")",
":",
"if",
"index",
"!=",
"None",
":",
"if",
"_CONFIG",
".",
"has_option",
"(",
"configuration",
",",
"'default'",
")",
"and",
"count",
"==",
"index",
":",
"return",
"True",
"if",
"name",
"!=",
"None",
":",
"if",
"_CONFIG",
".",
"has_option",
"(",
"configuration",
",",
"'default'",
")",
"and",
"configuration",
"==",
"name",
":",
"return",
"True",
"count",
"+=",
"1",
"return",
"False"
] | returns True if the specified configuration is the default one | [
"returns",
"True",
"if",
"the",
"specified",
"configuration",
"is",
"the",
"default",
"one"
] | 65574d23f51a7bbced9bb25010d02da5ca5d906f | https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/config.py#L177-L199 |
250,164 | eeue56/PyChat.js | pychatjs/server/room.py | Room.disconnect | def disconnect(self, user):
""" Disconnect a user and send a message to the
connected clients """
self.remove_user(user)
self.send_message(create_message('RoomServer', 'Please all say goodbye to {name}!'.format(name=user.id.name)))
self.send_message(create_disconnect(user.id.name)) | python | def disconnect(self, user):
""" Disconnect a user and send a message to the
connected clients """
self.remove_user(user)
self.send_message(create_message('RoomServer', 'Please all say goodbye to {name}!'.format(name=user.id.name)))
self.send_message(create_disconnect(user.id.name)) | [
"def",
"disconnect",
"(",
"self",
",",
"user",
")",
":",
"self",
".",
"remove_user",
"(",
"user",
")",
"self",
".",
"send_message",
"(",
"create_message",
"(",
"'RoomServer'",
",",
"'Please all say goodbye to {name}!'",
".",
"format",
"(",
"name",
"=",
"user",
".",
"id",
".",
"name",
")",
")",
")",
"self",
".",
"send_message",
"(",
"create_disconnect",
"(",
"user",
".",
"id",
".",
"name",
")",
")"
] | Disconnect a user and send a message to the
connected clients | [
"Disconnect",
"a",
"user",
"and",
"send",
"a",
"message",
"to",
"the",
"connected",
"clients"
] | 45056de6f988350c90a6dbe674459a4affde8abc | https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/room.py#L21-L26 |
250,165 | eeue56/PyChat.js | pychatjs/server/room.py | Room.get_user | def get_user(self, username):
""" gets a user with given username if connected """
for user in self.users:
if user.id.name == username:
return user
return None | python | def get_user(self, username):
""" gets a user with given username if connected """
for user in self.users:
if user.id.name == username:
return user
return None | [
"def",
"get_user",
"(",
"self",
",",
"username",
")",
":",
"for",
"user",
"in",
"self",
".",
"users",
":",
"if",
"user",
".",
"id",
".",
"name",
"==",
"username",
":",
"return",
"user",
"return",
"None"
] | gets a user with given username if connected | [
"gets",
"a",
"user",
"with",
"given",
"username",
"if",
"connected"
] | 45056de6f988350c90a6dbe674459a4affde8abc | https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/room.py#L28-L33 |
250,166 | eeue56/PyChat.js | pychatjs/server/room.py | Room.send_message | def send_message(self, message):
""" send a message to each of the users """
for handler in self.users:
logging.info('Handler: ' + str(handler))
handler.write_message(message) | python | def send_message(self, message):
""" send a message to each of the users """
for handler in self.users:
logging.info('Handler: ' + str(handler))
handler.write_message(message) | [
"def",
"send_message",
"(",
"self",
",",
"message",
")",
":",
"for",
"handler",
"in",
"self",
".",
"users",
":",
"logging",
".",
"info",
"(",
"'Handler: '",
"+",
"str",
"(",
"handler",
")",
")",
"handler",
".",
"write_message",
"(",
"message",
")"
] | send a message to each of the users | [
"send",
"a",
"message",
"to",
"each",
"of",
"the",
"users"
] | 45056de6f988350c90a6dbe674459a4affde8abc | https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/room.py#L50-L54 |
250,167 | eeue56/PyChat.js | pychatjs/server/room.py | Room.welcome | def welcome(self, user):
""" welcomes a user to the roomserver """
self.send_message(create_message('RoomServer', 'Please welcome {name} to the server!\nThere are currently {i} users online -\n {r}\n'.format(name=user.id,
i=self.amount_of_users_connected,
r=' '.join(self.user_names))))
logging.debug('Welcoming user {user} to {room}'.format(user=user.id.name, room=self.name)) | python | def welcome(self, user):
""" welcomes a user to the roomserver """
self.send_message(create_message('RoomServer', 'Please welcome {name} to the server!\nThere are currently {i} users online -\n {r}\n'.format(name=user.id,
i=self.amount_of_users_connected,
r=' '.join(self.user_names))))
logging.debug('Welcoming user {user} to {room}'.format(user=user.id.name, room=self.name)) | [
"def",
"welcome",
"(",
"self",
",",
"user",
")",
":",
"self",
".",
"send_message",
"(",
"create_message",
"(",
"'RoomServer'",
",",
"'Please welcome {name} to the server!\\nThere are currently {i} users online -\\n {r}\\n'",
".",
"format",
"(",
"name",
"=",
"user",
".",
"id",
",",
"i",
"=",
"self",
".",
"amount_of_users_connected",
",",
"r",
"=",
"' '",
".",
"join",
"(",
"self",
".",
"user_names",
")",
")",
")",
")",
"logging",
".",
"debug",
"(",
"'Welcoming user {user} to {room}'",
".",
"format",
"(",
"user",
"=",
"user",
".",
"id",
".",
"name",
",",
"room",
"=",
"self",
".",
"name",
")",
")"
] | welcomes a user to the roomserver | [
"welcomes",
"a",
"user",
"to",
"the",
"roomserver"
] | 45056de6f988350c90a6dbe674459a4affde8abc | https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/room.py#L56-L61 |
250,168 | tomokinakamaru/mapletree | mapletree/defaults/request/validators.py | float_range | def float_range(string, minimum, maximum, inf, sup):
""" Requires values to be a number and range in a certain range.
:param string: Value to validate
:param minimum: Minimum value to accept
:param maximum: Maximum value to accept
:param inf: Infimum value to accept
:param sup: Supremum value to accept
:type string: str
:type minimum: float
:type maximum: float
:type inf: float
:type sup: float
"""
return _inrange(float(string), minimum, maximum, inf, sup) | python | def float_range(string, minimum, maximum, inf, sup):
""" Requires values to be a number and range in a certain range.
:param string: Value to validate
:param minimum: Minimum value to accept
:param maximum: Maximum value to accept
:param inf: Infimum value to accept
:param sup: Supremum value to accept
:type string: str
:type minimum: float
:type maximum: float
:type inf: float
:type sup: float
"""
return _inrange(float(string), minimum, maximum, inf, sup) | [
"def",
"float_range",
"(",
"string",
",",
"minimum",
",",
"maximum",
",",
"inf",
",",
"sup",
")",
":",
"return",
"_inrange",
"(",
"float",
"(",
"string",
")",
",",
"minimum",
",",
"maximum",
",",
"inf",
",",
"sup",
")"
] | Requires values to be a number and range in a certain range.
:param string: Value to validate
:param minimum: Minimum value to accept
:param maximum: Maximum value to accept
:param inf: Infimum value to accept
:param sup: Supremum value to accept
:type string: str
:type minimum: float
:type maximum: float
:type inf: float
:type sup: float | [
"Requires",
"values",
"to",
"be",
"a",
"number",
"and",
"range",
"in",
"a",
"certain",
"range",
"."
] | 19ec68769ef2c1cd2e4164ed8623e0c4280279bb | https://github.com/tomokinakamaru/mapletree/blob/19ec68769ef2c1cd2e4164ed8623e0c4280279bb/mapletree/defaults/request/validators.py#L56-L70 |
250,169 | tomokinakamaru/mapletree | mapletree/defaults/request/validators.py | length_range | def length_range(string, minimum, maximum):
""" Requires values' length to be in a certain range.
:param string: Value to validate
:param minimum: Minimum length to accept
:param maximum: Maximum length to accept
:type string: str
:type minimum: int
:type maximum: int
"""
int_range(len(string), minimum, maximum)
return string | python | def length_range(string, minimum, maximum):
""" Requires values' length to be in a certain range.
:param string: Value to validate
:param minimum: Minimum length to accept
:param maximum: Maximum length to accept
:type string: str
:type minimum: int
:type maximum: int
"""
int_range(len(string), minimum, maximum)
return string | [
"def",
"length_range",
"(",
"string",
",",
"minimum",
",",
"maximum",
")",
":",
"int_range",
"(",
"len",
"(",
"string",
")",
",",
"minimum",
",",
"maximum",
")",
"return",
"string"
] | Requires values' length to be in a certain range.
:param string: Value to validate
:param minimum: Minimum length to accept
:param maximum: Maximum length to accept
:type string: str
:type minimum: int
:type maximum: int | [
"Requires",
"values",
"length",
"to",
"be",
"in",
"a",
"certain",
"range",
"."
] | 19ec68769ef2c1cd2e4164ed8623e0c4280279bb | https://github.com/tomokinakamaru/mapletree/blob/19ec68769ef2c1cd2e4164ed8623e0c4280279bb/mapletree/defaults/request/validators.py#L127-L138 |
250,170 | kcolford/txt2boil | txt2boil/core/gen.py | _Gen.collectTriggers | def collectTriggers(self, rgx, code):
"""Return a dictionary of triggers and their corresponding matches
from the code.
"""
return {m.group(0): m for m in re.finditer(rgx, code)} | python | def collectTriggers(self, rgx, code):
"""Return a dictionary of triggers and their corresponding matches
from the code.
"""
return {m.group(0): m for m in re.finditer(rgx, code)} | [
"def",
"collectTriggers",
"(",
"self",
",",
"rgx",
",",
"code",
")",
":",
"return",
"{",
"m",
".",
"group",
"(",
"0",
")",
":",
"m",
"for",
"m",
"in",
"re",
".",
"finditer",
"(",
"rgx",
",",
"code",
")",
"}"
] | Return a dictionary of triggers and their corresponding matches
from the code. | [
"Return",
"a",
"dictionary",
"of",
"triggers",
"and",
"their",
"corresponding",
"matches",
"from",
"the",
"code",
"."
] | 853a47bb8db27c0224531f24dfd02839c983d027 | https://github.com/kcolford/txt2boil/blob/853a47bb8db27c0224531f24dfd02839c983d027/txt2boil/core/gen.py#L30-L36 |
250,171 | kcolford/txt2boil | txt2boil/core/gen.py | _Gen.genOutputs | def genOutputs(self, code, match):
"""Return a list out template outputs based on the triggers found in
the code and the template they create.
"""
out = sorted((k, match.output(m)) for (k, m) in
self.collectTriggers(match.match, code).items())
out = list(map(lambda a: a[1], out))
return out | python | def genOutputs(self, code, match):
"""Return a list out template outputs based on the triggers found in
the code and the template they create.
"""
out = sorted((k, match.output(m)) for (k, m) in
self.collectTriggers(match.match, code).items())
out = list(map(lambda a: a[1], out))
return out | [
"def",
"genOutputs",
"(",
"self",
",",
"code",
",",
"match",
")",
":",
"out",
"=",
"sorted",
"(",
"(",
"k",
",",
"match",
".",
"output",
"(",
"m",
")",
")",
"for",
"(",
"k",
",",
"m",
")",
"in",
"self",
".",
"collectTriggers",
"(",
"match",
".",
"match",
",",
"code",
")",
".",
"items",
"(",
")",
")",
"out",
"=",
"list",
"(",
"map",
"(",
"lambda",
"a",
":",
"a",
"[",
"1",
"]",
",",
"out",
")",
")",
"return",
"out"
] | Return a list out template outputs based on the triggers found in
the code and the template they create. | [
"Return",
"a",
"list",
"out",
"template",
"outputs",
"based",
"on",
"the",
"triggers",
"found",
"in",
"the",
"code",
"and",
"the",
"template",
"they",
"create",
"."
] | 853a47bb8db27c0224531f24dfd02839c983d027 | https://github.com/kcolford/txt2boil/blob/853a47bb8db27c0224531f24dfd02839c983d027/txt2boil/core/gen.py#L38-L47 |
250,172 | kcolford/txt2boil | txt2boil/core/gen.py | _Gen.gen | def gen(self, text, start=0):
"""Return the source code in text, filled with autogenerated code
starting at start.
"""
for cc in self.chunkComment(text, start):
c = self.extractChunkContent(cc)
cc = ''.join(cc)
m = self.matchComment(c)
idx = text.index(cc, start)
e = idx + len(cc)
if m:
assert text[idx:e] == cc
try:
end = text.index('\n\n', e - 1) + 1
except ValueError:
end = len(text)
text = text[:e] + text[end:]
new = self.genOutputs(self.code(text), m)
new = ''.join(new)
text = text[:e] + new + text[e:]
return self.gen(text, e + len(new))
return text | python | def gen(self, text, start=0):
"""Return the source code in text, filled with autogenerated code
starting at start.
"""
for cc in self.chunkComment(text, start):
c = self.extractChunkContent(cc)
cc = ''.join(cc)
m = self.matchComment(c)
idx = text.index(cc, start)
e = idx + len(cc)
if m:
assert text[idx:e] == cc
try:
end = text.index('\n\n', e - 1) + 1
except ValueError:
end = len(text)
text = text[:e] + text[end:]
new = self.genOutputs(self.code(text), m)
new = ''.join(new)
text = text[:e] + new + text[e:]
return self.gen(text, e + len(new))
return text | [
"def",
"gen",
"(",
"self",
",",
"text",
",",
"start",
"=",
"0",
")",
":",
"for",
"cc",
"in",
"self",
".",
"chunkComment",
"(",
"text",
",",
"start",
")",
":",
"c",
"=",
"self",
".",
"extractChunkContent",
"(",
"cc",
")",
"cc",
"=",
"''",
".",
"join",
"(",
"cc",
")",
"m",
"=",
"self",
".",
"matchComment",
"(",
"c",
")",
"idx",
"=",
"text",
".",
"index",
"(",
"cc",
",",
"start",
")",
"e",
"=",
"idx",
"+",
"len",
"(",
"cc",
")",
"if",
"m",
":",
"assert",
"text",
"[",
"idx",
":",
"e",
"]",
"==",
"cc",
"try",
":",
"end",
"=",
"text",
".",
"index",
"(",
"'\\n\\n'",
",",
"e",
"-",
"1",
")",
"+",
"1",
"except",
"ValueError",
":",
"end",
"=",
"len",
"(",
"text",
")",
"text",
"=",
"text",
"[",
":",
"e",
"]",
"+",
"text",
"[",
"end",
":",
"]",
"new",
"=",
"self",
".",
"genOutputs",
"(",
"self",
".",
"code",
"(",
"text",
")",
",",
"m",
")",
"new",
"=",
"''",
".",
"join",
"(",
"new",
")",
"text",
"=",
"text",
"[",
":",
"e",
"]",
"+",
"new",
"+",
"text",
"[",
"e",
":",
"]",
"return",
"self",
".",
"gen",
"(",
"text",
",",
"e",
"+",
"len",
"(",
"new",
")",
")",
"return",
"text"
] | Return the source code in text, filled with autogenerated code
starting at start. | [
"Return",
"the",
"source",
"code",
"in",
"text",
"filled",
"with",
"autogenerated",
"code",
"starting",
"at",
"start",
"."
] | 853a47bb8db27c0224531f24dfd02839c983d027 | https://github.com/kcolford/txt2boil/blob/853a47bb8db27c0224531f24dfd02839c983d027/txt2boil/core/gen.py#L49-L74 |
250,173 | pjuren/pyokit | src/pyokit/statistics/beta.py | beta_pdf | def beta_pdf(x, a, b):
"""Beta distirbution probability density function."""
bc = 1 / beta(a, b)
fc = x ** (a - 1)
sc = (1 - x) ** (b - 1)
return bc * fc * sc | python | def beta_pdf(x, a, b):
"""Beta distirbution probability density function."""
bc = 1 / beta(a, b)
fc = x ** (a - 1)
sc = (1 - x) ** (b - 1)
return bc * fc * sc | [
"def",
"beta_pdf",
"(",
"x",
",",
"a",
",",
"b",
")",
":",
"bc",
"=",
"1",
"/",
"beta",
"(",
"a",
",",
"b",
")",
"fc",
"=",
"x",
"**",
"(",
"a",
"-",
"1",
")",
"sc",
"=",
"(",
"1",
"-",
"x",
")",
"**",
"(",
"b",
"-",
"1",
")",
"return",
"bc",
"*",
"fc",
"*",
"sc"
] | Beta distirbution probability density function. | [
"Beta",
"distirbution",
"probability",
"density",
"function",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/statistics/beta.py#L110-L115 |
250,174 | limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/model.py | ModelWithDynamicFieldMixin.has_field | def has_field(cls, field_name):
"""
Check if the current class has a field with the name "field_name"
Add management of dynamic fields, to return True if the name matches an
existing dynamic field without existing copy for this name.
"""
if super(ModelWithDynamicFieldMixin, cls).has_field(field_name):
return True
try:
cls._get_dynamic_field_for(field_name)
except ValueError:
return False
else:
return True | python | def has_field(cls, field_name):
"""
Check if the current class has a field with the name "field_name"
Add management of dynamic fields, to return True if the name matches an
existing dynamic field without existing copy for this name.
"""
if super(ModelWithDynamicFieldMixin, cls).has_field(field_name):
return True
try:
cls._get_dynamic_field_for(field_name)
except ValueError:
return False
else:
return True | [
"def",
"has_field",
"(",
"cls",
",",
"field_name",
")",
":",
"if",
"super",
"(",
"ModelWithDynamicFieldMixin",
",",
"cls",
")",
".",
"has_field",
"(",
"field_name",
")",
":",
"return",
"True",
"try",
":",
"cls",
".",
"_get_dynamic_field_for",
"(",
"field_name",
")",
"except",
"ValueError",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | Check if the current class has a field with the name "field_name"
Add management of dynamic fields, to return True if the name matches an
existing dynamic field without existing copy for this name. | [
"Check",
"if",
"the",
"current",
"class",
"has",
"a",
"field",
"with",
"the",
"name",
"field_name",
"Add",
"management",
"of",
"dynamic",
"fields",
"to",
"return",
"True",
"if",
"the",
"name",
"matches",
"an",
"existing",
"dynamic",
"field",
"without",
"existing",
"copy",
"for",
"this",
"name",
"."
] | 13f34e39efd2f802761457da30ab2a4213b63934 | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/model.py#L49-L63 |
250,175 | limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/model.py | ModelWithDynamicFieldMixin._add_dynamic_field_to_model | def _add_dynamic_field_to_model(cls, field, field_name):
"""
Add a copy of the DynamicField "field" to the current class and its
subclasses using the "field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_model(cls)
# set it as an attribute on the class, to be reachable
setattr(cls, "_redis_attr_%s" % field_name, new_field)
# NOTE: don't add the field to the "_fields" list, to avoid use extra
# memory to each future instance that will create a field for each
# dynamic one created
# # add the field to the list to avoid to done all of this again
# # (_fields is already on this class only, not subclasses)
# cls._fields.append(field_name)
# each subclass needs its own copy
for subclass in cls.__subclasses__():
subclass._add_dynamic_field_to_model(field, field_name)
return new_field | python | def _add_dynamic_field_to_model(cls, field, field_name):
"""
Add a copy of the DynamicField "field" to the current class and its
subclasses using the "field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_model(cls)
# set it as an attribute on the class, to be reachable
setattr(cls, "_redis_attr_%s" % field_name, new_field)
# NOTE: don't add the field to the "_fields" list, to avoid use extra
# memory to each future instance that will create a field for each
# dynamic one created
# # add the field to the list to avoid to done all of this again
# # (_fields is already on this class only, not subclasses)
# cls._fields.append(field_name)
# each subclass needs its own copy
for subclass in cls.__subclasses__():
subclass._add_dynamic_field_to_model(field, field_name)
return new_field | [
"def",
"_add_dynamic_field_to_model",
"(",
"cls",
",",
"field",
",",
"field_name",
")",
":",
"# create the new field",
"new_field",
"=",
"field",
".",
"_create_dynamic_version",
"(",
")",
"new_field",
".",
"name",
"=",
"field_name",
"new_field",
".",
"_attach_to_model",
"(",
"cls",
")",
"# set it as an attribute on the class, to be reachable",
"setattr",
"(",
"cls",
",",
"\"_redis_attr_%s\"",
"%",
"field_name",
",",
"new_field",
")",
"# NOTE: don't add the field to the \"_fields\" list, to avoid use extra",
"# memory to each future instance that will create a field for each",
"# dynamic one created",
"# # add the field to the list to avoid to done all of this again",
"# # (_fields is already on this class only, not subclasses)",
"# cls._fields.append(field_name)",
"# each subclass needs its own copy",
"for",
"subclass",
"in",
"cls",
".",
"__subclasses__",
"(",
")",
":",
"subclass",
".",
"_add_dynamic_field_to_model",
"(",
"field",
",",
"field_name",
")",
"return",
"new_field"
] | Add a copy of the DynamicField "field" to the current class and its
subclasses using the "field_name" name | [
"Add",
"a",
"copy",
"of",
"the",
"DynamicField",
"field",
"to",
"the",
"current",
"class",
"and",
"its",
"subclasses",
"using",
"the",
"field_name",
"name"
] | 13f34e39efd2f802761457da30ab2a4213b63934 | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/model.py#L102-L127 |
250,176 | limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/model.py | ModelWithDynamicFieldMixin._add_dynamic_field_to_instance | def _add_dynamic_field_to_instance(self, field, field_name):
"""
Add a copy of the DynamicField "field" to the current instance using the
"field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_instance(self)
# add the field to the list to avoid doing all of this again
if field_name not in self._fields: # (maybe already in it via the class)
if id(self._fields) == id(self.__class__._fields):
# unlink the list from the class
self._fields = list(self._fields)
self._fields.append(field_name)
# if the field is an hashable field, add it to the list to allow calling
# hmget on these fields
if isinstance(field, limpyd_fields.InstanceHashField):
if id(self._instancehash_fields) == id(self.__class__._instancehash_fields):
# unlink the link from the class
self._instancehash_fields = list(self._instancehash_fields)
self._instancehash_fields.append(field_name)
# set it as an attribute on the instance, to be reachable
setattr(self, field_name, new_field)
return new_field | python | def _add_dynamic_field_to_instance(self, field, field_name):
"""
Add a copy of the DynamicField "field" to the current instance using the
"field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_instance(self)
# add the field to the list to avoid doing all of this again
if field_name not in self._fields: # (maybe already in it via the class)
if id(self._fields) == id(self.__class__._fields):
# unlink the list from the class
self._fields = list(self._fields)
self._fields.append(field_name)
# if the field is an hashable field, add it to the list to allow calling
# hmget on these fields
if isinstance(field, limpyd_fields.InstanceHashField):
if id(self._instancehash_fields) == id(self.__class__._instancehash_fields):
# unlink the link from the class
self._instancehash_fields = list(self._instancehash_fields)
self._instancehash_fields.append(field_name)
# set it as an attribute on the instance, to be reachable
setattr(self, field_name, new_field)
return new_field | [
"def",
"_add_dynamic_field_to_instance",
"(",
"self",
",",
"field",
",",
"field_name",
")",
":",
"# create the new field",
"new_field",
"=",
"field",
".",
"_create_dynamic_version",
"(",
")",
"new_field",
".",
"name",
"=",
"field_name",
"new_field",
".",
"_attach_to_instance",
"(",
"self",
")",
"# add the field to the list to avoid doing all of this again",
"if",
"field_name",
"not",
"in",
"self",
".",
"_fields",
":",
"# (maybe already in it via the class)",
"if",
"id",
"(",
"self",
".",
"_fields",
")",
"==",
"id",
"(",
"self",
".",
"__class__",
".",
"_fields",
")",
":",
"# unlink the list from the class",
"self",
".",
"_fields",
"=",
"list",
"(",
"self",
".",
"_fields",
")",
"self",
".",
"_fields",
".",
"append",
"(",
"field_name",
")",
"# if the field is an hashable field, add it to the list to allow calling",
"# hmget on these fields",
"if",
"isinstance",
"(",
"field",
",",
"limpyd_fields",
".",
"InstanceHashField",
")",
":",
"if",
"id",
"(",
"self",
".",
"_instancehash_fields",
")",
"==",
"id",
"(",
"self",
".",
"__class__",
".",
"_instancehash_fields",
")",
":",
"# unlink the link from the class",
"self",
".",
"_instancehash_fields",
"=",
"list",
"(",
"self",
".",
"_instancehash_fields",
")",
"self",
".",
"_instancehash_fields",
".",
"append",
"(",
"field_name",
")",
"# set it as an attribute on the instance, to be reachable",
"setattr",
"(",
"self",
",",
"field_name",
",",
"new_field",
")",
"return",
"new_field"
] | Add a copy of the DynamicField "field" to the current instance using the
"field_name" name | [
"Add",
"a",
"copy",
"of",
"the",
"DynamicField",
"field",
"to",
"the",
"current",
"instance",
"using",
"the",
"field_name",
"name"
] | 13f34e39efd2f802761457da30ab2a4213b63934 | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/model.py#L129-L157 |
250,177 | limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/model.py | ModelWithDynamicFieldMixin.get_field_name_for | def get_field_name_for(cls, field_name, dynamic_part):
"""
Given the name of a dynamic field, and a dynamic part, return the
name of the final dynamic field to use. It will then be used with
get_field.
"""
field = cls.get_field(field_name)
return field.get_name_for(dynamic_part) | python | def get_field_name_for(cls, field_name, dynamic_part):
"""
Given the name of a dynamic field, and a dynamic part, return the
name of the final dynamic field to use. It will then be used with
get_field.
"""
field = cls.get_field(field_name)
return field.get_name_for(dynamic_part) | [
"def",
"get_field_name_for",
"(",
"cls",
",",
"field_name",
",",
"dynamic_part",
")",
":",
"field",
"=",
"cls",
".",
"get_field",
"(",
"field_name",
")",
"return",
"field",
".",
"get_name_for",
"(",
"dynamic_part",
")"
] | Given the name of a dynamic field, and a dynamic part, return the
name of the final dynamic field to use. It will then be used with
get_field. | [
"Given",
"the",
"name",
"of",
"a",
"dynamic",
"field",
"and",
"a",
"dynamic",
"part",
"return",
"the",
"name",
"of",
"the",
"final",
"dynamic",
"field",
"to",
"use",
".",
"It",
"will",
"then",
"be",
"used",
"with",
"get_field",
"."
] | 13f34e39efd2f802761457da30ab2a4213b63934 | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/model.py#L160-L167 |
250,178 | heikomuller/sco-datastore | scodata/image.py | get_image_files | def get_image_files(directory, files):
"""Recursively iterate through directory tree and list all files that have a
valid image file suffix
Parameters
----------
directory : directory
Path to directory on disk
files : List(string)
List of file names
Returns
-------
List(string)
List of files that have a valid image suffix
"""
# For each file in the directory test if it is a valid image file or a
# sub-directory.
for f in os.listdir(directory):
abs_file = os.path.join(directory, f)
if os.path.isdir(abs_file):
# Recursively iterate through sub-directories
get_image_files(abs_file, files)
else:
# Add to file collection if has valid suffix
if '.' in f and '.' + f.rsplit('.', 1)[1] in VALID_IMGFILE_SUFFIXES:
files.append(abs_file)
return files | python | def get_image_files(directory, files):
"""Recursively iterate through directory tree and list all files that have a
valid image file suffix
Parameters
----------
directory : directory
Path to directory on disk
files : List(string)
List of file names
Returns
-------
List(string)
List of files that have a valid image suffix
"""
# For each file in the directory test if it is a valid image file or a
# sub-directory.
for f in os.listdir(directory):
abs_file = os.path.join(directory, f)
if os.path.isdir(abs_file):
# Recursively iterate through sub-directories
get_image_files(abs_file, files)
else:
# Add to file collection if has valid suffix
if '.' in f and '.' + f.rsplit('.', 1)[1] in VALID_IMGFILE_SUFFIXES:
files.append(abs_file)
return files | [
"def",
"get_image_files",
"(",
"directory",
",",
"files",
")",
":",
"# For each file in the directory test if it is a valid image file or a",
"# sub-directory.",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"abs_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"f",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"abs_file",
")",
":",
"# Recursively iterate through sub-directories",
"get_image_files",
"(",
"abs_file",
",",
"files",
")",
"else",
":",
"# Add to file collection if has valid suffix",
"if",
"'.'",
"in",
"f",
"and",
"'.'",
"+",
"f",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
"1",
"]",
"in",
"VALID_IMGFILE_SUFFIXES",
":",
"files",
".",
"append",
"(",
"abs_file",
")",
"return",
"files"
] | Recursively iterate through directory tree and list all files that have a
valid image file suffix
Parameters
----------
directory : directory
Path to directory on disk
files : List(string)
List of file names
Returns
-------
List(string)
List of files that have a valid image suffix | [
"Recursively",
"iterate",
"through",
"directory",
"tree",
"and",
"list",
"all",
"files",
"that",
"have",
"a",
"valid",
"image",
"file",
"suffix"
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/image.py#L879-L906 |
250,179 | heikomuller/sco-datastore | scodata/image.py | DefaultImageManager.create_object | def create_object(self, filename, img_properties=None):
"""Create an image object on local disk from the given file. The file
is copied to a new local directory that is created for the image object.
The optional list of image properties will be associated with the new
object together with the set of default properties for images.
Parameters
----------
filename : string
Path to file on disk
img_properties : Dictionary, optional
Set of image properties.
Returns
-------
ImageHandle
Handle for created image object
"""
# Get the file name, i.e., last component of the given absolute path
prop_name = os.path.basename(os.path.normpath(filename))
# Ensure that the image file has a valid suffix. Currently we do not
# check whether the file actually is an image. If the suffix is valid
# get the associated Mime type from the dictionary.
prop_mime = None
pos = prop_name.rfind('.')
if pos >= 0:
suffix = prop_name[pos:].lower()
if suffix in VALID_IMGFILE_SUFFIXES:
prop_mime = VALID_IMGFILE_SUFFIXES[suffix]
if not prop_mime:
raise ValueError('unsupported image type: ' + prop_name)
# Create a new object identifier.
identifier = str(uuid.uuid4()).replace('-','')
# The sub-folder to store the image is given by the first two
# characters of the identifier.
image_dir = self.get_directory(identifier)
# Create the directory if it doesn't exists
if not os.access(image_dir, os.F_OK):
os.makedirs(image_dir)
# Create the initial set of properties for the new image object.
properties = {
datastore.PROPERTY_NAME: prop_name,
datastore.PROPERTY_FILENAME : prop_name,
datastore.PROPERTY_FILESIZE : os.path.getsize(filename),
datastore.PROPERTY_MIMETYPE : prop_mime
}
# Add additional image properties (if given). Note that this will not
# override the default image properties.
if not img_properties is None:
for prop in img_properties:
if not prop in properties:
properties[prop] = img_properties[prop]
# Copy original file to new object's directory
shutil.copyfile(filename, os.path.join(image_dir, prop_name))
# Create object handle and store it in database before returning it
obj = ImageHandle(identifier, properties, image_dir)
self.insert_object(obj)
return obj | python | def create_object(self, filename, img_properties=None):
"""Create an image object on local disk from the given file. The file
is copied to a new local directory that is created for the image object.
The optional list of image properties will be associated with the new
object together with the set of default properties for images.
Parameters
----------
filename : string
Path to file on disk
img_properties : Dictionary, optional
Set of image properties.
Returns
-------
ImageHandle
Handle for created image object
"""
# Get the file name, i.e., last component of the given absolute path
prop_name = os.path.basename(os.path.normpath(filename))
# Ensure that the image file has a valid suffix. Currently we do not
# check whether the file actually is an image. If the suffix is valid
# get the associated Mime type from the dictionary.
prop_mime = None
pos = prop_name.rfind('.')
if pos >= 0:
suffix = prop_name[pos:].lower()
if suffix in VALID_IMGFILE_SUFFIXES:
prop_mime = VALID_IMGFILE_SUFFIXES[suffix]
if not prop_mime:
raise ValueError('unsupported image type: ' + prop_name)
# Create a new object identifier.
identifier = str(uuid.uuid4()).replace('-','')
# The sub-folder to store the image is given by the first two
# characters of the identifier.
image_dir = self.get_directory(identifier)
# Create the directory if it doesn't exists
if not os.access(image_dir, os.F_OK):
os.makedirs(image_dir)
# Create the initial set of properties for the new image object.
properties = {
datastore.PROPERTY_NAME: prop_name,
datastore.PROPERTY_FILENAME : prop_name,
datastore.PROPERTY_FILESIZE : os.path.getsize(filename),
datastore.PROPERTY_MIMETYPE : prop_mime
}
# Add additional image properties (if given). Note that this will not
# override the default image properties.
if not img_properties is None:
for prop in img_properties:
if not prop in properties:
properties[prop] = img_properties[prop]
# Copy original file to new object's directory
shutil.copyfile(filename, os.path.join(image_dir, prop_name))
# Create object handle and store it in database before returning it
obj = ImageHandle(identifier, properties, image_dir)
self.insert_object(obj)
return obj | [
"def",
"create_object",
"(",
"self",
",",
"filename",
",",
"img_properties",
"=",
"None",
")",
":",
"# Get the file name, i.e., last component of the given absolute path",
"prop_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"filename",
")",
")",
"# Ensure that the image file has a valid suffix. Currently we do not",
"# check whether the file actually is an image. If the suffix is valid",
"# get the associated Mime type from the dictionary.",
"prop_mime",
"=",
"None",
"pos",
"=",
"prop_name",
".",
"rfind",
"(",
"'.'",
")",
"if",
"pos",
">=",
"0",
":",
"suffix",
"=",
"prop_name",
"[",
"pos",
":",
"]",
".",
"lower",
"(",
")",
"if",
"suffix",
"in",
"VALID_IMGFILE_SUFFIXES",
":",
"prop_mime",
"=",
"VALID_IMGFILE_SUFFIXES",
"[",
"suffix",
"]",
"if",
"not",
"prop_mime",
":",
"raise",
"ValueError",
"(",
"'unsupported image type: '",
"+",
"prop_name",
")",
"# Create a new object identifier.",
"identifier",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"# The sub-folder to store the image is given by the first two",
"# characters of the identifier.",
"image_dir",
"=",
"self",
".",
"get_directory",
"(",
"identifier",
")",
"# Create the directory if it doesn't exists",
"if",
"not",
"os",
".",
"access",
"(",
"image_dir",
",",
"os",
".",
"F_OK",
")",
":",
"os",
".",
"makedirs",
"(",
"image_dir",
")",
"# Create the initial set of properties for the new image object.",
"properties",
"=",
"{",
"datastore",
".",
"PROPERTY_NAME",
":",
"prop_name",
",",
"datastore",
".",
"PROPERTY_FILENAME",
":",
"prop_name",
",",
"datastore",
".",
"PROPERTY_FILESIZE",
":",
"os",
".",
"path",
".",
"getsize",
"(",
"filename",
")",
",",
"datastore",
".",
"PROPERTY_MIMETYPE",
":",
"prop_mime",
"}",
"# Add additional image properties (if given). Note that this will not",
"# override the default image properties.",
"if",
"not",
"img_properties",
"is",
"None",
":",
"for",
"prop",
"in",
"img_properties",
":",
"if",
"not",
"prop",
"in",
"properties",
":",
"properties",
"[",
"prop",
"]",
"=",
"img_properties",
"[",
"prop",
"]",
"# Copy original file to new object's directory",
"shutil",
".",
"copyfile",
"(",
"filename",
",",
"os",
".",
"path",
".",
"join",
"(",
"image_dir",
",",
"prop_name",
")",
")",
"# Create object handle and store it in database before returning it",
"obj",
"=",
"ImageHandle",
"(",
"identifier",
",",
"properties",
",",
"image_dir",
")",
"self",
".",
"insert_object",
"(",
"obj",
")",
"return",
"obj"
] | Create an image object on local disk from the given file. The file
is copied to a new local directory that is created for the image object.
The optional list of image properties will be associated with the new
object together with the set of default properties for images.
Parameters
----------
filename : string
Path to file on disk
img_properties : Dictionary, optional
Set of image properties.
Returns
-------
ImageHandle
Handle for created image object | [
"Create",
"an",
"image",
"object",
"on",
"local",
"disk",
"from",
"the",
"given",
"file",
".",
"The",
"file",
"is",
"copied",
"to",
"a",
"new",
"local",
"directory",
"that",
"is",
"created",
"for",
"the",
"image",
"object",
".",
"The",
"optional",
"list",
"of",
"image",
"properties",
"will",
"be",
"associated",
"with",
"the",
"new",
"object",
"together",
"with",
"the",
"set",
"of",
"default",
"properties",
"for",
"images",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/image.py#L327-L384 |
250,180 | heikomuller/sco-datastore | scodata/image.py | DefaultImageManager.from_dict | def from_dict(self, document):
"""Create image object from JSON document retrieved from database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
ImageHandle
Handle for image object
"""
# Get object properties from Json document
identifier = str(document['_id'])
active = document['active']
timestamp = datetime.datetime.strptime(document['timestamp'], '%Y-%m-%dT%H:%M:%S.%f')
properties = document['properties']
# The directory is not materilaized in database to allow moving the
# base directory without having to update the database.
directory = self.get_directory(identifier)
# Cretae image handle
return ImageHandle(identifier, properties, directory, timestamp=timestamp, is_active=active) | python | def from_dict(self, document):
"""Create image object from JSON document retrieved from database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
ImageHandle
Handle for image object
"""
# Get object properties from Json document
identifier = str(document['_id'])
active = document['active']
timestamp = datetime.datetime.strptime(document['timestamp'], '%Y-%m-%dT%H:%M:%S.%f')
properties = document['properties']
# The directory is not materilaized in database to allow moving the
# base directory without having to update the database.
directory = self.get_directory(identifier)
# Cretae image handle
return ImageHandle(identifier, properties, directory, timestamp=timestamp, is_active=active) | [
"def",
"from_dict",
"(",
"self",
",",
"document",
")",
":",
"# Get object properties from Json document",
"identifier",
"=",
"str",
"(",
"document",
"[",
"'_id'",
"]",
")",
"active",
"=",
"document",
"[",
"'active'",
"]",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"document",
"[",
"'timestamp'",
"]",
",",
"'%Y-%m-%dT%H:%M:%S.%f'",
")",
"properties",
"=",
"document",
"[",
"'properties'",
"]",
"# The directory is not materilaized in database to allow moving the",
"# base directory without having to update the database.",
"directory",
"=",
"self",
".",
"get_directory",
"(",
"identifier",
")",
"# Cretae image handle",
"return",
"ImageHandle",
"(",
"identifier",
",",
"properties",
",",
"directory",
",",
"timestamp",
"=",
"timestamp",
",",
"is_active",
"=",
"active",
")"
] | Create image object from JSON document retrieved from database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
ImageHandle
Handle for image object | [
"Create",
"image",
"object",
"from",
"JSON",
"document",
"retrieved",
"from",
"database",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/image.py#L386-L408 |
250,181 | heikomuller/sco-datastore | scodata/image.py | DefaultImageManager.get_directory | def get_directory(self, identifier):
"""Implements the policy for naming directories for image objects. Image
object directories are name by their identifier. In addition, these
directories are grouped in parent directories named by the first two
characters of the identifier. The aim is to avoid having too many
sub-folders in a single directory.
Parameters
----------
identifier : string
Unique object identifier
Returns
-------
string
Path to image objects data directory
"""
return os.path.join(
os.path.join(self.directory, identifier[:2]),
identifier
) | python | def get_directory(self, identifier):
"""Implements the policy for naming directories for image objects. Image
object directories are name by their identifier. In addition, these
directories are grouped in parent directories named by the first two
characters of the identifier. The aim is to avoid having too many
sub-folders in a single directory.
Parameters
----------
identifier : string
Unique object identifier
Returns
-------
string
Path to image objects data directory
"""
return os.path.join(
os.path.join(self.directory, identifier[:2]),
identifier
) | [
"def",
"get_directory",
"(",
"self",
",",
"identifier",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"directory",
",",
"identifier",
"[",
":",
"2",
"]",
")",
",",
"identifier",
")"
] | Implements the policy for naming directories for image objects. Image
object directories are name by their identifier. In addition, these
directories are grouped in parent directories named by the first two
characters of the identifier. The aim is to avoid having too many
sub-folders in a single directory.
Parameters
----------
identifier : string
Unique object identifier
Returns
-------
string
Path to image objects data directory | [
"Implements",
"the",
"policy",
"for",
"naming",
"directories",
"for",
"image",
"objects",
".",
"Image",
"object",
"directories",
"are",
"name",
"by",
"their",
"identifier",
".",
"In",
"addition",
"these",
"directories",
"are",
"grouped",
"in",
"parent",
"directories",
"named",
"by",
"the",
"first",
"two",
"characters",
"of",
"the",
"identifier",
".",
"The",
"aim",
"is",
"to",
"avoid",
"having",
"too",
"many",
"sub",
"-",
"folders",
"in",
"a",
"single",
"directory",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/image.py#L410-L430 |
250,182 | heikomuller/sco-datastore | scodata/image.py | DefaultImageGroupManager.create_object | def create_object(self, name, images, filename, options=None, object_identifier=None, read_only=False):
"""Create an image group object with the given list of images. The
file name specifies the location on local disk where the tar-file
containing the image group files is located. The file will be copied
to the image groups data directory.
Parameters
----------
name : string
User-provided name for the image group
images : List(GroupImage)
List of objects describing images in the group
filename : string
Location of local file containing all images in the group
options : list(dict('name':...,'value:...')), optional
List of image group options. If None, default values will be used.
object_identifier : string
Unique object identifier, optional
read_only : boolean, optional
Optional value for the read-only property
Returns
-------
ImageGroupHandle
Object handle for created image group
"""
# Raise an exception if given image group is not valied.
self.validate_group(images)
# Create a new object identifier if none is given.
if object_identifier is None:
identifier = str(uuid.uuid4()).replace('-','')
else:
identifier = object_identifier
# Create the initial set of properties.
prop_filename = os.path.basename(os.path.normpath(filename))
prop_mime = 'application/x-tar' if filename.endswith('.tar') else 'application/x-gzip'
properties = {
datastore.PROPERTY_NAME: name,
datastore.PROPERTY_FILENAME : prop_filename,
datastore.PROPERTY_FILESIZE : os.path.getsize(filename),
datastore.PROPERTY_MIMETYPE : prop_mime
}
if read_only:
properties[datastore.PROPERTY_READONLY] = True
# Directories are simply named by object identifier
directory = os.path.join(self.directory, identifier)
# Create the directory if it doesn't exists
if not os.access(directory, os.F_OK):
os.makedirs(directory)
# Move original file to object directory
shutil.copyfile(filename, os.path.join(directory, prop_filename))
# Get dictionary of given options. If none are given opts will be an
# empty dictionary. If duplicate attribute names are present an
# exception will be raised.
opts = attribute.to_dict(options, self.attribute_defs)
# Create the image group object and store it in the database before
# returning it.
obj = ImageGroupHandle(
identifier,
properties,
directory,
images,
opts
)
self.insert_object(obj)
return obj | python | def create_object(self, name, images, filename, options=None, object_identifier=None, read_only=False):
"""Create an image group object with the given list of images. The
file name specifies the location on local disk where the tar-file
containing the image group files is located. The file will be copied
to the image groups data directory.
Parameters
----------
name : string
User-provided name for the image group
images : List(GroupImage)
List of objects describing images in the group
filename : string
Location of local file containing all images in the group
options : list(dict('name':...,'value:...')), optional
List of image group options. If None, default values will be used.
object_identifier : string
Unique object identifier, optional
read_only : boolean, optional
Optional value for the read-only property
Returns
-------
ImageGroupHandle
Object handle for created image group
"""
# Raise an exception if given image group is not valied.
self.validate_group(images)
# Create a new object identifier if none is given.
if object_identifier is None:
identifier = str(uuid.uuid4()).replace('-','')
else:
identifier = object_identifier
# Create the initial set of properties.
prop_filename = os.path.basename(os.path.normpath(filename))
prop_mime = 'application/x-tar' if filename.endswith('.tar') else 'application/x-gzip'
properties = {
datastore.PROPERTY_NAME: name,
datastore.PROPERTY_FILENAME : prop_filename,
datastore.PROPERTY_FILESIZE : os.path.getsize(filename),
datastore.PROPERTY_MIMETYPE : prop_mime
}
if read_only:
properties[datastore.PROPERTY_READONLY] = True
# Directories are simply named by object identifier
directory = os.path.join(self.directory, identifier)
# Create the directory if it doesn't exists
if not os.access(directory, os.F_OK):
os.makedirs(directory)
# Move original file to object directory
shutil.copyfile(filename, os.path.join(directory, prop_filename))
# Get dictionary of given options. If none are given opts will be an
# empty dictionary. If duplicate attribute names are present an
# exception will be raised.
opts = attribute.to_dict(options, self.attribute_defs)
# Create the image group object and store it in the database before
# returning it.
obj = ImageGroupHandle(
identifier,
properties,
directory,
images,
opts
)
self.insert_object(obj)
return obj | [
"def",
"create_object",
"(",
"self",
",",
"name",
",",
"images",
",",
"filename",
",",
"options",
"=",
"None",
",",
"object_identifier",
"=",
"None",
",",
"read_only",
"=",
"False",
")",
":",
"# Raise an exception if given image group is not valied.",
"self",
".",
"validate_group",
"(",
"images",
")",
"# Create a new object identifier if none is given.",
"if",
"object_identifier",
"is",
"None",
":",
"identifier",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"else",
":",
"identifier",
"=",
"object_identifier",
"# Create the initial set of properties.",
"prop_filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"filename",
")",
")",
"prop_mime",
"=",
"'application/x-tar'",
"if",
"filename",
".",
"endswith",
"(",
"'.tar'",
")",
"else",
"'application/x-gzip'",
"properties",
"=",
"{",
"datastore",
".",
"PROPERTY_NAME",
":",
"name",
",",
"datastore",
".",
"PROPERTY_FILENAME",
":",
"prop_filename",
",",
"datastore",
".",
"PROPERTY_FILESIZE",
":",
"os",
".",
"path",
".",
"getsize",
"(",
"filename",
")",
",",
"datastore",
".",
"PROPERTY_MIMETYPE",
":",
"prop_mime",
"}",
"if",
"read_only",
":",
"properties",
"[",
"datastore",
".",
"PROPERTY_READONLY",
"]",
"=",
"True",
"# Directories are simply named by object identifier",
"directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"directory",
",",
"identifier",
")",
"# Create the directory if it doesn't exists",
"if",
"not",
"os",
".",
"access",
"(",
"directory",
",",
"os",
".",
"F_OK",
")",
":",
"os",
".",
"makedirs",
"(",
"directory",
")",
"# Move original file to object directory",
"shutil",
".",
"copyfile",
"(",
"filename",
",",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"prop_filename",
")",
")",
"# Get dictionary of given options. If none are given opts will be an",
"# empty dictionary. If duplicate attribute names are present an",
"# exception will be raised.",
"opts",
"=",
"attribute",
".",
"to_dict",
"(",
"options",
",",
"self",
".",
"attribute_defs",
")",
"# Create the image group object and store it in the database before",
"# returning it.",
"obj",
"=",
"ImageGroupHandle",
"(",
"identifier",
",",
"properties",
",",
"directory",
",",
"images",
",",
"opts",
")",
"self",
".",
"insert_object",
"(",
"obj",
")",
"return",
"obj"
] | Create an image group object with the given list of images. The
file name specifies the location on local disk where the tar-file
containing the image group files is located. The file will be copied
to the image groups data directory.
Parameters
----------
name : string
User-provided name for the image group
images : List(GroupImage)
List of objects describing images in the group
filename : string
Location of local file containing all images in the group
options : list(dict('name':...,'value:...')), optional
List of image group options. If None, default values will be used.
object_identifier : string
Unique object identifier, optional
read_only : boolean, optional
Optional value for the read-only property
Returns
-------
ImageGroupHandle
Object handle for created image group | [
"Create",
"an",
"image",
"group",
"object",
"with",
"the",
"given",
"list",
"of",
"images",
".",
"The",
"file",
"name",
"specifies",
"the",
"location",
"on",
"local",
"disk",
"where",
"the",
"tar",
"-",
"file",
"containing",
"the",
"image",
"group",
"files",
"is",
"located",
".",
"The",
"file",
"will",
"be",
"copied",
"to",
"the",
"image",
"groups",
"data",
"directory",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/image.py#L545-L610 |
250,183 | heikomuller/sco-datastore | scodata/image.py | DefaultImageGroupManager.from_dict | def from_dict(self, document):
"""Create image group object from JSON document retrieved from database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
ImageGroupHandle
Handle for image group object
"""
# Get object attributes from Json document
identifier = str(document['_id'])
# Create list of group images from Json
images = list()
for grp_image in document['images']:
images.append(GroupImage(
grp_image['identifier'],
grp_image['folder'],
grp_image['name'],
os.path.join(
self.image_manager.get_directory(grp_image['identifier']),
grp_image['name']
)
))
# Create list of properties and add group size
properties = document['properties']
properties[PROPERTY_GROUPSIZE] = len(document['images'])
# Directories are simply named by object identifier
directory = os.path.join(self.directory, identifier)
# Create image group handle.
return ImageGroupHandle(
identifier,
properties,
directory,
images,
attribute.attributes_from_dict(document['options']),
timestamp=datetime.datetime.strptime(
document['timestamp'],
'%Y-%m-%dT%H:%M:%S.%f'
),
is_active=document['active']
) | python | def from_dict(self, document):
"""Create image group object from JSON document retrieved from database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
ImageGroupHandle
Handle for image group object
"""
# Get object attributes from Json document
identifier = str(document['_id'])
# Create list of group images from Json
images = list()
for grp_image in document['images']:
images.append(GroupImage(
grp_image['identifier'],
grp_image['folder'],
grp_image['name'],
os.path.join(
self.image_manager.get_directory(grp_image['identifier']),
grp_image['name']
)
))
# Create list of properties and add group size
properties = document['properties']
properties[PROPERTY_GROUPSIZE] = len(document['images'])
# Directories are simply named by object identifier
directory = os.path.join(self.directory, identifier)
# Create image group handle.
return ImageGroupHandle(
identifier,
properties,
directory,
images,
attribute.attributes_from_dict(document['options']),
timestamp=datetime.datetime.strptime(
document['timestamp'],
'%Y-%m-%dT%H:%M:%S.%f'
),
is_active=document['active']
) | [
"def",
"from_dict",
"(",
"self",
",",
"document",
")",
":",
"# Get object attributes from Json document",
"identifier",
"=",
"str",
"(",
"document",
"[",
"'_id'",
"]",
")",
"# Create list of group images from Json",
"images",
"=",
"list",
"(",
")",
"for",
"grp_image",
"in",
"document",
"[",
"'images'",
"]",
":",
"images",
".",
"append",
"(",
"GroupImage",
"(",
"grp_image",
"[",
"'identifier'",
"]",
",",
"grp_image",
"[",
"'folder'",
"]",
",",
"grp_image",
"[",
"'name'",
"]",
",",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"image_manager",
".",
"get_directory",
"(",
"grp_image",
"[",
"'identifier'",
"]",
")",
",",
"grp_image",
"[",
"'name'",
"]",
")",
")",
")",
"# Create list of properties and add group size",
"properties",
"=",
"document",
"[",
"'properties'",
"]",
"properties",
"[",
"PROPERTY_GROUPSIZE",
"]",
"=",
"len",
"(",
"document",
"[",
"'images'",
"]",
")",
"# Directories are simply named by object identifier",
"directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"directory",
",",
"identifier",
")",
"# Create image group handle.",
"return",
"ImageGroupHandle",
"(",
"identifier",
",",
"properties",
",",
"directory",
",",
"images",
",",
"attribute",
".",
"attributes_from_dict",
"(",
"document",
"[",
"'options'",
"]",
")",
",",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"document",
"[",
"'timestamp'",
"]",
",",
"'%Y-%m-%dT%H:%M:%S.%f'",
")",
",",
"is_active",
"=",
"document",
"[",
"'active'",
"]",
")"
] | Create image group object from JSON document retrieved from database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
ImageGroupHandle
Handle for image group object | [
"Create",
"image",
"group",
"object",
"from",
"JSON",
"document",
"retrieved",
"from",
"database",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/image.py#L612-L656 |
250,184 | heikomuller/sco-datastore | scodata/image.py | DefaultImageGroupManager.get_collections_for_image | def get_collections_for_image(self, image_id):
"""Get identifier of all collections that contain a given image.
Parameters
----------
image_id : string
Unique identifierof image object
Returns
-------
List(string)
List of image collection identifier
"""
result = []
# Get all active collections that contain the image identifier
for document in self.collection.find({'active' : True, 'images.identifier' : image_id}):
result.append(str(document['_id']))
return result | python | def get_collections_for_image(self, image_id):
"""Get identifier of all collections that contain a given image.
Parameters
----------
image_id : string
Unique identifierof image object
Returns
-------
List(string)
List of image collection identifier
"""
result = []
# Get all active collections that contain the image identifier
for document in self.collection.find({'active' : True, 'images.identifier' : image_id}):
result.append(str(document['_id']))
return result | [
"def",
"get_collections_for_image",
"(",
"self",
",",
"image_id",
")",
":",
"result",
"=",
"[",
"]",
"# Get all active collections that contain the image identifier",
"for",
"document",
"in",
"self",
".",
"collection",
".",
"find",
"(",
"{",
"'active'",
":",
"True",
",",
"'images.identifier'",
":",
"image_id",
"}",
")",
":",
"result",
".",
"append",
"(",
"str",
"(",
"document",
"[",
"'_id'",
"]",
")",
")",
"return",
"result"
] | Get identifier of all collections that contain a given image.
Parameters
----------
image_id : string
Unique identifierof image object
Returns
-------
List(string)
List of image collection identifier | [
"Get",
"identifier",
"of",
"all",
"collections",
"that",
"contain",
"a",
"given",
"image",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/image.py#L658-L675 |
250,185 | heikomuller/sco-datastore | scodata/image.py | DefaultImageGroupManager.to_dict | def to_dict(self, img_coll):
"""Create a Json-like dictionary for image group. Extends the basic
object with an array of image identifiers.
Parameters
----------
img_coll : ImageGroupHandle
Returns
-------
(JSON)
Json-like object, i.e., dictionary.
"""
# Get the basic Json object from the super class
json_obj = super(DefaultImageGroupManager, self).to_dict(img_coll)
# Add list of images as Json array
images = []
for img_group in img_coll.images:
images.append({
'identifier' : img_group.identifier,
'folder' : img_group.folder,
'name' : img_group.name
})
json_obj['images'] = images
# Transform dictionary of options into list of elements, one per typed
# attribute in the options set.
json_obj['options'] = attribute.attributes_to_dict(img_coll.options)
return json_obj | python | def to_dict(self, img_coll):
"""Create a Json-like dictionary for image group. Extends the basic
object with an array of image identifiers.
Parameters
----------
img_coll : ImageGroupHandle
Returns
-------
(JSON)
Json-like object, i.e., dictionary.
"""
# Get the basic Json object from the super class
json_obj = super(DefaultImageGroupManager, self).to_dict(img_coll)
# Add list of images as Json array
images = []
for img_group in img_coll.images:
images.append({
'identifier' : img_group.identifier,
'folder' : img_group.folder,
'name' : img_group.name
})
json_obj['images'] = images
# Transform dictionary of options into list of elements, one per typed
# attribute in the options set.
json_obj['options'] = attribute.attributes_to_dict(img_coll.options)
return json_obj | [
"def",
"to_dict",
"(",
"self",
",",
"img_coll",
")",
":",
"# Get the basic Json object from the super class",
"json_obj",
"=",
"super",
"(",
"DefaultImageGroupManager",
",",
"self",
")",
".",
"to_dict",
"(",
"img_coll",
")",
"# Add list of images as Json array",
"images",
"=",
"[",
"]",
"for",
"img_group",
"in",
"img_coll",
".",
"images",
":",
"images",
".",
"append",
"(",
"{",
"'identifier'",
":",
"img_group",
".",
"identifier",
",",
"'folder'",
":",
"img_group",
".",
"folder",
",",
"'name'",
":",
"img_group",
".",
"name",
"}",
")",
"json_obj",
"[",
"'images'",
"]",
"=",
"images",
"# Transform dictionary of options into list of elements, one per typed",
"# attribute in the options set.",
"json_obj",
"[",
"'options'",
"]",
"=",
"attribute",
".",
"attributes_to_dict",
"(",
"img_coll",
".",
"options",
")",
"return",
"json_obj"
] | Create a Json-like dictionary for image group. Extends the basic
object with an array of image identifiers.
Parameters
----------
img_coll : ImageGroupHandle
Returns
-------
(JSON)
Json-like object, i.e., dictionary. | [
"Create",
"a",
"Json",
"-",
"like",
"dictionary",
"for",
"image",
"group",
".",
"Extends",
"the",
"basic",
"object",
"with",
"an",
"array",
"of",
"image",
"identifiers",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/image.py#L711-L738 |
250,186 | heikomuller/sco-datastore | scodata/image.py | DefaultImageGroupManager.validate_group | def validate_group(images):
"""Validates that the combination of folder and name for all images in
a group is unique. Raises a ValueError exception if uniqueness
constraint is violated.
Parameters
----------
images : List(GroupImage)
List of images in group
"""
image_ids = set()
for image in images:
key = image.folder + image.name
if key in image_ids:
raise ValueError('Duplicate images in group: ' + key)
else:
image_ids.add(key) | python | def validate_group(images):
"""Validates that the combination of folder and name for all images in
a group is unique. Raises a ValueError exception if uniqueness
constraint is violated.
Parameters
----------
images : List(GroupImage)
List of images in group
"""
image_ids = set()
for image in images:
key = image.folder + image.name
if key in image_ids:
raise ValueError('Duplicate images in group: ' + key)
else:
image_ids.add(key) | [
"def",
"validate_group",
"(",
"images",
")",
":",
"image_ids",
"=",
"set",
"(",
")",
"for",
"image",
"in",
"images",
":",
"key",
"=",
"image",
".",
"folder",
"+",
"image",
".",
"name",
"if",
"key",
"in",
"image_ids",
":",
"raise",
"ValueError",
"(",
"'Duplicate images in group: '",
"+",
"key",
")",
"else",
":",
"image_ids",
".",
"add",
"(",
"key",
")"
] | Validates that the combination of folder and name for all images in
a group is unique. Raises a ValueError exception if uniqueness
constraint is violated.
Parameters
----------
images : List(GroupImage)
List of images in group | [
"Validates",
"that",
"the",
"combination",
"of",
"folder",
"and",
"name",
"for",
"all",
"images",
"in",
"a",
"group",
"is",
"unique",
".",
"Raises",
"a",
"ValueError",
"exception",
"if",
"uniqueness",
"constraint",
"is",
"violated",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/image.py#L771-L787 |
250,187 | heikomuller/sco-datastore | scodata/image.py | DefaultPredictionImageSetManager.create_object | def create_object(self, name, image_sets):
"""Create a prediction image set list.
Parameters
----------
name : string
User-provided name for the image group.
image_sets : list(PredictionImageSet)
List of prediction image sets
Returns
-------
PredictionImageSetHandle
Object handle for created prediction image set
"""
# Create a new object identifier
identifier = str(uuid.uuid4()).replace('-','')
properties = {datastore.PROPERTY_NAME: name}
# Create the image group object and store it in the database before
# returning it.
obj = PredictionImageSetHandle(identifier, properties, image_sets)
self.insert_object(obj)
return obj | python | def create_object(self, name, image_sets):
"""Create a prediction image set list.
Parameters
----------
name : string
User-provided name for the image group.
image_sets : list(PredictionImageSet)
List of prediction image sets
Returns
-------
PredictionImageSetHandle
Object handle for created prediction image set
"""
# Create a new object identifier
identifier = str(uuid.uuid4()).replace('-','')
properties = {datastore.PROPERTY_NAME: name}
# Create the image group object and store it in the database before
# returning it.
obj = PredictionImageSetHandle(identifier, properties, image_sets)
self.insert_object(obj)
return obj | [
"def",
"create_object",
"(",
"self",
",",
"name",
",",
"image_sets",
")",
":",
"# Create a new object identifier",
"identifier",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"properties",
"=",
"{",
"datastore",
".",
"PROPERTY_NAME",
":",
"name",
"}",
"# Create the image group object and store it in the database before",
"# returning it.",
"obj",
"=",
"PredictionImageSetHandle",
"(",
"identifier",
",",
"properties",
",",
"image_sets",
")",
"self",
".",
"insert_object",
"(",
"obj",
")",
"return",
"obj"
] | Create a prediction image set list.
Parameters
----------
name : string
User-provided name for the image group.
image_sets : list(PredictionImageSet)
List of prediction image sets
Returns
-------
PredictionImageSetHandle
Object handle for created prediction image set | [
"Create",
"a",
"prediction",
"image",
"set",
"list",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/image.py#L806-L828 |
250,188 | heikomuller/sco-datastore | scodata/image.py | DefaultPredictionImageSetManager.from_dict | def from_dict(self, document):
"""Create a prediction image set resource from a dictionary
serialization.
Parameters
----------
document : dict
Dictionary serialization of the resource
Returns
-------
PredictionImageSetHandle
Handle for prediction image sets
"""
return PredictionImageSetHandle(
str(document['_id']),
document['properties'],
[PredictionImageSet.from_dict(img) for img in document['images']],
timestamp=datetime.datetime.strptime(
document['timestamp'],
'%Y-%m-%dT%H:%M:%S.%f'
),
is_active=document['active']
) | python | def from_dict(self, document):
"""Create a prediction image set resource from a dictionary
serialization.
Parameters
----------
document : dict
Dictionary serialization of the resource
Returns
-------
PredictionImageSetHandle
Handle for prediction image sets
"""
return PredictionImageSetHandle(
str(document['_id']),
document['properties'],
[PredictionImageSet.from_dict(img) for img in document['images']],
timestamp=datetime.datetime.strptime(
document['timestamp'],
'%Y-%m-%dT%H:%M:%S.%f'
),
is_active=document['active']
) | [
"def",
"from_dict",
"(",
"self",
",",
"document",
")",
":",
"return",
"PredictionImageSetHandle",
"(",
"str",
"(",
"document",
"[",
"'_id'",
"]",
")",
",",
"document",
"[",
"'properties'",
"]",
",",
"[",
"PredictionImageSet",
".",
"from_dict",
"(",
"img",
")",
"for",
"img",
"in",
"document",
"[",
"'images'",
"]",
"]",
",",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"document",
"[",
"'timestamp'",
"]",
",",
"'%Y-%m-%dT%H:%M:%S.%f'",
")",
",",
"is_active",
"=",
"document",
"[",
"'active'",
"]",
")"
] | Create a prediction image set resource from a dictionary
serialization.
Parameters
----------
document : dict
Dictionary serialization of the resource
Returns
-------
PredictionImageSetHandle
Handle for prediction image sets | [
"Create",
"a",
"prediction",
"image",
"set",
"resource",
"from",
"a",
"dictionary",
"serialization",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/image.py#L830-L853 |
250,189 | heikomuller/sco-datastore | scodata/image.py | DefaultPredictionImageSetManager.to_dict | def to_dict(self, img_sets):
"""Create a dictionary serialization for a prediction image set handle.
Parameters
----------
img_sets : PredictionImageSetHandle
Returns
-------
dict
Dictionary serialization of the resource
"""
# Get the basic Json object from the super class
json_obj = super(DefaultPredictionImageSetManager, self).to_dict(img_sets)
# Add list of image sets as Json array
json_obj['images'] = [img_set.to_dict() for img_set in img_sets.images]
return json_obj | python | def to_dict(self, img_sets):
"""Create a dictionary serialization for a prediction image set handle.
Parameters
----------
img_sets : PredictionImageSetHandle
Returns
-------
dict
Dictionary serialization of the resource
"""
# Get the basic Json object from the super class
json_obj = super(DefaultPredictionImageSetManager, self).to_dict(img_sets)
# Add list of image sets as Json array
json_obj['images'] = [img_set.to_dict() for img_set in img_sets.images]
return json_obj | [
"def",
"to_dict",
"(",
"self",
",",
"img_sets",
")",
":",
"# Get the basic Json object from the super class",
"json_obj",
"=",
"super",
"(",
"DefaultPredictionImageSetManager",
",",
"self",
")",
".",
"to_dict",
"(",
"img_sets",
")",
"# Add list of image sets as Json array",
"json_obj",
"[",
"'images'",
"]",
"=",
"[",
"img_set",
".",
"to_dict",
"(",
")",
"for",
"img_set",
"in",
"img_sets",
".",
"images",
"]",
"return",
"json_obj"
] | Create a dictionary serialization for a prediction image set handle.
Parameters
----------
img_sets : PredictionImageSetHandle
Returns
-------
dict
Dictionary serialization of the resource | [
"Create",
"a",
"dictionary",
"serialization",
"for",
"a",
"prediction",
"image",
"set",
"handle",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/image.py#L855-L871 |
250,190 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/playbook/play.py | Play._load_tasks | def _load_tasks(self, tasks, vars={}, additional_conditions=[]):
''' handle task and handler include statements '''
results = []
if tasks is None:
# support empty handler files, and the like.
tasks = []
for x in tasks:
task_vars = self.vars.copy()
task_vars.update(vars)
if 'include' in x:
tokens = shlex.split(x['include'])
items = ['']
included_additional_conditions = list(additional_conditions)
for k in x:
if k.startswith("with_"):
plugin_name = k[5:]
if plugin_name not in utils.plugins.lookup_loader:
raise errors.AnsibleError("cannot find lookup plugin named %s for usage in with_%s" % (plugin_name, plugin_name))
terms = utils.template_ds(self.basedir, x[k], task_vars)
items = utils.plugins.lookup_loader.get(plugin_name, basedir=self.basedir, runner=None).run(terms, inject=task_vars)
elif k.startswith("when_"):
included_additional_conditions.append(utils.compile_when_to_only_if("%s %s" % (k[5:], x[k])))
elif k in ("include", "vars", "only_if"):
pass
else:
raise errors.AnsibleError("parse error: task includes cannot be used with other directives: %s" % k)
if 'vars' in x:
task_vars.update(x['vars'])
if 'only_if' in x:
included_additional_conditions.append(x['only_if'])
for item in items:
mv = task_vars.copy()
mv['item'] = item
for t in tokens[1:]:
(k,v) = t.split("=", 1)
mv[k] = utils.template_ds(self.basedir, v, mv)
include_file = utils.template(self.basedir, tokens[0], mv)
data = utils.parse_yaml_from_file(utils.path_dwim(self.basedir, include_file))
results += self._load_tasks(data, mv, included_additional_conditions)
elif type(x) == dict:
results.append(Task(self,x,module_vars=task_vars, additional_conditions=additional_conditions))
else:
raise Exception("unexpected task type")
for x in results:
if self.tags is not None:
x.tags.extend(self.tags)
return results | python | def _load_tasks(self, tasks, vars={}, additional_conditions=[]):
''' handle task and handler include statements '''
results = []
if tasks is None:
# support empty handler files, and the like.
tasks = []
for x in tasks:
task_vars = self.vars.copy()
task_vars.update(vars)
if 'include' in x:
tokens = shlex.split(x['include'])
items = ['']
included_additional_conditions = list(additional_conditions)
for k in x:
if k.startswith("with_"):
plugin_name = k[5:]
if plugin_name not in utils.plugins.lookup_loader:
raise errors.AnsibleError("cannot find lookup plugin named %s for usage in with_%s" % (plugin_name, plugin_name))
terms = utils.template_ds(self.basedir, x[k], task_vars)
items = utils.plugins.lookup_loader.get(plugin_name, basedir=self.basedir, runner=None).run(terms, inject=task_vars)
elif k.startswith("when_"):
included_additional_conditions.append(utils.compile_when_to_only_if("%s %s" % (k[5:], x[k])))
elif k in ("include", "vars", "only_if"):
pass
else:
raise errors.AnsibleError("parse error: task includes cannot be used with other directives: %s" % k)
if 'vars' in x:
task_vars.update(x['vars'])
if 'only_if' in x:
included_additional_conditions.append(x['only_if'])
for item in items:
mv = task_vars.copy()
mv['item'] = item
for t in tokens[1:]:
(k,v) = t.split("=", 1)
mv[k] = utils.template_ds(self.basedir, v, mv)
include_file = utils.template(self.basedir, tokens[0], mv)
data = utils.parse_yaml_from_file(utils.path_dwim(self.basedir, include_file))
results += self._load_tasks(data, mv, included_additional_conditions)
elif type(x) == dict:
results.append(Task(self,x,module_vars=task_vars, additional_conditions=additional_conditions))
else:
raise Exception("unexpected task type")
for x in results:
if self.tags is not None:
x.tags.extend(self.tags)
return results | [
"def",
"_load_tasks",
"(",
"self",
",",
"tasks",
",",
"vars",
"=",
"{",
"}",
",",
"additional_conditions",
"=",
"[",
"]",
")",
":",
"results",
"=",
"[",
"]",
"if",
"tasks",
"is",
"None",
":",
"# support empty handler files, and the like.",
"tasks",
"=",
"[",
"]",
"for",
"x",
"in",
"tasks",
":",
"task_vars",
"=",
"self",
".",
"vars",
".",
"copy",
"(",
")",
"task_vars",
".",
"update",
"(",
"vars",
")",
"if",
"'include'",
"in",
"x",
":",
"tokens",
"=",
"shlex",
".",
"split",
"(",
"x",
"[",
"'include'",
"]",
")",
"items",
"=",
"[",
"''",
"]",
"included_additional_conditions",
"=",
"list",
"(",
"additional_conditions",
")",
"for",
"k",
"in",
"x",
":",
"if",
"k",
".",
"startswith",
"(",
"\"with_\"",
")",
":",
"plugin_name",
"=",
"k",
"[",
"5",
":",
"]",
"if",
"plugin_name",
"not",
"in",
"utils",
".",
"plugins",
".",
"lookup_loader",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"cannot find lookup plugin named %s for usage in with_%s\"",
"%",
"(",
"plugin_name",
",",
"plugin_name",
")",
")",
"terms",
"=",
"utils",
".",
"template_ds",
"(",
"self",
".",
"basedir",
",",
"x",
"[",
"k",
"]",
",",
"task_vars",
")",
"items",
"=",
"utils",
".",
"plugins",
".",
"lookup_loader",
".",
"get",
"(",
"plugin_name",
",",
"basedir",
"=",
"self",
".",
"basedir",
",",
"runner",
"=",
"None",
")",
".",
"run",
"(",
"terms",
",",
"inject",
"=",
"task_vars",
")",
"elif",
"k",
".",
"startswith",
"(",
"\"when_\"",
")",
":",
"included_additional_conditions",
".",
"append",
"(",
"utils",
".",
"compile_when_to_only_if",
"(",
"\"%s %s\"",
"%",
"(",
"k",
"[",
"5",
":",
"]",
",",
"x",
"[",
"k",
"]",
")",
")",
")",
"elif",
"k",
"in",
"(",
"\"include\"",
",",
"\"vars\"",
",",
"\"only_if\"",
")",
":",
"pass",
"else",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"parse error: task includes cannot be used with other directives: %s\"",
"%",
"k",
")",
"if",
"'vars'",
"in",
"x",
":",
"task_vars",
".",
"update",
"(",
"x",
"[",
"'vars'",
"]",
")",
"if",
"'only_if'",
"in",
"x",
":",
"included_additional_conditions",
".",
"append",
"(",
"x",
"[",
"'only_if'",
"]",
")",
"for",
"item",
"in",
"items",
":",
"mv",
"=",
"task_vars",
".",
"copy",
"(",
")",
"mv",
"[",
"'item'",
"]",
"=",
"item",
"for",
"t",
"in",
"tokens",
"[",
"1",
":",
"]",
":",
"(",
"k",
",",
"v",
")",
"=",
"t",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
"mv",
"[",
"k",
"]",
"=",
"utils",
".",
"template_ds",
"(",
"self",
".",
"basedir",
",",
"v",
",",
"mv",
")",
"include_file",
"=",
"utils",
".",
"template",
"(",
"self",
".",
"basedir",
",",
"tokens",
"[",
"0",
"]",
",",
"mv",
")",
"data",
"=",
"utils",
".",
"parse_yaml_from_file",
"(",
"utils",
".",
"path_dwim",
"(",
"self",
".",
"basedir",
",",
"include_file",
")",
")",
"results",
"+=",
"self",
".",
"_load_tasks",
"(",
"data",
",",
"mv",
",",
"included_additional_conditions",
")",
"elif",
"type",
"(",
"x",
")",
"==",
"dict",
":",
"results",
".",
"append",
"(",
"Task",
"(",
"self",
",",
"x",
",",
"module_vars",
"=",
"task_vars",
",",
"additional_conditions",
"=",
"additional_conditions",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"unexpected task type\"",
")",
"for",
"x",
"in",
"results",
":",
"if",
"self",
".",
"tags",
"is",
"not",
"None",
":",
"x",
".",
"tags",
".",
"extend",
"(",
"self",
".",
"tags",
")",
"return",
"results"
] | handle task and handler include statements | [
"handle",
"task",
"and",
"handler",
"include",
"statements"
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/playbook/play.py#L100-L152 |
250,191 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/playbook/play.py | Play._get_vars | def _get_vars(self):
''' load the vars section from a play, accounting for all sorts of variable features
including loading from yaml files, prompting, and conditional includes of the first
file found in a list. '''
if self.vars is None:
self.vars = {}
if type(self.vars) not in [dict, list]:
raise errors.AnsibleError("'vars' section must contain only key/value pairs")
vars = {}
# translate a list of vars into a dict
if type(self.vars) == list:
for item in self.vars:
if getattr(item, 'items', None) is None:
raise errors.AnsibleError("expecting a key-value pair in 'vars' section")
k, v = item.items()[0]
vars[k] = v
else:
vars.update(self.vars)
if type(self.playbook.extra_vars) == dict:
vars.update(self.playbook.extra_vars)
if type(self.vars_prompt) == list:
for var in self.vars_prompt:
if not 'name' in var:
raise errors.AnsibleError("'vars_prompt' item is missing 'name:'")
vname = var['name']
prompt = var.get("prompt", vname)
default = var.get("default", None)
private = var.get("private", True)
confirm = var.get("confirm", False)
encrypt = var.get("encrypt", None)
salt_size = var.get("salt_size", None)
salt = var.get("salt", None)
if vname not in self.playbook.extra_vars:
vars[vname] = self.playbook.callbacks.on_vars_prompt (
vname, private, prompt, encrypt, confirm, salt_size, salt, default
)
elif type(self.vars_prompt) == dict:
for (vname, prompt) in self.vars_prompt.iteritems():
prompt_msg = "%s: " % prompt
if vname not in self.playbook.extra_vars:
vars[vname] = self.playbook.callbacks.on_vars_prompt(
varname=vname, private=False, prompt=prompt_msg, default=None
)
else:
raise errors.AnsibleError("'vars_prompt' section is malformed, see docs")
results = self.playbook.extra_vars.copy()
results.update(vars)
return results | python | def _get_vars(self):
''' load the vars section from a play, accounting for all sorts of variable features
including loading from yaml files, prompting, and conditional includes of the first
file found in a list. '''
if self.vars is None:
self.vars = {}
if type(self.vars) not in [dict, list]:
raise errors.AnsibleError("'vars' section must contain only key/value pairs")
vars = {}
# translate a list of vars into a dict
if type(self.vars) == list:
for item in self.vars:
if getattr(item, 'items', None) is None:
raise errors.AnsibleError("expecting a key-value pair in 'vars' section")
k, v = item.items()[0]
vars[k] = v
else:
vars.update(self.vars)
if type(self.playbook.extra_vars) == dict:
vars.update(self.playbook.extra_vars)
if type(self.vars_prompt) == list:
for var in self.vars_prompt:
if not 'name' in var:
raise errors.AnsibleError("'vars_prompt' item is missing 'name:'")
vname = var['name']
prompt = var.get("prompt", vname)
default = var.get("default", None)
private = var.get("private", True)
confirm = var.get("confirm", False)
encrypt = var.get("encrypt", None)
salt_size = var.get("salt_size", None)
salt = var.get("salt", None)
if vname not in self.playbook.extra_vars:
vars[vname] = self.playbook.callbacks.on_vars_prompt (
vname, private, prompt, encrypt, confirm, salt_size, salt, default
)
elif type(self.vars_prompt) == dict:
for (vname, prompt) in self.vars_prompt.iteritems():
prompt_msg = "%s: " % prompt
if vname not in self.playbook.extra_vars:
vars[vname] = self.playbook.callbacks.on_vars_prompt(
varname=vname, private=False, prompt=prompt_msg, default=None
)
else:
raise errors.AnsibleError("'vars_prompt' section is malformed, see docs")
results = self.playbook.extra_vars.copy()
results.update(vars)
return results | [
"def",
"_get_vars",
"(",
"self",
")",
":",
"if",
"self",
".",
"vars",
"is",
"None",
":",
"self",
".",
"vars",
"=",
"{",
"}",
"if",
"type",
"(",
"self",
".",
"vars",
")",
"not",
"in",
"[",
"dict",
",",
"list",
"]",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"'vars' section must contain only key/value pairs\"",
")",
"vars",
"=",
"{",
"}",
"# translate a list of vars into a dict",
"if",
"type",
"(",
"self",
".",
"vars",
")",
"==",
"list",
":",
"for",
"item",
"in",
"self",
".",
"vars",
":",
"if",
"getattr",
"(",
"item",
",",
"'items'",
",",
"None",
")",
"is",
"None",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"expecting a key-value pair in 'vars' section\"",
")",
"k",
",",
"v",
"=",
"item",
".",
"items",
"(",
")",
"[",
"0",
"]",
"vars",
"[",
"k",
"]",
"=",
"v",
"else",
":",
"vars",
".",
"update",
"(",
"self",
".",
"vars",
")",
"if",
"type",
"(",
"self",
".",
"playbook",
".",
"extra_vars",
")",
"==",
"dict",
":",
"vars",
".",
"update",
"(",
"self",
".",
"playbook",
".",
"extra_vars",
")",
"if",
"type",
"(",
"self",
".",
"vars_prompt",
")",
"==",
"list",
":",
"for",
"var",
"in",
"self",
".",
"vars_prompt",
":",
"if",
"not",
"'name'",
"in",
"var",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"'vars_prompt' item is missing 'name:'\"",
")",
"vname",
"=",
"var",
"[",
"'name'",
"]",
"prompt",
"=",
"var",
".",
"get",
"(",
"\"prompt\"",
",",
"vname",
")",
"default",
"=",
"var",
".",
"get",
"(",
"\"default\"",
",",
"None",
")",
"private",
"=",
"var",
".",
"get",
"(",
"\"private\"",
",",
"True",
")",
"confirm",
"=",
"var",
".",
"get",
"(",
"\"confirm\"",
",",
"False",
")",
"encrypt",
"=",
"var",
".",
"get",
"(",
"\"encrypt\"",
",",
"None",
")",
"salt_size",
"=",
"var",
".",
"get",
"(",
"\"salt_size\"",
",",
"None",
")",
"salt",
"=",
"var",
".",
"get",
"(",
"\"salt\"",
",",
"None",
")",
"if",
"vname",
"not",
"in",
"self",
".",
"playbook",
".",
"extra_vars",
":",
"vars",
"[",
"vname",
"]",
"=",
"self",
".",
"playbook",
".",
"callbacks",
".",
"on_vars_prompt",
"(",
"vname",
",",
"private",
",",
"prompt",
",",
"encrypt",
",",
"confirm",
",",
"salt_size",
",",
"salt",
",",
"default",
")",
"elif",
"type",
"(",
"self",
".",
"vars_prompt",
")",
"==",
"dict",
":",
"for",
"(",
"vname",
",",
"prompt",
")",
"in",
"self",
".",
"vars_prompt",
".",
"iteritems",
"(",
")",
":",
"prompt_msg",
"=",
"\"%s: \"",
"%",
"prompt",
"if",
"vname",
"not",
"in",
"self",
".",
"playbook",
".",
"extra_vars",
":",
"vars",
"[",
"vname",
"]",
"=",
"self",
".",
"playbook",
".",
"callbacks",
".",
"on_vars_prompt",
"(",
"varname",
"=",
"vname",
",",
"private",
"=",
"False",
",",
"prompt",
"=",
"prompt_msg",
",",
"default",
"=",
"None",
")",
"else",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"'vars_prompt' section is malformed, see docs\"",
")",
"results",
"=",
"self",
".",
"playbook",
".",
"extra_vars",
".",
"copy",
"(",
")",
"results",
".",
"update",
"(",
"vars",
")",
"return",
"results"
] | load the vars section from a play, accounting for all sorts of variable features
including loading from yaml files, prompting, and conditional includes of the first
file found in a list. | [
"load",
"the",
"vars",
"section",
"from",
"a",
"play",
"accounting",
"for",
"all",
"sorts",
"of",
"variable",
"features",
"including",
"loading",
"from",
"yaml",
"files",
"prompting",
"and",
"conditional",
"includes",
"of",
"the",
"first",
"file",
"found",
"in",
"a",
"list",
"."
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/playbook/play.py#L166-L225 |
250,192 | FreshXOpenSource/wallaby-frontend-qt | wallaby/FXUI.py | key_event_to_name | def key_event_to_name(event):
""" Converts a keystroke event into a corresponding key name.
"""
key_code = event.key()
modifiers = event.modifiers()
if modifiers & QtCore.Qt.KeypadModifier:
key = keypad_map.get(key_code)
else:
key = None
if key is None:
key = key_map.get(key_code)
name = ''
if modifiers & QtCore.Qt.ControlModifier:
name += 'Ctrl'
if modifiers & QtCore.Qt.AltModifier:
name += '-Alt' if name else 'Alt'
if modifiers & QtCore.Qt.MetaModifier:
name += '-Meta' if name else 'Meta'
if modifiers & QtCore.Qt.ShiftModifier and ((name != '') or (key is not None and len(key) > 1)):
name += '-Shift' if name else 'Shift'
if key:
if name:
name += '-'
name += key
return name | python | def key_event_to_name(event):
""" Converts a keystroke event into a corresponding key name.
"""
key_code = event.key()
modifiers = event.modifiers()
if modifiers & QtCore.Qt.KeypadModifier:
key = keypad_map.get(key_code)
else:
key = None
if key is None:
key = key_map.get(key_code)
name = ''
if modifiers & QtCore.Qt.ControlModifier:
name += 'Ctrl'
if modifiers & QtCore.Qt.AltModifier:
name += '-Alt' if name else 'Alt'
if modifiers & QtCore.Qt.MetaModifier:
name += '-Meta' if name else 'Meta'
if modifiers & QtCore.Qt.ShiftModifier and ((name != '') or (key is not None and len(key) > 1)):
name += '-Shift' if name else 'Shift'
if key:
if name:
name += '-'
name += key
return name | [
"def",
"key_event_to_name",
"(",
"event",
")",
":",
"key_code",
"=",
"event",
".",
"key",
"(",
")",
"modifiers",
"=",
"event",
".",
"modifiers",
"(",
")",
"if",
"modifiers",
"&",
"QtCore",
".",
"Qt",
".",
"KeypadModifier",
":",
"key",
"=",
"keypad_map",
".",
"get",
"(",
"key_code",
")",
"else",
":",
"key",
"=",
"None",
"if",
"key",
"is",
"None",
":",
"key",
"=",
"key_map",
".",
"get",
"(",
"key_code",
")",
"name",
"=",
"''",
"if",
"modifiers",
"&",
"QtCore",
".",
"Qt",
".",
"ControlModifier",
":",
"name",
"+=",
"'Ctrl'",
"if",
"modifiers",
"&",
"QtCore",
".",
"Qt",
".",
"AltModifier",
":",
"name",
"+=",
"'-Alt'",
"if",
"name",
"else",
"'Alt'",
"if",
"modifiers",
"&",
"QtCore",
".",
"Qt",
".",
"MetaModifier",
":",
"name",
"+=",
"'-Meta'",
"if",
"name",
"else",
"'Meta'",
"if",
"modifiers",
"&",
"QtCore",
".",
"Qt",
".",
"ShiftModifier",
"and",
"(",
"(",
"name",
"!=",
"''",
")",
"or",
"(",
"key",
"is",
"not",
"None",
"and",
"len",
"(",
"key",
")",
">",
"1",
")",
")",
":",
"name",
"+=",
"'-Shift'",
"if",
"name",
"else",
"'Shift'",
"if",
"key",
":",
"if",
"name",
":",
"name",
"+=",
"'-'",
"name",
"+=",
"key",
"return",
"name"
] | Converts a keystroke event into a corresponding key name. | [
"Converts",
"a",
"keystroke",
"event",
"into",
"a",
"corresponding",
"key",
"name",
"."
] | eee70d0ec4ce34827f62a1654e28dbff8a8afb1a | https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/FXUI.py#L253-L282 |
250,193 | KelSolaar/Oncilla | oncilla/libraries/python/pyclbr.py | readmodule | def readmodule(module, path=None):
'''Backwards compatible interface.
Call readmodule_ex() and then only keep Class objects from the
resulting dictionary.'''
res = {}
for key, value in _readmodule(module, path or []).items():
if isinstance(value, Class):
res[key] = value
return res | python | def readmodule(module, path=None):
'''Backwards compatible interface.
Call readmodule_ex() and then only keep Class objects from the
resulting dictionary.'''
res = {}
for key, value in _readmodule(module, path or []).items():
if isinstance(value, Class):
res[key] = value
return res | [
"def",
"readmodule",
"(",
"module",
",",
"path",
"=",
"None",
")",
":",
"res",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"_readmodule",
"(",
"module",
",",
"path",
"or",
"[",
"]",
")",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Class",
")",
":",
"res",
"[",
"key",
"]",
"=",
"value",
"return",
"res"
] | Backwards compatible interface.
Call readmodule_ex() and then only keep Class objects from the
resulting dictionary. | [
"Backwards",
"compatible",
"interface",
"."
] | 2b4db3704cf2c22a09a207681cb041fff555a994 | https://github.com/KelSolaar/Oncilla/blob/2b4db3704cf2c22a09a207681cb041fff555a994/oncilla/libraries/python/pyclbr.py#L97-L107 |
250,194 | ojake/django-tracked-model | tracked_model/serializer.py | _basic_field_data | def _basic_field_data(field, obj):
"""Returns ``obj.field`` data as a dict"""
value = field.value_from_object(obj)
return {Field.TYPE: FieldType.VAL, Field.VALUE: value} | python | def _basic_field_data(field, obj):
"""Returns ``obj.field`` data as a dict"""
value = field.value_from_object(obj)
return {Field.TYPE: FieldType.VAL, Field.VALUE: value} | [
"def",
"_basic_field_data",
"(",
"field",
",",
"obj",
")",
":",
"value",
"=",
"field",
".",
"value_from_object",
"(",
"obj",
")",
"return",
"{",
"Field",
".",
"TYPE",
":",
"FieldType",
".",
"VAL",
",",
"Field",
".",
"VALUE",
":",
"value",
"}"
] | Returns ``obj.field`` data as a dict | [
"Returns",
"obj",
".",
"field",
"data",
"as",
"a",
"dict"
] | 19bc48874dd2e5fb5defedc6b8c5c3915cce1424 | https://github.com/ojake/django-tracked-model/blob/19bc48874dd2e5fb5defedc6b8c5c3915cce1424/tracked_model/serializer.py#L9-L12 |
250,195 | ojake/django-tracked-model | tracked_model/serializer.py | _related_field_data | def _related_field_data(field, obj):
"""Returns relation ``field`` as a dict.
Dict contains related pk info and some meta information
for reconstructing objects.
"""
data = _basic_field_data(field, obj)
relation_info = {
Field.REL_DB_TABLE: field.rel.to._meta.db_table,
Field.REL_APP: field.rel.to._meta.app_label,
Field.REL_MODEL: field.rel.to.__name__
}
data[Field.TYPE] = FieldType.REL
data[Field.REL] = relation_info
return data | python | def _related_field_data(field, obj):
"""Returns relation ``field`` as a dict.
Dict contains related pk info and some meta information
for reconstructing objects.
"""
data = _basic_field_data(field, obj)
relation_info = {
Field.REL_DB_TABLE: field.rel.to._meta.db_table,
Field.REL_APP: field.rel.to._meta.app_label,
Field.REL_MODEL: field.rel.to.__name__
}
data[Field.TYPE] = FieldType.REL
data[Field.REL] = relation_info
return data | [
"def",
"_related_field_data",
"(",
"field",
",",
"obj",
")",
":",
"data",
"=",
"_basic_field_data",
"(",
"field",
",",
"obj",
")",
"relation_info",
"=",
"{",
"Field",
".",
"REL_DB_TABLE",
":",
"field",
".",
"rel",
".",
"to",
".",
"_meta",
".",
"db_table",
",",
"Field",
".",
"REL_APP",
":",
"field",
".",
"rel",
".",
"to",
".",
"_meta",
".",
"app_label",
",",
"Field",
".",
"REL_MODEL",
":",
"field",
".",
"rel",
".",
"to",
".",
"__name__",
"}",
"data",
"[",
"Field",
".",
"TYPE",
"]",
"=",
"FieldType",
".",
"REL",
"data",
"[",
"Field",
".",
"REL",
"]",
"=",
"relation_info",
"return",
"data"
] | Returns relation ``field`` as a dict.
Dict contains related pk info and some meta information
for reconstructing objects. | [
"Returns",
"relation",
"field",
"as",
"a",
"dict",
"."
] | 19bc48874dd2e5fb5defedc6b8c5c3915cce1424 | https://github.com/ojake/django-tracked-model/blob/19bc48874dd2e5fb5defedc6b8c5c3915cce1424/tracked_model/serializer.py#L15-L29 |
250,196 | ojake/django-tracked-model | tracked_model/serializer.py | _m2m_field_data | def _m2m_field_data(field, obj):
"""Returns m2m ``field`` as a dict.
Value is an array of related primary keys and some meta information
for reconstructing objects.
"""
data = _basic_field_data(field, obj)
data[Field.TYPE] = FieldType.M2M
related = field.rel.to
relation_info = {
Field.REL_DB_TABLE: related._meta.db_table,
Field.REL_APP: related._meta.app_label,
Field.REL_MODEL: related.__name__
}
data[Field.REL] = relation_info
value = data[Field.VALUE]
value = [x[0] for x in value.values_list('pk')]
data[Field.VALUE] = value
return data | python | def _m2m_field_data(field, obj):
"""Returns m2m ``field`` as a dict.
Value is an array of related primary keys and some meta information
for reconstructing objects.
"""
data = _basic_field_data(field, obj)
data[Field.TYPE] = FieldType.M2M
related = field.rel.to
relation_info = {
Field.REL_DB_TABLE: related._meta.db_table,
Field.REL_APP: related._meta.app_label,
Field.REL_MODEL: related.__name__
}
data[Field.REL] = relation_info
value = data[Field.VALUE]
value = [x[0] for x in value.values_list('pk')]
data[Field.VALUE] = value
return data | [
"def",
"_m2m_field_data",
"(",
"field",
",",
"obj",
")",
":",
"data",
"=",
"_basic_field_data",
"(",
"field",
",",
"obj",
")",
"data",
"[",
"Field",
".",
"TYPE",
"]",
"=",
"FieldType",
".",
"M2M",
"related",
"=",
"field",
".",
"rel",
".",
"to",
"relation_info",
"=",
"{",
"Field",
".",
"REL_DB_TABLE",
":",
"related",
".",
"_meta",
".",
"db_table",
",",
"Field",
".",
"REL_APP",
":",
"related",
".",
"_meta",
".",
"app_label",
",",
"Field",
".",
"REL_MODEL",
":",
"related",
".",
"__name__",
"}",
"data",
"[",
"Field",
".",
"REL",
"]",
"=",
"relation_info",
"value",
"=",
"data",
"[",
"Field",
".",
"VALUE",
"]",
"value",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"value",
".",
"values_list",
"(",
"'pk'",
")",
"]",
"data",
"[",
"Field",
".",
"VALUE",
"]",
"=",
"value",
"return",
"data"
] | Returns m2m ``field`` as a dict.
Value is an array of related primary keys and some meta information
for reconstructing objects. | [
"Returns",
"m2m",
"field",
"as",
"a",
"dict",
"."
] | 19bc48874dd2e5fb5defedc6b8c5c3915cce1424 | https://github.com/ojake/django-tracked-model/blob/19bc48874dd2e5fb5defedc6b8c5c3915cce1424/tracked_model/serializer.py#L32-L50 |
250,197 | ojake/django-tracked-model | tracked_model/serializer.py | dump_model | def dump_model(obj):
"""Returns ``obj`` as a dict.
Returnded dic has a form of:
{
'field_name': {
'type': `FieldType`,
'value': field value,
# if field is a relation, it also has:
'rel': {
'db_table': model db table,
'app_label': model app label,
'model_name': model name
}
}
}
"""
data = {}
for field in obj._meta.fields:
if isinstance(field, RELATED_FIELDS):
field_data = _related_field_data(field, obj)
else:
field_data = _basic_field_data(field, obj)
data[field.name] = field_data
if obj.pk:
for m2m in obj._meta.many_to_many:
field_data = _m2m_field_data(m2m, obj)
data[m2m.name] = field_data
return data | python | def dump_model(obj):
"""Returns ``obj`` as a dict.
Returnded dic has a form of:
{
'field_name': {
'type': `FieldType`,
'value': field value,
# if field is a relation, it also has:
'rel': {
'db_table': model db table,
'app_label': model app label,
'model_name': model name
}
}
}
"""
data = {}
for field in obj._meta.fields:
if isinstance(field, RELATED_FIELDS):
field_data = _related_field_data(field, obj)
else:
field_data = _basic_field_data(field, obj)
data[field.name] = field_data
if obj.pk:
for m2m in obj._meta.many_to_many:
field_data = _m2m_field_data(m2m, obj)
data[m2m.name] = field_data
return data | [
"def",
"dump_model",
"(",
"obj",
")",
":",
"data",
"=",
"{",
"}",
"for",
"field",
"in",
"obj",
".",
"_meta",
".",
"fields",
":",
"if",
"isinstance",
"(",
"field",
",",
"RELATED_FIELDS",
")",
":",
"field_data",
"=",
"_related_field_data",
"(",
"field",
",",
"obj",
")",
"else",
":",
"field_data",
"=",
"_basic_field_data",
"(",
"field",
",",
"obj",
")",
"data",
"[",
"field",
".",
"name",
"]",
"=",
"field_data",
"if",
"obj",
".",
"pk",
":",
"for",
"m2m",
"in",
"obj",
".",
"_meta",
".",
"many_to_many",
":",
"field_data",
"=",
"_m2m_field_data",
"(",
"m2m",
",",
"obj",
")",
"data",
"[",
"m2m",
".",
"name",
"]",
"=",
"field_data",
"return",
"data"
] | Returns ``obj`` as a dict.
Returnded dic has a form of:
{
'field_name': {
'type': `FieldType`,
'value': field value,
# if field is a relation, it also has:
'rel': {
'db_table': model db table,
'app_label': model app label,
'model_name': model name
}
}
} | [
"Returns",
"obj",
"as",
"a",
"dict",
"."
] | 19bc48874dd2e5fb5defedc6b8c5c3915cce1424 | https://github.com/ojake/django-tracked-model/blob/19bc48874dd2e5fb5defedc6b8c5c3915cce1424/tracked_model/serializer.py#L53-L83 |
250,198 | ojake/django-tracked-model | tracked_model/serializer.py | restore_model | def restore_model(cls, data):
"""Returns instance of ``cls`` with attributed loaded
from ``data`` dict.
"""
obj = cls()
for field in data:
setattr(obj, field, data[field][Field.VALUE])
return obj | python | def restore_model(cls, data):
"""Returns instance of ``cls`` with attributed loaded
from ``data`` dict.
"""
obj = cls()
for field in data:
setattr(obj, field, data[field][Field.VALUE])
return obj | [
"def",
"restore_model",
"(",
"cls",
",",
"data",
")",
":",
"obj",
"=",
"cls",
"(",
")",
"for",
"field",
"in",
"data",
":",
"setattr",
"(",
"obj",
",",
"field",
",",
"data",
"[",
"field",
"]",
"[",
"Field",
".",
"VALUE",
"]",
")",
"return",
"obj"
] | Returns instance of ``cls`` with attributed loaded
from ``data`` dict. | [
"Returns",
"instance",
"of",
"cls",
"with",
"attributed",
"loaded",
"from",
"data",
"dict",
"."
] | 19bc48874dd2e5fb5defedc6b8c5c3915cce1424 | https://github.com/ojake/django-tracked-model/blob/19bc48874dd2e5fb5defedc6b8c5c3915cce1424/tracked_model/serializer.py#L86-L94 |
250,199 | refinery29/chassis | chassis/services/cache.py | retrieve_object | def retrieve_object(cache, template, indexes):
"""Retrieve an object from Redis using a pipeline.
Arguments:
template: a dictionary containg the keys for the object and
template strings for the corresponding redis keys. The template
string uses named string interpolation format. Example:
{
'username': 'user:$(id)s:username',
'email': 'user:$(id)s:email',
'phone': 'user:$(id)s:phone'
}
indexes: a dictionary containing the values to use to cosntruct the
redis keys: Example:
{
'id': 342
}
Returns: a dictionary with the same keys as template, but containing
the values retrieved from redis, if all the values are retrieved.
If any value is missing, returns None. Example:
{
'username': 'bob',
'email': '[email protected]',
'phone': '555-555-5555'
}
"""
keys = []
with cache as redis_connection:
pipe = redis_connection.pipeline()
for (result_key, redis_key_template) in template.items():
keys.append(result_key)
pipe.get(redis_key_template % indexes)
results = pipe.execute()
return None if None in results else dict(zip(keys, results)) | python | def retrieve_object(cache, template, indexes):
"""Retrieve an object from Redis using a pipeline.
Arguments:
template: a dictionary containg the keys for the object and
template strings for the corresponding redis keys. The template
string uses named string interpolation format. Example:
{
'username': 'user:$(id)s:username',
'email': 'user:$(id)s:email',
'phone': 'user:$(id)s:phone'
}
indexes: a dictionary containing the values to use to cosntruct the
redis keys: Example:
{
'id': 342
}
Returns: a dictionary with the same keys as template, but containing
the values retrieved from redis, if all the values are retrieved.
If any value is missing, returns None. Example:
{
'username': 'bob',
'email': '[email protected]',
'phone': '555-555-5555'
}
"""
keys = []
with cache as redis_connection:
pipe = redis_connection.pipeline()
for (result_key, redis_key_template) in template.items():
keys.append(result_key)
pipe.get(redis_key_template % indexes)
results = pipe.execute()
return None if None in results else dict(zip(keys, results)) | [
"def",
"retrieve_object",
"(",
"cache",
",",
"template",
",",
"indexes",
")",
":",
"keys",
"=",
"[",
"]",
"with",
"cache",
"as",
"redis_connection",
":",
"pipe",
"=",
"redis_connection",
".",
"pipeline",
"(",
")",
"for",
"(",
"result_key",
",",
"redis_key_template",
")",
"in",
"template",
".",
"items",
"(",
")",
":",
"keys",
".",
"append",
"(",
"result_key",
")",
"pipe",
".",
"get",
"(",
"redis_key_template",
"%",
"indexes",
")",
"results",
"=",
"pipe",
".",
"execute",
"(",
")",
"return",
"None",
"if",
"None",
"in",
"results",
"else",
"dict",
"(",
"zip",
"(",
"keys",
",",
"results",
")",
")"
] | Retrieve an object from Redis using a pipeline.
Arguments:
template: a dictionary containg the keys for the object and
template strings for the corresponding redis keys. The template
string uses named string interpolation format. Example:
{
'username': 'user:$(id)s:username',
'email': 'user:$(id)s:email',
'phone': 'user:$(id)s:phone'
}
indexes: a dictionary containing the values to use to cosntruct the
redis keys: Example:
{
'id': 342
}
Returns: a dictionary with the same keys as template, but containing
the values retrieved from redis, if all the values are retrieved.
If any value is missing, returns None. Example:
{
'username': 'bob',
'email': '[email protected]',
'phone': '555-555-5555'
} | [
"Retrieve",
"an",
"object",
"from",
"Redis",
"using",
"a",
"pipeline",
"."
] | 1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192 | https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/cache.py#L43-L82 |
Subsets and Splits