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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
OzymandiasTheGreat/python-libinput | libinput/event.py | PointerEvent.has_axis | def has_axis(self, axis):
"""Check if the event has a valid value for the given axis.
If this method returns True for an axis and :meth:`get_axis_value`
returns a value of 0, the event is a scroll stop event.
For pointer events that are not of type
:attr:`~libinput.constant.EventType.POINTER_AXIS`, this method raises
:exc:`AttributeError`.
Args:
axis (~libinput.constant.PointerAxis): The axis to check.
Returns:
bool: True if this event contains a value for this axis.
Raises:
AttributeError
"""
if self.type != EventType.POINTER_AXIS:
raise AttributeError(_wrong_meth.format(self.type))
return self._libinput.libinput_event_pointer_has_axis(
self._handle, axis) | python | def has_axis(self, axis):
"""Check if the event has a valid value for the given axis.
If this method returns True for an axis and :meth:`get_axis_value`
returns a value of 0, the event is a scroll stop event.
For pointer events that are not of type
:attr:`~libinput.constant.EventType.POINTER_AXIS`, this method raises
:exc:`AttributeError`.
Args:
axis (~libinput.constant.PointerAxis): The axis to check.
Returns:
bool: True if this event contains a value for this axis.
Raises:
AttributeError
"""
if self.type != EventType.POINTER_AXIS:
raise AttributeError(_wrong_meth.format(self.type))
return self._libinput.libinput_event_pointer_has_axis(
self._handle, axis) | [
"def",
"has_axis",
"(",
"self",
",",
"axis",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"POINTER_AXIS",
":",
"raise",
"AttributeError",
"(",
"_wrong_meth",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_li... | Check if the event has a valid value for the given axis.
If this method returns True for an axis and :meth:`get_axis_value`
returns a value of 0, the event is a scroll stop event.
For pointer events that are not of type
:attr:`~libinput.constant.EventType.POINTER_AXIS`, this method raises
:exc:`AttributeError`.
Args:
axis (~libinput.constant.PointerAxis): The axis to check.
Returns:
bool: True if this event contains a value for this axis.
Raises:
AttributeError | [
"Check",
"if",
"the",
"event",
"has",
"a",
"valid",
"value",
"for",
"the",
"given",
"axis",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L327-L348 | train | 53,700 |
OzymandiasTheGreat/python-libinput | libinput/event.py | PointerEvent.get_axis_value | def get_axis_value(self, axis):
"""Return the axis value of the given axis.
The interpretation of the value depends on the axis. For the two
scrolling axes :attr:`~libinput.constant.PointerAxis.SCROLL_VERTICAL`
and :attr:`~libinput.constant.PointerAxis.SCROLL_HORIZONTAL`, the value
of the event is in relative scroll units, with the positive direction
being down or right, respectively. For the interpretation of the value,
see :attr:`axis_source`.
If :meth:`has_axis` returns False for an axis, this method returns 0
for that axis.
For pointer events that are not of type
:attr:`~libinput.constant.Event.POINTER_AXIS`, this method raises
:exc:`AttributeError`.
Args:
axis (~libinput.constant.PointerAxis): The axis who's value to get.
Returns:
float: The axis value of this event.
Raises:
AttributeError
"""
if self.type != EventType.POINTER_AXIS:
raise AttributeError(_wrong_meth.format(self.type))
return self._libinput.libinput_event_pointer_get_axis_value(
self._handle, axis) | python | def get_axis_value(self, axis):
"""Return the axis value of the given axis.
The interpretation of the value depends on the axis. For the two
scrolling axes :attr:`~libinput.constant.PointerAxis.SCROLL_VERTICAL`
and :attr:`~libinput.constant.PointerAxis.SCROLL_HORIZONTAL`, the value
of the event is in relative scroll units, with the positive direction
being down or right, respectively. For the interpretation of the value,
see :attr:`axis_source`.
If :meth:`has_axis` returns False for an axis, this method returns 0
for that axis.
For pointer events that are not of type
:attr:`~libinput.constant.Event.POINTER_AXIS`, this method raises
:exc:`AttributeError`.
Args:
axis (~libinput.constant.PointerAxis): The axis who's value to get.
Returns:
float: The axis value of this event.
Raises:
AttributeError
"""
if self.type != EventType.POINTER_AXIS:
raise AttributeError(_wrong_meth.format(self.type))
return self._libinput.libinput_event_pointer_get_axis_value(
self._handle, axis) | [
"def",
"get_axis_value",
"(",
"self",
",",
"axis",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"POINTER_AXIS",
":",
"raise",
"AttributeError",
"(",
"_wrong_meth",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
... | Return the axis value of the given axis.
The interpretation of the value depends on the axis. For the two
scrolling axes :attr:`~libinput.constant.PointerAxis.SCROLL_VERTICAL`
and :attr:`~libinput.constant.PointerAxis.SCROLL_HORIZONTAL`, the value
of the event is in relative scroll units, with the positive direction
being down or right, respectively. For the interpretation of the value,
see :attr:`axis_source`.
If :meth:`has_axis` returns False for an axis, this method returns 0
for that axis.
For pointer events that are not of type
:attr:`~libinput.constant.Event.POINTER_AXIS`, this method raises
:exc:`AttributeError`.
Args:
axis (~libinput.constant.PointerAxis): The axis who's value to get.
Returns:
float: The axis value of this event.
Raises:
AttributeError | [
"Return",
"the",
"axis",
"value",
"of",
"the",
"given",
"axis",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L350-L378 | train | 53,701 |
OzymandiasTheGreat/python-libinput | libinput/event.py | PointerEvent.axis_source | def axis_source(self):
"""The source for a given axis event.
Axis events (scroll events) can be caused by a hardware item such as
a scroll wheel or emulated from other input sources, such as two-finger
or edge scrolling on a touchpad.
If the source is :attr:`~libinput.constant.PointerAxisSource.FINGER`,
libinput guarantees that a scroll sequence is terminated with a scroll
value of 0. A caller may use this information to decide on whether
kinetic scrolling should be triggered on this scroll sequence. The
coordinate system is identical to the cursor movement, i.e. a scroll
value of 1 represents the equivalent relative motion of 1.
If the source is :attr:`~libinput.constant.PointerAxisSource.WHEEL`,
no terminating event is guaranteed (though it may happen). Scrolling
is in discrete steps, the value is the angle the wheel moved in
degrees. The default is 15 degrees per wheel click, but some mice may
have differently grained wheels. It is up to the caller how to
interpret such different step sizes.
If the source is :attr:`~libinput.constant.PointerAxisSource.CONTINUOUS`,
no terminating event is guaranteed (though it may happen). The
coordinate system is identical to the cursor movement, i.e. a scroll
value of 1 represents the equivalent relative motion of 1.
If the source is :attr:`~libinput.constant.PointerAxisSource.WHEEL_TILT`,
no terminating event is guaranteed (though it may happen). Scrolling
is in discrete steps and there is no physical equivalent for the value
returned here. For backwards compatibility, the value of this
property is identical to a single mouse wheel rotation by this device
(see the documentation for
:attr:`~libinput.constant.PointerAxisSource.WHEEL` above). Callers
should not use this value but instead exclusively refer to the value
returned by :meth:`get_axis_value_discrete`.
For pointer events that are not of type
:attr:`~libinput.constant.Event.POINTER_AXIS`, this property raises
:exc:`AttributeError`.
Returns:
~libinput.constant.PointerAxisSource: The source for this axis
event.
Raises:
AttributeError
"""
if self.type != EventType.POINTER_AXIS:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_pointer_get_axis_source(
self._handle) | python | def axis_source(self):
"""The source for a given axis event.
Axis events (scroll events) can be caused by a hardware item such as
a scroll wheel or emulated from other input sources, such as two-finger
or edge scrolling on a touchpad.
If the source is :attr:`~libinput.constant.PointerAxisSource.FINGER`,
libinput guarantees that a scroll sequence is terminated with a scroll
value of 0. A caller may use this information to decide on whether
kinetic scrolling should be triggered on this scroll sequence. The
coordinate system is identical to the cursor movement, i.e. a scroll
value of 1 represents the equivalent relative motion of 1.
If the source is :attr:`~libinput.constant.PointerAxisSource.WHEEL`,
no terminating event is guaranteed (though it may happen). Scrolling
is in discrete steps, the value is the angle the wheel moved in
degrees. The default is 15 degrees per wheel click, but some mice may
have differently grained wheels. It is up to the caller how to
interpret such different step sizes.
If the source is :attr:`~libinput.constant.PointerAxisSource.CONTINUOUS`,
no terminating event is guaranteed (though it may happen). The
coordinate system is identical to the cursor movement, i.e. a scroll
value of 1 represents the equivalent relative motion of 1.
If the source is :attr:`~libinput.constant.PointerAxisSource.WHEEL_TILT`,
no terminating event is guaranteed (though it may happen). Scrolling
is in discrete steps and there is no physical equivalent for the value
returned here. For backwards compatibility, the value of this
property is identical to a single mouse wheel rotation by this device
(see the documentation for
:attr:`~libinput.constant.PointerAxisSource.WHEEL` above). Callers
should not use this value but instead exclusively refer to the value
returned by :meth:`get_axis_value_discrete`.
For pointer events that are not of type
:attr:`~libinput.constant.Event.POINTER_AXIS`, this property raises
:exc:`AttributeError`.
Returns:
~libinput.constant.PointerAxisSource: The source for this axis
event.
Raises:
AttributeError
"""
if self.type != EventType.POINTER_AXIS:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_pointer_get_axis_source(
self._handle) | [
"def",
"axis_source",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"POINTER_AXIS",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_libinput",
"."... | The source for a given axis event.
Axis events (scroll events) can be caused by a hardware item such as
a scroll wheel or emulated from other input sources, such as two-finger
or edge scrolling on a touchpad.
If the source is :attr:`~libinput.constant.PointerAxisSource.FINGER`,
libinput guarantees that a scroll sequence is terminated with a scroll
value of 0. A caller may use this information to decide on whether
kinetic scrolling should be triggered on this scroll sequence. The
coordinate system is identical to the cursor movement, i.e. a scroll
value of 1 represents the equivalent relative motion of 1.
If the source is :attr:`~libinput.constant.PointerAxisSource.WHEEL`,
no terminating event is guaranteed (though it may happen). Scrolling
is in discrete steps, the value is the angle the wheel moved in
degrees. The default is 15 degrees per wheel click, but some mice may
have differently grained wheels. It is up to the caller how to
interpret such different step sizes.
If the source is :attr:`~libinput.constant.PointerAxisSource.CONTINUOUS`,
no terminating event is guaranteed (though it may happen). The
coordinate system is identical to the cursor movement, i.e. a scroll
value of 1 represents the equivalent relative motion of 1.
If the source is :attr:`~libinput.constant.PointerAxisSource.WHEEL_TILT`,
no terminating event is guaranteed (though it may happen). Scrolling
is in discrete steps and there is no physical equivalent for the value
returned here. For backwards compatibility, the value of this
property is identical to a single mouse wheel rotation by this device
(see the documentation for
:attr:`~libinput.constant.PointerAxisSource.WHEEL` above). Callers
should not use this value but instead exclusively refer to the value
returned by :meth:`get_axis_value_discrete`.
For pointer events that are not of type
:attr:`~libinput.constant.Event.POINTER_AXIS`, this property raises
:exc:`AttributeError`.
Returns:
~libinput.constant.PointerAxisSource: The source for this axis
event.
Raises:
AttributeError | [
"The",
"source",
"for",
"a",
"given",
"axis",
"event",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L381-L429 | train | 53,702 |
OzymandiasTheGreat/python-libinput | libinput/event.py | PointerEvent.get_axis_value_discrete | def get_axis_value_discrete(self, axis):
"""Return the axis value in discrete steps for a given axis event.
How a value translates into a discrete step depends on the source.
If the source is :attr:`~libinput.constant.PointerAxisSource.WHEEL`,
the discrete value correspond to the number of physical mouse wheel
clicks.
If the source is :attr:`~libinput.constant.PointerAxisSource.CONTINUOUS`
or :attr:`~libinput.constant.PointerAxisSource.FINGER`, the discrete
value is always 0.
Args:
axis (~libinput.constant.PointerAxis): The axis who's value to get.
Returns:
float: The discrete value for the given event.
Raises:
AttributeError
"""
if self.type != EventType.POINTER_AXIS:
raise AttributeError(_wrong_meth.format(self.type))
return self._libinput.libinput_event_pointer_get_axis_value_discrete(
self._handle, axis) | python | def get_axis_value_discrete(self, axis):
"""Return the axis value in discrete steps for a given axis event.
How a value translates into a discrete step depends on the source.
If the source is :attr:`~libinput.constant.PointerAxisSource.WHEEL`,
the discrete value correspond to the number of physical mouse wheel
clicks.
If the source is :attr:`~libinput.constant.PointerAxisSource.CONTINUOUS`
or :attr:`~libinput.constant.PointerAxisSource.FINGER`, the discrete
value is always 0.
Args:
axis (~libinput.constant.PointerAxis): The axis who's value to get.
Returns:
float: The discrete value for the given event.
Raises:
AttributeError
"""
if self.type != EventType.POINTER_AXIS:
raise AttributeError(_wrong_meth.format(self.type))
return self._libinput.libinput_event_pointer_get_axis_value_discrete(
self._handle, axis) | [
"def",
"get_axis_value_discrete",
"(",
"self",
",",
"axis",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"POINTER_AXIS",
":",
"raise",
"AttributeError",
"(",
"_wrong_meth",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self"... | Return the axis value in discrete steps for a given axis event.
How a value translates into a discrete step depends on the source.
If the source is :attr:`~libinput.constant.PointerAxisSource.WHEEL`,
the discrete value correspond to the number of physical mouse wheel
clicks.
If the source is :attr:`~libinput.constant.PointerAxisSource.CONTINUOUS`
or :attr:`~libinput.constant.PointerAxisSource.FINGER`, the discrete
value is always 0.
Args:
axis (~libinput.constant.PointerAxis): The axis who's value to get.
Returns:
float: The discrete value for the given event.
Raises:
AttributeError | [
"Return",
"the",
"axis",
"value",
"in",
"discrete",
"steps",
"for",
"a",
"given",
"axis",
"event",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L431-L454 | train | 53,703 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TouchEvent.slot | def slot(self):
"""The slot of this touch event.
See the kernel's multitouch protocol B documentation for more
information.
If the touch event has no assigned slot, for example if it is from
a single touch device, this property returns -1.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_UP`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION` or
:attr:`~libinput.constant.EventType.TOUCH_CANCEL`, this property
raises :exc:`AttributeError`.
Returns:
int: The slot of this touch event.
Raises:
AttributeError
"""
if self.type == EventType.TOUCH_FRAME:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_touch_get_slot(self._handle) | python | def slot(self):
"""The slot of this touch event.
See the kernel's multitouch protocol B documentation for more
information.
If the touch event has no assigned slot, for example if it is from
a single touch device, this property returns -1.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_UP`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION` or
:attr:`~libinput.constant.EventType.TOUCH_CANCEL`, this property
raises :exc:`AttributeError`.
Returns:
int: The slot of this touch event.
Raises:
AttributeError
"""
if self.type == EventType.TOUCH_FRAME:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_touch_get_slot(self._handle) | [
"def",
"slot",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"==",
"EventType",
".",
"TOUCH_FRAME",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_libinput",
".",
"lib... | The slot of this touch event.
See the kernel's multitouch protocol B documentation for more
information.
If the touch event has no assigned slot, for example if it is from
a single touch device, this property returns -1.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_UP`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION` or
:attr:`~libinput.constant.EventType.TOUCH_CANCEL`, this property
raises :exc:`AttributeError`.
Returns:
int: The slot of this touch event.
Raises:
AttributeError | [
"The",
"slot",
"of",
"this",
"touch",
"event",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L574-L597 | train | 53,704 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TouchEvent.seat_slot | def seat_slot(self):
"""The seat slot of the touch event.
A seat slot is a non-negative seat wide unique identifier of an active
touch point.
Events from single touch devices will be represented as one individual
touch point per device.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_UP`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION` or
:attr:`~libinput.constant.EventType.TOUCH_CANCEL`, this property
raises :exc:`AssertionError`.
Returns:
int: The seat slot of the touch event.
Raises:
AssertionError
"""
if self.type == EventType.TOUCH_FRAME:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_touch_get_seat_slot(self._handle) | python | def seat_slot(self):
"""The seat slot of the touch event.
A seat slot is a non-negative seat wide unique identifier of an active
touch point.
Events from single touch devices will be represented as one individual
touch point per device.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_UP`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION` or
:attr:`~libinput.constant.EventType.TOUCH_CANCEL`, this property
raises :exc:`AssertionError`.
Returns:
int: The seat slot of the touch event.
Raises:
AssertionError
"""
if self.type == EventType.TOUCH_FRAME:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_touch_get_seat_slot(self._handle) | [
"def",
"seat_slot",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"==",
"EventType",
".",
"TOUCH_FRAME",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_libinput",
".",
... | The seat slot of the touch event.
A seat slot is a non-negative seat wide unique identifier of an active
touch point.
Events from single touch devices will be represented as one individual
touch point per device.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_UP`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION` or
:attr:`~libinput.constant.EventType.TOUCH_CANCEL`, this property
raises :exc:`AssertionError`.
Returns:
int: The seat slot of the touch event.
Raises:
AssertionError | [
"The",
"seat",
"slot",
"of",
"the",
"touch",
"event",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L600-L623 | train | 53,705 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TouchEvent.coords | def coords(self):
"""The current absolute coordinates of the touch event,
in mm from the top left corner of the device.
To get the corresponding output screen coordinates, use
:meth:`transform_coords`.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION`, this property
raises :exc:`AttributeError`.
Returns:
(float, float): The current absolute (x, y) coordinates.
Raises:
AttributeError
"""
if self.type not in {EventType.TOUCH_DOWN, EventType.TOUCH_MOTION}:
raise AttributeError(_wrong_prop.format(self.type))
x = self._libinput.libinput_event_touch_get_x(self._handle)
y = self._libinput.libinput_event_touch_get_y(self._handle)
return x, y | python | def coords(self):
"""The current absolute coordinates of the touch event,
in mm from the top left corner of the device.
To get the corresponding output screen coordinates, use
:meth:`transform_coords`.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION`, this property
raises :exc:`AttributeError`.
Returns:
(float, float): The current absolute (x, y) coordinates.
Raises:
AttributeError
"""
if self.type not in {EventType.TOUCH_DOWN, EventType.TOUCH_MOTION}:
raise AttributeError(_wrong_prop.format(self.type))
x = self._libinput.libinput_event_touch_get_x(self._handle)
y = self._libinput.libinput_event_touch_get_y(self._handle)
return x, y | [
"def",
"coords",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"not",
"in",
"{",
"EventType",
".",
"TOUCH_DOWN",
",",
"EventType",
".",
"TOUCH_MOTION",
"}",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
... | The current absolute coordinates of the touch event,
in mm from the top left corner of the device.
To get the corresponding output screen coordinates, use
:meth:`transform_coords`.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION`, this property
raises :exc:`AttributeError`.
Returns:
(float, float): The current absolute (x, y) coordinates.
Raises:
AttributeError | [
"The",
"current",
"absolute",
"coordinates",
"of",
"the",
"touch",
"event",
"in",
"mm",
"from",
"the",
"top",
"left",
"corner",
"of",
"the",
"device",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L626-L647 | train | 53,706 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TouchEvent.transform_coords | def transform_coords(self, width, height):
"""Return the current absolute coordinates of the touch event,
transformed to screen coordinates.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION`, this method
raises :exc:`AttributeError`.
Args:
width (int): The current output screen width.
height (int): The current output screen height.
Returns:
(float, float): The current absolute (x, y) coordinates transformed
to screen coordinates.
"""
if self.type not in {EventType.TOUCH_DOWN, EventType.TOUCH_MOTION}:
raise AttributeError(_wrong_meth.format(self.type))
x = self._libinput.libinput_event_touch_get_x_transformed(
self._handle, width)
y = self._libinput.libinput_event_touch_get_y_transformed(
self._handle, height)
return x, y | python | def transform_coords(self, width, height):
"""Return the current absolute coordinates of the touch event,
transformed to screen coordinates.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION`, this method
raises :exc:`AttributeError`.
Args:
width (int): The current output screen width.
height (int): The current output screen height.
Returns:
(float, float): The current absolute (x, y) coordinates transformed
to screen coordinates.
"""
if self.type not in {EventType.TOUCH_DOWN, EventType.TOUCH_MOTION}:
raise AttributeError(_wrong_meth.format(self.type))
x = self._libinput.libinput_event_touch_get_x_transformed(
self._handle, width)
y = self._libinput.libinput_event_touch_get_y_transformed(
self._handle, height)
return x, y | [
"def",
"transform_coords",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"if",
"self",
".",
"type",
"not",
"in",
"{",
"EventType",
".",
"TOUCH_DOWN",
",",
"EventType",
".",
"TOUCH_MOTION",
"}",
":",
"raise",
"AttributeError",
"(",
"_wrong_meth",
".",... | Return the current absolute coordinates of the touch event,
transformed to screen coordinates.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION`, this method
raises :exc:`AttributeError`.
Args:
width (int): The current output screen width.
height (int): The current output screen height.
Returns:
(float, float): The current absolute (x, y) coordinates transformed
to screen coordinates. | [
"Return",
"the",
"current",
"absolute",
"coordinates",
"of",
"the",
"touch",
"event",
"transformed",
"to",
"screen",
"coordinates",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L649-L671 | train | 53,707 |
OzymandiasTheGreat/python-libinput | libinput/event.py | GestureEvent.cancelled | def cancelled(self):
"""Return if the gesture ended normally, or if it was cancelled.
For gesture events that are not of type
:attr:`~libinput.constant.EventType.GESTURE_SWIPE_END` or
:attr:`~libinput.constant.EventType.GESTURE_PINCH_END`, this property
raises :exc:`AttributeError`.
Returns:
bool: :obj:`True` indicating that the gesture was cancelled.
Raises:
AttributeError
"""
if self.type not in {EventType.GESTURE_SWIPE_END,
EventType.GESTURE_PINCH_END}:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_gesture_get_cancelled(self._handle) | python | def cancelled(self):
"""Return if the gesture ended normally, or if it was cancelled.
For gesture events that are not of type
:attr:`~libinput.constant.EventType.GESTURE_SWIPE_END` or
:attr:`~libinput.constant.EventType.GESTURE_PINCH_END`, this property
raises :exc:`AttributeError`.
Returns:
bool: :obj:`True` indicating that the gesture was cancelled.
Raises:
AttributeError
"""
if self.type not in {EventType.GESTURE_SWIPE_END,
EventType.GESTURE_PINCH_END}:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_gesture_get_cancelled(self._handle) | [
"def",
"cancelled",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"not",
"in",
"{",
"EventType",
".",
"GESTURE_SWIPE_END",
",",
"EventType",
".",
"GESTURE_PINCH_END",
"}",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
... | Return if the gesture ended normally, or if it was cancelled.
For gesture events that are not of type
:attr:`~libinput.constant.EventType.GESTURE_SWIPE_END` or
:attr:`~libinput.constant.EventType.GESTURE_PINCH_END`, this property
raises :exc:`AttributeError`.
Returns:
bool: :obj:`True` indicating that the gesture was cancelled.
Raises:
AttributeError | [
"Return",
"if",
"the",
"gesture",
"ended",
"normally",
"or",
"if",
"it",
"was",
"cancelled",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L752-L769 | train | 53,708 |
OzymandiasTheGreat/python-libinput | libinput/event.py | GestureEvent.scale | def scale(self):
"""The absolute scale of a pinch gesture, the scale is
the division of the current distance between the fingers and
the distance at the start of the gesture.
The scale begins at 1.0, and if e.g. the fingers moved together by
50% then the scale will become 0.5, if they move twice as far apart
as initially the scale becomes 2.0, etc.
For gesture events that are of type
:attr:`~libinput.constant.EventType.GESTURE_PINCH_BEGIN`, this property
returns 1.0.
For gesture events that are of type
:attr:`~libinput.constant.EventType.GESTURE_PINCH_END`, this property
returns the scale value of the most recent
:attr:`~libinput.constant.EventType.GESTURE_PINCH_UPDATE` event
(if any) or 1.0 otherwise.
For all other events this property raises :exc:`AttributeError`.
Returns:
float: The absolute scale of a pinch gesture.
Raises:
AttributeError
"""
if self.type not in {EventType.GESTURE_PINCH_BEGIN,
EventType.GESTURE_PINCH_UPDATE, EventType.GESTURE_PINCH_END}:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_gesture_get_scale(self._handle) | python | def scale(self):
"""The absolute scale of a pinch gesture, the scale is
the division of the current distance between the fingers and
the distance at the start of the gesture.
The scale begins at 1.0, and if e.g. the fingers moved together by
50% then the scale will become 0.5, if they move twice as far apart
as initially the scale becomes 2.0, etc.
For gesture events that are of type
:attr:`~libinput.constant.EventType.GESTURE_PINCH_BEGIN`, this property
returns 1.0.
For gesture events that are of type
:attr:`~libinput.constant.EventType.GESTURE_PINCH_END`, this property
returns the scale value of the most recent
:attr:`~libinput.constant.EventType.GESTURE_PINCH_UPDATE` event
(if any) or 1.0 otherwise.
For all other events this property raises :exc:`AttributeError`.
Returns:
float: The absolute scale of a pinch gesture.
Raises:
AttributeError
"""
if self.type not in {EventType.GESTURE_PINCH_BEGIN,
EventType.GESTURE_PINCH_UPDATE, EventType.GESTURE_PINCH_END}:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_gesture_get_scale(self._handle) | [
"def",
"scale",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"not",
"in",
"{",
"EventType",
".",
"GESTURE_PINCH_BEGIN",
",",
"EventType",
".",
"GESTURE_PINCH_UPDATE",
",",
"EventType",
".",
"GESTURE_PINCH_END",
"}",
":",
"raise",
"AttributeError",
"(",
... | The absolute scale of a pinch gesture, the scale is
the division of the current distance between the fingers and
the distance at the start of the gesture.
The scale begins at 1.0, and if e.g. the fingers moved together by
50% then the scale will become 0.5, if they move twice as far apart
as initially the scale becomes 2.0, etc.
For gesture events that are of type
:attr:`~libinput.constant.EventType.GESTURE_PINCH_BEGIN`, this property
returns 1.0.
For gesture events that are of type
:attr:`~libinput.constant.EventType.GESTURE_PINCH_END`, this property
returns the scale value of the most recent
:attr:`~libinput.constant.EventType.GESTURE_PINCH_UPDATE` event
(if any) or 1.0 otherwise.
For all other events this property raises :exc:`AttributeError`.
Returns:
float: The absolute scale of a pinch gesture.
Raises:
AttributeError | [
"The",
"absolute",
"scale",
"of",
"a",
"pinch",
"gesture",
"the",
"scale",
"is",
"the",
"division",
"of",
"the",
"current",
"distance",
"between",
"the",
"fingers",
"and",
"the",
"distance",
"at",
"the",
"start",
"of",
"the",
"gesture",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L832-L862 | train | 53,709 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TabletToolEvent.rotation | def rotation(self):
"""The current Z rotation of the tool in degrees, clockwise
from the tool's logical neutral position and whether it has changed
in this event.
For tools of type :attr:`~libinput.constant.TabletToolType.MOUSE`
and :attr:`~libinput.constant.TabletToolType.LENS` the logical
neutral position is pointing to the current logical north
of the tablet. For tools of type
:attr:`~libinput.constant.TabletToolType.BRUSH`, the logical
neutral position is with the buttons pointing up.
If this axis does not exist on the current tool, this property is
(0, :obj:`False`).
Returns:
(float, bool): The current value of the the axis and whether it has
changed.
"""
rotation = self._libinput.libinput_event_tablet_tool_get_rotation(
self._handle)
changed = self._libinput. \
libinput_event_tablet_tool_rotation_has_changed(self._handle)
return rotation, changed | python | def rotation(self):
"""The current Z rotation of the tool in degrees, clockwise
from the tool's logical neutral position and whether it has changed
in this event.
For tools of type :attr:`~libinput.constant.TabletToolType.MOUSE`
and :attr:`~libinput.constant.TabletToolType.LENS` the logical
neutral position is pointing to the current logical north
of the tablet. For tools of type
:attr:`~libinput.constant.TabletToolType.BRUSH`, the logical
neutral position is with the buttons pointing up.
If this axis does not exist on the current tool, this property is
(0, :obj:`False`).
Returns:
(float, bool): The current value of the the axis and whether it has
changed.
"""
rotation = self._libinput.libinput_event_tablet_tool_get_rotation(
self._handle)
changed = self._libinput. \
libinput_event_tablet_tool_rotation_has_changed(self._handle)
return rotation, changed | [
"def",
"rotation",
"(",
"self",
")",
":",
"rotation",
"=",
"self",
".",
"_libinput",
".",
"libinput_event_tablet_tool_get_rotation",
"(",
"self",
".",
"_handle",
")",
"changed",
"=",
"self",
".",
"_libinput",
".",
"libinput_event_tablet_tool_rotation_has_changed",
"... | The current Z rotation of the tool in degrees, clockwise
from the tool's logical neutral position and whether it has changed
in this event.
For tools of type :attr:`~libinput.constant.TabletToolType.MOUSE`
and :attr:`~libinput.constant.TabletToolType.LENS` the logical
neutral position is pointing to the current logical north
of the tablet. For tools of type
:attr:`~libinput.constant.TabletToolType.BRUSH`, the logical
neutral position is with the buttons pointing up.
If this axis does not exist on the current tool, this property is
(0, :obj:`False`).
Returns:
(float, bool): The current value of the the axis and whether it has
changed. | [
"The",
"current",
"Z",
"rotation",
"of",
"the",
"tool",
"in",
"degrees",
"clockwise",
"from",
"the",
"tool",
"s",
"logical",
"neutral",
"position",
"and",
"whether",
"it",
"has",
"changed",
"in",
"this",
"event",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1152-L1176 | train | 53,710 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TabletToolEvent.wheel_delta | def wheel_delta(self):
"""The delta for the wheel in degrees and whether it has changed in
this event.
Returns:
(float, bool): The delta of the wheel, in degrees, compared to
the last event and whether it has changed.
"""
delta = self._libinput.libinput_event_tablet_tool_get_wheel_delta(
self._handle)
changed = self._libinput.libinput_event_tablet_tool_wheel_has_changed(
self._handle)
return delta, changed | python | def wheel_delta(self):
"""The delta for the wheel in degrees and whether it has changed in
this event.
Returns:
(float, bool): The delta of the wheel, in degrees, compared to
the last event and whether it has changed.
"""
delta = self._libinput.libinput_event_tablet_tool_get_wheel_delta(
self._handle)
changed = self._libinput.libinput_event_tablet_tool_wheel_has_changed(
self._handle)
return delta, changed | [
"def",
"wheel_delta",
"(",
"self",
")",
":",
"delta",
"=",
"self",
".",
"_libinput",
".",
"libinput_event_tablet_tool_get_wheel_delta",
"(",
"self",
".",
"_handle",
")",
"changed",
"=",
"self",
".",
"_libinput",
".",
"libinput_event_tablet_tool_wheel_has_changed",
"... | The delta for the wheel in degrees and whether it has changed in
this event.
Returns:
(float, bool): The delta of the wheel, in degrees, compared to
the last event and whether it has changed. | [
"The",
"delta",
"for",
"the",
"wheel",
"in",
"degrees",
"and",
"whether",
"it",
"has",
"changed",
"in",
"this",
"event",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1202-L1215 | train | 53,711 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TabletToolEvent.tool | def tool(self):
"""The tool that was in use during this event.
If the caller keeps a reference to a tool, the tool object will
compare equal to the previously obtained tool object.
Note:
Physical tool tracking requires hardware support. If unavailable,
libinput creates one tool per type per tablet. See
`Tracking unique tools`_ for more details.
Returns:
~libinput.define.TabletTool: The new tool triggering this event.
"""
htablettool = self._libinput.libinput_event_tablet_tool_get_tool(
self._handle)
return TabletTool(htablettool, self._libinput) | python | def tool(self):
"""The tool that was in use during this event.
If the caller keeps a reference to a tool, the tool object will
compare equal to the previously obtained tool object.
Note:
Physical tool tracking requires hardware support. If unavailable,
libinput creates one tool per type per tablet. See
`Tracking unique tools`_ for more details.
Returns:
~libinput.define.TabletTool: The new tool triggering this event.
"""
htablettool = self._libinput.libinput_event_tablet_tool_get_tool(
self._handle)
return TabletTool(htablettool, self._libinput) | [
"def",
"tool",
"(",
"self",
")",
":",
"htablettool",
"=",
"self",
".",
"_libinput",
".",
"libinput_event_tablet_tool_get_tool",
"(",
"self",
".",
"_handle",
")",
"return",
"TabletTool",
"(",
"htablettool",
",",
"self",
".",
"_libinput",
")"
] | The tool that was in use during this event.
If the caller keeps a reference to a tool, the tool object will
compare equal to the previously obtained tool object.
Note:
Physical tool tracking requires hardware support. If unavailable,
libinput creates one tool per type per tablet. See
`Tracking unique tools`_ for more details.
Returns:
~libinput.define.TabletTool: The new tool triggering this event. | [
"The",
"tool",
"that",
"was",
"in",
"use",
"during",
"this",
"event",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1261-L1277 | train | 53,712 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TabletToolEvent.seat_button_count | def seat_button_count(self):
"""The total number of buttons pressed on all devices on
the associated seat after the the event was triggered.
For events that are not of type
:attr:`~libinput.constant.EventType.TABLET_TOOL_BUTTON`, this property
raises :exc:`AttributeError`.
Returns:
int: The seat wide pressed button count for the key of this event.
"""
if self.type != EventType.TABLET_TOOL_BUTTON:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_tool_get_seat_button_count(
self._handle) | python | def seat_button_count(self):
"""The total number of buttons pressed on all devices on
the associated seat after the the event was triggered.
For events that are not of type
:attr:`~libinput.constant.EventType.TABLET_TOOL_BUTTON`, this property
raises :exc:`AttributeError`.
Returns:
int: The seat wide pressed button count for the key of this event.
"""
if self.type != EventType.TABLET_TOOL_BUTTON:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_tool_get_seat_button_count(
self._handle) | [
"def",
"seat_button_count",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"TABLET_TOOL_BUTTON",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_libi... | The total number of buttons pressed on all devices on
the associated seat after the the event was triggered.
For events that are not of type
:attr:`~libinput.constant.EventType.TABLET_TOOL_BUTTON`, this property
raises :exc:`AttributeError`.
Returns:
int: The seat wide pressed button count for the key of this event. | [
"The",
"total",
"number",
"of",
"buttons",
"pressed",
"on",
"all",
"devices",
"on",
"the",
"associated",
"seat",
"after",
"the",
"the",
"event",
"was",
"triggered",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1350-L1365 | train | 53,713 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TabletPadEvent.ring_position | def ring_position(self):
"""The current position of the ring, in degrees
counterclockwise from the northern-most point of the ring in
the tablet's current logical orientation.
If the source is
:attr:`~libinput.constant.TabletPadRingAxisSource.FINGER`,
libinput sends a terminating event with a ring value of -1 when
the finger is lifted from the ring. A caller may use this information
to e.g. determine if kinetic scrolling should be triggered.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_RING`, this property
raises :exc:`AttributeError`.
Returns:
float: The current value of the the axis. -1 if the finger was
lifted.
Raises:
AttributeError
"""
if self.type != EventType.TABLET_PAD_RING:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_pad_get_ring_position(
self._handle) | python | def ring_position(self):
"""The current position of the ring, in degrees
counterclockwise from the northern-most point of the ring in
the tablet's current logical orientation.
If the source is
:attr:`~libinput.constant.TabletPadRingAxisSource.FINGER`,
libinput sends a terminating event with a ring value of -1 when
the finger is lifted from the ring. A caller may use this information
to e.g. determine if kinetic scrolling should be triggered.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_RING`, this property
raises :exc:`AttributeError`.
Returns:
float: The current value of the the axis. -1 if the finger was
lifted.
Raises:
AttributeError
"""
if self.type != EventType.TABLET_PAD_RING:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_pad_get_ring_position(
self._handle) | [
"def",
"ring_position",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"TABLET_PAD_RING",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_libinput",
... | The current position of the ring, in degrees
counterclockwise from the northern-most point of the ring in
the tablet's current logical orientation.
If the source is
:attr:`~libinput.constant.TabletPadRingAxisSource.FINGER`,
libinput sends a terminating event with a ring value of -1 when
the finger is lifted from the ring. A caller may use this information
to e.g. determine if kinetic scrolling should be triggered.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_RING`, this property
raises :exc:`AttributeError`.
Returns:
float: The current value of the the axis. -1 if the finger was
lifted.
Raises:
AttributeError | [
"The",
"current",
"position",
"of",
"the",
"ring",
"in",
"degrees",
"counterclockwise",
"from",
"the",
"northern",
"-",
"most",
"point",
"of",
"the",
"ring",
"in",
"the",
"tablet",
"s",
"current",
"logical",
"orientation",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1445-L1470 | train | 53,714 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TabletPadEvent.ring_number | def ring_number(self):
"""The number of the ring that has changed state,
with 0 being the first ring.
On tablets with only one ring, this method always returns 0.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_RING`, this property
raises :exc:`AssertionError`.
Returns:
int: The index of the ring that changed state.
Raises:
AssertionError
"""
if self.type != EventType.TABLET_PAD_RING:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_pad_get_ring_number(
self._handle) | python | def ring_number(self):
"""The number of the ring that has changed state,
with 0 being the first ring.
On tablets with only one ring, this method always returns 0.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_RING`, this property
raises :exc:`AssertionError`.
Returns:
int: The index of the ring that changed state.
Raises:
AssertionError
"""
if self.type != EventType.TABLET_PAD_RING:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_pad_get_ring_number(
self._handle) | [
"def",
"ring_number",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"TABLET_PAD_RING",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_libinput",
... | The number of the ring that has changed state,
with 0 being the first ring.
On tablets with only one ring, this method always returns 0.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_RING`, this property
raises :exc:`AssertionError`.
Returns:
int: The index of the ring that changed state.
Raises:
AssertionError | [
"The",
"number",
"of",
"the",
"ring",
"that",
"has",
"changed",
"state",
"with",
"0",
"being",
"the",
"first",
"ring",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1473-L1492 | train | 53,715 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TabletPadEvent.ring_source | def ring_source(self):
"""The source of the interaction with the ring.
If the source is
:attr:`~libinput.constant.TabletPadRingAxisSource.FINGER`,
libinput sends a ring position value of -1 to terminate
the current interaction.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_RING`, this property
raises :exc:`AttributeError`.
Returns:
~libinput.constant.TabletPadRingAxisSource: The source of the ring
interaction.
Raises:
AttributeError
"""
if self.type != EventType.TABLET_PAD_RING:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_pad_get_ring_source(
self._handle) | python | def ring_source(self):
"""The source of the interaction with the ring.
If the source is
:attr:`~libinput.constant.TabletPadRingAxisSource.FINGER`,
libinput sends a ring position value of -1 to terminate
the current interaction.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_RING`, this property
raises :exc:`AttributeError`.
Returns:
~libinput.constant.TabletPadRingAxisSource: The source of the ring
interaction.
Raises:
AttributeError
"""
if self.type != EventType.TABLET_PAD_RING:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_pad_get_ring_source(
self._handle) | [
"def",
"ring_source",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"TABLET_PAD_RING",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_libinput",
... | The source of the interaction with the ring.
If the source is
:attr:`~libinput.constant.TabletPadRingAxisSource.FINGER`,
libinput sends a ring position value of -1 to terminate
the current interaction.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_RING`, this property
raises :exc:`AttributeError`.
Returns:
~libinput.constant.TabletPadRingAxisSource: The source of the ring
interaction.
Raises:
AttributeError | [
"The",
"source",
"of",
"the",
"interaction",
"with",
"the",
"ring",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1495-L1517 | train | 53,716 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TabletPadEvent.strip_number | def strip_number(self):
"""The number of the strip that has changed state,
with 0 being the first strip.
On tablets with only one strip, this method always returns 0.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property
raises :exc:`AttributeError`.
Returns:
int: The index of the strip that changed state.
Raises:
AttributeError
"""
if self.type != EventType.TABLET_PAD_STRIP:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_pad_get_strip_number(
self._handle) | python | def strip_number(self):
"""The number of the strip that has changed state,
with 0 being the first strip.
On tablets with only one strip, this method always returns 0.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property
raises :exc:`AttributeError`.
Returns:
int: The index of the strip that changed state.
Raises:
AttributeError
"""
if self.type != EventType.TABLET_PAD_STRIP:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_pad_get_strip_number(
self._handle) | [
"def",
"strip_number",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"TABLET_PAD_STRIP",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_libinput",
... | The number of the strip that has changed state,
with 0 being the first strip.
On tablets with only one strip, this method always returns 0.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property
raises :exc:`AttributeError`.
Returns:
int: The index of the strip that changed state.
Raises:
AttributeError | [
"The",
"number",
"of",
"the",
"strip",
"that",
"has",
"changed",
"state",
"with",
"0",
"being",
"the",
"first",
"strip",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1548-L1567 | train | 53,717 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TabletPadEvent.strip_source | def strip_source(self):
"""The source of the interaction with the strip.
If the source is
:attr:`~libinput.constant.TabletPadStripAxisSource.FINGER`, libinput
sends a strip position value of -1 to terminate the current interaction.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property
raises :exc:`AttributeError`.
Returns:
~libinput.constant.TabletPadStripAxisSource: The source of
the strip interaction.
Raises:
AttributeError
"""
if self.type != EventType.TABLET_PAD_STRIP:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_pad_get_strip_source(
self._handle) | python | def strip_source(self):
"""The source of the interaction with the strip.
If the source is
:attr:`~libinput.constant.TabletPadStripAxisSource.FINGER`, libinput
sends a strip position value of -1 to terminate the current interaction.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property
raises :exc:`AttributeError`.
Returns:
~libinput.constant.TabletPadStripAxisSource: The source of
the strip interaction.
Raises:
AttributeError
"""
if self.type != EventType.TABLET_PAD_STRIP:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_pad_get_strip_source(
self._handle) | [
"def",
"strip_source",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"TABLET_PAD_STRIP",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_libinput",
... | The source of the interaction with the strip.
If the source is
:attr:`~libinput.constant.TabletPadStripAxisSource.FINGER`, libinput
sends a strip position value of -1 to terminate the current interaction.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property
raises :exc:`AttributeError`.
Returns:
~libinput.constant.TabletPadStripAxisSource: The source of
the strip interaction.
Raises:
AttributeError | [
"The",
"source",
"of",
"the",
"interaction",
"with",
"the",
"strip",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1570-L1591 | train | 53,718 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TabletPadEvent.button_number | def button_number(self):
"""The button number that triggered this event, starting at 0.
For events that are not of type
:attr:`~libinput.constant.Event.TABLET_PAD_BUTTON`,
this property raises :exc:`AttributeError`.
Note that the number returned is a generic sequential button number
and not a semantic button code as defined in ``linux/input.h``.
See `Tablet pad button numbers`_ for more details.
Returns:
int: The button triggering this event.
Raises:
AttributeError
"""
if self.type != EventType.TABLET_PAD_BUTTON:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_pad_get_button_number(
self._handle) | python | def button_number(self):
"""The button number that triggered this event, starting at 0.
For events that are not of type
:attr:`~libinput.constant.Event.TABLET_PAD_BUTTON`,
this property raises :exc:`AttributeError`.
Note that the number returned is a generic sequential button number
and not a semantic button code as defined in ``linux/input.h``.
See `Tablet pad button numbers`_ for more details.
Returns:
int: The button triggering this event.
Raises:
AttributeError
"""
if self.type != EventType.TABLET_PAD_BUTTON:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_pad_get_button_number(
self._handle) | [
"def",
"button_number",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"TABLET_PAD_BUTTON",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_libinput"... | The button number that triggered this event, starting at 0.
For events that are not of type
:attr:`~libinput.constant.Event.TABLET_PAD_BUTTON`,
this property raises :exc:`AttributeError`.
Note that the number returned is a generic sequential button number
and not a semantic button code as defined in ``linux/input.h``.
See `Tablet pad button numbers`_ for more details.
Returns:
int: The button triggering this event.
Raises:
AttributeError | [
"The",
"button",
"number",
"that",
"triggered",
"this",
"event",
"starting",
"at",
"0",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1594-L1614 | train | 53,719 |
OzymandiasTheGreat/python-libinput | libinput/event.py | TabletPadEvent.mode_group | def mode_group(self):
"""The mode group that the button, ring, or strip that
triggered this event is considered in.
The mode is a virtual grouping of functionality, usually based on some
visual feedback like LEDs on the pad. See `Tablet pad modes`_
for details.
Returns:
~libinput.define.TabletPadModeGroup: The mode group of the button,
ring or strip that caused this event.
"""
hmodegroup = self._libinput.libinput_event_tablet_pad_get_mode_group(
self._handle)
return TabletPadModeGroup(hmodegroup, self._libinput) | python | def mode_group(self):
"""The mode group that the button, ring, or strip that
triggered this event is considered in.
The mode is a virtual grouping of functionality, usually based on some
visual feedback like LEDs on the pad. See `Tablet pad modes`_
for details.
Returns:
~libinput.define.TabletPadModeGroup: The mode group of the button,
ring or strip that caused this event.
"""
hmodegroup = self._libinput.libinput_event_tablet_pad_get_mode_group(
self._handle)
return TabletPadModeGroup(hmodegroup, self._libinput) | [
"def",
"mode_group",
"(",
"self",
")",
":",
"hmodegroup",
"=",
"self",
".",
"_libinput",
".",
"libinput_event_tablet_pad_get_mode_group",
"(",
"self",
".",
"_handle",
")",
"return",
"TabletPadModeGroup",
"(",
"hmodegroup",
",",
"self",
".",
"_libinput",
")"
] | The mode group that the button, ring, or strip that
triggered this event is considered in.
The mode is a virtual grouping of functionality, usually based on some
visual feedback like LEDs on the pad. See `Tablet pad modes`_
for details.
Returns:
~libinput.define.TabletPadModeGroup: The mode group of the button,
ring or strip that caused this event. | [
"The",
"mode",
"group",
"that",
"the",
"button",
"ring",
"or",
"strip",
"that",
"triggered",
"this",
"event",
"is",
"considered",
"in",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1665-L1680 | train | 53,720 |
KelSolaar/Manager | setup.py | get_long_description | def get_long_description():
"""
Returns the Package long description.
:return: Package long description.
:rtype: unicode
"""
description = []
with open("README.rst") as file:
for line in file:
if ".. code:: python" in line and len(description) >= 2:
blockLine = description[-2]
if re.search(r":$", blockLine) and not re.search(r"::$", blockLine):
description[-2] = "::".join(blockLine.rsplit(":", 1))
continue
description.append(line)
return "".join(description) | python | def get_long_description():
"""
Returns the Package long description.
:return: Package long description.
:rtype: unicode
"""
description = []
with open("README.rst") as file:
for line in file:
if ".. code:: python" in line and len(description) >= 2:
blockLine = description[-2]
if re.search(r":$", blockLine) and not re.search(r"::$", blockLine):
description[-2] = "::".join(blockLine.rsplit(":", 1))
continue
description.append(line)
return "".join(description) | [
"def",
"get_long_description",
"(",
")",
":",
"description",
"=",
"[",
"]",
"with",
"open",
"(",
"\"README.rst\"",
")",
"as",
"file",
":",
"for",
"line",
"in",
"file",
":",
"if",
"\".. code:: python\"",
"in",
"line",
"and",
"len",
"(",
"description",
")",
... | Returns the Package long description.
:return: Package long description.
:rtype: unicode | [
"Returns",
"the",
"Package",
"long",
"description",
"."
] | 39c8153fc021fc8a76e345a6e336ec2644f089d1 | https://github.com/KelSolaar/Manager/blob/39c8153fc021fc8a76e345a6e336ec2644f089d1/setup.py#L35-L53 | train | 53,721 |
portfoliome/foil | foil/ftp.py | ftp_listing_paths | def ftp_listing_paths(ftpconn: FTP, root: str) -> Iterable[str]:
"""Generate the full file paths from a root path."""
for current_path, dirs, files in ftp_walk(ftpconn, root):
yield from (os.path.join(current_path, file) for file in files) | python | def ftp_listing_paths(ftpconn: FTP, root: str) -> Iterable[str]:
"""Generate the full file paths from a root path."""
for current_path, dirs, files in ftp_walk(ftpconn, root):
yield from (os.path.join(current_path, file) for file in files) | [
"def",
"ftp_listing_paths",
"(",
"ftpconn",
":",
"FTP",
",",
"root",
":",
"str",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"for",
"current_path",
",",
"dirs",
",",
"files",
"in",
"ftp_walk",
"(",
"ftpconn",
",",
"root",
")",
":",
"yield",
"from",
... | Generate the full file paths from a root path. | [
"Generate",
"the",
"full",
"file",
"paths",
"from",
"a",
"root",
"path",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/ftp.py#L35-L39 | train | 53,722 |
portfoliome/foil | foil/ftp.py | ftp_walk | def ftp_walk(ftpconn: FTP, rootpath=''):
"""Recursively traverse an ftp directory to discovery directory listing."""
current_directory = rootpath
try:
directories, files = directory_listing(ftpconn, current_directory)
except ftplib.error_perm:
return
# Yield before recursion
yield current_directory, directories, files
# Recurse into sub-directories
for name in directories:
new_path = os.path.join(current_directory, name)
for entry in ftp_walk(ftpconn, rootpath=new_path):
yield entry
else:
return | python | def ftp_walk(ftpconn: FTP, rootpath=''):
"""Recursively traverse an ftp directory to discovery directory listing."""
current_directory = rootpath
try:
directories, files = directory_listing(ftpconn, current_directory)
except ftplib.error_perm:
return
# Yield before recursion
yield current_directory, directories, files
# Recurse into sub-directories
for name in directories:
new_path = os.path.join(current_directory, name)
for entry in ftp_walk(ftpconn, rootpath=new_path):
yield entry
else:
return | [
"def",
"ftp_walk",
"(",
"ftpconn",
":",
"FTP",
",",
"rootpath",
"=",
"''",
")",
":",
"current_directory",
"=",
"rootpath",
"try",
":",
"directories",
",",
"files",
"=",
"directory_listing",
"(",
"ftpconn",
",",
"current_directory",
")",
"except",
"ftplib",
"... | Recursively traverse an ftp directory to discovery directory listing. | [
"Recursively",
"traverse",
"an",
"ftp",
"directory",
"to",
"discovery",
"directory",
"listing",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/ftp.py#L42-L62 | train | 53,723 |
portfoliome/foil | foil/ftp.py | directory_listing | def directory_listing(conn: FTP, path: str) -> Tuple[List, List]:
"""Return the directories and files for single FTP listing."""
entries = deque()
conn.dir(path, entries.append)
entries = map(parse_line, entries)
grouped_entries = defaultdict(list)
for key, value in entries:
grouped_entries[key].append(value)
directories = grouped_entries[ListingType.directory]
files = grouped_entries[ListingType.file]
return directories, files | python | def directory_listing(conn: FTP, path: str) -> Tuple[List, List]:
"""Return the directories and files for single FTP listing."""
entries = deque()
conn.dir(path, entries.append)
entries = map(parse_line, entries)
grouped_entries = defaultdict(list)
for key, value in entries:
grouped_entries[key].append(value)
directories = grouped_entries[ListingType.directory]
files = grouped_entries[ListingType.file]
return directories, files | [
"def",
"directory_listing",
"(",
"conn",
":",
"FTP",
",",
"path",
":",
"str",
")",
"->",
"Tuple",
"[",
"List",
",",
"List",
"]",
":",
"entries",
"=",
"deque",
"(",
")",
"conn",
".",
"dir",
"(",
"path",
",",
"entries",
".",
"append",
")",
"entries",... | Return the directories and files for single FTP listing. | [
"Return",
"the",
"directories",
"and",
"files",
"for",
"single",
"FTP",
"listing",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/ftp.py#L65-L79 | train | 53,724 |
portfoliome/foil | foil/ftp.py | download_ftp_url | def download_ftp_url(source_url, target_uri, buffer_size=8192):
"""Uses urllib. thread safe?"""
ensure_file_directory(target_uri)
with urllib.request.urlopen(source_url) as source_file:
with open(target_uri, 'wb') as target_file:
shutil.copyfileobj(source_file, target_file, buffer_size) | python | def download_ftp_url(source_url, target_uri, buffer_size=8192):
"""Uses urllib. thread safe?"""
ensure_file_directory(target_uri)
with urllib.request.urlopen(source_url) as source_file:
with open(target_uri, 'wb') as target_file:
shutil.copyfileobj(source_file, target_file, buffer_size) | [
"def",
"download_ftp_url",
"(",
"source_url",
",",
"target_uri",
",",
"buffer_size",
"=",
"8192",
")",
":",
"ensure_file_directory",
"(",
"target_uri",
")",
"with",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"source_url",
")",
"as",
"source_file",
":",
"wi... | Uses urllib. thread safe? | [
"Uses",
"urllib",
".",
"thread",
"safe?"
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/ftp.py#L90-L97 | train | 53,725 |
BlueBrain/hpcbench | hpcbench/benchmark/babelstream.py | BabelStream.devices | def devices(self):
"""List of devices to test
"""
eax = self.attributes.get('devices')
if eax is None:
eax = self._all_devices
if not isinstance(eax, list):
eax = [eax]
return [str(dev) for dev in eax] | python | def devices(self):
"""List of devices to test
"""
eax = self.attributes.get('devices')
if eax is None:
eax = self._all_devices
if not isinstance(eax, list):
eax = [eax]
return [str(dev) for dev in eax] | [
"def",
"devices",
"(",
"self",
")",
":",
"eax",
"=",
"self",
".",
"attributes",
".",
"get",
"(",
"'devices'",
")",
"if",
"eax",
"is",
"None",
":",
"eax",
"=",
"self",
".",
"_all_devices",
"if",
"not",
"isinstance",
"(",
"eax",
",",
"list",
")",
":"... | List of devices to test | [
"List",
"of",
"devices",
"to",
"test"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/babelstream.py#L69-L77 | train | 53,726 |
PolyJIT/benchbuild | benchbuild/utils/schema.py | exceptions | def exceptions(error_is_fatal=True, error_messages=None):
"""
Handle SQLAlchemy exceptions in a sane way.
Args:
func: An arbitrary function to wrap.
error_is_fatal: Should we exit the program on exception?
reraise: Should we reraise the exception, after logging? Only makes sense
if error_is_fatal is False.
error_messages: A dictionary that assigns an exception class to a
customized error message.
"""
def exception_decorator(func):
nonlocal error_messages
@functools.wraps(func)
def exc_wrapper(*args, **kwargs):
nonlocal error_messages
try:
result = func(*args, **kwargs)
except sa.exc.SQLAlchemyError as err:
result = None
details = None
err_type = err.__class__
if error_messages and err_type in error_messages:
details = error_messages[err_type]
if details:
LOG.error(details)
LOG.error("For developers: (%s) %s", err.__class__, str(err))
if error_is_fatal:
sys.exit("Abort, SQL operation failed.")
if not ui.ask(
"I can continue at your own risk, do you want that?"):
raise err
return result
return exc_wrapper
return exception_decorator | python | def exceptions(error_is_fatal=True, error_messages=None):
"""
Handle SQLAlchemy exceptions in a sane way.
Args:
func: An arbitrary function to wrap.
error_is_fatal: Should we exit the program on exception?
reraise: Should we reraise the exception, after logging? Only makes sense
if error_is_fatal is False.
error_messages: A dictionary that assigns an exception class to a
customized error message.
"""
def exception_decorator(func):
nonlocal error_messages
@functools.wraps(func)
def exc_wrapper(*args, **kwargs):
nonlocal error_messages
try:
result = func(*args, **kwargs)
except sa.exc.SQLAlchemyError as err:
result = None
details = None
err_type = err.__class__
if error_messages and err_type in error_messages:
details = error_messages[err_type]
if details:
LOG.error(details)
LOG.error("For developers: (%s) %s", err.__class__, str(err))
if error_is_fatal:
sys.exit("Abort, SQL operation failed.")
if not ui.ask(
"I can continue at your own risk, do you want that?"):
raise err
return result
return exc_wrapper
return exception_decorator | [
"def",
"exceptions",
"(",
"error_is_fatal",
"=",
"True",
",",
"error_messages",
"=",
"None",
")",
":",
"def",
"exception_decorator",
"(",
"func",
")",
":",
"nonlocal",
"error_messages",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"exc_wrapper",
... | Handle SQLAlchemy exceptions in a sane way.
Args:
func: An arbitrary function to wrap.
error_is_fatal: Should we exit the program on exception?
reraise: Should we reraise the exception, after logging? Only makes sense
if error_is_fatal is False.
error_messages: A dictionary that assigns an exception class to a
customized error message. | [
"Handle",
"SQLAlchemy",
"exceptions",
"in",
"a",
"sane",
"way",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/schema.py#L50-L89 | train | 53,727 |
PolyJIT/benchbuild | benchbuild/utils/schema.py | get_version_data | def get_version_data():
"""Retreive migration information."""
connect_str = str(settings.CFG["db"]["connect_string"])
repo_url = path.template_path("../db/")
return (connect_str, repo_url) | python | def get_version_data():
"""Retreive migration information."""
connect_str = str(settings.CFG["db"]["connect_string"])
repo_url = path.template_path("../db/")
return (connect_str, repo_url) | [
"def",
"get_version_data",
"(",
")",
":",
"connect_str",
"=",
"str",
"(",
"settings",
".",
"CFG",
"[",
"\"db\"",
"]",
"[",
"\"connect_string\"",
"]",
")",
"repo_url",
"=",
"path",
".",
"template_path",
"(",
"\"../db/\"",
")",
"return",
"(",
"connect_str",
... | Retreive migration information. | [
"Retreive",
"migration",
"information",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/schema.py#L339-L343 | train | 53,728 |
PolyJIT/benchbuild | benchbuild/utils/schema.py | enforce_versioning | def enforce_versioning(force=False):
"""Install versioning on the db."""
connect_str, repo_url = get_version_data()
LOG.warning("Your database uses an unversioned benchbuild schema.")
if not force and not ui.ask(
"Should I enforce version control on your schema?"):
LOG.error("User declined schema versioning.")
return None
repo_version = migrate.version(repo_url, url=connect_str)
migrate.version_control(connect_str, repo_url, version=repo_version)
return repo_version | python | def enforce_versioning(force=False):
"""Install versioning on the db."""
connect_str, repo_url = get_version_data()
LOG.warning("Your database uses an unversioned benchbuild schema.")
if not force and not ui.ask(
"Should I enforce version control on your schema?"):
LOG.error("User declined schema versioning.")
return None
repo_version = migrate.version(repo_url, url=connect_str)
migrate.version_control(connect_str, repo_url, version=repo_version)
return repo_version | [
"def",
"enforce_versioning",
"(",
"force",
"=",
"False",
")",
":",
"connect_str",
",",
"repo_url",
"=",
"get_version_data",
"(",
")",
"LOG",
".",
"warning",
"(",
"\"Your database uses an unversioned benchbuild schema.\"",
")",
"if",
"not",
"force",
"and",
"not",
"... | Install versioning on the db. | [
"Install",
"versioning",
"on",
"the",
"db",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/schema.py#L351-L361 | train | 53,729 |
PolyJIT/benchbuild | benchbuild/utils/schema.py | init_functions | def init_functions(connection):
"""Initialize all SQL functions in the database."""
if settings.CFG["db"]["create_functions"]:
print("Refreshing SQL functions...")
for file in path.template_files("../sql/", exts=[".sql"]):
func = sa.DDL(path.template_str(file))
LOG.info("Loading: '%s' into database", file)
connection.execute(func)
connection.commit() | python | def init_functions(connection):
"""Initialize all SQL functions in the database."""
if settings.CFG["db"]["create_functions"]:
print("Refreshing SQL functions...")
for file in path.template_files("../sql/", exts=[".sql"]):
func = sa.DDL(path.template_str(file))
LOG.info("Loading: '%s' into database", file)
connection.execute(func)
connection.commit() | [
"def",
"init_functions",
"(",
"connection",
")",
":",
"if",
"settings",
".",
"CFG",
"[",
"\"db\"",
"]",
"[",
"\"create_functions\"",
"]",
":",
"print",
"(",
"\"Refreshing SQL functions...\"",
")",
"for",
"file",
"in",
"path",
".",
"template_files",
"(",
"\"../... | Initialize all SQL functions in the database. | [
"Initialize",
"all",
"SQL",
"functions",
"in",
"the",
"database",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/schema.py#L494-L502 | train | 53,730 |
PolyJIT/benchbuild | benchbuild/utils/schema.py | SessionManager.connect_engine | def connect_engine(self):
"""
Establish a connection to the database.
Provides simple error handling for fatal errors.
Returns:
True, if we could establish a connection, else False.
"""
try:
self.connection = self.engine.connect()
return True
except sa.exc.OperationalError as opex:
LOG.fatal("Could not connect to the database. The error was: '%s'",
str(opex))
return False | python | def connect_engine(self):
"""
Establish a connection to the database.
Provides simple error handling for fatal errors.
Returns:
True, if we could establish a connection, else False.
"""
try:
self.connection = self.engine.connect()
return True
except sa.exc.OperationalError as opex:
LOG.fatal("Could not connect to the database. The error was: '%s'",
str(opex))
return False | [
"def",
"connect_engine",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"connection",
"=",
"self",
".",
"engine",
".",
"connect",
"(",
")",
"return",
"True",
"except",
"sa",
".",
"exc",
".",
"OperationalError",
"as",
"opex",
":",
"LOG",
".",
"fatal",
... | Establish a connection to the database.
Provides simple error handling for fatal errors.
Returns:
True, if we could establish a connection, else False. | [
"Establish",
"a",
"connection",
"to",
"the",
"database",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/schema.py#L410-L425 | train | 53,731 |
PolyJIT/benchbuild | benchbuild/utils/schema.py | SessionManager.configure_engine | def configure_engine(self):
"""
Configure the databse connection.
Sets appropriate transaction isolation levels and handle errors.
Returns:
True, if we did not encounter any unrecoverable errors, else False.
"""
try:
self.connection.execution_options(isolation_level="SERIALIZABLE")
except sa.exc.ArgumentError:
LOG.debug("Unable to set isolation level to SERIALIZABLE")
return True | python | def configure_engine(self):
"""
Configure the databse connection.
Sets appropriate transaction isolation levels and handle errors.
Returns:
True, if we did not encounter any unrecoverable errors, else False.
"""
try:
self.connection.execution_options(isolation_level="SERIALIZABLE")
except sa.exc.ArgumentError:
LOG.debug("Unable to set isolation level to SERIALIZABLE")
return True | [
"def",
"configure_engine",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"connection",
".",
"execution_options",
"(",
"isolation_level",
"=",
"\"SERIALIZABLE\"",
")",
"except",
"sa",
".",
"exc",
".",
"ArgumentError",
":",
"LOG",
".",
"debug",
"(",
"\"Unabl... | Configure the databse connection.
Sets appropriate transaction isolation levels and handle errors.
Returns:
True, if we did not encounter any unrecoverable errors, else False. | [
"Configure",
"the",
"databse",
"connection",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/schema.py#L427-L440 | train | 53,732 |
portfoliome/foil | foil/dates.py | parse_date | def parse_date(date_str: str, pattern=_RE_DATE) -> dt.date:
"""Parse datetime.date from YYYY-MM-DD format."""
groups = re.match(pattern, date_str)
return dt.date(*_date_to_tuple(groups.groupdict())) | python | def parse_date(date_str: str, pattern=_RE_DATE) -> dt.date:
"""Parse datetime.date from YYYY-MM-DD format."""
groups = re.match(pattern, date_str)
return dt.date(*_date_to_tuple(groups.groupdict())) | [
"def",
"parse_date",
"(",
"date_str",
":",
"str",
",",
"pattern",
"=",
"_RE_DATE",
")",
"->",
"dt",
".",
"date",
":",
"groups",
"=",
"re",
".",
"match",
"(",
"pattern",
",",
"date_str",
")",
"return",
"dt",
".",
"date",
"(",
"*",
"_date_to_tuple",
"(... | Parse datetime.date from YYYY-MM-DD format. | [
"Parse",
"datetime",
".",
"date",
"from",
"YYYY",
"-",
"MM",
"-",
"DD",
"format",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/dates.py#L47-L52 | train | 53,733 |
portfoliome/foil | foil/dates.py | _datetime_to_tuple | def _datetime_to_tuple(dt_dict):
"""datetime.datetime components from dictionary to tuple.
Example
-------
dt_dict = {'year': '2014','month': '07','day': '23',
'hour': '13','minute': '12','second': '45','microsecond': '321'}
_datetime_to_tuple(dt_dict) -> (2014, 7, 23, 13, 12, 45, 321)
"""
year, month, day = _date_to_tuple(dt_dict)
hour, minute, second, microsecond = _time_to_tuple(dt_dict)
return year, month, day, hour, minute, second, microsecond | python | def _datetime_to_tuple(dt_dict):
"""datetime.datetime components from dictionary to tuple.
Example
-------
dt_dict = {'year': '2014','month': '07','day': '23',
'hour': '13','minute': '12','second': '45','microsecond': '321'}
_datetime_to_tuple(dt_dict) -> (2014, 7, 23, 13, 12, 45, 321)
"""
year, month, day = _date_to_tuple(dt_dict)
hour, minute, second, microsecond = _time_to_tuple(dt_dict)
return year, month, day, hour, minute, second, microsecond | [
"def",
"_datetime_to_tuple",
"(",
"dt_dict",
")",
":",
"year",
",",
"month",
",",
"day",
"=",
"_date_to_tuple",
"(",
"dt_dict",
")",
"hour",
",",
"minute",
",",
"second",
",",
"microsecond",
"=",
"_time_to_tuple",
"(",
"dt_dict",
")",
"return",
"year",
","... | datetime.datetime components from dictionary to tuple.
Example
-------
dt_dict = {'year': '2014','month': '07','day': '23',
'hour': '13','minute': '12','second': '45','microsecond': '321'}
_datetime_to_tuple(dt_dict) -> (2014, 7, 23, 13, 12, 45, 321) | [
"datetime",
".",
"datetime",
"components",
"from",
"dictionary",
"to",
"tuple",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/dates.py#L81-L95 | train | 53,734 |
portfoliome/foil | foil/dates.py | DateTimeParser.convert_2_utc | def convert_2_utc(self, datetime_, timezone):
"""convert to datetime to UTC offset."""
datetime_ = self.tz_mapper[timezone].localize(datetime_)
return datetime_.astimezone(pytz.UTC) | python | def convert_2_utc(self, datetime_, timezone):
"""convert to datetime to UTC offset."""
datetime_ = self.tz_mapper[timezone].localize(datetime_)
return datetime_.astimezone(pytz.UTC) | [
"def",
"convert_2_utc",
"(",
"self",
",",
"datetime_",
",",
"timezone",
")",
":",
"datetime_",
"=",
"self",
".",
"tz_mapper",
"[",
"timezone",
"]",
".",
"localize",
"(",
"datetime_",
")",
"return",
"datetime_",
".",
"astimezone",
"(",
"pytz",
".",
"UTC",
... | convert to datetime to UTC offset. | [
"convert",
"to",
"datetime",
"to",
"UTC",
"offset",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/dates.py#L74-L78 | train | 53,735 |
jfear/sramongo | sramongo/services/entrez.py | esearch | def esearch(database, query, userhistory=True, webenv=False, query_key=False, retstart=False, retmax=False,
api_key=False, email=False, **kwargs) -> Optional[EsearchResult]:
"""Search for a query using the Entrez ESearch API.
Parameters
----------
database : str
Entez database to search.
query : str
Query string
userhistory : bool
Tells API to return a WebEnV and query_key.
webenv : str
An Entrez WebEnv to use saved history.
query_key : str
An Entrez query_key to use saved history.
retstart : int
Return values starting at this index.
retmax : int
Return at most this number of values.
api_key : str
A users API key which allows more requests per second
email : str
A users email which is required if not using API.
Returns
-------
EsearchResult
A named tuple with values [ids, count, webenv, query_key]
"""
cleaned_query = urllib.parse.quote_plus(query, safe='/+')
url = BASE_URL + f'esearch.fcgi?db={database}&term={cleaned_query}&retmode=json'
url = check_userhistory(userhistory, url)
url = check_webenv(webenv, url)
url = check_query_key(query_key, url)
url = check_retstart(retstart, url)
url = check_retmax(retmax, url)
url = check_api_key(api_key, url)
url = check_email(email, url)
time.sleep(PAUSE)
resp = requests.get(url)
if resp.status_code != 200:
print('There was a server error')
return
text = resp.json()
time.sleep(.5)
return EsearchResult(
text['esearchresult'].get('idlist', []),
make_number(text['esearchresult'].get('count', ''), int),
text['esearchresult'].get('webenv', ''),
text['esearchresult'].get('querykey', '')
) | python | def esearch(database, query, userhistory=True, webenv=False, query_key=False, retstart=False, retmax=False,
api_key=False, email=False, **kwargs) -> Optional[EsearchResult]:
"""Search for a query using the Entrez ESearch API.
Parameters
----------
database : str
Entez database to search.
query : str
Query string
userhistory : bool
Tells API to return a WebEnV and query_key.
webenv : str
An Entrez WebEnv to use saved history.
query_key : str
An Entrez query_key to use saved history.
retstart : int
Return values starting at this index.
retmax : int
Return at most this number of values.
api_key : str
A users API key which allows more requests per second
email : str
A users email which is required if not using API.
Returns
-------
EsearchResult
A named tuple with values [ids, count, webenv, query_key]
"""
cleaned_query = urllib.parse.quote_plus(query, safe='/+')
url = BASE_URL + f'esearch.fcgi?db={database}&term={cleaned_query}&retmode=json'
url = check_userhistory(userhistory, url)
url = check_webenv(webenv, url)
url = check_query_key(query_key, url)
url = check_retstart(retstart, url)
url = check_retmax(retmax, url)
url = check_api_key(api_key, url)
url = check_email(email, url)
time.sleep(PAUSE)
resp = requests.get(url)
if resp.status_code != 200:
print('There was a server error')
return
text = resp.json()
time.sleep(.5)
return EsearchResult(
text['esearchresult'].get('idlist', []),
make_number(text['esearchresult'].get('count', ''), int),
text['esearchresult'].get('webenv', ''),
text['esearchresult'].get('querykey', '')
) | [
"def",
"esearch",
"(",
"database",
",",
"query",
",",
"userhistory",
"=",
"True",
",",
"webenv",
"=",
"False",
",",
"query_key",
"=",
"False",
",",
"retstart",
"=",
"False",
",",
"retmax",
"=",
"False",
",",
"api_key",
"=",
"False",
",",
"email",
"=",
... | Search for a query using the Entrez ESearch API.
Parameters
----------
database : str
Entez database to search.
query : str
Query string
userhistory : bool
Tells API to return a WebEnV and query_key.
webenv : str
An Entrez WebEnv to use saved history.
query_key : str
An Entrez query_key to use saved history.
retstart : int
Return values starting at this index.
retmax : int
Return at most this number of values.
api_key : str
A users API key which allows more requests per second
email : str
A users email which is required if not using API.
Returns
-------
EsearchResult
A named tuple with values [ids, count, webenv, query_key] | [
"Search",
"for",
"a",
"query",
"using",
"the",
"Entrez",
"ESearch",
"API",
"."
] | 82a9a157e44bda4100be385c644b3ac21be66038 | https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/services/entrez.py#L28-L83 | train | 53,736 |
jfear/sramongo | sramongo/services/entrez.py | epost | def epost(database, ids: List[str], webenv=False, api_key=False, email=False, **kwargs) -> Optional[EpostResult]:
"""Post IDs using the Entrez ESearch API.
Parameters
----------
database : str
Entez database to search.
ids : list
List of IDs to submit to the server.
webenv : str
An Entrez WebEnv to post ids to.
api_key : str
A users API key which allows more requests per second
email : str
A users email which is required if not using API.
Returns
-------
requests.Response
"""
url = BASE_URL + f'epost.fcgi'
id = ','.join(ids)
url_params = f'db={database}&id={id}'
url_params = check_webenv(webenv, url_params)
url_params = check_api_key(api_key, url_params)
url_params = check_email(email, url_params)
resp = entrez_try_put_multiple_times(url, url_params, num_tries=3)
time.sleep(.5)
return parse_epost(resp.text) | python | def epost(database, ids: List[str], webenv=False, api_key=False, email=False, **kwargs) -> Optional[EpostResult]:
"""Post IDs using the Entrez ESearch API.
Parameters
----------
database : str
Entez database to search.
ids : list
List of IDs to submit to the server.
webenv : str
An Entrez WebEnv to post ids to.
api_key : str
A users API key which allows more requests per second
email : str
A users email which is required if not using API.
Returns
-------
requests.Response
"""
url = BASE_URL + f'epost.fcgi'
id = ','.join(ids)
url_params = f'db={database}&id={id}'
url_params = check_webenv(webenv, url_params)
url_params = check_api_key(api_key, url_params)
url_params = check_email(email, url_params)
resp = entrez_try_put_multiple_times(url, url_params, num_tries=3)
time.sleep(.5)
return parse_epost(resp.text) | [
"def",
"epost",
"(",
"database",
",",
"ids",
":",
"List",
"[",
"str",
"]",
",",
"webenv",
"=",
"False",
",",
"api_key",
"=",
"False",
",",
"email",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
"->",
"Optional",
"[",
"EpostResult",
"]",
":",
"url",
... | Post IDs using the Entrez ESearch API.
Parameters
----------
database : str
Entez database to search.
ids : list
List of IDs to submit to the server.
webenv : str
An Entrez WebEnv to post ids to.
api_key : str
A users API key which allows more requests per second
email : str
A users email which is required if not using API.
Returns
-------
requests.Response | [
"Post",
"IDs",
"using",
"the",
"Entrez",
"ESearch",
"API",
"."
] | 82a9a157e44bda4100be385c644b3ac21be66038 | https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/services/entrez.py#L86-L115 | train | 53,737 |
jfear/sramongo | sramongo/services/entrez.py | efetch | def efetch(database, ids=False, webenv=False, query_key=False, count=False, retstart=False, retmax=False,
rettype='full', retmode='xml', api_key=False, email=False, **kwargs) -> str:
"""Get documents using the Entrez ESearch API.gg
Parameters
----------
database : str
Entez database to search.
ids : list or str
List of IDs to submit to the server.
webenv : str
An Entrez WebEnv to use saved history.
query_key : str
An Entrez query_key to use saved history.
count : int
Number of records in the webenv
retstart : int
Return values starting at this index.
retmax : int
Return at most this number of values.
rettype : str
The type of document to return. Refer to link for valid return types for each database.
https://www.ncbi.nlm.nih.gov/books/NBK25499/table/chapter4.T._valid_values_of__retmode_and/?report=objectonly
retmode : str
The format of document to return. Refer to link for valid formats for each database.
https://www.ncbi.nlm.nih.gov/books/NBK25499/table/chapter4.T._valid_values_of__retmode_and/?report=objectonly
api_key : str
A users API key which allows more requests per second
email : str
A users email which is required if not using API.
Yields
------
str
Text from effect results. Format depends on parameters passed to retmode
"""
url = BASE_URL + f'efetch.fcgi?db={database}&retmode={retmode}&rettype={rettype}'
url = check_webenv(webenv, url)
url = check_query_key(query_key, url)
url = check_api_key(api_key, url)
url = check_email(email, url)
if ids:
if isinstance(ids, str):
id = ids
else:
id = ','.join(ids)
url += f'&id={id}'
count = len(id.split(','))
for resp in entrez_sets_of_results(url, retstart, retmax, count):
yield resp.text | python | def efetch(database, ids=False, webenv=False, query_key=False, count=False, retstart=False, retmax=False,
rettype='full', retmode='xml', api_key=False, email=False, **kwargs) -> str:
"""Get documents using the Entrez ESearch API.gg
Parameters
----------
database : str
Entez database to search.
ids : list or str
List of IDs to submit to the server.
webenv : str
An Entrez WebEnv to use saved history.
query_key : str
An Entrez query_key to use saved history.
count : int
Number of records in the webenv
retstart : int
Return values starting at this index.
retmax : int
Return at most this number of values.
rettype : str
The type of document to return. Refer to link for valid return types for each database.
https://www.ncbi.nlm.nih.gov/books/NBK25499/table/chapter4.T._valid_values_of__retmode_and/?report=objectonly
retmode : str
The format of document to return. Refer to link for valid formats for each database.
https://www.ncbi.nlm.nih.gov/books/NBK25499/table/chapter4.T._valid_values_of__retmode_and/?report=objectonly
api_key : str
A users API key which allows more requests per second
email : str
A users email which is required if not using API.
Yields
------
str
Text from effect results. Format depends on parameters passed to retmode
"""
url = BASE_URL + f'efetch.fcgi?db={database}&retmode={retmode}&rettype={rettype}'
url = check_webenv(webenv, url)
url = check_query_key(query_key, url)
url = check_api_key(api_key, url)
url = check_email(email, url)
if ids:
if isinstance(ids, str):
id = ids
else:
id = ','.join(ids)
url += f'&id={id}'
count = len(id.split(','))
for resp in entrez_sets_of_results(url, retstart, retmax, count):
yield resp.text | [
"def",
"efetch",
"(",
"database",
",",
"ids",
"=",
"False",
",",
"webenv",
"=",
"False",
",",
"query_key",
"=",
"False",
",",
"count",
"=",
"False",
",",
"retstart",
"=",
"False",
",",
"retmax",
"=",
"False",
",",
"rettype",
"=",
"'full'",
",",
"retm... | Get documents using the Entrez ESearch API.gg
Parameters
----------
database : str
Entez database to search.
ids : list or str
List of IDs to submit to the server.
webenv : str
An Entrez WebEnv to use saved history.
query_key : str
An Entrez query_key to use saved history.
count : int
Number of records in the webenv
retstart : int
Return values starting at this index.
retmax : int
Return at most this number of values.
rettype : str
The type of document to return. Refer to link for valid return types for each database.
https://www.ncbi.nlm.nih.gov/books/NBK25499/table/chapter4.T._valid_values_of__retmode_and/?report=objectonly
retmode : str
The format of document to return. Refer to link for valid formats for each database.
https://www.ncbi.nlm.nih.gov/books/NBK25499/table/chapter4.T._valid_values_of__retmode_and/?report=objectonly
api_key : str
A users API key which allows more requests per second
email : str
A users email which is required if not using API.
Yields
------
str
Text from effect results. Format depends on parameters passed to retmode | [
"Get",
"documents",
"using",
"the",
"Entrez",
"ESearch",
"API",
".",
"gg"
] | 82a9a157e44bda4100be385c644b3ac21be66038 | https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/services/entrez.py#L223-L275 | train | 53,738 |
jfear/sramongo | sramongo/services/entrez.py | entrez_sets_of_results | def entrez_sets_of_results(url, retstart=False, retmax=False, count=False) -> Optional[List[requests.Response]]:
"""Gets sets of results back from Entrez.
Entrez can only return 500 results at a time. This creates a generator that gets results by incrementing
retstart and retmax.
Parameters
----------
url : str
The Entrez API url to use.
retstart : int
Return values starting at this index.
retmax : int
Return at most this number of values.
count : int
The number of results returned by EQuery.
Yields
------
requests.Response
"""
if not retstart:
retstart = 0
if not retmax:
retmax = 500
if not count:
count = retmax
retmax = 500 # Entrez can return a max of 500
while retstart < count:
diff = count - retstart
if diff < 500:
retmax = diff
_url = url + f'&retstart={retstart}&retmax={retmax}'
resp = entrez_try_get_multiple_times(_url)
if resp is None:
return
retstart += retmax
yield resp | python | def entrez_sets_of_results(url, retstart=False, retmax=False, count=False) -> Optional[List[requests.Response]]:
"""Gets sets of results back from Entrez.
Entrez can only return 500 results at a time. This creates a generator that gets results by incrementing
retstart and retmax.
Parameters
----------
url : str
The Entrez API url to use.
retstart : int
Return values starting at this index.
retmax : int
Return at most this number of values.
count : int
The number of results returned by EQuery.
Yields
------
requests.Response
"""
if not retstart:
retstart = 0
if not retmax:
retmax = 500
if not count:
count = retmax
retmax = 500 # Entrez can return a max of 500
while retstart < count:
diff = count - retstart
if diff < 500:
retmax = diff
_url = url + f'&retstart={retstart}&retmax={retmax}'
resp = entrez_try_get_multiple_times(_url)
if resp is None:
return
retstart += retmax
yield resp | [
"def",
"entrez_sets_of_results",
"(",
"url",
",",
"retstart",
"=",
"False",
",",
"retmax",
"=",
"False",
",",
"count",
"=",
"False",
")",
"->",
"Optional",
"[",
"List",
"[",
"requests",
".",
"Response",
"]",
"]",
":",
"if",
"not",
"retstart",
":",
"ret... | Gets sets of results back from Entrez.
Entrez can only return 500 results at a time. This creates a generator that gets results by incrementing
retstart and retmax.
Parameters
----------
url : str
The Entrez API url to use.
retstart : int
Return values starting at this index.
retmax : int
Return at most this number of values.
count : int
The number of results returned by EQuery.
Yields
------
requests.Response | [
"Gets",
"sets",
"of",
"results",
"back",
"from",
"Entrez",
"."
] | 82a9a157e44bda4100be385c644b3ac21be66038 | https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/services/entrez.py#L358-L401 | train | 53,739 |
PolyJIT/benchbuild | benchbuild/cli/log.py | print_runs | def print_runs(query):
""" Print all rows in this result query. """
if query is None:
return
for tup in query:
print(("{0} @ {1} - {2} id: {3} group: {4}".format(
tup.end, tup.experiment_name, tup.project_name,
tup.experiment_group, tup.run_group))) | python | def print_runs(query):
""" Print all rows in this result query. """
if query is None:
return
for tup in query:
print(("{0} @ {1} - {2} id: {3} group: {4}".format(
tup.end, tup.experiment_name, tup.project_name,
tup.experiment_group, tup.run_group))) | [
"def",
"print_runs",
"(",
"query",
")",
":",
"if",
"query",
"is",
"None",
":",
"return",
"for",
"tup",
"in",
"query",
":",
"print",
"(",
"(",
"\"{0} @ {1} - {2} id: {3} group: {4}\"",
".",
"format",
"(",
"tup",
".",
"end",
",",
"tup",
".",
"experiment_name... | Print all rows in this result query. | [
"Print",
"all",
"rows",
"in",
"this",
"result",
"query",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/cli/log.py#L9-L18 | train | 53,740 |
PolyJIT/benchbuild | benchbuild/cli/log.py | print_logs | def print_logs(query, types=None):
""" Print status logs. """
if query is None:
return
for run, log in query:
print(("{0} @ {1} - {2} id: {3} group: {4} status: {5}".format(
run.end, run.experiment_name, run.project_name,
run.experiment_group, run.run_group, log.status)))
print(("command: {0}".format(run.command)))
if "stderr" in types:
print("StdErr:")
print((log.stderr))
if "stdout" in types:
print("StdOut:")
print((log.stdout))
print() | python | def print_logs(query, types=None):
""" Print status logs. """
if query is None:
return
for run, log in query:
print(("{0} @ {1} - {2} id: {3} group: {4} status: {5}".format(
run.end, run.experiment_name, run.project_name,
run.experiment_group, run.run_group, log.status)))
print(("command: {0}".format(run.command)))
if "stderr" in types:
print("StdErr:")
print((log.stderr))
if "stdout" in types:
print("StdOut:")
print((log.stdout))
print() | [
"def",
"print_logs",
"(",
"query",
",",
"types",
"=",
"None",
")",
":",
"if",
"query",
"is",
"None",
":",
"return",
"for",
"run",
",",
"log",
"in",
"query",
":",
"print",
"(",
"(",
"\"{0} @ {1} - {2} id: {3} group: {4} status: {5}\"",
".",
"format",
"(",
"... | Print status logs. | [
"Print",
"status",
"logs",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/cli/log.py#L21-L37 | train | 53,741 |
sci-bots/svg-model | svg_model/merge.py | get_svg_layers | def get_svg_layers(svg_sources):
'''
Collect layers from input svg sources.
Args:
svg_sources (list) : A list of file-like objects, each containing
one or more XML layers.
Returns
-------
(width, height), layers : (int, int), list
The first item in the tuple is the shape of the largest layer, and the
second item is a list of ``Element`` objects (from :mod:`lxml.etree`
module), one per SVG layer.
'''
layers = []
width, height = None, None
def extract_length(attr):
'Extract length in pixels.'
match = CRE_MM_LENGTH.match(attr)
if match:
# Length is specified in millimeters.
return INKSCAPE_PPmm.magnitude * float(match.group('length'))
else:
return float(attr)
for svg_source_i in svg_sources:
# Parse input file.
xml_root = etree.parse(svg_source_i)
svg_root = xml_root.xpath('/svg:svg', namespaces=INKSCAPE_NSMAP)[0]
width = max(extract_length(svg_root.attrib['width']), width)
height = max(extract_length(svg_root.attrib['height']), height)
layers += svg_root.xpath('//svg:g[@inkscape:groupmode="layer"]',
namespaces=INKSCAPE_NSMAP)
for i, layer_i in enumerate(layers):
layer_i.attrib['id'] = 'layer%d' % (i + 1)
return (width, height), layers | python | def get_svg_layers(svg_sources):
'''
Collect layers from input svg sources.
Args:
svg_sources (list) : A list of file-like objects, each containing
one or more XML layers.
Returns
-------
(width, height), layers : (int, int), list
The first item in the tuple is the shape of the largest layer, and the
second item is a list of ``Element`` objects (from :mod:`lxml.etree`
module), one per SVG layer.
'''
layers = []
width, height = None, None
def extract_length(attr):
'Extract length in pixels.'
match = CRE_MM_LENGTH.match(attr)
if match:
# Length is specified in millimeters.
return INKSCAPE_PPmm.magnitude * float(match.group('length'))
else:
return float(attr)
for svg_source_i in svg_sources:
# Parse input file.
xml_root = etree.parse(svg_source_i)
svg_root = xml_root.xpath('/svg:svg', namespaces=INKSCAPE_NSMAP)[0]
width = max(extract_length(svg_root.attrib['width']), width)
height = max(extract_length(svg_root.attrib['height']), height)
layers += svg_root.xpath('//svg:g[@inkscape:groupmode="layer"]',
namespaces=INKSCAPE_NSMAP)
for i, layer_i in enumerate(layers):
layer_i.attrib['id'] = 'layer%d' % (i + 1)
return (width, height), layers | [
"def",
"get_svg_layers",
"(",
"svg_sources",
")",
":",
"layers",
"=",
"[",
"]",
"width",
",",
"height",
"=",
"None",
",",
"None",
"def",
"extract_length",
"(",
"attr",
")",
":",
"'Extract length in pixels.'",
"match",
"=",
"CRE_MM_LENGTH",
".",
"match",
"(",... | Collect layers from input svg sources.
Args:
svg_sources (list) : A list of file-like objects, each containing
one or more XML layers.
Returns
-------
(width, height), layers : (int, int), list
The first item in the tuple is the shape of the largest layer, and the
second item is a list of ``Element`` objects (from :mod:`lxml.etree`
module), one per SVG layer. | [
"Collect",
"layers",
"from",
"input",
"svg",
"sources",
"."
] | 2d119650f995e62b29ce0b3151a23f3b957cb072 | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/merge.py#L14-L53 | train | 53,742 |
sci-bots/svg-model | svg_model/merge.py | merge_svg_layers | def merge_svg_layers(svg_sources, share_transform=True):
'''
Merge layers from input svg sources into a single XML document.
Args:
svg_sources (list) : A list of file-like objects, each containing
one or more XML layers.
share_transform (bool) : If exactly one layer has a transform, apply it
to *all* other layers as well.
Returns:
StringIO.StringIO : File-like object containing merge XML document.
'''
# Get list of XML layers.
(width, height), layers = get_svg_layers(svg_sources)
if share_transform:
transforms = [layer_i.attrib['transform'] for layer_i in layers
if 'transform' in layer_i.attrib]
if len(transforms) > 1:
raise ValueError('Transform can only be shared if *exactly one* '
'layer has a transform ({} layers have '
'`transform` attributes)'.format(len(transforms)))
elif transforms:
# Apply single common transform to all layers.
for layer_i in layers:
layer_i.attrib['transform'] = transforms[0]
# Create blank XML output document.
dwg = svgwrite.Drawing(profile='tiny', debug=False, size=(width, height))
# Add append layers to output XML root element.
output_svg_root = etree.fromstring(dwg.tostring())
output_svg_root.extend(layers)
# Write merged XML document to output file-like object.
output = StringIO.StringIO()
output.write(etree.tostring(output_svg_root))
output.seek(0)
return output | python | def merge_svg_layers(svg_sources, share_transform=True):
'''
Merge layers from input svg sources into a single XML document.
Args:
svg_sources (list) : A list of file-like objects, each containing
one or more XML layers.
share_transform (bool) : If exactly one layer has a transform, apply it
to *all* other layers as well.
Returns:
StringIO.StringIO : File-like object containing merge XML document.
'''
# Get list of XML layers.
(width, height), layers = get_svg_layers(svg_sources)
if share_transform:
transforms = [layer_i.attrib['transform'] for layer_i in layers
if 'transform' in layer_i.attrib]
if len(transforms) > 1:
raise ValueError('Transform can only be shared if *exactly one* '
'layer has a transform ({} layers have '
'`transform` attributes)'.format(len(transforms)))
elif transforms:
# Apply single common transform to all layers.
for layer_i in layers:
layer_i.attrib['transform'] = transforms[0]
# Create blank XML output document.
dwg = svgwrite.Drawing(profile='tiny', debug=False, size=(width, height))
# Add append layers to output XML root element.
output_svg_root = etree.fromstring(dwg.tostring())
output_svg_root.extend(layers)
# Write merged XML document to output file-like object.
output = StringIO.StringIO()
output.write(etree.tostring(output_svg_root))
output.seek(0)
return output | [
"def",
"merge_svg_layers",
"(",
"svg_sources",
",",
"share_transform",
"=",
"True",
")",
":",
"# Get list of XML layers.",
"(",
"width",
",",
"height",
")",
",",
"layers",
"=",
"get_svg_layers",
"(",
"svg_sources",
")",
"if",
"share_transform",
":",
"transforms",
... | Merge layers from input svg sources into a single XML document.
Args:
svg_sources (list) : A list of file-like objects, each containing
one or more XML layers.
share_transform (bool) : If exactly one layer has a transform, apply it
to *all* other layers as well.
Returns:
StringIO.StringIO : File-like object containing merge XML document. | [
"Merge",
"layers",
"from",
"input",
"svg",
"sources",
"into",
"a",
"single",
"XML",
"document",
"."
] | 2d119650f995e62b29ce0b3151a23f3b957cb072 | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/merge.py#L56-L97 | train | 53,743 |
BlueBrain/hpcbench | hpcbench/cli/bensh.py | main | def main(argv=None):
"""ben-sh entry point"""
arguments = cli_common(__doc__, argv=argv)
campaign_file = arguments['CAMPAIGN_FILE']
if arguments['-g']:
if osp.exists(campaign_file):
raise Exception('Campaign file already exists')
with open(campaign_file, 'w') as ostr:
Generator().write(ostr)
else:
node = arguments.get('-n')
output_dir = arguments.get('--output-dir')
exclude_nodes = arguments.get('--exclude-nodes')
srun_tag = arguments.get('--srun')
driver = CampaignDriver(
campaign_file,
node=node,
output_dir=output_dir,
srun=srun_tag,
exclude_nodes=exclude_nodes,
)
driver()
if argv is not None:
return driver
campaign_fd = int(arguments.get('--campaign-path-fd') or 1)
message = (osp.abspath(driver.campaign_path) + '\n').encode()
os.write(campaign_fd, message) | python | def main(argv=None):
"""ben-sh entry point"""
arguments = cli_common(__doc__, argv=argv)
campaign_file = arguments['CAMPAIGN_FILE']
if arguments['-g']:
if osp.exists(campaign_file):
raise Exception('Campaign file already exists')
with open(campaign_file, 'w') as ostr:
Generator().write(ostr)
else:
node = arguments.get('-n')
output_dir = arguments.get('--output-dir')
exclude_nodes = arguments.get('--exclude-nodes')
srun_tag = arguments.get('--srun')
driver = CampaignDriver(
campaign_file,
node=node,
output_dir=output_dir,
srun=srun_tag,
exclude_nodes=exclude_nodes,
)
driver()
if argv is not None:
return driver
campaign_fd = int(arguments.get('--campaign-path-fd') or 1)
message = (osp.abspath(driver.campaign_path) + '\n').encode()
os.write(campaign_fd, message) | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"arguments",
"=",
"cli_common",
"(",
"__doc__",
",",
"argv",
"=",
"argv",
")",
"campaign_file",
"=",
"arguments",
"[",
"'CAMPAIGN_FILE'",
"]",
"if",
"arguments",
"[",
"'-g'",
"]",
":",
"if",
"osp",
"."... | ben-sh entry point | [
"ben",
"-",
"sh",
"entry",
"point"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/cli/bensh.py#L35-L61 | train | 53,744 |
BlueBrain/hpcbench | hpcbench/cli/benumb.py | main | def main(argv=None):
"""ben-umb entry point"""
arguments = cli_common(__doc__, argv=argv)
driver = CampaignDriver(arguments['CAMPAIGN-DIR'], expandcampvars=False)
driver(no_exec=True)
if argv is not None:
return driver | python | def main(argv=None):
"""ben-umb entry point"""
arguments = cli_common(__doc__, argv=argv)
driver = CampaignDriver(arguments['CAMPAIGN-DIR'], expandcampvars=False)
driver(no_exec=True)
if argv is not None:
return driver | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"arguments",
"=",
"cli_common",
"(",
"__doc__",
",",
"argv",
"=",
"argv",
")",
"driver",
"=",
"CampaignDriver",
"(",
"arguments",
"[",
"'CAMPAIGN-DIR'",
"]",
",",
"expandcampvars",
"=",
"False",
")",
"dr... | ben-umb entry point | [
"ben",
"-",
"umb",
"entry",
"point"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/cli/benumb.py#L19-L25 | train | 53,745 |
portfoliome/foil | foil/counting.py | count_by | def count_by(records: Sequence[Dict], field_name: str) -> defaultdict:
"""
Frequency each value occurs in a record sequence for a given field name.
"""
counter = defaultdict(int)
for record in records:
name = record[field_name]
counter[name] += 1
return counter | python | def count_by(records: Sequence[Dict], field_name: str) -> defaultdict:
"""
Frequency each value occurs in a record sequence for a given field name.
"""
counter = defaultdict(int)
for record in records:
name = record[field_name]
counter[name] += 1
return counter | [
"def",
"count_by",
"(",
"records",
":",
"Sequence",
"[",
"Dict",
"]",
",",
"field_name",
":",
"str",
")",
"->",
"defaultdict",
":",
"counter",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"record",
"in",
"records",
":",
"name",
"=",
"record",
"[",
"fiel... | Frequency each value occurs in a record sequence for a given field name. | [
"Frequency",
"each",
"value",
"occurs",
"in",
"a",
"record",
"sequence",
"for",
"a",
"given",
"field",
"name",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/counting.py#L5-L16 | train | 53,746 |
PolyJIT/benchbuild | benchbuild/reports/status.py | FullDump.generate | def generate(self):
"""
Fetch all rows associated with this experiment.
This will generate a huge .csv.
"""
exp_name = self.exp_name()
fname = os.path.basename(self.out_path)
fname = "{exp}_{prefix}_{name}{ending}".format(
exp=exp_name,
prefix=os.path.splitext(fname)[0],
ending=os.path.splitext(fname)[-1],
name="full")
first = True
for chunk in self.report():
print("Writing chunk to :'{0}'".format(fname))
chunk.to_csv(fname, header=first, mode='a')
first = False | python | def generate(self):
"""
Fetch all rows associated with this experiment.
This will generate a huge .csv.
"""
exp_name = self.exp_name()
fname = os.path.basename(self.out_path)
fname = "{exp}_{prefix}_{name}{ending}".format(
exp=exp_name,
prefix=os.path.splitext(fname)[0],
ending=os.path.splitext(fname)[-1],
name="full")
first = True
for chunk in self.report():
print("Writing chunk to :'{0}'".format(fname))
chunk.to_csv(fname, header=first, mode='a')
first = False | [
"def",
"generate",
"(",
"self",
")",
":",
"exp_name",
"=",
"self",
".",
"exp_name",
"(",
")",
"fname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"out_path",
")",
"fname",
"=",
"\"{exp}_{prefix}_{name}{ending}\"",
".",
"format",
"(",
"exp... | Fetch all rows associated with this experiment.
This will generate a huge .csv. | [
"Fetch",
"all",
"rows",
"associated",
"with",
"this",
"experiment",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/reports/status.py#L82-L100 | train | 53,747 |
BlueBrain/hpcbench | hpcbench/cli/bendoc.py | main | def main(argv=None):
"""ben-doc entry point"""
arguments = cli_common(__doc__, argv=argv)
campaign_path = arguments['CAMPAIGN-DIR']
driver = CampaignDriver(campaign_path, expandcampvars=False)
with pushd(campaign_path):
render(
template=arguments['--template'],
ostr=arguments['--output'],
campaign=driver,
)
if argv is not None:
return driver | python | def main(argv=None):
"""ben-doc entry point"""
arguments = cli_common(__doc__, argv=argv)
campaign_path = arguments['CAMPAIGN-DIR']
driver = CampaignDriver(campaign_path, expandcampvars=False)
with pushd(campaign_path):
render(
template=arguments['--template'],
ostr=arguments['--output'],
campaign=driver,
)
if argv is not None:
return driver | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"arguments",
"=",
"cli_common",
"(",
"__doc__",
",",
"argv",
"=",
"argv",
")",
"campaign_path",
"=",
"arguments",
"[",
"'CAMPAIGN-DIR'",
"]",
"driver",
"=",
"CampaignDriver",
"(",
"campaign_path",
",",
"ex... | ben-doc entry point | [
"ben",
"-",
"doc",
"entry",
"point"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/cli/bendoc.py#L24-L36 | train | 53,748 |
chrisjsewell/jsonextended | jsonextended/utils.py | class_to_str | def class_to_str(obj):
""" get class string from object
Examples
--------
>>> class_to_str(list).split('.')[1]
'list'
"""
mod_str = obj.__module__
name_str = obj.__name__
if mod_str == '__main__':
return name_str
else:
return '.'.join([mod_str, name_str]) | python | def class_to_str(obj):
""" get class string from object
Examples
--------
>>> class_to_str(list).split('.')[1]
'list'
"""
mod_str = obj.__module__
name_str = obj.__name__
if mod_str == '__main__':
return name_str
else:
return '.'.join([mod_str, name_str]) | [
"def",
"class_to_str",
"(",
"obj",
")",
":",
"mod_str",
"=",
"obj",
".",
"__module__",
"name_str",
"=",
"obj",
".",
"__name__",
"if",
"mod_str",
"==",
"'__main__'",
":",
"return",
"name_str",
"else",
":",
"return",
"'.'",
".",
"join",
"(",
"[",
"mod_str"... | get class string from object
Examples
--------
>>> class_to_str(list).split('.')[1]
'list' | [
"get",
"class",
"string",
"from",
"object"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/utils.py#L22-L37 | train | 53,749 |
chrisjsewell/jsonextended | jsonextended/utils.py | get_module_path | def get_module_path(module):
"""return a directory path to a module"""
return pathlib.Path(
os.path.dirname(os.path.abspath(inspect.getfile(module)))) | python | def get_module_path(module):
"""return a directory path to a module"""
return pathlib.Path(
os.path.dirname(os.path.abspath(inspect.getfile(module)))) | [
"def",
"get_module_path",
"(",
"module",
")",
":",
"return",
"pathlib",
".",
"Path",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"inspect",
".",
"getfile",
"(",
"module",
")",
")",
")",
")"
] | return a directory path to a module | [
"return",
"a",
"directory",
"path",
"to",
"a",
"module"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/utils.py#L40-L43 | train | 53,750 |
chrisjsewell/jsonextended | jsonextended/utils.py | get_data_path | def get_data_path(data, module, check_exists=True):
"""return a directory path to data within a module
Parameters
----------
data : str or list[str]
file name or list of sub-directories
and file name (e.g. ['lammps','data.txt'])
"""
basepath = os.path.dirname(os.path.abspath(inspect.getfile(module)))
if isinstance(data, basestring):
data = [data]
dirpath = os.path.join(basepath, *data)
if check_exists:
assert os.path.exists(dirpath), '{0} does not exist'.format(dirpath)
return pathlib.Path(dirpath) | python | def get_data_path(data, module, check_exists=True):
"""return a directory path to data within a module
Parameters
----------
data : str or list[str]
file name or list of sub-directories
and file name (e.g. ['lammps','data.txt'])
"""
basepath = os.path.dirname(os.path.abspath(inspect.getfile(module)))
if isinstance(data, basestring):
data = [data]
dirpath = os.path.join(basepath, *data)
if check_exists:
assert os.path.exists(dirpath), '{0} does not exist'.format(dirpath)
return pathlib.Path(dirpath) | [
"def",
"get_data_path",
"(",
"data",
",",
"module",
",",
"check_exists",
"=",
"True",
")",
":",
"basepath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"inspect",
".",
"getfile",
"(",
"module",
")",
")",
")",
... | return a directory path to data within a module
Parameters
----------
data : str or list[str]
file name or list of sub-directories
and file name (e.g. ['lammps','data.txt']) | [
"return",
"a",
"directory",
"path",
"to",
"data",
"within",
"a",
"module"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/utils.py#L59-L79 | train | 53,751 |
chrisjsewell/jsonextended | jsonextended/utils.py | load_memit | def load_memit():
"""load memory usage ipython magic,
require memory_profiler package to be installed
to get usage: %memit?
Author: Vlad Niculae <vlad@vene.ro>
Makes use of memory_profiler from Fabian Pedregosa
available at https://github.com/fabianp/memory_profiler
"""
from IPython.core.magic import Magics, line_magic, magics_class
from memory_profiler import memory_usage as _mu
try:
ip = get_ipython()
except NameError as err:
raise Exception('not in ipython/jupyter kernel:\n {}'.format(err))
@magics_class
class MemMagics(Magics):
@line_magic
def memit(self, line='', setup='pass'):
"""Measure memory usage of a Python statement
Usage, in line mode:
%memit [-ir<R>t<T>] statement
Options:
-r<R>: repeat the loop iteration <R> times
and take the best result. Default: 3
-i: run the code in the current environment, without forking a new
process.
This is required on some MacOS versions of Accelerate if your
line contains a call to `np.dot`.
-t<T>: timeout after <T> seconds. Unused if `-i` is active.
Default: None
Examples
--------
::
In [1]: import numpy as np
In [2]: %memit np.zeros(1e7)
maximum of 3: 76.402344 MB per loop
In [3]: %memit np.ones(1e6)
maximum of 3: 7.820312 MB per loop
In [4]: %memit -r 10 np.empty(1e8)
maximum of 10: 0.101562 MB per loop
In [5]: memit -t 3 while True: pass;
Subprocess timed out.
Subprocess timed out.
Subprocess timed out.
ERROR: all subprocesses exited unsuccessfully. Try again with the
`-i` option.
maximum of 3: -inf MB per loop
"""
opts, stmt = self.parse_options(line, 'r:t:i', posix=False,
strict=False)
repeat = int(getattr(opts, 'r', 3))
if repeat < 1:
repeat == 1
timeout = int(getattr(opts, 't', 0))
if timeout <= 0:
timeout = None
run_in_place = hasattr(opts, 'i')
# Don't depend on multiprocessing:
try:
import multiprocessing as pr
from multiprocessing.queues import SimpleQueue
q = SimpleQueue()
except ImportError:
class ListWithPut(list):
"""Just a list,
where the `append` method is aliased to `put`."""
def put(self, x):
self.append(x)
q = ListWithPut()
print(
'WARNING: cannot import module `multiprocessing`. Forcing '
'the `-i` option.')
run_in_place = True
ns = self.shell.user_ns
def _get_usage(q, stmt, setup='pass', ns={}):
try:
exec(setup) in ns
_mu0 = _mu()[0]
exec(stmt) in ns
_mu1 = _mu()[0]
q.put(_mu1 - _mu0)
except Exception as e:
q.put(float('-inf'))
raise e
if run_in_place:
for _ in range(repeat):
_get_usage(q, stmt, ns=ns)
else:
# run in consecutive subprocesses
at_least_one_worked = False
for _ in range(repeat):
p = pr.Process(
target=_get_usage, args=(q, stmt, 'pass', ns))
p.start()
p.join(timeout=timeout)
if p.exitcode == 0:
at_least_one_worked = True
else:
p.terminate()
if p.exitcode is None:
print('Subprocess timed out.')
else:
print(
'Subprocess exited with code %d.' % p.exitcode)
q.put(float('-inf'))
if not at_least_one_worked:
print('ERROR: all subprocesses exited unsuccessfully. Try '
'again with the `-i` option.')
usages = [q.get() for _ in range(repeat)]
usage = max(usages)
print("maximum of %d: %f MB per loop" % (repeat, usage))
ip.register_magics(MemMagics) | python | def load_memit():
"""load memory usage ipython magic,
require memory_profiler package to be installed
to get usage: %memit?
Author: Vlad Niculae <vlad@vene.ro>
Makes use of memory_profiler from Fabian Pedregosa
available at https://github.com/fabianp/memory_profiler
"""
from IPython.core.magic import Magics, line_magic, magics_class
from memory_profiler import memory_usage as _mu
try:
ip = get_ipython()
except NameError as err:
raise Exception('not in ipython/jupyter kernel:\n {}'.format(err))
@magics_class
class MemMagics(Magics):
@line_magic
def memit(self, line='', setup='pass'):
"""Measure memory usage of a Python statement
Usage, in line mode:
%memit [-ir<R>t<T>] statement
Options:
-r<R>: repeat the loop iteration <R> times
and take the best result. Default: 3
-i: run the code in the current environment, without forking a new
process.
This is required on some MacOS versions of Accelerate if your
line contains a call to `np.dot`.
-t<T>: timeout after <T> seconds. Unused if `-i` is active.
Default: None
Examples
--------
::
In [1]: import numpy as np
In [2]: %memit np.zeros(1e7)
maximum of 3: 76.402344 MB per loop
In [3]: %memit np.ones(1e6)
maximum of 3: 7.820312 MB per loop
In [4]: %memit -r 10 np.empty(1e8)
maximum of 10: 0.101562 MB per loop
In [5]: memit -t 3 while True: pass;
Subprocess timed out.
Subprocess timed out.
Subprocess timed out.
ERROR: all subprocesses exited unsuccessfully. Try again with the
`-i` option.
maximum of 3: -inf MB per loop
"""
opts, stmt = self.parse_options(line, 'r:t:i', posix=False,
strict=False)
repeat = int(getattr(opts, 'r', 3))
if repeat < 1:
repeat == 1
timeout = int(getattr(opts, 't', 0))
if timeout <= 0:
timeout = None
run_in_place = hasattr(opts, 'i')
# Don't depend on multiprocessing:
try:
import multiprocessing as pr
from multiprocessing.queues import SimpleQueue
q = SimpleQueue()
except ImportError:
class ListWithPut(list):
"""Just a list,
where the `append` method is aliased to `put`."""
def put(self, x):
self.append(x)
q = ListWithPut()
print(
'WARNING: cannot import module `multiprocessing`. Forcing '
'the `-i` option.')
run_in_place = True
ns = self.shell.user_ns
def _get_usage(q, stmt, setup='pass', ns={}):
try:
exec(setup) in ns
_mu0 = _mu()[0]
exec(stmt) in ns
_mu1 = _mu()[0]
q.put(_mu1 - _mu0)
except Exception as e:
q.put(float('-inf'))
raise e
if run_in_place:
for _ in range(repeat):
_get_usage(q, stmt, ns=ns)
else:
# run in consecutive subprocesses
at_least_one_worked = False
for _ in range(repeat):
p = pr.Process(
target=_get_usage, args=(q, stmt, 'pass', ns))
p.start()
p.join(timeout=timeout)
if p.exitcode == 0:
at_least_one_worked = True
else:
p.terminate()
if p.exitcode is None:
print('Subprocess timed out.')
else:
print(
'Subprocess exited with code %d.' % p.exitcode)
q.put(float('-inf'))
if not at_least_one_worked:
print('ERROR: all subprocesses exited unsuccessfully. Try '
'again with the `-i` option.')
usages = [q.get() for _ in range(repeat)]
usage = max(usages)
print("maximum of %d: %f MB per loop" % (repeat, usage))
ip.register_magics(MemMagics) | [
"def",
"load_memit",
"(",
")",
":",
"from",
"IPython",
".",
"core",
".",
"magic",
"import",
"Magics",
",",
"line_magic",
",",
"magics_class",
"from",
"memory_profiler",
"import",
"memory_usage",
"as",
"_mu",
"try",
":",
"ip",
"=",
"get_ipython",
"(",
")",
... | load memory usage ipython magic,
require memory_profiler package to be installed
to get usage: %memit?
Author: Vlad Niculae <vlad@vene.ro>
Makes use of memory_profiler from Fabian Pedregosa
available at https://github.com/fabianp/memory_profiler | [
"load",
"memory",
"usage",
"ipython",
"magic",
"require",
"memory_profiler",
"package",
"to",
"be",
"installed"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/utils.py#L147-L282 | train | 53,752 |
jfear/sramongo | sramongo/xml_helpers.py | parse_tree_from_dict | def parse_tree_from_dict(node, locs):
"""Processes key locations.
Parameters
----------
node: xml.etree.ElementTree.ElementTree.element
Current node.
locs: dict
A dictionary mapping key to a tuple. The tuple can either be 2 or 3
elements long. The first element maps to the location in the
current node. The second element given a processing hint. Possible
values are:
* 'text': assumes the text element of the path is wanted.
* 'child': assumes that the child of the given path is wanted.
* str: Any other string will be treated as an attribute lookup
of the path.
If 'child' is given, then a third element needs to be given
indicating the type of processing. Possible values are:
* 'text': assumes the text element of the path is wanted.
* 'tag': assumes the class tag of the path is wanted.
* str: Any other string will be treated as an attribute lookup
of the path.
"""
d = dict()
for n, l in locs.items():
try:
if l[1] == 'text':
d[n] = node.find(l[0]).text
elif l[1] == 'child':
child = node.find(l[0]).getchildren()
if len(child) > 1:
raise AmbiguousElementException(
'There are too many elements')
elif l[2] == 'text':
d[n] = child[0].text
elif l[2] == 'tag':
d[n] = child[0].tag
else:
d[n] = node.find(l[0]).get(l[1])
except:
pass
return d | python | def parse_tree_from_dict(node, locs):
"""Processes key locations.
Parameters
----------
node: xml.etree.ElementTree.ElementTree.element
Current node.
locs: dict
A dictionary mapping key to a tuple. The tuple can either be 2 or 3
elements long. The first element maps to the location in the
current node. The second element given a processing hint. Possible
values are:
* 'text': assumes the text element of the path is wanted.
* 'child': assumes that the child of the given path is wanted.
* str: Any other string will be treated as an attribute lookup
of the path.
If 'child' is given, then a third element needs to be given
indicating the type of processing. Possible values are:
* 'text': assumes the text element of the path is wanted.
* 'tag': assumes the class tag of the path is wanted.
* str: Any other string will be treated as an attribute lookup
of the path.
"""
d = dict()
for n, l in locs.items():
try:
if l[1] == 'text':
d[n] = node.find(l[0]).text
elif l[1] == 'child':
child = node.find(l[0]).getchildren()
if len(child) > 1:
raise AmbiguousElementException(
'There are too many elements')
elif l[2] == 'text':
d[n] = child[0].text
elif l[2] == 'tag':
d[n] = child[0].tag
else:
d[n] = node.find(l[0]).get(l[1])
except:
pass
return d | [
"def",
"parse_tree_from_dict",
"(",
"node",
",",
"locs",
")",
":",
"d",
"=",
"dict",
"(",
")",
"for",
"n",
",",
"l",
"in",
"locs",
".",
"items",
"(",
")",
":",
"try",
":",
"if",
"l",
"[",
"1",
"]",
"==",
"'text'",
":",
"d",
"[",
"n",
"]",
"... | Processes key locations.
Parameters
----------
node: xml.etree.ElementTree.ElementTree.element
Current node.
locs: dict
A dictionary mapping key to a tuple. The tuple can either be 2 or 3
elements long. The first element maps to the location in the
current node. The second element given a processing hint. Possible
values are:
* 'text': assumes the text element of the path is wanted.
* 'child': assumes that the child of the given path is wanted.
* str: Any other string will be treated as an attribute lookup
of the path.
If 'child' is given, then a third element needs to be given
indicating the type of processing. Possible values are:
* 'text': assumes the text element of the path is wanted.
* 'tag': assumes the class tag of the path is wanted.
* str: Any other string will be treated as an attribute lookup
of the path. | [
"Processes",
"key",
"locations",
"."
] | 82a9a157e44bda4100be385c644b3ac21be66038 | https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/xml_helpers.py#L26-L72 | train | 53,753 |
jfear/sramongo | sramongo/xml_helpers.py | xml_to_root | def xml_to_root(xml: Union[str, IO]) -> ElementTree.Element:
"""Parse XML into an ElemeTree object.
Parameters
----------
xml : str or file-like object
A filename, file object or string version of xml can be passed.
Returns
-------
Elementree.Element
"""
if isinstance(xml, str):
if '<' in xml:
return ElementTree.fromstring(xml)
else:
with open(xml) as fh:
xml_to_root(fh)
tree = ElementTree.parse(xml)
return tree.getroot() | python | def xml_to_root(xml: Union[str, IO]) -> ElementTree.Element:
"""Parse XML into an ElemeTree object.
Parameters
----------
xml : str or file-like object
A filename, file object or string version of xml can be passed.
Returns
-------
Elementree.Element
"""
if isinstance(xml, str):
if '<' in xml:
return ElementTree.fromstring(xml)
else:
with open(xml) as fh:
xml_to_root(fh)
tree = ElementTree.parse(xml)
return tree.getroot() | [
"def",
"xml_to_root",
"(",
"xml",
":",
"Union",
"[",
"str",
",",
"IO",
"]",
")",
"->",
"ElementTree",
".",
"Element",
":",
"if",
"isinstance",
"(",
"xml",
",",
"str",
")",
":",
"if",
"'<'",
"in",
"xml",
":",
"return",
"ElementTree",
".",
"fromstring"... | Parse XML into an ElemeTree object.
Parameters
----------
xml : str or file-like object
A filename, file object or string version of xml can be passed.
Returns
-------
Elementree.Element | [
"Parse",
"XML",
"into",
"an",
"ElemeTree",
"object",
"."
] | 82a9a157e44bda4100be385c644b3ac21be66038 | https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/xml_helpers.py#L75-L95 | train | 53,754 |
elkiwy/paynter | paynter/image.py | Image.mergeAllLayers | def mergeAllLayers(self):
"""
Merge all the layers together.
:rtype: The result :py:class:`Layer` object.
"""
start = time.time()
while(len(self.layers)>1):
self.mergeBottomLayers()
print('merge time:'+str(time.time()-start))
return self.layers[0] | python | def mergeAllLayers(self):
"""
Merge all the layers together.
:rtype: The result :py:class:`Layer` object.
"""
start = time.time()
while(len(self.layers)>1):
self.mergeBottomLayers()
print('merge time:'+str(time.time()-start))
return self.layers[0] | [
"def",
"mergeAllLayers",
"(",
"self",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"while",
"(",
"len",
"(",
"self",
".",
"layers",
")",
">",
"1",
")",
":",
"self",
".",
"mergeBottomLayers",
"(",
")",
"print",
"(",
"'merge time:'",
"+",
"... | Merge all the layers together.
:rtype: The result :py:class:`Layer` object. | [
"Merge",
"all",
"the",
"layers",
"together",
"."
] | f73cb5bb010a6b32ee41640a50396ed0bae8d496 | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/image.py#L77-L87 | train | 53,755 |
Metatab/metatab | metatab/parser.py | TermParser.synonyms | def synonyms(self):
"""Return a dict of term synonyms"""
syns = {}
for k, v in self._declared_terms.items():
k = k.strip()
if v.get('synonym'):
syns[k.lower()] = v['synonym']
if not '.' in k:
syns[ROOT_TERM + '.' + k.lower()] = v['synonym']
return syns | python | def synonyms(self):
"""Return a dict of term synonyms"""
syns = {}
for k, v in self._declared_terms.items():
k = k.strip()
if v.get('synonym'):
syns[k.lower()] = v['synonym']
if not '.' in k:
syns[ROOT_TERM + '.' + k.lower()] = v['synonym']
return syns | [
"def",
"synonyms",
"(",
"self",
")",
":",
"syns",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_declared_terms",
".",
"items",
"(",
")",
":",
"k",
"=",
"k",
".",
"strip",
"(",
")",
"if",
"v",
".",
"get",
"(",
"'synonym'",
")",
":"... | Return a dict of term synonyms | [
"Return",
"a",
"dict",
"of",
"term",
"synonyms"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/parser.py#L107-L119 | train | 53,756 |
Metatab/metatab | metatab/parser.py | TermParser.super_terms | def super_terms(self):
"""Return a dictionary mapping term names to their super terms"""
# If the doc already has super terms, we've already parsed something, so
# assume we parsed the declaration, and can use re-use the old decls.
if self.doc and self.doc.super_terms:
return self.doc.super_terms
return {k.lower(): v['inheritsfrom'].lower()
for k, v in self._declared_terms.items() if 'inheritsfrom' in v} | python | def super_terms(self):
"""Return a dictionary mapping term names to their super terms"""
# If the doc already has super terms, we've already parsed something, so
# assume we parsed the declaration, and can use re-use the old decls.
if self.doc and self.doc.super_terms:
return self.doc.super_terms
return {k.lower(): v['inheritsfrom'].lower()
for k, v in self._declared_terms.items() if 'inheritsfrom' in v} | [
"def",
"super_terms",
"(",
"self",
")",
":",
"# If the doc already has super terms, we've already parsed something, so",
"# assume we parsed the declaration, and can use re-use the old decls.",
"if",
"self",
".",
"doc",
"and",
"self",
".",
"doc",
".",
"super_terms",
":",
"retur... | Return a dictionary mapping term names to their super terms | [
"Return",
"a",
"dictionary",
"mapping",
"term",
"names",
"to",
"their",
"super",
"terms"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/parser.py#L123-L133 | train | 53,757 |
Metatab/metatab | metatab/parser.py | TermParser.declare_dict | def declare_dict(self):
"""Return declared sections, terms and synonyms as a dict"""
# Run the parser, if it has not been run yet.
if not self.root:
for _ in self: pass
return {
'sections': self._declared_sections,
'terms': self._declared_terms,
'synonyms': self.synonyms
} | python | def declare_dict(self):
"""Return declared sections, terms and synonyms as a dict"""
# Run the parser, if it has not been run yet.
if not self.root:
for _ in self: pass
return {
'sections': self._declared_sections,
'terms': self._declared_terms,
'synonyms': self.synonyms
} | [
"def",
"declare_dict",
"(",
"self",
")",
":",
"# Run the parser, if it has not been run yet.",
"if",
"not",
"self",
".",
"root",
":",
"for",
"_",
"in",
"self",
":",
"pass",
"return",
"{",
"'sections'",
":",
"self",
".",
"_declared_sections",
",",
"'terms'",
":... | Return declared sections, terms and synonyms as a dict | [
"Return",
"declared",
"sections",
"terms",
"and",
"synonyms",
"as",
"a",
"dict"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/parser.py#L136-L146 | train | 53,758 |
Metatab/metatab | metatab/parser.py | TermParser.errors_as_dict | def errors_as_dict(self):
"""Return parse errors as a dict"""
errors = []
for e in self.errors:
errors.append({
'file': e.term.file_name,
'row': e.term.row if e.term else '<unknown>',
'col': e.term.col if e.term else '<unknown>',
'term': e.term.join if e.term else '<unknown>',
'error': str(e)
})
return errors | python | def errors_as_dict(self):
"""Return parse errors as a dict"""
errors = []
for e in self.errors:
errors.append({
'file': e.term.file_name,
'row': e.term.row if e.term else '<unknown>',
'col': e.term.col if e.term else '<unknown>',
'term': e.term.join if e.term else '<unknown>',
'error': str(e)
})
return errors | [
"def",
"errors_as_dict",
"(",
"self",
")",
":",
"errors",
"=",
"[",
"]",
"for",
"e",
"in",
"self",
".",
"errors",
":",
"errors",
".",
"append",
"(",
"{",
"'file'",
":",
"e",
".",
"term",
".",
"file_name",
",",
"'row'",
":",
"e",
".",
"term",
".",... | Return parse errors as a dict | [
"Return",
"parse",
"errors",
"as",
"a",
"dict"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/parser.py#L220-L234 | train | 53,759 |
Metatab/metatab | metatab/parser.py | TermParser.inherited_children | def inherited_children(self, t):
"""Generate inherited children based on a terms InhertsFrom property.
The input term must have both an InheritsFrom property and a defined Section
:param t: A subclassed terms -- has an InheritsFrom value
"""
if not t.get('inheritsfrom'):
return
if not 'section' in t:
raise DeclarationError("DeclareTerm for '{}' must specify a section to use InheritsFrom"
.format(t['term']))
t_p, t_r = Term.split_term(t['term'])
ih_p, ih_r = Term.split_term(t['inheritsfrom'])
# The inherited terms must come from the same section
section_terms = self._declared_sections[t['section'].lower()]['terms']
# For each of the terms in the section, look for terms that are children
# of the term that the input term inherits from. Then yield each of those terms
# after chang the term name to be a child of the input term.
for st_name in section_terms:
if st_name.lower().startswith(ih_r.lower() + '.'):
st_p, st_r = Term.split_term(st_name)
# Yield the term, but replace the parent part
subtype_name = t_r + '.' + st_r
subtype_d = dict(self._declared_terms[st_name.lower()].items())
subtype_d['inheritsfrom'] = '';
subtype_d['term'] = subtype_name
yield subtype_d | python | def inherited_children(self, t):
"""Generate inherited children based on a terms InhertsFrom property.
The input term must have both an InheritsFrom property and a defined Section
:param t: A subclassed terms -- has an InheritsFrom value
"""
if not t.get('inheritsfrom'):
return
if not 'section' in t:
raise DeclarationError("DeclareTerm for '{}' must specify a section to use InheritsFrom"
.format(t['term']))
t_p, t_r = Term.split_term(t['term'])
ih_p, ih_r = Term.split_term(t['inheritsfrom'])
# The inherited terms must come from the same section
section_terms = self._declared_sections[t['section'].lower()]['terms']
# For each of the terms in the section, look for terms that are children
# of the term that the input term inherits from. Then yield each of those terms
# after chang the term name to be a child of the input term.
for st_name in section_terms:
if st_name.lower().startswith(ih_r.lower() + '.'):
st_p, st_r = Term.split_term(st_name)
# Yield the term, but replace the parent part
subtype_name = t_r + '.' + st_r
subtype_d = dict(self._declared_terms[st_name.lower()].items())
subtype_d['inheritsfrom'] = '';
subtype_d['term'] = subtype_name
yield subtype_d | [
"def",
"inherited_children",
"(",
"self",
",",
"t",
")",
":",
"if",
"not",
"t",
".",
"get",
"(",
"'inheritsfrom'",
")",
":",
"return",
"if",
"not",
"'section'",
"in",
"t",
":",
"raise",
"DeclarationError",
"(",
"\"DeclareTerm for '{}' must specify a section to u... | Generate inherited children based on a terms InhertsFrom property.
The input term must have both an InheritsFrom property and a defined Section
:param t: A subclassed terms -- has an InheritsFrom value | [
"Generate",
"inherited",
"children",
"based",
"on",
"a",
"terms",
"InhertsFrom",
"property",
".",
"The",
"input",
"term",
"must",
"have",
"both",
"an",
"InheritsFrom",
"property",
"and",
"a",
"defined",
"Section"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/parser.py#L548-L581 | train | 53,760 |
Capitains/Nautilus | capitains_nautilus/manager.py | read_levels | def read_levels(text):
""" Read text and get there reffs
:param text: Collection (Readable)
:return:
"""
x = []
for i in range(0, len(NAUTILUSRESOLVER.getMetadata(text).citation)):
x.append(NAUTILUSRESOLVER.getReffs(text, level=i))
return x | python | def read_levels(text):
""" Read text and get there reffs
:param text: Collection (Readable)
:return:
"""
x = []
for i in range(0, len(NAUTILUSRESOLVER.getMetadata(text).citation)):
x.append(NAUTILUSRESOLVER.getReffs(text, level=i))
return x | [
"def",
"read_levels",
"(",
"text",
")",
":",
"x",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"NAUTILUSRESOLVER",
".",
"getMetadata",
"(",
"text",
")",
".",
"citation",
")",
")",
":",
"x",
".",
"append",
"(",
"NAUTILUSRESOL... | Read text and get there reffs
:param text: Collection (Readable)
:return: | [
"Read",
"text",
"and",
"get",
"there",
"reffs"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/manager.py#L15-L24 | train | 53,761 |
Capitains/Nautilus | capitains_nautilus/manager.py | FlaskNautilusManager | def FlaskNautilusManager(resolver, flask_nautilus):
""" Provides a manager for flask scripts to perform specific maintenance operations
:param resolver: Nautilus Extension Instance
:type resolver: NautilusCtsResolver
:param flask_nautilus: Flask Application
:type flask_nautilus: FlaskNautilus
:return: CLI
:rtype: click.group
Import with
.. code-block:: python
:lineno:
from capitains_nautilus.manager import FlaskNautilusManager
manager = FlaskNautilusManager(resolver, flask_nautilus, app) # Where app is the name of your app
if __name__ == "__main__":
manager()
"""
global NAUTILUSRESOLVER
NAUTILUSRESOLVER = resolver
@click.group()
@click.option('--verbose', default=False)
def CLI(verbose):
""" CLI for Flask Nautilus """
click.echo("Command Line Interface of Flask")
resolver.logger.disabled = not verbose
@CLI.command()
def flush_resolver():
""" Flush the resolver cache system """
if resolver.clear() is True:
click.echo("Caching of Resolver Cleared")
@CLI.command()
def flush_http_cache():
""" Flush the http cache
Warning : Might flush other Flask Caching data !
"""
flask_nautilus.flaskcache.clear()
@CLI.command()
def flush_both():
""" Flush all caches
"""
if resolver.cache.clear() is True:
click.echo("Caching of Resolver Cleared")
if flask_nautilus.flaskcache.clear() is True:
click.echo("Caching of HTTP Cleared")
@CLI.command()
def parse():
""" Preprocess the inventory and cache it """
ret = resolver.parse()
click.echo("Preprocessed %s texts" % len(ret.readableDescendants))
@CLI.command()
@click.option('--threads', default=0, type=int)
def process_reffs(threads):
""" Preprocess the inventory and cache it """
if threads < 1:
threads = THREADS
texts = list(resolver.getMetadata().readableDescendants)
click.echo("Using {} processes to parse references of {} texts".format(threads, len(texts)))
with Pool(processes=threads) as executor:
for future in executor.imap_unordered(read_levels, [t.id for t in texts]):
del future
click.echo("References parsed")
return CLI | python | def FlaskNautilusManager(resolver, flask_nautilus):
""" Provides a manager for flask scripts to perform specific maintenance operations
:param resolver: Nautilus Extension Instance
:type resolver: NautilusCtsResolver
:param flask_nautilus: Flask Application
:type flask_nautilus: FlaskNautilus
:return: CLI
:rtype: click.group
Import with
.. code-block:: python
:lineno:
from capitains_nautilus.manager import FlaskNautilusManager
manager = FlaskNautilusManager(resolver, flask_nautilus, app) # Where app is the name of your app
if __name__ == "__main__":
manager()
"""
global NAUTILUSRESOLVER
NAUTILUSRESOLVER = resolver
@click.group()
@click.option('--verbose', default=False)
def CLI(verbose):
""" CLI for Flask Nautilus """
click.echo("Command Line Interface of Flask")
resolver.logger.disabled = not verbose
@CLI.command()
def flush_resolver():
""" Flush the resolver cache system """
if resolver.clear() is True:
click.echo("Caching of Resolver Cleared")
@CLI.command()
def flush_http_cache():
""" Flush the http cache
Warning : Might flush other Flask Caching data !
"""
flask_nautilus.flaskcache.clear()
@CLI.command()
def flush_both():
""" Flush all caches
"""
if resolver.cache.clear() is True:
click.echo("Caching of Resolver Cleared")
if flask_nautilus.flaskcache.clear() is True:
click.echo("Caching of HTTP Cleared")
@CLI.command()
def parse():
""" Preprocess the inventory and cache it """
ret = resolver.parse()
click.echo("Preprocessed %s texts" % len(ret.readableDescendants))
@CLI.command()
@click.option('--threads', default=0, type=int)
def process_reffs(threads):
""" Preprocess the inventory and cache it """
if threads < 1:
threads = THREADS
texts = list(resolver.getMetadata().readableDescendants)
click.echo("Using {} processes to parse references of {} texts".format(threads, len(texts)))
with Pool(processes=threads) as executor:
for future in executor.imap_unordered(read_levels, [t.id for t in texts]):
del future
click.echo("References parsed")
return CLI | [
"def",
"FlaskNautilusManager",
"(",
"resolver",
",",
"flask_nautilus",
")",
":",
"global",
"NAUTILUSRESOLVER",
"NAUTILUSRESOLVER",
"=",
"resolver",
"@",
"click",
".",
"group",
"(",
")",
"@",
"click",
".",
"option",
"(",
"'--verbose'",
",",
"default",
"=",
"Fal... | Provides a manager for flask scripts to perform specific maintenance operations
:param resolver: Nautilus Extension Instance
:type resolver: NautilusCtsResolver
:param flask_nautilus: Flask Application
:type flask_nautilus: FlaskNautilus
:return: CLI
:rtype: click.group
Import with
.. code-block:: python
:lineno:
from capitains_nautilus.manager import FlaskNautilusManager
manager = FlaskNautilusManager(resolver, flask_nautilus, app) # Where app is the name of your app
if __name__ == "__main__":
manager() | [
"Provides",
"a",
"manager",
"for",
"flask",
"scripts",
"to",
"perform",
"specific",
"maintenance",
"operations"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/manager.py#L27-L102 | train | 53,762 |
chrisjsewell/jsonextended | jsonextended/edict.py | is_iter_non_string | def is_iter_non_string(obj):
"""test if object is a list or tuple"""
if isinstance(obj, list) or isinstance(obj, tuple):
return True
return False | python | def is_iter_non_string(obj):
"""test if object is a list or tuple"""
if isinstance(obj, list) or isinstance(obj, tuple):
return True
return False | [
"def",
"is_iter_non_string",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"list",
")",
"or",
"isinstance",
"(",
"obj",
",",
"tuple",
")",
":",
"return",
"True",
"return",
"False"
] | test if object is a list or tuple | [
"test",
"if",
"object",
"is",
"a",
"list",
"or",
"tuple"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L45-L49 | train | 53,763 |
chrisjsewell/jsonextended | jsonextended/edict.py | is_dict_like | def is_dict_like(obj, attr=('keys', 'items')):
"""test if object is dict like"""
for a in attr:
if not hasattr(obj, a):
return False
return True | python | def is_dict_like(obj, attr=('keys', 'items')):
"""test if object is dict like"""
for a in attr:
if not hasattr(obj, a):
return False
return True | [
"def",
"is_dict_like",
"(",
"obj",
",",
"attr",
"=",
"(",
"'keys'",
",",
"'items'",
")",
")",
":",
"for",
"a",
"in",
"attr",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"a",
")",
":",
"return",
"False",
"return",
"True"
] | test if object is dict like | [
"test",
"if",
"object",
"is",
"dict",
"like"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L58-L63 | train | 53,764 |
chrisjsewell/jsonextended | jsonextended/edict.py | is_list_of_dict_like | def is_list_of_dict_like(obj, attr=('keys', 'items')):
"""test if object is a list only containing dict like items """
try:
if len(obj) == 0:
return False
return all([is_dict_like(i, attr) for i in obj])
except Exception:
return False | python | def is_list_of_dict_like(obj, attr=('keys', 'items')):
"""test if object is a list only containing dict like items """
try:
if len(obj) == 0:
return False
return all([is_dict_like(i, attr) for i in obj])
except Exception:
return False | [
"def",
"is_list_of_dict_like",
"(",
"obj",
",",
"attr",
"=",
"(",
"'keys'",
",",
"'items'",
")",
")",
":",
"try",
":",
"if",
"len",
"(",
"obj",
")",
"==",
"0",
":",
"return",
"False",
"return",
"all",
"(",
"[",
"is_dict_like",
"(",
"i",
",",
"attr"... | test if object is a list only containing dict like items | [
"test",
"if",
"object",
"is",
"a",
"list",
"only",
"containing",
"dict",
"like",
"items"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L66-L73 | train | 53,765 |
chrisjsewell/jsonextended | jsonextended/edict.py | is_path_like | def is_path_like(obj, attr=('name', 'is_file', 'is_dir', 'iterdir')):
"""test if object is pathlib.Path like"""
for a in attr:
if not hasattr(obj, a):
return False
return True | python | def is_path_like(obj, attr=('name', 'is_file', 'is_dir', 'iterdir')):
"""test if object is pathlib.Path like"""
for a in attr:
if not hasattr(obj, a):
return False
return True | [
"def",
"is_path_like",
"(",
"obj",
",",
"attr",
"=",
"(",
"'name'",
",",
"'is_file'",
",",
"'is_dir'",
",",
"'iterdir'",
")",
")",
":",
"for",
"a",
"in",
"attr",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"a",
")",
":",
"return",
"False",
"retur... | test if object is pathlib.Path like | [
"test",
"if",
"object",
"is",
"pathlib",
".",
"Path",
"like"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L76-L81 | train | 53,766 |
chrisjsewell/jsonextended | jsonextended/edict.py | convert_type | def convert_type(d, intype, outtype, convert_list=True, in_place=True):
""" convert all values of one type to another
Parameters
----------
d : dict
intype : type_class
outtype : type_class
convert_list : bool
whether to convert instances inside lists and tuples
in_place : bool
if True, applies conversions to original dict, else returns copy
Examples
--------
>>> from pprint import pprint
>>> d = {'a':'1','b':'2'}
>>> pprint(convert_type(d,str,float))
{'a': 1.0, 'b': 2.0}
>>> d = {'a':['1','2']}
>>> pprint(convert_type(d,str,float))
{'a': [1.0, 2.0]}
>>> d = {'a':[('1','2'),[3,4]]}
>>> pprint(convert_type(d,str,float))
{'a': [(1.0, 2.0), [3, 4]]}
"""
if not in_place:
out_dict = copy.deepcopy(d)
else:
out_dict = d
def _convert(obj):
if isinstance(obj, intype):
try:
obj = outtype(obj)
except Exception:
pass
elif isinstance(obj, list) and convert_list:
obj = _traverse_iter(obj)
elif isinstance(obj, tuple) and convert_list:
obj = tuple(_traverse_iter(obj))
return obj
def _traverse_dict(dic):
for key in dic.keys():
if is_dict_like(dic[key]):
_traverse_dict(dic[key])
else:
dic[key] = _convert(dic[key])
def _traverse_iter(iter):
new_iter = []
for key in iter:
if is_dict_like(key):
_traverse_dict(key)
new_iter.append(key)
else:
new_iter.append(_convert(key))
return new_iter
if is_dict_like(out_dict):
_traverse_dict(out_dict)
else:
_convert(out_dict)
return out_dict | python | def convert_type(d, intype, outtype, convert_list=True, in_place=True):
""" convert all values of one type to another
Parameters
----------
d : dict
intype : type_class
outtype : type_class
convert_list : bool
whether to convert instances inside lists and tuples
in_place : bool
if True, applies conversions to original dict, else returns copy
Examples
--------
>>> from pprint import pprint
>>> d = {'a':'1','b':'2'}
>>> pprint(convert_type(d,str,float))
{'a': 1.0, 'b': 2.0}
>>> d = {'a':['1','2']}
>>> pprint(convert_type(d,str,float))
{'a': [1.0, 2.0]}
>>> d = {'a':[('1','2'),[3,4]]}
>>> pprint(convert_type(d,str,float))
{'a': [(1.0, 2.0), [3, 4]]}
"""
if not in_place:
out_dict = copy.deepcopy(d)
else:
out_dict = d
def _convert(obj):
if isinstance(obj, intype):
try:
obj = outtype(obj)
except Exception:
pass
elif isinstance(obj, list) and convert_list:
obj = _traverse_iter(obj)
elif isinstance(obj, tuple) and convert_list:
obj = tuple(_traverse_iter(obj))
return obj
def _traverse_dict(dic):
for key in dic.keys():
if is_dict_like(dic[key]):
_traverse_dict(dic[key])
else:
dic[key] = _convert(dic[key])
def _traverse_iter(iter):
new_iter = []
for key in iter:
if is_dict_like(key):
_traverse_dict(key)
new_iter.append(key)
else:
new_iter.append(_convert(key))
return new_iter
if is_dict_like(out_dict):
_traverse_dict(out_dict)
else:
_convert(out_dict)
return out_dict | [
"def",
"convert_type",
"(",
"d",
",",
"intype",
",",
"outtype",
",",
"convert_list",
"=",
"True",
",",
"in_place",
"=",
"True",
")",
":",
"if",
"not",
"in_place",
":",
"out_dict",
"=",
"copy",
".",
"deepcopy",
"(",
"d",
")",
"else",
":",
"out_dict",
... | convert all values of one type to another
Parameters
----------
d : dict
intype : type_class
outtype : type_class
convert_list : bool
whether to convert instances inside lists and tuples
in_place : bool
if True, applies conversions to original dict, else returns copy
Examples
--------
>>> from pprint import pprint
>>> d = {'a':'1','b':'2'}
>>> pprint(convert_type(d,str,float))
{'a': 1.0, 'b': 2.0}
>>> d = {'a':['1','2']}
>>> pprint(convert_type(d,str,float))
{'a': [1.0, 2.0]}
>>> d = {'a':[('1','2'),[3,4]]}
>>> pprint(convert_type(d,str,float))
{'a': [(1.0, 2.0), [3, 4]]} | [
"convert",
"all",
"values",
"of",
"one",
"type",
"to",
"another"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L84-L156 | train | 53,767 |
chrisjsewell/jsonextended | jsonextended/edict.py | extract | def extract(d, path=None):
""" extract section of dictionary
Parameters
----------
d : dict
path : list[str]
keys to section
Returns
-------
new_dict : dict
original, without extracted section
extract_dict : dict
extracted section
Examples
--------
>>> from pprint import pprint
>>> d = {1:{"a":"A"},2:{"b":"B",'c':'C'}}
>>> pprint(extract(d,[2,'b']))
({1: {'a': 'A'}, 2: {'c': 'C'}}, {'b': 'B'})
"""
path = [] if path is None else path
d_new = copy.deepcopy(d)
d_sub = d_new
for key in path[:-1]:
d_sub = d_sub[key]
key = path[-1]
d_extract = {key: d_sub[key]}
d_sub.pop(key)
return d_new, d_extract | python | def extract(d, path=None):
""" extract section of dictionary
Parameters
----------
d : dict
path : list[str]
keys to section
Returns
-------
new_dict : dict
original, without extracted section
extract_dict : dict
extracted section
Examples
--------
>>> from pprint import pprint
>>> d = {1:{"a":"A"},2:{"b":"B",'c':'C'}}
>>> pprint(extract(d,[2,'b']))
({1: {'a': 'A'}, 2: {'c': 'C'}}, {'b': 'B'})
"""
path = [] if path is None else path
d_new = copy.deepcopy(d)
d_sub = d_new
for key in path[:-1]:
d_sub = d_sub[key]
key = path[-1]
d_extract = {key: d_sub[key]}
d_sub.pop(key)
return d_new, d_extract | [
"def",
"extract",
"(",
"d",
",",
"path",
"=",
"None",
")",
":",
"path",
"=",
"[",
"]",
"if",
"path",
"is",
"None",
"else",
"path",
"d_new",
"=",
"copy",
".",
"deepcopy",
"(",
"d",
")",
"d_sub",
"=",
"d_new",
"for",
"key",
"in",
"path",
"[",
":"... | extract section of dictionary
Parameters
----------
d : dict
path : list[str]
keys to section
Returns
-------
new_dict : dict
original, without extracted section
extract_dict : dict
extracted section
Examples
--------
>>> from pprint import pprint
>>> d = {1:{"a":"A"},2:{"b":"B",'c':'C'}}
>>> pprint(extract(d,[2,'b']))
({1: {'a': 'A'}, 2: {'c': 'C'}}, {'b': 'B'}) | [
"extract",
"section",
"of",
"dictionary"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L367-L403 | train | 53,768 |
chrisjsewell/jsonextended | jsonextended/edict.py | indexes | def indexes(dic, keys=None):
""" index dictionary by multiple keys
Parameters
----------
dic : dict
keys : list
Examples
--------
>>> d = {1:{"a":"A"},2:{"b":"B"}}
>>> indexes(d,[1,'a'])
'A'
"""
keys = [] if keys is None else keys
assert hasattr(dic, 'keys')
new = dic.copy()
old_key = None
for key in keys:
if not hasattr(new, 'keys'):
raise KeyError('No indexes after: {}'.format(old_key))
old_key = key
new = new[key]
return new | python | def indexes(dic, keys=None):
""" index dictionary by multiple keys
Parameters
----------
dic : dict
keys : list
Examples
--------
>>> d = {1:{"a":"A"},2:{"b":"B"}}
>>> indexes(d,[1,'a'])
'A'
"""
keys = [] if keys is None else keys
assert hasattr(dic, 'keys')
new = dic.copy()
old_key = None
for key in keys:
if not hasattr(new, 'keys'):
raise KeyError('No indexes after: {}'.format(old_key))
old_key = key
new = new[key]
return new | [
"def",
"indexes",
"(",
"dic",
",",
"keys",
"=",
"None",
")",
":",
"keys",
"=",
"[",
"]",
"if",
"keys",
"is",
"None",
"else",
"keys",
"assert",
"hasattr",
"(",
"dic",
",",
"'keys'",
")",
"new",
"=",
"dic",
".",
"copy",
"(",
")",
"old_key",
"=",
... | index dictionary by multiple keys
Parameters
----------
dic : dict
keys : list
Examples
--------
>>> d = {1:{"a":"A"},2:{"b":"B"}}
>>> indexes(d,[1,'a'])
'A' | [
"index",
"dictionary",
"by",
"multiple",
"keys"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L406-L432 | train | 53,769 |
chrisjsewell/jsonextended | jsonextended/edict.py | unflatten | def unflatten(d, key_as_tuple=True, delim='.',
list_of_dicts=None, deepcopy=True):
r""" unflatten dictionary with keys as tuples or delimited strings
Parameters
----------
d : dict
key_as_tuple : bool
if true, keys are tuples, else, keys are delimited strings
delim : str
if keys are strings, then split by delim
list_of_dicts: str or None
if key starts with this treat as a list
Examples
--------
>>> from pprint import pprint
>>> d = {('a','b'):1,('a','c'):2}
>>> pprint(unflatten(d))
{'a': {'b': 1, 'c': 2}}
>>> d2 = {'a.b':1,'a.c':2}
>>> pprint(unflatten(d2,key_as_tuple=False))
{'a': {'b': 1, 'c': 2}}
>>> d3 = {('a','__list__1', 'a'): 1, ('a','__list__0', 'b'): 2}
>>> pprint(unflatten(d3,list_of_dicts='__list__'))
{'a': [{'b': 2}, {'a': 1}]}
>>> unflatten({('a','b','c'):1,('a','b'):2})
Traceback (most recent call last):
...
KeyError: "child conflict for path: ('a', 'b'); 2 and {'c': 1}"
"""
if not d:
return d
if deepcopy:
try:
d = copy.deepcopy(d)
except Exception:
warnings.warn(
'error in deepcopy, so using references to input dict')
if key_as_tuple:
result = d.pop(()) if () in d else {}
else:
result = d.pop('') if '' in d else {}
for key, value in d.items():
if not isinstance(key, tuple) and key_as_tuple:
raise ValueError(
'key not tuple and key_as_tuple set to True: {}'.format(key))
elif not isinstance(key, basestring) and not key_as_tuple:
raise ValueError(
'key not string and key_as_tuple set to False: {}'.format(key))
elif isinstance(key, basestring) and not key_as_tuple:
parts = key.split(delim)
else:
parts = key
d = result
for part in parts[:-1]:
if part not in d:
d[part] = {}
d = d[part]
if not is_dict_like(d):
v1, v2 = sorted([str(d), str({parts[-1]: value})])
raise KeyError("child conflict for path: "
"{0}; {1} and {2}".format(parts[:-1], v1, v2))
elif parts[-1] in d:
try:
value = merge([d[parts[-1]], value])
except Exception:
v1, v2 = sorted([str(value), str(d[parts[-1]])])
raise KeyError("child conflict for path: "
"{0}; {1} and {2}".format(parts, v1, v2))
d[parts[-1]] = value
if list_of_dicts is not None:
result = _recreate_lists(result, list_of_dicts)
# if is_dict_like(result):
# if all([str(k).startswith(list_of_dicts) for k in result.keys()]):
# result = [result[k] for k in sorted(list(result.keys()),
# key=lambda x: int(x.replace(list_of_dicts, '')))]
return result | python | def unflatten(d, key_as_tuple=True, delim='.',
list_of_dicts=None, deepcopy=True):
r""" unflatten dictionary with keys as tuples or delimited strings
Parameters
----------
d : dict
key_as_tuple : bool
if true, keys are tuples, else, keys are delimited strings
delim : str
if keys are strings, then split by delim
list_of_dicts: str or None
if key starts with this treat as a list
Examples
--------
>>> from pprint import pprint
>>> d = {('a','b'):1,('a','c'):2}
>>> pprint(unflatten(d))
{'a': {'b': 1, 'c': 2}}
>>> d2 = {'a.b':1,'a.c':2}
>>> pprint(unflatten(d2,key_as_tuple=False))
{'a': {'b': 1, 'c': 2}}
>>> d3 = {('a','__list__1', 'a'): 1, ('a','__list__0', 'b'): 2}
>>> pprint(unflatten(d3,list_of_dicts='__list__'))
{'a': [{'b': 2}, {'a': 1}]}
>>> unflatten({('a','b','c'):1,('a','b'):2})
Traceback (most recent call last):
...
KeyError: "child conflict for path: ('a', 'b'); 2 and {'c': 1}"
"""
if not d:
return d
if deepcopy:
try:
d = copy.deepcopy(d)
except Exception:
warnings.warn(
'error in deepcopy, so using references to input dict')
if key_as_tuple:
result = d.pop(()) if () in d else {}
else:
result = d.pop('') if '' in d else {}
for key, value in d.items():
if not isinstance(key, tuple) and key_as_tuple:
raise ValueError(
'key not tuple and key_as_tuple set to True: {}'.format(key))
elif not isinstance(key, basestring) and not key_as_tuple:
raise ValueError(
'key not string and key_as_tuple set to False: {}'.format(key))
elif isinstance(key, basestring) and not key_as_tuple:
parts = key.split(delim)
else:
parts = key
d = result
for part in parts[:-1]:
if part not in d:
d[part] = {}
d = d[part]
if not is_dict_like(d):
v1, v2 = sorted([str(d), str({parts[-1]: value})])
raise KeyError("child conflict for path: "
"{0}; {1} and {2}".format(parts[:-1], v1, v2))
elif parts[-1] in d:
try:
value = merge([d[parts[-1]], value])
except Exception:
v1, v2 = sorted([str(value), str(d[parts[-1]])])
raise KeyError("child conflict for path: "
"{0}; {1} and {2}".format(parts, v1, v2))
d[parts[-1]] = value
if list_of_dicts is not None:
result = _recreate_lists(result, list_of_dicts)
# if is_dict_like(result):
# if all([str(k).startswith(list_of_dicts) for k in result.keys()]):
# result = [result[k] for k in sorted(list(result.keys()),
# key=lambda x: int(x.replace(list_of_dicts, '')))]
return result | [
"def",
"unflatten",
"(",
"d",
",",
"key_as_tuple",
"=",
"True",
",",
"delim",
"=",
"'.'",
",",
"list_of_dicts",
"=",
"None",
",",
"deepcopy",
"=",
"True",
")",
":",
"if",
"not",
"d",
":",
"return",
"d",
"if",
"deepcopy",
":",
"try",
":",
"d",
"=",
... | r""" unflatten dictionary with keys as tuples or delimited strings
Parameters
----------
d : dict
key_as_tuple : bool
if true, keys are tuples, else, keys are delimited strings
delim : str
if keys are strings, then split by delim
list_of_dicts: str or None
if key starts with this treat as a list
Examples
--------
>>> from pprint import pprint
>>> d = {('a','b'):1,('a','c'):2}
>>> pprint(unflatten(d))
{'a': {'b': 1, 'c': 2}}
>>> d2 = {'a.b':1,'a.c':2}
>>> pprint(unflatten(d2,key_as_tuple=False))
{'a': {'b': 1, 'c': 2}}
>>> d3 = {('a','__list__1', 'a'): 1, ('a','__list__0', 'b'): 2}
>>> pprint(unflatten(d3,list_of_dicts='__list__'))
{'a': [{'b': 2}, {'a': 1}]}
>>> unflatten({('a','b','c'):1,('a','b'):2})
Traceback (most recent call last):
...
KeyError: "child conflict for path: ('a', 'b'); 2 and {'c': 1}" | [
"r",
"unflatten",
"dictionary",
"with",
"keys",
"as",
"tuples",
"or",
"delimited",
"strings"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L543-L634 | train | 53,770 |
chrisjsewell/jsonextended | jsonextended/edict.py | remove_keys | def remove_keys(d, keys=None, use_wildcards=True,
list_of_dicts=False, deepcopy=True):
"""remove certain keys from nested dict, retaining preceeding paths
Parameters
----------
keys: list
use_wildcards : bool
if true, can use * (matches everything)
and ? (matches any single character)
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
Examples
--------
>>> from pprint import pprint
>>> d = {1:{"a":"A"},"a":{"b":"B"}}
>>> pprint(remove_keys(d,['a']))
{1: 'A', 'b': 'B'}
>>> pprint(remove_keys({'abc':1},['a*'],use_wildcards=False))
{'abc': 1}
>>> pprint(remove_keys({'abc':1},['a*'],use_wildcards=True))
{}
"""
keys = [] if keys is None else keys
list_of_dicts = '__list__' if list_of_dicts else None
def is_in(a, bs):
if use_wildcards:
for b in bs:
try:
if a == b:
return True
if fnmatch(a, b):
return True
except Exception:
pass
return False
else:
try:
return a in bs
except Exception:
return False
if not hasattr(d, 'items'):
return d
else:
dic = flatten(d, list_of_dicts=list_of_dicts)
new_dic = {}
for key, value in dic.items():
new_key = tuple([i for i in key if not is_in(i, keys)])
if not new_key:
continue
try:
if new_key[-1].startswith(list_of_dicts):
continue
except Exception:
pass
new_dic[new_key] = value
return unflatten(
new_dic, list_of_dicts=list_of_dicts, deepcopy=deepcopy) | python | def remove_keys(d, keys=None, use_wildcards=True,
list_of_dicts=False, deepcopy=True):
"""remove certain keys from nested dict, retaining preceeding paths
Parameters
----------
keys: list
use_wildcards : bool
if true, can use * (matches everything)
and ? (matches any single character)
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
Examples
--------
>>> from pprint import pprint
>>> d = {1:{"a":"A"},"a":{"b":"B"}}
>>> pprint(remove_keys(d,['a']))
{1: 'A', 'b': 'B'}
>>> pprint(remove_keys({'abc':1},['a*'],use_wildcards=False))
{'abc': 1}
>>> pprint(remove_keys({'abc':1},['a*'],use_wildcards=True))
{}
"""
keys = [] if keys is None else keys
list_of_dicts = '__list__' if list_of_dicts else None
def is_in(a, bs):
if use_wildcards:
for b in bs:
try:
if a == b:
return True
if fnmatch(a, b):
return True
except Exception:
pass
return False
else:
try:
return a in bs
except Exception:
return False
if not hasattr(d, 'items'):
return d
else:
dic = flatten(d, list_of_dicts=list_of_dicts)
new_dic = {}
for key, value in dic.items():
new_key = tuple([i for i in key if not is_in(i, keys)])
if not new_key:
continue
try:
if new_key[-1].startswith(list_of_dicts):
continue
except Exception:
pass
new_dic[new_key] = value
return unflatten(
new_dic, list_of_dicts=list_of_dicts, deepcopy=deepcopy) | [
"def",
"remove_keys",
"(",
"d",
",",
"keys",
"=",
"None",
",",
"use_wildcards",
"=",
"True",
",",
"list_of_dicts",
"=",
"False",
",",
"deepcopy",
"=",
"True",
")",
":",
"keys",
"=",
"[",
"]",
"if",
"keys",
"is",
"None",
"else",
"keys",
"list_of_dicts",... | remove certain keys from nested dict, retaining preceeding paths
Parameters
----------
keys: list
use_wildcards : bool
if true, can use * (matches everything)
and ? (matches any single character)
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
Examples
--------
>>> from pprint import pprint
>>> d = {1:{"a":"A"},"a":{"b":"B"}}
>>> pprint(remove_keys(d,['a']))
{1: 'A', 'b': 'B'}
>>> pprint(remove_keys({'abc':1},['a*'],use_wildcards=False))
{'abc': 1}
>>> pprint(remove_keys({'abc':1},['a*'],use_wildcards=True))
{} | [
"remove",
"certain",
"keys",
"from",
"nested",
"dict",
"retaining",
"preceeding",
"paths"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L874-L938 | train | 53,771 |
chrisjsewell/jsonextended | jsonextended/edict.py | remove_paths | def remove_paths(d, keys, list_of_dicts=False, deepcopy=True):
""" remove paths containing certain keys from dict
Parameters
----------
d: dict
keys : list
list of keys to find and remove path
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {1:{"a":"A"},2:{"b":"B"},4:{5:{6:'a',7:'b'}}}
>>> pprint(remove_paths(d,[6,'a']))
{2: {'b': 'B'}, 4: {5: {7: 'b'}}}
>>> d = {1:{2: 3}, 1:{4: 5}}
>>> pprint(remove_paths(d,[(1, 2)]))
{1: {4: 5}}
>>> d2 = {'a':[{'b':1,'c':{'b':3}},{'b':1,'c':2}]}
>>> pprint(remove_paths(d2,["b"],list_of_dicts=False))
{'a': [{'b': 1, 'c': {'b': 3}}, {'b': 1, 'c': 2}]}
>>> pprint(remove_paths(d2,["b"],list_of_dicts=True))
{'a': [{'c': 2}]}
"""
keys = [(key,) if not isinstance(key, tuple) else key for key in keys]
list_of_dicts = '__list__' if list_of_dicts else None
def contains(path):
for k in keys:
if set(k).issubset(path):
return True
return False
flatd = flatten(d, list_of_dicts=list_of_dicts)
flatd = {path: v for path, v in flatd.items() if not contains(path)}
return unflatten(flatd, list_of_dicts=list_of_dicts, deepcopy=deepcopy) | python | def remove_paths(d, keys, list_of_dicts=False, deepcopy=True):
""" remove paths containing certain keys from dict
Parameters
----------
d: dict
keys : list
list of keys to find and remove path
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {1:{"a":"A"},2:{"b":"B"},4:{5:{6:'a',7:'b'}}}
>>> pprint(remove_paths(d,[6,'a']))
{2: {'b': 'B'}, 4: {5: {7: 'b'}}}
>>> d = {1:{2: 3}, 1:{4: 5}}
>>> pprint(remove_paths(d,[(1, 2)]))
{1: {4: 5}}
>>> d2 = {'a':[{'b':1,'c':{'b':3}},{'b':1,'c':2}]}
>>> pprint(remove_paths(d2,["b"],list_of_dicts=False))
{'a': [{'b': 1, 'c': {'b': 3}}, {'b': 1, 'c': 2}]}
>>> pprint(remove_paths(d2,["b"],list_of_dicts=True))
{'a': [{'c': 2}]}
"""
keys = [(key,) if not isinstance(key, tuple) else key for key in keys]
list_of_dicts = '__list__' if list_of_dicts else None
def contains(path):
for k in keys:
if set(k).issubset(path):
return True
return False
flatd = flatten(d, list_of_dicts=list_of_dicts)
flatd = {path: v for path, v in flatd.items() if not contains(path)}
return unflatten(flatd, list_of_dicts=list_of_dicts, deepcopy=deepcopy) | [
"def",
"remove_paths",
"(",
"d",
",",
"keys",
",",
"list_of_dicts",
"=",
"False",
",",
"deepcopy",
"=",
"True",
")",
":",
"keys",
"=",
"[",
"(",
"key",
",",
")",
"if",
"not",
"isinstance",
"(",
"key",
",",
"tuple",
")",
"else",
"key",
"for",
"key",... | remove paths containing certain keys from dict
Parameters
----------
d: dict
keys : list
list of keys to find and remove path
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {1:{"a":"A"},2:{"b":"B"},4:{5:{6:'a',7:'b'}}}
>>> pprint(remove_paths(d,[6,'a']))
{2: {'b': 'B'}, 4: {5: {7: 'b'}}}
>>> d = {1:{2: 3}, 1:{4: 5}}
>>> pprint(remove_paths(d,[(1, 2)]))
{1: {4: 5}}
>>> d2 = {'a':[{'b':1,'c':{'b':3}},{'b':1,'c':2}]}
>>> pprint(remove_paths(d2,["b"],list_of_dicts=False))
{'a': [{'b': 1, 'c': {'b': 3}}, {'b': 1, 'c': 2}]}
>>> pprint(remove_paths(d2,["b"],list_of_dicts=True))
{'a': [{'c': 2}]} | [
"remove",
"paths",
"containing",
"certain",
"keys",
"from",
"dict"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L992-L1039 | train | 53,772 |
chrisjsewell/jsonextended | jsonextended/edict.py | filter_values | def filter_values(d, vals=None, list_of_dicts=False, deepcopy=True):
""" filters leaf nodes of nested dictionary
Parameters
----------
d : dict
vals : list
values to filter by
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> d = {1:{"a":"A"},2:{"b":"B"},4:{5:{6:'a'}}}
>>> filter_values(d,['a'])
{4: {5: {6: 'a'}}}
"""
vals = [] if vals is None else vals
list_of_dicts = '__list__' if list_of_dicts else None
flatd = flatten(d, list_of_dicts=list_of_dicts)
def is_in(a, b):
try:
return a in b
except Exception:
return False
flatd = {k: v for k, v in flatd.items() if is_in(v, vals)}
return unflatten(flatd, list_of_dicts=list_of_dicts, deepcopy=deepcopy) | python | def filter_values(d, vals=None, list_of_dicts=False, deepcopy=True):
""" filters leaf nodes of nested dictionary
Parameters
----------
d : dict
vals : list
values to filter by
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> d = {1:{"a":"A"},2:{"b":"B"},4:{5:{6:'a'}}}
>>> filter_values(d,['a'])
{4: {5: {6: 'a'}}}
"""
vals = [] if vals is None else vals
list_of_dicts = '__list__' if list_of_dicts else None
flatd = flatten(d, list_of_dicts=list_of_dicts)
def is_in(a, b):
try:
return a in b
except Exception:
return False
flatd = {k: v for k, v in flatd.items() if is_in(v, vals)}
return unflatten(flatd, list_of_dicts=list_of_dicts, deepcopy=deepcopy) | [
"def",
"filter_values",
"(",
"d",
",",
"vals",
"=",
"None",
",",
"list_of_dicts",
"=",
"False",
",",
"deepcopy",
"=",
"True",
")",
":",
"vals",
"=",
"[",
"]",
"if",
"vals",
"is",
"None",
"else",
"vals",
"list_of_dicts",
"=",
"'__list__'",
"if",
"list_o... | filters leaf nodes of nested dictionary
Parameters
----------
d : dict
vals : list
values to filter by
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> d = {1:{"a":"A"},2:{"b":"B"},4:{5:{6:'a'}}}
>>> filter_values(d,['a'])
{4: {5: {6: 'a'}}} | [
"filters",
"leaf",
"nodes",
"of",
"nested",
"dictionary"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1044-L1077 | train | 53,773 |
chrisjsewell/jsonextended | jsonextended/edict.py | filter_keys | def filter_keys(d, keys, use_wildcards=False,
list_of_dicts=False, deepcopy=True):
""" filter dict by certain keys
Parameters
----------
d : dict
keys: list
use_wildcards : bool
if true, can use * (matches everything)
and ? (matches any single character)
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {1:{"a":"A"},2:{"b":"B"},4:{5:{6:'a',7:'b'}}}
>>> pprint(filter_keys(d,['a',6]))
{1: {'a': 'A'}, 4: {5: {6: 'a'}}}
>>> d = {1:{"axxxx":"A"},2:{"b":"B"}}
>>> pprint(filter_keys(d,['a*'],use_wildcards=True))
{1: {'axxxx': 'A'}}
"""
list_of_dicts = '__list__' if list_of_dicts else None
flatd = flatten(d, list_of_dicts=list_of_dicts)
def is_in(a, bs):
if use_wildcards:
for b in bs:
try:
if a == b:
return True
if fnmatch(b, a):
return True
except Exception:
pass
return False
else:
try:
return a in bs
except Exception:
return False
flatd = {paths: v for paths, v in flatd.items() if any(
[is_in(k, paths) for k in keys])}
return unflatten(flatd, list_of_dicts=list_of_dicts, deepcopy=deepcopy) | python | def filter_keys(d, keys, use_wildcards=False,
list_of_dicts=False, deepcopy=True):
""" filter dict by certain keys
Parameters
----------
d : dict
keys: list
use_wildcards : bool
if true, can use * (matches everything)
and ? (matches any single character)
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {1:{"a":"A"},2:{"b":"B"},4:{5:{6:'a',7:'b'}}}
>>> pprint(filter_keys(d,['a',6]))
{1: {'a': 'A'}, 4: {5: {6: 'a'}}}
>>> d = {1:{"axxxx":"A"},2:{"b":"B"}}
>>> pprint(filter_keys(d,['a*'],use_wildcards=True))
{1: {'axxxx': 'A'}}
"""
list_of_dicts = '__list__' if list_of_dicts else None
flatd = flatten(d, list_of_dicts=list_of_dicts)
def is_in(a, bs):
if use_wildcards:
for b in bs:
try:
if a == b:
return True
if fnmatch(b, a):
return True
except Exception:
pass
return False
else:
try:
return a in bs
except Exception:
return False
flatd = {paths: v for paths, v in flatd.items() if any(
[is_in(k, paths) for k in keys])}
return unflatten(flatd, list_of_dicts=list_of_dicts, deepcopy=deepcopy) | [
"def",
"filter_keys",
"(",
"d",
",",
"keys",
",",
"use_wildcards",
"=",
"False",
",",
"list_of_dicts",
"=",
"False",
",",
"deepcopy",
"=",
"True",
")",
":",
"list_of_dicts",
"=",
"'__list__'",
"if",
"list_of_dicts",
"else",
"None",
"flatd",
"=",
"flatten",
... | filter dict by certain keys
Parameters
----------
d : dict
keys: list
use_wildcards : bool
if true, can use * (matches everything)
and ? (matches any single character)
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {1:{"a":"A"},2:{"b":"B"},4:{5:{6:'a',7:'b'}}}
>>> pprint(filter_keys(d,['a',6]))
{1: {'a': 'A'}, 4: {5: {6: 'a'}}}
>>> d = {1:{"axxxx":"A"},2:{"b":"B"}}
>>> pprint(filter_keys(d,['a*'],use_wildcards=True))
{1: {'axxxx': 'A'}} | [
"filter",
"dict",
"by",
"certain",
"keys"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1264-L1316 | train | 53,774 |
chrisjsewell/jsonextended | jsonextended/edict.py | filter_paths | def filter_paths(d, paths, list_of_dicts=False, deepcopy=True):
""" filter dict by certain paths containing key sets
Parameters
----------
d : dict
paths : list[str] or list[tuple]
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {'a':{'b':1,'c':{'d':2}},'e':{'c':3}}
>>> filter_paths(d,[('c','d')])
{'a': {'c': {'d': 2}}}
>>> d2 = {'a':[{'b':1,'c':3},{'b':1,'c':2}]}
>>> pprint(filter_paths(d2,["b"],list_of_dicts=False))
{}
>>> pprint(filter_paths(d2,["c"],list_of_dicts=True))
{'a': [{'c': 3}, {'c': 2}]}
"""
list_of_dicts = '__list__' if list_of_dicts else None
all_keys = [x for y in paths if isinstance(y, tuple) for x in y]
all_keys += [x for x in paths if not isinstance(x, tuple)]
# faster to filter first I think
new_d = filter_keys(d, all_keys, list_of_dicts=list_of_dicts)
new_d = flatten(d, list_of_dicts=list_of_dicts)
for key in list(new_d.keys()):
if not any([
set(key).issuperset(path if isinstance(path, tuple) else[path])
for path in paths]):
new_d.pop(key)
return unflatten(new_d, list_of_dicts=list_of_dicts, deepcopy=deepcopy) | python | def filter_paths(d, paths, list_of_dicts=False, deepcopy=True):
""" filter dict by certain paths containing key sets
Parameters
----------
d : dict
paths : list[str] or list[tuple]
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {'a':{'b':1,'c':{'d':2}},'e':{'c':3}}
>>> filter_paths(d,[('c','d')])
{'a': {'c': {'d': 2}}}
>>> d2 = {'a':[{'b':1,'c':3},{'b':1,'c':2}]}
>>> pprint(filter_paths(d2,["b"],list_of_dicts=False))
{}
>>> pprint(filter_paths(d2,["c"],list_of_dicts=True))
{'a': [{'c': 3}, {'c': 2}]}
"""
list_of_dicts = '__list__' if list_of_dicts else None
all_keys = [x for y in paths if isinstance(y, tuple) for x in y]
all_keys += [x for x in paths if not isinstance(x, tuple)]
# faster to filter first I think
new_d = filter_keys(d, all_keys, list_of_dicts=list_of_dicts)
new_d = flatten(d, list_of_dicts=list_of_dicts)
for key in list(new_d.keys()):
if not any([
set(key).issuperset(path if isinstance(path, tuple) else[path])
for path in paths]):
new_d.pop(key)
return unflatten(new_d, list_of_dicts=list_of_dicts, deepcopy=deepcopy) | [
"def",
"filter_paths",
"(",
"d",
",",
"paths",
",",
"list_of_dicts",
"=",
"False",
",",
"deepcopy",
"=",
"True",
")",
":",
"list_of_dicts",
"=",
"'__list__'",
"if",
"list_of_dicts",
"else",
"None",
"all_keys",
"=",
"[",
"x",
"for",
"y",
"in",
"paths",
"i... | filter dict by certain paths containing key sets
Parameters
----------
d : dict
paths : list[str] or list[tuple]
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {'a':{'b':1,'c':{'d':2}},'e':{'c':3}}
>>> filter_paths(d,[('c','d')])
{'a': {'c': {'d': 2}}}
>>> d2 = {'a':[{'b':1,'c':3},{'b':1,'c':2}]}
>>> pprint(filter_paths(d2,["b"],list_of_dicts=False))
{}
>>> pprint(filter_paths(d2,["c"],list_of_dicts=True))
{'a': [{'c': 3}, {'c': 2}]} | [
"filter",
"dict",
"by",
"certain",
"paths",
"containing",
"key",
"sets"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1319-L1359 | train | 53,775 |
chrisjsewell/jsonextended | jsonextended/edict.py | rename_keys | def rename_keys(d, keymap=None, list_of_dicts=False, deepcopy=True):
""" rename keys in dict
Parameters
----------
d : dict
keymap : dict
dictionary of key name mappings
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {'a':{'old_name':1}}
>>> pprint(rename_keys(d,{'old_name':'new_name'}))
{'a': {'new_name': 1}}
"""
list_of_dicts = '__list__' if list_of_dicts else None
keymap = {} if keymap is None else keymap
flatd = flatten(d, list_of_dicts=list_of_dicts)
flatd = {
tuple([keymap.get(k, k) for k in path]): v for path, v in flatd.items()
}
return unflatten(flatd, list_of_dicts=list_of_dicts, deepcopy=deepcopy) | python | def rename_keys(d, keymap=None, list_of_dicts=False, deepcopy=True):
""" rename keys in dict
Parameters
----------
d : dict
keymap : dict
dictionary of key name mappings
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {'a':{'old_name':1}}
>>> pprint(rename_keys(d,{'old_name':'new_name'}))
{'a': {'new_name': 1}}
"""
list_of_dicts = '__list__' if list_of_dicts else None
keymap = {} if keymap is None else keymap
flatd = flatten(d, list_of_dicts=list_of_dicts)
flatd = {
tuple([keymap.get(k, k) for k in path]): v for path, v in flatd.items()
}
return unflatten(flatd, list_of_dicts=list_of_dicts, deepcopy=deepcopy) | [
"def",
"rename_keys",
"(",
"d",
",",
"keymap",
"=",
"None",
",",
"list_of_dicts",
"=",
"False",
",",
"deepcopy",
"=",
"True",
")",
":",
"list_of_dicts",
"=",
"'__list__'",
"if",
"list_of_dicts",
"else",
"None",
"keymap",
"=",
"{",
"}",
"if",
"keymap",
"i... | rename keys in dict
Parameters
----------
d : dict
keymap : dict
dictionary of key name mappings
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
Examples
--------
>>> from pprint import pprint
>>> d = {'a':{'old_name':1}}
>>> pprint(rename_keys(d,{'old_name':'new_name'}))
{'a': {'new_name': 1}} | [
"rename",
"keys",
"in",
"dict"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1362-L1393 | train | 53,776 |
chrisjsewell/jsonextended | jsonextended/edict.py | combine_lists | def combine_lists(d, keys=None, deepcopy=True):
"""combine lists of dicts
Parameters
----------
d : dict or list[dict]
keys : list
keys to combine (all if None)
deepcopy: bool
deepcopy values
Example
-------
>>> from pprint import pprint
>>> d = {'path_key': {'a': 1, 'split': [{'x': 1, 'y': 3}, {'x': 2, 'y': 4}]}}
>>> pprint(combine_lists(d,['split']))
{'path_key': {'a': 1, 'split': {'x': [1, 2], 'y': [3, 4]}}}
>>> combine_lists([{"a":2}, {"a":1}])
{'a': [2, 1]}
""" # noqa: E501
if isinstance(d, list):
init_list = True
d = {'dummy_key843': d}
else:
init_list = False
flattened = flatten(d, list_of_dicts=None)
for key, value in list(flattened.items()):
if keys is not None:
try:
if not key[-1] in keys:
continue
except Exception:
continue
if not isinstance(value, list):
continue
if not all([is_dict_like(d) for d in value]):
continue
newd = {}
for subdic in value:
for subk, subv in subdic.items():
if subk not in newd:
newd[subk] = []
newd[subk].append(subv)
flattened[key] = newd
final = unflatten(flattened, list_of_dicts=None, deepcopy=deepcopy)
if init_list:
return list(final.values())[0]
else:
return final | python | def combine_lists(d, keys=None, deepcopy=True):
"""combine lists of dicts
Parameters
----------
d : dict or list[dict]
keys : list
keys to combine (all if None)
deepcopy: bool
deepcopy values
Example
-------
>>> from pprint import pprint
>>> d = {'path_key': {'a': 1, 'split': [{'x': 1, 'y': 3}, {'x': 2, 'y': 4}]}}
>>> pprint(combine_lists(d,['split']))
{'path_key': {'a': 1, 'split': {'x': [1, 2], 'y': [3, 4]}}}
>>> combine_lists([{"a":2}, {"a":1}])
{'a': [2, 1]}
""" # noqa: E501
if isinstance(d, list):
init_list = True
d = {'dummy_key843': d}
else:
init_list = False
flattened = flatten(d, list_of_dicts=None)
for key, value in list(flattened.items()):
if keys is not None:
try:
if not key[-1] in keys:
continue
except Exception:
continue
if not isinstance(value, list):
continue
if not all([is_dict_like(d) for d in value]):
continue
newd = {}
for subdic in value:
for subk, subv in subdic.items():
if subk not in newd:
newd[subk] = []
newd[subk].append(subv)
flattened[key] = newd
final = unflatten(flattened, list_of_dicts=None, deepcopy=deepcopy)
if init_list:
return list(final.values())[0]
else:
return final | [
"def",
"combine_lists",
"(",
"d",
",",
"keys",
"=",
"None",
",",
"deepcopy",
"=",
"True",
")",
":",
"# noqa: E501",
"if",
"isinstance",
"(",
"d",
",",
"list",
")",
":",
"init_list",
"=",
"True",
"d",
"=",
"{",
"'dummy_key843'",
":",
"d",
"}",
"else",... | combine lists of dicts
Parameters
----------
d : dict or list[dict]
keys : list
keys to combine (all if None)
deepcopy: bool
deepcopy values
Example
-------
>>> from pprint import pprint
>>> d = {'path_key': {'a': 1, 'split': [{'x': 1, 'y': 3}, {'x': 2, 'y': 4}]}}
>>> pprint(combine_lists(d,['split']))
{'path_key': {'a': 1, 'split': {'x': [1, 2], 'y': [3, 4]}}}
>>> combine_lists([{"a":2}, {"a":1}])
{'a': [2, 1]} | [
"combine",
"lists",
"of",
"dicts"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1673-L1727 | train | 53,777 |
chrisjsewell/jsonextended | jsonextended/edict.py | list_to_dict | def list_to_dict(lst, key=None, remove_key=True):
""" convert a list of dicts to a dict with root keys
Parameters
----------
lst : list[dict]
key : str or None
a key contained by all of the dicts
if None use index number string
remove_key : bool
remove key from dicts in list
Examples
--------
>>> from pprint import pprint
>>> lst = [{'name':'f','b':1},{'name':'g','c':2}]
>>> pprint(list_to_dict(lst))
{'0': {'b': 1, 'name': 'f'}, '1': {'c': 2, 'name': 'g'}}
>>> pprint(list_to_dict(lst,'name'))
{'f': {'b': 1}, 'g': {'c': 2}}
"""
assert all([is_dict_like(d) for d in lst])
if key is not None:
assert all([key in d for d in lst])
new_dict = {}
for i, d in enumerate(lst):
d = unflatten(flatten(d))
if key is None:
new_dict[str(i)] = d
else:
if remove_key:
k = d.pop(key)
else:
k = d[key]
new_dict[k] = d
return new_dict | python | def list_to_dict(lst, key=None, remove_key=True):
""" convert a list of dicts to a dict with root keys
Parameters
----------
lst : list[dict]
key : str or None
a key contained by all of the dicts
if None use index number string
remove_key : bool
remove key from dicts in list
Examples
--------
>>> from pprint import pprint
>>> lst = [{'name':'f','b':1},{'name':'g','c':2}]
>>> pprint(list_to_dict(lst))
{'0': {'b': 1, 'name': 'f'}, '1': {'c': 2, 'name': 'g'}}
>>> pprint(list_to_dict(lst,'name'))
{'f': {'b': 1}, 'g': {'c': 2}}
"""
assert all([is_dict_like(d) for d in lst])
if key is not None:
assert all([key in d for d in lst])
new_dict = {}
for i, d in enumerate(lst):
d = unflatten(flatten(d))
if key is None:
new_dict[str(i)] = d
else:
if remove_key:
k = d.pop(key)
else:
k = d[key]
new_dict[k] = d
return new_dict | [
"def",
"list_to_dict",
"(",
"lst",
",",
"key",
"=",
"None",
",",
"remove_key",
"=",
"True",
")",
":",
"assert",
"all",
"(",
"[",
"is_dict_like",
"(",
"d",
")",
"for",
"d",
"in",
"lst",
"]",
")",
"if",
"key",
"is",
"not",
"None",
":",
"assert",
"a... | convert a list of dicts to a dict with root keys
Parameters
----------
lst : list[dict]
key : str or None
a key contained by all of the dicts
if None use index number string
remove_key : bool
remove key from dicts in list
Examples
--------
>>> from pprint import pprint
>>> lst = [{'name':'f','b':1},{'name':'g','c':2}]
>>> pprint(list_to_dict(lst))
{'0': {'b': 1, 'name': 'f'}, '1': {'c': 2, 'name': 'g'}}
>>> pprint(list_to_dict(lst,'name'))
{'f': {'b': 1}, 'g': {'c': 2}} | [
"convert",
"a",
"list",
"of",
"dicts",
"to",
"a",
"dict",
"with",
"root",
"keys"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1730-L1769 | train | 53,778 |
chrisjsewell/jsonextended | jsonextended/edict.py | diff | def diff(new_dict, old_dict, iter_prefix='__iter__',
np_allclose=False, **kwargs):
""" return the difference between two dict_like objects
Parameters
----------
new_dict: dict
old_dict: dict
iter_prefix: str
prefix to use for list and tuple indexes
np_allclose: bool
if True, try using numpy.allclose to assess differences
**kwargs:
keyword arguments to parse to numpy.allclose
Returns
-------
outcome: dict
Containing none or more of:
- "insertions" : list of (path, val)
- "deletions" : list of (path, val)
- "changes" : list of (path, (val1, val2))
- "uncomparable" : list of (path, (val1, val2))
Examples
--------
>>> from pprint import pprint
>>> diff({'a':1},{'a':1})
{}
>>> pprint(diff({'a': 1, 'b': 2, 'c': 5},{'b': 3, 'c': 4, 'd': 6}))
{'changes': [(('b',), (2, 3)), (('c',), (5, 4))],
'deletions': [(('d',), 6)],
'insertions': [(('a',), 1)]}
>>> pprint(diff({'a': [{"b":1}, {"c":2}, 1]},{'a': [{"b":1}, {"d":2}, 2]}))
{'changes': [(('a', '__iter__2'), (1, 2))],
'deletions': [(('a', '__iter__1', 'd'), 2)],
'insertions': [(('a', '__iter__1', 'c'), 2)]}
>>> diff({'a':1}, {'a':1+1e-10})
{'changes': [(('a',), (1, 1.0000000001))]}
>>> diff({'a':1}, {'a':1+1e-10}, np_allclose=True)
{}
"""
if np_allclose:
try:
import numpy
except ImportError:
raise ValueError("to use np_allclose, numpy must be installed")
dct1_flat = flatten(new_dict, all_iters=iter_prefix)
dct2_flat = flatten(old_dict, all_iters=iter_prefix)
outcome = {'insertions': [], 'deletions': [],
'changes': [], 'uncomparable': []}
for path, val in dct1_flat.items():
if path not in dct2_flat:
outcome['insertions'].append((path, val))
continue
other_val = dct2_flat.pop(path)
if np_allclose:
try:
if numpy.allclose(val, other_val, **kwargs):
continue
except Exception:
pass
try:
if val != other_val:
outcome['changes'].append((path, (val, other_val)))
except Exception:
outcome['uncomparable'].append((path, (val, other_val)))
for path2, val2 in dct2_flat.items():
outcome['deletions'].append((path2, val2))
# remove any empty lists and sort
for key in list(outcome.keys()):
if not outcome[key]:
outcome.pop(key)
try:
outcome[key] = sorted(outcome[key])
except Exception:
pass
return outcome | python | def diff(new_dict, old_dict, iter_prefix='__iter__',
np_allclose=False, **kwargs):
""" return the difference between two dict_like objects
Parameters
----------
new_dict: dict
old_dict: dict
iter_prefix: str
prefix to use for list and tuple indexes
np_allclose: bool
if True, try using numpy.allclose to assess differences
**kwargs:
keyword arguments to parse to numpy.allclose
Returns
-------
outcome: dict
Containing none or more of:
- "insertions" : list of (path, val)
- "deletions" : list of (path, val)
- "changes" : list of (path, (val1, val2))
- "uncomparable" : list of (path, (val1, val2))
Examples
--------
>>> from pprint import pprint
>>> diff({'a':1},{'a':1})
{}
>>> pprint(diff({'a': 1, 'b': 2, 'c': 5},{'b': 3, 'c': 4, 'd': 6}))
{'changes': [(('b',), (2, 3)), (('c',), (5, 4))],
'deletions': [(('d',), 6)],
'insertions': [(('a',), 1)]}
>>> pprint(diff({'a': [{"b":1}, {"c":2}, 1]},{'a': [{"b":1}, {"d":2}, 2]}))
{'changes': [(('a', '__iter__2'), (1, 2))],
'deletions': [(('a', '__iter__1', 'd'), 2)],
'insertions': [(('a', '__iter__1', 'c'), 2)]}
>>> diff({'a':1}, {'a':1+1e-10})
{'changes': [(('a',), (1, 1.0000000001))]}
>>> diff({'a':1}, {'a':1+1e-10}, np_allclose=True)
{}
"""
if np_allclose:
try:
import numpy
except ImportError:
raise ValueError("to use np_allclose, numpy must be installed")
dct1_flat = flatten(new_dict, all_iters=iter_prefix)
dct2_flat = flatten(old_dict, all_iters=iter_prefix)
outcome = {'insertions': [], 'deletions': [],
'changes': [], 'uncomparable': []}
for path, val in dct1_flat.items():
if path not in dct2_flat:
outcome['insertions'].append((path, val))
continue
other_val = dct2_flat.pop(path)
if np_allclose:
try:
if numpy.allclose(val, other_val, **kwargs):
continue
except Exception:
pass
try:
if val != other_val:
outcome['changes'].append((path, (val, other_val)))
except Exception:
outcome['uncomparable'].append((path, (val, other_val)))
for path2, val2 in dct2_flat.items():
outcome['deletions'].append((path2, val2))
# remove any empty lists and sort
for key in list(outcome.keys()):
if not outcome[key]:
outcome.pop(key)
try:
outcome[key] = sorted(outcome[key])
except Exception:
pass
return outcome | [
"def",
"diff",
"(",
"new_dict",
",",
"old_dict",
",",
"iter_prefix",
"=",
"'__iter__'",
",",
"np_allclose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"np_allclose",
":",
"try",
":",
"import",
"numpy",
"except",
"ImportError",
":",
"raise",
"... | return the difference between two dict_like objects
Parameters
----------
new_dict: dict
old_dict: dict
iter_prefix: str
prefix to use for list and tuple indexes
np_allclose: bool
if True, try using numpy.allclose to assess differences
**kwargs:
keyword arguments to parse to numpy.allclose
Returns
-------
outcome: dict
Containing none or more of:
- "insertions" : list of (path, val)
- "deletions" : list of (path, val)
- "changes" : list of (path, (val1, val2))
- "uncomparable" : list of (path, (val1, val2))
Examples
--------
>>> from pprint import pprint
>>> diff({'a':1},{'a':1})
{}
>>> pprint(diff({'a': 1, 'b': 2, 'c': 5},{'b': 3, 'c': 4, 'd': 6}))
{'changes': [(('b',), (2, 3)), (('c',), (5, 4))],
'deletions': [(('d',), 6)],
'insertions': [(('a',), 1)]}
>>> pprint(diff({'a': [{"b":1}, {"c":2}, 1]},{'a': [{"b":1}, {"d":2}, 2]}))
{'changes': [(('a', '__iter__2'), (1, 2))],
'deletions': [(('a', '__iter__1', 'd'), 2)],
'insertions': [(('a', '__iter__1', 'c'), 2)]}
>>> diff({'a':1}, {'a':1+1e-10})
{'changes': [(('a',), (1, 1.0000000001))]}
>>> diff({'a':1}, {'a':1+1e-10}, np_allclose=True)
{} | [
"return",
"the",
"difference",
"between",
"two",
"dict_like",
"objects"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1772-L1862 | train | 53,779 |
bjodah/pycompilation | pycompilation/util.py | copy | def copy(src, dst, only_update=False, copystat=True, cwd=None,
dest_is_dir=False, create_dest_dirs=False, logger=None):
"""
Augmented shutil.copy with extra options and slightly
modified behaviour
Parameters
==========
src: string
path to source file
dst: string
path to destingation
only_update: bool
only copy if source is newer than destination
(returns None if it was newer), default: False
copystat: bool
See shutil.copystat. default: True
cwd: string
Path to working directory (root of relative paths)
dest_is_dir: bool
ensures that dst is treated as a directory. default: False
create_dest_dirs: bool
creates directories if needed.
logger: logging.Looger
debug level info emitted. Passed onto make_dirs.
Returns
=======
Path to the copied file.
"""
# Handle virtual working directory
if cwd:
if not os.path.isabs(src):
src = os.path.join(cwd, src)
if not os.path.isabs(dst):
dst = os.path.join(cwd, dst)
# Make sure source file extists
if not os.path.exists(src):
# Source needs to exist
msg = "Source: `{}` does not exist".format(src)
raise FileNotFoundError(msg)
# We accept both (re)naming destination file _or_
# passing a (possible non-existant) destination directory
if dest_is_dir:
if not dst[-1] == '/':
dst = dst+'/'
else:
if os.path.exists(dst) and os.path.isdir(dst):
dest_is_dir = True
if dest_is_dir:
dest_dir = dst
dest_fname = os.path.basename(src)
dst = os.path.join(dest_dir, dest_fname)
else:
dest_dir = os.path.dirname(dst)
dest_fname = os.path.basename(dst)
if not os.path.exists(dest_dir):
if create_dest_dirs:
make_dirs(dest_dir, logger=logger)
else:
msg = "You must create directory first."
raise FileNotFoundError(msg)
if only_update:
if not missing_or_other_newer(dst, src):
if logger:
logger.debug(
"Did not copy {} to {} (source not newer)".format(
src, dst))
return
if os.path.islink(dst):
if os.path.abspath(os.path.realpath(dst)) == \
os.path.abspath(dst):
pass # destination is a symlic pointing to src
else:
if logger:
logger.debug("Copying {} to {}".format(src, dst))
shutil.copy(src, dst)
if copystat:
shutil.copystat(src, dst)
return dst | python | def copy(src, dst, only_update=False, copystat=True, cwd=None,
dest_is_dir=False, create_dest_dirs=False, logger=None):
"""
Augmented shutil.copy with extra options and slightly
modified behaviour
Parameters
==========
src: string
path to source file
dst: string
path to destingation
only_update: bool
only copy if source is newer than destination
(returns None if it was newer), default: False
copystat: bool
See shutil.copystat. default: True
cwd: string
Path to working directory (root of relative paths)
dest_is_dir: bool
ensures that dst is treated as a directory. default: False
create_dest_dirs: bool
creates directories if needed.
logger: logging.Looger
debug level info emitted. Passed onto make_dirs.
Returns
=======
Path to the copied file.
"""
# Handle virtual working directory
if cwd:
if not os.path.isabs(src):
src = os.path.join(cwd, src)
if not os.path.isabs(dst):
dst = os.path.join(cwd, dst)
# Make sure source file extists
if not os.path.exists(src):
# Source needs to exist
msg = "Source: `{}` does not exist".format(src)
raise FileNotFoundError(msg)
# We accept both (re)naming destination file _or_
# passing a (possible non-existant) destination directory
if dest_is_dir:
if not dst[-1] == '/':
dst = dst+'/'
else:
if os.path.exists(dst) and os.path.isdir(dst):
dest_is_dir = True
if dest_is_dir:
dest_dir = dst
dest_fname = os.path.basename(src)
dst = os.path.join(dest_dir, dest_fname)
else:
dest_dir = os.path.dirname(dst)
dest_fname = os.path.basename(dst)
if not os.path.exists(dest_dir):
if create_dest_dirs:
make_dirs(dest_dir, logger=logger)
else:
msg = "You must create directory first."
raise FileNotFoundError(msg)
if only_update:
if not missing_or_other_newer(dst, src):
if logger:
logger.debug(
"Did not copy {} to {} (source not newer)".format(
src, dst))
return
if os.path.islink(dst):
if os.path.abspath(os.path.realpath(dst)) == \
os.path.abspath(dst):
pass # destination is a symlic pointing to src
else:
if logger:
logger.debug("Copying {} to {}".format(src, dst))
shutil.copy(src, dst)
if copystat:
shutil.copystat(src, dst)
return dst | [
"def",
"copy",
"(",
"src",
",",
"dst",
",",
"only_update",
"=",
"False",
",",
"copystat",
"=",
"True",
",",
"cwd",
"=",
"None",
",",
"dest_is_dir",
"=",
"False",
",",
"create_dest_dirs",
"=",
"False",
",",
"logger",
"=",
"None",
")",
":",
"# Handle vir... | Augmented shutil.copy with extra options and slightly
modified behaviour
Parameters
==========
src: string
path to source file
dst: string
path to destingation
only_update: bool
only copy if source is newer than destination
(returns None if it was newer), default: False
copystat: bool
See shutil.copystat. default: True
cwd: string
Path to working directory (root of relative paths)
dest_is_dir: bool
ensures that dst is treated as a directory. default: False
create_dest_dirs: bool
creates directories if needed.
logger: logging.Looger
debug level info emitted. Passed onto make_dirs.
Returns
=======
Path to the copied file. | [
"Augmented",
"shutil",
".",
"copy",
"with",
"extra",
"options",
"and",
"slightly",
"modified",
"behaviour"
] | 43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18 | https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L92-L178 | train | 53,780 |
bjodah/pycompilation | pycompilation/util.py | md5_of_file | def md5_of_file(path, nblocks=128):
"""
Computes the md5 hash of a file.
Parameters
==========
path: string
path to file to compute hash of
Returns
=======
hashlib md5 hash object. Use .digest() or .hexdigest()
on returned object to get binary or hex encoded string.
"""
md = md5()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(nblocks*md.block_size), b''):
md.update(chunk)
return md | python | def md5_of_file(path, nblocks=128):
"""
Computes the md5 hash of a file.
Parameters
==========
path: string
path to file to compute hash of
Returns
=======
hashlib md5 hash object. Use .digest() or .hexdigest()
on returned object to get binary or hex encoded string.
"""
md = md5()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(nblocks*md.block_size), b''):
md.update(chunk)
return md | [
"def",
"md5_of_file",
"(",
"path",
",",
"nblocks",
"=",
"128",
")",
":",
"md",
"=",
"md5",
"(",
")",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"read",
"(",
"nblock... | Computes the md5 hash of a file.
Parameters
==========
path: string
path to file to compute hash of
Returns
=======
hashlib md5 hash object. Use .digest() or .hexdigest()
on returned object to get binary or hex encoded string. | [
"Computes",
"the",
"md5",
"hash",
"of",
"a",
"file",
"."
] | 43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18 | https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L181-L199 | train | 53,781 |
bjodah/pycompilation | pycompilation/util.py | missing_or_other_newer | def missing_or_other_newer(path, other_path, cwd=None):
"""
Investigate if path is non-existant or older than provided reference
path.
Parameters
==========
path: string
path to path which might be missing or too old
other_path: string
reference path
cwd: string
working directory (root of relative paths)
Returns
=======
True if path is older or missing.
"""
cwd = cwd or '.'
path = get_abspath(path, cwd=cwd)
other_path = get_abspath(other_path, cwd=cwd)
if not os.path.exists(path):
return True
if os.path.getmtime(other_path) - 1e-6 >= os.path.getmtime(path):
# 1e-6 is needed beacuse http://stackoverflow.com/questions/17086426/
return True
return False | python | def missing_or_other_newer(path, other_path, cwd=None):
"""
Investigate if path is non-existant or older than provided reference
path.
Parameters
==========
path: string
path to path which might be missing or too old
other_path: string
reference path
cwd: string
working directory (root of relative paths)
Returns
=======
True if path is older or missing.
"""
cwd = cwd or '.'
path = get_abspath(path, cwd=cwd)
other_path = get_abspath(other_path, cwd=cwd)
if not os.path.exists(path):
return True
if os.path.getmtime(other_path) - 1e-6 >= os.path.getmtime(path):
# 1e-6 is needed beacuse http://stackoverflow.com/questions/17086426/
return True
return False | [
"def",
"missing_or_other_newer",
"(",
"path",
",",
"other_path",
",",
"cwd",
"=",
"None",
")",
":",
"cwd",
"=",
"cwd",
"or",
"'.'",
"path",
"=",
"get_abspath",
"(",
"path",
",",
"cwd",
"=",
"cwd",
")",
"other_path",
"=",
"get_abspath",
"(",
"other_path",... | Investigate if path is non-existant or older than provided reference
path.
Parameters
==========
path: string
path to path which might be missing or too old
other_path: string
reference path
cwd: string
working directory (root of relative paths)
Returns
=======
True if path is older or missing. | [
"Investigate",
"if",
"path",
"is",
"non",
"-",
"existant",
"or",
"older",
"than",
"provided",
"reference",
"path",
"."
] | 43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18 | https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L208-L234 | train | 53,782 |
bjodah/pycompilation | pycompilation/util.py | find_binary_of_command | def find_binary_of_command(candidates):
"""
Calls `find_executable` from distuils for
provided candidates and returns first hit.
If no candidate mathces, a RuntimeError is raised
"""
from distutils.spawn import find_executable
for c in candidates:
binary_path = find_executable(c)
if c and binary_path:
return c, binary_path
raise RuntimeError('No binary located for candidates: {}'.format(
candidates)) | python | def find_binary_of_command(candidates):
"""
Calls `find_executable` from distuils for
provided candidates and returns first hit.
If no candidate mathces, a RuntimeError is raised
"""
from distutils.spawn import find_executable
for c in candidates:
binary_path = find_executable(c)
if c and binary_path:
return c, binary_path
raise RuntimeError('No binary located for candidates: {}'.format(
candidates)) | [
"def",
"find_binary_of_command",
"(",
"candidates",
")",
":",
"from",
"distutils",
".",
"spawn",
"import",
"find_executable",
"for",
"c",
"in",
"candidates",
":",
"binary_path",
"=",
"find_executable",
"(",
"c",
")",
"if",
"c",
"and",
"binary_path",
":",
"retu... | Calls `find_executable` from distuils for
provided candidates and returns first hit.
If no candidate mathces, a RuntimeError is raised | [
"Calls",
"find_executable",
"from",
"distuils",
"for",
"provided",
"candidates",
"and",
"returns",
"first",
"hit",
".",
"If",
"no",
"candidate",
"mathces",
"a",
"RuntimeError",
"is",
"raised"
] | 43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18 | https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L321-L333 | train | 53,783 |
bjodah/pycompilation | pycompilation/util.py | HasMetaData.get_from_metadata_file | def get_from_metadata_file(cls, dirpath, key):
"""
Get value of key in metadata file dict.
"""
fullpath = os.path.join(dirpath, cls.metadata_filename)
if os.path.exists(fullpath):
d = pickle.load(open(fullpath, 'rb'))
return d[key]
else:
raise FileNotFoundError(
"No such file: {0}".format(fullpath)) | python | def get_from_metadata_file(cls, dirpath, key):
"""
Get value of key in metadata file dict.
"""
fullpath = os.path.join(dirpath, cls.metadata_filename)
if os.path.exists(fullpath):
d = pickle.load(open(fullpath, 'rb'))
return d[key]
else:
raise FileNotFoundError(
"No such file: {0}".format(fullpath)) | [
"def",
"get_from_metadata_file",
"(",
"cls",
",",
"dirpath",
",",
"key",
")",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"cls",
".",
"metadata_filename",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fullpath",
")",... | Get value of key in metadata file dict. | [
"Get",
"value",
"of",
"key",
"in",
"metadata",
"file",
"dict",
"."
] | 43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18 | https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L249-L259 | train | 53,784 |
chrisjsewell/jsonextended | jsonextended/plugins.py | view_plugins | def view_plugins(category=None):
""" return a view of the loaded plugin names and descriptions
Parameters
----------
category : None or str
if str, apply for single plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
>>> class DecoderPlugin(object):
... plugin_name = 'example'
... plugin_descript = 'a decoder for dicts containing _example_ key'
... dict_signature = ('_example_',)
...
>>> errors = load_plugin_classes([DecoderPlugin])
>>> pprint(view_plugins())
{'decoders': {'example': 'a decoder for dicts containing _example_ key'},
'encoders': {},
'parsers': {}}
>>> view_plugins('decoders')
{'example': 'a decoder for dicts containing _example_ key'}
>>> unload_all_plugins()
"""
if category is not None:
if category == 'parsers':
return {
name: {"descript": klass.plugin_descript,
"regex": klass.file_regex}
for name, klass in _all_plugins[category].items()
}
return {
name: klass.plugin_descript
for name, klass in _all_plugins[category].items()
}
else:
return {cat: {name: klass.plugin_descript
for name, klass in plugins.items()}
for cat, plugins in _all_plugins.items()} | python | def view_plugins(category=None):
""" return a view of the loaded plugin names and descriptions
Parameters
----------
category : None or str
if str, apply for single plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
>>> class DecoderPlugin(object):
... plugin_name = 'example'
... plugin_descript = 'a decoder for dicts containing _example_ key'
... dict_signature = ('_example_',)
...
>>> errors = load_plugin_classes([DecoderPlugin])
>>> pprint(view_plugins())
{'decoders': {'example': 'a decoder for dicts containing _example_ key'},
'encoders': {},
'parsers': {}}
>>> view_plugins('decoders')
{'example': 'a decoder for dicts containing _example_ key'}
>>> unload_all_plugins()
"""
if category is not None:
if category == 'parsers':
return {
name: {"descript": klass.plugin_descript,
"regex": klass.file_regex}
for name, klass in _all_plugins[category].items()
}
return {
name: klass.plugin_descript
for name, klass in _all_plugins[category].items()
}
else:
return {cat: {name: klass.plugin_descript
for name, klass in plugins.items()}
for cat, plugins in _all_plugins.items()} | [
"def",
"view_plugins",
"(",
"category",
"=",
"None",
")",
":",
"if",
"category",
"is",
"not",
"None",
":",
"if",
"category",
"==",
"'parsers'",
":",
"return",
"{",
"name",
":",
"{",
"\"descript\"",
":",
"klass",
".",
"plugin_descript",
",",
"\"regex\"",
... | return a view of the loaded plugin names and descriptions
Parameters
----------
category : None or str
if str, apply for single plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
>>> class DecoderPlugin(object):
... plugin_name = 'example'
... plugin_descript = 'a decoder for dicts containing _example_ key'
... dict_signature = ('_example_',)
...
>>> errors = load_plugin_classes([DecoderPlugin])
>>> pprint(view_plugins())
{'decoders': {'example': 'a decoder for dicts containing _example_ key'},
'encoders': {},
'parsers': {}}
>>> view_plugins('decoders')
{'example': 'a decoder for dicts containing _example_ key'}
>>> unload_all_plugins() | [
"return",
"a",
"view",
"of",
"the",
"loaded",
"plugin",
"names",
"and",
"descriptions"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L80-L127 | train | 53,785 |
chrisjsewell/jsonextended | jsonextended/plugins.py | unload_plugin | def unload_plugin(name, category=None):
""" remove single plugin
Parameters
----------
name : str
plugin name
category : str
plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
>>> class DecoderPlugin(object):
... plugin_name = 'example'
... plugin_descript = 'a decoder for dicts containing _example_ key'
... dict_signature = ('_example_',)
...
>>> errors = load_plugin_classes([DecoderPlugin],category='decoders')
>>> pprint(view_plugins())
{'decoders': {'example': 'a decoder for dicts containing _example_ key'},
'encoders': {},
'parsers': {}}
>>> unload_plugin('example','decoders')
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
"""
if category is not None:
_all_plugins[category].pop(name)
else:
for cat in _all_plugins:
if name in _all_plugins[cat]:
_all_plugins[cat].pop(name) | python | def unload_plugin(name, category=None):
""" remove single plugin
Parameters
----------
name : str
plugin name
category : str
plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
>>> class DecoderPlugin(object):
... plugin_name = 'example'
... plugin_descript = 'a decoder for dicts containing _example_ key'
... dict_signature = ('_example_',)
...
>>> errors = load_plugin_classes([DecoderPlugin],category='decoders')
>>> pprint(view_plugins())
{'decoders': {'example': 'a decoder for dicts containing _example_ key'},
'encoders': {},
'parsers': {}}
>>> unload_plugin('example','decoders')
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
"""
if category is not None:
_all_plugins[category].pop(name)
else:
for cat in _all_plugins:
if name in _all_plugins[cat]:
_all_plugins[cat].pop(name) | [
"def",
"unload_plugin",
"(",
"name",
",",
"category",
"=",
"None",
")",
":",
"if",
"category",
"is",
"not",
"None",
":",
"_all_plugins",
"[",
"category",
"]",
".",
"pop",
"(",
"name",
")",
"else",
":",
"for",
"cat",
"in",
"_all_plugins",
":",
"if",
"... | remove single plugin
Parameters
----------
name : str
plugin name
category : str
plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
>>> class DecoderPlugin(object):
... plugin_name = 'example'
... plugin_descript = 'a decoder for dicts containing _example_ key'
... dict_signature = ('_example_',)
...
>>> errors = load_plugin_classes([DecoderPlugin],category='decoders')
>>> pprint(view_plugins())
{'decoders': {'example': 'a decoder for dicts containing _example_ key'},
'encoders': {},
'parsers': {}}
>>> unload_plugin('example','decoders')
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}} | [
"remove",
"single",
"plugin"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L174-L213 | train | 53,786 |
chrisjsewell/jsonextended | jsonextended/plugins.py | load_plugin_classes | def load_plugin_classes(classes, category=None, overwrite=False):
""" load plugins from class objects
Parameters
----------
classes: list
list of classes
category : None or str
if str, apply for single plugin category
overwrite : bool
if True, allow existing plugins to be overwritten
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
>>> class DecoderPlugin(object):
... plugin_name = 'example'
... plugin_descript = 'a decoder for dicts containing _example_ key'
... dict_signature = ('_example_',)
...
>>> errors = load_plugin_classes([DecoderPlugin])
>>> pprint(view_plugins())
{'decoders': {'example': 'a decoder for dicts containing _example_ key'},
'encoders': {},
'parsers': {}}
>>> unload_all_plugins()
"""
load_errors = []
for klass in classes:
for pcat, pinterface in _plugins_interface.items():
if category is not None and not pcat == category:
continue
if all([hasattr(klass, attr) for attr in pinterface]):
if klass.plugin_name in _all_plugins[pcat] and not overwrite:
err = '{0} is already set for {1}'.format(
klass.plugin_name, pcat)
load_errors.append((klass.__name__, '{}'.format(err)))
continue
_all_plugins[pcat][klass.plugin_name] = klass()
else:
load_errors.append((
klass.__name__,
'does not match {} interface: {}'.format(pcat, pinterface)
))
return load_errors | python | def load_plugin_classes(classes, category=None, overwrite=False):
""" load plugins from class objects
Parameters
----------
classes: list
list of classes
category : None or str
if str, apply for single plugin category
overwrite : bool
if True, allow existing plugins to be overwritten
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
>>> class DecoderPlugin(object):
... plugin_name = 'example'
... plugin_descript = 'a decoder for dicts containing _example_ key'
... dict_signature = ('_example_',)
...
>>> errors = load_plugin_classes([DecoderPlugin])
>>> pprint(view_plugins())
{'decoders': {'example': 'a decoder for dicts containing _example_ key'},
'encoders': {},
'parsers': {}}
>>> unload_all_plugins()
"""
load_errors = []
for klass in classes:
for pcat, pinterface in _plugins_interface.items():
if category is not None and not pcat == category:
continue
if all([hasattr(klass, attr) for attr in pinterface]):
if klass.plugin_name in _all_plugins[pcat] and not overwrite:
err = '{0} is already set for {1}'.format(
klass.plugin_name, pcat)
load_errors.append((klass.__name__, '{}'.format(err)))
continue
_all_plugins[pcat][klass.plugin_name] = klass()
else:
load_errors.append((
klass.__name__,
'does not match {} interface: {}'.format(pcat, pinterface)
))
return load_errors | [
"def",
"load_plugin_classes",
"(",
"classes",
",",
"category",
"=",
"None",
",",
"overwrite",
"=",
"False",
")",
":",
"load_errors",
"=",
"[",
"]",
"for",
"klass",
"in",
"classes",
":",
"for",
"pcat",
",",
"pinterface",
"in",
"_plugins_interface",
".",
"it... | load plugins from class objects
Parameters
----------
classes: list
list of classes
category : None or str
if str, apply for single plugin category
overwrite : bool
if True, allow existing plugins to be overwritten
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
>>> class DecoderPlugin(object):
... plugin_name = 'example'
... plugin_descript = 'a decoder for dicts containing _example_ key'
... dict_signature = ('_example_',)
...
>>> errors = load_plugin_classes([DecoderPlugin])
>>> pprint(view_plugins())
{'decoders': {'example': 'a decoder for dicts containing _example_ key'},
'encoders': {},
'parsers': {}}
>>> unload_all_plugins() | [
"load",
"plugins",
"from",
"class",
"objects"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L216-L267 | train | 53,787 |
chrisjsewell/jsonextended | jsonextended/plugins.py | load_plugins_dir | def load_plugins_dir(path, category=None, overwrite=False):
""" load plugins from a directory
Parameters
----------
path : str or path_like
category : None or str
if str, apply for single plugin category
overwrite : bool
if True, allow existing plugins to be overwritten
"""
# get potential plugin python files
if hasattr(path, 'glob'):
pypaths = path.glob('*.py')
else:
pypaths = glob.glob(os.path.join(path, '*.py'))
load_errors = []
for pypath in pypaths:
# use uuid to ensure no conflicts in name space
mod_name = str(uuid.uuid4())
try:
if hasattr(pypath, 'resolve'):
# Make the path absolute, resolving any symlinks
pypath = pypath.resolve()
with warnings.catch_warnings(record=True):
warnings.filterwarnings("ignore", category=ImportWarning)
# for MockPaths
if hasattr(pypath, 'maketemp'):
with pypath.maketemp() as f:
module = load_source(mod_name, f.name)
else:
module = load_source(mod_name, str(pypath))
except Exception as err:
load_errors.append((str(pypath), 'Load Error: {}'.format(err)))
continue
# only get classes that are local to the module
class_members = inspect.getmembers(module, inspect.isclass)
classes = [klass for klass_name, klass in class_members if
klass.__module__ == mod_name]
load_errors += load_plugin_classes(classes, category, overwrite)
return load_errors | python | def load_plugins_dir(path, category=None, overwrite=False):
""" load plugins from a directory
Parameters
----------
path : str or path_like
category : None or str
if str, apply for single plugin category
overwrite : bool
if True, allow existing plugins to be overwritten
"""
# get potential plugin python files
if hasattr(path, 'glob'):
pypaths = path.glob('*.py')
else:
pypaths = glob.glob(os.path.join(path, '*.py'))
load_errors = []
for pypath in pypaths:
# use uuid to ensure no conflicts in name space
mod_name = str(uuid.uuid4())
try:
if hasattr(pypath, 'resolve'):
# Make the path absolute, resolving any symlinks
pypath = pypath.resolve()
with warnings.catch_warnings(record=True):
warnings.filterwarnings("ignore", category=ImportWarning)
# for MockPaths
if hasattr(pypath, 'maketemp'):
with pypath.maketemp() as f:
module = load_source(mod_name, f.name)
else:
module = load_source(mod_name, str(pypath))
except Exception as err:
load_errors.append((str(pypath), 'Load Error: {}'.format(err)))
continue
# only get classes that are local to the module
class_members = inspect.getmembers(module, inspect.isclass)
classes = [klass for klass_name, klass in class_members if
klass.__module__ == mod_name]
load_errors += load_plugin_classes(classes, category, overwrite)
return load_errors | [
"def",
"load_plugins_dir",
"(",
"path",
",",
"category",
"=",
"None",
",",
"overwrite",
"=",
"False",
")",
":",
"# get potential plugin python files",
"if",
"hasattr",
"(",
"path",
",",
"'glob'",
")",
":",
"pypaths",
"=",
"path",
".",
"glob",
"(",
"'*.py'",
... | load plugins from a directory
Parameters
----------
path : str or path_like
category : None or str
if str, apply for single plugin category
overwrite : bool
if True, allow existing plugins to be overwritten | [
"load",
"plugins",
"from",
"a",
"directory"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L318-L365 | train | 53,788 |
chrisjsewell/jsonextended | jsonextended/plugins.py | load_builtin_plugins | def load_builtin_plugins(category=None, overwrite=False):
"""load plugins from builtin directories
Parameters
----------
name: None or str
category : None or str
if str, apply for single plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
>>> errors = load_builtin_plugins()
>>> errors
[]
>>> pprint(view_plugins(),width=200)
{'decoders': {'decimal.Decimal': 'encode/decode Decimal type',
'fractions.Fraction': 'encode/decode Fraction type',
'numpy.ndarray': 'encode/decode numpy.ndarray',
'pint.Quantity': 'encode/decode pint.Quantity object',
'python.set': 'decode/encode python set'},
'encoders': {'decimal.Decimal': 'encode/decode Decimal type',
'fractions.Fraction': 'encode/decode Fraction type',
'numpy.ndarray': 'encode/decode numpy.ndarray',
'pint.Quantity': 'encode/decode pint.Quantity object',
'python.set': 'decode/encode python set'},
'parsers': {'csv.basic': 'read *.csv delimited file with headers to {header:[column_values]}',
'csv.literal': 'read *.literal.csv delimited files with headers to {header:column_values}, with number strings converted to int/float',
'hdf5.read': 'read *.hdf5 (in read mode) files using h5py',
'ipynb': 'read Jupyter Notebooks',
'json.basic': 'read *.json files using json.load',
'keypair': "read *.keypair, where each line should be; '<key> <pair>'",
'yaml.ruamel': 'read *.yaml files using ruamel.yaml'}}
>>> unload_all_plugins()
""" # noqa: E501
load_errors = []
for cat, path in _plugins_builtin.items():
if cat != category and category is not None:
continue
load_errors += load_plugins_dir(path, cat, overwrite=overwrite)
return load_errors | python | def load_builtin_plugins(category=None, overwrite=False):
"""load plugins from builtin directories
Parameters
----------
name: None or str
category : None or str
if str, apply for single plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
>>> errors = load_builtin_plugins()
>>> errors
[]
>>> pprint(view_plugins(),width=200)
{'decoders': {'decimal.Decimal': 'encode/decode Decimal type',
'fractions.Fraction': 'encode/decode Fraction type',
'numpy.ndarray': 'encode/decode numpy.ndarray',
'pint.Quantity': 'encode/decode pint.Quantity object',
'python.set': 'decode/encode python set'},
'encoders': {'decimal.Decimal': 'encode/decode Decimal type',
'fractions.Fraction': 'encode/decode Fraction type',
'numpy.ndarray': 'encode/decode numpy.ndarray',
'pint.Quantity': 'encode/decode pint.Quantity object',
'python.set': 'decode/encode python set'},
'parsers': {'csv.basic': 'read *.csv delimited file with headers to {header:[column_values]}',
'csv.literal': 'read *.literal.csv delimited files with headers to {header:column_values}, with number strings converted to int/float',
'hdf5.read': 'read *.hdf5 (in read mode) files using h5py',
'ipynb': 'read Jupyter Notebooks',
'json.basic': 'read *.json files using json.load',
'keypair': "read *.keypair, where each line should be; '<key> <pair>'",
'yaml.ruamel': 'read *.yaml files using ruamel.yaml'}}
>>> unload_all_plugins()
""" # noqa: E501
load_errors = []
for cat, path in _plugins_builtin.items():
if cat != category and category is not None:
continue
load_errors += load_plugins_dir(path, cat, overwrite=overwrite)
return load_errors | [
"def",
"load_builtin_plugins",
"(",
"category",
"=",
"None",
",",
"overwrite",
"=",
"False",
")",
":",
"# noqa: E501",
"load_errors",
"=",
"[",
"]",
"for",
"cat",
",",
"path",
"in",
"_plugins_builtin",
".",
"items",
"(",
")",
":",
"if",
"cat",
"!=",
"cat... | load plugins from builtin directories
Parameters
----------
name: None or str
category : None or str
if str, apply for single plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
>>> errors = load_builtin_plugins()
>>> errors
[]
>>> pprint(view_plugins(),width=200)
{'decoders': {'decimal.Decimal': 'encode/decode Decimal type',
'fractions.Fraction': 'encode/decode Fraction type',
'numpy.ndarray': 'encode/decode numpy.ndarray',
'pint.Quantity': 'encode/decode pint.Quantity object',
'python.set': 'decode/encode python set'},
'encoders': {'decimal.Decimal': 'encode/decode Decimal type',
'fractions.Fraction': 'encode/decode Fraction type',
'numpy.ndarray': 'encode/decode numpy.ndarray',
'pint.Quantity': 'encode/decode pint.Quantity object',
'python.set': 'decode/encode python set'},
'parsers': {'csv.basic': 'read *.csv delimited file with headers to {header:[column_values]}',
'csv.literal': 'read *.literal.csv delimited files with headers to {header:column_values}, with number strings converted to int/float',
'hdf5.read': 'read *.hdf5 (in read mode) files using h5py',
'ipynb': 'read Jupyter Notebooks',
'json.basic': 'read *.json files using json.load',
'keypair': "read *.keypair, where each line should be; '<key> <pair>'",
'yaml.ruamel': 'read *.yaml files using ruamel.yaml'}}
>>> unload_all_plugins() | [
"load",
"plugins",
"from",
"builtin",
"directories"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L368-L416 | train | 53,789 |
chrisjsewell/jsonextended | jsonextended/plugins.py | encode | def encode(obj, outtype='json', raise_error=False):
""" encode objects, via encoder plugins, to new types
Parameters
----------
outtype: str
use encoder method to_<outtype> to encode
raise_error : bool
if True, raise ValueError if no suitable plugin found
Examples
--------
>>> load_builtin_plugins('encoders')
[]
>>> from decimal import Decimal
>>> encode(Decimal('1.3425345'))
{'_python_Decimal_': '1.3425345'}
>>> encode(Decimal('1.3425345'),outtype='str')
'1.3425345'
>>> encode(set([1,2,3,4,4]))
{'_python_set_': [1, 2, 3, 4]}
>>> encode(set([1,2,3,4,4]),outtype='str')
'{1, 2, 3, 4}'
>>> unload_all_plugins()
"""
for encoder in get_plugins('encoders').values():
if (isinstance(obj, encoder.objclass)
and hasattr(encoder, 'to_{}'.format(outtype))):
return getattr(encoder, 'to_{}'.format(outtype))(obj)
break
if raise_error:
raise ValueError(
"No JSON serializer is available for"
"{0} (of type {1})".format(obj, type(obj)))
else:
return obj | python | def encode(obj, outtype='json', raise_error=False):
""" encode objects, via encoder plugins, to new types
Parameters
----------
outtype: str
use encoder method to_<outtype> to encode
raise_error : bool
if True, raise ValueError if no suitable plugin found
Examples
--------
>>> load_builtin_plugins('encoders')
[]
>>> from decimal import Decimal
>>> encode(Decimal('1.3425345'))
{'_python_Decimal_': '1.3425345'}
>>> encode(Decimal('1.3425345'),outtype='str')
'1.3425345'
>>> encode(set([1,2,3,4,4]))
{'_python_set_': [1, 2, 3, 4]}
>>> encode(set([1,2,3,4,4]),outtype='str')
'{1, 2, 3, 4}'
>>> unload_all_plugins()
"""
for encoder in get_plugins('encoders').values():
if (isinstance(obj, encoder.objclass)
and hasattr(encoder, 'to_{}'.format(outtype))):
return getattr(encoder, 'to_{}'.format(outtype))(obj)
break
if raise_error:
raise ValueError(
"No JSON serializer is available for"
"{0} (of type {1})".format(obj, type(obj)))
else:
return obj | [
"def",
"encode",
"(",
"obj",
",",
"outtype",
"=",
"'json'",
",",
"raise_error",
"=",
"False",
")",
":",
"for",
"encoder",
"in",
"get_plugins",
"(",
"'encoders'",
")",
".",
"values",
"(",
")",
":",
"if",
"(",
"isinstance",
"(",
"obj",
",",
"encoder",
... | encode objects, via encoder plugins, to new types
Parameters
----------
outtype: str
use encoder method to_<outtype> to encode
raise_error : bool
if True, raise ValueError if no suitable plugin found
Examples
--------
>>> load_builtin_plugins('encoders')
[]
>>> from decimal import Decimal
>>> encode(Decimal('1.3425345'))
{'_python_Decimal_': '1.3425345'}
>>> encode(Decimal('1.3425345'),outtype='str')
'1.3425345'
>>> encode(set([1,2,3,4,4]))
{'_python_set_': [1, 2, 3, 4]}
>>> encode(set([1,2,3,4,4]),outtype='str')
'{1, 2, 3, 4}'
>>> unload_all_plugins() | [
"encode",
"objects",
"via",
"encoder",
"plugins",
"to",
"new",
"types"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L419-L459 | train | 53,790 |
chrisjsewell/jsonextended | jsonextended/plugins.py | decode | def decode(dct, intype='json', raise_error=False):
""" decode dict objects, via decoder plugins, to new type
Parameters
----------
intype: str
use decoder method from_<intype> to encode
raise_error : bool
if True, raise ValueError if no suitable plugin found
Examples
--------
>>> load_builtin_plugins('decoders')
[]
>>> from decimal import Decimal
>>> decode({'_python_Decimal_':'1.3425345'})
Decimal('1.3425345')
>>> unload_all_plugins()
"""
for decoder in get_plugins('decoders').values():
if (set(list(decoder.dict_signature)).issubset(dct.keys())
and hasattr(decoder, 'from_{}'.format(intype))
and getattr(decoder, 'allow_other_keys', False)):
return getattr(decoder, 'from_{}'.format(intype))(dct)
break
elif (sorted(list(decoder.dict_signature)) == sorted(dct.keys())
and hasattr(decoder, 'from_{}'.format(intype))):
return getattr(decoder, 'from_{}'.format(intype))(dct)
break
if raise_error:
raise ValueError('no suitable plugin found for: {}'.format(dct))
else:
return dct | python | def decode(dct, intype='json', raise_error=False):
""" decode dict objects, via decoder plugins, to new type
Parameters
----------
intype: str
use decoder method from_<intype> to encode
raise_error : bool
if True, raise ValueError if no suitable plugin found
Examples
--------
>>> load_builtin_plugins('decoders')
[]
>>> from decimal import Decimal
>>> decode({'_python_Decimal_':'1.3425345'})
Decimal('1.3425345')
>>> unload_all_plugins()
"""
for decoder in get_plugins('decoders').values():
if (set(list(decoder.dict_signature)).issubset(dct.keys())
and hasattr(decoder, 'from_{}'.format(intype))
and getattr(decoder, 'allow_other_keys', False)):
return getattr(decoder, 'from_{}'.format(intype))(dct)
break
elif (sorted(list(decoder.dict_signature)) == sorted(dct.keys())
and hasattr(decoder, 'from_{}'.format(intype))):
return getattr(decoder, 'from_{}'.format(intype))(dct)
break
if raise_error:
raise ValueError('no suitable plugin found for: {}'.format(dct))
else:
return dct | [
"def",
"decode",
"(",
"dct",
",",
"intype",
"=",
"'json'",
",",
"raise_error",
"=",
"False",
")",
":",
"for",
"decoder",
"in",
"get_plugins",
"(",
"'decoders'",
")",
".",
"values",
"(",
")",
":",
"if",
"(",
"set",
"(",
"list",
"(",
"decoder",
".",
... | decode dict objects, via decoder plugins, to new type
Parameters
----------
intype: str
use decoder method from_<intype> to encode
raise_error : bool
if True, raise ValueError if no suitable plugin found
Examples
--------
>>> load_builtin_plugins('decoders')
[]
>>> from decimal import Decimal
>>> decode({'_python_Decimal_':'1.3425345'})
Decimal('1.3425345')
>>> unload_all_plugins() | [
"decode",
"dict",
"objects",
"via",
"decoder",
"plugins",
"to",
"new",
"type"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L462-L498 | train | 53,791 |
chrisjsewell/jsonextended | jsonextended/plugins.py | parser_available | def parser_available(fpath):
""" test if parser plugin available for fpath
Examples
--------
>>> load_builtin_plugins('parsers')
[]
>>> test_file = StringIO('{"a":[1,2,3.4]}')
>>> test_file.name = 'test.json'
>>> parser_available(test_file)
True
>>> test_file.name = 'test.other'
>>> parser_available(test_file)
False
>>> unload_all_plugins()
"""
if isinstance(fpath, basestring):
fname = fpath
elif hasattr(fpath, 'open') and hasattr(fpath, 'name'):
fname = fpath.name
elif hasattr(fpath, 'readline') and hasattr(fpath, 'name'):
fname = fpath.name
else:
raise ValueError(
'fpath should be a str or file_like object: {}'.format(fpath))
for parser in get_plugins('parsers').values():
if fnmatch(fname, parser.file_regex):
return True
return False | python | def parser_available(fpath):
""" test if parser plugin available for fpath
Examples
--------
>>> load_builtin_plugins('parsers')
[]
>>> test_file = StringIO('{"a":[1,2,3.4]}')
>>> test_file.name = 'test.json'
>>> parser_available(test_file)
True
>>> test_file.name = 'test.other'
>>> parser_available(test_file)
False
>>> unload_all_plugins()
"""
if isinstance(fpath, basestring):
fname = fpath
elif hasattr(fpath, 'open') and hasattr(fpath, 'name'):
fname = fpath.name
elif hasattr(fpath, 'readline') and hasattr(fpath, 'name'):
fname = fpath.name
else:
raise ValueError(
'fpath should be a str or file_like object: {}'.format(fpath))
for parser in get_plugins('parsers').values():
if fnmatch(fname, parser.file_regex):
return True
return False | [
"def",
"parser_available",
"(",
"fpath",
")",
":",
"if",
"isinstance",
"(",
"fpath",
",",
"basestring",
")",
":",
"fname",
"=",
"fpath",
"elif",
"hasattr",
"(",
"fpath",
",",
"'open'",
")",
"and",
"hasattr",
"(",
"fpath",
",",
"'name'",
")",
":",
"fnam... | test if parser plugin available for fpath
Examples
--------
>>> load_builtin_plugins('parsers')
[]
>>> test_file = StringIO('{"a":[1,2,3.4]}')
>>> test_file.name = 'test.json'
>>> parser_available(test_file)
True
>>> test_file.name = 'test.other'
>>> parser_available(test_file)
False
>>> unload_all_plugins() | [
"test",
"if",
"parser",
"plugin",
"available",
"for",
"fpath"
] | c3a7a880cc09789b3c61204265dcbb127be76c8a | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L501-L534 | train | 53,792 |
portfoliome/foil | foil/fileio.py | DelimitedReader.from_zipfile | def from_zipfile(cls, path, filename, encoding, dialect, fields, converters):
"""Read delimited text from zipfile."""
stream = ZipReader(path, filename).readlines(encoding)
return cls(stream, dialect, fields, converters) | python | def from_zipfile(cls, path, filename, encoding, dialect, fields, converters):
"""Read delimited text from zipfile."""
stream = ZipReader(path, filename).readlines(encoding)
return cls(stream, dialect, fields, converters) | [
"def",
"from_zipfile",
"(",
"cls",
",",
"path",
",",
"filename",
",",
"encoding",
",",
"dialect",
",",
"fields",
",",
"converters",
")",
":",
"stream",
"=",
"ZipReader",
"(",
"path",
",",
"filename",
")",
".",
"readlines",
"(",
"encoding",
")",
"return",... | Read delimited text from zipfile. | [
"Read",
"delimited",
"text",
"from",
"zipfile",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/fileio.py#L77-L81 | train | 53,793 |
portfoliome/foil | foil/fileio.py | DelimitedSubsetReader.from_file | def from_file(cls, path, encoding, dialect, fields, converters, field_index):
"""Read delimited text from a text file."""
return cls(open(path, 'r', encoding=encoding), dialect, fields, converters, field_index) | python | def from_file(cls, path, encoding, dialect, fields, converters, field_index):
"""Read delimited text from a text file."""
return cls(open(path, 'r', encoding=encoding), dialect, fields, converters, field_index) | [
"def",
"from_file",
"(",
"cls",
",",
"path",
",",
"encoding",
",",
"dialect",
",",
"fields",
",",
"converters",
",",
"field_index",
")",
":",
"return",
"cls",
"(",
"open",
"(",
"path",
",",
"'r'",
",",
"encoding",
"=",
"encoding",
")",
",",
"dialect",
... | Read delimited text from a text file. | [
"Read",
"delimited",
"text",
"from",
"a",
"text",
"file",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/fileio.py#L125-L128 | train | 53,794 |
portfoliome/foil | foil/fileio.py | ZipReader.read_bytes | def read_bytes(self):
"""Read content into byte string."""
with ZipFile(self.path, mode='r') as archive:
return archive.read(self.filename) | python | def read_bytes(self):
"""Read content into byte string."""
with ZipFile(self.path, mode='r') as archive:
return archive.read(self.filename) | [
"def",
"read_bytes",
"(",
"self",
")",
":",
"with",
"ZipFile",
"(",
"self",
".",
"path",
",",
"mode",
"=",
"'r'",
")",
"as",
"archive",
":",
"return",
"archive",
".",
"read",
"(",
"self",
".",
"filename",
")"
] | Read content into byte string. | [
"Read",
"content",
"into",
"byte",
"string",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/fileio.py#L156-L160 | train | 53,795 |
portfoliome/foil | foil/fileio.py | ZipReader.readlines_bytes | def readlines_bytes(self):
"""Read content into byte str line iterator."""
with open_zipfile_archive(self.path, self.filename) as file:
for line in file:
yield line.rstrip(b'\r\n') | python | def readlines_bytes(self):
"""Read content into byte str line iterator."""
with open_zipfile_archive(self.path, self.filename) as file:
for line in file:
yield line.rstrip(b'\r\n') | [
"def",
"readlines_bytes",
"(",
"self",
")",
":",
"with",
"open_zipfile_archive",
"(",
"self",
".",
"path",
",",
"self",
".",
"filename",
")",
"as",
"file",
":",
"for",
"line",
"in",
"file",
":",
"yield",
"line",
".",
"rstrip",
"(",
"b'\\r\\n'",
")"
] | Read content into byte str line iterator. | [
"Read",
"content",
"into",
"byte",
"str",
"line",
"iterator",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/fileio.py#L167-L172 | train | 53,796 |
Capitains/Nautilus | capitains_nautilus/cts/resolver/base.py | ProtoNautilusCtsResolver.xmlparse | def xmlparse(self, file):
""" Parse a XML file
:param file: Opened File
:return: Tree
"""
if self.CACHE_FULL_TEI is True:
return self.get_or(
_cache_key("Nautilus", self.name, "File", "Tree", file.name),
super(ProtoNautilusCtsResolver, self).xmlparse, file
)
return super(ProtoNautilusCtsResolver, self).xmlparse(file) | python | def xmlparse(self, file):
""" Parse a XML file
:param file: Opened File
:return: Tree
"""
if self.CACHE_FULL_TEI is True:
return self.get_or(
_cache_key("Nautilus", self.name, "File", "Tree", file.name),
super(ProtoNautilusCtsResolver, self).xmlparse, file
)
return super(ProtoNautilusCtsResolver, self).xmlparse(file) | [
"def",
"xmlparse",
"(",
"self",
",",
"file",
")",
":",
"if",
"self",
".",
"CACHE_FULL_TEI",
"is",
"True",
":",
"return",
"self",
".",
"get_or",
"(",
"_cache_key",
"(",
"\"Nautilus\"",
",",
"self",
".",
"name",
",",
"\"File\"",
",",
"\"Tree\"",
",",
"fi... | Parse a XML file
:param file: Opened File
:return: Tree | [
"Parse",
"a",
"XML",
"file"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L48-L59 | train | 53,797 |
Capitains/Nautilus | capitains_nautilus/cts/resolver/base.py | ProtoNautilusCtsResolver.get_or | def get_or(self, cache_key, callback, *args, **kwargs):
""" Get or set the cache using callback and arguments
:param cache_key: Cache key for given resource
:param callback: Callback if object does not exist
:param args: Ordered Argument for the callback
:param kwargs: Keyword argument for the callback
:return: Output of the callback
"""
cached = self.cache.get(cache_key)
if cached is not None:
return cached
else:
try:
output = callback(*args, **kwargs)
except MyCapytain.errors.UnknownCollection as E:
raise UnknownCollection(str(E))
except Exception as E:
raise E
self.cache.set(cache_key, output, self.TIMEOUT)
return output | python | def get_or(self, cache_key, callback, *args, **kwargs):
""" Get or set the cache using callback and arguments
:param cache_key: Cache key for given resource
:param callback: Callback if object does not exist
:param args: Ordered Argument for the callback
:param kwargs: Keyword argument for the callback
:return: Output of the callback
"""
cached = self.cache.get(cache_key)
if cached is not None:
return cached
else:
try:
output = callback(*args, **kwargs)
except MyCapytain.errors.UnknownCollection as E:
raise UnknownCollection(str(E))
except Exception as E:
raise E
self.cache.set(cache_key, output, self.TIMEOUT)
return output | [
"def",
"get_or",
"(",
"self",
",",
"cache_key",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cached",
"=",
"self",
".",
"cache",
".",
"get",
"(",
"cache_key",
")",
"if",
"cached",
"is",
"not",
"None",
":",
"return",
"cache... | Get or set the cache using callback and arguments
:param cache_key: Cache key for given resource
:param callback: Callback if object does not exist
:param args: Ordered Argument for the callback
:param kwargs: Keyword argument for the callback
:return: Output of the callback | [
"Get",
"or",
"set",
"the",
"cache",
"using",
"callback",
"and",
"arguments"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L61-L81 | train | 53,798 |
Capitains/Nautilus | capitains_nautilus/cts/resolver/base.py | ProtoNautilusCtsResolver.read | def read(self, identifier, path=None):
""" Read a text object given an identifier and a path
:param identifier: Identifier of the text
:param path: Path of the text files
:return: Text
"""
if self.CACHE_FULL_TEI is True:
o = self.cache.get(_cache_key(self.texts_parsed_cache_key, identifier))
if o is not None:
return o
else:
with open(path) as f:
o = Text(urn=identifier, resource=self.xmlparse(f))
self.cache.set(_cache_key(self.texts_parsed_cache_key, identifier), o)
else:
with open(path) as f:
o = Text(urn=identifier, resource=self.xmlparse(f))
return o | python | def read(self, identifier, path=None):
""" Read a text object given an identifier and a path
:param identifier: Identifier of the text
:param path: Path of the text files
:return: Text
"""
if self.CACHE_FULL_TEI is True:
o = self.cache.get(_cache_key(self.texts_parsed_cache_key, identifier))
if o is not None:
return o
else:
with open(path) as f:
o = Text(urn=identifier, resource=self.xmlparse(f))
self.cache.set(_cache_key(self.texts_parsed_cache_key, identifier), o)
else:
with open(path) as f:
o = Text(urn=identifier, resource=self.xmlparse(f))
return o | [
"def",
"read",
"(",
"self",
",",
"identifier",
",",
"path",
"=",
"None",
")",
":",
"if",
"self",
".",
"CACHE_FULL_TEI",
"is",
"True",
":",
"o",
"=",
"self",
".",
"cache",
".",
"get",
"(",
"_cache_key",
"(",
"self",
".",
"texts_parsed_cache_key",
",",
... | Read a text object given an identifier and a path
:param identifier: Identifier of the text
:param path: Path of the text files
:return: Text | [
"Read",
"a",
"text",
"object",
"given",
"an",
"identifier",
"and",
"a",
"path"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L83-L101 | train | 53,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.