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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Opentrons/opentrons | api/src/opentrons/hardware_control/types.py | Axis.gantry_axes | def gantry_axes(cls) -> Tuple['Axis', 'Axis', 'Axis', 'Axis']:
""" The axes which are tied to the gantry and require the deck
calibration transform
"""
return (cls.X, cls.Y, cls.Z, cls.A) | python | def gantry_axes(cls) -> Tuple['Axis', 'Axis', 'Axis', 'Axis']:
""" The axes which are tied to the gantry and require the deck
calibration transform
"""
return (cls.X, cls.Y, cls.Z, cls.A) | [
"def",
"gantry_axes",
"(",
"cls",
")",
"->",
"Tuple",
"[",
"'Axis'",
",",
"'Axis'",
",",
"'Axis'",
",",
"'Axis'",
"]",
":",
"return",
"(",
"cls",
".",
"X",
",",
"cls",
".",
"Y",
",",
"cls",
".",
"Z",
",",
"cls",
".",
"A",
")"
] | The axes which are tied to the gantry and require the deck
calibration transform | [
"The",
"axes",
"which",
"are",
"tied",
"to",
"the",
"gantry",
"and",
"require",
"the",
"deck",
"calibration",
"transform"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/types.py#L22-L26 | train | 198,200 |
Opentrons/opentrons | api/src/opentrons/util/calibration_functions.py | update_instrument_config | def update_instrument_config(
instrument, measured_center) -> Tuple[Point, float]:
"""
Update config and pose tree with instrument's x and y offsets
and tip length based on delta between probe center and measured_center,
persist updated config and return it
"""
from copy import deepcopy
from opentrons.trackers.pose_tracker import update
robot = instrument.robot
config = robot.config
instrument_offset = deepcopy(config.instrument_offset)
dx, dy, dz = array(measured_center) - config.tip_probe.center
log.debug("This is measured probe center dx {}".format(Point(dx, dy, dz)))
# any Z offset will adjust the tip length, so instruments have Z=0 offset
old_x, old_y, _ = instrument_offset[instrument.mount][instrument.type]
instrument_offset[instrument.mount][instrument.type] = \
(old_x - dx, old_y - dy, 0.0)
tip_length = deepcopy(config.tip_length)
tip_length[instrument.name] = tip_length[instrument.name] + dz
config = config \
._replace(instrument_offset=instrument_offset) \
._replace(tip_length=tip_length)
robot.config = config
log.debug("Updating config for {} instrument".format(instrument.mount))
robot_configs.save_robot_settings(config)
new_coordinates = change_base(
robot.poses,
src=instrument,
dst=instrument.instrument_mover) - Point(dx, dy, 0.0)
robot.poses = update(robot.poses, instrument, new_coordinates)
return robot.config | python | def update_instrument_config(
instrument, measured_center) -> Tuple[Point, float]:
"""
Update config and pose tree with instrument's x and y offsets
and tip length based on delta between probe center and measured_center,
persist updated config and return it
"""
from copy import deepcopy
from opentrons.trackers.pose_tracker import update
robot = instrument.robot
config = robot.config
instrument_offset = deepcopy(config.instrument_offset)
dx, dy, dz = array(measured_center) - config.tip_probe.center
log.debug("This is measured probe center dx {}".format(Point(dx, dy, dz)))
# any Z offset will adjust the tip length, so instruments have Z=0 offset
old_x, old_y, _ = instrument_offset[instrument.mount][instrument.type]
instrument_offset[instrument.mount][instrument.type] = \
(old_x - dx, old_y - dy, 0.0)
tip_length = deepcopy(config.tip_length)
tip_length[instrument.name] = tip_length[instrument.name] + dz
config = config \
._replace(instrument_offset=instrument_offset) \
._replace(tip_length=tip_length)
robot.config = config
log.debug("Updating config for {} instrument".format(instrument.mount))
robot_configs.save_robot_settings(config)
new_coordinates = change_base(
robot.poses,
src=instrument,
dst=instrument.instrument_mover) - Point(dx, dy, 0.0)
robot.poses = update(robot.poses, instrument, new_coordinates)
return robot.config | [
"def",
"update_instrument_config",
"(",
"instrument",
",",
"measured_center",
")",
"->",
"Tuple",
"[",
"Point",
",",
"float",
"]",
":",
"from",
"copy",
"import",
"deepcopy",
"from",
"opentrons",
".",
"trackers",
".",
"pose_tracker",
"import",
"update",
"robot",
... | Update config and pose tree with instrument's x and y offsets
and tip length based on delta between probe center and measured_center,
persist updated config and return it | [
"Update",
"config",
"and",
"pose",
"tree",
"with",
"instrument",
"s",
"x",
"and",
"y",
"offsets",
"and",
"tip",
"length",
"based",
"on",
"delta",
"between",
"probe",
"center",
"and",
"measured_center",
"persist",
"updated",
"config",
"and",
"return",
"it"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/util/calibration_functions.py#L88-L125 | train | 198,201 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0.read_pipette_id | def read_pipette_id(self, mount) -> Optional[str]:
'''
Reads in an attached pipette's ID
The ID is unique to this pipette, and is a string of unknown length
:param mount: string with value 'left' or 'right'
:return id string, or None
'''
res: Optional[str] = None
if self.simulating:
res = '1234567890'
else:
try:
res = self._read_from_pipette(
GCODES['READ_INSTRUMENT_ID'], mount)
except UnicodeDecodeError:
log.exception("Failed to decode pipette ID string:")
res = None
return res | python | def read_pipette_id(self, mount) -> Optional[str]:
'''
Reads in an attached pipette's ID
The ID is unique to this pipette, and is a string of unknown length
:param mount: string with value 'left' or 'right'
:return id string, or None
'''
res: Optional[str] = None
if self.simulating:
res = '1234567890'
else:
try:
res = self._read_from_pipette(
GCODES['READ_INSTRUMENT_ID'], mount)
except UnicodeDecodeError:
log.exception("Failed to decode pipette ID string:")
res = None
return res | [
"def",
"read_pipette_id",
"(",
"self",
",",
"mount",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"res",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
"if",
"self",
".",
"simulating",
":",
"res",
"=",
"'1234567890'",
"else",
":",
"try",
":",
"res",
... | Reads in an attached pipette's ID
The ID is unique to this pipette, and is a string of unknown length
:param mount: string with value 'left' or 'right'
:return id string, or None | [
"Reads",
"in",
"an",
"attached",
"pipette",
"s",
"ID",
"The",
"ID",
"is",
"unique",
"to",
"this",
"pipette",
"and",
"is",
"a",
"string",
"of",
"unknown",
"length"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L358-L376 | train | 198,202 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0.read_pipette_model | def read_pipette_model(self, mount) -> Optional[str]:
'''
Reads an attached pipette's MODEL
The MODEL is a unique string for this model of pipette
:param mount: string with value 'left' or 'right'
:return model string, or None
'''
if self.simulating:
res = None
else:
res = self._read_from_pipette(
GCODES['READ_INSTRUMENT_MODEL'], mount)
if res and '_v' not in res:
# Backward compatibility for pipettes programmed with model
# strings that did not include the _v# designation
res = res + '_v1'
elif res and '_v13' in res:
# Backward compatibility for pipettes programmed with model
# strings that did not include the "." to seperate version
# major and minor values
res = res.replace('_v13', '_v1.3')
return res | python | def read_pipette_model(self, mount) -> Optional[str]:
'''
Reads an attached pipette's MODEL
The MODEL is a unique string for this model of pipette
:param mount: string with value 'left' or 'right'
:return model string, or None
'''
if self.simulating:
res = None
else:
res = self._read_from_pipette(
GCODES['READ_INSTRUMENT_MODEL'], mount)
if res and '_v' not in res:
# Backward compatibility for pipettes programmed with model
# strings that did not include the _v# designation
res = res + '_v1'
elif res and '_v13' in res:
# Backward compatibility for pipettes programmed with model
# strings that did not include the "." to seperate version
# major and minor values
res = res.replace('_v13', '_v1.3')
return res | [
"def",
"read_pipette_model",
"(",
"self",
",",
"mount",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"self",
".",
"simulating",
":",
"res",
"=",
"None",
"else",
":",
"res",
"=",
"self",
".",
"_read_from_pipette",
"(",
"GCODES",
"[",
"'READ_INSTRUME... | Reads an attached pipette's MODEL
The MODEL is a unique string for this model of pipette
:param mount: string with value 'left' or 'right'
:return model string, or None | [
"Reads",
"an",
"attached",
"pipette",
"s",
"MODEL",
"The",
"MODEL",
"is",
"a",
"unique",
"string",
"for",
"this",
"model",
"of",
"pipette"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L378-L401 | train | 198,203 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0.get_fw_version | def get_fw_version(self):
'''
Queries Smoothieware for it's build version, and returns
the parsed response.
returns: str
Current version of attached Smoothi-driver. Versions are derived
from git branch-hash (eg: edge-66ec883NOMSD)
Example Smoothieware response:
Build version: edge-66ec883NOMSD, Build date: Jan 28 2018 15:26:57, MCU: LPC1769, System Clock: 120MHz # NOQA
CNC Build NOMSD Build
6 axis
'''
version = 'Virtual Smoothie'
if not self.simulating:
version = self._send_command('version')
version = version.split(',')[0].split(':')[-1].strip()
version = version.replace('NOMSD', '')
return version | python | def get_fw_version(self):
'''
Queries Smoothieware for it's build version, and returns
the parsed response.
returns: str
Current version of attached Smoothi-driver. Versions are derived
from git branch-hash (eg: edge-66ec883NOMSD)
Example Smoothieware response:
Build version: edge-66ec883NOMSD, Build date: Jan 28 2018 15:26:57, MCU: LPC1769, System Clock: 120MHz # NOQA
CNC Build NOMSD Build
6 axis
'''
version = 'Virtual Smoothie'
if not self.simulating:
version = self._send_command('version')
version = version.split(',')[0].split(':')[-1].strip()
version = version.replace('NOMSD', '')
return version | [
"def",
"get_fw_version",
"(",
"self",
")",
":",
"version",
"=",
"'Virtual Smoothie'",
"if",
"not",
"self",
".",
"simulating",
":",
"version",
"=",
"self",
".",
"_send_command",
"(",
"'version'",
")",
"version",
"=",
"version",
".",
"split",
"(",
"','",
")"... | Queries Smoothieware for it's build version, and returns
the parsed response.
returns: str
Current version of attached Smoothi-driver. Versions are derived
from git branch-hash (eg: edge-66ec883NOMSD)
Example Smoothieware response:
Build version: edge-66ec883NOMSD, Build date: Jan 28 2018 15:26:57, MCU: LPC1769, System Clock: 120MHz # NOQA
CNC Build NOMSD Build
6 axis | [
"Queries",
"Smoothieware",
"for",
"it",
"s",
"build",
"version",
"and",
"returns",
"the",
"parsed",
"response",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L478-L498 | train | 198,204 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0.position | def position(self):
"""
Instead of sending M114.2 we are storing target values in
self._position since movement and home commands are blocking and
assumed to go the correct place.
Cases where Smoothie would not be in the correct place (such as if a
belt slips) would not be corrected by getting position with M114.2
because Smoothie would also not be aware of slippage.
"""
return {k.upper(): v for k, v in self._position.items()} | python | def position(self):
"""
Instead of sending M114.2 we are storing target values in
self._position since movement and home commands are blocking and
assumed to go the correct place.
Cases where Smoothie would not be in the correct place (such as if a
belt slips) would not be corrected by getting position with M114.2
because Smoothie would also not be aware of slippage.
"""
return {k.upper(): v for k, v in self._position.items()} | [
"def",
"position",
"(",
"self",
")",
":",
"return",
"{",
"k",
".",
"upper",
"(",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_position",
".",
"items",
"(",
")",
"}"
] | Instead of sending M114.2 we are storing target values in
self._position since movement and home commands are blocking and
assumed to go the correct place.
Cases where Smoothie would not be in the correct place (such as if a
belt slips) would not be corrected by getting position with M114.2
because Smoothie would also not be aware of slippage. | [
"Instead",
"of",
"sending",
"M114",
".",
"2",
"we",
"are",
"storing",
"target",
"values",
"in",
"self",
".",
"_position",
"since",
"movement",
"and",
"home",
"commands",
"are",
"blocking",
"and",
"assumed",
"to",
"go",
"the",
"correct",
"place",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L501-L511 | train | 198,205 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0.set_active_current | def set_active_current(self, settings):
'''
Sets the amperage of each motor for when it is activated by driver.
Values are initialized from the `robot_config.high_current` values,
and can then be changed through this method by other parts of the API.
For example, `Pipette` setting the active-current of it's pipette,
depending on what model pipette it is, and what action it is performing
settings
Dict with axes as valies (e.g.: 'X', 'Y', 'Z', 'A', 'B', or 'C')
and floating point number for current (generally between 0.1 and 2)
'''
self._active_current_settings['now'].update(settings)
# if an axis specified in the `settings` is currently active,
# reset it's current to the new active-current value
active_axes_to_update = {
axis: amperage
for axis, amperage in self._active_current_settings['now'].items()
if self._active_axes.get(axis) is True
if self.current[axis] != amperage
}
if active_axes_to_update:
self._save_current(active_axes_to_update, axes_active=True) | python | def set_active_current(self, settings):
'''
Sets the amperage of each motor for when it is activated by driver.
Values are initialized from the `robot_config.high_current` values,
and can then be changed through this method by other parts of the API.
For example, `Pipette` setting the active-current of it's pipette,
depending on what model pipette it is, and what action it is performing
settings
Dict with axes as valies (e.g.: 'X', 'Y', 'Z', 'A', 'B', or 'C')
and floating point number for current (generally between 0.1 and 2)
'''
self._active_current_settings['now'].update(settings)
# if an axis specified in the `settings` is currently active,
# reset it's current to the new active-current value
active_axes_to_update = {
axis: amperage
for axis, amperage in self._active_current_settings['now'].items()
if self._active_axes.get(axis) is True
if self.current[axis] != amperage
}
if active_axes_to_update:
self._save_current(active_axes_to_update, axes_active=True) | [
"def",
"set_active_current",
"(",
"self",
",",
"settings",
")",
":",
"self",
".",
"_active_current_settings",
"[",
"'now'",
"]",
".",
"update",
"(",
"settings",
")",
"# if an axis specified in the `settings` is currently active,",
"# reset it's current to the new active-curre... | Sets the amperage of each motor for when it is activated by driver.
Values are initialized from the `robot_config.high_current` values,
and can then be changed through this method by other parts of the API.
For example, `Pipette` setting the active-current of it's pipette,
depending on what model pipette it is, and what action it is performing
settings
Dict with axes as valies (e.g.: 'X', 'Y', 'Z', 'A', 'B', or 'C')
and floating point number for current (generally between 0.1 and 2) | [
"Sets",
"the",
"amperage",
"of",
"each",
"motor",
"for",
"when",
"it",
"is",
"activated",
"by",
"driver",
".",
"Values",
"are",
"initialized",
"from",
"the",
"robot_config",
".",
"high_current",
"values",
"and",
"can",
"then",
"be",
"changed",
"through",
"th... | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L630-L654 | train | 198,206 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0.set_dwelling_current | def set_dwelling_current(self, settings):
'''
Sets the amperage of each motor for when it is dwelling.
Values are initialized from the `robot_config.log_current` values,
and can then be changed through this method by other parts of the API.
For example, `Pipette` setting the dwelling-current of it's pipette,
depending on what model pipette it is.
settings
Dict with axes as valies (e.g.: 'X', 'Y', 'Z', 'A', 'B', or 'C')
and floating point number for current (generally between 0.1 and 2)
'''
self._dwelling_current_settings['now'].update(settings)
# if an axis specified in the `settings` is currently dwelling,
# reset it's current to the new dwelling-current value
dwelling_axes_to_update = {
axis: amps
for axis, amps in self._dwelling_current_settings['now'].items()
if self._active_axes.get(axis) is False
if self.current[axis] != amps
}
if dwelling_axes_to_update:
self._save_current(dwelling_axes_to_update, axes_active=False) | python | def set_dwelling_current(self, settings):
'''
Sets the amperage of each motor for when it is dwelling.
Values are initialized from the `robot_config.log_current` values,
and can then be changed through this method by other parts of the API.
For example, `Pipette` setting the dwelling-current of it's pipette,
depending on what model pipette it is.
settings
Dict with axes as valies (e.g.: 'X', 'Y', 'Z', 'A', 'B', or 'C')
and floating point number for current (generally between 0.1 and 2)
'''
self._dwelling_current_settings['now'].update(settings)
# if an axis specified in the `settings` is currently dwelling,
# reset it's current to the new dwelling-current value
dwelling_axes_to_update = {
axis: amps
for axis, amps in self._dwelling_current_settings['now'].items()
if self._active_axes.get(axis) is False
if self.current[axis] != amps
}
if dwelling_axes_to_update:
self._save_current(dwelling_axes_to_update, axes_active=False) | [
"def",
"set_dwelling_current",
"(",
"self",
",",
"settings",
")",
":",
"self",
".",
"_dwelling_current_settings",
"[",
"'now'",
"]",
".",
"update",
"(",
"settings",
")",
"# if an axis specified in the `settings` is currently dwelling,",
"# reset it's current to the new dwelli... | Sets the amperage of each motor for when it is dwelling.
Values are initialized from the `robot_config.log_current` values,
and can then be changed through this method by other parts of the API.
For example, `Pipette` setting the dwelling-current of it's pipette,
depending on what model pipette it is.
settings
Dict with axes as valies (e.g.: 'X', 'Y', 'Z', 'A', 'B', or 'C')
and floating point number for current (generally between 0.1 and 2) | [
"Sets",
"the",
"amperage",
"of",
"each",
"motor",
"for",
"when",
"it",
"is",
"dwelling",
".",
"Values",
"are",
"initialized",
"from",
"the",
"robot_config",
".",
"log_current",
"values",
"and",
"can",
"then",
"be",
"changed",
"through",
"this",
"method",
"by... | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L663-L687 | train | 198,207 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0._generate_current_command | def _generate_current_command(self):
'''
Returns a constructed GCode string that contains this driver's
axis-current settings, plus a small delay to wait for those settings
to take effect.
'''
values = ['{}{}'.format(axis, value)
for axis, value in sorted(self.current.items())]
current_cmd = '{} {}'.format(
GCODES['SET_CURRENT'],
' '.join(values)
)
command = '{currents} {code}P{seconds}'.format(
currents=current_cmd,
code=GCODES['DWELL'],
seconds=CURRENT_CHANGE_DELAY
)
log.debug("_generate_current_command: {}".format(command))
return command | python | def _generate_current_command(self):
'''
Returns a constructed GCode string that contains this driver's
axis-current settings, plus a small delay to wait for those settings
to take effect.
'''
values = ['{}{}'.format(axis, value)
for axis, value in sorted(self.current.items())]
current_cmd = '{} {}'.format(
GCODES['SET_CURRENT'],
' '.join(values)
)
command = '{currents} {code}P{seconds}'.format(
currents=current_cmd,
code=GCODES['DWELL'],
seconds=CURRENT_CHANGE_DELAY
)
log.debug("_generate_current_command: {}".format(command))
return command | [
"def",
"_generate_current_command",
"(",
"self",
")",
":",
"values",
"=",
"[",
"'{}{}'",
".",
"format",
"(",
"axis",
",",
"value",
")",
"for",
"axis",
",",
"value",
"in",
"sorted",
"(",
"self",
".",
"current",
".",
"items",
"(",
")",
")",
"]",
"curre... | Returns a constructed GCode string that contains this driver's
axis-current settings, plus a small delay to wait for those settings
to take effect. | [
"Returns",
"a",
"constructed",
"GCode",
"string",
"that",
"contains",
"this",
"driver",
"s",
"axis",
"-",
"current",
"settings",
"plus",
"a",
"small",
"delay",
"to",
"wait",
"for",
"those",
"settings",
"to",
"take",
"effect",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L724-L742 | train | 198,208 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0.disengage_axis | def disengage_axis(self, axes):
'''
Disable the stepper-motor-driver's 36v output to motor
This is a safe GCODE to send to Smoothieware, as it will automatically
re-engage the motor if it receives a home or move command
axes
String containing the axes to be disengaged
(e.g.: 'XY' or 'ZA' or 'XYZABC')
'''
axes = ''.join(set(axes.upper()) & set(AXES))
if axes:
log.debug("disengage_axis: {}".format(axes))
self._send_command(GCODES['DISENGAGE_MOTOR'] + axes)
for axis in axes:
self.engaged_axes[axis] = False | python | def disengage_axis(self, axes):
'''
Disable the stepper-motor-driver's 36v output to motor
This is a safe GCODE to send to Smoothieware, as it will automatically
re-engage the motor if it receives a home or move command
axes
String containing the axes to be disengaged
(e.g.: 'XY' or 'ZA' or 'XYZABC')
'''
axes = ''.join(set(axes.upper()) & set(AXES))
if axes:
log.debug("disengage_axis: {}".format(axes))
self._send_command(GCODES['DISENGAGE_MOTOR'] + axes)
for axis in axes:
self.engaged_axes[axis] = False | [
"def",
"disengage_axis",
"(",
"self",
",",
"axes",
")",
":",
"axes",
"=",
"''",
".",
"join",
"(",
"set",
"(",
"axes",
".",
"upper",
"(",
")",
")",
"&",
"set",
"(",
"AXES",
")",
")",
"if",
"axes",
":",
"log",
".",
"debug",
"(",
"\"disengage_axis: ... | Disable the stepper-motor-driver's 36v output to motor
This is a safe GCODE to send to Smoothieware, as it will automatically
re-engage the motor if it receives a home or move command
axes
String containing the axes to be disengaged
(e.g.: 'XY' or 'ZA' or 'XYZABC') | [
"Disable",
"the",
"stepper",
"-",
"motor",
"-",
"driver",
"s",
"36v",
"output",
"to",
"motor",
"This",
"is",
"a",
"safe",
"GCODE",
"to",
"send",
"to",
"Smoothieware",
"as",
"it",
"will",
"automatically",
"re",
"-",
"engage",
"the",
"motor",
"if",
"it",
... | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L744-L759 | train | 198,209 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0.dwell_axes | def dwell_axes(self, axes):
'''
Sets motors to low current, for when they are not moving.
Dwell for XYZA axes is only called after HOMING
Dwell for BC axes is called after both HOMING and MOVING
axes:
String containing the axes to set to low current (eg: 'XYZABC')
'''
axes = ''.join(set(axes) & set(AXES) - set(DISABLE_AXES))
dwelling_currents = {
ax: self._dwelling_current_settings['now'][ax]
for ax in axes
if self._active_axes[ax] is True
}
if dwelling_currents:
self._save_current(dwelling_currents, axes_active=False) | python | def dwell_axes(self, axes):
'''
Sets motors to low current, for when they are not moving.
Dwell for XYZA axes is only called after HOMING
Dwell for BC axes is called after both HOMING and MOVING
axes:
String containing the axes to set to low current (eg: 'XYZABC')
'''
axes = ''.join(set(axes) & set(AXES) - set(DISABLE_AXES))
dwelling_currents = {
ax: self._dwelling_current_settings['now'][ax]
for ax in axes
if self._active_axes[ax] is True
}
if dwelling_currents:
self._save_current(dwelling_currents, axes_active=False) | [
"def",
"dwell_axes",
"(",
"self",
",",
"axes",
")",
":",
"axes",
"=",
"''",
".",
"join",
"(",
"set",
"(",
"axes",
")",
"&",
"set",
"(",
"AXES",
")",
"-",
"set",
"(",
"DISABLE_AXES",
")",
")",
"dwelling_currents",
"=",
"{",
"ax",
":",
"self",
".",... | Sets motors to low current, for when they are not moving.
Dwell for XYZA axes is only called after HOMING
Dwell for BC axes is called after both HOMING and MOVING
axes:
String containing the axes to set to low current (eg: 'XYZABC') | [
"Sets",
"motors",
"to",
"low",
"current",
"for",
"when",
"they",
"are",
"not",
"moving",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L761-L778 | train | 198,210 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0._read_from_pipette | def _read_from_pipette(self, gcode, mount) -> Optional[str]:
'''
Read from an attached pipette's internal memory. The gcode used
determines which portion of memory is read and returned.
All motors must be disengaged to consistently read over I2C lines
gcode:
String (str) containing a GCode
either 'READ_INSTRUMENT_ID' or 'READ_INSTRUMENT_MODEL'
mount:
String (str) with value 'left' or 'right'
'''
allowed_mounts = {'left': 'L', 'right': 'R'}
mount = allowed_mounts.get(mount)
if not mount:
raise ValueError('Unexpected mount: {}'.format(mount))
try:
# EMI interference from both plunger motors has been found to
# prevent the I2C lines from communicating between Smoothieware and
# pipette's onboard EEPROM. To avoid, turn off both plunger motors
self.disengage_axis('BC')
self.delay(CURRENT_CHANGE_DELAY)
# request from Smoothieware the information from that pipette
res = self._send_command(gcode + mount)
if res:
res = _parse_instrument_data(res)
assert mount in res
# data is read/written as strings of HEX characters
# to avoid firmware weirdness in how it parses GCode arguments
return _byte_array_to_ascii_string(res[mount])
except (ParseError, AssertionError, SmoothieError):
pass
return None | python | def _read_from_pipette(self, gcode, mount) -> Optional[str]:
'''
Read from an attached pipette's internal memory. The gcode used
determines which portion of memory is read and returned.
All motors must be disengaged to consistently read over I2C lines
gcode:
String (str) containing a GCode
either 'READ_INSTRUMENT_ID' or 'READ_INSTRUMENT_MODEL'
mount:
String (str) with value 'left' or 'right'
'''
allowed_mounts = {'left': 'L', 'right': 'R'}
mount = allowed_mounts.get(mount)
if not mount:
raise ValueError('Unexpected mount: {}'.format(mount))
try:
# EMI interference from both plunger motors has been found to
# prevent the I2C lines from communicating between Smoothieware and
# pipette's onboard EEPROM. To avoid, turn off both plunger motors
self.disengage_axis('BC')
self.delay(CURRENT_CHANGE_DELAY)
# request from Smoothieware the information from that pipette
res = self._send_command(gcode + mount)
if res:
res = _parse_instrument_data(res)
assert mount in res
# data is read/written as strings of HEX characters
# to avoid firmware weirdness in how it parses GCode arguments
return _byte_array_to_ascii_string(res[mount])
except (ParseError, AssertionError, SmoothieError):
pass
return None | [
"def",
"_read_from_pipette",
"(",
"self",
",",
"gcode",
",",
"mount",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"allowed_mounts",
"=",
"{",
"'left'",
":",
"'L'",
",",
"'right'",
":",
"'R'",
"}",
"mount",
"=",
"allowed_mounts",
".",
"get",
"(",
"moun... | Read from an attached pipette's internal memory. The gcode used
determines which portion of memory is read and returned.
All motors must be disengaged to consistently read over I2C lines
gcode:
String (str) containing a GCode
either 'READ_INSTRUMENT_ID' or 'READ_INSTRUMENT_MODEL'
mount:
String (str) with value 'left' or 'right' | [
"Read",
"from",
"an",
"attached",
"pipette",
"s",
"internal",
"memory",
".",
"The",
"gcode",
"used",
"determines",
"which",
"portion",
"of",
"memory",
"is",
"read",
"and",
"returned",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L995-L1028 | train | 198,211 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0._write_to_pipette | def _write_to_pipette(self, gcode, mount, data_string):
'''
Write to an attached pipette's internal memory. The gcode used
determines which portion of memory is written to.
NOTE: To enable write-access to the pipette, it's button must be held
gcode:
String (str) containing a GCode
either 'WRITE_INSTRUMENT_ID' or 'WRITE_INSTRUMENT_MODEL'
mount:
String (str) with value 'left' or 'right'
data_string:
String (str) that is of unkown length
'''
allowed_mounts = {'left': 'L', 'right': 'R'}
mount = allowed_mounts.get(mount)
if not mount:
raise ValueError('Unexpected mount: {}'.format(mount))
if not isinstance(data_string, str):
raise ValueError(
'Expected {0}, not {1}'.format(str, type(data_string)))
# EMI interference from both plunger motors has been found to
# prevent the I2C lines from communicating between Smoothieware and
# pipette's onboard EEPROM. To avoid, turn off both plunger motors
self.disengage_axis('BC')
self.delay(CURRENT_CHANGE_DELAY)
# data is read/written as strings of HEX characters
# to avoid firmware weirdness in how it parses GCode arguments
byte_string = _byte_array_to_hex_string(
bytearray(data_string.encode()))
command = gcode + mount + byte_string
log.debug("_write_to_pipette: {}".format(command))
self._send_command(command) | python | def _write_to_pipette(self, gcode, mount, data_string):
'''
Write to an attached pipette's internal memory. The gcode used
determines which portion of memory is written to.
NOTE: To enable write-access to the pipette, it's button must be held
gcode:
String (str) containing a GCode
either 'WRITE_INSTRUMENT_ID' or 'WRITE_INSTRUMENT_MODEL'
mount:
String (str) with value 'left' or 'right'
data_string:
String (str) that is of unkown length
'''
allowed_mounts = {'left': 'L', 'right': 'R'}
mount = allowed_mounts.get(mount)
if not mount:
raise ValueError('Unexpected mount: {}'.format(mount))
if not isinstance(data_string, str):
raise ValueError(
'Expected {0}, not {1}'.format(str, type(data_string)))
# EMI interference from both plunger motors has been found to
# prevent the I2C lines from communicating between Smoothieware and
# pipette's onboard EEPROM. To avoid, turn off both plunger motors
self.disengage_axis('BC')
self.delay(CURRENT_CHANGE_DELAY)
# data is read/written as strings of HEX characters
# to avoid firmware weirdness in how it parses GCode arguments
byte_string = _byte_array_to_hex_string(
bytearray(data_string.encode()))
command = gcode + mount + byte_string
log.debug("_write_to_pipette: {}".format(command))
self._send_command(command) | [
"def",
"_write_to_pipette",
"(",
"self",
",",
"gcode",
",",
"mount",
",",
"data_string",
")",
":",
"allowed_mounts",
"=",
"{",
"'left'",
":",
"'L'",
",",
"'right'",
":",
"'R'",
"}",
"mount",
"=",
"allowed_mounts",
".",
"get",
"(",
"mount",
")",
"if",
"... | Write to an attached pipette's internal memory. The gcode used
determines which portion of memory is written to.
NOTE: To enable write-access to the pipette, it's button must be held
gcode:
String (str) containing a GCode
either 'WRITE_INSTRUMENT_ID' or 'WRITE_INSTRUMENT_MODEL'
mount:
String (str) with value 'left' or 'right'
data_string:
String (str) that is of unkown length | [
"Write",
"to",
"an",
"attached",
"pipette",
"s",
"internal",
"memory",
".",
"The",
"gcode",
"used",
"determines",
"which",
"portion",
"of",
"memory",
"is",
"written",
"to",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L1030-L1063 | train | 198,212 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0.move | def move(self, target, home_flagged_axes=False):
'''
Move to the `target` Smoothieware coordinate, along any of the size
axes, XYZABC.
target: dict
dict setting the coordinate that Smoothieware will be at when
`move()` returns. `target` keys are the axis in upper-case, and the
values are the coordinate in millimeters (float)
home_flagged_axes: boolean (default=False)
If set to `True`, each axis included within the target coordinate
may be homed before moving, determined by Smoothieware's internal
homing-status flags (`True` means it has already homed). All axes'
flags are set to `False` by Smoothieware under three conditions:
1) Smoothieware boots or resets, 2) if a HALT gcode or signal
is sent, or 3) a homing/limitswitch error occured.
'''
from numpy import isclose
self.run_flag.wait()
def valid_movement(coords, axis):
return not (
(axis in DISABLE_AXES) or
(coords is None) or
isclose(coords, self.position[axis])
)
def create_coords_list(coords_dict):
return [
axis + str(round(coords, GCODE_ROUNDING_PRECISION))
for axis, coords in sorted(coords_dict.items())
if valid_movement(coords, axis)
]
backlash_target = target.copy()
backlash_target.update({
axis: value + PLUNGER_BACKLASH_MM
for axis, value in sorted(target.items())
if axis in 'BC' and self.position[axis] < value
})
target_coords = create_coords_list(target)
backlash_coords = create_coords_list(backlash_target)
if target_coords:
non_moving_axes = ''.join([
ax
for ax in AXES
if ax not in target.keys()
])
self.dwell_axes(non_moving_axes)
self.activate_axes(target.keys())
# include the current-setting gcodes within the moving gcode string
# to reduce latency, since we're setting current so much
command = self._generate_current_command()
if backlash_coords != target_coords:
command += ' ' + GCODES['MOVE'] + ''.join(backlash_coords)
command += ' ' + GCODES['MOVE'] + ''.join(target_coords)
try:
for axis in target.keys():
self.engaged_axes[axis] = True
if home_flagged_axes:
self.home_flagged_axes(''.join(list(target.keys())))
log.debug("move: {}".format(command))
# TODO (andy) a movement's timeout should be calculated by
# how long the movement is expected to take. A default timeout
# of 30 seconds prevents any movements that take longer
self._send_command(command, timeout=DEFAULT_MOVEMENT_TIMEOUT)
finally:
# dwell pipette motors because they get hot
plunger_axis_moved = ''.join(set('BC') & set(target.keys()))
if plunger_axis_moved:
self.dwell_axes(plunger_axis_moved)
self._set_saved_current()
self._update_position(target) | python | def move(self, target, home_flagged_axes=False):
'''
Move to the `target` Smoothieware coordinate, along any of the size
axes, XYZABC.
target: dict
dict setting the coordinate that Smoothieware will be at when
`move()` returns. `target` keys are the axis in upper-case, and the
values are the coordinate in millimeters (float)
home_flagged_axes: boolean (default=False)
If set to `True`, each axis included within the target coordinate
may be homed before moving, determined by Smoothieware's internal
homing-status flags (`True` means it has already homed). All axes'
flags are set to `False` by Smoothieware under three conditions:
1) Smoothieware boots or resets, 2) if a HALT gcode or signal
is sent, or 3) a homing/limitswitch error occured.
'''
from numpy import isclose
self.run_flag.wait()
def valid_movement(coords, axis):
return not (
(axis in DISABLE_AXES) or
(coords is None) or
isclose(coords, self.position[axis])
)
def create_coords_list(coords_dict):
return [
axis + str(round(coords, GCODE_ROUNDING_PRECISION))
for axis, coords in sorted(coords_dict.items())
if valid_movement(coords, axis)
]
backlash_target = target.copy()
backlash_target.update({
axis: value + PLUNGER_BACKLASH_MM
for axis, value in sorted(target.items())
if axis in 'BC' and self.position[axis] < value
})
target_coords = create_coords_list(target)
backlash_coords = create_coords_list(backlash_target)
if target_coords:
non_moving_axes = ''.join([
ax
for ax in AXES
if ax not in target.keys()
])
self.dwell_axes(non_moving_axes)
self.activate_axes(target.keys())
# include the current-setting gcodes within the moving gcode string
# to reduce latency, since we're setting current so much
command = self._generate_current_command()
if backlash_coords != target_coords:
command += ' ' + GCODES['MOVE'] + ''.join(backlash_coords)
command += ' ' + GCODES['MOVE'] + ''.join(target_coords)
try:
for axis in target.keys():
self.engaged_axes[axis] = True
if home_flagged_axes:
self.home_flagged_axes(''.join(list(target.keys())))
log.debug("move: {}".format(command))
# TODO (andy) a movement's timeout should be calculated by
# how long the movement is expected to take. A default timeout
# of 30 seconds prevents any movements that take longer
self._send_command(command, timeout=DEFAULT_MOVEMENT_TIMEOUT)
finally:
# dwell pipette motors because they get hot
plunger_axis_moved = ''.join(set('BC') & set(target.keys()))
if plunger_axis_moved:
self.dwell_axes(plunger_axis_moved)
self._set_saved_current()
self._update_position(target) | [
"def",
"move",
"(",
"self",
",",
"target",
",",
"home_flagged_axes",
"=",
"False",
")",
":",
"from",
"numpy",
"import",
"isclose",
"self",
".",
"run_flag",
".",
"wait",
"(",
")",
"def",
"valid_movement",
"(",
"coords",
",",
"axis",
")",
":",
"return",
... | Move to the `target` Smoothieware coordinate, along any of the size
axes, XYZABC.
target: dict
dict setting the coordinate that Smoothieware will be at when
`move()` returns. `target` keys are the axis in upper-case, and the
values are the coordinate in millimeters (float)
home_flagged_axes: boolean (default=False)
If set to `True`, each axis included within the target coordinate
may be homed before moving, determined by Smoothieware's internal
homing-status flags (`True` means it has already homed). All axes'
flags are set to `False` by Smoothieware under three conditions:
1) Smoothieware boots or resets, 2) if a HALT gcode or signal
is sent, or 3) a homing/limitswitch error occured. | [
"Move",
"to",
"the",
"target",
"Smoothieware",
"coordinate",
"along",
"any",
"of",
"the",
"size",
"axes",
"XYZABC",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L1068-L1148 | train | 198,213 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0.fast_home | def fast_home(self, axis, safety_margin):
''' home after a controlled motor stall
Given a known distance we have just stalled along an axis, move
that distance away from the homing switch. Then finish with home.
'''
# move some mm distance away from the target axes endstop switch(es)
destination = {
ax: self.homed_position.get(ax) - abs(safety_margin)
for ax in axis.upper()
}
# there is a chance the axis will hit it's home switch too soon
# if this happens, catch the error and continue with homing afterwards
try:
self.move(destination)
except SmoothieError:
pass
# then home once we're closer to the endstop(s)
disabled = ''.join([ax for ax in AXES if ax not in axis.upper()])
return self.home(axis=axis, disabled=disabled) | python | def fast_home(self, axis, safety_margin):
''' home after a controlled motor stall
Given a known distance we have just stalled along an axis, move
that distance away from the homing switch. Then finish with home.
'''
# move some mm distance away from the target axes endstop switch(es)
destination = {
ax: self.homed_position.get(ax) - abs(safety_margin)
for ax in axis.upper()
}
# there is a chance the axis will hit it's home switch too soon
# if this happens, catch the error and continue with homing afterwards
try:
self.move(destination)
except SmoothieError:
pass
# then home once we're closer to the endstop(s)
disabled = ''.join([ax for ax in AXES if ax not in axis.upper()])
return self.home(axis=axis, disabled=disabled) | [
"def",
"fast_home",
"(",
"self",
",",
"axis",
",",
"safety_margin",
")",
":",
"# move some mm distance away from the target axes endstop switch(es)",
"destination",
"=",
"{",
"ax",
":",
"self",
".",
"homed_position",
".",
"get",
"(",
"ax",
")",
"-",
"abs",
"(",
... | home after a controlled motor stall
Given a known distance we have just stalled along an axis, move
that distance away from the homing switch. Then finish with home. | [
"home",
"after",
"a",
"controlled",
"motor",
"stall"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L1230-L1251 | train | 198,214 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0.unstick_axes | def unstick_axes(self, axes, distance=None, speed=None):
'''
The plunger axes on OT2 can build up static friction over time and
when it's cold. To get over this, the robot can move that plunger at
normal current and a very slow speed to increase the torque, removing
the static friction
axes:
String containing each axis to be moved. Ex: 'BC' or 'ZABC'
distance:
Distance to travel in millimeters (default is 1mm)
speed:
Millimeters-per-second to travel to travel at (default is 1mm/sec)
'''
for ax in axes:
if ax not in AXES:
raise ValueError('Unknown axes: {}'.format(axes))
if distance is None:
distance = UNSTICK_DISTANCE
if speed is None:
speed = UNSTICK_SPEED
self.push_active_current()
self.set_active_current({
ax: self._config.high_current[ax]
for ax in axes
})
self.push_axis_max_speed()
self.set_axis_max_speed({ax: speed for ax in axes})
# only need to request switch state once
state_of_switches = {ax: False for ax in AXES}
if not self.simulating:
state_of_switches = self.switch_state
# incase axes is pressing endstop, home it slowly instead of moving
homing_axes = ''.join([ax for ax in axes if state_of_switches[ax]])
moving_axes = {
ax: self.position[ax] - distance # retract
for ax in axes
if (not state_of_switches[ax]) and (ax not in homing_axes)
}
try:
if moving_axes:
self.move(moving_axes)
if homing_axes:
self.home(homing_axes)
finally:
self.pop_active_current()
self.pop_axis_max_speed() | python | def unstick_axes(self, axes, distance=None, speed=None):
'''
The plunger axes on OT2 can build up static friction over time and
when it's cold. To get over this, the robot can move that plunger at
normal current and a very slow speed to increase the torque, removing
the static friction
axes:
String containing each axis to be moved. Ex: 'BC' or 'ZABC'
distance:
Distance to travel in millimeters (default is 1mm)
speed:
Millimeters-per-second to travel to travel at (default is 1mm/sec)
'''
for ax in axes:
if ax not in AXES:
raise ValueError('Unknown axes: {}'.format(axes))
if distance is None:
distance = UNSTICK_DISTANCE
if speed is None:
speed = UNSTICK_SPEED
self.push_active_current()
self.set_active_current({
ax: self._config.high_current[ax]
for ax in axes
})
self.push_axis_max_speed()
self.set_axis_max_speed({ax: speed for ax in axes})
# only need to request switch state once
state_of_switches = {ax: False for ax in AXES}
if not self.simulating:
state_of_switches = self.switch_state
# incase axes is pressing endstop, home it slowly instead of moving
homing_axes = ''.join([ax for ax in axes if state_of_switches[ax]])
moving_axes = {
ax: self.position[ax] - distance # retract
for ax in axes
if (not state_of_switches[ax]) and (ax not in homing_axes)
}
try:
if moving_axes:
self.move(moving_axes)
if homing_axes:
self.home(homing_axes)
finally:
self.pop_active_current()
self.pop_axis_max_speed() | [
"def",
"unstick_axes",
"(",
"self",
",",
"axes",
",",
"distance",
"=",
"None",
",",
"speed",
"=",
"None",
")",
":",
"for",
"ax",
"in",
"axes",
":",
"if",
"ax",
"not",
"in",
"AXES",
":",
"raise",
"ValueError",
"(",
"'Unknown axes: {}'",
".",
"format",
... | The plunger axes on OT2 can build up static friction over time and
when it's cold. To get over this, the robot can move that plunger at
normal current and a very slow speed to increase the torque, removing
the static friction
axes:
String containing each axis to be moved. Ex: 'BC' or 'ZABC'
distance:
Distance to travel in millimeters (default is 1mm)
speed:
Millimeters-per-second to travel to travel at (default is 1mm/sec) | [
"The",
"plunger",
"axes",
"on",
"OT2",
"can",
"build",
"up",
"static",
"friction",
"over",
"time",
"and",
"when",
"it",
"s",
"cold",
".",
"To",
"get",
"over",
"this",
"the",
"robot",
"can",
"move",
"that",
"plunger",
"at",
"normal",
"current",
"and",
"... | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L1253-L1306 | train | 198,215 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0.kill | def kill(self):
"""
In order to terminate Smoothie motion immediately (including
interrupting a command in progress, we set the reset pin low and then
back to high, then call `_setup` method to send the RESET_FROM_ERROR
Smoothie code to return Smoothie to a normal waiting state and reset
any other state needed for the driver.
"""
log.debug("kill")
self._smoothie_hard_halt()
self._reset_from_error()
self._setup() | python | def kill(self):
"""
In order to terminate Smoothie motion immediately (including
interrupting a command in progress, we set the reset pin low and then
back to high, then call `_setup` method to send the RESET_FROM_ERROR
Smoothie code to return Smoothie to a normal waiting state and reset
any other state needed for the driver.
"""
log.debug("kill")
self._smoothie_hard_halt()
self._reset_from_error()
self._setup() | [
"def",
"kill",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"kill\"",
")",
"self",
".",
"_smoothie_hard_halt",
"(",
")",
"self",
".",
"_reset_from_error",
"(",
")",
"self",
".",
"_setup",
"(",
")"
] | In order to terminate Smoothie motion immediately (including
interrupting a command in progress, we set the reset pin low and then
back to high, then call `_setup` method to send the RESET_FROM_ERROR
Smoothie code to return Smoothie to a normal waiting state and reset
any other state needed for the driver. | [
"In",
"order",
"to",
"terminate",
"Smoothie",
"motion",
"immediately",
"(",
"including",
"interrupting",
"a",
"command",
"in",
"progress",
"we",
"set",
"the",
"reset",
"pin",
"low",
"and",
"then",
"back",
"to",
"high",
"then",
"call",
"_setup",
"method",
"to... | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L1372-L1383 | train | 198,216 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0.home_flagged_axes | def home_flagged_axes(self, axes_string):
'''
Given a list of axes to check, this method will home each axis if
Smoothieware's internal flag sets it as needing to be homed
'''
axes_that_need_to_home = [
axis
for axis, already_homed in self.homed_flags.items()
if (not already_homed) and (axis in axes_string)
]
if axes_that_need_to_home:
axes_string = ''.join(axes_that_need_to_home)
self.home(axes_string) | python | def home_flagged_axes(self, axes_string):
'''
Given a list of axes to check, this method will home each axis if
Smoothieware's internal flag sets it as needing to be homed
'''
axes_that_need_to_home = [
axis
for axis, already_homed in self.homed_flags.items()
if (not already_homed) and (axis in axes_string)
]
if axes_that_need_to_home:
axes_string = ''.join(axes_that_need_to_home)
self.home(axes_string) | [
"def",
"home_flagged_axes",
"(",
"self",
",",
"axes_string",
")",
":",
"axes_that_need_to_home",
"=",
"[",
"axis",
"for",
"axis",
",",
"already_homed",
"in",
"self",
".",
"homed_flags",
".",
"items",
"(",
")",
"if",
"(",
"not",
"already_homed",
")",
"and",
... | Given a list of axes to check, this method will home each axis if
Smoothieware's internal flag sets it as needing to be homed | [
"Given",
"a",
"list",
"of",
"axes",
"to",
"check",
"this",
"method",
"will",
"home",
"each",
"axis",
"if",
"Smoothieware",
"s",
"internal",
"flag",
"sets",
"it",
"as",
"needing",
"to",
"be",
"homed"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L1385-L1397 | train | 198,217 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | SmoothieDriver_3_0_0.update_firmware | async def update_firmware(self,
filename: str,
loop: asyncio.AbstractEventLoop = None,
explicit_modeset: bool = True) -> str:
"""
Program the smoothie board with a given hex file.
If explicit_modeset is True (default), explicitly place the smoothie in
programming mode.
If explicit_modeset is False, assume the smoothie is already in
programming mode.
"""
# ensure there is a reference to the port
if self.simulating:
return 'Did nothing (simulating)'
smoothie_update._ensure_programmer_executable()
if not self.is_connected():
self._connect_to_port()
# get port name
port = self._connection.port
if explicit_modeset:
# set smoothieware into programming mode
self._smoothie_programming_mode()
# close the port so other application can access it
self._connection.close()
# run lpc21isp, THIS WILL TAKE AROUND 1 MINUTE TO COMPLETE
update_cmd = 'lpc21isp -wipe -donotstart {0} {1} {2} 12000'.format(
filename, port, self._config.serial_speed)
kwargs: Dict[str, Any] = {'stdout': asyncio.subprocess.PIPE}
if loop:
kwargs['loop'] = loop
proc = await asyncio.create_subprocess_shell(
update_cmd, **kwargs)
rd: bytes = await proc.stdout.read() # type: ignore
res = rd.decode().strip()
await proc.communicate()
# re-open the port
self._connection.open()
# reset smoothieware
self._smoothie_reset()
# run setup gcodes
self._setup()
return res | python | async def update_firmware(self,
filename: str,
loop: asyncio.AbstractEventLoop = None,
explicit_modeset: bool = True) -> str:
"""
Program the smoothie board with a given hex file.
If explicit_modeset is True (default), explicitly place the smoothie in
programming mode.
If explicit_modeset is False, assume the smoothie is already in
programming mode.
"""
# ensure there is a reference to the port
if self.simulating:
return 'Did nothing (simulating)'
smoothie_update._ensure_programmer_executable()
if not self.is_connected():
self._connect_to_port()
# get port name
port = self._connection.port
if explicit_modeset:
# set smoothieware into programming mode
self._smoothie_programming_mode()
# close the port so other application can access it
self._connection.close()
# run lpc21isp, THIS WILL TAKE AROUND 1 MINUTE TO COMPLETE
update_cmd = 'lpc21isp -wipe -donotstart {0} {1} {2} 12000'.format(
filename, port, self._config.serial_speed)
kwargs: Dict[str, Any] = {'stdout': asyncio.subprocess.PIPE}
if loop:
kwargs['loop'] = loop
proc = await asyncio.create_subprocess_shell(
update_cmd, **kwargs)
rd: bytes = await proc.stdout.read() # type: ignore
res = rd.decode().strip()
await proc.communicate()
# re-open the port
self._connection.open()
# reset smoothieware
self._smoothie_reset()
# run setup gcodes
self._setup()
return res | [
"async",
"def",
"update_firmware",
"(",
"self",
",",
"filename",
":",
"str",
",",
"loop",
":",
"asyncio",
".",
"AbstractEventLoop",
"=",
"None",
",",
"explicit_modeset",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"# ensure there is a reference to the port"... | Program the smoothie board with a given hex file.
If explicit_modeset is True (default), explicitly place the smoothie in
programming mode.
If explicit_modeset is False, assume the smoothie is already in
programming mode. | [
"Program",
"the",
"smoothie",
"board",
"with",
"a",
"given",
"hex",
"file",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L1438-L1488 | train | 198,218 |
Opentrons/opentrons | api/src/opentrons/legacy_api/containers/__init__.py | load_new_labware | def load_new_labware(container_name):
""" Load a labware in the new schema into a placeable.
:raises KeyError: If the labware name is not found
"""
defn = new_labware.load_definition_by_name(container_name)
labware_id = defn['otId']
saved_offset = _look_up_offsets(labware_id)
container = Container()
log.info(f"Container name {container_name}")
container.properties['type'] = container_name
container.properties['otId'] = labware_id
format = defn['parameters']['format']
container._coordinates = Vector(defn['cornerOffsetFromSlot'])
for well_name in itertools.chain(*defn['ordering']):
well_obj, well_pos = _load_new_well(
defn['wells'][well_name], saved_offset, format)
container.add(well_obj, well_name, well_pos)
return container | python | def load_new_labware(container_name):
""" Load a labware in the new schema into a placeable.
:raises KeyError: If the labware name is not found
"""
defn = new_labware.load_definition_by_name(container_name)
labware_id = defn['otId']
saved_offset = _look_up_offsets(labware_id)
container = Container()
log.info(f"Container name {container_name}")
container.properties['type'] = container_name
container.properties['otId'] = labware_id
format = defn['parameters']['format']
container._coordinates = Vector(defn['cornerOffsetFromSlot'])
for well_name in itertools.chain(*defn['ordering']):
well_obj, well_pos = _load_new_well(
defn['wells'][well_name], saved_offset, format)
container.add(well_obj, well_name, well_pos)
return container | [
"def",
"load_new_labware",
"(",
"container_name",
")",
":",
"defn",
"=",
"new_labware",
".",
"load_definition_by_name",
"(",
"container_name",
")",
"labware_id",
"=",
"defn",
"[",
"'otId'",
"]",
"saved_offset",
"=",
"_look_up_offsets",
"(",
"labware_id",
")",
"con... | Load a labware in the new schema into a placeable.
:raises KeyError: If the labware name is not found | [
"Load",
"a",
"labware",
"in",
"the",
"new",
"schema",
"into",
"a",
"placeable",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/containers/__init__.py#L204-L223 | train | 198,219 |
chimpler/pyhocon | pyhocon/converter.py | HOCONConverter.to_yaml | def to_yaml(cls, config, compact=False, indent=2, level=0):
"""Convert HOCON input into a YAML output
:return: YAML string representation
:type return: basestring
"""
lines = ""
if isinstance(config, ConfigTree):
if len(config) > 0:
if level > 0:
lines += '\n'
bet_lines = []
for key, item in config.items():
bet_lines.append('{indent}{key}: {value}'.format(
indent=''.rjust(level * indent, ' '),
key=key.strip('"'), # for dotted keys enclosed with "" to not be interpreted as nested key,
value=cls.to_yaml(item, compact, indent, level + 1))
)
lines += '\n'.join(bet_lines)
elif isinstance(config, list):
config_list = [line for line in config if line is not None]
if len(config_list) == 0:
lines += '[]'
else:
lines += '\n'
bet_lines = []
for item in config_list:
bet_lines.append('{indent}- {value}'.format(indent=''.rjust(level * indent, ' '),
value=cls.to_yaml(item, compact, indent, level + 1)))
lines += '\n'.join(bet_lines)
elif isinstance(config, basestring):
# if it contains a \n then it's multiline
lines = config.split('\n')
if len(lines) == 1:
lines = config
else:
lines = '|\n' + '\n'.join([line.rjust(level * indent, ' ') for line in lines])
elif config is None or isinstance(config, NoneValue):
lines = 'null'
elif config is True:
lines = 'true'
elif config is False:
lines = 'false'
else:
lines = str(config)
return lines | python | def to_yaml(cls, config, compact=False, indent=2, level=0):
"""Convert HOCON input into a YAML output
:return: YAML string representation
:type return: basestring
"""
lines = ""
if isinstance(config, ConfigTree):
if len(config) > 0:
if level > 0:
lines += '\n'
bet_lines = []
for key, item in config.items():
bet_lines.append('{indent}{key}: {value}'.format(
indent=''.rjust(level * indent, ' '),
key=key.strip('"'), # for dotted keys enclosed with "" to not be interpreted as nested key,
value=cls.to_yaml(item, compact, indent, level + 1))
)
lines += '\n'.join(bet_lines)
elif isinstance(config, list):
config_list = [line for line in config if line is not None]
if len(config_list) == 0:
lines += '[]'
else:
lines += '\n'
bet_lines = []
for item in config_list:
bet_lines.append('{indent}- {value}'.format(indent=''.rjust(level * indent, ' '),
value=cls.to_yaml(item, compact, indent, level + 1)))
lines += '\n'.join(bet_lines)
elif isinstance(config, basestring):
# if it contains a \n then it's multiline
lines = config.split('\n')
if len(lines) == 1:
lines = config
else:
lines = '|\n' + '\n'.join([line.rjust(level * indent, ' ') for line in lines])
elif config is None or isinstance(config, NoneValue):
lines = 'null'
elif config is True:
lines = 'true'
elif config is False:
lines = 'false'
else:
lines = str(config)
return lines | [
"def",
"to_yaml",
"(",
"cls",
",",
"config",
",",
"compact",
"=",
"False",
",",
"indent",
"=",
"2",
",",
"level",
"=",
"0",
")",
":",
"lines",
"=",
"\"\"",
"if",
"isinstance",
"(",
"config",
",",
"ConfigTree",
")",
":",
"if",
"len",
"(",
"config",
... | Convert HOCON input into a YAML output
:return: YAML string representation
:type return: basestring | [
"Convert",
"HOCON",
"input",
"into",
"a",
"YAML",
"output"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/converter.py#L140-L185 | train | 198,220 |
chimpler/pyhocon | pyhocon/converter.py | HOCONConverter.to_properties | def to_properties(cls, config, compact=False, indent=2, key_stack=[]):
"""Convert HOCON input into a .properties output
:return: .properties string representation
:type return: basestring
:return:
"""
def escape_value(value):
return value.replace('=', '\\=').replace('!', '\\!').replace('#', '\\#').replace('\n', '\\\n')
stripped_key_stack = [key.strip('"') for key in key_stack]
lines = []
if isinstance(config, ConfigTree):
for key, item in config.items():
if item is not None:
lines.append(cls.to_properties(item, compact, indent, stripped_key_stack + [key]))
elif isinstance(config, list):
for index, item in enumerate(config):
if item is not None:
lines.append(cls.to_properties(item, compact, indent, stripped_key_stack + [str(index)]))
elif isinstance(config, basestring):
lines.append('.'.join(stripped_key_stack) + ' = ' + escape_value(config))
elif config is True:
lines.append('.'.join(stripped_key_stack) + ' = true')
elif config is False:
lines.append('.'.join(stripped_key_stack) + ' = false')
elif config is None or isinstance(config, NoneValue):
pass
else:
lines.append('.'.join(stripped_key_stack) + ' = ' + str(config))
return '\n'.join([line for line in lines if len(line) > 0]) | python | def to_properties(cls, config, compact=False, indent=2, key_stack=[]):
"""Convert HOCON input into a .properties output
:return: .properties string representation
:type return: basestring
:return:
"""
def escape_value(value):
return value.replace('=', '\\=').replace('!', '\\!').replace('#', '\\#').replace('\n', '\\\n')
stripped_key_stack = [key.strip('"') for key in key_stack]
lines = []
if isinstance(config, ConfigTree):
for key, item in config.items():
if item is not None:
lines.append(cls.to_properties(item, compact, indent, stripped_key_stack + [key]))
elif isinstance(config, list):
for index, item in enumerate(config):
if item is not None:
lines.append(cls.to_properties(item, compact, indent, stripped_key_stack + [str(index)]))
elif isinstance(config, basestring):
lines.append('.'.join(stripped_key_stack) + ' = ' + escape_value(config))
elif config is True:
lines.append('.'.join(stripped_key_stack) + ' = true')
elif config is False:
lines.append('.'.join(stripped_key_stack) + ' = false')
elif config is None or isinstance(config, NoneValue):
pass
else:
lines.append('.'.join(stripped_key_stack) + ' = ' + str(config))
return '\n'.join([line for line in lines if len(line) > 0]) | [
"def",
"to_properties",
"(",
"cls",
",",
"config",
",",
"compact",
"=",
"False",
",",
"indent",
"=",
"2",
",",
"key_stack",
"=",
"[",
"]",
")",
":",
"def",
"escape_value",
"(",
"value",
")",
":",
"return",
"value",
".",
"replace",
"(",
"'='",
",",
... | Convert HOCON input into a .properties output
:return: .properties string representation
:type return: basestring
:return: | [
"Convert",
"HOCON",
"input",
"into",
"a",
".",
"properties",
"output"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/converter.py#L188-L219 | train | 198,221 |
chimpler/pyhocon | pyhocon/converter.py | HOCONConverter.convert_from_file | def convert_from_file(cls, input_file=None, output_file=None, output_format='json', indent=2, compact=False):
"""Convert to json, properties or yaml
:param input_file: input file, if not specified stdin
:param output_file: output file, if not specified stdout
:param output_format: json, properties or yaml
:return: json, properties or yaml string representation
"""
if input_file is None:
content = sys.stdin.read()
config = ConfigFactory.parse_string(content)
else:
config = ConfigFactory.parse_file(input_file)
res = cls.convert(config, output_format, indent, compact)
if output_file is None:
print(res)
else:
with open(output_file, "w") as fd:
fd.write(res) | python | def convert_from_file(cls, input_file=None, output_file=None, output_format='json', indent=2, compact=False):
"""Convert to json, properties or yaml
:param input_file: input file, if not specified stdin
:param output_file: output file, if not specified stdout
:param output_format: json, properties or yaml
:return: json, properties or yaml string representation
"""
if input_file is None:
content = sys.stdin.read()
config = ConfigFactory.parse_string(content)
else:
config = ConfigFactory.parse_file(input_file)
res = cls.convert(config, output_format, indent, compact)
if output_file is None:
print(res)
else:
with open(output_file, "w") as fd:
fd.write(res) | [
"def",
"convert_from_file",
"(",
"cls",
",",
"input_file",
"=",
"None",
",",
"output_file",
"=",
"None",
",",
"output_format",
"=",
"'json'",
",",
"indent",
"=",
"2",
",",
"compact",
"=",
"False",
")",
":",
"if",
"input_file",
"is",
"None",
":",
"content... | Convert to json, properties or yaml
:param input_file: input file, if not specified stdin
:param output_file: output file, if not specified stdout
:param output_format: json, properties or yaml
:return: json, properties or yaml string representation | [
"Convert",
"to",
"json",
"properties",
"or",
"yaml"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/converter.py#L237-L257 | train | 198,222 |
chimpler/pyhocon | pyhocon/config_parser.py | ListParser.postParse | def postParse(self, instring, loc, token_list):
"""Create a list from the tokens
:param instring:
:param loc:
:param token_list:
:return:
"""
cleaned_token_list = [token for tokens in (token.tokens if isinstance(token, ConfigInclude) else [token]
for token in token_list if token != '')
for token in tokens]
config_list = ConfigList(cleaned_token_list)
return [config_list] | python | def postParse(self, instring, loc, token_list):
"""Create a list from the tokens
:param instring:
:param loc:
:param token_list:
:return:
"""
cleaned_token_list = [token for tokens in (token.tokens if isinstance(token, ConfigInclude) else [token]
for token in token_list if token != '')
for token in tokens]
config_list = ConfigList(cleaned_token_list)
return [config_list] | [
"def",
"postParse",
"(",
"self",
",",
"instring",
",",
"loc",
",",
"token_list",
")",
":",
"cleaned_token_list",
"=",
"[",
"token",
"for",
"tokens",
"in",
"(",
"token",
".",
"tokens",
"if",
"isinstance",
"(",
"token",
",",
"ConfigInclude",
")",
"else",
"... | Create a list from the tokens
:param instring:
:param loc:
:param token_list:
:return: | [
"Create",
"a",
"list",
"from",
"the",
"tokens"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_parser.py#L644-L656 | train | 198,223 |
chimpler/pyhocon | pyhocon/config_parser.py | ConfigTreeParser.postParse | def postParse(self, instring, loc, token_list):
"""Create ConfigTree from tokens
:param instring:
:param loc:
:param token_list:
:return:
"""
config_tree = ConfigTree(root=self.root)
for element in token_list:
expanded_tokens = element.tokens if isinstance(element, ConfigInclude) else [element]
for tokens in expanded_tokens:
# key, value1 (optional), ...
key = tokens[0].strip()
operator = '='
if len(tokens) == 3 and tokens[1].strip() in [':', '=', '+=']:
operator = tokens[1].strip()
values = tokens[2:]
elif len(tokens) == 2:
values = tokens[1:]
else:
raise ParseSyntaxException("Unknown tokens {tokens} received".format(tokens=tokens))
# empty string
if len(values) == 0:
config_tree.put(key, '')
else:
value = values[0]
if isinstance(value, list) and operator == "+=":
value = ConfigValues([ConfigSubstitution(key, True, '', False, loc), value], False, loc)
config_tree.put(key, value, False)
elif isinstance(value, unicode) and operator == "+=":
value = ConfigValues([ConfigSubstitution(key, True, '', True, loc), ' ' + value], True, loc)
config_tree.put(key, value, False)
elif isinstance(value, list):
config_tree.put(key, value, False)
else:
existing_value = config_tree.get(key, None)
if isinstance(value, ConfigTree) and not isinstance(existing_value, list):
# Only Tree has to be merged with tree
config_tree.put(key, value, True)
elif isinstance(value, ConfigValues):
conf_value = value
value.parent = config_tree
value.key = key
if isinstance(existing_value, list) or isinstance(existing_value, ConfigTree):
config_tree.put(key, conf_value, True)
else:
config_tree.put(key, conf_value, False)
else:
config_tree.put(key, value, False)
return config_tree | python | def postParse(self, instring, loc, token_list):
"""Create ConfigTree from tokens
:param instring:
:param loc:
:param token_list:
:return:
"""
config_tree = ConfigTree(root=self.root)
for element in token_list:
expanded_tokens = element.tokens if isinstance(element, ConfigInclude) else [element]
for tokens in expanded_tokens:
# key, value1 (optional), ...
key = tokens[0].strip()
operator = '='
if len(tokens) == 3 and tokens[1].strip() in [':', '=', '+=']:
operator = tokens[1].strip()
values = tokens[2:]
elif len(tokens) == 2:
values = tokens[1:]
else:
raise ParseSyntaxException("Unknown tokens {tokens} received".format(tokens=tokens))
# empty string
if len(values) == 0:
config_tree.put(key, '')
else:
value = values[0]
if isinstance(value, list) and operator == "+=":
value = ConfigValues([ConfigSubstitution(key, True, '', False, loc), value], False, loc)
config_tree.put(key, value, False)
elif isinstance(value, unicode) and operator == "+=":
value = ConfigValues([ConfigSubstitution(key, True, '', True, loc), ' ' + value], True, loc)
config_tree.put(key, value, False)
elif isinstance(value, list):
config_tree.put(key, value, False)
else:
existing_value = config_tree.get(key, None)
if isinstance(value, ConfigTree) and not isinstance(existing_value, list):
# Only Tree has to be merged with tree
config_tree.put(key, value, True)
elif isinstance(value, ConfigValues):
conf_value = value
value.parent = config_tree
value.key = key
if isinstance(existing_value, list) or isinstance(existing_value, ConfigTree):
config_tree.put(key, conf_value, True)
else:
config_tree.put(key, conf_value, False)
else:
config_tree.put(key, value, False)
return config_tree | [
"def",
"postParse",
"(",
"self",
",",
"instring",
",",
"loc",
",",
"token_list",
")",
":",
"config_tree",
"=",
"ConfigTree",
"(",
"root",
"=",
"self",
".",
"root",
")",
"for",
"element",
"in",
"token_list",
":",
"expanded_tokens",
"=",
"element",
".",
"t... | Create ConfigTree from tokens
:param instring:
:param loc:
:param token_list:
:return: | [
"Create",
"ConfigTree",
"from",
"tokens"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_parser.py#L680-L731 | train | 198,224 |
chimpler/pyhocon | pyhocon/config_tree.py | ConfigTree.merge_configs | def merge_configs(a, b, copy_trees=False):
"""Merge config b into a
:param a: target config
:type a: ConfigTree
:param b: source config
:type b: ConfigTree
:return: merged config a
"""
for key, value in b.items():
# if key is in both a and b and both values are dictionary then merge it otherwise override it
if key in a and isinstance(a[key], ConfigTree) and isinstance(b[key], ConfigTree):
if copy_trees:
a[key] = a[key].copy()
ConfigTree.merge_configs(a[key], b[key], copy_trees=copy_trees)
else:
if isinstance(value, ConfigValues):
value.parent = a
value.key = key
if key in a:
value.overriden_value = a[key]
a[key] = value
if a.root:
if b.root:
a.history[key] = a.history.get(key, []) + b.history.get(key, [value])
else:
a.history[key] = a.history.get(key, []) + [value]
return a | python | def merge_configs(a, b, copy_trees=False):
"""Merge config b into a
:param a: target config
:type a: ConfigTree
:param b: source config
:type b: ConfigTree
:return: merged config a
"""
for key, value in b.items():
# if key is in both a and b and both values are dictionary then merge it otherwise override it
if key in a and isinstance(a[key], ConfigTree) and isinstance(b[key], ConfigTree):
if copy_trees:
a[key] = a[key].copy()
ConfigTree.merge_configs(a[key], b[key], copy_trees=copy_trees)
else:
if isinstance(value, ConfigValues):
value.parent = a
value.key = key
if key in a:
value.overriden_value = a[key]
a[key] = value
if a.root:
if b.root:
a.history[key] = a.history.get(key, []) + b.history.get(key, [value])
else:
a.history[key] = a.history.get(key, []) + [value]
return a | [
"def",
"merge_configs",
"(",
"a",
",",
"b",
",",
"copy_trees",
"=",
"False",
")",
":",
"for",
"key",
",",
"value",
"in",
"b",
".",
"items",
"(",
")",
":",
"# if key is in both a and b and both values are dictionary then merge it otherwise override it",
"if",
"key",
... | Merge config b into a
:param a: target config
:type a: ConfigTree
:param b: source config
:type b: ConfigTree
:return: merged config a | [
"Merge",
"config",
"b",
"into",
"a"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_tree.py#L41-L69 | train | 198,225 |
chimpler/pyhocon | pyhocon/config_tree.py | ConfigTree.get | def get(self, key, default=UndefinedKey):
"""Get a value from the tree
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: object
:return: value in the tree located at key
"""
return self._get(ConfigTree.parse_key(key), 0, default) | python | def get(self, key, default=UndefinedKey):
"""Get a value from the tree
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: object
:return: value in the tree located at key
"""
return self._get(ConfigTree.parse_key(key), 0, default) | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"UndefinedKey",
")",
":",
"return",
"self",
".",
"_get",
"(",
"ConfigTree",
".",
"parse_key",
"(",
"key",
")",
",",
"0",
",",
"default",
")"
] | Get a value from the tree
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: object
:return: value in the tree located at key | [
"Get",
"a",
"value",
"from",
"the",
"tree"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_tree.py#L200-L209 | train | 198,226 |
chimpler/pyhocon | pyhocon/config_tree.py | ConfigTree.get_string | def get_string(self, key, default=UndefinedKey):
"""Return string representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: basestring
:return: string value
:type return: basestring
"""
value = self.get(key, default)
if value is None:
return None
string_value = unicode(value)
if isinstance(value, bool):
string_value = string_value.lower()
return string_value | python | def get_string(self, key, default=UndefinedKey):
"""Return string representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: basestring
:return: string value
:type return: basestring
"""
value = self.get(key, default)
if value is None:
return None
string_value = unicode(value)
if isinstance(value, bool):
string_value = string_value.lower()
return string_value | [
"def",
"get_string",
"(",
"self",
",",
"key",
",",
"default",
"=",
"UndefinedKey",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"key",
",",
"default",
")",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"string_value",
"=",
"unicode",
"(",
"... | Return string representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: basestring
:return: string value
:type return: basestring | [
"Return",
"string",
"representation",
"of",
"value",
"found",
"at",
"key"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_tree.py#L211-L228 | train | 198,227 |
chimpler/pyhocon | pyhocon/config_tree.py | ConfigTree.pop | def pop(self, key, default=UndefinedKey):
"""Remove specified key and return the corresponding value.
If key is not found, default is returned if given, otherwise ConfigMissingException is raised
This method assumes the user wants to remove the last value in the chain so it parses via parse_key
and pops the last value out of the dict.
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: object
:param default: default value if key not found
:return: value in the tree located at key
"""
if default != UndefinedKey and key not in self:
return default
value = self.get(key, UndefinedKey)
lst = ConfigTree.parse_key(key)
parent = self.KEY_SEP.join(lst[0:-1])
child = lst[-1]
if parent:
self.get(parent).__delitem__(child)
else:
self.__delitem__(child)
return value | python | def pop(self, key, default=UndefinedKey):
"""Remove specified key and return the corresponding value.
If key is not found, default is returned if given, otherwise ConfigMissingException is raised
This method assumes the user wants to remove the last value in the chain so it parses via parse_key
and pops the last value out of the dict.
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: object
:param default: default value if key not found
:return: value in the tree located at key
"""
if default != UndefinedKey and key not in self:
return default
value = self.get(key, UndefinedKey)
lst = ConfigTree.parse_key(key)
parent = self.KEY_SEP.join(lst[0:-1])
child = lst[-1]
if parent:
self.get(parent).__delitem__(child)
else:
self.__delitem__(child)
return value | [
"def",
"pop",
"(",
"self",
",",
"key",
",",
"default",
"=",
"UndefinedKey",
")",
":",
"if",
"default",
"!=",
"UndefinedKey",
"and",
"key",
"not",
"in",
"self",
":",
"return",
"default",
"value",
"=",
"self",
".",
"get",
"(",
"key",
",",
"UndefinedKey",... | Remove specified key and return the corresponding value.
If key is not found, default is returned if given, otherwise ConfigMissingException is raised
This method assumes the user wants to remove the last value in the chain so it parses via parse_key
and pops the last value out of the dict.
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: object
:param default: default value if key not found
:return: value in the tree located at key | [
"Remove",
"specified",
"key",
"and",
"return",
"the",
"corresponding",
"value",
".",
"If",
"key",
"is",
"not",
"found",
"default",
"is",
"returned",
"if",
"given",
"otherwise",
"ConfigMissingException",
"is",
"raised"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_tree.py#L230-L256 | train | 198,228 |
chimpler/pyhocon | pyhocon/config_tree.py | ConfigTree.get_int | def get_int(self, key, default=UndefinedKey):
"""Return int representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: int
:return: int value
:type return: int
"""
value = self.get(key, default)
try:
return int(value) if value is not None else None
except (TypeError, ValueError):
raise ConfigException(
u"{key} has type '{type}' rather than 'int'".format(key=key, type=type(value).__name__)) | python | def get_int(self, key, default=UndefinedKey):
"""Return int representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: int
:return: int value
:type return: int
"""
value = self.get(key, default)
try:
return int(value) if value is not None else None
except (TypeError, ValueError):
raise ConfigException(
u"{key} has type '{type}' rather than 'int'".format(key=key, type=type(value).__name__)) | [
"def",
"get_int",
"(",
"self",
",",
"key",
",",
"default",
"=",
"UndefinedKey",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"key",
",",
"default",
")",
"try",
":",
"return",
"int",
"(",
"value",
")",
"if",
"value",
"is",
"not",
"None",
"else",... | Return int representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: int
:return: int value
:type return: int | [
"Return",
"int",
"representation",
"of",
"value",
"found",
"at",
"key"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_tree.py#L258-L273 | train | 198,229 |
chimpler/pyhocon | pyhocon/config_tree.py | ConfigTree.get_float | def get_float(self, key, default=UndefinedKey):
"""Return float representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: float
:return: float value
:type return: float
"""
value = self.get(key, default)
try:
return float(value) if value is not None else None
except (TypeError, ValueError):
raise ConfigException(
u"{key} has type '{type}' rather than 'float'".format(key=key, type=type(value).__name__)) | python | def get_float(self, key, default=UndefinedKey):
"""Return float representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: float
:return: float value
:type return: float
"""
value = self.get(key, default)
try:
return float(value) if value is not None else None
except (TypeError, ValueError):
raise ConfigException(
u"{key} has type '{type}' rather than 'float'".format(key=key, type=type(value).__name__)) | [
"def",
"get_float",
"(",
"self",
",",
"key",
",",
"default",
"=",
"UndefinedKey",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"key",
",",
"default",
")",
"try",
":",
"return",
"float",
"(",
"value",
")",
"if",
"value",
"is",
"not",
"None",
"el... | Return float representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: float
:return: float value
:type return: float | [
"Return",
"float",
"representation",
"of",
"value",
"found",
"at",
"key"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_tree.py#L275-L290 | train | 198,230 |
chimpler/pyhocon | pyhocon/config_tree.py | ConfigTree.get_bool | def get_bool(self, key, default=UndefinedKey):
"""Return boolean representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: bool
:return: boolean value
:type return: bool
"""
# String conversions as per API-recommendations:
# https://github.com/typesafehub/config/blob/master/HOCON.md#automatic-type-conversions
bool_conversions = {
None: None,
'true': True, 'yes': True, 'on': True,
'false': False, 'no': False, 'off': False
}
string_value = self.get_string(key, default)
if string_value is not None:
string_value = string_value.lower()
try:
return bool_conversions[string_value]
except KeyError:
raise ConfigException(
u"{key} does not translate to a Boolean value".format(key=key)) | python | def get_bool(self, key, default=UndefinedKey):
"""Return boolean representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: bool
:return: boolean value
:type return: bool
"""
# String conversions as per API-recommendations:
# https://github.com/typesafehub/config/blob/master/HOCON.md#automatic-type-conversions
bool_conversions = {
None: None,
'true': True, 'yes': True, 'on': True,
'false': False, 'no': False, 'off': False
}
string_value = self.get_string(key, default)
if string_value is not None:
string_value = string_value.lower()
try:
return bool_conversions[string_value]
except KeyError:
raise ConfigException(
u"{key} does not translate to a Boolean value".format(key=key)) | [
"def",
"get_bool",
"(",
"self",
",",
"key",
",",
"default",
"=",
"UndefinedKey",
")",
":",
"# String conversions as per API-recommendations:",
"# https://github.com/typesafehub/config/blob/master/HOCON.md#automatic-type-conversions",
"bool_conversions",
"=",
"{",
"None",
":",
"... | Return boolean representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: bool
:return: boolean value
:type return: bool | [
"Return",
"boolean",
"representation",
"of",
"value",
"found",
"at",
"key"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_tree.py#L292-L317 | train | 198,231 |
chimpler/pyhocon | pyhocon/config_tree.py | ConfigTree.get_list | def get_list(self, key, default=UndefinedKey):
"""Return list representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: list
:return: list value
:type return: list
"""
value = self.get(key, default)
if isinstance(value, list):
return value
elif isinstance(value, ConfigTree):
lst = []
for k, v in sorted(value.items(), key=lambda kv: kv[0]):
if re.match('^[1-9][0-9]*$|0', k):
lst.append(v)
else:
raise ConfigException(u"{key} does not translate to a list".format(key=key))
return lst
elif value is None:
return None
else:
raise ConfigException(
u"{key} has type '{type}' rather than 'list'".format(key=key, type=type(value).__name__)) | python | def get_list(self, key, default=UndefinedKey):
"""Return list representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: list
:return: list value
:type return: list
"""
value = self.get(key, default)
if isinstance(value, list):
return value
elif isinstance(value, ConfigTree):
lst = []
for k, v in sorted(value.items(), key=lambda kv: kv[0]):
if re.match('^[1-9][0-9]*$|0', k):
lst.append(v)
else:
raise ConfigException(u"{key} does not translate to a list".format(key=key))
return lst
elif value is None:
return None
else:
raise ConfigException(
u"{key} has type '{type}' rather than 'list'".format(key=key, type=type(value).__name__)) | [
"def",
"get_list",
"(",
"self",
",",
"key",
",",
"default",
"=",
"UndefinedKey",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"key",
",",
"default",
")",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"value",
"elif",
"isinsta... | Return list representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: list
:return: list value
:type return: list | [
"Return",
"list",
"representation",
"of",
"value",
"found",
"at",
"key"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_tree.py#L319-L344 | train | 198,232 |
chimpler/pyhocon | pyhocon/config_tree.py | ConfigTree.get_config | def get_config(self, key, default=UndefinedKey):
"""Return tree config representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: config
:return: config value
:type return: ConfigTree
"""
value = self.get(key, default)
if isinstance(value, dict):
return value
elif value is None:
return None
else:
raise ConfigException(
u"{key} has type '{type}' rather than 'config'".format(key=key, type=type(value).__name__)) | python | def get_config(self, key, default=UndefinedKey):
"""Return tree config representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: config
:return: config value
:type return: ConfigTree
"""
value = self.get(key, default)
if isinstance(value, dict):
return value
elif value is None:
return None
else:
raise ConfigException(
u"{key} has type '{type}' rather than 'config'".format(key=key, type=type(value).__name__)) | [
"def",
"get_config",
"(",
"self",
",",
"key",
",",
"default",
"=",
"UndefinedKey",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"key",
",",
"default",
")",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"return",
"value",
"elif",
"value... | Return tree config representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: config
:return: config value
:type return: ConfigTree | [
"Return",
"tree",
"config",
"representation",
"of",
"value",
"found",
"at",
"key"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_tree.py#L346-L363 | train | 198,233 |
chimpler/pyhocon | pyhocon/config_tree.py | ConfigTree.as_plain_ordered_dict | def as_plain_ordered_dict(self):
"""return a deep copy of this config as a plain OrderedDict
The config tree should be fully resolved.
This is useful to get an object with no special semantics such as path expansion for the keys.
In particular this means that keys that contain dots are not surrounded with '"' in the plain OrderedDict.
:return: this config as an OrderedDict
:type return: OrderedDict
"""
def plain_value(v):
if isinstance(v, list):
return [plain_value(e) for e in v]
elif isinstance(v, ConfigTree):
return v.as_plain_ordered_dict()
else:
if isinstance(v, ConfigValues):
raise ConfigException("The config tree contains unresolved elements")
return v
return OrderedDict((key.strip('"'), plain_value(value)) for key, value in self.items()) | python | def as_plain_ordered_dict(self):
"""return a deep copy of this config as a plain OrderedDict
The config tree should be fully resolved.
This is useful to get an object with no special semantics such as path expansion for the keys.
In particular this means that keys that contain dots are not surrounded with '"' in the plain OrderedDict.
:return: this config as an OrderedDict
:type return: OrderedDict
"""
def plain_value(v):
if isinstance(v, list):
return [plain_value(e) for e in v]
elif isinstance(v, ConfigTree):
return v.as_plain_ordered_dict()
else:
if isinstance(v, ConfigValues):
raise ConfigException("The config tree contains unresolved elements")
return v
return OrderedDict((key.strip('"'), plain_value(value)) for key, value in self.items()) | [
"def",
"as_plain_ordered_dict",
"(",
"self",
")",
":",
"def",
"plain_value",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"return",
"[",
"plain_value",
"(",
"e",
")",
"for",
"e",
"in",
"v",
"]",
"elif",
"isinstance",
"(",
... | return a deep copy of this config as a plain OrderedDict
The config tree should be fully resolved.
This is useful to get an object with no special semantics such as path expansion for the keys.
In particular this means that keys that contain dots are not surrounded with '"' in the plain OrderedDict.
:return: this config as an OrderedDict
:type return: OrderedDict | [
"return",
"a",
"deep",
"copy",
"of",
"this",
"config",
"as",
"a",
"plain",
"OrderedDict"
] | e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3 | https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_tree.py#L406-L427 | train | 198,234 |
cphyc/matplotlib-label-lines | labellines/core.py | labelLine | def labelLine(line, x, label=None, align=True, **kwargs):
'''Label a single matplotlib line at position x
Parameters
----------
line : matplotlib.lines.Line
The line holding the label
x : number
The location in data unit of the label
label : string, optional
The label to set. This is inferred from the line by default
kwargs : dict, optional
Optional arguments passed to ax.text
'''
ax = line.axes
xdata = line.get_xdata()
ydata = line.get_ydata()
order = np.argsort(xdata)
xdata = xdata[order]
ydata = ydata[order]
# Convert datetime objects to floats
if isinstance(x, datetime):
x = date2num(x)
xmin, xmax = xdata[0], xdata[-1]
if (x < xmin) or (x > xmax):
raise Exception('x label location is outside data range!')
# Find corresponding y co-ordinate and angle of the
ip = 1
for i in range(len(xdata)):
if x < xdata[i]:
ip = i
break
y = ydata[ip-1] + (ydata[ip]-ydata[ip-1]) * \
(x-xdata[ip-1])/(xdata[ip]-xdata[ip-1])
if not label:
label = line.get_label()
if align:
# Compute the slope
dx = xdata[ip] - xdata[ip-1]
dy = ydata[ip] - ydata[ip-1]
ang = degrees(atan2(dy, dx))
# Transform to screen co-ordinates
pt = np.array([x, y]).reshape((1, 2))
trans_angle = ax.transData.transform_angles(np.array((ang, )), pt)[0]
else:
trans_angle = 0
# Set a bunch of keyword arguments
if 'color' not in kwargs:
kwargs['color'] = line.get_color()
if ('horizontalalignment' not in kwargs) and ('ha' not in kwargs):
kwargs['ha'] = 'center'
if ('verticalalignment' not in kwargs) and ('va' not in kwargs):
kwargs['va'] = 'center'
if 'backgroundcolor' not in kwargs:
kwargs['backgroundcolor'] = ax.get_facecolor()
if 'clip_on' not in kwargs:
kwargs['clip_on'] = True
if 'zorder' not in kwargs:
kwargs['zorder'] = 2.5
ax.text(x, y, label, rotation=trans_angle, **kwargs) | python | def labelLine(line, x, label=None, align=True, **kwargs):
'''Label a single matplotlib line at position x
Parameters
----------
line : matplotlib.lines.Line
The line holding the label
x : number
The location in data unit of the label
label : string, optional
The label to set. This is inferred from the line by default
kwargs : dict, optional
Optional arguments passed to ax.text
'''
ax = line.axes
xdata = line.get_xdata()
ydata = line.get_ydata()
order = np.argsort(xdata)
xdata = xdata[order]
ydata = ydata[order]
# Convert datetime objects to floats
if isinstance(x, datetime):
x = date2num(x)
xmin, xmax = xdata[0], xdata[-1]
if (x < xmin) or (x > xmax):
raise Exception('x label location is outside data range!')
# Find corresponding y co-ordinate and angle of the
ip = 1
for i in range(len(xdata)):
if x < xdata[i]:
ip = i
break
y = ydata[ip-1] + (ydata[ip]-ydata[ip-1]) * \
(x-xdata[ip-1])/(xdata[ip]-xdata[ip-1])
if not label:
label = line.get_label()
if align:
# Compute the slope
dx = xdata[ip] - xdata[ip-1]
dy = ydata[ip] - ydata[ip-1]
ang = degrees(atan2(dy, dx))
# Transform to screen co-ordinates
pt = np.array([x, y]).reshape((1, 2))
trans_angle = ax.transData.transform_angles(np.array((ang, )), pt)[0]
else:
trans_angle = 0
# Set a bunch of keyword arguments
if 'color' not in kwargs:
kwargs['color'] = line.get_color()
if ('horizontalalignment' not in kwargs) and ('ha' not in kwargs):
kwargs['ha'] = 'center'
if ('verticalalignment' not in kwargs) and ('va' not in kwargs):
kwargs['va'] = 'center'
if 'backgroundcolor' not in kwargs:
kwargs['backgroundcolor'] = ax.get_facecolor()
if 'clip_on' not in kwargs:
kwargs['clip_on'] = True
if 'zorder' not in kwargs:
kwargs['zorder'] = 2.5
ax.text(x, y, label, rotation=trans_angle, **kwargs) | [
"def",
"labelLine",
"(",
"line",
",",
"x",
",",
"label",
"=",
"None",
",",
"align",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"ax",
"=",
"line",
".",
"axes",
"xdata",
"=",
"line",
".",
"get_xdata",
"(",
")",
"ydata",
"=",
"line",
".",
"ge... | Label a single matplotlib line at position x
Parameters
----------
line : matplotlib.lines.Line
The line holding the label
x : number
The location in data unit of the label
label : string, optional
The label to set. This is inferred from the line by default
kwargs : dict, optional
Optional arguments passed to ax.text | [
"Label",
"a",
"single",
"matplotlib",
"line",
"at",
"position",
"x"
] | 995e6d1003403b7493d02bc4b75122617d0f01a3 | https://github.com/cphyc/matplotlib-label-lines/blob/995e6d1003403b7493d02bc4b75122617d0f01a3/labellines/core.py#L9-L84 | train | 198,235 |
cphyc/matplotlib-label-lines | labellines/core.py | labelLines | def labelLines(lines, align=True, xvals=None, **kwargs):
'''Label all lines with their respective legends.
Parameters
----------
lines : list of matplotlib lines
The lines to label
align : boolean, optional
If True, the label will be aligned with the slope of the line
at the location of the label. If False, they will be horizontal.
xvals : (xfirst, xlast) or array of float, optional
The location of the labels. If a tuple, the labels will be
evenly spaced between xfirst and xlast (in the axis units).
kwargs : dict, optional
Optional arguments passed to ax.text
'''
ax = lines[0].axes
labLines = []
labels = []
# Take only the lines which have labels other than the default ones
for line in lines:
label = line.get_label()
if "_line" not in label:
labLines.append(line)
labels.append(label)
if xvals is None:
xvals = ax.get_xlim() # set axis limits as annotation limits, xvals now a tuple
if type(xvals) == tuple:
xmin, xmax = xvals
xscale = ax.get_xscale()
if xscale == "log":
xvals = np.logspace(np.log10(xmin), np.log10(xmax), len(labLines)+2)[1:-1]
else:
xvals = np.linspace(xmin, xmax, len(labLines)+2)[1:-1]
for line, x, label in zip(labLines, xvals, labels):
labelLine(line, x, label, align, **kwargs) | python | def labelLines(lines, align=True, xvals=None, **kwargs):
'''Label all lines with their respective legends.
Parameters
----------
lines : list of matplotlib lines
The lines to label
align : boolean, optional
If True, the label will be aligned with the slope of the line
at the location of the label. If False, they will be horizontal.
xvals : (xfirst, xlast) or array of float, optional
The location of the labels. If a tuple, the labels will be
evenly spaced between xfirst and xlast (in the axis units).
kwargs : dict, optional
Optional arguments passed to ax.text
'''
ax = lines[0].axes
labLines = []
labels = []
# Take only the lines which have labels other than the default ones
for line in lines:
label = line.get_label()
if "_line" not in label:
labLines.append(line)
labels.append(label)
if xvals is None:
xvals = ax.get_xlim() # set axis limits as annotation limits, xvals now a tuple
if type(xvals) == tuple:
xmin, xmax = xvals
xscale = ax.get_xscale()
if xscale == "log":
xvals = np.logspace(np.log10(xmin), np.log10(xmax), len(labLines)+2)[1:-1]
else:
xvals = np.linspace(xmin, xmax, len(labLines)+2)[1:-1]
for line, x, label in zip(labLines, xvals, labels):
labelLine(line, x, label, align, **kwargs) | [
"def",
"labelLines",
"(",
"lines",
",",
"align",
"=",
"True",
",",
"xvals",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ax",
"=",
"lines",
"[",
"0",
"]",
".",
"axes",
"labLines",
"=",
"[",
"]",
"labels",
"=",
"[",
"]",
"# Take only the lines w... | Label all lines with their respective legends.
Parameters
----------
lines : list of matplotlib lines
The lines to label
align : boolean, optional
If True, the label will be aligned with the slope of the line
at the location of the label. If False, they will be horizontal.
xvals : (xfirst, xlast) or array of float, optional
The location of the labels. If a tuple, the labels will be
evenly spaced between xfirst and xlast (in the axis units).
kwargs : dict, optional
Optional arguments passed to ax.text | [
"Label",
"all",
"lines",
"with",
"their",
"respective",
"legends",
"."
] | 995e6d1003403b7493d02bc4b75122617d0f01a3 | https://github.com/cphyc/matplotlib-label-lines/blob/995e6d1003403b7493d02bc4b75122617d0f01a3/labellines/core.py#L87-L125 | train | 198,236 |
kakwa/ldapcherry | misc/debug_lc.py | new_as_dict | def new_as_dict(self, raw=True, vars=None):
"""Convert an INI file to a dictionary"""
# Load INI file into a dict
result = {}
for section in self.sections():
if section not in result:
result[section] = {}
for option in self.options(section):
value = self.get(section, option, raw=raw, vars=vars)
try:
value = cherrypy.lib.reprconf.unrepr(value)
except Exception:
x = sys.exc_info()[1]
msg = ("Config error in section: %r, option: %r, "
"value: %r. Config values must be valid Python." %
(section, option, value))
raise ValueError(msg, x.__class__.__name__, x.args)
result[section][option] = value
return result | python | def new_as_dict(self, raw=True, vars=None):
"""Convert an INI file to a dictionary"""
# Load INI file into a dict
result = {}
for section in self.sections():
if section not in result:
result[section] = {}
for option in self.options(section):
value = self.get(section, option, raw=raw, vars=vars)
try:
value = cherrypy.lib.reprconf.unrepr(value)
except Exception:
x = sys.exc_info()[1]
msg = ("Config error in section: %r, option: %r, "
"value: %r. Config values must be valid Python." %
(section, option, value))
raise ValueError(msg, x.__class__.__name__, x.args)
result[section][option] = value
return result | [
"def",
"new_as_dict",
"(",
"self",
",",
"raw",
"=",
"True",
",",
"vars",
"=",
"None",
")",
":",
"# Load INI file into a dict",
"result",
"=",
"{",
"}",
"for",
"section",
"in",
"self",
".",
"sections",
"(",
")",
":",
"if",
"section",
"not",
"in",
"resul... | Convert an INI file to a dictionary | [
"Convert",
"an",
"INI",
"file",
"to",
"a",
"dictionary"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/misc/debug_lc.py#L13-L31 | train | 198,237 |
kakwa/ldapcherry | ldapcherry/backend/backendDemo.py | Backend.auth | def auth(self, username, password):
""" Check authentication against the backend
:param username: 'key' attribute of the user
:type username: string
:param password: password of the user
:type password: string
:rtype: boolean (True is authentication success, False otherwise)
"""
if username not in self.users:
return False
elif self.users[username][self.pwd_attr] == password:
return True
return False | python | def auth(self, username, password):
""" Check authentication against the backend
:param username: 'key' attribute of the user
:type username: string
:param password: password of the user
:type password: string
:rtype: boolean (True is authentication success, False otherwise)
"""
if username not in self.users:
return False
elif self.users[username][self.pwd_attr] == password:
return True
return False | [
"def",
"auth",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"if",
"username",
"not",
"in",
"self",
".",
"users",
":",
"return",
"False",
"elif",
"self",
".",
"users",
"[",
"username",
"]",
"[",
"self",
".",
"pwd_attr",
"]",
"==",
"passwor... | Check authentication against the backend
:param username: 'key' attribute of the user
:type username: string
:param password: password of the user
:type password: string
:rtype: boolean (True is authentication success, False otherwise) | [
"Check",
"authentication",
"against",
"the",
"backend"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendDemo.py#L79-L92 | train | 198,238 |
kakwa/ldapcherry | ldapcherry/backend/backendDemo.py | Backend.add_user | def add_user(self, attrs):
""" Add a user to the backend
:param attrs: attributes of the user
:type attrs: dict ({<attr>: <value>})
.. warning:: raise UserAlreadyExists if user already exists
"""
username = attrs[self.key]
if username in self.users:
raise UserAlreadyExists(username, self.backend_name)
self.users[username] = attrs
self.users[username]['groups'] = set([]) | python | def add_user(self, attrs):
""" Add a user to the backend
:param attrs: attributes of the user
:type attrs: dict ({<attr>: <value>})
.. warning:: raise UserAlreadyExists if user already exists
"""
username = attrs[self.key]
if username in self.users:
raise UserAlreadyExists(username, self.backend_name)
self.users[username] = attrs
self.users[username]['groups'] = set([]) | [
"def",
"add_user",
"(",
"self",
",",
"attrs",
")",
":",
"username",
"=",
"attrs",
"[",
"self",
".",
"key",
"]",
"if",
"username",
"in",
"self",
".",
"users",
":",
"raise",
"UserAlreadyExists",
"(",
"username",
",",
"self",
".",
"backend_name",
")",
"se... | Add a user to the backend
:param attrs: attributes of the user
:type attrs: dict ({<attr>: <value>})
.. warning:: raise UserAlreadyExists if user already exists | [
"Add",
"a",
"user",
"to",
"the",
"backend"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendDemo.py#L94-L106 | train | 198,239 |
kakwa/ldapcherry | ldapcherry/backend/backendDemo.py | Backend.del_user | def del_user(self, username):
""" Delete a user from the backend
:param username: 'key' attribute of the user
:type username: string
"""
self._check_fix_users(username)
try:
del self.users[username]
except Exception as e:
raise UserDoesntExist(username, self.backend_name) | python | def del_user(self, username):
""" Delete a user from the backend
:param username: 'key' attribute of the user
:type username: string
"""
self._check_fix_users(username)
try:
del self.users[username]
except Exception as e:
raise UserDoesntExist(username, self.backend_name) | [
"def",
"del_user",
"(",
"self",
",",
"username",
")",
":",
"self",
".",
"_check_fix_users",
"(",
"username",
")",
"try",
":",
"del",
"self",
".",
"users",
"[",
"username",
"]",
"except",
"Exception",
"as",
"e",
":",
"raise",
"UserDoesntExist",
"(",
"user... | Delete a user from the backend
:param username: 'key' attribute of the user
:type username: string | [
"Delete",
"a",
"user",
"from",
"the",
"backend"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendDemo.py#L108-L119 | train | 198,240 |
kakwa/ldapcherry | ldapcherry/backend/backendDemo.py | Backend.set_attrs | def set_attrs(self, username, attrs):
""" set a list of attributes for a given user
:param username: 'key' attribute of the user
:type username: string
:param attrs: attributes of the user
:type attrs: dict ({<attr>: <value>})
"""
self._check_fix_users(username)
for attr in attrs:
self.users[username][attr] = attrs[attr] | python | def set_attrs(self, username, attrs):
""" set a list of attributes for a given user
:param username: 'key' attribute of the user
:type username: string
:param attrs: attributes of the user
:type attrs: dict ({<attr>: <value>})
"""
self._check_fix_users(username)
for attr in attrs:
self.users[username][attr] = attrs[attr] | [
"def",
"set_attrs",
"(",
"self",
",",
"username",
",",
"attrs",
")",
":",
"self",
".",
"_check_fix_users",
"(",
"username",
")",
"for",
"attr",
"in",
"attrs",
":",
"self",
".",
"users",
"[",
"username",
"]",
"[",
"attr",
"]",
"=",
"attrs",
"[",
"attr... | set a list of attributes for a given user
:param username: 'key' attribute of the user
:type username: string
:param attrs: attributes of the user
:type attrs: dict ({<attr>: <value>}) | [
"set",
"a",
"list",
"of",
"attributes",
"for",
"a",
"given",
"user"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendDemo.py#L121-L131 | train | 198,241 |
kakwa/ldapcherry | ldapcherry/backend/backendDemo.py | Backend.add_to_groups | def add_to_groups(self, username, groups):
""" Add a user to a list of groups
:param username: 'key' attribute of the user
:type username: string
:param groups: list of groups
:type groups: list of strings
"""
self._check_fix_users(username)
current_groups = self.users[username]['groups']
new_groups = current_groups | set(groups)
self.users[username]['groups'] = new_groups | python | def add_to_groups(self, username, groups):
""" Add a user to a list of groups
:param username: 'key' attribute of the user
:type username: string
:param groups: list of groups
:type groups: list of strings
"""
self._check_fix_users(username)
current_groups = self.users[username]['groups']
new_groups = current_groups | set(groups)
self.users[username]['groups'] = new_groups | [
"def",
"add_to_groups",
"(",
"self",
",",
"username",
",",
"groups",
")",
":",
"self",
".",
"_check_fix_users",
"(",
"username",
")",
"current_groups",
"=",
"self",
".",
"users",
"[",
"username",
"]",
"[",
"'groups'",
"]",
"new_groups",
"=",
"current_groups"... | Add a user to a list of groups
:param username: 'key' attribute of the user
:type username: string
:param groups: list of groups
:type groups: list of strings | [
"Add",
"a",
"user",
"to",
"a",
"list",
"of",
"groups"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendDemo.py#L133-L144 | train | 198,242 |
kakwa/ldapcherry | ldapcherry/backend/backendDemo.py | Backend.search | def search(self, searchstring):
""" Search backend for users
:param searchstring: the search string
:type searchstring: string
:rtype: dict of dict ( {<user attr key>: {<attr>: <value>}} )
"""
ret = {}
for user in self.users:
match = False
for attr in self.search_attrs:
if attr not in self.users[user]:
pass
elif re.search(searchstring + '.*', self.users[user][attr]):
match = True
if match:
ret[user] = self.users[user]
return ret | python | def search(self, searchstring):
""" Search backend for users
:param searchstring: the search string
:type searchstring: string
:rtype: dict of dict ( {<user attr key>: {<attr>: <value>}} )
"""
ret = {}
for user in self.users:
match = False
for attr in self.search_attrs:
if attr not in self.users[user]:
pass
elif re.search(searchstring + '.*', self.users[user][attr]):
match = True
if match:
ret[user] = self.users[user]
return ret | [
"def",
"search",
"(",
"self",
",",
"searchstring",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"user",
"in",
"self",
".",
"users",
":",
"match",
"=",
"False",
"for",
"attr",
"in",
"self",
".",
"search_attrs",
":",
"if",
"attr",
"not",
"in",
"self",
".",... | Search backend for users
:param searchstring: the search string
:type searchstring: string
:rtype: dict of dict ( {<user attr key>: {<attr>: <value>}} ) | [
"Search",
"backend",
"for",
"users"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendDemo.py#L161-L178 | train | 198,243 |
kakwa/ldapcherry | ldapcherry/backend/backendDemo.py | Backend.get_user | def get_user(self, username):
""" Get a user's attributes
:param username: 'key' attribute of the user
:type username: string
:rtype: dict ( {<attr>: <value>} )
.. warning:: raise UserDoesntExist if user doesn't exist
"""
try:
return self.users[username]
except Exception as e:
raise UserDoesntExist(username, self.backend_name) | python | def get_user(self, username):
""" Get a user's attributes
:param username: 'key' attribute of the user
:type username: string
:rtype: dict ( {<attr>: <value>} )
.. warning:: raise UserDoesntExist if user doesn't exist
"""
try:
return self.users[username]
except Exception as e:
raise UserDoesntExist(username, self.backend_name) | [
"def",
"get_user",
"(",
"self",
",",
"username",
")",
":",
"try",
":",
"return",
"self",
".",
"users",
"[",
"username",
"]",
"except",
"Exception",
"as",
"e",
":",
"raise",
"UserDoesntExist",
"(",
"username",
",",
"self",
".",
"backend_name",
")"
] | Get a user's attributes
:param username: 'key' attribute of the user
:type username: string
:rtype: dict ( {<attr>: <value>} )
.. warning:: raise UserDoesntExist if user doesn't exist | [
"Get",
"a",
"user",
"s",
"attributes"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendDemo.py#L180-L192 | train | 198,244 |
kakwa/ldapcherry | ldapcherry/backend/backendDemo.py | Backend.get_groups | def get_groups(self, username):
""" Get a user's groups
:param username: 'key' attribute of the user
:type username: string
:rtype: list of groups
"""
try:
return self.users[username]['groups']
except Exception as e:
raise UserDoesntExist(username, self.backend_name) | python | def get_groups(self, username):
""" Get a user's groups
:param username: 'key' attribute of the user
:type username: string
:rtype: list of groups
"""
try:
return self.users[username]['groups']
except Exception as e:
raise UserDoesntExist(username, self.backend_name) | [
"def",
"get_groups",
"(",
"self",
",",
"username",
")",
":",
"try",
":",
"return",
"self",
".",
"users",
"[",
"username",
"]",
"[",
"'groups'",
"]",
"except",
"Exception",
"as",
"e",
":",
"raise",
"UserDoesntExist",
"(",
"username",
",",
"self",
".",
"... | Get a user's groups
:param username: 'key' attribute of the user
:type username: string
:rtype: list of groups | [
"Get",
"a",
"user",
"s",
"groups"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendDemo.py#L194-L204 | train | 198,245 |
kakwa/ldapcherry | ldapcherry/lclogging.py | get_loglevel | def get_loglevel(level):
""" return logging level object
corresponding to a given level passed as
a string
@str level: name of a syslog log level
@rtype: logging, logging level from logging module
"""
if level == 'debug':
return logging.DEBUG
elif level == 'notice':
return logging.INFO
elif level == 'info':
return logging.INFO
elif level == 'warning' or level == 'warn':
return logging.WARNING
elif level == 'error' or level == 'err':
return logging.ERROR
elif level == 'critical' or level == 'crit':
return logging.CRITICAL
elif level == 'alert':
return logging.CRITICAL
elif level == 'emergency' or level == 'emerg':
return logging.CRITICAL
else:
return logging.INFO | python | def get_loglevel(level):
""" return logging level object
corresponding to a given level passed as
a string
@str level: name of a syslog log level
@rtype: logging, logging level from logging module
"""
if level == 'debug':
return logging.DEBUG
elif level == 'notice':
return logging.INFO
elif level == 'info':
return logging.INFO
elif level == 'warning' or level == 'warn':
return logging.WARNING
elif level == 'error' or level == 'err':
return logging.ERROR
elif level == 'critical' or level == 'crit':
return logging.CRITICAL
elif level == 'alert':
return logging.CRITICAL
elif level == 'emergency' or level == 'emerg':
return logging.CRITICAL
else:
return logging.INFO | [
"def",
"get_loglevel",
"(",
"level",
")",
":",
"if",
"level",
"==",
"'debug'",
":",
"return",
"logging",
".",
"DEBUG",
"elif",
"level",
"==",
"'notice'",
":",
"return",
"logging",
".",
"INFO",
"elif",
"level",
"==",
"'info'",
":",
"return",
"logging",
".... | return logging level object
corresponding to a given level passed as
a string
@str level: name of a syslog log level
@rtype: logging, logging level from logging module | [
"return",
"logging",
"level",
"object",
"corresponding",
"to",
"a",
"given",
"level",
"passed",
"as",
"a",
"string"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/lclogging.py#L49-L73 | train | 198,246 |
kakwa/ldapcherry | ldapcherry/backend/backendLdap.py | Backend._normalize_group_attrs | def _normalize_group_attrs(self, attrs):
"""Normalize the attributes used to set groups
If it's a list of one element, it just become this
element.
It raises an error if the attribute doesn't exist
or if it's multivaluated.
"""
for key in self.group_attrs_keys:
if key not in attrs:
raise MissingGroupAttr(key)
if type(attrs[key]) is list and len(attrs[key]) == 1:
attrs[key] = attrs[key][0]
if type(attrs[key]) is list and len(attrs[key]) != 1:
raise MultivaluedGroupAttr(key) | python | def _normalize_group_attrs(self, attrs):
"""Normalize the attributes used to set groups
If it's a list of one element, it just become this
element.
It raises an error if the attribute doesn't exist
or if it's multivaluated.
"""
for key in self.group_attrs_keys:
if key not in attrs:
raise MissingGroupAttr(key)
if type(attrs[key]) is list and len(attrs[key]) == 1:
attrs[key] = attrs[key][0]
if type(attrs[key]) is list and len(attrs[key]) != 1:
raise MultivaluedGroupAttr(key) | [
"def",
"_normalize_group_attrs",
"(",
"self",
",",
"attrs",
")",
":",
"for",
"key",
"in",
"self",
".",
"group_attrs_keys",
":",
"if",
"key",
"not",
"in",
"attrs",
":",
"raise",
"MissingGroupAttr",
"(",
"key",
")",
"if",
"type",
"(",
"attrs",
"[",
"key",
... | Normalize the attributes used to set groups
If it's a list of one element, it just become this
element.
It raises an error if the attribute doesn't exist
or if it's multivaluated. | [
"Normalize",
"the",
"attributes",
"used",
"to",
"set",
"groups",
"If",
"it",
"s",
"a",
"list",
"of",
"one",
"element",
"it",
"just",
"become",
"this",
"element",
".",
"It",
"raises",
"an",
"error",
"if",
"the",
"attribute",
"doesn",
"t",
"exist",
"or",
... | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendLdap.py#L179-L192 | train | 198,247 |
kakwa/ldapcherry | ldapcherry/backend/backendLdap.py | Backend._connect | def _connect(self):
"""Initialize an ldap client"""
ldap_client = ldap.initialize(self.uri)
ldap.set_option(ldap.OPT_REFERRALS, 0)
ldap.set_option(ldap.OPT_TIMEOUT, self.timeout)
if self.starttls == 'on':
ldap.set_option(ldap.OPT_X_TLS_DEMAND, True)
else:
ldap.set_option(ldap.OPT_X_TLS_DEMAND, False)
# set the CA file if declared and if necessary
if self.ca and self.checkcert == 'on':
# check if the CA file actually exists
if os.path.isfile(self.ca):
ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.ca)
else:
raise CaFileDontExist(self.ca)
if self.checkcert == 'off':
# this is dark magic
# remove any of these two lines and it doesn't work
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
ldap_client.set_option(
ldap.OPT_X_TLS_REQUIRE_CERT,
ldap.OPT_X_TLS_NEVER
)
else:
# this is even darker magic
ldap_client.set_option(
ldap.OPT_X_TLS_REQUIRE_CERT,
ldap.OPT_X_TLS_DEMAND
)
# it doesn't make sense to set it to never
# (== don't check certifate)
# but it only works with this option...
# ... and it checks the certificat
# (I've lost my sanity over this)
ldap.set_option(
ldap.OPT_X_TLS_REQUIRE_CERT,
ldap.OPT_X_TLS_NEVER
)
if self.starttls == 'on':
try:
ldap_client.start_tls_s()
except Exception as e:
self._exception_handler(e)
return ldap_client | python | def _connect(self):
"""Initialize an ldap client"""
ldap_client = ldap.initialize(self.uri)
ldap.set_option(ldap.OPT_REFERRALS, 0)
ldap.set_option(ldap.OPT_TIMEOUT, self.timeout)
if self.starttls == 'on':
ldap.set_option(ldap.OPT_X_TLS_DEMAND, True)
else:
ldap.set_option(ldap.OPT_X_TLS_DEMAND, False)
# set the CA file if declared and if necessary
if self.ca and self.checkcert == 'on':
# check if the CA file actually exists
if os.path.isfile(self.ca):
ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.ca)
else:
raise CaFileDontExist(self.ca)
if self.checkcert == 'off':
# this is dark magic
# remove any of these two lines and it doesn't work
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
ldap_client.set_option(
ldap.OPT_X_TLS_REQUIRE_CERT,
ldap.OPT_X_TLS_NEVER
)
else:
# this is even darker magic
ldap_client.set_option(
ldap.OPT_X_TLS_REQUIRE_CERT,
ldap.OPT_X_TLS_DEMAND
)
# it doesn't make sense to set it to never
# (== don't check certifate)
# but it only works with this option...
# ... and it checks the certificat
# (I've lost my sanity over this)
ldap.set_option(
ldap.OPT_X_TLS_REQUIRE_CERT,
ldap.OPT_X_TLS_NEVER
)
if self.starttls == 'on':
try:
ldap_client.start_tls_s()
except Exception as e:
self._exception_handler(e)
return ldap_client | [
"def",
"_connect",
"(",
"self",
")",
":",
"ldap_client",
"=",
"ldap",
".",
"initialize",
"(",
"self",
".",
"uri",
")",
"ldap",
".",
"set_option",
"(",
"ldap",
".",
"OPT_REFERRALS",
",",
"0",
")",
"ldap",
".",
"set_option",
"(",
"ldap",
".",
"OPT_TIMEOU... | Initialize an ldap client | [
"Initialize",
"an",
"ldap",
"client"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendLdap.py#L194-L238 | train | 198,248 |
kakwa/ldapcherry | ldapcherry/backend/backendLdap.py | Backend._bind | def _bind(self):
"""bind to the ldap with the technical account"""
ldap_client = self._connect()
try:
ldap_client.simple_bind_s(self.binddn, self.bindpassword)
except Exception as e:
ldap_client.unbind_s()
self._exception_handler(e)
return ldap_client | python | def _bind(self):
"""bind to the ldap with the technical account"""
ldap_client = self._connect()
try:
ldap_client.simple_bind_s(self.binddn, self.bindpassword)
except Exception as e:
ldap_client.unbind_s()
self._exception_handler(e)
return ldap_client | [
"def",
"_bind",
"(",
"self",
")",
":",
"ldap_client",
"=",
"self",
".",
"_connect",
"(",
")",
"try",
":",
"ldap_client",
".",
"simple_bind_s",
"(",
"self",
".",
"binddn",
",",
"self",
".",
"bindpassword",
")",
"except",
"Exception",
"as",
"e",
":",
"ld... | bind to the ldap with the technical account | [
"bind",
"to",
"the",
"ldap",
"with",
"the",
"technical",
"account"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendLdap.py#L240-L248 | train | 198,249 |
kakwa/ldapcherry | ldapcherry/backend/backendLdap.py | Backend._get_user | def _get_user(self, username, attrs=ALL_ATTRS):
"""Get a user from the ldap"""
username = ldap.filter.escape_filter_chars(username)
user_filter = self.user_filter_tmpl % {
'username': self._uni(username)
}
r = self._search(self._byte_p2(user_filter), attrs, self.userdn)
if len(r) == 0:
return None
# if NO_ATTR, only return the DN
if attrs == NO_ATTR:
dn_entry = r[0][0]
# in other cases, return everything (dn + attributes)
else:
dn_entry = r[0]
return dn_entry | python | def _get_user(self, username, attrs=ALL_ATTRS):
"""Get a user from the ldap"""
username = ldap.filter.escape_filter_chars(username)
user_filter = self.user_filter_tmpl % {
'username': self._uni(username)
}
r = self._search(self._byte_p2(user_filter), attrs, self.userdn)
if len(r) == 0:
return None
# if NO_ATTR, only return the DN
if attrs == NO_ATTR:
dn_entry = r[0][0]
# in other cases, return everything (dn + attributes)
else:
dn_entry = r[0]
return dn_entry | [
"def",
"_get_user",
"(",
"self",
",",
"username",
",",
"attrs",
"=",
"ALL_ATTRS",
")",
":",
"username",
"=",
"ldap",
".",
"filter",
".",
"escape_filter_chars",
"(",
"username",
")",
"user_filter",
"=",
"self",
".",
"user_filter_tmpl",
"%",
"{",
"'username'",... | Get a user from the ldap | [
"Get",
"a",
"user",
"from",
"the",
"ldap"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendLdap.py#L308-L326 | train | 198,250 |
kakwa/ldapcherry | ldapcherry/backend/backendLdap.py | Backend.auth | def auth(self, username, password):
"""Authentication of a user"""
binddn = self._get_user(self._byte_p2(username), NO_ATTR)
if binddn is not None:
ldap_client = self._connect()
try:
ldap_client.simple_bind_s(
self._byte_p2(binddn),
self._byte_p2(password)
)
except ldap.INVALID_CREDENTIALS:
ldap_client.unbind_s()
return False
ldap_client.unbind_s()
return True
else:
return False | python | def auth(self, username, password):
"""Authentication of a user"""
binddn = self._get_user(self._byte_p2(username), NO_ATTR)
if binddn is not None:
ldap_client = self._connect()
try:
ldap_client.simple_bind_s(
self._byte_p2(binddn),
self._byte_p2(password)
)
except ldap.INVALID_CREDENTIALS:
ldap_client.unbind_s()
return False
ldap_client.unbind_s()
return True
else:
return False | [
"def",
"auth",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"binddn",
"=",
"self",
".",
"_get_user",
"(",
"self",
".",
"_byte_p2",
"(",
"username",
")",
",",
"NO_ATTR",
")",
"if",
"binddn",
"is",
"not",
"None",
":",
"ldap_client",
"=",
"s... | Authentication of a user | [
"Authentication",
"of",
"a",
"user"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendLdap.py#L399-L416 | train | 198,251 |
kakwa/ldapcherry | ldapcherry/backend/backendLdap.py | Backend.add_user | def add_user(self, attrs):
"""add a user"""
ldap_client = self._bind()
# encoding crap
attrs_srt = self.attrs_pretreatment(attrs)
attrs_srt[self._byte_p2('objectClass')] = self.objectclasses
# construct is DN
dn = \
self._byte_p2(self.dn_user_attr) + \
self._byte_p2('=') + \
self._byte_p2(ldap.dn.escape_dn_chars(
attrs[self.dn_user_attr]
)
) + \
self._byte_p2(',') + \
self._byte_p2(self.userdn)
# gen the ldif first add_s and add the user
ldif = modlist.addModlist(attrs_srt)
try:
ldap_client.add_s(dn, ldif)
except ldap.ALREADY_EXISTS as e:
raise UserAlreadyExists(attrs[self.key], self.backend_name)
except Exception as e:
ldap_client.unbind_s()
self._exception_handler(e)
ldap_client.unbind_s() | python | def add_user(self, attrs):
"""add a user"""
ldap_client = self._bind()
# encoding crap
attrs_srt = self.attrs_pretreatment(attrs)
attrs_srt[self._byte_p2('objectClass')] = self.objectclasses
# construct is DN
dn = \
self._byte_p2(self.dn_user_attr) + \
self._byte_p2('=') + \
self._byte_p2(ldap.dn.escape_dn_chars(
attrs[self.dn_user_attr]
)
) + \
self._byte_p2(',') + \
self._byte_p2(self.userdn)
# gen the ldif first add_s and add the user
ldif = modlist.addModlist(attrs_srt)
try:
ldap_client.add_s(dn, ldif)
except ldap.ALREADY_EXISTS as e:
raise UserAlreadyExists(attrs[self.key], self.backend_name)
except Exception as e:
ldap_client.unbind_s()
self._exception_handler(e)
ldap_client.unbind_s() | [
"def",
"add_user",
"(",
"self",
",",
"attrs",
")",
":",
"ldap_client",
"=",
"self",
".",
"_bind",
"(",
")",
"# encoding crap",
"attrs_srt",
"=",
"self",
".",
"attrs_pretreatment",
"(",
"attrs",
")",
"attrs_srt",
"[",
"self",
".",
"_byte_p2",
"(",
"'objectC... | add a user | [
"add",
"a",
"user"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendLdap.py#L428-L454 | train | 198,252 |
kakwa/ldapcherry | ldapcherry/backend/backendLdap.py | Backend.del_user | def del_user(self, username):
"""delete a user"""
ldap_client = self._bind()
# recover the user dn
dn = self._byte_p2(self._get_user(self._byte_p2(username), NO_ATTR))
# delete
if dn is not None:
ldap_client.delete_s(dn)
else:
ldap_client.unbind_s()
raise UserDoesntExist(username, self.backend_name)
ldap_client.unbind_s() | python | def del_user(self, username):
"""delete a user"""
ldap_client = self._bind()
# recover the user dn
dn = self._byte_p2(self._get_user(self._byte_p2(username), NO_ATTR))
# delete
if dn is not None:
ldap_client.delete_s(dn)
else:
ldap_client.unbind_s()
raise UserDoesntExist(username, self.backend_name)
ldap_client.unbind_s() | [
"def",
"del_user",
"(",
"self",
",",
"username",
")",
":",
"ldap_client",
"=",
"self",
".",
"_bind",
"(",
")",
"# recover the user dn",
"dn",
"=",
"self",
".",
"_byte_p2",
"(",
"self",
".",
"_get_user",
"(",
"self",
".",
"_byte_p2",
"(",
"username",
")",... | delete a user | [
"delete",
"a",
"user"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendLdap.py#L456-L467 | train | 198,253 |
kakwa/ldapcherry | ldapcherry/backend/backendLdap.py | Backend.set_attrs | def set_attrs(self, username, attrs):
""" set user attributes"""
ldap_client = self._bind()
tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
if tmp is None:
raise UserDoesntExist(username, self.backend_name)
dn = self._byte_p2(tmp[0])
old_attrs = tmp[1]
for attr in attrs:
bcontent = self._byte_p2(attrs[attr])
battr = self._byte_p2(attr)
new = {battr: self._modlist(self._byte_p3(bcontent))}
# if attr is dn entry, use rename
if attr.lower() == self.dn_user_attr.lower():
ldap_client.rename_s(
dn,
ldap.dn.dn2str([[(battr, bcontent, 1)]])
)
dn = ldap.dn.dn2str(
[[(battr, bcontent, 1)]] + ldap.dn.str2dn(dn)[1:]
)
else:
# if attr is already set, replace the value
# (see dict old passed to modifyModlist)
if attr in old_attrs:
if type(old_attrs[attr]) is list:
tmp = []
for value in old_attrs[attr]:
tmp.append(self._byte_p2(value))
bold_value = tmp
else:
bold_value = self._modlist(
self._byte_p3(old_attrs[attr])
)
old = {battr: bold_value}
# attribute is not set, just add it
else:
old = {}
ldif = modlist.modifyModlist(old, new)
if ldif:
try:
ldap_client.modify_s(dn, ldif)
except Exception as e:
ldap_client.unbind_s()
self._exception_handler(e)
ldap_client.unbind_s() | python | def set_attrs(self, username, attrs):
""" set user attributes"""
ldap_client = self._bind()
tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
if tmp is None:
raise UserDoesntExist(username, self.backend_name)
dn = self._byte_p2(tmp[0])
old_attrs = tmp[1]
for attr in attrs:
bcontent = self._byte_p2(attrs[attr])
battr = self._byte_p2(attr)
new = {battr: self._modlist(self._byte_p3(bcontent))}
# if attr is dn entry, use rename
if attr.lower() == self.dn_user_attr.lower():
ldap_client.rename_s(
dn,
ldap.dn.dn2str([[(battr, bcontent, 1)]])
)
dn = ldap.dn.dn2str(
[[(battr, bcontent, 1)]] + ldap.dn.str2dn(dn)[1:]
)
else:
# if attr is already set, replace the value
# (see dict old passed to modifyModlist)
if attr in old_attrs:
if type(old_attrs[attr]) is list:
tmp = []
for value in old_attrs[attr]:
tmp.append(self._byte_p2(value))
bold_value = tmp
else:
bold_value = self._modlist(
self._byte_p3(old_attrs[attr])
)
old = {battr: bold_value}
# attribute is not set, just add it
else:
old = {}
ldif = modlist.modifyModlist(old, new)
if ldif:
try:
ldap_client.modify_s(dn, ldif)
except Exception as e:
ldap_client.unbind_s()
self._exception_handler(e)
ldap_client.unbind_s() | [
"def",
"set_attrs",
"(",
"self",
",",
"username",
",",
"attrs",
")",
":",
"ldap_client",
"=",
"self",
".",
"_bind",
"(",
")",
"tmp",
"=",
"self",
".",
"_get_user",
"(",
"self",
".",
"_byte_p2",
"(",
"username",
")",
",",
"ALL_ATTRS",
")",
"if",
"tmp"... | set user attributes | [
"set",
"user",
"attributes"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendLdap.py#L469-L515 | train | 198,254 |
kakwa/ldapcherry | ldapcherry/backend/backendLdap.py | Backend.del_from_groups | def del_from_groups(self, username, groups):
"""Delete user from groups"""
# it follows the same logic than add_to_groups
# but with MOD_DELETE
ldap_client = self._bind()
tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
if tmp is None:
raise UserDoesntExist(username, self.backend_name)
dn = tmp[0]
attrs = tmp[1]
attrs['dn'] = dn
self._normalize_group_attrs(attrs)
dn = self._byte_p2(tmp[0])
for group in groups:
group = self._byte_p2(group)
for attr in self.group_attrs:
content = self._byte_p2(self.group_attrs[attr] % attrs)
ldif = [(ldap.MOD_DELETE, attr, self._byte_p3(content))]
try:
ldap_client.modify_s(group, ldif)
except ldap.NO_SUCH_ATTRIBUTE as e:
self._logger(
severity=logging.INFO,
msg="%(backend)s: user '%(user)s'"
" wasn't member of group '%(group)s'"
" (attribute '%(attr)s')" % {
'user': username,
'group': self._uni(group),
'attr': attr,
'backend': self.backend_name
}
)
except Exception as e:
ldap_client.unbind_s()
self._exception_handler(e)
ldap_client.unbind_s() | python | def del_from_groups(self, username, groups):
"""Delete user from groups"""
# it follows the same logic than add_to_groups
# but with MOD_DELETE
ldap_client = self._bind()
tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
if tmp is None:
raise UserDoesntExist(username, self.backend_name)
dn = tmp[0]
attrs = tmp[1]
attrs['dn'] = dn
self._normalize_group_attrs(attrs)
dn = self._byte_p2(tmp[0])
for group in groups:
group = self._byte_p2(group)
for attr in self.group_attrs:
content = self._byte_p2(self.group_attrs[attr] % attrs)
ldif = [(ldap.MOD_DELETE, attr, self._byte_p3(content))]
try:
ldap_client.modify_s(group, ldif)
except ldap.NO_SUCH_ATTRIBUTE as e:
self._logger(
severity=logging.INFO,
msg="%(backend)s: user '%(user)s'"
" wasn't member of group '%(group)s'"
" (attribute '%(attr)s')" % {
'user': username,
'group': self._uni(group),
'attr': attr,
'backend': self.backend_name
}
)
except Exception as e:
ldap_client.unbind_s()
self._exception_handler(e)
ldap_client.unbind_s() | [
"def",
"del_from_groups",
"(",
"self",
",",
"username",
",",
"groups",
")",
":",
"# it follows the same logic than add_to_groups",
"# but with MOD_DELETE",
"ldap_client",
"=",
"self",
".",
"_bind",
"(",
")",
"tmp",
"=",
"self",
".",
"_get_user",
"(",
"self",
".",
... | Delete user from groups | [
"Delete",
"user",
"from",
"groups"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendLdap.py#L572-L607 | train | 198,255 |
kakwa/ldapcherry | ldapcherry/backend/backendLdap.py | Backend.get_user | def get_user(self, username):
"""Gest a specific user"""
ret = {}
tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
if tmp is None:
raise UserDoesntExist(username, self.backend_name)
attrs_tmp = tmp[1]
for attr in attrs_tmp:
value_tmp = attrs_tmp[attr]
if len(value_tmp) == 1:
ret[attr] = value_tmp[0]
else:
ret[attr] = value_tmp
return ret | python | def get_user(self, username):
"""Gest a specific user"""
ret = {}
tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
if tmp is None:
raise UserDoesntExist(username, self.backend_name)
attrs_tmp = tmp[1]
for attr in attrs_tmp:
value_tmp = attrs_tmp[attr]
if len(value_tmp) == 1:
ret[attr] = value_tmp[0]
else:
ret[attr] = value_tmp
return ret | [
"def",
"get_user",
"(",
"self",
",",
"username",
")",
":",
"ret",
"=",
"{",
"}",
"tmp",
"=",
"self",
".",
"_get_user",
"(",
"self",
".",
"_byte_p2",
"(",
"username",
")",
",",
"ALL_ATTRS",
")",
"if",
"tmp",
"is",
"None",
":",
"raise",
"UserDoesntExis... | Gest a specific user | [
"Gest",
"a",
"specific",
"user"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendLdap.py#L636-L649 | train | 198,256 |
kakwa/ldapcherry | ldapcherry/backend/backendLdap.py | Backend.get_groups | def get_groups(self, username):
"""Get all groups of a user"""
username = ldap.filter.escape_filter_chars(self._byte_p2(username))
userdn = self._get_user(username, NO_ATTR)
searchfilter = self.group_filter_tmpl % {
'userdn': userdn,
'username': username
}
groups = self._search(searchfilter, NO_ATTR, self.groupdn)
ret = []
for entry in groups:
ret.append(self._uni(entry[0]))
return ret | python | def get_groups(self, username):
"""Get all groups of a user"""
username = ldap.filter.escape_filter_chars(self._byte_p2(username))
userdn = self._get_user(username, NO_ATTR)
searchfilter = self.group_filter_tmpl % {
'userdn': userdn,
'username': username
}
groups = self._search(searchfilter, NO_ATTR, self.groupdn)
ret = []
for entry in groups:
ret.append(self._uni(entry[0]))
return ret | [
"def",
"get_groups",
"(",
"self",
",",
"username",
")",
":",
"username",
"=",
"ldap",
".",
"filter",
".",
"escape_filter_chars",
"(",
"self",
".",
"_byte_p2",
"(",
"username",
")",
")",
"userdn",
"=",
"self",
".",
"_get_user",
"(",
"username",
",",
"NO_A... | Get all groups of a user | [
"Get",
"all",
"groups",
"of",
"a",
"user"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendLdap.py#L651-L665 | train | 198,257 |
kakwa/ldapcherry | ldapcherry/roles.py | Roles._merge_groups | def _merge_groups(self, backends_list):
""" merge a list backends_groups"""
ret = {}
for backends in backends_list:
for b in backends:
if b not in ret:
ret[b] = set([])
for group in backends[b]:
ret[b].add(group)
for b in ret:
ret[b] = list(ret[b])
ret[b].sort()
return ret | python | def _merge_groups(self, backends_list):
""" merge a list backends_groups"""
ret = {}
for backends in backends_list:
for b in backends:
if b not in ret:
ret[b] = set([])
for group in backends[b]:
ret[b].add(group)
for b in ret:
ret[b] = list(ret[b])
ret[b].sort()
return ret | [
"def",
"_merge_groups",
"(",
"self",
",",
"backends_list",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"backends",
"in",
"backends_list",
":",
"for",
"b",
"in",
"backends",
":",
"if",
"b",
"not",
"in",
"ret",
":",
"ret",
"[",
"b",
"]",
"=",
"set",
"(",
... | merge a list backends_groups | [
"merge",
"a",
"list",
"backends_groups"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/roles.py#L50-L62 | train | 198,258 |
kakwa/ldapcherry | ldapcherry/roles.py | Roles._is_parent | def _is_parent(self, roleid1, roleid2):
"""Test if roleid1 is contained inside roleid2"""
role2 = copy.deepcopy(self.flatten[roleid2])
role1 = copy.deepcopy(self.flatten[roleid1])
if role1 == role2:
return False
# Check if role1 is contained by role2
for b1 in role1['backends_groups']:
if b1 not in role2['backends_groups']:
return False
for group in role1['backends_groups'][b1]:
if group not in role2['backends_groups'][b1]:
return False
# If role2 is inside role1, roles are equal, throw exception
for b2 in role2['backends_groups']:
if b2 not in role1['backends_groups']:
return True
for group in role2['backends_groups'][b2]:
if group not in role1['backends_groups'][b2]:
return True
raise DumplicateRoleContent(roleid1, roleid2) | python | def _is_parent(self, roleid1, roleid2):
"""Test if roleid1 is contained inside roleid2"""
role2 = copy.deepcopy(self.flatten[roleid2])
role1 = copy.deepcopy(self.flatten[roleid1])
if role1 == role2:
return False
# Check if role1 is contained by role2
for b1 in role1['backends_groups']:
if b1 not in role2['backends_groups']:
return False
for group in role1['backends_groups'][b1]:
if group not in role2['backends_groups'][b1]:
return False
# If role2 is inside role1, roles are equal, throw exception
for b2 in role2['backends_groups']:
if b2 not in role1['backends_groups']:
return True
for group in role2['backends_groups'][b2]:
if group not in role1['backends_groups'][b2]:
return True
raise DumplicateRoleContent(roleid1, roleid2) | [
"def",
"_is_parent",
"(",
"self",
",",
"roleid1",
",",
"roleid2",
")",
":",
"role2",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"flatten",
"[",
"roleid2",
"]",
")",
"role1",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"flatten",
"[",
"roleid... | Test if roleid1 is contained inside roleid2 | [
"Test",
"if",
"roleid1",
"is",
"contained",
"inside",
"roleid2"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/roles.py#L90-L114 | train | 198,259 |
kakwa/ldapcherry | ldapcherry/roles.py | Roles.get_groups_to_remove | def get_groups_to_remove(self, current_roles, roles_to_remove):
"""get groups to remove from list of
roles to remove and current roles
"""
current_roles = set(current_roles)
ret = {}
roles_to_remove = set(roles_to_remove)
tmp = set([])
# get sub roles of the role to remove that the user belongs to
# if we remove a role, there is no reason to keep the sub roles
for r in roles_to_remove:
for sr in self._get_subroles(r):
if sr not in roles_to_remove and sr in current_roles:
tmp.add(sr)
roles_to_remove = roles_to_remove.union(tmp)
roles = current_roles.difference(set(roles_to_remove))
groups_roles = self._get_groups(roles)
groups_roles_to_remove = self._get_groups(roles_to_remove)
# if groups belongs to roles the user keeps, don't remove it
for b in groups_roles_to_remove:
if b in groups_roles:
groups_roles_to_remove[b] = \
groups_roles_to_remove[b].difference(groups_roles[b])
return groups_roles_to_remove | python | def get_groups_to_remove(self, current_roles, roles_to_remove):
"""get groups to remove from list of
roles to remove and current roles
"""
current_roles = set(current_roles)
ret = {}
roles_to_remove = set(roles_to_remove)
tmp = set([])
# get sub roles of the role to remove that the user belongs to
# if we remove a role, there is no reason to keep the sub roles
for r in roles_to_remove:
for sr in self._get_subroles(r):
if sr not in roles_to_remove and sr in current_roles:
tmp.add(sr)
roles_to_remove = roles_to_remove.union(tmp)
roles = current_roles.difference(set(roles_to_remove))
groups_roles = self._get_groups(roles)
groups_roles_to_remove = self._get_groups(roles_to_remove)
# if groups belongs to roles the user keeps, don't remove it
for b in groups_roles_to_remove:
if b in groups_roles:
groups_roles_to_remove[b] = \
groups_roles_to_remove[b].difference(groups_roles[b])
return groups_roles_to_remove | [
"def",
"get_groups_to_remove",
"(",
"self",
",",
"current_roles",
",",
"roles_to_remove",
")",
":",
"current_roles",
"=",
"set",
"(",
"current_roles",
")",
"ret",
"=",
"{",
"}",
"roles_to_remove",
"=",
"set",
"(",
"roles_to_remove",
")",
"tmp",
"=",
"set",
"... | get groups to remove from list of
roles to remove and current roles | [
"get",
"groups",
"to",
"remove",
"from",
"list",
"of",
"roles",
"to",
"remove",
"and",
"current",
"roles"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/roles.py#L256-L282 | train | 198,260 |
kakwa/ldapcherry | ldapcherry/roles.py | Roles.get_roles | def get_roles(self, groups):
"""get list of roles and list of standalone groups"""
roles = set([])
parentroles = set([])
notroles = set([])
tmp = set([])
usedgroups = {}
unusedgroups = {}
ret = {}
# determine roles membership
for role in self.roles:
if self._check_member(
role, groups, notroles,
tmp, parentroles, usedgroups):
roles.add(role)
# determine standalone groups not matching any roles
for b in groups:
for g in groups[b]:
if b not in usedgroups or g not in usedgroups[b]:
if b not in unusedgroups:
unusedgroups[b] = set([])
unusedgroups[b].add(g)
ret['roles'] = roles
ret['unusedgroups'] = unusedgroups
return ret | python | def get_roles(self, groups):
"""get list of roles and list of standalone groups"""
roles = set([])
parentroles = set([])
notroles = set([])
tmp = set([])
usedgroups = {}
unusedgroups = {}
ret = {}
# determine roles membership
for role in self.roles:
if self._check_member(
role, groups, notroles,
tmp, parentroles, usedgroups):
roles.add(role)
# determine standalone groups not matching any roles
for b in groups:
for g in groups[b]:
if b not in usedgroups or g not in usedgroups[b]:
if b not in unusedgroups:
unusedgroups[b] = set([])
unusedgroups[b].add(g)
ret['roles'] = roles
ret['unusedgroups'] = unusedgroups
return ret | [
"def",
"get_roles",
"(",
"self",
",",
"groups",
")",
":",
"roles",
"=",
"set",
"(",
"[",
"]",
")",
"parentroles",
"=",
"set",
"(",
"[",
"]",
")",
"notroles",
"=",
"set",
"(",
"[",
"]",
")",
"tmp",
"=",
"set",
"(",
"[",
"]",
")",
"usedgroups",
... | get list of roles and list of standalone groups | [
"get",
"list",
"of",
"roles",
"and",
"list",
"of",
"standalone",
"groups"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/roles.py#L302-L327 | train | 198,261 |
kakwa/ldapcherry | ldapcherry/roles.py | Roles.get_display_name | def get_display_name(self, role):
"""get the display name of a role"""
if role not in self.flatten:
raise MissingRole(role)
return self.flatten[role]['display_name'] | python | def get_display_name(self, role):
"""get the display name of a role"""
if role not in self.flatten:
raise MissingRole(role)
return self.flatten[role]['display_name'] | [
"def",
"get_display_name",
"(",
"self",
",",
"role",
")",
":",
"if",
"role",
"not",
"in",
"self",
".",
"flatten",
":",
"raise",
"MissingRole",
"(",
"role",
")",
"return",
"self",
".",
"flatten",
"[",
"role",
"]",
"[",
"'display_name'",
"]"
] | get the display name of a role | [
"get",
"the",
"display",
"name",
"of",
"a",
"role"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/roles.py#L333-L337 | train | 198,262 |
kakwa/ldapcherry | ldapcherry/roles.py | Roles.get_groups | def get_groups(self, roles):
"""get the list of groups from role"""
ret = {}
for role in roles:
if role not in self.flatten:
raise MissingRole(role)
for b in self.flatten[role]['backends_groups']:
if b not in ret:
ret[b] = []
ret[b] = ret[b] + self.flatten[role]['backends_groups'][b]
return ret | python | def get_groups(self, roles):
"""get the list of groups from role"""
ret = {}
for role in roles:
if role not in self.flatten:
raise MissingRole(role)
for b in self.flatten[role]['backends_groups']:
if b not in ret:
ret[b] = []
ret[b] = ret[b] + self.flatten[role]['backends_groups'][b]
return ret | [
"def",
"get_groups",
"(",
"self",
",",
"roles",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"role",
"in",
"roles",
":",
"if",
"role",
"not",
"in",
"self",
".",
"flatten",
":",
"raise",
"MissingRole",
"(",
"role",
")",
"for",
"b",
"in",
"self",
".",
"f... | get the list of groups from role | [
"get",
"the",
"list",
"of",
"groups",
"from",
"role"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/roles.py#L339-L349 | train | 198,263 |
kakwa/ldapcherry | ldapcherry/roles.py | Roles.is_admin | def is_admin(self, roles):
"""determine from a list of roles if is ldapcherry administrator"""
for r in roles:
if r in self.admin_roles:
return True
return False | python | def is_admin(self, roles):
"""determine from a list of roles if is ldapcherry administrator"""
for r in roles:
if r in self.admin_roles:
return True
return False | [
"def",
"is_admin",
"(",
"self",
",",
"roles",
")",
":",
"for",
"r",
"in",
"roles",
":",
"if",
"r",
"in",
"self",
".",
"admin_roles",
":",
"return",
"True",
"return",
"False"
] | determine from a list of roles if is ldapcherry administrator | [
"determine",
"from",
"a",
"list",
"of",
"roles",
"if",
"is",
"ldapcherry",
"administrator"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/roles.py#L351-L356 | train | 198,264 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry._get_param | def _get_param(self, section, key, config, default=None):
""" Get configuration parameter "key" from config
@str section: the section of the config file
@str key: the key to get
@dict config: the configuration (dictionnary)
@str default: the default value if parameter "key" is not present
@rtype: str (value of config['key'] if present default otherwith
"""
if section in config and key in config[section]:
return config[section][key]
if default is not None:
return default
else:
raise MissingParameter(section, key) | python | def _get_param(self, section, key, config, default=None):
""" Get configuration parameter "key" from config
@str section: the section of the config file
@str key: the key to get
@dict config: the configuration (dictionnary)
@str default: the default value if parameter "key" is not present
@rtype: str (value of config['key'] if present default otherwith
"""
if section in config and key in config[section]:
return config[section][key]
if default is not None:
return default
else:
raise MissingParameter(section, key) | [
"def",
"_get_param",
"(",
"self",
",",
"section",
",",
"key",
",",
"config",
",",
"default",
"=",
"None",
")",
":",
"if",
"section",
"in",
"config",
"and",
"key",
"in",
"config",
"[",
"section",
"]",
":",
"return",
"config",
"[",
"section",
"]",
"[",... | Get configuration parameter "key" from config
@str section: the section of the config file
@str key: the key to get
@dict config: the configuration (dictionnary)
@str default: the default value if parameter "key" is not present
@rtype: str (value of config['key'] if present default otherwith | [
"Get",
"configuration",
"parameter",
"key",
"from",
"config"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L63-L76 | train | 198,265 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry._get_groups | def _get_groups(self, username):
""" Get groups of a user
@str username: name of the user
@rtype: dict, format { '<backend>': [<list of groups>] }
"""
ret = {}
for b in self.backends:
ret[b] = self.backends[b].get_groups(username)
cherrypy.log.error(
msg="user '" + username + "' groups: " + str(ret),
severity=logging.DEBUG,
)
return ret | python | def _get_groups(self, username):
""" Get groups of a user
@str username: name of the user
@rtype: dict, format { '<backend>': [<list of groups>] }
"""
ret = {}
for b in self.backends:
ret[b] = self.backends[b].get_groups(username)
cherrypy.log.error(
msg="user '" + username + "' groups: " + str(ret),
severity=logging.DEBUG,
)
return ret | [
"def",
"_get_groups",
"(",
"self",
",",
"username",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"b",
"in",
"self",
".",
"backends",
":",
"ret",
"[",
"b",
"]",
"=",
"self",
".",
"backends",
"[",
"b",
"]",
".",
"get_groups",
"(",
"username",
")",
"cherr... | Get groups of a user
@str username: name of the user
@rtype: dict, format { '<backend>': [<list of groups>] } | [
"Get",
"groups",
"of",
"a",
"user"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L78-L90 | train | 198,266 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry._get_roles | def _get_roles(self, username):
""" Get roles of a user
@str username: name of the user
@rtype: dict, format { 'roles': [<list of roles>],
'unusedgroups': [<list of groups not matching roles>] }
"""
groups = self._get_groups(username)
user_roles = self.roles.get_roles(groups)
cherrypy.log.error(
msg="user '" + username + "' roles: " + str(user_roles),
severity=logging.DEBUG,
)
return user_roles | python | def _get_roles(self, username):
""" Get roles of a user
@str username: name of the user
@rtype: dict, format { 'roles': [<list of roles>],
'unusedgroups': [<list of groups not matching roles>] }
"""
groups = self._get_groups(username)
user_roles = self.roles.get_roles(groups)
cherrypy.log.error(
msg="user '" + username + "' roles: " + str(user_roles),
severity=logging.DEBUG,
)
return user_roles | [
"def",
"_get_roles",
"(",
"self",
",",
"username",
")",
":",
"groups",
"=",
"self",
".",
"_get_groups",
"(",
"username",
")",
"user_roles",
"=",
"self",
".",
"roles",
".",
"get_roles",
"(",
"groups",
")",
"cherrypy",
".",
"log",
".",
"error",
"(",
"msg... | Get roles of a user
@str username: name of the user
@rtype: dict, format { 'roles': [<list of roles>],
'unusedgroups': [<list of groups not matching roles>] } | [
"Get",
"roles",
"of",
"a",
"user"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L92-L104 | train | 198,267 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry._is_admin | def _is_admin(self, username):
""" Check if a user is an ldapcherry administrator
@str username: name of the user
@rtype: bool, True if administrator, False otherwise
"""
roles = self._get_roles(username)
return self.roles.is_admin(roles['roles']) | python | def _is_admin(self, username):
""" Check if a user is an ldapcherry administrator
@str username: name of the user
@rtype: bool, True if administrator, False otherwise
"""
roles = self._get_roles(username)
return self.roles.is_admin(roles['roles']) | [
"def",
"_is_admin",
"(",
"self",
",",
"username",
")",
":",
"roles",
"=",
"self",
".",
"_get_roles",
"(",
"username",
")",
"return",
"self",
".",
"roles",
".",
"is_admin",
"(",
"roles",
"[",
"'roles'",
"]",
")"
] | Check if a user is an ldapcherry administrator
@str username: name of the user
@rtype: bool, True if administrator, False otherwise | [
"Check",
"if",
"a",
"user",
"is",
"an",
"ldapcherry",
"administrator"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L106-L112 | train | 198,268 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry._check_backends | def _check_backends(self):
""" Check that every backend in roles and attributes
is declared in main configuration
"""
backends = self.backends_params.keys()
for b in self.roles.get_backends():
if b not in backends:
raise MissingBackend(b, 'role')
for b in self.attributes.get_backends():
if b not in backends:
raise MissingBackend(b, 'attribute') | python | def _check_backends(self):
""" Check that every backend in roles and attributes
is declared in main configuration
"""
backends = self.backends_params.keys()
for b in self.roles.get_backends():
if b not in backends:
raise MissingBackend(b, 'role')
for b in self.attributes.get_backends():
if b not in backends:
raise MissingBackend(b, 'attribute') | [
"def",
"_check_backends",
"(",
"self",
")",
":",
"backends",
"=",
"self",
".",
"backends_params",
".",
"keys",
"(",
")",
"for",
"b",
"in",
"self",
".",
"roles",
".",
"get_backends",
"(",
")",
":",
"if",
"b",
"not",
"in",
"backends",
":",
"raise",
"Mi... | Check that every backend in roles and attributes
is declared in main configuration | [
"Check",
"that",
"every",
"backend",
"in",
"roles",
"and",
"attributes",
"is",
"declared",
"in",
"main",
"configuration"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L114-L124 | train | 198,269 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry._init_backends | def _init_backends(self, config):
""" Init all backends
@dict: configuration of ldapcherry
"""
self.backends_params = {}
self.backends = {}
self.backends_display_names = {}
for entry in config['backends']:
# split at the first dot
backend, sep, param = entry.partition('.')
value = config['backends'][entry]
if backend not in self.backends_params:
self.backends_params[backend] = {}
self.backends_params[backend][param] = value
for backend in self.backends_params:
# get the backend display_name
try:
self.backends_display_names[backend] = \
self.backends_params[backend]['display_name']
except Exception as e:
self.backends_display_names[backend] = backend
self.backends_params[backend]['display_name'] = backend
params = self.backends_params[backend]
# Loading the backend module
try:
module = params['module']
except Exception as e:
raise MissingParameter('backends', backend + '.module')
try:
bc = __import__(module, globals(), locals(), ['Backend'], 0)
except Exception as e:
self._handle_exception(e)
raise BackendModuleLoadingFail(module)
try:
attrslist = self.attributes.get_backend_attributes(backend)
key = self.attributes.get_backend_key(backend)
self.backends[backend] = bc.Backend(
params,
cherrypy.log.error,
backend,
attrslist,
key,
)
except MissingParameter as e:
raise
except Exception as e:
self._handle_exception(e)
raise BackendModuleInitFail(module) | python | def _init_backends(self, config):
""" Init all backends
@dict: configuration of ldapcherry
"""
self.backends_params = {}
self.backends = {}
self.backends_display_names = {}
for entry in config['backends']:
# split at the first dot
backend, sep, param = entry.partition('.')
value = config['backends'][entry]
if backend not in self.backends_params:
self.backends_params[backend] = {}
self.backends_params[backend][param] = value
for backend in self.backends_params:
# get the backend display_name
try:
self.backends_display_names[backend] = \
self.backends_params[backend]['display_name']
except Exception as e:
self.backends_display_names[backend] = backend
self.backends_params[backend]['display_name'] = backend
params = self.backends_params[backend]
# Loading the backend module
try:
module = params['module']
except Exception as e:
raise MissingParameter('backends', backend + '.module')
try:
bc = __import__(module, globals(), locals(), ['Backend'], 0)
except Exception as e:
self._handle_exception(e)
raise BackendModuleLoadingFail(module)
try:
attrslist = self.attributes.get_backend_attributes(backend)
key = self.attributes.get_backend_key(backend)
self.backends[backend] = bc.Backend(
params,
cherrypy.log.error,
backend,
attrslist,
key,
)
except MissingParameter as e:
raise
except Exception as e:
self._handle_exception(e)
raise BackendModuleInitFail(module) | [
"def",
"_init_backends",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"backends_params",
"=",
"{",
"}",
"self",
".",
"backends",
"=",
"{",
"}",
"self",
".",
"backends_display_names",
"=",
"{",
"}",
"for",
"entry",
"in",
"config",
"[",
"'backends'",... | Init all backends
@dict: configuration of ldapcherry | [
"Init",
"all",
"backends"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L126-L173 | train | 198,270 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry._set_access_log | def _set_access_log(self, config, level):
""" Configure access logs
"""
access_handler = self._get_param(
'global',
'log.access_handler',
config,
'syslog',
)
# log format for syslog
syslog_formatter = logging.Formatter(
"ldapcherry[%(process)d]: %(message)s"
)
# replace access log handler by a syslog handler
if access_handler == 'syslog':
cherrypy.log.access_log.handlers = []
handler = logging.handlers.SysLogHandler(
address='/dev/log',
facility='user',
)
handler.setFormatter(syslog_formatter)
cherrypy.log.access_log.addHandler(handler)
# if stdout, open a logger on stdout
elif access_handler == 'stdout':
cherrypy.log.access_log.handlers = []
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(
'ldapcherry.access - %(levelname)s - %(message)s'
)
handler.setFormatter(formatter)
cherrypy.log.access_log.addHandler(handler)
# if file, we keep the default
elif access_handler == 'file':
pass
# replace access log handler by a null handler
elif access_handler == 'none':
cherrypy.log.access_log.handlers = []
handler = logging.NullHandler()
cherrypy.log.access_log.addHandler(handler)
# set log level
cherrypy.log.access_log.setLevel(level) | python | def _set_access_log(self, config, level):
""" Configure access logs
"""
access_handler = self._get_param(
'global',
'log.access_handler',
config,
'syslog',
)
# log format for syslog
syslog_formatter = logging.Formatter(
"ldapcherry[%(process)d]: %(message)s"
)
# replace access log handler by a syslog handler
if access_handler == 'syslog':
cherrypy.log.access_log.handlers = []
handler = logging.handlers.SysLogHandler(
address='/dev/log',
facility='user',
)
handler.setFormatter(syslog_formatter)
cherrypy.log.access_log.addHandler(handler)
# if stdout, open a logger on stdout
elif access_handler == 'stdout':
cherrypy.log.access_log.handlers = []
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(
'ldapcherry.access - %(levelname)s - %(message)s'
)
handler.setFormatter(formatter)
cherrypy.log.access_log.addHandler(handler)
# if file, we keep the default
elif access_handler == 'file':
pass
# replace access log handler by a null handler
elif access_handler == 'none':
cherrypy.log.access_log.handlers = []
handler = logging.NullHandler()
cherrypy.log.access_log.addHandler(handler)
# set log level
cherrypy.log.access_log.setLevel(level) | [
"def",
"_set_access_log",
"(",
"self",
",",
"config",
",",
"level",
")",
":",
"access_handler",
"=",
"self",
".",
"_get_param",
"(",
"'global'",
",",
"'log.access_handler'",
",",
"config",
",",
"'syslog'",
",",
")",
"# log format for syslog",
"syslog_formatter",
... | Configure access logs | [
"Configure",
"access",
"logs"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L231-L276 | train | 198,271 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry._set_error_log | def _set_error_log(self, config, level, debug=False):
""" Configure error logs
"""
error_handler = self._get_param(
'global',
'log.error_handler',
config,
'syslog'
)
# log format for syslog
syslog_formatter = logging.Formatter(
"ldapcherry[%(process)d]: %(message)s",
)
# replacing the error handler by a syslog handler
if error_handler == 'syslog':
cherrypy.log.error_log.handlers = []
# redefining log.error method because cherrypy does weird
# things like adding the date inside the message
# or adding space even if context is empty
# (by the way, what's the use of "context"?)
cherrypy.log.error = syslog_error
handler = logging.handlers.SysLogHandler(
address='/dev/log',
facility='user',
)
handler.setFormatter(syslog_formatter)
cherrypy.log.error_log.addHandler(handler)
# if stdout, open a logger on stdout
elif error_handler == 'stdout':
cherrypy.log.error_log.handlers = []
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(
'ldapcherry.app - %(levelname)s - %(message)s'
)
handler.setFormatter(formatter)
cherrypy.log.error_log.addHandler(handler)
# if file, we keep the default
elif error_handler == 'file':
pass
# replacing the error handler by a null handler
elif error_handler == 'none':
cherrypy.log.error_log.handlers = []
handler = logging.NullHandler()
cherrypy.log.error_log.addHandler(handler)
# set log level
cherrypy.log.error_log.setLevel(level)
if debug:
cherrypy.log.error_log.handlers = []
handler = logging.StreamHandler(sys.stderr)
handler.setLevel(logging.DEBUG)
cherrypy.log.error_log.addHandler(handler)
cherrypy.log.error_log.setLevel(logging.DEBUG) | python | def _set_error_log(self, config, level, debug=False):
""" Configure error logs
"""
error_handler = self._get_param(
'global',
'log.error_handler',
config,
'syslog'
)
# log format for syslog
syslog_formatter = logging.Formatter(
"ldapcherry[%(process)d]: %(message)s",
)
# replacing the error handler by a syslog handler
if error_handler == 'syslog':
cherrypy.log.error_log.handlers = []
# redefining log.error method because cherrypy does weird
# things like adding the date inside the message
# or adding space even if context is empty
# (by the way, what's the use of "context"?)
cherrypy.log.error = syslog_error
handler = logging.handlers.SysLogHandler(
address='/dev/log',
facility='user',
)
handler.setFormatter(syslog_formatter)
cherrypy.log.error_log.addHandler(handler)
# if stdout, open a logger on stdout
elif error_handler == 'stdout':
cherrypy.log.error_log.handlers = []
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(
'ldapcherry.app - %(levelname)s - %(message)s'
)
handler.setFormatter(formatter)
cherrypy.log.error_log.addHandler(handler)
# if file, we keep the default
elif error_handler == 'file':
pass
# replacing the error handler by a null handler
elif error_handler == 'none':
cherrypy.log.error_log.handlers = []
handler = logging.NullHandler()
cherrypy.log.error_log.addHandler(handler)
# set log level
cherrypy.log.error_log.setLevel(level)
if debug:
cherrypy.log.error_log.handlers = []
handler = logging.StreamHandler(sys.stderr)
handler.setLevel(logging.DEBUG)
cherrypy.log.error_log.addHandler(handler)
cherrypy.log.error_log.setLevel(logging.DEBUG) | [
"def",
"_set_error_log",
"(",
"self",
",",
"config",
",",
"level",
",",
"debug",
"=",
"False",
")",
":",
"error_handler",
"=",
"self",
".",
"_get_param",
"(",
"'global'",
",",
"'log.error_handler'",
",",
"config",
",",
"'syslog'",
")",
"# log format for syslog... | Configure error logs | [
"Configure",
"error",
"logs"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L278-L337 | train | 198,272 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry._auth | def _auth(self, user, password):
""" authenticate a user
@str user: login of the user
@str password: password of the user
@rtype: dict, {'connected': <boolean, True if connection succeded>,
'isadmin': <True if user is ldapcherry administrator>}
"""
if self.auth_mode == 'none':
return {'connected': True, 'isadmin': True}
elif self.auth_mode == 'and':
ret1 = True
for b in self.backends:
ret1 = self.backends[b].auth(user, password) and ret1
elif self.auth_mode == 'or':
ret1 = False
for b in self.backends:
ret1 = self.backends[b].auth(user, password) or ret1
elif self.auth_mode == 'custom':
ret1 = self.auth.auth(user, password)
else:
raise Exception()
if not ret1:
return {'connected': False, 'isadmin': False}
else:
isadmin = self._is_admin(user)
return {'connected': True, 'isadmin': isadmin} | python | def _auth(self, user, password):
""" authenticate a user
@str user: login of the user
@str password: password of the user
@rtype: dict, {'connected': <boolean, True if connection succeded>,
'isadmin': <True if user is ldapcherry administrator>}
"""
if self.auth_mode == 'none':
return {'connected': True, 'isadmin': True}
elif self.auth_mode == 'and':
ret1 = True
for b in self.backends:
ret1 = self.backends[b].auth(user, password) and ret1
elif self.auth_mode == 'or':
ret1 = False
for b in self.backends:
ret1 = self.backends[b].auth(user, password) or ret1
elif self.auth_mode == 'custom':
ret1 = self.auth.auth(user, password)
else:
raise Exception()
if not ret1:
return {'connected': False, 'isadmin': False}
else:
isadmin = self._is_admin(user)
return {'connected': True, 'isadmin': isadmin} | [
"def",
"_auth",
"(",
"self",
",",
"user",
",",
"password",
")",
":",
"if",
"self",
".",
"auth_mode",
"==",
"'none'",
":",
"return",
"{",
"'connected'",
":",
"True",
",",
"'isadmin'",
":",
"True",
"}",
"elif",
"self",
".",
"auth_mode",
"==",
"'and'",
... | authenticate a user
@str user: login of the user
@str password: password of the user
@rtype: dict, {'connected': <boolean, True if connection succeded>,
'isadmin': <True if user is ldapcherry administrator>} | [
"authenticate",
"a",
"user"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L339-L364 | train | 198,273 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry._add_notification | def _add_notification(self, message):
""" add a notification in the notification queue of a user
"""
sess = cherrypy.session
username = sess.get(SESSION_KEY, None)
if username not in self.notifications:
self.notifications[username] = []
self.notifications[username].append(message) | python | def _add_notification(self, message):
""" add a notification in the notification queue of a user
"""
sess = cherrypy.session
username = sess.get(SESSION_KEY, None)
if username not in self.notifications:
self.notifications[username] = []
self.notifications[username].append(message) | [
"def",
"_add_notification",
"(",
"self",
",",
"message",
")",
":",
"sess",
"=",
"cherrypy",
".",
"session",
"username",
"=",
"sess",
".",
"get",
"(",
"SESSION_KEY",
",",
"None",
")",
"if",
"username",
"not",
"in",
"self",
".",
"notifications",
":",
"self... | add a notification in the notification queue of a user | [
"add",
"a",
"notification",
"in",
"the",
"notification",
"queue",
"of",
"a",
"user"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L461-L468 | train | 198,274 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry._empty_notification | def _empty_notification(self):
""" empty and return list of message notification
"""
sess = cherrypy.session
username = sess.get(SESSION_KEY, None)
if username in self.notifications:
ret = self.notifications[username]
else:
ret = []
self.notifications[username] = []
return ret | python | def _empty_notification(self):
""" empty and return list of message notification
"""
sess = cherrypy.session
username = sess.get(SESSION_KEY, None)
if username in self.notifications:
ret = self.notifications[username]
else:
ret = []
self.notifications[username] = []
return ret | [
"def",
"_empty_notification",
"(",
"self",
")",
":",
"sess",
"=",
"cherrypy",
".",
"session",
"username",
"=",
"sess",
".",
"get",
"(",
"SESSION_KEY",
",",
"None",
")",
"if",
"username",
"in",
"self",
".",
"notifications",
":",
"ret",
"=",
"self",
".",
... | empty and return list of message notification | [
"empty",
"and",
"return",
"list",
"of",
"message",
"notification"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L470-L480 | train | 198,275 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry._merge_user_attrs | def _merge_user_attrs(self, attrs_backend, attrs_out, backend_name):
""" merge attributes from one backend search to the attributes dict
output
"""
for attr in attrs_backend:
if attr in self.attributes.backend_attributes[backend_name]:
attrid = self.attributes.backend_attributes[backend_name][attr]
if attrid not in attrs_out:
attrs_out[attrid] = attrs_backend[attr] | python | def _merge_user_attrs(self, attrs_backend, attrs_out, backend_name):
""" merge attributes from one backend search to the attributes dict
output
"""
for attr in attrs_backend:
if attr in self.attributes.backend_attributes[backend_name]:
attrid = self.attributes.backend_attributes[backend_name][attr]
if attrid not in attrs_out:
attrs_out[attrid] = attrs_backend[attr] | [
"def",
"_merge_user_attrs",
"(",
"self",
",",
"attrs_backend",
",",
"attrs_out",
",",
"backend_name",
")",
":",
"for",
"attr",
"in",
"attrs_backend",
":",
"if",
"attr",
"in",
"self",
".",
"attributes",
".",
"backend_attributes",
"[",
"backend_name",
"]",
":",
... | merge attributes from one backend search to the attributes dict
output | [
"merge",
"attributes",
"from",
"one",
"backend",
"search",
"to",
"the",
"attributes",
"dict",
"output"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L482-L491 | train | 198,276 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry.index | def index(self):
"""main page rendering
"""
self._check_auth(must_admin=False)
is_admin = self._check_admin()
sess = cherrypy.session
user = sess.get(SESSION_KEY, None)
if self.auth_mode == 'none':
user_attrs = None
else:
user_attrs = self._get_user(user)
attrs_list = self.attributes.get_search_attributes()
return self.temp['index.tmpl'].render(
is_admin=is_admin,
attrs_list=attrs_list,
searchresult=user_attrs,
notifications=self._empty_notification(),
) | python | def index(self):
"""main page rendering
"""
self._check_auth(must_admin=False)
is_admin = self._check_admin()
sess = cherrypy.session
user = sess.get(SESSION_KEY, None)
if self.auth_mode == 'none':
user_attrs = None
else:
user_attrs = self._get_user(user)
attrs_list = self.attributes.get_search_attributes()
return self.temp['index.tmpl'].render(
is_admin=is_admin,
attrs_list=attrs_list,
searchresult=user_attrs,
notifications=self._empty_notification(),
) | [
"def",
"index",
"(",
"self",
")",
":",
"self",
".",
"_check_auth",
"(",
"must_admin",
"=",
"False",
")",
"is_admin",
"=",
"self",
".",
"_check_admin",
"(",
")",
"sess",
"=",
"cherrypy",
".",
"session",
"user",
"=",
"sess",
".",
"get",
"(",
"SESSION_KEY... | main page rendering | [
"main",
"page",
"rendering"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L952-L969 | train | 198,277 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry.adduser | def adduser(self, **params):
""" add user page """
self._check_auth(must_admin=True)
is_admin = self._check_admin()
if cherrypy.request.method.upper() == 'POST':
params = self._parse_params(params)
self._adduser(params)
self._add_notification("User added")
graph = {}
for r in self.roles.graph:
s = list(self.roles.graph[r]['sub_roles'])
p = list(self.roles.graph[r]['parent_roles'])
graph[r] = {'sub_roles': s, 'parent_roles': p}
graph_js = json.dumps(graph, separators=(',', ':'))
display_names = {}
for r in self.roles.flatten:
display_names[r] = self.roles.flatten[r]['display_name']
roles_js = json.dumps(display_names, separators=(',', ':'))
try:
form = self.temp['form.tmpl'].render(
attributes=self.attributes.attributes,
values=None,
modify=False,
autofill=True
)
roles = self.temp['roles.tmpl'].render(
roles=self.roles.flatten,
graph=self.roles.graph,
graph_js=graph_js,
roles_js=roles_js,
current_roles=None,
)
return self.temp['adduser.tmpl'].render(
form=form,
roles=roles,
is_admin=is_admin,
custom_js=self.custom_js,
notifications=self._empty_notification(),
)
except NameError:
raise TemplateRenderError(
exceptions.text_error_template().render()
) | python | def adduser(self, **params):
""" add user page """
self._check_auth(must_admin=True)
is_admin = self._check_admin()
if cherrypy.request.method.upper() == 'POST':
params = self._parse_params(params)
self._adduser(params)
self._add_notification("User added")
graph = {}
for r in self.roles.graph:
s = list(self.roles.graph[r]['sub_roles'])
p = list(self.roles.graph[r]['parent_roles'])
graph[r] = {'sub_roles': s, 'parent_roles': p}
graph_js = json.dumps(graph, separators=(',', ':'))
display_names = {}
for r in self.roles.flatten:
display_names[r] = self.roles.flatten[r]['display_name']
roles_js = json.dumps(display_names, separators=(',', ':'))
try:
form = self.temp['form.tmpl'].render(
attributes=self.attributes.attributes,
values=None,
modify=False,
autofill=True
)
roles = self.temp['roles.tmpl'].render(
roles=self.roles.flatten,
graph=self.roles.graph,
graph_js=graph_js,
roles_js=roles_js,
current_roles=None,
)
return self.temp['adduser.tmpl'].render(
form=form,
roles=roles,
is_admin=is_admin,
custom_js=self.custom_js,
notifications=self._empty_notification(),
)
except NameError:
raise TemplateRenderError(
exceptions.text_error_template().render()
) | [
"def",
"adduser",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"self",
".",
"_check_auth",
"(",
"must_admin",
"=",
"True",
")",
"is_admin",
"=",
"self",
".",
"_check_admin",
"(",
")",
"if",
"cherrypy",
".",
"request",
".",
"method",
".",
"upper",
... | add user page | [
"add",
"user",
"page"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L1029-L1073 | train | 198,278 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry.delete | def delete(self, user):
""" remove user page """
self._check_auth(must_admin=True)
is_admin = self._check_admin()
try:
referer = cherrypy.request.headers['Referer']
except Exception as e:
referer = '/'
self._deleteuser(user)
self._add_notification('User Deleted')
raise cherrypy.HTTPRedirect(referer) | python | def delete(self, user):
""" remove user page """
self._check_auth(must_admin=True)
is_admin = self._check_admin()
try:
referer = cherrypy.request.headers['Referer']
except Exception as e:
referer = '/'
self._deleteuser(user)
self._add_notification('User Deleted')
raise cherrypy.HTTPRedirect(referer) | [
"def",
"delete",
"(",
"self",
",",
"user",
")",
":",
"self",
".",
"_check_auth",
"(",
"must_admin",
"=",
"True",
")",
"is_admin",
"=",
"self",
".",
"_check_admin",
"(",
")",
"try",
":",
"referer",
"=",
"cherrypy",
".",
"request",
".",
"headers",
"[",
... | remove user page | [
"remove",
"user",
"page"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L1077-L1087 | train | 198,279 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry.modify | def modify(self, user=None, **params):
""" modify user page """
self._check_auth(must_admin=True)
is_admin = self._check_admin()
if cherrypy.request.method.upper() == 'POST':
params = self._parse_params(params)
self._modify(params)
self._add_notification("User modified")
try:
referer = cherrypy.request.headers['Referer']
except Exception as e:
referer = '/'
raise cherrypy.HTTPRedirect(referer)
graph = {}
for r in self.roles.graph:
s = list(self.roles.graph[r]['sub_roles'])
p = list(self.roles.graph[r]['parent_roles'])
graph[r] = {'sub_roles': s, 'parent_roles': p}
graph_js = json.dumps(graph, separators=(',', ':'))
display_names = {}
for r in self.roles.flatten:
display_names[r] = self.roles.flatten[r]['display_name']
if user is None:
cherrypy.response.status = 400
return self.temp['error.tmpl'].render(
is_admin=is_admin,
alert='warning',
message="No user requested"
)
user_attrs = self._get_user(user)
if user_attrs == {}:
cherrypy.response.status = 400
return self.temp['error.tmpl'].render(
is_admin=is_admin,
alert='warning',
message="User '" + user + "' does not exist"
)
tmp = self._get_roles(user)
user_roles = tmp['roles']
standalone_groups = tmp['unusedgroups']
roles_js = json.dumps(display_names, separators=(',', ':'))
key = self.attributes.get_key()
try:
form = self.temp['form.tmpl'].render(
attributes=self.attributes.attributes,
values=user_attrs,
modify=True,
keyattr=key,
autofill=False
)
roles = self.temp['roles.tmpl'].render(
roles=self.roles.flatten,
graph=self.roles.graph,
graph_js=graph_js,
roles_js=roles_js,
current_roles=user_roles,
)
glued_template = self.temp['modify.tmpl'].render(
form=form,
roles=roles,
is_admin=is_admin,
standalone_groups=standalone_groups,
backends_display_names=self.backends_display_names,
custom_js=self.custom_js,
notifications=self._empty_notification(),
)
except NameError:
raise TemplateRenderError(
exceptions.text_error_template().render()
)
return glued_template | python | def modify(self, user=None, **params):
""" modify user page """
self._check_auth(must_admin=True)
is_admin = self._check_admin()
if cherrypy.request.method.upper() == 'POST':
params = self._parse_params(params)
self._modify(params)
self._add_notification("User modified")
try:
referer = cherrypy.request.headers['Referer']
except Exception as e:
referer = '/'
raise cherrypy.HTTPRedirect(referer)
graph = {}
for r in self.roles.graph:
s = list(self.roles.graph[r]['sub_roles'])
p = list(self.roles.graph[r]['parent_roles'])
graph[r] = {'sub_roles': s, 'parent_roles': p}
graph_js = json.dumps(graph, separators=(',', ':'))
display_names = {}
for r in self.roles.flatten:
display_names[r] = self.roles.flatten[r]['display_name']
if user is None:
cherrypy.response.status = 400
return self.temp['error.tmpl'].render(
is_admin=is_admin,
alert='warning',
message="No user requested"
)
user_attrs = self._get_user(user)
if user_attrs == {}:
cherrypy.response.status = 400
return self.temp['error.tmpl'].render(
is_admin=is_admin,
alert='warning',
message="User '" + user + "' does not exist"
)
tmp = self._get_roles(user)
user_roles = tmp['roles']
standalone_groups = tmp['unusedgroups']
roles_js = json.dumps(display_names, separators=(',', ':'))
key = self.attributes.get_key()
try:
form = self.temp['form.tmpl'].render(
attributes=self.attributes.attributes,
values=user_attrs,
modify=True,
keyattr=key,
autofill=False
)
roles = self.temp['roles.tmpl'].render(
roles=self.roles.flatten,
graph=self.roles.graph,
graph_js=graph_js,
roles_js=roles_js,
current_roles=user_roles,
)
glued_template = self.temp['modify.tmpl'].render(
form=form,
roles=roles,
is_admin=is_admin,
standalone_groups=standalone_groups,
backends_display_names=self.backends_display_names,
custom_js=self.custom_js,
notifications=self._empty_notification(),
)
except NameError:
raise TemplateRenderError(
exceptions.text_error_template().render()
)
return glued_template | [
"def",
"modify",
"(",
"self",
",",
"user",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"self",
".",
"_check_auth",
"(",
"must_admin",
"=",
"True",
")",
"is_admin",
"=",
"self",
".",
"_check_admin",
"(",
")",
"if",
"cherrypy",
".",
"request",
".",... | modify user page | [
"modify",
"user",
"page"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L1091-L1169 | train | 198,280 |
kakwa/ldapcherry | ldapcherry/__init__.py | LdapCherry.selfmodify | def selfmodify(self, **params):
""" self modify user page """
self._check_auth(must_admin=False)
is_admin = self._check_admin()
sess = cherrypy.session
user = sess.get(SESSION_KEY, None)
if self.auth_mode == 'none':
return self.temp['error.tmpl'].render(
is_admin=is_admin,
alert='warning',
message="Not accessible with authentication disabled."
)
if cherrypy.request.method.upper() == 'POST':
params = self._parse_params(params)
self._selfmodify(params)
self._add_notification(
"Self modification done"
)
user_attrs = self._get_user(user)
try:
if user_attrs == {}:
return self.temp['error.tmpl'].render(
is_admin=is_admin,
alert='warning',
message="User doesn't exist"
)
form = self.temp['form.tmpl'].render(
attributes=self.attributes.get_selfattributes(),
values=user_attrs,
modify=True,
autofill=False
)
return self.temp['selfmodify.tmpl'].render(
form=form,
is_admin=is_admin,
notifications=self._empty_notification(),
)
except NameError:
raise TemplateRenderError(
exceptions.text_error_template().render()
) | python | def selfmodify(self, **params):
""" self modify user page """
self._check_auth(must_admin=False)
is_admin = self._check_admin()
sess = cherrypy.session
user = sess.get(SESSION_KEY, None)
if self.auth_mode == 'none':
return self.temp['error.tmpl'].render(
is_admin=is_admin,
alert='warning',
message="Not accessible with authentication disabled."
)
if cherrypy.request.method.upper() == 'POST':
params = self._parse_params(params)
self._selfmodify(params)
self._add_notification(
"Self modification done"
)
user_attrs = self._get_user(user)
try:
if user_attrs == {}:
return self.temp['error.tmpl'].render(
is_admin=is_admin,
alert='warning',
message="User doesn't exist"
)
form = self.temp['form.tmpl'].render(
attributes=self.attributes.get_selfattributes(),
values=user_attrs,
modify=True,
autofill=False
)
return self.temp['selfmodify.tmpl'].render(
form=form,
is_admin=is_admin,
notifications=self._empty_notification(),
)
except NameError:
raise TemplateRenderError(
exceptions.text_error_template().render()
) | [
"def",
"selfmodify",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"self",
".",
"_check_auth",
"(",
"must_admin",
"=",
"False",
")",
"is_admin",
"=",
"self",
".",
"_check_admin",
"(",
")",
"sess",
"=",
"cherrypy",
".",
"session",
"user",
"=",
"sess",... | self modify user page | [
"self",
"modify",
"user",
"page"
] | b5e7cb6a44065abc30d164e72981b3713a172dda | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L1184-L1226 | train | 198,281 |
wooey/Wooey | wooey/views/wooey_celery.py | JobJSONHTML.render_to_response | def render_to_response(self, context, *args, **kwargs):
"""
Build dictionary of content
"""
preview_outputs = []
file_outputs = []
bast_ctx = context
added = set()
for output_group, output_files in context['job_info']['file_groups'].items():
for output_file_content in output_files:
if output_group:
bast_ctx.update({
'job_info': context['job_info'],
'output_group': output_group,
'output_file_content': output_file_content,
})
preview = render_to_string('wooey/preview/%s.html' % output_group, bast_ctx)
preview_outputs.append(preview)
for file_info in context['job_info']['all_files']:
if file_info and file_info.get('name') not in added:
row_ctx = dict(
file=file_info,
**context
)
table_row = render_to_string('wooey/jobs/results/table_row.html', row_ctx)
file_outputs.append(table_row)
added.add(file_info.get('name'))
return JsonResponse({
'status': context['job_info']['status'].lower(),
'command': context['job_info']['job'].command,
'stdout': context['job_info']['job'].get_stdout(),
'stderr': context['job_info']['job'].get_stderr(),
'preview_outputs_html': preview_outputs,
'file_outputs_html': file_outputs,
}) | python | def render_to_response(self, context, *args, **kwargs):
"""
Build dictionary of content
"""
preview_outputs = []
file_outputs = []
bast_ctx = context
added = set()
for output_group, output_files in context['job_info']['file_groups'].items():
for output_file_content in output_files:
if output_group:
bast_ctx.update({
'job_info': context['job_info'],
'output_group': output_group,
'output_file_content': output_file_content,
})
preview = render_to_string('wooey/preview/%s.html' % output_group, bast_ctx)
preview_outputs.append(preview)
for file_info in context['job_info']['all_files']:
if file_info and file_info.get('name') not in added:
row_ctx = dict(
file=file_info,
**context
)
table_row = render_to_string('wooey/jobs/results/table_row.html', row_ctx)
file_outputs.append(table_row)
added.add(file_info.get('name'))
return JsonResponse({
'status': context['job_info']['status'].lower(),
'command': context['job_info']['job'].command,
'stdout': context['job_info']['job'].get_stdout(),
'stderr': context['job_info']['job'].get_stderr(),
'preview_outputs_html': preview_outputs,
'file_outputs_html': file_outputs,
}) | [
"def",
"render_to_response",
"(",
"self",
",",
"context",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"preview_outputs",
"=",
"[",
"]",
"file_outputs",
"=",
"[",
"]",
"bast_ctx",
"=",
"context",
"added",
"=",
"set",
"(",
")",
"for",
"output_gr... | Build dictionary of content | [
"Build",
"dictionary",
"of",
"content"
] | f06285387b7f78bf2c5d84faff4f986bc0979f86 | https://github.com/wooey/Wooey/blob/f06285387b7f78bf2c5d84faff4f986bc0979f86/wooey/views/wooey_celery.py#L215-L252 | train | 198,282 |
wooey/Wooey | wooey/tasks.py | cleanup_dead_jobs | def cleanup_dead_jobs():
"""
This cleans up jobs that have been marked as ran, but are not queue'd in celery. It is meant
to cleanup jobs that have been lost due to a server crash or some other reason a job is
in limbo.
"""
from .models import WooeyJob
# Get active tasks from Celery
inspect = celery_app.control.inspect()
active_tasks = {task['id'] for worker, tasks in six.iteritems(inspect.active()) for task in tasks}
# find jobs that are marked as running but not present in celery's active tasks
active_jobs = WooeyJob.objects.filter(status=WooeyJob.RUNNING)
to_disable = set()
for job in active_jobs:
if job.celery_id not in active_tasks:
to_disable.add(job.pk)
WooeyJob.objects.filter(pk__in=to_disable).update(status=WooeyJob.FAILED) | python | def cleanup_dead_jobs():
"""
This cleans up jobs that have been marked as ran, but are not queue'd in celery. It is meant
to cleanup jobs that have been lost due to a server crash or some other reason a job is
in limbo.
"""
from .models import WooeyJob
# Get active tasks from Celery
inspect = celery_app.control.inspect()
active_tasks = {task['id'] for worker, tasks in six.iteritems(inspect.active()) for task in tasks}
# find jobs that are marked as running but not present in celery's active tasks
active_jobs = WooeyJob.objects.filter(status=WooeyJob.RUNNING)
to_disable = set()
for job in active_jobs:
if job.celery_id not in active_tasks:
to_disable.add(job.pk)
WooeyJob.objects.filter(pk__in=to_disable).update(status=WooeyJob.FAILED) | [
"def",
"cleanup_dead_jobs",
"(",
")",
":",
"from",
".",
"models",
"import",
"WooeyJob",
"# Get active tasks from Celery",
"inspect",
"=",
"celery_app",
".",
"control",
".",
"inspect",
"(",
")",
"active_tasks",
"=",
"{",
"task",
"[",
"'id'",
"]",
"for",
"worker... | This cleans up jobs that have been marked as ran, but are not queue'd in celery. It is meant
to cleanup jobs that have been lost due to a server crash or some other reason a job is
in limbo. | [
"This",
"cleans",
"up",
"jobs",
"that",
"have",
"been",
"marked",
"as",
"ran",
"but",
"are",
"not",
"queue",
"d",
"in",
"celery",
".",
"It",
"is",
"meant",
"to",
"cleanup",
"jobs",
"that",
"have",
"been",
"lost",
"due",
"to",
"a",
"server",
"crash",
... | f06285387b7f78bf2c5d84faff4f986bc0979f86 | https://github.com/wooey/Wooey/blob/f06285387b7f78bf2c5d84faff4f986bc0979f86/wooey/tasks.py#L227-L246 | train | 198,283 |
wooey/Wooey | wooey/backend/utils.py | normalize_query | def normalize_query(query_string,
findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
normspace=re.compile(r'\s{2,}').sub):
"""
Split the query string into individual keywords, discarding spaces
and grouping quoted words together.
>>> normalize_query(' some random words "with quotes " and spaces')
['some', 'random', 'words', 'with quotes', 'and', 'spaces']
"""
return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)] | python | def normalize_query(query_string,
findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
normspace=re.compile(r'\s{2,}').sub):
"""
Split the query string into individual keywords, discarding spaces
and grouping quoted words together.
>>> normalize_query(' some random words "with quotes " and spaces')
['some', 'random', 'words', 'with quotes', 'and', 'spaces']
"""
return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)] | [
"def",
"normalize_query",
"(",
"query_string",
",",
"findterms",
"=",
"re",
".",
"compile",
"(",
"r'\"([^\"]+)\"|(\\S+)'",
")",
".",
"findall",
",",
"normspace",
"=",
"re",
".",
"compile",
"(",
"r'\\s{2,}'",
")",
".",
"sub",
")",
":",
"return",
"[",
"norms... | Split the query string into individual keywords, discarding spaces
and grouping quoted words together.
>>> normalize_query(' some random words "with quotes " and spaces')
['some', 'random', 'words', 'with quotes', 'and', 'spaces'] | [
"Split",
"the",
"query",
"string",
"into",
"individual",
"keywords",
"discarding",
"spaces",
"and",
"grouping",
"quoted",
"words",
"together",
"."
] | f06285387b7f78bf2c5d84faff4f986bc0979f86 | https://github.com/wooey/Wooey/blob/f06285387b7f78bf2c5d84faff4f986bc0979f86/wooey/backend/utils.py#L821-L832 | train | 198,284 |
wooey/Wooey | wooey/models/mixins.py | ModelDiffMixin.save | def save(self, *args, **kwargs):
"""
Saves model and set initial state.
"""
super(ModelDiffMixin, self).save(*args, **kwargs)
self.__initial = self._dict | python | def save(self, *args, **kwargs):
"""
Saves model and set initial state.
"""
super(ModelDiffMixin, self).save(*args, **kwargs)
self.__initial = self._dict | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"ModelDiffMixin",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"__initial",
"=",
"self",
".",
"_dict"
] | Saves model and set initial state. | [
"Saves",
"model",
"and",
"set",
"initial",
"state",
"."
] | f06285387b7f78bf2c5d84faff4f986bc0979f86 | https://github.com/wooey/Wooey/blob/f06285387b7f78bf2c5d84faff4f986bc0979f86/wooey/models/mixins.py#L54-L59 | train | 198,285 |
RPi-Distro/python-sense-hat | sense_hat/sense_hat.py | SenseHat._load_text_assets | def _load_text_assets(self, text_image_file, text_file):
"""
Internal. Builds a character indexed dictionary of pixels used by the
show_message function below
"""
text_pixels = self.load_image(text_image_file, False)
with open(text_file, 'r') as f:
loaded_text = f.read()
self._text_dict = {}
for index, s in enumerate(loaded_text):
start = index * 40
end = start + 40
char = text_pixels[start:end]
self._text_dict[s] = char | python | def _load_text_assets(self, text_image_file, text_file):
"""
Internal. Builds a character indexed dictionary of pixels used by the
show_message function below
"""
text_pixels = self.load_image(text_image_file, False)
with open(text_file, 'r') as f:
loaded_text = f.read()
self._text_dict = {}
for index, s in enumerate(loaded_text):
start = index * 40
end = start + 40
char = text_pixels[start:end]
self._text_dict[s] = char | [
"def",
"_load_text_assets",
"(",
"self",
",",
"text_image_file",
",",
"text_file",
")",
":",
"text_pixels",
"=",
"self",
".",
"load_image",
"(",
"text_image_file",
",",
"False",
")",
"with",
"open",
"(",
"text_file",
",",
"'r'",
")",
"as",
"f",
":",
"loade... | Internal. Builds a character indexed dictionary of pixels used by the
show_message function below | [
"Internal",
".",
"Builds",
"a",
"character",
"indexed",
"dictionary",
"of",
"pixels",
"used",
"by",
"the",
"show_message",
"function",
"below"
] | 9a37f0923ce8dbde69514c3b8d58d30de01c9ee7 | https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L104-L118 | train | 198,286 |
RPi-Distro/python-sense-hat | sense_hat/sense_hat.py | SenseHat._trim_whitespace | def _trim_whitespace(self, char): # For loading text assets only
"""
Internal. Trims white space pixels from the front and back of loaded
text characters
"""
psum = lambda x: sum(sum(x, []))
if psum(char) > 0:
is_empty = True
while is_empty: # From front
row = char[0:8]
is_empty = psum(row) == 0
if is_empty:
del char[0:8]
is_empty = True
while is_empty: # From back
row = char[-8:]
is_empty = psum(row) == 0
if is_empty:
del char[-8:]
return char | python | def _trim_whitespace(self, char): # For loading text assets only
"""
Internal. Trims white space pixels from the front and back of loaded
text characters
"""
psum = lambda x: sum(sum(x, []))
if psum(char) > 0:
is_empty = True
while is_empty: # From front
row = char[0:8]
is_empty = psum(row) == 0
if is_empty:
del char[0:8]
is_empty = True
while is_empty: # From back
row = char[-8:]
is_empty = psum(row) == 0
if is_empty:
del char[-8:]
return char | [
"def",
"_trim_whitespace",
"(",
"self",
",",
"char",
")",
":",
"# For loading text assets only",
"psum",
"=",
"lambda",
"x",
":",
"sum",
"(",
"sum",
"(",
"x",
",",
"[",
"]",
")",
")",
"if",
"psum",
"(",
"char",
")",
">",
"0",
":",
"is_empty",
"=",
... | Internal. Trims white space pixels from the front and back of loaded
text characters | [
"Internal",
".",
"Trims",
"white",
"space",
"pixels",
"from",
"the",
"front",
"and",
"back",
"of",
"loaded",
"text",
"characters"
] | 9a37f0923ce8dbde69514c3b8d58d30de01c9ee7 | https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L120-L140 | train | 198,287 |
RPi-Distro/python-sense-hat | sense_hat/sense_hat.py | SenseHat._get_settings_file | def _get_settings_file(self, imu_settings_file):
"""
Internal. Logic to check for a system wide RTIMU ini file. This is
copied to the home folder if one is not already found there.
"""
ini_file = '%s.ini' % imu_settings_file
home_dir = pwd.getpwuid(os.getuid())[5]
home_path = os.path.join(home_dir, self.SETTINGS_HOME_PATH)
if not os.path.exists(home_path):
os.makedirs(home_path)
home_file = os.path.join(home_path, ini_file)
home_exists = os.path.isfile(home_file)
system_file = os.path.join('/etc', ini_file)
system_exists = os.path.isfile(system_file)
if system_exists and not home_exists:
shutil.copyfile(system_file, home_file)
return RTIMU.Settings(os.path.join(home_path, imu_settings_file)) | python | def _get_settings_file(self, imu_settings_file):
"""
Internal. Logic to check for a system wide RTIMU ini file. This is
copied to the home folder if one is not already found there.
"""
ini_file = '%s.ini' % imu_settings_file
home_dir = pwd.getpwuid(os.getuid())[5]
home_path = os.path.join(home_dir, self.SETTINGS_HOME_PATH)
if not os.path.exists(home_path):
os.makedirs(home_path)
home_file = os.path.join(home_path, ini_file)
home_exists = os.path.isfile(home_file)
system_file = os.path.join('/etc', ini_file)
system_exists = os.path.isfile(system_file)
if system_exists and not home_exists:
shutil.copyfile(system_file, home_file)
return RTIMU.Settings(os.path.join(home_path, imu_settings_file)) | [
"def",
"_get_settings_file",
"(",
"self",
",",
"imu_settings_file",
")",
":",
"ini_file",
"=",
"'%s.ini'",
"%",
"imu_settings_file",
"home_dir",
"=",
"pwd",
".",
"getpwuid",
"(",
"os",
".",
"getuid",
"(",
")",
")",
"[",
"5",
"]",
"home_path",
"=",
"os",
... | Internal. Logic to check for a system wide RTIMU ini file. This is
copied to the home folder if one is not already found there. | [
"Internal",
".",
"Logic",
"to",
"check",
"for",
"a",
"system",
"wide",
"RTIMU",
"ini",
"file",
".",
"This",
"is",
"copied",
"to",
"the",
"home",
"folder",
"if",
"one",
"is",
"not",
"already",
"found",
"there",
"."
] | 9a37f0923ce8dbde69514c3b8d58d30de01c9ee7 | https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L142-L163 | train | 198,288 |
RPi-Distro/python-sense-hat | sense_hat/sense_hat.py | SenseHat.set_rotation | def set_rotation(self, r=0, redraw=True):
"""
Sets the LED matrix rotation for viewing, adjust if the Pi is upside
down or sideways. 0 is with the Pi HDMI port facing downwards
"""
if r in self._pix_map.keys():
if redraw:
pixel_list = self.get_pixels()
self._rotation = r
if redraw:
self.set_pixels(pixel_list)
else:
raise ValueError('Rotation must be 0, 90, 180 or 270 degrees') | python | def set_rotation(self, r=0, redraw=True):
"""
Sets the LED matrix rotation for viewing, adjust if the Pi is upside
down or sideways. 0 is with the Pi HDMI port facing downwards
"""
if r in self._pix_map.keys():
if redraw:
pixel_list = self.get_pixels()
self._rotation = r
if redraw:
self.set_pixels(pixel_list)
else:
raise ValueError('Rotation must be 0, 90, 180 or 270 degrees') | [
"def",
"set_rotation",
"(",
"self",
",",
"r",
"=",
"0",
",",
"redraw",
"=",
"True",
")",
":",
"if",
"r",
"in",
"self",
".",
"_pix_map",
".",
"keys",
"(",
")",
":",
"if",
"redraw",
":",
"pixel_list",
"=",
"self",
".",
"get_pixels",
"(",
")",
"self... | Sets the LED matrix rotation for viewing, adjust if the Pi is upside
down or sideways. 0 is with the Pi HDMI port facing downwards | [
"Sets",
"the",
"LED",
"matrix",
"rotation",
"for",
"viewing",
"adjust",
"if",
"the",
"Pi",
"is",
"upside",
"down",
"or",
"sideways",
".",
"0",
"is",
"with",
"the",
"Pi",
"HDMI",
"port",
"facing",
"downwards"
] | 9a37f0923ce8dbde69514c3b8d58d30de01c9ee7 | https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L206-L219 | train | 198,289 |
RPi-Distro/python-sense-hat | sense_hat/sense_hat.py | SenseHat.flip_h | def flip_h(self, redraw=True):
"""
Flip LED matrix horizontal
"""
pixel_list = self.get_pixels()
flipped = []
for i in range(8):
offset = i * 8
flipped.extend(reversed(pixel_list[offset:offset + 8]))
if redraw:
self.set_pixels(flipped)
return flipped | python | def flip_h(self, redraw=True):
"""
Flip LED matrix horizontal
"""
pixel_list = self.get_pixels()
flipped = []
for i in range(8):
offset = i * 8
flipped.extend(reversed(pixel_list[offset:offset + 8]))
if redraw:
self.set_pixels(flipped)
return flipped | [
"def",
"flip_h",
"(",
"self",
",",
"redraw",
"=",
"True",
")",
":",
"pixel_list",
"=",
"self",
".",
"get_pixels",
"(",
")",
"flipped",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"8",
")",
":",
"offset",
"=",
"i",
"*",
"8",
"flipped",
".",
"... | Flip LED matrix horizontal | [
"Flip",
"LED",
"matrix",
"horizontal"
] | 9a37f0923ce8dbde69514c3b8d58d30de01c9ee7 | https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L244-L256 | train | 198,290 |
RPi-Distro/python-sense-hat | sense_hat/sense_hat.py | SenseHat.load_image | def load_image(self, file_path, redraw=True):
"""
Accepts a path to an 8 x 8 image file and updates the LED matrix with
the image
"""
if not os.path.exists(file_path):
raise IOError('%s not found' % file_path)
img = Image.open(file_path).convert('RGB')
pixel_list = list(map(list, img.getdata()))
if redraw:
self.set_pixels(pixel_list)
return pixel_list | python | def load_image(self, file_path, redraw=True):
"""
Accepts a path to an 8 x 8 image file and updates the LED matrix with
the image
"""
if not os.path.exists(file_path):
raise IOError('%s not found' % file_path)
img = Image.open(file_path).convert('RGB')
pixel_list = list(map(list, img.getdata()))
if redraw:
self.set_pixels(pixel_list)
return pixel_list | [
"def",
"load_image",
"(",
"self",
",",
"file_path",
",",
"redraw",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"raise",
"IOError",
"(",
"'%s not found'",
"%",
"file_path",
")",
"img",
"=",
"Image",
... | Accepts a path to an 8 x 8 image file and updates the LED matrix with
the image | [
"Accepts",
"a",
"path",
"to",
"an",
"8",
"x",
"8",
"image",
"file",
"and",
"updates",
"the",
"LED",
"matrix",
"with",
"the",
"image"
] | 9a37f0923ce8dbde69514c3b8d58d30de01c9ee7 | https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L373-L388 | train | 198,291 |
RPi-Distro/python-sense-hat | sense_hat/sense_hat.py | SenseHat._get_char_pixels | def _get_char_pixels(self, s):
"""
Internal. Safeguards the character indexed dictionary for the
show_message function below
"""
if len(s) == 1 and s in self._text_dict.keys():
return list(self._text_dict[s])
else:
return list(self._text_dict['?']) | python | def _get_char_pixels(self, s):
"""
Internal. Safeguards the character indexed dictionary for the
show_message function below
"""
if len(s) == 1 and s in self._text_dict.keys():
return list(self._text_dict[s])
else:
return list(self._text_dict['?']) | [
"def",
"_get_char_pixels",
"(",
"self",
",",
"s",
")",
":",
"if",
"len",
"(",
"s",
")",
"==",
"1",
"and",
"s",
"in",
"self",
".",
"_text_dict",
".",
"keys",
"(",
")",
":",
"return",
"list",
"(",
"self",
".",
"_text_dict",
"[",
"s",
"]",
")",
"e... | Internal. Safeguards the character indexed dictionary for the
show_message function below | [
"Internal",
".",
"Safeguards",
"the",
"character",
"indexed",
"dictionary",
"for",
"the",
"show_message",
"function",
"below"
] | 9a37f0923ce8dbde69514c3b8d58d30de01c9ee7 | https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L415-L424 | train | 198,292 |
RPi-Distro/python-sense-hat | sense_hat/sense_hat.py | SenseHat.show_message | def show_message(
self,
text_string,
scroll_speed=.1,
text_colour=[255, 255, 255],
back_colour=[0, 0, 0]
):
"""
Scrolls a string of text across the LED matrix using the specified
speed and colours
"""
# We must rotate the pixel map left through 90 degrees when drawing
# text, see _load_text_assets
previous_rotation = self._rotation
self._rotation -= 90
if self._rotation < 0:
self._rotation = 270
dummy_colour = [None, None, None]
string_padding = [dummy_colour] * 64
letter_padding = [dummy_colour] * 8
# Build pixels from dictionary
scroll_pixels = []
scroll_pixels.extend(string_padding)
for s in text_string:
scroll_pixels.extend(self._trim_whitespace(self._get_char_pixels(s)))
scroll_pixels.extend(letter_padding)
scroll_pixels.extend(string_padding)
# Recolour pixels as necessary
coloured_pixels = [
text_colour if pixel == [255, 255, 255] else back_colour
for pixel in scroll_pixels
]
# Shift right by 8 pixels per frame to scroll
scroll_length = len(coloured_pixels) // 8
for i in range(scroll_length - 8):
start = i * 8
end = start + 64
self.set_pixels(coloured_pixels[start:end])
time.sleep(scroll_speed)
self._rotation = previous_rotation | python | def show_message(
self,
text_string,
scroll_speed=.1,
text_colour=[255, 255, 255],
back_colour=[0, 0, 0]
):
"""
Scrolls a string of text across the LED matrix using the specified
speed and colours
"""
# We must rotate the pixel map left through 90 degrees when drawing
# text, see _load_text_assets
previous_rotation = self._rotation
self._rotation -= 90
if self._rotation < 0:
self._rotation = 270
dummy_colour = [None, None, None]
string_padding = [dummy_colour] * 64
letter_padding = [dummy_colour] * 8
# Build pixels from dictionary
scroll_pixels = []
scroll_pixels.extend(string_padding)
for s in text_string:
scroll_pixels.extend(self._trim_whitespace(self._get_char_pixels(s)))
scroll_pixels.extend(letter_padding)
scroll_pixels.extend(string_padding)
# Recolour pixels as necessary
coloured_pixels = [
text_colour if pixel == [255, 255, 255] else back_colour
for pixel in scroll_pixels
]
# Shift right by 8 pixels per frame to scroll
scroll_length = len(coloured_pixels) // 8
for i in range(scroll_length - 8):
start = i * 8
end = start + 64
self.set_pixels(coloured_pixels[start:end])
time.sleep(scroll_speed)
self._rotation = previous_rotation | [
"def",
"show_message",
"(",
"self",
",",
"text_string",
",",
"scroll_speed",
"=",
".1",
",",
"text_colour",
"=",
"[",
"255",
",",
"255",
",",
"255",
"]",
",",
"back_colour",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
")",
":",
"# We must rotate the pixel ... | Scrolls a string of text across the LED matrix using the specified
speed and colours | [
"Scrolls",
"a",
"string",
"of",
"text",
"across",
"the",
"LED",
"matrix",
"using",
"the",
"specified",
"speed",
"and",
"colours"
] | 9a37f0923ce8dbde69514c3b8d58d30de01c9ee7 | https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L426-L466 | train | 198,293 |
RPi-Distro/python-sense-hat | sense_hat/sense_hat.py | SenseHat.show_letter | def show_letter(
self,
s,
text_colour=[255, 255, 255],
back_colour=[0, 0, 0]
):
"""
Displays a single text character on the LED matrix using the specified
colours
"""
if len(s) > 1:
raise ValueError('Only one character may be passed into this method')
# We must rotate the pixel map left through 90 degrees when drawing
# text, see _load_text_assets
previous_rotation = self._rotation
self._rotation -= 90
if self._rotation < 0:
self._rotation = 270
dummy_colour = [None, None, None]
pixel_list = [dummy_colour] * 8
pixel_list.extend(self._get_char_pixels(s))
pixel_list.extend([dummy_colour] * 16)
coloured_pixels = [
text_colour if pixel == [255, 255, 255] else back_colour
for pixel in pixel_list
]
self.set_pixels(coloured_pixels)
self._rotation = previous_rotation | python | def show_letter(
self,
s,
text_colour=[255, 255, 255],
back_colour=[0, 0, 0]
):
"""
Displays a single text character on the LED matrix using the specified
colours
"""
if len(s) > 1:
raise ValueError('Only one character may be passed into this method')
# We must rotate the pixel map left through 90 degrees when drawing
# text, see _load_text_assets
previous_rotation = self._rotation
self._rotation -= 90
if self._rotation < 0:
self._rotation = 270
dummy_colour = [None, None, None]
pixel_list = [dummy_colour] * 8
pixel_list.extend(self._get_char_pixels(s))
pixel_list.extend([dummy_colour] * 16)
coloured_pixels = [
text_colour if pixel == [255, 255, 255] else back_colour
for pixel in pixel_list
]
self.set_pixels(coloured_pixels)
self._rotation = previous_rotation | [
"def",
"show_letter",
"(",
"self",
",",
"s",
",",
"text_colour",
"=",
"[",
"255",
",",
"255",
",",
"255",
"]",
",",
"back_colour",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
")",
":",
"if",
"len",
"(",
"s",
")",
">",
"1",
":",
"raise",
"ValueErr... | Displays a single text character on the LED matrix using the specified
colours | [
"Displays",
"a",
"single",
"text",
"character",
"on",
"the",
"LED",
"matrix",
"using",
"the",
"specified",
"colours"
] | 9a37f0923ce8dbde69514c3b8d58d30de01c9ee7 | https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L468-L496 | train | 198,294 |
RPi-Distro/python-sense-hat | sense_hat/sense_hat.py | SenseHat.gamma_reset | def gamma_reset(self):
"""
Resets the LED matrix gamma correction to default
"""
with open(self._fb_device) as f:
fcntl.ioctl(f, self.SENSE_HAT_FB_FBIORESET_GAMMA, self.SENSE_HAT_FB_GAMMA_DEFAULT) | python | def gamma_reset(self):
"""
Resets the LED matrix gamma correction to default
"""
with open(self._fb_device) as f:
fcntl.ioctl(f, self.SENSE_HAT_FB_FBIORESET_GAMMA, self.SENSE_HAT_FB_GAMMA_DEFAULT) | [
"def",
"gamma_reset",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"_fb_device",
")",
"as",
"f",
":",
"fcntl",
".",
"ioctl",
"(",
"f",
",",
"self",
".",
"SENSE_HAT_FB_FBIORESET_GAMMA",
",",
"self",
".",
"SENSE_HAT_FB_GAMMA_DEFAULT",
")"
] | Resets the LED matrix gamma correction to default | [
"Resets",
"the",
"LED",
"matrix",
"gamma",
"correction",
"to",
"default"
] | 9a37f0923ce8dbde69514c3b8d58d30de01c9ee7 | https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L519-L525 | train | 198,295 |
RPi-Distro/python-sense-hat | sense_hat/sense_hat.py | SenseHat._init_humidity | def _init_humidity(self):
"""
Internal. Initialises the humidity sensor via RTIMU
"""
if not self._humidity_init:
self._humidity_init = self._humidity.humidityInit()
if not self._humidity_init:
raise OSError('Humidity Init Failed') | python | def _init_humidity(self):
"""
Internal. Initialises the humidity sensor via RTIMU
"""
if not self._humidity_init:
self._humidity_init = self._humidity.humidityInit()
if not self._humidity_init:
raise OSError('Humidity Init Failed') | [
"def",
"_init_humidity",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_humidity_init",
":",
"self",
".",
"_humidity_init",
"=",
"self",
".",
"_humidity",
".",
"humidityInit",
"(",
")",
"if",
"not",
"self",
".",
"_humidity_init",
":",
"raise",
"OSError... | Internal. Initialises the humidity sensor via RTIMU | [
"Internal",
".",
"Initialises",
"the",
"humidity",
"sensor",
"via",
"RTIMU"
] | 9a37f0923ce8dbde69514c3b8d58d30de01c9ee7 | https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L541-L549 | train | 198,296 |
RPi-Distro/python-sense-hat | sense_hat/sense_hat.py | SenseHat._init_pressure | def _init_pressure(self):
"""
Internal. Initialises the pressure sensor via RTIMU
"""
if not self._pressure_init:
self._pressure_init = self._pressure.pressureInit()
if not self._pressure_init:
raise OSError('Pressure Init Failed') | python | def _init_pressure(self):
"""
Internal. Initialises the pressure sensor via RTIMU
"""
if not self._pressure_init:
self._pressure_init = self._pressure.pressureInit()
if not self._pressure_init:
raise OSError('Pressure Init Failed') | [
"def",
"_init_pressure",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pressure_init",
":",
"self",
".",
"_pressure_init",
"=",
"self",
".",
"_pressure",
".",
"pressureInit",
"(",
")",
"if",
"not",
"self",
".",
"_pressure_init",
":",
"raise",
"OSError... | Internal. Initialises the pressure sensor via RTIMU | [
"Internal",
".",
"Initialises",
"the",
"pressure",
"sensor",
"via",
"RTIMU"
] | 9a37f0923ce8dbde69514c3b8d58d30de01c9ee7 | https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L551-L559 | train | 198,297 |
RPi-Distro/python-sense-hat | sense_hat/sense_hat.py | SenseHat.get_humidity | def get_humidity(self):
"""
Returns the percentage of relative humidity
"""
self._init_humidity() # Ensure humidity sensor is initialised
humidity = 0
data = self._humidity.humidityRead()
if (data[0]): # Humidity valid
humidity = data[1]
return humidity | python | def get_humidity(self):
"""
Returns the percentage of relative humidity
"""
self._init_humidity() # Ensure humidity sensor is initialised
humidity = 0
data = self._humidity.humidityRead()
if (data[0]): # Humidity valid
humidity = data[1]
return humidity | [
"def",
"get_humidity",
"(",
"self",
")",
":",
"self",
".",
"_init_humidity",
"(",
")",
"# Ensure humidity sensor is initialised",
"humidity",
"=",
"0",
"data",
"=",
"self",
".",
"_humidity",
".",
"humidityRead",
"(",
")",
"if",
"(",
"data",
"[",
"0",
"]",
... | Returns the percentage of relative humidity | [
"Returns",
"the",
"percentage",
"of",
"relative",
"humidity"
] | 9a37f0923ce8dbde69514c3b8d58d30de01c9ee7 | https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L561-L571 | train | 198,298 |
RPi-Distro/python-sense-hat | sense_hat/sense_hat.py | SenseHat.get_temperature_from_humidity | def get_temperature_from_humidity(self):
"""
Returns the temperature in Celsius from the humidity sensor
"""
self._init_humidity() # Ensure humidity sensor is initialised
temp = 0
data = self._humidity.humidityRead()
if (data[2]): # Temp valid
temp = data[3]
return temp | python | def get_temperature_from_humidity(self):
"""
Returns the temperature in Celsius from the humidity sensor
"""
self._init_humidity() # Ensure humidity sensor is initialised
temp = 0
data = self._humidity.humidityRead()
if (data[2]): # Temp valid
temp = data[3]
return temp | [
"def",
"get_temperature_from_humidity",
"(",
"self",
")",
":",
"self",
".",
"_init_humidity",
"(",
")",
"# Ensure humidity sensor is initialised",
"temp",
"=",
"0",
"data",
"=",
"self",
".",
"_humidity",
".",
"humidityRead",
"(",
")",
"if",
"(",
"data",
"[",
"... | Returns the temperature in Celsius from the humidity sensor | [
"Returns",
"the",
"temperature",
"in",
"Celsius",
"from",
"the",
"humidity",
"sensor"
] | 9a37f0923ce8dbde69514c3b8d58d30de01c9ee7 | https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L577-L587 | train | 198,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.