repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
fossasia/AYABInterface | AYABInterface/communication/states.py | State._next | def _next(self, state_class, *args):
"""Transition into the next state.
:param type state_class: a subclass of :class:`State`. It is intialized
with the communication object and :paramref:`args`
:param args: additional arguments
"""
self._communication.state = state_class(self._communication, *args) | python | def _next(self, state_class, *args):
"""Transition into the next state.
:param type state_class: a subclass of :class:`State`. It is intialized
with the communication object and :paramref:`args`
:param args: additional arguments
"""
self._communication.state = state_class(self._communication, *args) | [
"def",
"_next",
"(",
"self",
",",
"state_class",
",",
"*",
"args",
")",
":",
"self",
".",
"_communication",
".",
"state",
"=",
"state_class",
"(",
"self",
".",
"_communication",
",",
"*",
"args",
")"
] | Transition into the next state.
:param type state_class: a subclass of :class:`State`. It is intialized
with the communication object and :paramref:`args`
:param args: additional arguments | [
"Transition",
"into",
"the",
"next",
"state",
"."
] | train | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/communication/states.py#L186-L193 |
fossasia/AYABInterface | AYABInterface/communication/states.py | InitialHandshake.receive_information_confirmation | def receive_information_confirmation(self, message):
"""A InformationConfirmation is received.
If :meth:`the api version is supported
<AYABInterface.communication.Communication.api_version_is_supported>`,
the communication object transitions into a
:class:`InitializingMachine`, if unsupported, into a
:class:`UnsupportedApiVersion`
"""
if message.api_version_is_supported():
self._next(InitializingMachine)
else:
self._next(UnsupportedApiVersion)
self._communication.controller = message | python | def receive_information_confirmation(self, message):
"""A InformationConfirmation is received.
If :meth:`the api version is supported
<AYABInterface.communication.Communication.api_version_is_supported>`,
the communication object transitions into a
:class:`InitializingMachine`, if unsupported, into a
:class:`UnsupportedApiVersion`
"""
if message.api_version_is_supported():
self._next(InitializingMachine)
else:
self._next(UnsupportedApiVersion)
self._communication.controller = message | [
"def",
"receive_information_confirmation",
"(",
"self",
",",
"message",
")",
":",
"if",
"message",
".",
"api_version_is_supported",
"(",
")",
":",
"self",
".",
"_next",
"(",
"InitializingMachine",
")",
"else",
":",
"self",
".",
"_next",
"(",
"UnsupportedApiVersion",
")",
"self",
".",
"_communication",
".",
"controller",
"=",
"message"
] | A InformationConfirmation is received.
If :meth:`the api version is supported
<AYABInterface.communication.Communication.api_version_is_supported>`,
the communication object transitions into a
:class:`InitializingMachine`, if unsupported, into a
:class:`UnsupportedApiVersion` | [
"A",
"InformationConfirmation",
"is",
"received",
"."
] | train | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/communication/states.py#L316-L330 |
fossasia/AYABInterface | AYABInterface/communication/states.py | StartingToKnit.receive_start_confirmation | def receive_start_confirmation(self, message):
"""Receive a StartConfirmation message.
:param message: a :class:`StartConfirmation
<AYABInterface.communication.hardware_messages.StartConfirmation>`
message
If the message indicates success, the communication object transitions
into :class:`KnittingStarted` or else, into :class:`StartingFailed`.
"""
if message.is_success():
self._next(KnittingStarted)
else:
self._next(StartingFailed) | python | def receive_start_confirmation(self, message):
"""Receive a StartConfirmation message.
:param message: a :class:`StartConfirmation
<AYABInterface.communication.hardware_messages.StartConfirmation>`
message
If the message indicates success, the communication object transitions
into :class:`KnittingStarted` or else, into :class:`StartingFailed`.
"""
if message.is_success():
self._next(KnittingStarted)
else:
self._next(StartingFailed) | [
"def",
"receive_start_confirmation",
"(",
"self",
",",
"message",
")",
":",
"if",
"message",
".",
"is_success",
"(",
")",
":",
"self",
".",
"_next",
"(",
"KnittingStarted",
")",
"else",
":",
"self",
".",
"_next",
"(",
"StartingFailed",
")"
] | Receive a StartConfirmation message.
:param message: a :class:`StartConfirmation
<AYABInterface.communication.hardware_messages.StartConfirmation>`
message
If the message indicates success, the communication object transitions
into :class:`KnittingStarted` or else, into :class:`StartingFailed`. | [
"Receive",
"a",
"StartConfirmation",
"message",
"."
] | train | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/communication/states.py#L418-L431 |
fossasia/AYABInterface | AYABInterface/communication/states.py | StartingToKnit.enter | def enter(self):
"""Send a StartRequest."""
self._communication.send(StartRequest,
self._communication.left_end_needle,
self._communication.right_end_needle) | python | def enter(self):
"""Send a StartRequest."""
self._communication.send(StartRequest,
self._communication.left_end_needle,
self._communication.right_end_needle) | [
"def",
"enter",
"(",
"self",
")",
":",
"self",
".",
"_communication",
".",
"send",
"(",
"StartRequest",
",",
"self",
".",
"_communication",
".",
"left_end_needle",
",",
"self",
".",
"_communication",
".",
"right_end_needle",
")"
] | Send a StartRequest. | [
"Send",
"a",
"StartRequest",
"."
] | train | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/communication/states.py#L441-L445 |
fossasia/AYABInterface | AYABInterface/communication/states.py | KnittingLine.enter | def enter(self):
"""Send a LineConfirmation to the controller.
When this state is entered, a
:class:`AYABInterface.communication.host_messages.LineConfirmation`
is sent to the controller.
Also, the :attr:`last line requested
<AYABInterface.communication.Communication.last_requested_line_number>`
is set.
"""
self._communication.last_requested_line_number = self._line_number
self._communication.send(LineConfirmation, self._line_number) | python | def enter(self):
"""Send a LineConfirmation to the controller.
When this state is entered, a
:class:`AYABInterface.communication.host_messages.LineConfirmation`
is sent to the controller.
Also, the :attr:`last line requested
<AYABInterface.communication.Communication.last_requested_line_number>`
is set.
"""
self._communication.last_requested_line_number = self._line_number
self._communication.send(LineConfirmation, self._line_number) | [
"def",
"enter",
"(",
"self",
")",
":",
"self",
".",
"_communication",
".",
"last_requested_line_number",
"=",
"self",
".",
"_line_number",
"self",
".",
"_communication",
".",
"send",
"(",
"LineConfirmation",
",",
"self",
".",
"_line_number",
")"
] | Send a LineConfirmation to the controller.
When this state is entered, a
:class:`AYABInterface.communication.host_messages.LineConfirmation`
is sent to the controller.
Also, the :attr:`last line requested
<AYABInterface.communication.Communication.last_requested_line_number>`
is set. | [
"Send",
"a",
"LineConfirmation",
"to",
"the",
"controller",
"."
] | train | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/communication/states.py#L502-L513 |
fossasia/AYABInterface | AYABInterface/convert/__init__.py | colors_to_needle_positions | def colors_to_needle_positions(rows):
"""Convert rows to needle positions.
:return:
:rtype: list
"""
needles = []
for row in rows:
colors = set(row)
if len(colors) == 1:
needles.append([NeedlePositions(row, tuple(colors), False)])
elif len(colors) == 2:
color1, color2 = colors
if color1 != row[0]:
color1, color2 = color2, color1
needles_ = _row_color(row, color1)
needles.append([NeedlePositions(needles_, (color1, color2), True)])
else:
colors = []
for color in row:
if color not in colors:
colors.append(color)
needles_ = []
for color in colors:
needles_.append(NeedlePositions(_row_color(row, color),
(color,), False))
needles.append(needles_)
return needles | python | def colors_to_needle_positions(rows):
"""Convert rows to needle positions.
:return:
:rtype: list
"""
needles = []
for row in rows:
colors = set(row)
if len(colors) == 1:
needles.append([NeedlePositions(row, tuple(colors), False)])
elif len(colors) == 2:
color1, color2 = colors
if color1 != row[0]:
color1, color2 = color2, color1
needles_ = _row_color(row, color1)
needles.append([NeedlePositions(needles_, (color1, color2), True)])
else:
colors = []
for color in row:
if color not in colors:
colors.append(color)
needles_ = []
for color in colors:
needles_.append(NeedlePositions(_row_color(row, color),
(color,), False))
needles.append(needles_)
return needles | [
"def",
"colors_to_needle_positions",
"(",
"rows",
")",
":",
"needles",
"=",
"[",
"]",
"for",
"row",
"in",
"rows",
":",
"colors",
"=",
"set",
"(",
"row",
")",
"if",
"len",
"(",
"colors",
")",
"==",
"1",
":",
"needles",
".",
"append",
"(",
"[",
"NeedlePositions",
"(",
"row",
",",
"tuple",
"(",
"colors",
")",
",",
"False",
")",
"]",
")",
"elif",
"len",
"(",
"colors",
")",
"==",
"2",
":",
"color1",
",",
"color2",
"=",
"colors",
"if",
"color1",
"!=",
"row",
"[",
"0",
"]",
":",
"color1",
",",
"color2",
"=",
"color2",
",",
"color1",
"needles_",
"=",
"_row_color",
"(",
"row",
",",
"color1",
")",
"needles",
".",
"append",
"(",
"[",
"NeedlePositions",
"(",
"needles_",
",",
"(",
"color1",
",",
"color2",
")",
",",
"True",
")",
"]",
")",
"else",
":",
"colors",
"=",
"[",
"]",
"for",
"color",
"in",
"row",
":",
"if",
"color",
"not",
"in",
"colors",
":",
"colors",
".",
"append",
"(",
"color",
")",
"needles_",
"=",
"[",
"]",
"for",
"color",
"in",
"colors",
":",
"needles_",
".",
"append",
"(",
"NeedlePositions",
"(",
"_row_color",
"(",
"row",
",",
"color",
")",
",",
"(",
"color",
",",
")",
",",
"False",
")",
")",
"needles",
".",
"append",
"(",
"needles_",
")",
"return",
"needles"
] | Convert rows to needle positions.
:return:
:rtype: list | [
"Convert",
"rows",
"to",
"needle",
"positions",
"."
] | train | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/convert/__init__.py#L12-L39 |
fossasia/AYABInterface | AYABInterface/needle_positions.py | NeedlePositions.check | def check(self):
"""Check for validity.
:raises ValueError:
- if not all lines are as long as the :attr:`number of needles
<AYABInterface.machines.Machine.number_of_needles>`
- if the contents of the rows are not :attr:`needle positions
<AYABInterface.machines.Machine.needle_positions>`
"""
# TODO: This violates the law of demeter.
# The architecture should be changed that this check is either
# performed by the machine or by the unity of machine and
# carriage.
expected_positions = self._machine.needle_positions
expected_row_length = self._machine.number_of_needles
for row_index, row in enumerate(self._rows):
if len(row) != expected_row_length:
message = _ROW_LENGTH_ERROR_MESSAGE.format(
row_index, len(row), expected_row_length)
raise ValueError(message)
for needle_index, needle_position in enumerate(row):
if needle_position not in expected_positions:
message = _NEEDLE_POSITION_ERROR_MESSAGE.format(
row_index, needle_index, repr(needle_position),
", ".join(map(repr, expected_positions)))
raise ValueError(message) | python | def check(self):
"""Check for validity.
:raises ValueError:
- if not all lines are as long as the :attr:`number of needles
<AYABInterface.machines.Machine.number_of_needles>`
- if the contents of the rows are not :attr:`needle positions
<AYABInterface.machines.Machine.needle_positions>`
"""
# TODO: This violates the law of demeter.
# The architecture should be changed that this check is either
# performed by the machine or by the unity of machine and
# carriage.
expected_positions = self._machine.needle_positions
expected_row_length = self._machine.number_of_needles
for row_index, row in enumerate(self._rows):
if len(row) != expected_row_length:
message = _ROW_LENGTH_ERROR_MESSAGE.format(
row_index, len(row), expected_row_length)
raise ValueError(message)
for needle_index, needle_position in enumerate(row):
if needle_position not in expected_positions:
message = _NEEDLE_POSITION_ERROR_MESSAGE.format(
row_index, needle_index, repr(needle_position),
", ".join(map(repr, expected_positions)))
raise ValueError(message) | [
"def",
"check",
"(",
"self",
")",
":",
"# TODO: This violates the law of demeter.",
"# The architecture should be changed that this check is either",
"# performed by the machine or by the unity of machine and",
"# carriage.",
"expected_positions",
"=",
"self",
".",
"_machine",
".",
"needle_positions",
"expected_row_length",
"=",
"self",
".",
"_machine",
".",
"number_of_needles",
"for",
"row_index",
",",
"row",
"in",
"enumerate",
"(",
"self",
".",
"_rows",
")",
":",
"if",
"len",
"(",
"row",
")",
"!=",
"expected_row_length",
":",
"message",
"=",
"_ROW_LENGTH_ERROR_MESSAGE",
".",
"format",
"(",
"row_index",
",",
"len",
"(",
"row",
")",
",",
"expected_row_length",
")",
"raise",
"ValueError",
"(",
"message",
")",
"for",
"needle_index",
",",
"needle_position",
"in",
"enumerate",
"(",
"row",
")",
":",
"if",
"needle_position",
"not",
"in",
"expected_positions",
":",
"message",
"=",
"_NEEDLE_POSITION_ERROR_MESSAGE",
".",
"format",
"(",
"row_index",
",",
"needle_index",
",",
"repr",
"(",
"needle_position",
")",
",",
"\", \"",
".",
"join",
"(",
"map",
"(",
"repr",
",",
"expected_positions",
")",
")",
")",
"raise",
"ValueError",
"(",
"message",
")"
] | Check for validity.
:raises ValueError:
- if not all lines are as long as the :attr:`number of needles
<AYABInterface.machines.Machine.number_of_needles>`
- if the contents of the rows are not :attr:`needle positions
<AYABInterface.machines.Machine.needle_positions>` | [
"Check",
"for",
"validity",
"."
] | train | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/needle_positions.py#L26-L52 |
fossasia/AYABInterface | AYABInterface/needle_positions.py | NeedlePositions.get_row | def get_row(self, index, default=None):
"""Return the row at the given index or the default value."""
if not isinstance(index, int) or index < 0 or index >= len(self._rows):
return default
return self._rows[index] | python | def get_row(self, index, default=None):
"""Return the row at the given index or the default value."""
if not isinstance(index, int) or index < 0 or index >= len(self._rows):
return default
return self._rows[index] | [
"def",
"get_row",
"(",
"self",
",",
"index",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"index",
",",
"int",
")",
"or",
"index",
"<",
"0",
"or",
"index",
">=",
"len",
"(",
"self",
".",
"_rows",
")",
":",
"return",
"default",
"return",
"self",
".",
"_rows",
"[",
"index",
"]"
] | Return the row at the given index or the default value. | [
"Return",
"the",
"row",
"at",
"the",
"given",
"index",
"or",
"the",
"default",
"value",
"."
] | train | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/needle_positions.py#L61-L65 |
fossasia/AYABInterface | AYABInterface/needle_positions.py | NeedlePositions.row_completed | def row_completed(self, index):
"""Mark the row at index as completed.
.. seealso:: :meth:`completed_row_indices`
This method notifies the obsevrers from :meth:`on_row_completed`.
"""
self._completed_rows.append(index)
for row_completed in self._on_row_completed:
row_completed(index) | python | def row_completed(self, index):
"""Mark the row at index as completed.
.. seealso:: :meth:`completed_row_indices`
This method notifies the obsevrers from :meth:`on_row_completed`.
"""
self._completed_rows.append(index)
for row_completed in self._on_row_completed:
row_completed(index) | [
"def",
"row_completed",
"(",
"self",
",",
"index",
")",
":",
"self",
".",
"_completed_rows",
".",
"append",
"(",
"index",
")",
"for",
"row_completed",
"in",
"self",
".",
"_on_row_completed",
":",
"row_completed",
"(",
"index",
")"
] | Mark the row at index as completed.
.. seealso:: :meth:`completed_row_indices`
This method notifies the obsevrers from :meth:`on_row_completed`. | [
"Mark",
"the",
"row",
"at",
"index",
"as",
"completed",
"."
] | train | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/needle_positions.py#L67-L76 |
fossasia/AYABInterface | AYABInterface/interaction.py | Interaction.communicate_through | def communicate_through(self, file):
"""Setup communication through a file.
:rtype: AYABInterface.communication.Communication
"""
if self._communication is not None:
raise ValueError("Already communicating.")
self._communication = communication = Communication(
file, self._get_needle_positions,
self._machine, [self._on_message_received],
right_end_needle=self.right_end_needle,
left_end_needle=self.left_end_needle)
return communication | python | def communicate_through(self, file):
"""Setup communication through a file.
:rtype: AYABInterface.communication.Communication
"""
if self._communication is not None:
raise ValueError("Already communicating.")
self._communication = communication = Communication(
file, self._get_needle_positions,
self._machine, [self._on_message_received],
right_end_needle=self.right_end_needle,
left_end_needle=self.left_end_needle)
return communication | [
"def",
"communicate_through",
"(",
"self",
",",
"file",
")",
":",
"if",
"self",
".",
"_communication",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Already communicating.\"",
")",
"self",
".",
"_communication",
"=",
"communication",
"=",
"Communication",
"(",
"file",
",",
"self",
".",
"_get_needle_positions",
",",
"self",
".",
"_machine",
",",
"[",
"self",
".",
"_on_message_received",
"]",
",",
"right_end_needle",
"=",
"self",
".",
"right_end_needle",
",",
"left_end_needle",
"=",
"self",
".",
"left_end_needle",
")",
"return",
"communication"
] | Setup communication through a file.
:rtype: AYABInterface.communication.Communication | [
"Setup",
"communication",
"through",
"a",
"file",
"."
] | train | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/interaction.py#L47-L59 |
fossasia/AYABInterface | AYABInterface/interaction.py | Interaction.actions | def actions(self):
"""A list of actions to perform.
:return: a list of :class:`AYABInterface.actions.Action`
"""
actions = []
do = actions.append
# determine the number of colors
colors = self.colors
# rows and colors
movements = (
MoveCarriageToTheRight(KnitCarriage()),
MoveCarriageToTheLeft(KnitCarriage()))
rows = self._rows
first_needles = self._get_row_needles(0)
# handle switches
if len(colors) == 1:
actions.extend([
SwitchOffMachine(),
SwitchCarriageToModeNl()])
else:
actions.extend([
SwitchCarriageToModeKc(),
SwitchOnMachine()])
# move needles
do(MoveNeedlesIntoPosition("B", first_needles))
do(MoveCarriageOverLeftHallSensor())
# use colors
if len(colors) == 1:
do(PutColorInNutA(colors[0]))
if len(colors) == 2:
do(PutColorInNutA(colors[0]))
do(PutColorInNutB(colors[1]))
# knit
for index, row in enumerate(rows):
do(movements[index & 1])
return actions | python | def actions(self):
"""A list of actions to perform.
:return: a list of :class:`AYABInterface.actions.Action`
"""
actions = []
do = actions.append
# determine the number of colors
colors = self.colors
# rows and colors
movements = (
MoveCarriageToTheRight(KnitCarriage()),
MoveCarriageToTheLeft(KnitCarriage()))
rows = self._rows
first_needles = self._get_row_needles(0)
# handle switches
if len(colors) == 1:
actions.extend([
SwitchOffMachine(),
SwitchCarriageToModeNl()])
else:
actions.extend([
SwitchCarriageToModeKc(),
SwitchOnMachine()])
# move needles
do(MoveNeedlesIntoPosition("B", first_needles))
do(MoveCarriageOverLeftHallSensor())
# use colors
if len(colors) == 1:
do(PutColorInNutA(colors[0]))
if len(colors) == 2:
do(PutColorInNutA(colors[0]))
do(PutColorInNutB(colors[1]))
# knit
for index, row in enumerate(rows):
do(movements[index & 1])
return actions | [
"def",
"actions",
"(",
"self",
")",
":",
"actions",
"=",
"[",
"]",
"do",
"=",
"actions",
".",
"append",
"# determine the number of colors",
"colors",
"=",
"self",
".",
"colors",
"# rows and colors",
"movements",
"=",
"(",
"MoveCarriageToTheRight",
"(",
"KnitCarriage",
"(",
")",
")",
",",
"MoveCarriageToTheLeft",
"(",
"KnitCarriage",
"(",
")",
")",
")",
"rows",
"=",
"self",
".",
"_rows",
"first_needles",
"=",
"self",
".",
"_get_row_needles",
"(",
"0",
")",
"# handle switches",
"if",
"len",
"(",
"colors",
")",
"==",
"1",
":",
"actions",
".",
"extend",
"(",
"[",
"SwitchOffMachine",
"(",
")",
",",
"SwitchCarriageToModeNl",
"(",
")",
"]",
")",
"else",
":",
"actions",
".",
"extend",
"(",
"[",
"SwitchCarriageToModeKc",
"(",
")",
",",
"SwitchOnMachine",
"(",
")",
"]",
")",
"# move needles",
"do",
"(",
"MoveNeedlesIntoPosition",
"(",
"\"B\"",
",",
"first_needles",
")",
")",
"do",
"(",
"MoveCarriageOverLeftHallSensor",
"(",
")",
")",
"# use colors",
"if",
"len",
"(",
"colors",
")",
"==",
"1",
":",
"do",
"(",
"PutColorInNutA",
"(",
"colors",
"[",
"0",
"]",
")",
")",
"if",
"len",
"(",
"colors",
")",
"==",
"2",
":",
"do",
"(",
"PutColorInNutA",
"(",
"colors",
"[",
"0",
"]",
")",
")",
"do",
"(",
"PutColorInNutB",
"(",
"colors",
"[",
"1",
"]",
")",
")",
"# knit",
"for",
"index",
",",
"row",
"in",
"enumerate",
"(",
"rows",
")",
":",
"do",
"(",
"movements",
"[",
"index",
"&",
"1",
"]",
")",
"return",
"actions"
] | A list of actions to perform.
:return: a list of :class:`AYABInterface.actions.Action` | [
"A",
"list",
"of",
"actions",
"to",
"perform",
"."
] | train | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/interaction.py#L93-L135 |
fossasia/AYABInterface | AYABInterface/machines.py | Machine.needle_positions_to_bytes | def needle_positions_to_bytes(self, needle_positions):
"""Convert the needle positions to the wire format.
This conversion is used for :ref:`cnfline`.
:param needle_positions: an iterable over :attr:`needle_positions` of
length :attr:`number_of_needles`
:rtype: bytes
"""
bit = self.needle_positions
assert len(bit) == 2
max_length = len(needle_positions)
assert max_length == self.number_of_needles
result = []
for byte_index in range(0, max_length, 8):
byte = 0
for bit_index in range(8):
index = byte_index + bit_index
if index >= max_length:
break
needle_position = needle_positions[index]
if bit.index(needle_position) == 1:
byte |= 1 << bit_index
result.append(byte)
if byte_index >= max_length:
break
result.extend(b"\x00" * (25 - len(result)))
return bytes(result) | python | def needle_positions_to_bytes(self, needle_positions):
"""Convert the needle positions to the wire format.
This conversion is used for :ref:`cnfline`.
:param needle_positions: an iterable over :attr:`needle_positions` of
length :attr:`number_of_needles`
:rtype: bytes
"""
bit = self.needle_positions
assert len(bit) == 2
max_length = len(needle_positions)
assert max_length == self.number_of_needles
result = []
for byte_index in range(0, max_length, 8):
byte = 0
for bit_index in range(8):
index = byte_index + bit_index
if index >= max_length:
break
needle_position = needle_positions[index]
if bit.index(needle_position) == 1:
byte |= 1 << bit_index
result.append(byte)
if byte_index >= max_length:
break
result.extend(b"\x00" * (25 - len(result)))
return bytes(result) | [
"def",
"needle_positions_to_bytes",
"(",
"self",
",",
"needle_positions",
")",
":",
"bit",
"=",
"self",
".",
"needle_positions",
"assert",
"len",
"(",
"bit",
")",
"==",
"2",
"max_length",
"=",
"len",
"(",
"needle_positions",
")",
"assert",
"max_length",
"==",
"self",
".",
"number_of_needles",
"result",
"=",
"[",
"]",
"for",
"byte_index",
"in",
"range",
"(",
"0",
",",
"max_length",
",",
"8",
")",
":",
"byte",
"=",
"0",
"for",
"bit_index",
"in",
"range",
"(",
"8",
")",
":",
"index",
"=",
"byte_index",
"+",
"bit_index",
"if",
"index",
">=",
"max_length",
":",
"break",
"needle_position",
"=",
"needle_positions",
"[",
"index",
"]",
"if",
"bit",
".",
"index",
"(",
"needle_position",
")",
"==",
"1",
":",
"byte",
"|=",
"1",
"<<",
"bit_index",
"result",
".",
"append",
"(",
"byte",
")",
"if",
"byte_index",
">=",
"max_length",
":",
"break",
"result",
".",
"extend",
"(",
"b\"\\x00\"",
"*",
"(",
"25",
"-",
"len",
"(",
"result",
")",
")",
")",
"return",
"bytes",
"(",
"result",
")"
] | Convert the needle positions to the wire format.
This conversion is used for :ref:`cnfline`.
:param needle_positions: an iterable over :attr:`needle_positions` of
length :attr:`number_of_needles`
:rtype: bytes | [
"Convert",
"the",
"needle",
"positions",
"to",
"the",
"wire",
"format",
"."
] | train | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/machines.py#L105-L132 |
fossasia/AYABInterface | AYABInterface/machines.py | Machine.name | def name(self):
"""The identifier of the machine."""
name = self.__class__.__name__
for i, character in enumerate(name):
if character.isdigit():
return name[:i] + "-" + name[i:]
return name | python | def name(self):
"""The identifier of the machine."""
name = self.__class__.__name__
for i, character in enumerate(name):
if character.isdigit():
return name[:i] + "-" + name[i:]
return name | [
"def",
"name",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"__class__",
".",
"__name__",
"for",
"i",
",",
"character",
"in",
"enumerate",
"(",
"name",
")",
":",
"if",
"character",
".",
"isdigit",
"(",
")",
":",
"return",
"name",
"[",
":",
"i",
"]",
"+",
"\"-\"",
"+",
"name",
"[",
"i",
":",
"]",
"return",
"name"
] | The identifier of the machine. | [
"The",
"identifier",
"of",
"the",
"machine",
"."
] | train | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/machines.py#L135-L141 |
fossasia/AYABInterface | AYABInterface/machines.py | Machine._id | def _id(self):
"""What this object is equal to."""
return (self.__class__, self.number_of_needles, self.needle_positions,
self.left_end_needle) | python | def _id(self):
"""What this object is equal to."""
return (self.__class__, self.number_of_needles, self.needle_positions,
self.left_end_needle) | [
"def",
"_id",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"__class__",
",",
"self",
".",
"number_of_needles",
",",
"self",
".",
"needle_positions",
",",
"self",
".",
"left_end_needle",
")"
] | What this object is equal to. | [
"What",
"this",
"object",
"is",
"equal",
"to",
"."
] | train | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/machines.py#L144-L147 |
wcember/pypub | pypub/epub.py | Epub.add_chapter | def add_chapter(self, c):
"""
Add a Chapter to your epub.
Args:
c (Chapter): A Chapter object representing your chapter.
Raises:
TypeError: Raised if a Chapter object isn't supplied to this
method.
"""
try:
assert type(c) == chapter.Chapter
except AssertionError:
raise TypeError('chapter must be of type Chapter')
chapter_file_output = os.path.join(self.OEBPS_DIR, self.current_chapter_path)
c._replace_images_in_chapter(self.OEBPS_DIR)
c.write(chapter_file_output)
self._increase_current_chapter_number()
self.chapters.append(c) | python | def add_chapter(self, c):
"""
Add a Chapter to your epub.
Args:
c (Chapter): A Chapter object representing your chapter.
Raises:
TypeError: Raised if a Chapter object isn't supplied to this
method.
"""
try:
assert type(c) == chapter.Chapter
except AssertionError:
raise TypeError('chapter must be of type Chapter')
chapter_file_output = os.path.join(self.OEBPS_DIR, self.current_chapter_path)
c._replace_images_in_chapter(self.OEBPS_DIR)
c.write(chapter_file_output)
self._increase_current_chapter_number()
self.chapters.append(c) | [
"def",
"add_chapter",
"(",
"self",
",",
"c",
")",
":",
"try",
":",
"assert",
"type",
"(",
"c",
")",
"==",
"chapter",
".",
"Chapter",
"except",
"AssertionError",
":",
"raise",
"TypeError",
"(",
"'chapter must be of type Chapter'",
")",
"chapter_file_output",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"OEBPS_DIR",
",",
"self",
".",
"current_chapter_path",
")",
"c",
".",
"_replace_images_in_chapter",
"(",
"self",
".",
"OEBPS_DIR",
")",
"c",
".",
"write",
"(",
"chapter_file_output",
")",
"self",
".",
"_increase_current_chapter_number",
"(",
")",
"self",
".",
"chapters",
".",
"append",
"(",
"c",
")"
] | Add a Chapter to your epub.
Args:
c (Chapter): A Chapter object representing your chapter.
Raises:
TypeError: Raised if a Chapter object isn't supplied to this
method. | [
"Add",
"a",
"Chapter",
"to",
"your",
"epub",
"."
] | train | https://github.com/wcember/pypub/blob/88a1adc2ccf6f02c33adea1d2d52c729128216fb/pypub/epub.py#L219-L238 |
wcember/pypub | pypub/epub.py | Epub.create_epub | def create_epub(self, output_directory, epub_name=None):
"""
Create an epub file from this object.
Args:
output_directory (str): Directory to output the epub file to
epub_name (Option[str]): The file name of your epub. This should not contain
.epub at the end. If this argument is not provided, defaults to the title of the epub.
"""
def createTOCs_and_ContentOPF():
for epub_file, name in ((self.toc_html, 'toc.html'), (self.toc_ncx, 'toc.ncx'), (self.opf, 'content.opf'),):
epub_file.add_chapters(self.chapters)
epub_file.write(os.path.join(self.OEBPS_DIR, name))
def create_zip_archive(epub_name):
try:
assert isinstance(epub_name, basestring) or epub_name is None
except AssertionError:
raise TypeError('epub_name must be string or None')
if epub_name is None:
epub_name = self.title
epub_name = ''.join([c for c in epub_name if c.isalpha() or c.isdigit() or c == ' ']).rstrip()
epub_name_with_path = os.path.join(output_directory, epub_name)
try:
os.remove(os.path.join(epub_name_with_path, '.zip'))
except OSError:
pass
shutil.make_archive(epub_name_with_path, 'zip', self.EPUB_DIR)
return epub_name_with_path + '.zip'
def turn_zip_into_epub(zip_archive):
epub_full_name = zip_archive.strip('.zip') + '.epub'
try:
os.remove(epub_full_name)
except OSError:
pass
os.rename(zip_archive, epub_full_name)
return epub_full_name
createTOCs_and_ContentOPF()
epub_path = turn_zip_into_epub(create_zip_archive(epub_name))
return epub_path | python | def create_epub(self, output_directory, epub_name=None):
"""
Create an epub file from this object.
Args:
output_directory (str): Directory to output the epub file to
epub_name (Option[str]): The file name of your epub. This should not contain
.epub at the end. If this argument is not provided, defaults to the title of the epub.
"""
def createTOCs_and_ContentOPF():
for epub_file, name in ((self.toc_html, 'toc.html'), (self.toc_ncx, 'toc.ncx'), (self.opf, 'content.opf'),):
epub_file.add_chapters(self.chapters)
epub_file.write(os.path.join(self.OEBPS_DIR, name))
def create_zip_archive(epub_name):
try:
assert isinstance(epub_name, basestring) or epub_name is None
except AssertionError:
raise TypeError('epub_name must be string or None')
if epub_name is None:
epub_name = self.title
epub_name = ''.join([c for c in epub_name if c.isalpha() or c.isdigit() or c == ' ']).rstrip()
epub_name_with_path = os.path.join(output_directory, epub_name)
try:
os.remove(os.path.join(epub_name_with_path, '.zip'))
except OSError:
pass
shutil.make_archive(epub_name_with_path, 'zip', self.EPUB_DIR)
return epub_name_with_path + '.zip'
def turn_zip_into_epub(zip_archive):
epub_full_name = zip_archive.strip('.zip') + '.epub'
try:
os.remove(epub_full_name)
except OSError:
pass
os.rename(zip_archive, epub_full_name)
return epub_full_name
createTOCs_and_ContentOPF()
epub_path = turn_zip_into_epub(create_zip_archive(epub_name))
return epub_path | [
"def",
"create_epub",
"(",
"self",
",",
"output_directory",
",",
"epub_name",
"=",
"None",
")",
":",
"def",
"createTOCs_and_ContentOPF",
"(",
")",
":",
"for",
"epub_file",
",",
"name",
"in",
"(",
"(",
"self",
".",
"toc_html",
",",
"'toc.html'",
")",
",",
"(",
"self",
".",
"toc_ncx",
",",
"'toc.ncx'",
")",
",",
"(",
"self",
".",
"opf",
",",
"'content.opf'",
")",
",",
")",
":",
"epub_file",
".",
"add_chapters",
"(",
"self",
".",
"chapters",
")",
"epub_file",
".",
"write",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"OEBPS_DIR",
",",
"name",
")",
")",
"def",
"create_zip_archive",
"(",
"epub_name",
")",
":",
"try",
":",
"assert",
"isinstance",
"(",
"epub_name",
",",
"basestring",
")",
"or",
"epub_name",
"is",
"None",
"except",
"AssertionError",
":",
"raise",
"TypeError",
"(",
"'epub_name must be string or None'",
")",
"if",
"epub_name",
"is",
"None",
":",
"epub_name",
"=",
"self",
".",
"title",
"epub_name",
"=",
"''",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"epub_name",
"if",
"c",
".",
"isalpha",
"(",
")",
"or",
"c",
".",
"isdigit",
"(",
")",
"or",
"c",
"==",
"' '",
"]",
")",
".",
"rstrip",
"(",
")",
"epub_name_with_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_directory",
",",
"epub_name",
")",
"try",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"epub_name_with_path",
",",
"'.zip'",
")",
")",
"except",
"OSError",
":",
"pass",
"shutil",
".",
"make_archive",
"(",
"epub_name_with_path",
",",
"'zip'",
",",
"self",
".",
"EPUB_DIR",
")",
"return",
"epub_name_with_path",
"+",
"'.zip'",
"def",
"turn_zip_into_epub",
"(",
"zip_archive",
")",
":",
"epub_full_name",
"=",
"zip_archive",
".",
"strip",
"(",
"'.zip'",
")",
"+",
"'.epub'",
"try",
":",
"os",
".",
"remove",
"(",
"epub_full_name",
")",
"except",
"OSError",
":",
"pass",
"os",
".",
"rename",
"(",
"zip_archive",
",",
"epub_full_name",
")",
"return",
"epub_full_name",
"createTOCs_and_ContentOPF",
"(",
")",
"epub_path",
"=",
"turn_zip_into_epub",
"(",
"create_zip_archive",
"(",
"epub_name",
")",
")",
"return",
"epub_path"
] | Create an epub file from this object.
Args:
output_directory (str): Directory to output the epub file to
epub_name (Option[str]): The file name of your epub. This should not contain
.epub at the end. If this argument is not provided, defaults to the title of the epub. | [
"Create",
"an",
"epub",
"file",
"from",
"this",
"object",
"."
] | train | https://github.com/wcember/pypub/blob/88a1adc2ccf6f02c33adea1d2d52c729128216fb/pypub/epub.py#L240-L280 |
wcember/pypub | pypub/chapter.py | save_image | def save_image(image_url, image_directory, image_name):
"""
Saves an online image from image_url to image_directory with the name image_name.
Returns the extension of the image saved, which is determined dynamically.
Args:
image_url (str): The url of the image.
image_directory (str): The directory to save the image in.
image_name (str): The file name to save the image as.
Raises:
ImageErrorException: Raised if unable to save the image at image_url
"""
image_type = get_image_type(image_url)
if image_type is None:
raise ImageErrorException(image_url)
full_image_file_name = os.path.join(image_directory, image_name + '.' + image_type)
# If the image is present on the local filesystem just copy it
if os.path.exists(image_url):
shutil.copy(image_url, full_image_file_name)
return image_type
try:
# urllib.urlretrieve(image_url, full_image_file_name)
with open(full_image_file_name, 'wb') as f:
user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0'
request_headers = {'User-Agent': user_agent}
requests_object = requests.get(image_url, headers=request_headers)
try:
content = requests_object.content
# Check for empty response
f.write(content)
except AttributeError:
raise ImageErrorException(image_url)
except IOError:
raise ImageErrorException(image_url)
return image_type | python | def save_image(image_url, image_directory, image_name):
"""
Saves an online image from image_url to image_directory with the name image_name.
Returns the extension of the image saved, which is determined dynamically.
Args:
image_url (str): The url of the image.
image_directory (str): The directory to save the image in.
image_name (str): The file name to save the image as.
Raises:
ImageErrorException: Raised if unable to save the image at image_url
"""
image_type = get_image_type(image_url)
if image_type is None:
raise ImageErrorException(image_url)
full_image_file_name = os.path.join(image_directory, image_name + '.' + image_type)
# If the image is present on the local filesystem just copy it
if os.path.exists(image_url):
shutil.copy(image_url, full_image_file_name)
return image_type
try:
# urllib.urlretrieve(image_url, full_image_file_name)
with open(full_image_file_name, 'wb') as f:
user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0'
request_headers = {'User-Agent': user_agent}
requests_object = requests.get(image_url, headers=request_headers)
try:
content = requests_object.content
# Check for empty response
f.write(content)
except AttributeError:
raise ImageErrorException(image_url)
except IOError:
raise ImageErrorException(image_url)
return image_type | [
"def",
"save_image",
"(",
"image_url",
",",
"image_directory",
",",
"image_name",
")",
":",
"image_type",
"=",
"get_image_type",
"(",
"image_url",
")",
"if",
"image_type",
"is",
"None",
":",
"raise",
"ImageErrorException",
"(",
"image_url",
")",
"full_image_file_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"image_directory",
",",
"image_name",
"+",
"'.'",
"+",
"image_type",
")",
"# If the image is present on the local filesystem just copy it",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"image_url",
")",
":",
"shutil",
".",
"copy",
"(",
"image_url",
",",
"full_image_file_name",
")",
"return",
"image_type",
"try",
":",
"# urllib.urlretrieve(image_url, full_image_file_name)",
"with",
"open",
"(",
"full_image_file_name",
",",
"'wb'",
")",
"as",
"f",
":",
"user_agent",
"=",
"r'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0'",
"request_headers",
"=",
"{",
"'User-Agent'",
":",
"user_agent",
"}",
"requests_object",
"=",
"requests",
".",
"get",
"(",
"image_url",
",",
"headers",
"=",
"request_headers",
")",
"try",
":",
"content",
"=",
"requests_object",
".",
"content",
"# Check for empty response",
"f",
".",
"write",
"(",
"content",
")",
"except",
"AttributeError",
":",
"raise",
"ImageErrorException",
"(",
"image_url",
")",
"except",
"IOError",
":",
"raise",
"ImageErrorException",
"(",
"image_url",
")",
"return",
"image_type"
] | Saves an online image from image_url to image_directory with the name image_name.
Returns the extension of the image saved, which is determined dynamically.
Args:
image_url (str): The url of the image.
image_directory (str): The directory to save the image in.
image_name (str): The file name to save the image as.
Raises:
ImageErrorException: Raised if unable to save the image at image_url | [
"Saves",
"an",
"online",
"image",
"from",
"image_url",
"to",
"image_directory",
"with",
"the",
"name",
"image_name",
".",
"Returns",
"the",
"extension",
"of",
"the",
"image",
"saved",
"which",
"is",
"determined",
"dynamically",
"."
] | train | https://github.com/wcember/pypub/blob/88a1adc2ccf6f02c33adea1d2d52c729128216fb/pypub/chapter.py#L46-L83 |
wcember/pypub | pypub/chapter.py | _replace_image | def _replace_image(image_url, image_tag, ebook_folder,
image_name=None):
"""
Replaces the src of an image to link to the local copy in the images folder of the ebook. Tightly coupled with bs4
package.
Args:
image_url (str): The url of the image.
image_tag (bs4.element.Tag): The bs4 tag containing the image.
ebook_folder (str): The directory where the ebook files are being saved. This must contain a subdirectory
called "images".
image_name (Option[str]): The short name to save the image as. Should not contain a directory or an extension.
"""
try:
assert isinstance(image_tag, bs4.element.Tag)
except AssertionError:
raise TypeError("image_tag cannot be of type " + str(type(image_tag)))
if image_name is None:
image_name = str(uuid.uuid4())
try:
image_full_path = os.path.join(ebook_folder, 'images')
assert os.path.exists(image_full_path)
image_extension = save_image(image_url, image_full_path,
image_name)
image_tag['src'] = 'images' + '/' + image_name + '.' + image_extension
except ImageErrorException:
image_tag.decompose()
except AssertionError:
raise ValueError('%s doesn\'t exist or doesn\'t contain a subdirectory images' % ebook_folder)
except TypeError:
image_tag.decompose() | python | def _replace_image(image_url, image_tag, ebook_folder,
image_name=None):
"""
Replaces the src of an image to link to the local copy in the images folder of the ebook. Tightly coupled with bs4
package.
Args:
image_url (str): The url of the image.
image_tag (bs4.element.Tag): The bs4 tag containing the image.
ebook_folder (str): The directory where the ebook files are being saved. This must contain a subdirectory
called "images".
image_name (Option[str]): The short name to save the image as. Should not contain a directory or an extension.
"""
try:
assert isinstance(image_tag, bs4.element.Tag)
except AssertionError:
raise TypeError("image_tag cannot be of type " + str(type(image_tag)))
if image_name is None:
image_name = str(uuid.uuid4())
try:
image_full_path = os.path.join(ebook_folder, 'images')
assert os.path.exists(image_full_path)
image_extension = save_image(image_url, image_full_path,
image_name)
image_tag['src'] = 'images' + '/' + image_name + '.' + image_extension
except ImageErrorException:
image_tag.decompose()
except AssertionError:
raise ValueError('%s doesn\'t exist or doesn\'t contain a subdirectory images' % ebook_folder)
except TypeError:
image_tag.decompose() | [
"def",
"_replace_image",
"(",
"image_url",
",",
"image_tag",
",",
"ebook_folder",
",",
"image_name",
"=",
"None",
")",
":",
"try",
":",
"assert",
"isinstance",
"(",
"image_tag",
",",
"bs4",
".",
"element",
".",
"Tag",
")",
"except",
"AssertionError",
":",
"raise",
"TypeError",
"(",
"\"image_tag cannot be of type \"",
"+",
"str",
"(",
"type",
"(",
"image_tag",
")",
")",
")",
"if",
"image_name",
"is",
"None",
":",
"image_name",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"try",
":",
"image_full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ebook_folder",
",",
"'images'",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"image_full_path",
")",
"image_extension",
"=",
"save_image",
"(",
"image_url",
",",
"image_full_path",
",",
"image_name",
")",
"image_tag",
"[",
"'src'",
"]",
"=",
"'images'",
"+",
"'/'",
"+",
"image_name",
"+",
"'.'",
"+",
"image_extension",
"except",
"ImageErrorException",
":",
"image_tag",
".",
"decompose",
"(",
")",
"except",
"AssertionError",
":",
"raise",
"ValueError",
"(",
"'%s doesn\\'t exist or doesn\\'t contain a subdirectory images'",
"%",
"ebook_folder",
")",
"except",
"TypeError",
":",
"image_tag",
".",
"decompose",
"(",
")"
] | Replaces the src of an image to link to the local copy in the images folder of the ebook. Tightly coupled with bs4
package.
Args:
image_url (str): The url of the image.
image_tag (bs4.element.Tag): The bs4 tag containing the image.
ebook_folder (str): The directory where the ebook files are being saved. This must contain a subdirectory
called "images".
image_name (Option[str]): The short name to save the image as. Should not contain a directory or an extension. | [
"Replaces",
"the",
"src",
"of",
"an",
"image",
"to",
"link",
"to",
"the",
"local",
"copy",
"in",
"the",
"images",
"folder",
"of",
"the",
"ebook",
".",
"Tightly",
"coupled",
"with",
"bs4",
"package",
"."
] | train | https://github.com/wcember/pypub/blob/88a1adc2ccf6f02c33adea1d2d52c729128216fb/pypub/chapter.py#L86-L116 |
wcember/pypub | pypub/chapter.py | Chapter.write | def write(self, file_name):
"""
Writes the chapter object to an xhtml file.
Args:
file_name (str): The full name of the xhtml file to save to.
"""
try:
assert file_name[-6:] == '.xhtml'
except (AssertionError, IndexError):
raise ValueError('filename must end with .xhtml')
with open(file_name, 'wb') as f:
f.write(self.content.encode('utf-8')) | python | def write(self, file_name):
"""
Writes the chapter object to an xhtml file.
Args:
file_name (str): The full name of the xhtml file to save to.
"""
try:
assert file_name[-6:] == '.xhtml'
except (AssertionError, IndexError):
raise ValueError('filename must end with .xhtml')
with open(file_name, 'wb') as f:
f.write(self.content.encode('utf-8')) | [
"def",
"write",
"(",
"self",
",",
"file_name",
")",
":",
"try",
":",
"assert",
"file_name",
"[",
"-",
"6",
":",
"]",
"==",
"'.xhtml'",
"except",
"(",
"AssertionError",
",",
"IndexError",
")",
":",
"raise",
"ValueError",
"(",
"'filename must end with .xhtml'",
")",
"with",
"open",
"(",
"file_name",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"self",
".",
"content",
".",
"encode",
"(",
"'utf-8'",
")",
")"
] | Writes the chapter object to an xhtml file.
Args:
file_name (str): The full name of the xhtml file to save to. | [
"Writes",
"the",
"chapter",
"object",
"to",
"an",
"xhtml",
"file",
"."
] | train | https://github.com/wcember/pypub/blob/88a1adc2ccf6f02c33adea1d2d52c729128216fb/pypub/chapter.py#L148-L160 |
wcember/pypub | pypub/chapter.py | ChapterFactory.create_chapter_from_url | def create_chapter_from_url(self, url, title=None):
"""
Creates a Chapter object from a url. Pulls the webpage from the
given url, sanitizes it using the clean_function method, and saves
it as the content of the created chapter. Basic webpage loaded
before any javascript executed.
Args:
url (string): The url to pull the content of the created Chapter
from
title (Option[string]): The title of the created Chapter. By
default, this is None, in which case the title will try to be
inferred from the webpage at the url.
Returns:
Chapter: A chapter object whose content is the webpage at the given
url and whose title is that provided or inferred from the url
Raises:
ValueError: Raised if unable to connect to url supplied
"""
try:
request_object = requests.get(url, headers=self.request_headers, allow_redirects=False)
except (requests.exceptions.MissingSchema,
requests.exceptions.ConnectionError):
raise ValueError("%s is an invalid url or no network connection" % url)
except requests.exceptions.SSLError:
raise ValueError("Url %s doesn't have valid SSL certificate" % url)
unicode_string = request_object.text
return self.create_chapter_from_string(unicode_string, url, title) | python | def create_chapter_from_url(self, url, title=None):
"""
Creates a Chapter object from a url. Pulls the webpage from the
given url, sanitizes it using the clean_function method, and saves
it as the content of the created chapter. Basic webpage loaded
before any javascript executed.
Args:
url (string): The url to pull the content of the created Chapter
from
title (Option[string]): The title of the created Chapter. By
default, this is None, in which case the title will try to be
inferred from the webpage at the url.
Returns:
Chapter: A chapter object whose content is the webpage at the given
url and whose title is that provided or inferred from the url
Raises:
ValueError: Raised if unable to connect to url supplied
"""
try:
request_object = requests.get(url, headers=self.request_headers, allow_redirects=False)
except (requests.exceptions.MissingSchema,
requests.exceptions.ConnectionError):
raise ValueError("%s is an invalid url or no network connection" % url)
except requests.exceptions.SSLError:
raise ValueError("Url %s doesn't have valid SSL certificate" % url)
unicode_string = request_object.text
return self.create_chapter_from_string(unicode_string, url, title) | [
"def",
"create_chapter_from_url",
"(",
"self",
",",
"url",
",",
"title",
"=",
"None",
")",
":",
"try",
":",
"request_object",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"request_headers",
",",
"allow_redirects",
"=",
"False",
")",
"except",
"(",
"requests",
".",
"exceptions",
".",
"MissingSchema",
",",
"requests",
".",
"exceptions",
".",
"ConnectionError",
")",
":",
"raise",
"ValueError",
"(",
"\"%s is an invalid url or no network connection\"",
"%",
"url",
")",
"except",
"requests",
".",
"exceptions",
".",
"SSLError",
":",
"raise",
"ValueError",
"(",
"\"Url %s doesn't have valid SSL certificate\"",
"%",
"url",
")",
"unicode_string",
"=",
"request_object",
".",
"text",
"return",
"self",
".",
"create_chapter_from_string",
"(",
"unicode_string",
",",
"url",
",",
"title",
")"
] | Creates a Chapter object from a url. Pulls the webpage from the
given url, sanitizes it using the clean_function method, and saves
it as the content of the created chapter. Basic webpage loaded
before any javascript executed.
Args:
url (string): The url to pull the content of the created Chapter
from
title (Option[string]): The title of the created Chapter. By
default, this is None, in which case the title will try to be
inferred from the webpage at the url.
Returns:
Chapter: A chapter object whose content is the webpage at the given
url and whose title is that provided or inferred from the url
Raises:
ValueError: Raised if unable to connect to url supplied | [
"Creates",
"a",
"Chapter",
"object",
"from",
"a",
"url",
".",
"Pulls",
"the",
"webpage",
"from",
"the",
"given",
"url",
"sanitizes",
"it",
"using",
"the",
"clean_function",
"method",
"and",
"saves",
"it",
"as",
"the",
"content",
"of",
"the",
"created",
"chapter",
".",
"Basic",
"webpage",
"loaded",
"before",
"any",
"javascript",
"executed",
"."
] | train | https://github.com/wcember/pypub/blob/88a1adc2ccf6f02c33adea1d2d52c729128216fb/pypub/chapter.py#L220-L249 |
wcember/pypub | pypub/chapter.py | ChapterFactory.create_chapter_from_file | def create_chapter_from_file(self, file_name, url=None, title=None):
"""
Creates a Chapter object from an html or xhtml file. Sanitizes the
file's content using the clean_function method, and saves
it as the content of the created chapter.
Args:
file_name (string): The file_name containing the html or xhtml
content of the created Chapter
url (Option[string]): A url to infer the title of the chapter from
title (Option[string]): The title of the created Chapter. By
default, this is None, in which case the title will try to be
inferred from the webpage at the url.
Returns:
Chapter: A chapter object whose content is the given file
and whose title is that provided or inferred from the url
"""
with codecs.open(file_name, 'r', encoding='utf-8') as f:
content_string = f.read()
return self.create_chapter_from_string(content_string, url, title) | python | def create_chapter_from_file(self, file_name, url=None, title=None):
"""
Creates a Chapter object from an html or xhtml file. Sanitizes the
file's content using the clean_function method, and saves
it as the content of the created chapter.
Args:
file_name (string): The file_name containing the html or xhtml
content of the created Chapter
url (Option[string]): A url to infer the title of the chapter from
title (Option[string]): The title of the created Chapter. By
default, this is None, in which case the title will try to be
inferred from the webpage at the url.
Returns:
Chapter: A chapter object whose content is the given file
and whose title is that provided or inferred from the url
"""
with codecs.open(file_name, 'r', encoding='utf-8') as f:
content_string = f.read()
return self.create_chapter_from_string(content_string, url, title) | [
"def",
"create_chapter_from_file",
"(",
"self",
",",
"file_name",
",",
"url",
"=",
"None",
",",
"title",
"=",
"None",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"file_name",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"content_string",
"=",
"f",
".",
"read",
"(",
")",
"return",
"self",
".",
"create_chapter_from_string",
"(",
"content_string",
",",
"url",
",",
"title",
")"
] | Creates a Chapter object from an html or xhtml file. Sanitizes the
file's content using the clean_function method, and saves
it as the content of the created chapter.
Args:
file_name (string): The file_name containing the html or xhtml
content of the created Chapter
url (Option[string]): A url to infer the title of the chapter from
title (Option[string]): The title of the created Chapter. By
default, this is None, in which case the title will try to be
inferred from the webpage at the url.
Returns:
Chapter: A chapter object whose content is the given file
and whose title is that provided or inferred from the url | [
"Creates",
"a",
"Chapter",
"object",
"from",
"an",
"html",
"or",
"xhtml",
"file",
".",
"Sanitizes",
"the",
"file",
"s",
"content",
"using",
"the",
"clean_function",
"method",
"and",
"saves",
"it",
"as",
"the",
"content",
"of",
"the",
"created",
"chapter",
"."
] | train | https://github.com/wcember/pypub/blob/88a1adc2ccf6f02c33adea1d2d52c729128216fb/pypub/chapter.py#L251-L271 |
wcember/pypub | pypub/chapter.py | ChapterFactory.create_chapter_from_string | def create_chapter_from_string(self, html_string, url=None, title=None):
"""
Creates a Chapter object from a string. Sanitizes the
string using the clean_function method, and saves
it as the content of the created chapter.
Args:
html_string (string): The html or xhtml content of the created
Chapter
url (Option[string]): A url to infer the title of the chapter from
title (Option[string]): The title of the created Chapter. By
default, this is None, in which case the title will try to be
inferred from the webpage at the url.
Returns:
Chapter: A chapter object whose content is the given string
and whose title is that provided or inferred from the url
"""
clean_html_string = self.clean_function(html_string)
clean_xhtml_string = clean.html_to_xhtml(clean_html_string)
if title:
pass
else:
try:
root = BeautifulSoup(html_string, 'html.parser')
title_node = root.title
if title_node is not None:
title = unicode(title_node.string)
else:
raise ValueError
except (IndexError, ValueError):
title = 'Ebook Chapter'
return Chapter(clean_xhtml_string, title, url) | python | def create_chapter_from_string(self, html_string, url=None, title=None):
"""
Creates a Chapter object from a string. Sanitizes the
string using the clean_function method, and saves
it as the content of the created chapter.
Args:
html_string (string): The html or xhtml content of the created
Chapter
url (Option[string]): A url to infer the title of the chapter from
title (Option[string]): The title of the created Chapter. By
default, this is None, in which case the title will try to be
inferred from the webpage at the url.
Returns:
Chapter: A chapter object whose content is the given string
and whose title is that provided or inferred from the url
"""
clean_html_string = self.clean_function(html_string)
clean_xhtml_string = clean.html_to_xhtml(clean_html_string)
if title:
pass
else:
try:
root = BeautifulSoup(html_string, 'html.parser')
title_node = root.title
if title_node is not None:
title = unicode(title_node.string)
else:
raise ValueError
except (IndexError, ValueError):
title = 'Ebook Chapter'
return Chapter(clean_xhtml_string, title, url) | [
"def",
"create_chapter_from_string",
"(",
"self",
",",
"html_string",
",",
"url",
"=",
"None",
",",
"title",
"=",
"None",
")",
":",
"clean_html_string",
"=",
"self",
".",
"clean_function",
"(",
"html_string",
")",
"clean_xhtml_string",
"=",
"clean",
".",
"html_to_xhtml",
"(",
"clean_html_string",
")",
"if",
"title",
":",
"pass",
"else",
":",
"try",
":",
"root",
"=",
"BeautifulSoup",
"(",
"html_string",
",",
"'html.parser'",
")",
"title_node",
"=",
"root",
".",
"title",
"if",
"title_node",
"is",
"not",
"None",
":",
"title",
"=",
"unicode",
"(",
"title_node",
".",
"string",
")",
"else",
":",
"raise",
"ValueError",
"except",
"(",
"IndexError",
",",
"ValueError",
")",
":",
"title",
"=",
"'Ebook Chapter'",
"return",
"Chapter",
"(",
"clean_xhtml_string",
",",
"title",
",",
"url",
")"
] | Creates a Chapter object from a string. Sanitizes the
string using the clean_function method, and saves
it as the content of the created chapter.
Args:
html_string (string): The html or xhtml content of the created
Chapter
url (Option[string]): A url to infer the title of the chapter from
title (Option[string]): The title of the created Chapter. By
default, this is None, in which case the title will try to be
inferred from the webpage at the url.
Returns:
Chapter: A chapter object whose content is the given string
and whose title is that provided or inferred from the url | [
"Creates",
"a",
"Chapter",
"object",
"from",
"a",
"string",
".",
"Sanitizes",
"the",
"string",
"using",
"the",
"clean_function",
"method",
"and",
"saves",
"it",
"as",
"the",
"content",
"of",
"the",
"created",
"chapter",
"."
] | train | https://github.com/wcember/pypub/blob/88a1adc2ccf6f02c33adea1d2d52c729128216fb/pypub/chapter.py#L273-L305 |
wcember/pypub | pypub/clean.py | create_html_from_fragment | def create_html_from_fragment(tag):
"""
Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not
Args:
tag: a bs4.element.Tag
Returns:"
bs4.element.Tag: A bs4 tag representing a full html document
"""
try:
assert isinstance(tag, bs4.element.Tag)
except AssertionError:
raise TypeError
try:
assert tag.find_all('body') == []
except AssertionError:
raise ValueError
soup = BeautifulSoup('<html><head></head><body></body></html>', 'html.parser')
soup.body.append(tag)
return soup | python | def create_html_from_fragment(tag):
"""
Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not
Args:
tag: a bs4.element.Tag
Returns:"
bs4.element.Tag: A bs4 tag representing a full html document
"""
try:
assert isinstance(tag, bs4.element.Tag)
except AssertionError:
raise TypeError
try:
assert tag.find_all('body') == []
except AssertionError:
raise ValueError
soup = BeautifulSoup('<html><head></head><body></body></html>', 'html.parser')
soup.body.append(tag)
return soup | [
"def",
"create_html_from_fragment",
"(",
"tag",
")",
":",
"try",
":",
"assert",
"isinstance",
"(",
"tag",
",",
"bs4",
".",
"element",
".",
"Tag",
")",
"except",
"AssertionError",
":",
"raise",
"TypeError",
"try",
":",
"assert",
"tag",
".",
"find_all",
"(",
"'body'",
")",
"==",
"[",
"]",
"except",
"AssertionError",
":",
"raise",
"ValueError",
"soup",
"=",
"BeautifulSoup",
"(",
"'<html><head></head><body></body></html>'",
",",
"'html.parser'",
")",
"soup",
".",
"body",
".",
"append",
"(",
"tag",
")",
"return",
"soup"
] | Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not
Args:
tag: a bs4.element.Tag
Returns:"
bs4.element.Tag: A bs4 tag representing a full html document | [
"Creates",
"full",
"html",
"tree",
"from",
"a",
"fragment",
".",
"Assumes",
"that",
"tag",
"should",
"be",
"wrapped",
"in",
"a",
"body",
"and",
"is",
"currently",
"not"
] | train | https://github.com/wcember/pypub/blob/88a1adc2ccf6f02c33adea1d2d52c729128216fb/pypub/clean.py#L11-L33 |
wcember/pypub | pypub/clean.py | clean | def clean(input_string,
tag_dictionary=constants.SUPPORTED_TAGS):
"""
Sanitizes HTML. Tags not contained as keys in the tag_dictionary input are
removed, and child nodes are recursively moved to parent of removed node.
Attributes not contained as arguments in tag_dictionary are removed.
Doctype is set to <!DOCTYPE html>.
Args:
input_string (basestring): A (possibly unicode) string representing HTML.
tag_dictionary (Option[dict]): A dictionary with tags as keys and
attributes as values. This operates as a whitelist--i.e. if a tag
isn't contained, it will be removed. By default, this is set to
use the supported tags and attributes for the Amazon Kindle,
as found at https://kdp.amazon.com/help?topicId=A1JPUWCSD6F59O
Returns:
str: A (possibly unicode) string representing HTML.
Raises:
TypeError: Raised if input_string isn't a unicode string or string.
"""
try:
assert isinstance(input_string, basestring)
except AssertionError:
raise TypeError
root = BeautifulSoup(input_string, 'html.parser')
article_tag = root.find_all('article')
if article_tag:
root = article_tag[0]
stack = root.findAll(True, recursive=False)
while stack:
current_node = stack.pop()
child_node_list = current_node.findAll(True, recursive=False)
if current_node.name not in tag_dictionary.keys():
parent_node = current_node.parent
current_node.extract()
for n in child_node_list:
parent_node.append(n)
else:
attribute_dict = current_node.attrs
for attribute in attribute_dict.keys():
if attribute not in tag_dictionary[current_node.name]:
attribute_dict.pop(attribute)
stack.extend(child_node_list)
#wrap partial tree if necessary
if root.find_all('html') == []:
root = create_html_from_fragment(root)
# Remove img tags without src attribute
image_node_list = root.find_all('img')
for node in image_node_list:
if not node.has_attr('src'):
node.extract()
unformatted_html_unicode_string = unicode(root.prettify(encoding='utf-8',
formatter=EntitySubstitution.substitute_html),
encoding='utf-8')
# fix <br> tags since not handled well by default by bs4
unformatted_html_unicode_string = unformatted_html_unicode_string.replace('<br>', '<br/>')
# remove and replace with space since not handled well by certain e-readers
unformatted_html_unicode_string = unformatted_html_unicode_string.replace(' ', ' ')
return unformatted_html_unicode_string | python | def clean(input_string,
tag_dictionary=constants.SUPPORTED_TAGS):
"""
Sanitizes HTML. Tags not contained as keys in the tag_dictionary input are
removed, and child nodes are recursively moved to parent of removed node.
Attributes not contained as arguments in tag_dictionary are removed.
Doctype is set to <!DOCTYPE html>.
Args:
input_string (basestring): A (possibly unicode) string representing HTML.
tag_dictionary (Option[dict]): A dictionary with tags as keys and
attributes as values. This operates as a whitelist--i.e. if a tag
isn't contained, it will be removed. By default, this is set to
use the supported tags and attributes for the Amazon Kindle,
as found at https://kdp.amazon.com/help?topicId=A1JPUWCSD6F59O
Returns:
str: A (possibly unicode) string representing HTML.
Raises:
TypeError: Raised if input_string isn't a unicode string or string.
"""
try:
assert isinstance(input_string, basestring)
except AssertionError:
raise TypeError
root = BeautifulSoup(input_string, 'html.parser')
article_tag = root.find_all('article')
if article_tag:
root = article_tag[0]
stack = root.findAll(True, recursive=False)
while stack:
current_node = stack.pop()
child_node_list = current_node.findAll(True, recursive=False)
if current_node.name not in tag_dictionary.keys():
parent_node = current_node.parent
current_node.extract()
for n in child_node_list:
parent_node.append(n)
else:
attribute_dict = current_node.attrs
for attribute in attribute_dict.keys():
if attribute not in tag_dictionary[current_node.name]:
attribute_dict.pop(attribute)
stack.extend(child_node_list)
#wrap partial tree if necessary
if root.find_all('html') == []:
root = create_html_from_fragment(root)
# Remove img tags without src attribute
image_node_list = root.find_all('img')
for node in image_node_list:
if not node.has_attr('src'):
node.extract()
unformatted_html_unicode_string = unicode(root.prettify(encoding='utf-8',
formatter=EntitySubstitution.substitute_html),
encoding='utf-8')
# fix <br> tags since not handled well by default by bs4
unformatted_html_unicode_string = unformatted_html_unicode_string.replace('<br>', '<br/>')
# remove and replace with space since not handled well by certain e-readers
unformatted_html_unicode_string = unformatted_html_unicode_string.replace(' ', ' ')
return unformatted_html_unicode_string | [
"def",
"clean",
"(",
"input_string",
",",
"tag_dictionary",
"=",
"constants",
".",
"SUPPORTED_TAGS",
")",
":",
"try",
":",
"assert",
"isinstance",
"(",
"input_string",
",",
"basestring",
")",
"except",
"AssertionError",
":",
"raise",
"TypeError",
"root",
"=",
"BeautifulSoup",
"(",
"input_string",
",",
"'html.parser'",
")",
"article_tag",
"=",
"root",
".",
"find_all",
"(",
"'article'",
")",
"if",
"article_tag",
":",
"root",
"=",
"article_tag",
"[",
"0",
"]",
"stack",
"=",
"root",
".",
"findAll",
"(",
"True",
",",
"recursive",
"=",
"False",
")",
"while",
"stack",
":",
"current_node",
"=",
"stack",
".",
"pop",
"(",
")",
"child_node_list",
"=",
"current_node",
".",
"findAll",
"(",
"True",
",",
"recursive",
"=",
"False",
")",
"if",
"current_node",
".",
"name",
"not",
"in",
"tag_dictionary",
".",
"keys",
"(",
")",
":",
"parent_node",
"=",
"current_node",
".",
"parent",
"current_node",
".",
"extract",
"(",
")",
"for",
"n",
"in",
"child_node_list",
":",
"parent_node",
".",
"append",
"(",
"n",
")",
"else",
":",
"attribute_dict",
"=",
"current_node",
".",
"attrs",
"for",
"attribute",
"in",
"attribute_dict",
".",
"keys",
"(",
")",
":",
"if",
"attribute",
"not",
"in",
"tag_dictionary",
"[",
"current_node",
".",
"name",
"]",
":",
"attribute_dict",
".",
"pop",
"(",
"attribute",
")",
"stack",
".",
"extend",
"(",
"child_node_list",
")",
"#wrap partial tree if necessary",
"if",
"root",
".",
"find_all",
"(",
"'html'",
")",
"==",
"[",
"]",
":",
"root",
"=",
"create_html_from_fragment",
"(",
"root",
")",
"# Remove img tags without src attribute",
"image_node_list",
"=",
"root",
".",
"find_all",
"(",
"'img'",
")",
"for",
"node",
"in",
"image_node_list",
":",
"if",
"not",
"node",
".",
"has_attr",
"(",
"'src'",
")",
":",
"node",
".",
"extract",
"(",
")",
"unformatted_html_unicode_string",
"=",
"unicode",
"(",
"root",
".",
"prettify",
"(",
"encoding",
"=",
"'utf-8'",
",",
"formatter",
"=",
"EntitySubstitution",
".",
"substitute_html",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
"# fix <br> tags since not handled well by default by bs4",
"unformatted_html_unicode_string",
"=",
"unformatted_html_unicode_string",
".",
"replace",
"(",
"'<br>'",
",",
"'<br/>'",
")",
"# remove and replace with space since not handled well by certain e-readers",
"unformatted_html_unicode_string",
"=",
"unformatted_html_unicode_string",
".",
"replace",
"(",
"' '",
",",
"' '",
")",
"return",
"unformatted_html_unicode_string"
] | Sanitizes HTML. Tags not contained as keys in the tag_dictionary input are
removed, and child nodes are recursively moved to parent of removed node.
Attributes not contained as arguments in tag_dictionary are removed.
Doctype is set to <!DOCTYPE html>.
Args:
input_string (basestring): A (possibly unicode) string representing HTML.
tag_dictionary (Option[dict]): A dictionary with tags as keys and
attributes as values. This operates as a whitelist--i.e. if a tag
isn't contained, it will be removed. By default, this is set to
use the supported tags and attributes for the Amazon Kindle,
as found at https://kdp.amazon.com/help?topicId=A1JPUWCSD6F59O
Returns:
str: A (possibly unicode) string representing HTML.
Raises:
TypeError: Raised if input_string isn't a unicode string or string. | [
"Sanitizes",
"HTML",
".",
"Tags",
"not",
"contained",
"as",
"keys",
"in",
"the",
"tag_dictionary",
"input",
"are",
"removed",
"and",
"child",
"nodes",
"are",
"recursively",
"moved",
"to",
"parent",
"of",
"removed",
"node",
".",
"Attributes",
"not",
"contained",
"as",
"arguments",
"in",
"tag_dictionary",
"are",
"removed",
".",
"Doctype",
"is",
"set",
"to",
"<!DOCTYPE",
"html",
">",
"."
] | train | https://github.com/wcember/pypub/blob/88a1adc2ccf6f02c33adea1d2d52c729128216fb/pypub/clean.py#L36-L96 |
wcember/pypub | pypub/clean.py | condense | def condense(input_string):
"""
Trims leadings and trailing whitespace between tags in an html document
Args:
input_string: A (possible unicode) string representing HTML.
Returns:
A (possibly unicode) string representing HTML.
Raises:
TypeError: Raised if input_string isn't a unicode string or string.
"""
try:
assert isinstance(input_string, basestring)
except AssertionError:
raise TypeError
removed_leading_whitespace = re.sub('>\s+', '>', input_string).strip()
removed_trailing_whitespace = re.sub('\s+<', '<', removed_leading_whitespace).strip()
return removed_trailing_whitespace | python | def condense(input_string):
"""
Trims leadings and trailing whitespace between tags in an html document
Args:
input_string: A (possible unicode) string representing HTML.
Returns:
A (possibly unicode) string representing HTML.
Raises:
TypeError: Raised if input_string isn't a unicode string or string.
"""
try:
assert isinstance(input_string, basestring)
except AssertionError:
raise TypeError
removed_leading_whitespace = re.sub('>\s+', '>', input_string).strip()
removed_trailing_whitespace = re.sub('\s+<', '<', removed_leading_whitespace).strip()
return removed_trailing_whitespace | [
"def",
"condense",
"(",
"input_string",
")",
":",
"try",
":",
"assert",
"isinstance",
"(",
"input_string",
",",
"basestring",
")",
"except",
"AssertionError",
":",
"raise",
"TypeError",
"removed_leading_whitespace",
"=",
"re",
".",
"sub",
"(",
"'>\\s+'",
",",
"'>'",
",",
"input_string",
")",
".",
"strip",
"(",
")",
"removed_trailing_whitespace",
"=",
"re",
".",
"sub",
"(",
"'\\s+<'",
",",
"'<'",
",",
"removed_leading_whitespace",
")",
".",
"strip",
"(",
")",
"return",
"removed_trailing_whitespace"
] | Trims leadings and trailing whitespace between tags in an html document
Args:
input_string: A (possible unicode) string representing HTML.
Returns:
A (possibly unicode) string representing HTML.
Raises:
TypeError: Raised if input_string isn't a unicode string or string. | [
"Trims",
"leadings",
"and",
"trailing",
"whitespace",
"between",
"tags",
"in",
"an",
"html",
"document"
] | train | https://github.com/wcember/pypub/blob/88a1adc2ccf6f02c33adea1d2d52c729128216fb/pypub/clean.py#L99-L118 |
wcember/pypub | pypub/clean.py | html_to_xhtml | def html_to_xhtml(html_unicode_string):
"""
Converts html to xhtml
Args:
html_unicode_string: A (possible unicode) string representing HTML.
Returns:
A (possibly unicode) string representing XHTML.
Raises:
TypeError: Raised if input_string isn't a unicode string or string.
"""
try:
assert isinstance(html_unicode_string, basestring)
except AssertionError:
raise TypeError
root = BeautifulSoup(html_unicode_string, 'html.parser')
# Confirm root node is html
try:
assert root.html is not None
except AssertionError:
raise ValueError(''.join(['html_unicode_string cannot be a fragment.',
'string is the following: %s', unicode(root)]))
# Add xmlns attribute to html node
root.html['xmlns'] = 'http://www.w3.org/1999/xhtml'
unicode_string = unicode(root.prettify(encoding='utf-8', formatter='html'), encoding='utf-8')
# Close singleton tag_dictionary
for tag in constants.SINGLETON_TAG_LIST:
unicode_string = unicode_string.replace(
'<' + tag + '/>',
'<' + tag + ' />')
return unicode_string | python | def html_to_xhtml(html_unicode_string):
"""
Converts html to xhtml
Args:
html_unicode_string: A (possible unicode) string representing HTML.
Returns:
A (possibly unicode) string representing XHTML.
Raises:
TypeError: Raised if input_string isn't a unicode string or string.
"""
try:
assert isinstance(html_unicode_string, basestring)
except AssertionError:
raise TypeError
root = BeautifulSoup(html_unicode_string, 'html.parser')
# Confirm root node is html
try:
assert root.html is not None
except AssertionError:
raise ValueError(''.join(['html_unicode_string cannot be a fragment.',
'string is the following: %s', unicode(root)]))
# Add xmlns attribute to html node
root.html['xmlns'] = 'http://www.w3.org/1999/xhtml'
unicode_string = unicode(root.prettify(encoding='utf-8', formatter='html'), encoding='utf-8')
# Close singleton tag_dictionary
for tag in constants.SINGLETON_TAG_LIST:
unicode_string = unicode_string.replace(
'<' + tag + '/>',
'<' + tag + ' />')
return unicode_string | [
"def",
"html_to_xhtml",
"(",
"html_unicode_string",
")",
":",
"try",
":",
"assert",
"isinstance",
"(",
"html_unicode_string",
",",
"basestring",
")",
"except",
"AssertionError",
":",
"raise",
"TypeError",
"root",
"=",
"BeautifulSoup",
"(",
"html_unicode_string",
",",
"'html.parser'",
")",
"# Confirm root node is html",
"try",
":",
"assert",
"root",
".",
"html",
"is",
"not",
"None",
"except",
"AssertionError",
":",
"raise",
"ValueError",
"(",
"''",
".",
"join",
"(",
"[",
"'html_unicode_string cannot be a fragment.'",
",",
"'string is the following: %s'",
",",
"unicode",
"(",
"root",
")",
"]",
")",
")",
"# Add xmlns attribute to html node",
"root",
".",
"html",
"[",
"'xmlns'",
"]",
"=",
"'http://www.w3.org/1999/xhtml'",
"unicode_string",
"=",
"unicode",
"(",
"root",
".",
"prettify",
"(",
"encoding",
"=",
"'utf-8'",
",",
"formatter",
"=",
"'html'",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
"# Close singleton tag_dictionary",
"for",
"tag",
"in",
"constants",
".",
"SINGLETON_TAG_LIST",
":",
"unicode_string",
"=",
"unicode_string",
".",
"replace",
"(",
"'<'",
"+",
"tag",
"+",
"'/>'",
",",
"'<'",
"+",
"tag",
"+",
"' />'",
")",
"return",
"unicode_string"
] | Converts html to xhtml
Args:
html_unicode_string: A (possible unicode) string representing HTML.
Returns:
A (possibly unicode) string representing XHTML.
Raises:
TypeError: Raised if input_string isn't a unicode string or string. | [
"Converts",
"html",
"to",
"xhtml"
] | train | https://github.com/wcember/pypub/blob/88a1adc2ccf6f02c33adea1d2d52c729128216fb/pypub/clean.py#L121-L153 |
etingof/apacheconfig | apacheconfig/loader.py | ApacheConfigLoader._merge_dicts | def _merge_dicts(self, dict1, dict2, path=[]):
"merges dict2 into dict1"
for key in dict2:
if key in dict1:
if isinstance(dict1[key], dict) and isinstance(dict2[key], dict):
self._merge_dicts(dict1[key], dict2[key], path + [str(key)])
elif dict1[key] != dict2[key]:
if self._options.get('allowmultioptions', True):
if not isinstance(dict1[key], list):
dict1[key] = [dict1[key]]
if not isinstance(dict2[key], list):
dict2[key] = [dict2[key]]
dict1[key] = self._merge_lists(dict1[key], dict2[key])
else:
if self._options.get('mergeduplicateoptions', False):
dict1[key] = dict2[key]
else:
raise error.ApacheConfigError('Duplicate option "%s" prohibited' % '.'.join(path + [str(key)]))
else:
dict1[key] = dict2[key]
return dict1 | python | def _merge_dicts(self, dict1, dict2, path=[]):
"merges dict2 into dict1"
for key in dict2:
if key in dict1:
if isinstance(dict1[key], dict) and isinstance(dict2[key], dict):
self._merge_dicts(dict1[key], dict2[key], path + [str(key)])
elif dict1[key] != dict2[key]:
if self._options.get('allowmultioptions', True):
if not isinstance(dict1[key], list):
dict1[key] = [dict1[key]]
if not isinstance(dict2[key], list):
dict2[key] = [dict2[key]]
dict1[key] = self._merge_lists(dict1[key], dict2[key])
else:
if self._options.get('mergeduplicateoptions', False):
dict1[key] = dict2[key]
else:
raise error.ApacheConfigError('Duplicate option "%s" prohibited' % '.'.join(path + [str(key)]))
else:
dict1[key] = dict2[key]
return dict1 | [
"def",
"_merge_dicts",
"(",
"self",
",",
"dict1",
",",
"dict2",
",",
"path",
"=",
"[",
"]",
")",
":",
"for",
"key",
"in",
"dict2",
":",
"if",
"key",
"in",
"dict1",
":",
"if",
"isinstance",
"(",
"dict1",
"[",
"key",
"]",
",",
"dict",
")",
"and",
"isinstance",
"(",
"dict2",
"[",
"key",
"]",
",",
"dict",
")",
":",
"self",
".",
"_merge_dicts",
"(",
"dict1",
"[",
"key",
"]",
",",
"dict2",
"[",
"key",
"]",
",",
"path",
"+",
"[",
"str",
"(",
"key",
")",
"]",
")",
"elif",
"dict1",
"[",
"key",
"]",
"!=",
"dict2",
"[",
"key",
"]",
":",
"if",
"self",
".",
"_options",
".",
"get",
"(",
"'allowmultioptions'",
",",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"dict1",
"[",
"key",
"]",
",",
"list",
")",
":",
"dict1",
"[",
"key",
"]",
"=",
"[",
"dict1",
"[",
"key",
"]",
"]",
"if",
"not",
"isinstance",
"(",
"dict2",
"[",
"key",
"]",
",",
"list",
")",
":",
"dict2",
"[",
"key",
"]",
"=",
"[",
"dict2",
"[",
"key",
"]",
"]",
"dict1",
"[",
"key",
"]",
"=",
"self",
".",
"_merge_lists",
"(",
"dict1",
"[",
"key",
"]",
",",
"dict2",
"[",
"key",
"]",
")",
"else",
":",
"if",
"self",
".",
"_options",
".",
"get",
"(",
"'mergeduplicateoptions'",
",",
"False",
")",
":",
"dict1",
"[",
"key",
"]",
"=",
"dict2",
"[",
"key",
"]",
"else",
":",
"raise",
"error",
".",
"ApacheConfigError",
"(",
"'Duplicate option \"%s\" prohibited'",
"%",
"'.'",
".",
"join",
"(",
"path",
"+",
"[",
"str",
"(",
"key",
")",
"]",
")",
")",
"else",
":",
"dict1",
"[",
"key",
"]",
"=",
"dict2",
"[",
"key",
"]",
"return",
"dict1"
] | merges dict2 into dict1 | [
"merges",
"dict2",
"into",
"dict1"
] | train | https://github.com/etingof/apacheconfig/blob/7126dbc0a547779276ac04cf32a051c26781c464/apacheconfig/loader.py#L285-L305 |
etingof/apacheconfig | apacheconfig/parser.py | BaseApacheConfigParser.p_statement | def p_statement(self, p):
"""statement : OPTION_AND_VALUE
"""
p[0] = ['statement', p[1][0], p[1][1]]
if self.options.get('lowercasenames'):
p[0][1] = p[0][1].lower()
if (not self.options.get('nostripvalues') and
not hasattr(p[0][2], 'is_single_quoted') and
not hasattr(p[0][2], 'is_double_quoted')):
p[0][2] = p[0][2].rstrip() | python | def p_statement(self, p):
"""statement : OPTION_AND_VALUE
"""
p[0] = ['statement', p[1][0], p[1][1]]
if self.options.get('lowercasenames'):
p[0][1] = p[0][1].lower()
if (not self.options.get('nostripvalues') and
not hasattr(p[0][2], 'is_single_quoted') and
not hasattr(p[0][2], 'is_double_quoted')):
p[0][2] = p[0][2].rstrip() | [
"def",
"p_statement",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"'statement'",
",",
"p",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"p",
"[",
"1",
"]",
"[",
"1",
"]",
"]",
"if",
"self",
".",
"options",
".",
"get",
"(",
"'lowercasenames'",
")",
":",
"p",
"[",
"0",
"]",
"[",
"1",
"]",
"=",
"p",
"[",
"0",
"]",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"if",
"(",
"not",
"self",
".",
"options",
".",
"get",
"(",
"'nostripvalues'",
")",
"and",
"not",
"hasattr",
"(",
"p",
"[",
"0",
"]",
"[",
"2",
"]",
",",
"'is_single_quoted'",
")",
"and",
"not",
"hasattr",
"(",
"p",
"[",
"0",
"]",
"[",
"2",
"]",
",",
"'is_double_quoted'",
")",
")",
":",
"p",
"[",
"0",
"]",
"[",
"2",
"]",
"=",
"p",
"[",
"0",
"]",
"[",
"2",
"]",
".",
"rstrip",
"(",
")"
] | statement : OPTION_AND_VALUE | [
"statement",
":",
"OPTION_AND_VALUE"
] | train | https://github.com/etingof/apacheconfig/blob/7126dbc0a547779276ac04cf32a051c26781c464/apacheconfig/parser.py#L79-L90 |
etingof/apacheconfig | apacheconfig/parser.py | BaseApacheConfigParser.p_statements | def p_statements(self, p):
"""statements : statements statement
| statement
"""
n = len(p)
if n == 3:
p[0] = p[1] + [p[2]]
elif n == 2:
p[0] = ['statements', p[1]] | python | def p_statements(self, p):
"""statements : statements statement
| statement
"""
n = len(p)
if n == 3:
p[0] = p[1] + [p[2]]
elif n == 2:
p[0] = ['statements', p[1]] | [
"def",
"p_statements",
"(",
"self",
",",
"p",
")",
":",
"n",
"=",
"len",
"(",
"p",
")",
"if",
"n",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"[",
"p",
"[",
"2",
"]",
"]",
"elif",
"n",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"'statements'",
",",
"p",
"[",
"1",
"]",
"]"
] | statements : statements statement
| statement | [
"statements",
":",
"statements",
"statement",
"|",
"statement"
] | train | https://github.com/etingof/apacheconfig/blob/7126dbc0a547779276ac04cf32a051c26781c464/apacheconfig/parser.py#L92-L100 |
etingof/apacheconfig | apacheconfig/parser.py | BaseApacheConfigParser.p_contents | def p_contents(self, p):
"""contents : contents statements
| contents comment
| contents include
| contents includeoptional
| contents block
| statements
| comment
| include
| includeoptional
| block
"""
n = len(p)
if n == 3:
p[0] = p[1] + [p[2]]
else:
p[0] = ['contents', p[1]] | python | def p_contents(self, p):
"""contents : contents statements
| contents comment
| contents include
| contents includeoptional
| contents block
| statements
| comment
| include
| includeoptional
| block
"""
n = len(p)
if n == 3:
p[0] = p[1] + [p[2]]
else:
p[0] = ['contents', p[1]] | [
"def",
"p_contents",
"(",
"self",
",",
"p",
")",
":",
"n",
"=",
"len",
"(",
"p",
")",
"if",
"n",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"[",
"p",
"[",
"2",
"]",
"]",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"'contents'",
",",
"p",
"[",
"1",
"]",
"]"
] | contents : contents statements
| contents comment
| contents include
| contents includeoptional
| contents block
| statements
| comment
| include
| includeoptional
| block | [
"contents",
":",
"contents",
"statements",
"|",
"contents",
"comment",
"|",
"contents",
"include",
"|",
"contents",
"includeoptional",
"|",
"contents",
"block",
"|",
"statements",
"|",
"comment",
"|",
"include",
"|",
"includeoptional",
"|",
"block"
] | train | https://github.com/etingof/apacheconfig/blob/7126dbc0a547779276ac04cf32a051c26781c464/apacheconfig/parser.py#L102-L118 |
etingof/apacheconfig | apacheconfig/parser.py | BaseApacheConfigParser.p_block | def p_block(self, p):
"""block : OPEN_TAG contents CLOSE_TAG
| OPEN_TAG CLOSE_TAG
| OPEN_CLOSE_TAG
"""
n = len(p)
if n == 4:
p[0] = ['block', p[1], p[2], p[3]]
elif n == 3:
p[0] = ['block', p[1], [], p[2]]
else:
p[0] = ['block', p[1], [], p[1]]
if self.options.get('lowercasenames'):
for tag in (1, 3):
p[0][tag] = p[0][tag].lower() | python | def p_block(self, p):
"""block : OPEN_TAG contents CLOSE_TAG
| OPEN_TAG CLOSE_TAG
| OPEN_CLOSE_TAG
"""
n = len(p)
if n == 4:
p[0] = ['block', p[1], p[2], p[3]]
elif n == 3:
p[0] = ['block', p[1], [], p[2]]
else:
p[0] = ['block', p[1], [], p[1]]
if self.options.get('lowercasenames'):
for tag in (1, 3):
p[0][tag] = p[0][tag].lower() | [
"def",
"p_block",
"(",
"self",
",",
"p",
")",
":",
"n",
"=",
"len",
"(",
"p",
")",
"if",
"n",
"==",
"4",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"'block'",
",",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
",",
"p",
"[",
"3",
"]",
"]",
"elif",
"n",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"'block'",
",",
"p",
"[",
"1",
"]",
",",
"[",
"]",
",",
"p",
"[",
"2",
"]",
"]",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"'block'",
",",
"p",
"[",
"1",
"]",
",",
"[",
"]",
",",
"p",
"[",
"1",
"]",
"]",
"if",
"self",
".",
"options",
".",
"get",
"(",
"'lowercasenames'",
")",
":",
"for",
"tag",
"in",
"(",
"1",
",",
"3",
")",
":",
"p",
"[",
"0",
"]",
"[",
"tag",
"]",
"=",
"p",
"[",
"0",
"]",
"[",
"tag",
"]",
".",
"lower",
"(",
")"
] | block : OPEN_TAG contents CLOSE_TAG
| OPEN_TAG CLOSE_TAG
| OPEN_CLOSE_TAG | [
"block",
":",
"OPEN_TAG",
"contents",
"CLOSE_TAG",
"|",
"OPEN_TAG",
"CLOSE_TAG",
"|",
"OPEN_CLOSE_TAG"
] | train | https://github.com/etingof/apacheconfig/blob/7126dbc0a547779276ac04cf32a051c26781c464/apacheconfig/parser.py#L120-L135 |
etingof/apacheconfig | apacheconfig/parser.py | BaseApacheConfigParser.p_config | def p_config(self, p):
"""config : config contents
| contents
"""
n = len(p)
if n == 3:
p[0] = p[1] + [p[2]]
elif n == 2:
p[0] = ['config', p[1]] | python | def p_config(self, p):
"""config : config contents
| contents
"""
n = len(p)
if n == 3:
p[0] = p[1] + [p[2]]
elif n == 2:
p[0] = ['config', p[1]] | [
"def",
"p_config",
"(",
"self",
",",
"p",
")",
":",
"n",
"=",
"len",
"(",
"p",
")",
"if",
"n",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"[",
"p",
"[",
"2",
"]",
"]",
"elif",
"n",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"'config'",
",",
"p",
"[",
"1",
"]",
"]"
] | config : config contents
| contents | [
"config",
":",
"config",
"contents",
"|",
"contents"
] | train | https://github.com/etingof/apacheconfig/blob/7126dbc0a547779276ac04cf32a051c26781c464/apacheconfig/parser.py#L137-L145 |
etingof/apacheconfig | apacheconfig/lexer.py | CStyleCommentsLexer.t_CCOMMENT | def t_CCOMMENT(self, t):
r'\/\*'
t.lexer.code_start = t.lexer.lexpos
t.lexer.ccomment_level = 1 # Initial comment level
t.lexer.begin('ccomment') | python | def t_CCOMMENT(self, t):
r'\/\*'
t.lexer.code_start = t.lexer.lexpos
t.lexer.ccomment_level = 1 # Initial comment level
t.lexer.begin('ccomment') | [
"def",
"t_CCOMMENT",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"lexer",
".",
"code_start",
"=",
"t",
".",
"lexer",
".",
"lexpos",
"t",
".",
"lexer",
".",
"ccomment_level",
"=",
"1",
"# Initial comment level",
"t",
".",
"lexer",
".",
"begin",
"(",
"'ccomment'",
")"
] | r'\/\* | [
"r",
"\\",
"/",
"\\",
"*"
] | train | https://github.com/etingof/apacheconfig/blob/7126dbc0a547779276ac04cf32a051c26781c464/apacheconfig/lexer.py#L46-L50 |
etingof/apacheconfig | apacheconfig/lexer.py | CStyleCommentsLexer.t_ccomment_close | def t_ccomment_close(self, t):
r'\*\/'
t.lexer.ccomment_level -= 1
if t.lexer.ccomment_level == 0:
t.value = t.lexer.lexdata[t.lexer.code_start:t.lexer.lexpos + 1 - 3]
t.type = "CCOMMENT"
t.lexer.lineno += t.value.count('\n')
t.lexer.begin('INITIAL')
return t | python | def t_ccomment_close(self, t):
r'\*\/'
t.lexer.ccomment_level -= 1
if t.lexer.ccomment_level == 0:
t.value = t.lexer.lexdata[t.lexer.code_start:t.lexer.lexpos + 1 - 3]
t.type = "CCOMMENT"
t.lexer.lineno += t.value.count('\n')
t.lexer.begin('INITIAL')
return t | [
"def",
"t_ccomment_close",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"lexer",
".",
"ccomment_level",
"-=",
"1",
"if",
"t",
".",
"lexer",
".",
"ccomment_level",
"==",
"0",
":",
"t",
".",
"value",
"=",
"t",
".",
"lexer",
".",
"lexdata",
"[",
"t",
".",
"lexer",
".",
"code_start",
":",
"t",
".",
"lexer",
".",
"lexpos",
"+",
"1",
"-",
"3",
"]",
"t",
".",
"type",
"=",
"\"CCOMMENT\"",
"t",
".",
"lexer",
".",
"lineno",
"+=",
"t",
".",
"value",
".",
"count",
"(",
"'\\n'",
")",
"t",
".",
"lexer",
".",
"begin",
"(",
"'INITIAL'",
")",
"return",
"t"
] | r'\*\/ | [
"r",
"\\",
"*",
"\\",
"/"
] | train | https://github.com/etingof/apacheconfig/blob/7126dbc0a547779276ac04cf32a051c26781c464/apacheconfig/lexer.py#L56-L65 |
etingof/apacheconfig | apacheconfig/lexer.py | BaseApacheConfigLexer.t_OPTION_AND_VALUE | def t_OPTION_AND_VALUE(self, t):
r'[^ \n\r\t=#]+[ \t=]+[^\r\n#]+' # TODO(etingof) escape hash
if t.value.endswith('\\'):
t.lexer.multiline_newline_seen = False
t.lexer.code_start = t.lexer.lexpos - len(t.value)
t.lexer.begin('multiline')
return
lineno = len(re.findall(r'\r\n|\n|\r', t.value))
option, value = self._parse_option_value(t.value)
process, option, value = self._pre_parse_value(option, value)
if not process:
return
if value.startswith('<<'):
t.lexer.heredoc_anchor = value[2:].strip()
t.lexer.heredoc_option = option
t.lexer.code_start = t.lexer.lexpos
t.lexer.begin('heredoc')
return
t.value = option, value
t.lexer.lineno += lineno
return t | python | def t_OPTION_AND_VALUE(self, t):
r'[^ \n\r\t=#]+[ \t=]+[^\r\n#]+' # TODO(etingof) escape hash
if t.value.endswith('\\'):
t.lexer.multiline_newline_seen = False
t.lexer.code_start = t.lexer.lexpos - len(t.value)
t.lexer.begin('multiline')
return
lineno = len(re.findall(r'\r\n|\n|\r', t.value))
option, value = self._parse_option_value(t.value)
process, option, value = self._pre_parse_value(option, value)
if not process:
return
if value.startswith('<<'):
t.lexer.heredoc_anchor = value[2:].strip()
t.lexer.heredoc_option = option
t.lexer.code_start = t.lexer.lexpos
t.lexer.begin('heredoc')
return
t.value = option, value
t.lexer.lineno += lineno
return t | [
"def",
"t_OPTION_AND_VALUE",
"(",
"self",
",",
"t",
")",
":",
"# TODO(etingof) escape hash",
"if",
"t",
".",
"value",
".",
"endswith",
"(",
"'\\\\'",
")",
":",
"t",
".",
"lexer",
".",
"multiline_newline_seen",
"=",
"False",
"t",
".",
"lexer",
".",
"code_start",
"=",
"t",
".",
"lexer",
".",
"lexpos",
"-",
"len",
"(",
"t",
".",
"value",
")",
"t",
".",
"lexer",
".",
"begin",
"(",
"'multiline'",
")",
"return",
"lineno",
"=",
"len",
"(",
"re",
".",
"findall",
"(",
"r'\\r\\n|\\n|\\r'",
",",
"t",
".",
"value",
")",
")",
"option",
",",
"value",
"=",
"self",
".",
"_parse_option_value",
"(",
"t",
".",
"value",
")",
"process",
",",
"option",
",",
"value",
"=",
"self",
".",
"_pre_parse_value",
"(",
"option",
",",
"value",
")",
"if",
"not",
"process",
":",
"return",
"if",
"value",
".",
"startswith",
"(",
"'<<'",
")",
":",
"t",
".",
"lexer",
".",
"heredoc_anchor",
"=",
"value",
"[",
"2",
":",
"]",
".",
"strip",
"(",
")",
"t",
".",
"lexer",
".",
"heredoc_option",
"=",
"option",
"t",
".",
"lexer",
".",
"code_start",
"=",
"t",
".",
"lexer",
".",
"lexpos",
"t",
".",
"lexer",
".",
"begin",
"(",
"'heredoc'",
")",
"return",
"t",
".",
"value",
"=",
"option",
",",
"value",
"t",
".",
"lexer",
".",
"lineno",
"+=",
"lineno",
"return",
"t"
] | r'[^ \n\r\t=#]+[ \t=]+[^\r\n#]+ | [
"r",
"[",
"^",
"\\",
"n",
"\\",
"r",
"\\",
"t",
"=",
"#",
"]",
"+",
"[",
"\\",
"t",
"=",
"]",
"+",
"[",
"^",
"\\",
"r",
"\\",
"n#",
"]",
"+"
] | train | https://github.com/etingof/apacheconfig/blob/7126dbc0a547779276ac04cf32a051c26781c464/apacheconfig/lexer.py#L183-L210 |
etingof/apacheconfig | apacheconfig/lexer.py | BaseApacheConfigLexer.t_multiline_OPTION_AND_VALUE | def t_multiline_OPTION_AND_VALUE(self, t):
r'[^\r\n]+'
t.lexer.multiline_newline_seen = False
if t.value.endswith('\\'):
return
t.type = "OPTION_AND_VALUE"
t.lexer.begin('INITIAL')
value = t.lexer.lexdata[t.lexer.code_start:t.lexer.lexpos + 1]
t.lexer.lineno += len(re.findall(r'\r\n|\n|\r', value))
value = value.replace('\\\n', '').replace('\r', '').replace('\n', '')
option, value = self._parse_option_value(value)
process, option, value = self._pre_parse_value(option, value)
if not process:
return
t.value = option, value
return t | python | def t_multiline_OPTION_AND_VALUE(self, t):
r'[^\r\n]+'
t.lexer.multiline_newline_seen = False
if t.value.endswith('\\'):
return
t.type = "OPTION_AND_VALUE"
t.lexer.begin('INITIAL')
value = t.lexer.lexdata[t.lexer.code_start:t.lexer.lexpos + 1]
t.lexer.lineno += len(re.findall(r'\r\n|\n|\r', value))
value = value.replace('\\\n', '').replace('\r', '').replace('\n', '')
option, value = self._parse_option_value(value)
process, option, value = self._pre_parse_value(option, value)
if not process:
return
t.value = option, value
return t | [
"def",
"t_multiline_OPTION_AND_VALUE",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"lexer",
".",
"multiline_newline_seen",
"=",
"False",
"if",
"t",
".",
"value",
".",
"endswith",
"(",
"'\\\\'",
")",
":",
"return",
"t",
".",
"type",
"=",
"\"OPTION_AND_VALUE\"",
"t",
".",
"lexer",
".",
"begin",
"(",
"'INITIAL'",
")",
"value",
"=",
"t",
".",
"lexer",
".",
"lexdata",
"[",
"t",
".",
"lexer",
".",
"code_start",
":",
"t",
".",
"lexer",
".",
"lexpos",
"+",
"1",
"]",
"t",
".",
"lexer",
".",
"lineno",
"+=",
"len",
"(",
"re",
".",
"findall",
"(",
"r'\\r\\n|\\n|\\r'",
",",
"value",
")",
")",
"value",
"=",
"value",
".",
"replace",
"(",
"'\\\\\\n'",
",",
"''",
")",
".",
"replace",
"(",
"'\\r'",
",",
"''",
")",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
"option",
",",
"value",
"=",
"self",
".",
"_parse_option_value",
"(",
"value",
")",
"process",
",",
"option",
",",
"value",
"=",
"self",
".",
"_pre_parse_value",
"(",
"option",
",",
"value",
")",
"if",
"not",
"process",
":",
"return",
"t",
".",
"value",
"=",
"option",
",",
"value",
"return",
"t"
] | r'[^\r\n]+ | [
"r",
"[",
"^",
"\\",
"r",
"\\",
"n",
"]",
"+"
] | train | https://github.com/etingof/apacheconfig/blob/7126dbc0a547779276ac04cf32a051c26781c464/apacheconfig/lexer.py#L212-L234 |
etingof/apacheconfig | apacheconfig/lexer.py | BaseApacheConfigLexer.t_multiline_NEWLINE | def t_multiline_NEWLINE(self, t):
r'\r\n|\n|\r'
if t.lexer.multiline_newline_seen:
return self.t_multiline_OPTION_AND_VALUE(t)
t.lexer.multiline_newline_seen = True | python | def t_multiline_NEWLINE(self, t):
r'\r\n|\n|\r'
if t.lexer.multiline_newline_seen:
return self.t_multiline_OPTION_AND_VALUE(t)
t.lexer.multiline_newline_seen = True | [
"def",
"t_multiline_NEWLINE",
"(",
"self",
",",
"t",
")",
":",
"if",
"t",
".",
"lexer",
".",
"multiline_newline_seen",
":",
"return",
"self",
".",
"t_multiline_OPTION_AND_VALUE",
"(",
"t",
")",
"t",
".",
"lexer",
".",
"multiline_newline_seen",
"=",
"True"
] | r'\r\n|\n|\r | [
"r",
"\\",
"r",
"\\",
"n|",
"\\",
"n|",
"\\",
"r"
] | train | https://github.com/etingof/apacheconfig/blob/7126dbc0a547779276ac04cf32a051c26781c464/apacheconfig/lexer.py#L236-L240 |
etingof/apacheconfig | apacheconfig/lexer.py | BaseApacheConfigLexer.t_heredoc_OPTION_AND_VALUE | def t_heredoc_OPTION_AND_VALUE(self, t):
r'[^\r\n]+'
if t.value.lstrip() != t.lexer.heredoc_anchor:
return
t.type = "OPTION_AND_VALUE"
t.lexer.begin('INITIAL')
value = t.lexer.lexdata[t.lexer.code_start + 1:t.lexer.lexpos - len(t.lexer.heredoc_anchor)]
t.lexer.lineno += len(re.findall(r'\r\n|\n|\r', t.value))
t.value = t.lexer.heredoc_option, value
return t | python | def t_heredoc_OPTION_AND_VALUE(self, t):
r'[^\r\n]+'
if t.value.lstrip() != t.lexer.heredoc_anchor:
return
t.type = "OPTION_AND_VALUE"
t.lexer.begin('INITIAL')
value = t.lexer.lexdata[t.lexer.code_start + 1:t.lexer.lexpos - len(t.lexer.heredoc_anchor)]
t.lexer.lineno += len(re.findall(r'\r\n|\n|\r', t.value))
t.value = t.lexer.heredoc_option, value
return t | [
"def",
"t_heredoc_OPTION_AND_VALUE",
"(",
"self",
",",
"t",
")",
":",
"if",
"t",
".",
"value",
".",
"lstrip",
"(",
")",
"!=",
"t",
".",
"lexer",
".",
"heredoc_anchor",
":",
"return",
"t",
".",
"type",
"=",
"\"OPTION_AND_VALUE\"",
"t",
".",
"lexer",
".",
"begin",
"(",
"'INITIAL'",
")",
"value",
"=",
"t",
".",
"lexer",
".",
"lexdata",
"[",
"t",
".",
"lexer",
".",
"code_start",
"+",
"1",
":",
"t",
".",
"lexer",
".",
"lexpos",
"-",
"len",
"(",
"t",
".",
"lexer",
".",
"heredoc_anchor",
")",
"]",
"t",
".",
"lexer",
".",
"lineno",
"+=",
"len",
"(",
"re",
".",
"findall",
"(",
"r'\\r\\n|\\n|\\r'",
",",
"t",
".",
"value",
")",
")",
"t",
".",
"value",
"=",
"t",
".",
"lexer",
".",
"heredoc_option",
",",
"value",
"return",
"t"
] | r'[^\r\n]+ | [
"r",
"[",
"^",
"\\",
"r",
"\\",
"n",
"]",
"+"
] | train | https://github.com/etingof/apacheconfig/blob/7126dbc0a547779276ac04cf32a051c26781c464/apacheconfig/lexer.py#L245-L259 |
amol-/depot | depot/manager.py | DepotManager.set_default | def set_default(cls, name):
"""Replaces the current application default depot"""
if name not in cls._depots:
raise RuntimeError('%s depot has not been configured' % (name,))
cls._default_depot = name | python | def set_default(cls, name):
"""Replaces the current application default depot"""
if name not in cls._depots:
raise RuntimeError('%s depot has not been configured' % (name,))
cls._default_depot = name | [
"def",
"set_default",
"(",
"cls",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"cls",
".",
"_depots",
":",
"raise",
"RuntimeError",
"(",
"'%s depot has not been configured'",
"%",
"(",
"name",
",",
")",
")",
"cls",
".",
"_default_depot",
"=",
"name"
] | Replaces the current application default depot | [
"Replaces",
"the",
"current",
"application",
"default",
"depot"
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/depot/manager.py#L25-L29 |
amol-/depot | depot/manager.py | DepotManager.get | def get(cls, name=None):
"""Gets the application wide depot instance.
Might return ``None`` if :meth:`configure` has not been
called yet.
"""
if name is None:
name = cls._default_depot
name = cls.resolve_alias(name) # resolve alias
return cls._depots.get(name) | python | def get(cls, name=None):
"""Gets the application wide depot instance.
Might return ``None`` if :meth:`configure` has not been
called yet.
"""
if name is None:
name = cls._default_depot
name = cls.resolve_alias(name) # resolve alias
return cls._depots.get(name) | [
"def",
"get",
"(",
"cls",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"cls",
".",
"_default_depot",
"name",
"=",
"cls",
".",
"resolve_alias",
"(",
"name",
")",
"# resolve alias",
"return",
"cls",
".",
"_depots",
".",
"get",
"(",
"name",
")"
] | Gets the application wide depot instance.
Might return ``None`` if :meth:`configure` has not been
called yet. | [
"Gets",
"the",
"application",
"wide",
"depot",
"instance",
"."
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/depot/manager.py#L51-L62 |
amol-/depot | depot/manager.py | DepotManager.get_file | def get_file(cls, path):
"""Retrieves a file by storage name and fileid in the form of a path
Path is expected to be ``storage_name/fileid``.
"""
depot_name, file_id = path.split('/', 1)
depot = cls.get(depot_name)
return depot.get(file_id) | python | def get_file(cls, path):
"""Retrieves a file by storage name and fileid in the form of a path
Path is expected to be ``storage_name/fileid``.
"""
depot_name, file_id = path.split('/', 1)
depot = cls.get(depot_name)
return depot.get(file_id) | [
"def",
"get_file",
"(",
"cls",
",",
"path",
")",
":",
"depot_name",
",",
"file_id",
"=",
"path",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"depot",
"=",
"cls",
".",
"get",
"(",
"depot_name",
")",
"return",
"depot",
".",
"get",
"(",
"file_id",
")"
] | Retrieves a file by storage name and fileid in the form of a path
Path is expected to be ``storage_name/fileid``. | [
"Retrieves",
"a",
"file",
"by",
"storage",
"name",
"and",
"fileid",
"in",
"the",
"form",
"of",
"a",
"path"
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/depot/manager.py#L65-L72 |
amol-/depot | depot/manager.py | DepotManager.configure | def configure(cls, name, config, prefix='depot.'):
"""Configures an application depot.
This configures the application wide depot from a settings dictionary.
The settings dictionary is usually loaded from an application configuration
file where all the depot options are specified with a given ``prefix``.
The default ``prefix`` is *depot.*, the minimum required setting
is ``depot.backend`` which specified the required backend for files storage.
Additional options depend on the choosen backend.
"""
if name in cls._depots:
raise RuntimeError('Depot %s has already been configured' % (name,))
if cls._default_depot is None:
cls._default_depot = name
cls._depots[name] = cls.from_config(config, prefix)
return cls._depots[name] | python | def configure(cls, name, config, prefix='depot.'):
"""Configures an application depot.
This configures the application wide depot from a settings dictionary.
The settings dictionary is usually loaded from an application configuration
file where all the depot options are specified with a given ``prefix``.
The default ``prefix`` is *depot.*, the minimum required setting
is ``depot.backend`` which specified the required backend for files storage.
Additional options depend on the choosen backend.
"""
if name in cls._depots:
raise RuntimeError('Depot %s has already been configured' % (name,))
if cls._default_depot is None:
cls._default_depot = name
cls._depots[name] = cls.from_config(config, prefix)
return cls._depots[name] | [
"def",
"configure",
"(",
"cls",
",",
"name",
",",
"config",
",",
"prefix",
"=",
"'depot.'",
")",
":",
"if",
"name",
"in",
"cls",
".",
"_depots",
":",
"raise",
"RuntimeError",
"(",
"'Depot %s has already been configured'",
"%",
"(",
"name",
",",
")",
")",
"if",
"cls",
".",
"_default_depot",
"is",
"None",
":",
"cls",
".",
"_default_depot",
"=",
"name",
"cls",
".",
"_depots",
"[",
"name",
"]",
"=",
"cls",
".",
"from_config",
"(",
"config",
",",
"prefix",
")",
"return",
"cls",
".",
"_depots",
"[",
"name",
"]"
] | Configures an application depot.
This configures the application wide depot from a settings dictionary.
The settings dictionary is usually loaded from an application configuration
file where all the depot options are specified with a given ``prefix``.
The default ``prefix`` is *depot.*, the minimum required setting
is ``depot.backend`` which specified the required backend for files storage.
Additional options depend on the choosen backend. | [
"Configures",
"an",
"application",
"depot",
"."
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/depot/manager.py#L84-L103 |
amol-/depot | depot/manager.py | DepotManager.make_middleware | def make_middleware(cls, app, **options):
"""Creates the application WSGI middleware in charge of serving local files.
A Depot middleware is required if your application wants to serve files from
storages that don't directly provide and HTTP interface like
:class:`depot.io.local.LocalFileStorage` and :class:`depot.io.gridfs.GridFSStorage`
"""
from depot.middleware import DepotMiddleware
mw = DepotMiddleware(app, **options)
cls.set_middleware(mw)
return mw | python | def make_middleware(cls, app, **options):
"""Creates the application WSGI middleware in charge of serving local files.
A Depot middleware is required if your application wants to serve files from
storages that don't directly provide and HTTP interface like
:class:`depot.io.local.LocalFileStorage` and :class:`depot.io.gridfs.GridFSStorage`
"""
from depot.middleware import DepotMiddleware
mw = DepotMiddleware(app, **options)
cls.set_middleware(mw)
return mw | [
"def",
"make_middleware",
"(",
"cls",
",",
"app",
",",
"*",
"*",
"options",
")",
":",
"from",
"depot",
".",
"middleware",
"import",
"DepotMiddleware",
"mw",
"=",
"DepotMiddleware",
"(",
"app",
",",
"*",
"*",
"options",
")",
"cls",
".",
"set_middleware",
"(",
"mw",
")",
"return",
"mw"
] | Creates the application WSGI middleware in charge of serving local files.
A Depot middleware is required if your application wants to serve files from
storages that don't directly provide and HTTP interface like
:class:`depot.io.local.LocalFileStorage` and :class:`depot.io.gridfs.GridFSStorage` | [
"Creates",
"the",
"application",
"WSGI",
"middleware",
"in",
"charge",
"of",
"serving",
"local",
"files",
"."
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/depot/manager.py#L122-L133 |
amol-/depot | depot/manager.py | DepotManager.from_config | def from_config(cls, config, prefix='depot.'):
"""Creates a new depot from a settings dictionary.
Behaves like the :meth:`configure` method but instead of configuring the application
depot it creates a new one each time.
"""
config = config or {}
# Get preferred storage backend
backend = config.get(prefix + 'backend', 'depot.io.local.LocalFileStorage')
# Get all options
prefixlen = len(prefix)
options = dict((k[prefixlen:], config[k]) for k in config.keys() if k.startswith(prefix))
# Backend is already passed as a positional argument
options.pop('backend', None)
return cls._new(backend, **options) | python | def from_config(cls, config, prefix='depot.'):
"""Creates a new depot from a settings dictionary.
Behaves like the :meth:`configure` method but instead of configuring the application
depot it creates a new one each time.
"""
config = config or {}
# Get preferred storage backend
backend = config.get(prefix + 'backend', 'depot.io.local.LocalFileStorage')
# Get all options
prefixlen = len(prefix)
options = dict((k[prefixlen:], config[k]) for k in config.keys() if k.startswith(prefix))
# Backend is already passed as a positional argument
options.pop('backend', None)
return cls._new(backend, **options) | [
"def",
"from_config",
"(",
"cls",
",",
"config",
",",
"prefix",
"=",
"'depot.'",
")",
":",
"config",
"=",
"config",
"or",
"{",
"}",
"# Get preferred storage backend",
"backend",
"=",
"config",
".",
"get",
"(",
"prefix",
"+",
"'backend'",
",",
"'depot.io.local.LocalFileStorage'",
")",
"# Get all options",
"prefixlen",
"=",
"len",
"(",
"prefix",
")",
"options",
"=",
"dict",
"(",
"(",
"k",
"[",
"prefixlen",
":",
"]",
",",
"config",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"config",
".",
"keys",
"(",
")",
"if",
"k",
".",
"startswith",
"(",
"prefix",
")",
")",
"# Backend is already passed as a positional argument",
"options",
".",
"pop",
"(",
"'backend'",
",",
"None",
")",
"return",
"cls",
".",
"_new",
"(",
"backend",
",",
"*",
"*",
"options",
")"
] | Creates a new depot from a settings dictionary.
Behaves like the :meth:`configure` method but instead of configuring the application
depot it creates a new one each time. | [
"Creates",
"a",
"new",
"depot",
"from",
"a",
"settings",
"dictionary",
"."
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/depot/manager.py#L143-L160 |
amol-/depot | depot/manager.py | DepotManager._clear | def _clear(cls):
"""This is only for testing pourposes, resets the DepotManager status
This is to simplify writing test fixtures, resets the DepotManager global
status and removes the informations related to the current configured depots
and middleware.
"""
cls._default_depot = None
cls._depots = {}
cls._middleware = None
cls._aliases = {} | python | def _clear(cls):
"""This is only for testing pourposes, resets the DepotManager status
This is to simplify writing test fixtures, resets the DepotManager global
status and removes the informations related to the current configured depots
and middleware.
"""
cls._default_depot = None
cls._depots = {}
cls._middleware = None
cls._aliases = {} | [
"def",
"_clear",
"(",
"cls",
")",
":",
"cls",
".",
"_default_depot",
"=",
"None",
"cls",
".",
"_depots",
"=",
"{",
"}",
"cls",
".",
"_middleware",
"=",
"None",
"cls",
".",
"_aliases",
"=",
"{",
"}"
] | This is only for testing pourposes, resets the DepotManager status
This is to simplify writing test fixtures, resets the DepotManager global
status and removes the informations related to the current configured depots
and middleware. | [
"This",
"is",
"only",
"for",
"testing",
"pourposes",
"resets",
"the",
"DepotManager",
"status"
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/depot/manager.py#L163-L173 |
amol-/depot | examples/turbogears/depotexample/websetup/schema.py | setup_schema | def setup_schema(command, conf, vars):
"""Place any commands to setup depotexample here"""
# Load the models
# <websetup.websetup.schema.before.model.import>
from depotexample import model
# <websetup.websetup.schema.after.model.import>
# <websetup.websetup.schema.before.metadata.create_all>
print("Creating tables")
model.metadata.create_all(bind=config['tg.app_globals'].sa_engine)
# <websetup.websetup.schema.after.metadata.create_all>
transaction.commit()
print('Initializing Migrations')
import alembic.config, alembic.command
alembic_cfg = alembic.config.Config()
alembic_cfg.set_main_option("script_location", "migration")
alembic_cfg.set_main_option("sqlalchemy.url", config['sqlalchemy.url'])
alembic.command.stamp(alembic_cfg, "head") | python | def setup_schema(command, conf, vars):
"""Place any commands to setup depotexample here"""
# Load the models
# <websetup.websetup.schema.before.model.import>
from depotexample import model
# <websetup.websetup.schema.after.model.import>
# <websetup.websetup.schema.before.metadata.create_all>
print("Creating tables")
model.metadata.create_all(bind=config['tg.app_globals'].sa_engine)
# <websetup.websetup.schema.after.metadata.create_all>
transaction.commit()
print('Initializing Migrations')
import alembic.config, alembic.command
alembic_cfg = alembic.config.Config()
alembic_cfg.set_main_option("script_location", "migration")
alembic_cfg.set_main_option("sqlalchemy.url", config['sqlalchemy.url'])
alembic.command.stamp(alembic_cfg, "head") | [
"def",
"setup_schema",
"(",
"command",
",",
"conf",
",",
"vars",
")",
":",
"# Load the models",
"# <websetup.websetup.schema.before.model.import>",
"from",
"depotexample",
"import",
"model",
"# <websetup.websetup.schema.after.model.import>",
"# <websetup.websetup.schema.before.metadata.create_all>",
"print",
"(",
"\"Creating tables\"",
")",
"model",
".",
"metadata",
".",
"create_all",
"(",
"bind",
"=",
"config",
"[",
"'tg.app_globals'",
"]",
".",
"sa_engine",
")",
"# <websetup.websetup.schema.after.metadata.create_all>",
"transaction",
".",
"commit",
"(",
")",
"print",
"(",
"'Initializing Migrations'",
")",
"import",
"alembic",
".",
"config",
",",
"alembic",
".",
"command",
"alembic_cfg",
"=",
"alembic",
".",
"config",
".",
"Config",
"(",
")",
"alembic_cfg",
".",
"set_main_option",
"(",
"\"script_location\"",
",",
"\"migration\"",
")",
"alembic_cfg",
".",
"set_main_option",
"(",
"\"sqlalchemy.url\"",
",",
"config",
"[",
"'sqlalchemy.url'",
"]",
")",
"alembic",
".",
"command",
".",
"stamp",
"(",
"alembic_cfg",
",",
"\"head\"",
")"
] | Place any commands to setup depotexample here | [
"Place",
"any",
"commands",
"to",
"setup",
"depotexample",
"here"
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/examples/turbogears/depotexample/websetup/schema.py#L9-L28 |
amol-/depot | examples/turbogears/depotexample/model/auth.py | User.permissions | def permissions(self):
"""Return a set with all permissions granted to the user."""
perms = set()
for g in self.groups:
perms = perms | set(g.permissions)
return perms | python | def permissions(self):
"""Return a set with all permissions granted to the user."""
perms = set()
for g in self.groups:
perms = perms | set(g.permissions)
return perms | [
"def",
"permissions",
"(",
"self",
")",
":",
"perms",
"=",
"set",
"(",
")",
"for",
"g",
"in",
"self",
".",
"groups",
":",
"perms",
"=",
"perms",
"|",
"set",
"(",
"g",
".",
"permissions",
")",
"return",
"perms"
] | Return a set with all permissions granted to the user. | [
"Return",
"a",
"set",
"with",
"all",
"permissions",
"granted",
"to",
"the",
"user",
"."
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/examples/turbogears/depotexample/model/auth.py#L88-L93 |
amol-/depot | examples/turbogears/depotexample/model/auth.py | User.by_email_address | def by_email_address(cls, email):
"""Return the user object whose email address is ``email``."""
return DBSession.query(cls).filter_by(email_address=email).first() | python | def by_email_address(cls, email):
"""Return the user object whose email address is ``email``."""
return DBSession.query(cls).filter_by(email_address=email).first() | [
"def",
"by_email_address",
"(",
"cls",
",",
"email",
")",
":",
"return",
"DBSession",
".",
"query",
"(",
"cls",
")",
".",
"filter_by",
"(",
"email_address",
"=",
"email",
")",
".",
"first",
"(",
")"
] | Return the user object whose email address is ``email``. | [
"Return",
"the",
"user",
"object",
"whose",
"email",
"address",
"is",
"email",
"."
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/examples/turbogears/depotexample/model/auth.py#L96-L98 |
amol-/depot | examples/turbogears/depotexample/model/auth.py | User.by_user_name | def by_user_name(cls, username):
"""Return the user object whose user name is ``username``."""
return DBSession.query(cls).filter_by(user_name=username).first() | python | def by_user_name(cls, username):
"""Return the user object whose user name is ``username``."""
return DBSession.query(cls).filter_by(user_name=username).first() | [
"def",
"by_user_name",
"(",
"cls",
",",
"username",
")",
":",
"return",
"DBSession",
".",
"query",
"(",
"cls",
")",
".",
"filter_by",
"(",
"user_name",
"=",
"username",
")",
".",
"first",
"(",
")"
] | Return the user object whose user name is ``username``. | [
"Return",
"the",
"user",
"object",
"whose",
"user",
"name",
"is",
"username",
"."
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/examples/turbogears/depotexample/model/auth.py#L101-L103 |
amol-/depot | examples/turbogears/depotexample/model/auth.py | User.validate_password | def validate_password(self, password):
"""
Check the password against existing credentials.
:param password: the password that was provided by the user to
try and authenticate. This is the clear text version that we will
need to match against the hashed one in the database.
:type password: unicode object.
:return: Whether the password is valid.
:rtype: bool
"""
hash = sha256()
hash.update((password + self.password[:64]).encode('utf-8'))
return self.password[64:] == hash.hexdigest() | python | def validate_password(self, password):
"""
Check the password against existing credentials.
:param password: the password that was provided by the user to
try and authenticate. This is the clear text version that we will
need to match against the hashed one in the database.
:type password: unicode object.
:return: Whether the password is valid.
:rtype: bool
"""
hash = sha256()
hash.update((password + self.password[:64]).encode('utf-8'))
return self.password[64:] == hash.hexdigest() | [
"def",
"validate_password",
"(",
"self",
",",
"password",
")",
":",
"hash",
"=",
"sha256",
"(",
")",
"hash",
".",
"update",
"(",
"(",
"password",
"+",
"self",
".",
"password",
"[",
":",
"64",
"]",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"return",
"self",
".",
"password",
"[",
"64",
":",
"]",
"==",
"hash",
".",
"hexdigest",
"(",
")"
] | Check the password against existing credentials.
:param password: the password that was provided by the user to
try and authenticate. This is the clear text version that we will
need to match against the hashed one in the database.
:type password: unicode object.
:return: Whether the password is valid.
:rtype: bool | [
"Check",
"the",
"password",
"against",
"existing",
"credentials",
"."
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/examples/turbogears/depotexample/model/auth.py#L132-L146 |
amol-/depot | examples/turbogears/depotexample/controllers/error.py | ErrorController.document | def document(self, *args, **kwargs):
"""Render the error document"""
resp = request.environ.get('pylons.original_response')
default_message = ("<p>We're sorry but we weren't able to process "
" this request.</p>")
values = dict(prefix=request.environ.get('SCRIPT_NAME', ''),
code=request.params.get('code', resp.status_int),
message=request.params.get('message', default_message))
return values | python | def document(self, *args, **kwargs):
"""Render the error document"""
resp = request.environ.get('pylons.original_response')
default_message = ("<p>We're sorry but we weren't able to process "
" this request.</p>")
values = dict(prefix=request.environ.get('SCRIPT_NAME', ''),
code=request.params.get('code', resp.status_int),
message=request.params.get('message', default_message))
return values | [
"def",
"document",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"resp",
"=",
"request",
".",
"environ",
".",
"get",
"(",
"'pylons.original_response'",
")",
"default_message",
"=",
"(",
"\"<p>We're sorry but we weren't able to process \"",
"\" this request.</p>\"",
")",
"values",
"=",
"dict",
"(",
"prefix",
"=",
"request",
".",
"environ",
".",
"get",
"(",
"'SCRIPT_NAME'",
",",
"''",
")",
",",
"code",
"=",
"request",
".",
"params",
".",
"get",
"(",
"'code'",
",",
"resp",
".",
"status_int",
")",
",",
"message",
"=",
"request",
".",
"params",
".",
"get",
"(",
"'message'",
",",
"default_message",
")",
")",
"return",
"values"
] | Render the error document | [
"Render",
"the",
"error",
"document"
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/examples/turbogears/depotexample/controllers/error.py#L22-L30 |
amol-/depot | examples/turbogears/depotexample/config/middleware.py | make_app | def make_app(global_conf, full_stack=True, **app_conf):
"""
Set depotexample up with the settings found in the PasteDeploy configuration
file used.
:param global_conf: The global settings for depotexample (those
defined under the ``[DEFAULT]`` section).
:type global_conf: dict
:param full_stack: Should the whole TG2 stack be set up?
:type full_stack: str or bool
:return: The depotexample application with all the relevant middleware
loaded.
This is the PasteDeploy factory for the depotexample application.
``app_conf`` contains all the application-specific settings (those defined
under ``[app:main]``.
"""
app = make_base_app(global_conf, full_stack=True, **app_conf)
# Wrap your base TurboGears 2 application with custom middleware here
from depot.manager import DepotManager
app = DepotManager.make_middleware(app)
return app | python | def make_app(global_conf, full_stack=True, **app_conf):
"""
Set depotexample up with the settings found in the PasteDeploy configuration
file used.
:param global_conf: The global settings for depotexample (those
defined under the ``[DEFAULT]`` section).
:type global_conf: dict
:param full_stack: Should the whole TG2 stack be set up?
:type full_stack: str or bool
:return: The depotexample application with all the relevant middleware
loaded.
This is the PasteDeploy factory for the depotexample application.
``app_conf`` contains all the application-specific settings (those defined
under ``[app:main]``.
"""
app = make_base_app(global_conf, full_stack=True, **app_conf)
# Wrap your base TurboGears 2 application with custom middleware here
from depot.manager import DepotManager
app = DepotManager.make_middleware(app)
return app | [
"def",
"make_app",
"(",
"global_conf",
",",
"full_stack",
"=",
"True",
",",
"*",
"*",
"app_conf",
")",
":",
"app",
"=",
"make_base_app",
"(",
"global_conf",
",",
"full_stack",
"=",
"True",
",",
"*",
"*",
"app_conf",
")",
"# Wrap your base TurboGears 2 application with custom middleware here",
"from",
"depot",
".",
"manager",
"import",
"DepotManager",
"app",
"=",
"DepotManager",
".",
"make_middleware",
"(",
"app",
")",
"return",
"app"
] | Set depotexample up with the settings found in the PasteDeploy configuration
file used.
:param global_conf: The global settings for depotexample (those
defined under the ``[DEFAULT]`` section).
:type global_conf: dict
:param full_stack: Should the whole TG2 stack be set up?
:type full_stack: str or bool
:return: The depotexample application with all the relevant middleware
loaded.
This is the PasteDeploy factory for the depotexample application.
``app_conf`` contains all the application-specific settings (those defined
under ``[app:main]``. | [
"Set",
"depotexample",
"up",
"with",
"the",
"settings",
"found",
"in",
"the",
"PasteDeploy",
"configuration",
"file",
"used",
".",
":",
"param",
"global_conf",
":",
"The",
"global",
"settings",
"for",
"depotexample",
"(",
"those",
"defined",
"under",
"the",
"[",
"DEFAULT",
"]",
"section",
")",
".",
":",
"type",
"global_conf",
":",
"dict",
":",
"param",
"full_stack",
":",
"Should",
"the",
"whole",
"TG2",
"stack",
"be",
"set",
"up?",
":",
"type",
"full_stack",
":",
"str",
"or",
"bool",
":",
"return",
":",
"The",
"depotexample",
"application",
"with",
"all",
"the",
"relevant",
"middleware",
"loaded",
".",
"This",
"is",
"the",
"PasteDeploy",
"factory",
"for",
"the",
"depotexample",
"application",
".",
"app_conf",
"contains",
"all",
"the",
"application",
"-",
"specific",
"settings",
"(",
"those",
"defined",
"under",
"[",
"app",
":",
"main",
"]",
"."
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/examples/turbogears/depotexample/config/middleware.py#L15-L41 |
amol-/depot | depot/fields/upload.py | UploadedFile.process_content | def process_content(self, content, filename=None, content_type=None):
"""Standard implementation of :meth:`.DepotFileInfo.process_content`
This is the standard depot implementation of files upload, it will
store the file on the default depot and will provide the standard
attributes.
Subclasses will need to call this method to ensure the standard
set of attributes is provided.
"""
file_path, file_id = self.store_content(content, filename, content_type)
self['file_id'] = file_id
self['path'] = file_path
saved_file = self.file
self['filename'] = saved_file.filename
self['content_type'] = saved_file.content_type
self['uploaded_at'] = saved_file.last_modified.strftime('%Y-%m-%d %H:%M:%S')
self['_public_url'] = saved_file.public_url | python | def process_content(self, content, filename=None, content_type=None):
"""Standard implementation of :meth:`.DepotFileInfo.process_content`
This is the standard depot implementation of files upload, it will
store the file on the default depot and will provide the standard
attributes.
Subclasses will need to call this method to ensure the standard
set of attributes is provided.
"""
file_path, file_id = self.store_content(content, filename, content_type)
self['file_id'] = file_id
self['path'] = file_path
saved_file = self.file
self['filename'] = saved_file.filename
self['content_type'] = saved_file.content_type
self['uploaded_at'] = saved_file.last_modified.strftime('%Y-%m-%d %H:%M:%S')
self['_public_url'] = saved_file.public_url | [
"def",
"process_content",
"(",
"self",
",",
"content",
",",
"filename",
"=",
"None",
",",
"content_type",
"=",
"None",
")",
":",
"file_path",
",",
"file_id",
"=",
"self",
".",
"store_content",
"(",
"content",
",",
"filename",
",",
"content_type",
")",
"self",
"[",
"'file_id'",
"]",
"=",
"file_id",
"self",
"[",
"'path'",
"]",
"=",
"file_path",
"saved_file",
"=",
"self",
".",
"file",
"self",
"[",
"'filename'",
"]",
"=",
"saved_file",
".",
"filename",
"self",
"[",
"'content_type'",
"]",
"=",
"saved_file",
".",
"content_type",
"self",
"[",
"'uploaded_at'",
"]",
"=",
"saved_file",
".",
"last_modified",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
")",
"self",
"[",
"'_public_url'",
"]",
"=",
"saved_file",
".",
"public_url"
] | Standard implementation of :meth:`.DepotFileInfo.process_content`
This is the standard depot implementation of files upload, it will
store the file on the default depot and will provide the standard
attributes.
Subclasses will need to call this method to ensure the standard
set of attributes is provided. | [
"Standard",
"implementation",
"of",
":",
"meth",
":",
".",
"DepotFileInfo",
".",
"process_content"
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/depot/fields/upload.py#L26-L45 |
amol-/depot | examples/turbogears/depotexample/websetup/bootstrap.py | bootstrap | def bootstrap(command, conf, vars):
"""Place any commands to setup depotexample here"""
# <websetup.bootstrap.before.auth
from sqlalchemy.exc import IntegrityError
try:
u = model.User()
u.user_name = 'manager'
u.display_name = 'Example manager'
u.email_address = '[email protected]'
u.password = 'managepass'
model.DBSession.add(u)
g = model.Group()
g.group_name = 'managers'
g.display_name = 'Managers Group'
g.users.append(u)
model.DBSession.add(g)
p = model.Permission()
p.permission_name = 'manage'
p.description = 'This permission give an administrative right to the bearer'
p.groups.append(g)
model.DBSession.add(p)
u1 = model.User()
u1.user_name = 'editor'
u1.display_name = 'Example editor'
u1.email_address = '[email protected]'
u1.password = 'editpass'
model.DBSession.add(u1)
model.DBSession.flush()
transaction.commit()
except IntegrityError:
print('Warning, there was a problem adding your auth data, it may have already been added:')
import traceback
print(traceback.format_exc())
transaction.abort()
print('Continuing with bootstrapping...') | python | def bootstrap(command, conf, vars):
"""Place any commands to setup depotexample here"""
# <websetup.bootstrap.before.auth
from sqlalchemy.exc import IntegrityError
try:
u = model.User()
u.user_name = 'manager'
u.display_name = 'Example manager'
u.email_address = '[email protected]'
u.password = 'managepass'
model.DBSession.add(u)
g = model.Group()
g.group_name = 'managers'
g.display_name = 'Managers Group'
g.users.append(u)
model.DBSession.add(g)
p = model.Permission()
p.permission_name = 'manage'
p.description = 'This permission give an administrative right to the bearer'
p.groups.append(g)
model.DBSession.add(p)
u1 = model.User()
u1.user_name = 'editor'
u1.display_name = 'Example editor'
u1.email_address = '[email protected]'
u1.password = 'editpass'
model.DBSession.add(u1)
model.DBSession.flush()
transaction.commit()
except IntegrityError:
print('Warning, there was a problem adding your auth data, it may have already been added:')
import traceback
print(traceback.format_exc())
transaction.abort()
print('Continuing with bootstrapping...') | [
"def",
"bootstrap",
"(",
"command",
",",
"conf",
",",
"vars",
")",
":",
"# <websetup.bootstrap.before.auth",
"from",
"sqlalchemy",
".",
"exc",
"import",
"IntegrityError",
"try",
":",
"u",
"=",
"model",
".",
"User",
"(",
")",
"u",
".",
"user_name",
"=",
"'manager'",
"u",
".",
"display_name",
"=",
"'Example manager'",
"u",
".",
"email_address",
"=",
"'[email protected]'",
"u",
".",
"password",
"=",
"'managepass'",
"model",
".",
"DBSession",
".",
"add",
"(",
"u",
")",
"g",
"=",
"model",
".",
"Group",
"(",
")",
"g",
".",
"group_name",
"=",
"'managers'",
"g",
".",
"display_name",
"=",
"'Managers Group'",
"g",
".",
"users",
".",
"append",
"(",
"u",
")",
"model",
".",
"DBSession",
".",
"add",
"(",
"g",
")",
"p",
"=",
"model",
".",
"Permission",
"(",
")",
"p",
".",
"permission_name",
"=",
"'manage'",
"p",
".",
"description",
"=",
"'This permission give an administrative right to the bearer'",
"p",
".",
"groups",
".",
"append",
"(",
"g",
")",
"model",
".",
"DBSession",
".",
"add",
"(",
"p",
")",
"u1",
"=",
"model",
".",
"User",
"(",
")",
"u1",
".",
"user_name",
"=",
"'editor'",
"u1",
".",
"display_name",
"=",
"'Example editor'",
"u1",
".",
"email_address",
"=",
"'[email protected]'",
"u1",
".",
"password",
"=",
"'editpass'",
"model",
".",
"DBSession",
".",
"add",
"(",
"u1",
")",
"model",
".",
"DBSession",
".",
"flush",
"(",
")",
"transaction",
".",
"commit",
"(",
")",
"except",
"IntegrityError",
":",
"print",
"(",
"'Warning, there was a problem adding your auth data, it may have already been added:'",
")",
"import",
"traceback",
"print",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"transaction",
".",
"abort",
"(",
")",
"print",
"(",
"'Continuing with bootstrapping...'",
")"
] | Place any commands to setup depotexample here | [
"Place",
"any",
"commands",
"to",
"setup",
"depotexample",
"here"
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/examples/turbogears/depotexample/websetup/bootstrap.py#L10-L53 |
amol-/depot | depot/io/utils.py | file_from_content | def file_from_content(content):
"""Provides a real file object from file content
Converts ``FileStorage``, ``FileIntent`` and
``bytes`` to an actual file.
"""
f = content
if isinstance(content, cgi.FieldStorage):
f = content.file
elif isinstance(content, FileIntent):
f = content._fileobj
elif isinstance(content, byte_string):
f = SpooledTemporaryFile(INMEMORY_FILESIZE)
f.write(content)
f.seek(0)
return f | python | def file_from_content(content):
"""Provides a real file object from file content
Converts ``FileStorage``, ``FileIntent`` and
``bytes`` to an actual file.
"""
f = content
if isinstance(content, cgi.FieldStorage):
f = content.file
elif isinstance(content, FileIntent):
f = content._fileobj
elif isinstance(content, byte_string):
f = SpooledTemporaryFile(INMEMORY_FILESIZE)
f.write(content)
f.seek(0)
return f | [
"def",
"file_from_content",
"(",
"content",
")",
":",
"f",
"=",
"content",
"if",
"isinstance",
"(",
"content",
",",
"cgi",
".",
"FieldStorage",
")",
":",
"f",
"=",
"content",
".",
"file",
"elif",
"isinstance",
"(",
"content",
",",
"FileIntent",
")",
":",
"f",
"=",
"content",
".",
"_fileobj",
"elif",
"isinstance",
"(",
"content",
",",
"byte_string",
")",
":",
"f",
"=",
"SpooledTemporaryFile",
"(",
"INMEMORY_FILESIZE",
")",
"f",
".",
"write",
"(",
"content",
")",
"f",
".",
"seek",
"(",
"0",
")",
"return",
"f"
] | Provides a real file object from file content
Converts ``FileStorage``, ``FileIntent`` and
``bytes`` to an actual file. | [
"Provides",
"a",
"real",
"file",
"object",
"from",
"file",
"content"
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/depot/io/utils.py#L16-L31 |
amol-/depot | depot/io/interfaces.py | FileStorage.fileinfo | def fileinfo(fileobj, filename=None, content_type=None, existing=None):
"""Tries to extract from the given input the actual file object, filename and content_type
This is used by the create and replace methods to correctly deduce their parameters
from the available information when possible.
"""
return _FileInfo(fileobj, filename, content_type).get_info(existing) | python | def fileinfo(fileobj, filename=None, content_type=None, existing=None):
"""Tries to extract from the given input the actual file object, filename and content_type
This is used by the create and replace methods to correctly deduce their parameters
from the available information when possible.
"""
return _FileInfo(fileobj, filename, content_type).get_info(existing) | [
"def",
"fileinfo",
"(",
"fileobj",
",",
"filename",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"existing",
"=",
"None",
")",
":",
"return",
"_FileInfo",
"(",
"fileobj",
",",
"filename",
",",
"content_type",
")",
".",
"get_info",
"(",
"existing",
")"
] | Tries to extract from the given input the actual file object, filename and content_type
This is used by the create and replace methods to correctly deduce their parameters
from the available information when possible. | [
"Tries",
"to",
"extract",
"from",
"the",
"given",
"input",
"the",
"actual",
"file",
"object",
"filename",
"and",
"content_type"
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/depot/io/interfaces.py#L136-L142 |
amol-/depot | examples/turbogears/depotexample/controllers/root.py | RootController.login | def login(self, came_from=lurl('/')):
"""Start the user login."""
login_counter = request.environ.get('repoze.who.logins', 0)
if login_counter > 0:
flash(_('Wrong credentials'), 'warning')
return dict(page='login', login_counter=str(login_counter),
came_from=came_from) | python | def login(self, came_from=lurl('/')):
"""Start the user login."""
login_counter = request.environ.get('repoze.who.logins', 0)
if login_counter > 0:
flash(_('Wrong credentials'), 'warning')
return dict(page='login', login_counter=str(login_counter),
came_from=came_from) | [
"def",
"login",
"(",
"self",
",",
"came_from",
"=",
"lurl",
"(",
"'/'",
")",
")",
":",
"login_counter",
"=",
"request",
".",
"environ",
".",
"get",
"(",
"'repoze.who.logins'",
",",
"0",
")",
"if",
"login_counter",
">",
"0",
":",
"flash",
"(",
"_",
"(",
"'Wrong credentials'",
")",
",",
"'warning'",
")",
"return",
"dict",
"(",
"page",
"=",
"'login'",
",",
"login_counter",
"=",
"str",
"(",
"login_counter",
")",
",",
"came_from",
"=",
"came_from",
")"
] | Start the user login. | [
"Start",
"the",
"user",
"login",
"."
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/examples/turbogears/depotexample/controllers/root.py#L97-L103 |
amol-/depot | examples/turbogears/depotexample/controllers/root.py | RootController.post_login | def post_login(self, came_from=lurl('/')):
"""
Redirect the user to the initially requested page on successful
authentication or redirect her back to the login page if login failed.
"""
if not request.identity:
login_counter = request.environ.get('repoze.who.logins', 0) + 1
redirect('/login',
params=dict(came_from=came_from, __logins=login_counter))
userid = request.identity['repoze.who.userid']
flash(_('Welcome back, %s!') % userid)
redirect(came_from) | python | def post_login(self, came_from=lurl('/')):
"""
Redirect the user to the initially requested page on successful
authentication or redirect her back to the login page if login failed.
"""
if not request.identity:
login_counter = request.environ.get('repoze.who.logins', 0) + 1
redirect('/login',
params=dict(came_from=came_from, __logins=login_counter))
userid = request.identity['repoze.who.userid']
flash(_('Welcome back, %s!') % userid)
redirect(came_from) | [
"def",
"post_login",
"(",
"self",
",",
"came_from",
"=",
"lurl",
"(",
"'/'",
")",
")",
":",
"if",
"not",
"request",
".",
"identity",
":",
"login_counter",
"=",
"request",
".",
"environ",
".",
"get",
"(",
"'repoze.who.logins'",
",",
"0",
")",
"+",
"1",
"redirect",
"(",
"'/login'",
",",
"params",
"=",
"dict",
"(",
"came_from",
"=",
"came_from",
",",
"__logins",
"=",
"login_counter",
")",
")",
"userid",
"=",
"request",
".",
"identity",
"[",
"'repoze.who.userid'",
"]",
"flash",
"(",
"_",
"(",
"'Welcome back, %s!'",
")",
"%",
"userid",
")",
"redirect",
"(",
"came_from",
")"
] | Redirect the user to the initially requested page on successful
authentication or redirect her back to the login page if login failed. | [
"Redirect",
"the",
"user",
"to",
"the",
"initially",
"requested",
"page",
"on",
"successful",
"authentication",
"or",
"redirect",
"her",
"back",
"to",
"the",
"login",
"page",
"if",
"login",
"failed",
"."
] | train | https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/examples/turbogears/depotexample/controllers/root.py#L106-L118 |
jeffreystarr/dateinfer | dateinfer/infer.py | infer | def infer(examples, alt_rules=None):
"""
Returns a datetime.strptime-compliant format string for parsing the *most likely* date format
used in examples. examples is a list containing example date strings.
"""
date_classes = _tag_most_likely(examples)
if alt_rules:
date_classes = _apply_rewrites(date_classes, alt_rules)
else:
date_classes = _apply_rewrites(date_classes, RULES)
date_string = ''
for date_class in date_classes:
date_string += date_class.directive
return date_string | python | def infer(examples, alt_rules=None):
"""
Returns a datetime.strptime-compliant format string for parsing the *most likely* date format
used in examples. examples is a list containing example date strings.
"""
date_classes = _tag_most_likely(examples)
if alt_rules:
date_classes = _apply_rewrites(date_classes, alt_rules)
else:
date_classes = _apply_rewrites(date_classes, RULES)
date_string = ''
for date_class in date_classes:
date_string += date_class.directive
return date_string | [
"def",
"infer",
"(",
"examples",
",",
"alt_rules",
"=",
"None",
")",
":",
"date_classes",
"=",
"_tag_most_likely",
"(",
"examples",
")",
"if",
"alt_rules",
":",
"date_classes",
"=",
"_apply_rewrites",
"(",
"date_classes",
",",
"alt_rules",
")",
"else",
":",
"date_classes",
"=",
"_apply_rewrites",
"(",
"date_classes",
",",
"RULES",
")",
"date_string",
"=",
"''",
"for",
"date_class",
"in",
"date_classes",
":",
"date_string",
"+=",
"date_class",
".",
"directive",
"return",
"date_string"
] | Returns a datetime.strptime-compliant format string for parsing the *most likely* date format
used in examples. examples is a list containing example date strings. | [
"Returns",
"a",
"datetime",
".",
"strptime",
"-",
"compliant",
"format",
"string",
"for",
"parsing",
"the",
"*",
"most",
"likely",
"*",
"date",
"format",
"used",
"in",
"examples",
".",
"examples",
"is",
"a",
"list",
"containing",
"example",
"date",
"strings",
"."
] | train | https://github.com/jeffreystarr/dateinfer/blob/5db408cf93fd91e09cba952874c9728b04ca518d/dateinfer/infer.py#L65-L81 |
jeffreystarr/dateinfer | dateinfer/infer.py | _apply_rewrites | def _apply_rewrites(date_classes, rules):
"""
Return a list of date elements by applying rewrites to the initial date element list
"""
for rule in rules:
date_classes = rule.execute(date_classes)
return date_classes | python | def _apply_rewrites(date_classes, rules):
"""
Return a list of date elements by applying rewrites to the initial date element list
"""
for rule in rules:
date_classes = rule.execute(date_classes)
return date_classes | [
"def",
"_apply_rewrites",
"(",
"date_classes",
",",
"rules",
")",
":",
"for",
"rule",
"in",
"rules",
":",
"date_classes",
"=",
"rule",
".",
"execute",
"(",
"date_classes",
")",
"return",
"date_classes"
] | Return a list of date elements by applying rewrites to the initial date element list | [
"Return",
"a",
"list",
"of",
"date",
"elements",
"by",
"applying",
"rewrites",
"to",
"the",
"initial",
"date",
"element",
"list"
] | train | https://github.com/jeffreystarr/dateinfer/blob/5db408cf93fd91e09cba952874c9728b04ca518d/dateinfer/infer.py#L84-L91 |
jeffreystarr/dateinfer | dateinfer/infer.py | _mode | def _mode(elems):
"""
Find the mode (most common element) in list elems. If there are ties, this function returns the least value.
If elems is an empty list, returns None.
"""
if len(elems) == 0:
return None
c = collections.Counter()
c.update(elems)
most_common = c.most_common(1)
most_common.sort()
return most_common[0][0] | python | def _mode(elems):
"""
Find the mode (most common element) in list elems. If there are ties, this function returns the least value.
If elems is an empty list, returns None.
"""
if len(elems) == 0:
return None
c = collections.Counter()
c.update(elems)
most_common = c.most_common(1)
most_common.sort()
return most_common[0][0] | [
"def",
"_mode",
"(",
"elems",
")",
":",
"if",
"len",
"(",
"elems",
")",
"==",
"0",
":",
"return",
"None",
"c",
"=",
"collections",
".",
"Counter",
"(",
")",
"c",
".",
"update",
"(",
"elems",
")",
"most_common",
"=",
"c",
".",
"most_common",
"(",
"1",
")",
"most_common",
".",
"sort",
"(",
")",
"return",
"most_common",
"[",
"0",
"]",
"[",
"0",
"]"
] | Find the mode (most common element) in list elems. If there are ties, this function returns the least value.
If elems is an empty list, returns None. | [
"Find",
"the",
"mode",
"(",
"most",
"common",
"element",
")",
"in",
"list",
"elems",
".",
"If",
"there",
"are",
"ties",
"this",
"function",
"returns",
"the",
"least",
"value",
"."
] | train | https://github.com/jeffreystarr/dateinfer/blob/5db408cf93fd91e09cba952874c9728b04ca518d/dateinfer/infer.py#L94-L108 |
jeffreystarr/dateinfer | dateinfer/infer.py | _most_restrictive | def _most_restrictive(date_elems):
"""
Return the date_elem that has the most restrictive range from date_elems
"""
most_index = len(DATE_ELEMENTS)
for date_elem in date_elems:
if date_elem in DATE_ELEMENTS and DATE_ELEMENTS.index(date_elem) < most_index:
most_index = DATE_ELEMENTS.index(date_elem)
if most_index < len(DATE_ELEMENTS):
return DATE_ELEMENTS[most_index]
else:
raise KeyError('No least restrictive date element found') | python | def _most_restrictive(date_elems):
"""
Return the date_elem that has the most restrictive range from date_elems
"""
most_index = len(DATE_ELEMENTS)
for date_elem in date_elems:
if date_elem in DATE_ELEMENTS and DATE_ELEMENTS.index(date_elem) < most_index:
most_index = DATE_ELEMENTS.index(date_elem)
if most_index < len(DATE_ELEMENTS):
return DATE_ELEMENTS[most_index]
else:
raise KeyError('No least restrictive date element found') | [
"def",
"_most_restrictive",
"(",
"date_elems",
")",
":",
"most_index",
"=",
"len",
"(",
"DATE_ELEMENTS",
")",
"for",
"date_elem",
"in",
"date_elems",
":",
"if",
"date_elem",
"in",
"DATE_ELEMENTS",
"and",
"DATE_ELEMENTS",
".",
"index",
"(",
"date_elem",
")",
"<",
"most_index",
":",
"most_index",
"=",
"DATE_ELEMENTS",
".",
"index",
"(",
"date_elem",
")",
"if",
"most_index",
"<",
"len",
"(",
"DATE_ELEMENTS",
")",
":",
"return",
"DATE_ELEMENTS",
"[",
"most_index",
"]",
"else",
":",
"raise",
"KeyError",
"(",
"'No least restrictive date element found'",
")"
] | Return the date_elem that has the most restrictive range from date_elems | [
"Return",
"the",
"date_elem",
"that",
"has",
"the",
"most",
"restrictive",
"range",
"from",
"date_elems"
] | train | https://github.com/jeffreystarr/dateinfer/blob/5db408cf93fd91e09cba952874c9728b04ca518d/dateinfer/infer.py#L111-L122 |
jeffreystarr/dateinfer | dateinfer/infer.py | _percent_match | def _percent_match(date_classes, tokens):
"""
For each date class, return the percentage of tokens that the class matched (floating point [0.0 - 1.0]). The
returned value is a tuple of length patterns. Tokens should be a list.
"""
match_count = [0] * len(date_classes)
for i, date_class in enumerate(date_classes):
for token in tokens:
if date_class.is_match(token):
match_count[i] += 1
percentages = tuple([float(m) / len(tokens) for m in match_count])
return percentages | python | def _percent_match(date_classes, tokens):
"""
For each date class, return the percentage of tokens that the class matched (floating point [0.0 - 1.0]). The
returned value is a tuple of length patterns. Tokens should be a list.
"""
match_count = [0] * len(date_classes)
for i, date_class in enumerate(date_classes):
for token in tokens:
if date_class.is_match(token):
match_count[i] += 1
percentages = tuple([float(m) / len(tokens) for m in match_count])
return percentages | [
"def",
"_percent_match",
"(",
"date_classes",
",",
"tokens",
")",
":",
"match_count",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"date_classes",
")",
"for",
"i",
",",
"date_class",
"in",
"enumerate",
"(",
"date_classes",
")",
":",
"for",
"token",
"in",
"tokens",
":",
"if",
"date_class",
".",
"is_match",
"(",
"token",
")",
":",
"match_count",
"[",
"i",
"]",
"+=",
"1",
"percentages",
"=",
"tuple",
"(",
"[",
"float",
"(",
"m",
")",
"/",
"len",
"(",
"tokens",
")",
"for",
"m",
"in",
"match_count",
"]",
")",
"return",
"percentages"
] | For each date class, return the percentage of tokens that the class matched (floating point [0.0 - 1.0]). The
returned value is a tuple of length patterns. Tokens should be a list. | [
"For",
"each",
"date",
"class",
"return",
"the",
"percentage",
"of",
"tokens",
"that",
"the",
"class",
"matched",
"(",
"floating",
"point",
"[",
"0",
".",
"0",
"-",
"1",
".",
"0",
"]",
")",
".",
"The",
"returned",
"value",
"is",
"a",
"tuple",
"of",
"length",
"patterns",
".",
"Tokens",
"should",
"be",
"a",
"list",
"."
] | train | https://github.com/jeffreystarr/dateinfer/blob/5db408cf93fd91e09cba952874c9728b04ca518d/dateinfer/infer.py#L125-L138 |
jeffreystarr/dateinfer | dateinfer/infer.py | _tag_most_likely | def _tag_most_likely(examples):
"""
Return a list of date elements by choosing the most likely element for a token within examples (context-free).
"""
tokenized_examples = [_tokenize_by_character_class(example) for example in examples]
# We currently need the tokenized_examples to all have the same length, so drop instances that have a length
# that does not equal the mode of lengths within tokenized_examples
token_lengths = [len(e) for e in tokenized_examples]
token_lengths_mode = _mode(token_lengths)
tokenized_examples = [example for example in tokenized_examples if len(example) == token_lengths_mode]
# Now, we iterate through the tokens, assigning date elements based on their likelihood. In cases where
# the assignments are unlikely for all date elements, assign filler.
most_likely = []
for token_index in range(0, token_lengths_mode):
tokens = [token[token_index] for token in tokenized_examples]
probabilities = _percent_match(DATE_ELEMENTS, tokens)
max_prob = max(probabilities)
if max_prob < 0.5:
most_likely.append(Filler(_mode(tokens)))
else:
if probabilities.count(max_prob) == 1:
most_likely.append(DATE_ELEMENTS[probabilities.index(max_prob)])
else:
choices = []
for index, prob in enumerate(probabilities):
if prob == max_prob:
choices.append(DATE_ELEMENTS[index])
most_likely.append(_most_restrictive(choices))
return most_likely | python | def _tag_most_likely(examples):
"""
Return a list of date elements by choosing the most likely element for a token within examples (context-free).
"""
tokenized_examples = [_tokenize_by_character_class(example) for example in examples]
# We currently need the tokenized_examples to all have the same length, so drop instances that have a length
# that does not equal the mode of lengths within tokenized_examples
token_lengths = [len(e) for e in tokenized_examples]
token_lengths_mode = _mode(token_lengths)
tokenized_examples = [example for example in tokenized_examples if len(example) == token_lengths_mode]
# Now, we iterate through the tokens, assigning date elements based on their likelihood. In cases where
# the assignments are unlikely for all date elements, assign filler.
most_likely = []
for token_index in range(0, token_lengths_mode):
tokens = [token[token_index] for token in tokenized_examples]
probabilities = _percent_match(DATE_ELEMENTS, tokens)
max_prob = max(probabilities)
if max_prob < 0.5:
most_likely.append(Filler(_mode(tokens)))
else:
if probabilities.count(max_prob) == 1:
most_likely.append(DATE_ELEMENTS[probabilities.index(max_prob)])
else:
choices = []
for index, prob in enumerate(probabilities):
if prob == max_prob:
choices.append(DATE_ELEMENTS[index])
most_likely.append(_most_restrictive(choices))
return most_likely | [
"def",
"_tag_most_likely",
"(",
"examples",
")",
":",
"tokenized_examples",
"=",
"[",
"_tokenize_by_character_class",
"(",
"example",
")",
"for",
"example",
"in",
"examples",
"]",
"# We currently need the tokenized_examples to all have the same length, so drop instances that have a length",
"# that does not equal the mode of lengths within tokenized_examples",
"token_lengths",
"=",
"[",
"len",
"(",
"e",
")",
"for",
"e",
"in",
"tokenized_examples",
"]",
"token_lengths_mode",
"=",
"_mode",
"(",
"token_lengths",
")",
"tokenized_examples",
"=",
"[",
"example",
"for",
"example",
"in",
"tokenized_examples",
"if",
"len",
"(",
"example",
")",
"==",
"token_lengths_mode",
"]",
"# Now, we iterate through the tokens, assigning date elements based on their likelihood. In cases where",
"# the assignments are unlikely for all date elements, assign filler.",
"most_likely",
"=",
"[",
"]",
"for",
"token_index",
"in",
"range",
"(",
"0",
",",
"token_lengths_mode",
")",
":",
"tokens",
"=",
"[",
"token",
"[",
"token_index",
"]",
"for",
"token",
"in",
"tokenized_examples",
"]",
"probabilities",
"=",
"_percent_match",
"(",
"DATE_ELEMENTS",
",",
"tokens",
")",
"max_prob",
"=",
"max",
"(",
"probabilities",
")",
"if",
"max_prob",
"<",
"0.5",
":",
"most_likely",
".",
"append",
"(",
"Filler",
"(",
"_mode",
"(",
"tokens",
")",
")",
")",
"else",
":",
"if",
"probabilities",
".",
"count",
"(",
"max_prob",
")",
"==",
"1",
":",
"most_likely",
".",
"append",
"(",
"DATE_ELEMENTS",
"[",
"probabilities",
".",
"index",
"(",
"max_prob",
")",
"]",
")",
"else",
":",
"choices",
"=",
"[",
"]",
"for",
"index",
",",
"prob",
"in",
"enumerate",
"(",
"probabilities",
")",
":",
"if",
"prob",
"==",
"max_prob",
":",
"choices",
".",
"append",
"(",
"DATE_ELEMENTS",
"[",
"index",
"]",
")",
"most_likely",
".",
"append",
"(",
"_most_restrictive",
"(",
"choices",
")",
")",
"return",
"most_likely"
] | Return a list of date elements by choosing the most likely element for a token within examples (context-free). | [
"Return",
"a",
"list",
"of",
"date",
"elements",
"by",
"choosing",
"the",
"most",
"likely",
"element",
"for",
"a",
"token",
"within",
"examples",
"(",
"context",
"-",
"free",
")",
"."
] | train | https://github.com/jeffreystarr/dateinfer/blob/5db408cf93fd91e09cba952874c9728b04ca518d/dateinfer/infer.py#L141-L172 |
jeffreystarr/dateinfer | dateinfer/infer.py | _tokenize_by_character_class | def _tokenize_by_character_class(s):
"""
Return a list of strings by splitting s (tokenizing) by character class.
For example:
_tokenize_by_character_class('Sat Jan 11 19:54:52 MST 2014') => ['Sat', ' ', 'Jan', ' ', '11', ' ', '19', ':',
'54', ':', '52', ' ', 'MST', ' ', '2014']
_tokenize_by_character_class('2013-08-14') => ['2013', '-', '08', '-', '14']
"""
character_classes = [string.digits, string.ascii_letters, string.punctuation, string.whitespace]
result = []
rest = list(s)
while rest:
progress = False
for character_class in character_classes:
if rest[0] in character_class:
progress = True
token = ''
for take_away in itertools.takewhile(lambda c: c in character_class, rest[:]):
token += take_away
rest.pop(0)
result.append(token)
break
if not progress: # none of the character classes matched; unprintable character?
result.append(rest[0])
rest = rest[1:]
return result | python | def _tokenize_by_character_class(s):
"""
Return a list of strings by splitting s (tokenizing) by character class.
For example:
_tokenize_by_character_class('Sat Jan 11 19:54:52 MST 2014') => ['Sat', ' ', 'Jan', ' ', '11', ' ', '19', ':',
'54', ':', '52', ' ', 'MST', ' ', '2014']
_tokenize_by_character_class('2013-08-14') => ['2013', '-', '08', '-', '14']
"""
character_classes = [string.digits, string.ascii_letters, string.punctuation, string.whitespace]
result = []
rest = list(s)
while rest:
progress = False
for character_class in character_classes:
if rest[0] in character_class:
progress = True
token = ''
for take_away in itertools.takewhile(lambda c: c in character_class, rest[:]):
token += take_away
rest.pop(0)
result.append(token)
break
if not progress: # none of the character classes matched; unprintable character?
result.append(rest[0])
rest = rest[1:]
return result | [
"def",
"_tokenize_by_character_class",
"(",
"s",
")",
":",
"character_classes",
"=",
"[",
"string",
".",
"digits",
",",
"string",
".",
"ascii_letters",
",",
"string",
".",
"punctuation",
",",
"string",
".",
"whitespace",
"]",
"result",
"=",
"[",
"]",
"rest",
"=",
"list",
"(",
"s",
")",
"while",
"rest",
":",
"progress",
"=",
"False",
"for",
"character_class",
"in",
"character_classes",
":",
"if",
"rest",
"[",
"0",
"]",
"in",
"character_class",
":",
"progress",
"=",
"True",
"token",
"=",
"''",
"for",
"take_away",
"in",
"itertools",
".",
"takewhile",
"(",
"lambda",
"c",
":",
"c",
"in",
"character_class",
",",
"rest",
"[",
":",
"]",
")",
":",
"token",
"+=",
"take_away",
"rest",
".",
"pop",
"(",
"0",
")",
"result",
".",
"append",
"(",
"token",
")",
"break",
"if",
"not",
"progress",
":",
"# none of the character classes matched; unprintable character?",
"result",
".",
"append",
"(",
"rest",
"[",
"0",
"]",
")",
"rest",
"=",
"rest",
"[",
"1",
":",
"]",
"return",
"result"
] | Return a list of strings by splitting s (tokenizing) by character class.
For example:
_tokenize_by_character_class('Sat Jan 11 19:54:52 MST 2014') => ['Sat', ' ', 'Jan', ' ', '11', ' ', '19', ':',
'54', ':', '52', ' ', 'MST', ' ', '2014']
_tokenize_by_character_class('2013-08-14') => ['2013', '-', '08', '-', '14'] | [
"Return",
"a",
"list",
"of",
"strings",
"by",
"splitting",
"s",
"(",
"tokenizing",
")",
"by",
"character",
"class",
"."
] | train | https://github.com/jeffreystarr/dateinfer/blob/5db408cf93fd91e09cba952874c9728b04ca518d/dateinfer/infer.py#L175-L203 |
jeffreystarr/dateinfer | dateinfer/ruleproc.py | If.execute | def execute(self, elem_list):
"""
If condition, return a new elem_list provided by executing action.
"""
if self.condition.is_true(elem_list):
return self.action.act(elem_list)
else:
return elem_list | python | def execute(self, elem_list):
"""
If condition, return a new elem_list provided by executing action.
"""
if self.condition.is_true(elem_list):
return self.action.act(elem_list)
else:
return elem_list | [
"def",
"execute",
"(",
"self",
",",
"elem_list",
")",
":",
"if",
"self",
".",
"condition",
".",
"is_true",
"(",
"elem_list",
")",
":",
"return",
"self",
".",
"action",
".",
"act",
"(",
"elem_list",
")",
"else",
":",
"return",
"elem_list"
] | If condition, return a new elem_list provided by executing action. | [
"If",
"condition",
"return",
"a",
"new",
"elem_list",
"provided",
"by",
"executing",
"action",
"."
] | train | https://github.com/jeffreystarr/dateinfer/blob/5db408cf93fd91e09cba952874c9728b04ca518d/dateinfer/ruleproc.py#L16-L23 |
jeffreystarr/dateinfer | dateinfer/ruleproc.py | Sequence.match | def match(elem, seq_expr):
"""
Return True if elem (an element of elem_list) matches seq_expr, an element in self.sequence
"""
if type(seq_expr) is str: # wild-card
if seq_expr == '.': # match any element
return True
elif seq_expr == '\d':
return elem.is_numerical()
elif seq_expr == '\D':
return not elem.is_numerical()
else: # invalid wild-card specified
raise LookupError('{0} is not a valid wild-card'.format(seq_expr))
else: # date element
return elem == seq_expr | python | def match(elem, seq_expr):
"""
Return True if elem (an element of elem_list) matches seq_expr, an element in self.sequence
"""
if type(seq_expr) is str: # wild-card
if seq_expr == '.': # match any element
return True
elif seq_expr == '\d':
return elem.is_numerical()
elif seq_expr == '\D':
return not elem.is_numerical()
else: # invalid wild-card specified
raise LookupError('{0} is not a valid wild-card'.format(seq_expr))
else: # date element
return elem == seq_expr | [
"def",
"match",
"(",
"elem",
",",
"seq_expr",
")",
":",
"if",
"type",
"(",
"seq_expr",
")",
"is",
"str",
":",
"# wild-card",
"if",
"seq_expr",
"==",
"'.'",
":",
"# match any element",
"return",
"True",
"elif",
"seq_expr",
"==",
"'\\d'",
":",
"return",
"elem",
".",
"is_numerical",
"(",
")",
"elif",
"seq_expr",
"==",
"'\\D'",
":",
"return",
"not",
"elem",
".",
"is_numerical",
"(",
")",
"else",
":",
"# invalid wild-card specified",
"raise",
"LookupError",
"(",
"'{0} is not a valid wild-card'",
".",
"format",
"(",
"seq_expr",
")",
")",
"else",
":",
"# date element",
"return",
"elem",
"==",
"seq_expr"
] | Return True if elem (an element of elem_list) matches seq_expr, an element in self.sequence | [
"Return",
"True",
"if",
"elem",
"(",
"an",
"element",
"of",
"elem_list",
")",
"matches",
"seq_expr",
"an",
"element",
"in",
"self",
".",
"sequence"
] | train | https://github.com/jeffreystarr/dateinfer/blob/5db408cf93fd91e09cba952874c9728b04ca518d/dateinfer/ruleproc.py#L150-L164 |
jeffreystarr/dateinfer | dateinfer/ruleproc.py | Sequence.find | def find(find_seq, elem_list):
"""
Return the first position in elem_list where find_seq starts
"""
seq_pos = 0
for index, elem in enumerate(elem_list):
if Sequence.match(elem, find_seq[seq_pos]):
seq_pos += 1
if seq_pos == len(find_seq): # found matching sequence
return index - seq_pos + 1
else: # exited sequence
seq_pos = 0
raise LookupError('Failed to find sequence in elem_list') | python | def find(find_seq, elem_list):
"""
Return the first position in elem_list where find_seq starts
"""
seq_pos = 0
for index, elem in enumerate(elem_list):
if Sequence.match(elem, find_seq[seq_pos]):
seq_pos += 1
if seq_pos == len(find_seq): # found matching sequence
return index - seq_pos + 1
else: # exited sequence
seq_pos = 0
raise LookupError('Failed to find sequence in elem_list') | [
"def",
"find",
"(",
"find_seq",
",",
"elem_list",
")",
":",
"seq_pos",
"=",
"0",
"for",
"index",
",",
"elem",
"in",
"enumerate",
"(",
"elem_list",
")",
":",
"if",
"Sequence",
".",
"match",
"(",
"elem",
",",
"find_seq",
"[",
"seq_pos",
"]",
")",
":",
"seq_pos",
"+=",
"1",
"if",
"seq_pos",
"==",
"len",
"(",
"find_seq",
")",
":",
"# found matching sequence",
"return",
"index",
"-",
"seq_pos",
"+",
"1",
"else",
":",
"# exited sequence",
"seq_pos",
"=",
"0",
"raise",
"LookupError",
"(",
"'Failed to find sequence in elem_list'",
")"
] | Return the first position in elem_list where find_seq starts | [
"Return",
"the",
"first",
"position",
"in",
"elem_list",
"where",
"find_seq",
"starts"
] | train | https://github.com/jeffreystarr/dateinfer/blob/5db408cf93fd91e09cba952874c9728b04ca518d/dateinfer/ruleproc.py#L167-L179 |
earlzo/hfut | hfut/util.py | get_point | def get_point(grade_str):
"""
根据成绩判断绩点
:param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩
:return: 成绩绩点
:rtype: float
"""
try:
grade = float(grade_str)
assert 0 <= grade <= 100
if 95 <= grade <= 100:
return 4.3
elif 90 <= grade < 95:
return 4.0
elif 85 <= grade < 90:
return 3.7
elif 82 <= grade < 85:
return 3.3
elif 78 <= grade < 82:
return 3.0
elif 75 <= grade < 78:
return 2.7
elif 72 <= grade < 75:
return 2.3
elif 68 <= grade < 72:
return 2.0
elif 66 <= grade < 68:
return 1.7
elif 64 <= grade < 66:
return 1.3
elif 60 <= grade < 64:
return 1.0
else:
return 0.0
except ValueError:
if grade_str == '优':
return 3.9
elif grade_str == '良':
return 3.0
elif grade_str == '中':
return 2.0
elif grade_str == '及格':
return 1.2
elif grade_str in ('不及格', '免修', '未考'):
return 0.0
else:
raise ValueError('{:s} 不是有效的成绩'.format(grade_str)) | python | def get_point(grade_str):
"""
根据成绩判断绩点
:param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩
:return: 成绩绩点
:rtype: float
"""
try:
grade = float(grade_str)
assert 0 <= grade <= 100
if 95 <= grade <= 100:
return 4.3
elif 90 <= grade < 95:
return 4.0
elif 85 <= grade < 90:
return 3.7
elif 82 <= grade < 85:
return 3.3
elif 78 <= grade < 82:
return 3.0
elif 75 <= grade < 78:
return 2.7
elif 72 <= grade < 75:
return 2.3
elif 68 <= grade < 72:
return 2.0
elif 66 <= grade < 68:
return 1.7
elif 64 <= grade < 66:
return 1.3
elif 60 <= grade < 64:
return 1.0
else:
return 0.0
except ValueError:
if grade_str == '优':
return 3.9
elif grade_str == '良':
return 3.0
elif grade_str == '中':
return 2.0
elif grade_str == '及格':
return 1.2
elif grade_str in ('不及格', '免修', '未考'):
return 0.0
else:
raise ValueError('{:s} 不是有效的成绩'.format(grade_str)) | [
"def",
"get_point",
"(",
"grade_str",
")",
":",
"try",
":",
"grade",
"=",
"float",
"(",
"grade_str",
")",
"assert",
"0",
"<=",
"grade",
"<=",
"100",
"if",
"95",
"<=",
"grade",
"<=",
"100",
":",
"return",
"4.3",
"elif",
"90",
"<=",
"grade",
"<",
"95",
":",
"return",
"4.0",
"elif",
"85",
"<=",
"grade",
"<",
"90",
":",
"return",
"3.7",
"elif",
"82",
"<=",
"grade",
"<",
"85",
":",
"return",
"3.3",
"elif",
"78",
"<=",
"grade",
"<",
"82",
":",
"return",
"3.0",
"elif",
"75",
"<=",
"grade",
"<",
"78",
":",
"return",
"2.7",
"elif",
"72",
"<=",
"grade",
"<",
"75",
":",
"return",
"2.3",
"elif",
"68",
"<=",
"grade",
"<",
"72",
":",
"return",
"2.0",
"elif",
"66",
"<=",
"grade",
"<",
"68",
":",
"return",
"1.7",
"elif",
"64",
"<=",
"grade",
"<",
"66",
":",
"return",
"1.3",
"elif",
"60",
"<=",
"grade",
"<",
"64",
":",
"return",
"1.0",
"else",
":",
"return",
"0.0",
"except",
"ValueError",
":",
"if",
"grade_str",
"==",
"'优':",
"",
"return",
"3.9",
"elif",
"grade_str",
"==",
"'良':",
"",
"return",
"3.0",
"elif",
"grade_str",
"==",
"'中':",
"",
"return",
"2.0",
"elif",
"grade_str",
"==",
"'及格':",
"",
"return",
"1.2",
"elif",
"grade_str",
"in",
"(",
"'不及格', '免修'",
",",
"'未考'):",
"",
"",
"",
"",
"return",
"0.0",
"else",
":",
"raise",
"ValueError",
"(",
"'{:s} 不是有效的成绩'.format(grade_",
"s",
"tr))",
"",
"",
"",
""
] | 根据成绩判断绩点
:param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩
:return: 成绩绩点
:rtype: float | [
"根据成绩判断绩点"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L21-L68 |
earlzo/hfut | hfut/util.py | cal_gpa | def cal_gpa(grades):
"""
根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考
:param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组
:return: 包含了课程平均绩点和 gpa 的元组
"""
# 课程总数
courses_sum = len(grades)
# 课程绩点和
points_sum = 0
# 学分和
credit_sum = 0
# 课程学分 x 课程绩点之和
gpa_points_sum = 0
for grade in grades:
point = get_point(grade.get('补考成绩') or grade['成绩'])
credit = float(grade['学分'])
points_sum += point
credit_sum += credit
gpa_points_sum += credit * point
ave_point = points_sum / courses_sum
gpa = gpa_points_sum / credit_sum
return round(ave_point, 5), round(gpa, 5) | python | def cal_gpa(grades):
"""
根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考
:param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组
:return: 包含了课程平均绩点和 gpa 的元组
"""
# 课程总数
courses_sum = len(grades)
# 课程绩点和
points_sum = 0
# 学分和
credit_sum = 0
# 课程学分 x 课程绩点之和
gpa_points_sum = 0
for grade in grades:
point = get_point(grade.get('补考成绩') or grade['成绩'])
credit = float(grade['学分'])
points_sum += point
credit_sum += credit
gpa_points_sum += credit * point
ave_point = points_sum / courses_sum
gpa = gpa_points_sum / credit_sum
return round(ave_point, 5), round(gpa, 5) | [
"def",
"cal_gpa",
"(",
"grades",
")",
":",
"# 课程总数",
"courses_sum",
"=",
"len",
"(",
"grades",
")",
"# 课程绩点和",
"points_sum",
"=",
"0",
"# 学分和",
"credit_sum",
"=",
"0",
"# 课程学分 x 课程绩点之和",
"gpa_points_sum",
"=",
"0",
"for",
"grade",
"in",
"grades",
":",
"point",
"=",
"get_point",
"(",
"grade",
".",
"get",
"(",
"'补考成绩') or gra",
"d",
"['",
"绩'])",
"",
"",
"",
"",
"credit",
"=",
"float",
"(",
"grade",
"[",
"'学分'])",
"",
"",
"points_sum",
"+=",
"point",
"credit_sum",
"+=",
"credit",
"gpa_points_sum",
"+=",
"credit",
"*",
"point",
"ave_point",
"=",
"points_sum",
"/",
"courses_sum",
"gpa",
"=",
"gpa_points_sum",
"/",
"credit_sum",
"return",
"round",
"(",
"ave_point",
",",
"5",
")",
",",
"round",
"(",
"gpa",
",",
"5",
")"
] | 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考
:param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组
:return: 包含了课程平均绩点和 gpa 的元组 | [
"根据成绩数组计算课程平均绩点和",
"gpa",
"算法不一定与学校一致",
"结果仅供参考"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L71-L95 |
earlzo/hfut | hfut/util.py | cal_term_code | def cal_term_code(year, is_first_term=True):
"""
计算对应的学期代码
:param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012
:param is_first_term: 是否为第一学期
:type is_first_term: bool
:return: 形如 "022" 的学期代码
"""
if year <= 2001:
msg = '出现了超出范围年份: {}'.format(year)
raise ValueError(msg)
term_code = (year - 2001) * 2
if is_first_term:
term_code -= 1
return '%03d' % term_code | python | def cal_term_code(year, is_first_term=True):
"""
计算对应的学期代码
:param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012
:param is_first_term: 是否为第一学期
:type is_first_term: bool
:return: 形如 "022" 的学期代码
"""
if year <= 2001:
msg = '出现了超出范围年份: {}'.format(year)
raise ValueError(msg)
term_code = (year - 2001) * 2
if is_first_term:
term_code -= 1
return '%03d' % term_code | [
"def",
"cal_term_code",
"(",
"year",
",",
"is_first_term",
"=",
"True",
")",
":",
"if",
"year",
"<=",
"2001",
":",
"msg",
"=",
"'出现了超出范围年份: {}'.format(year)",
"",
"",
"",
"",
"",
"raise",
"ValueError",
"(",
"msg",
")",
"term_code",
"=",
"(",
"year",
"-",
"2001",
")",
"*",
"2",
"if",
"is_first_term",
":",
"term_code",
"-=",
"1",
"return",
"'%03d'",
"%",
"term_code"
] | 计算对应的学期代码
:param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012
:param is_first_term: 是否为第一学期
:type is_first_term: bool
:return: 形如 "022" 的学期代码 | [
"计算对应的学期代码"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L98-L113 |
earlzo/hfut | hfut/util.py | term_str2code | def term_str2code(term_str):
"""
将学期字符串转换为对应的学期代码串
:param term_str: 形如 "2012-2013学年第二学期" 的学期字符串
:return: 形如 "022" 的学期代码
"""
result = ENV['TERM_PATTERN'].match(term_str).groups()
year = int(result[0])
return cal_term_code(year, result[1] == '一') | python | def term_str2code(term_str):
"""
将学期字符串转换为对应的学期代码串
:param term_str: 形如 "2012-2013学年第二学期" 的学期字符串
:return: 形如 "022" 的学期代码
"""
result = ENV['TERM_PATTERN'].match(term_str).groups()
year = int(result[0])
return cal_term_code(year, result[1] == '一') | [
"def",
"term_str2code",
"(",
"term_str",
")",
":",
"result",
"=",
"ENV",
"[",
"'TERM_PATTERN'",
"]",
".",
"match",
"(",
"term_str",
")",
".",
"groups",
"(",
")",
"year",
"=",
"int",
"(",
"result",
"[",
"0",
"]",
")",
"return",
"cal_term_code",
"(",
"year",
",",
"result",
"[",
"1",
"]",
"==",
"'一')",
""
] | 将学期字符串转换为对应的学期代码串
:param term_str: 形如 "2012-2013学年第二学期" 的学期字符串
:return: 形如 "022" 的学期代码 | [
"将学期字符串转换为对应的学期代码串"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L116-L125 |
earlzo/hfut | hfut/util.py | sort_hosts | def sort_hosts(hosts, method='GET', path='/', timeout=(5, 10), **kwargs):
"""
测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000
:param method: 请求方法
:param path: 默认的访问路径
:param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']`
:param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖
:param kwargs: 其他传递到 ``requests.request`` 的参数
:return: 形如 ``[(访问耗时, 地址)]`` 的排名数据
"""
ranks = []
class HostCheckerThread(Thread):
def __init__(self, host):
super(HostCheckerThread, self).__init__()
self.host = host
def run(self):
INFINITY = 10000000
try:
url = urllib.parse.urljoin(self.host, path)
res = requests.request(method, url, timeout=timeout, **kwargs)
res.raise_for_status()
cost = res.elapsed.total_seconds() * 1000
except Exception as e:
logger.warning('访问出错: %s', e)
cost = INFINITY
# http://stackoverflow.com/questions/6319207/are-lists-thread-safe
ranks.append((cost, self.host))
threads = [HostCheckerThread(u) for u in hosts]
for t in threads:
t.start()
for t in threads:
t.join()
ranks.sort()
return ranks | python | def sort_hosts(hosts, method='GET', path='/', timeout=(5, 10), **kwargs):
"""
测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000
:param method: 请求方法
:param path: 默认的访问路径
:param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']`
:param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖
:param kwargs: 其他传递到 ``requests.request`` 的参数
:return: 形如 ``[(访问耗时, 地址)]`` 的排名数据
"""
ranks = []
class HostCheckerThread(Thread):
def __init__(self, host):
super(HostCheckerThread, self).__init__()
self.host = host
def run(self):
INFINITY = 10000000
try:
url = urllib.parse.urljoin(self.host, path)
res = requests.request(method, url, timeout=timeout, **kwargs)
res.raise_for_status()
cost = res.elapsed.total_seconds() * 1000
except Exception as e:
logger.warning('访问出错: %s', e)
cost = INFINITY
# http://stackoverflow.com/questions/6319207/are-lists-thread-safe
ranks.append((cost, self.host))
threads = [HostCheckerThread(u) for u in hosts]
for t in threads:
t.start()
for t in threads:
t.join()
ranks.sort()
return ranks | [
"def",
"sort_hosts",
"(",
"hosts",
",",
"method",
"=",
"'GET'",
",",
"path",
"=",
"'/'",
",",
"timeout",
"=",
"(",
"5",
",",
"10",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"ranks",
"=",
"[",
"]",
"class",
"HostCheckerThread",
"(",
"Thread",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"host",
")",
":",
"super",
"(",
"HostCheckerThread",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"host",
"=",
"host",
"def",
"run",
"(",
"self",
")",
":",
"INFINITY",
"=",
"10000000",
"try",
":",
"url",
"=",
"urllib",
".",
"parse",
".",
"urljoin",
"(",
"self",
".",
"host",
",",
"path",
")",
"res",
"=",
"requests",
".",
"request",
"(",
"method",
",",
"url",
",",
"timeout",
"=",
"timeout",
",",
"*",
"*",
"kwargs",
")",
"res",
".",
"raise_for_status",
"(",
")",
"cost",
"=",
"res",
".",
"elapsed",
".",
"total_seconds",
"(",
")",
"*",
"1000",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"warning",
"(",
"'访问出错: %s', e)",
"",
"",
"",
"cost",
"=",
"INFINITY",
"# http://stackoverflow.com/questions/6319207/are-lists-thread-safe",
"ranks",
".",
"append",
"(",
"(",
"cost",
",",
"self",
".",
"host",
")",
")",
"threads",
"=",
"[",
"HostCheckerThread",
"(",
"u",
")",
"for",
"u",
"in",
"hosts",
"]",
"for",
"t",
"in",
"threads",
":",
"t",
".",
"start",
"(",
")",
"for",
"t",
"in",
"threads",
":",
"t",
".",
"join",
"(",
")",
"ranks",
".",
"sort",
"(",
")",
"return",
"ranks"
] | 测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000
:param method: 请求方法
:param path: 默认的访问路径
:param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']`
:param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖
:param kwargs: 其他传递到 ``requests.request`` 的参数
:return: 形如 ``[(访问耗时, 地址)]`` 的排名数据 | [
"测试各个地址的速度并返回排名",
"当出现错误时消耗时间为",
"INFINITY",
"=",
"10000000"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L128-L168 |
earlzo/hfut | hfut/util.py | filter_curriculum | def filter_curriculum(curriculum, week, weekday=None):
"""
筛选出指定星期[和指定星期几]的课程
:param curriculum: 课程表数据
:param week: 需要筛选的周数, 是一个代表周数的正整数
:param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日
:return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程
"""
if weekday:
c = [deepcopy(curriculum[weekday - 1])]
else:
c = deepcopy(curriculum)
for d in c:
l = len(d)
for t_idx in range(l):
t = d[t_idx]
if t is None:
continue
# 一般同一时间课程不会重复,重复时给出警告
t = list(filter(lambda k: week in k['上课周数'], t)) or None
if t is not None and len(t) > 1:
logger.warning('第 %d 周周 %d 第 %d 节课有冲突: %s', week, weekday or c.index(d) + 1, t_idx + 1, t)
d[t_idx] = t
return c[0] if weekday else c | python | def filter_curriculum(curriculum, week, weekday=None):
"""
筛选出指定星期[和指定星期几]的课程
:param curriculum: 课程表数据
:param week: 需要筛选的周数, 是一个代表周数的正整数
:param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日
:return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程
"""
if weekday:
c = [deepcopy(curriculum[weekday - 1])]
else:
c = deepcopy(curriculum)
for d in c:
l = len(d)
for t_idx in range(l):
t = d[t_idx]
if t is None:
continue
# 一般同一时间课程不会重复,重复时给出警告
t = list(filter(lambda k: week in k['上课周数'], t)) or None
if t is not None and len(t) > 1:
logger.warning('第 %d 周周 %d 第 %d 节课有冲突: %s', week, weekday or c.index(d) + 1, t_idx + 1, t)
d[t_idx] = t
return c[0] if weekday else c | [
"def",
"filter_curriculum",
"(",
"curriculum",
",",
"week",
",",
"weekday",
"=",
"None",
")",
":",
"if",
"weekday",
":",
"c",
"=",
"[",
"deepcopy",
"(",
"curriculum",
"[",
"weekday",
"-",
"1",
"]",
")",
"]",
"else",
":",
"c",
"=",
"deepcopy",
"(",
"curriculum",
")",
"for",
"d",
"in",
"c",
":",
"l",
"=",
"len",
"(",
"d",
")",
"for",
"t_idx",
"in",
"range",
"(",
"l",
")",
":",
"t",
"=",
"d",
"[",
"t_idx",
"]",
"if",
"t",
"is",
"None",
":",
"continue",
"# 一般同一时间课程不会重复,重复时给出警告",
"t",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"k",
":",
"week",
"in",
"k",
"[",
"'上课周数'], t)) o",
"r",
" ",
"o",
"n",
"e",
"",
"",
"if",
"t",
"is",
"not",
"None",
"and",
"len",
"(",
"t",
")",
">",
"1",
":",
"logger",
".",
"warning",
"(",
"'第 %d 周周 %d 第 %d 节课有冲突: %s', week, weekday or",
" ",
".ind",
"e",
"(d) + 1",
" t",
"i",
"d",
"x + 1",
",",
" ",
"t",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"d",
"[",
"t_idx",
"]",
"=",
"t",
"return",
"c",
"[",
"0",
"]",
"if",
"weekday",
"else",
"c"
] | 筛选出指定星期[和指定星期几]的课程
:param curriculum: 课程表数据
:param week: 需要筛选的周数, 是一个代表周数的正整数
:param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日
:return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程 | [
"筛选出指定星期",
"[",
"和指定星期几",
"]",
"的课程"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L171-L195 |
earlzo/hfut | hfut/util.py | curriculum2schedule | def curriculum2schedule(curriculum, first_day, compress=False, time_table=None):
"""
将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表
:param curriculum: 课表
:param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29)
:param compress: 压缩连续的课时为一个
:param time_table: 每天上课的时间表, 形如 ``((start timedelta, end timedelta), ...)`` 的 11 × 2 的矩阵
:return: [(datetime.datetime, str) ...]
"""
schedule = []
time_table = time_table or (
(timedelta(hours=8), timedelta(hours=8, minutes=50)),
(timedelta(hours=9), timedelta(hours=9, minutes=50)),
(timedelta(hours=10, minutes=10), timedelta(hours=11)),
(timedelta(hours=11, minutes=10), timedelta(hours=12)),
(timedelta(hours=14), timedelta(hours=14, minutes=50)),
(timedelta(hours=15), timedelta(hours=15, minutes=50)),
(timedelta(hours=16), timedelta(hours=16, minutes=50)),
(timedelta(hours=17), timedelta(hours=17, minutes=50)),
(timedelta(hours=19), timedelta(hours=19, minutes=50)),
(timedelta(hours=19, minutes=50), timedelta(hours=20, minutes=40)),
(timedelta(hours=20, minutes=40), timedelta(hours=21, minutes=30))
)
for i, d in enumerate(curriculum):
for j, cs in enumerate(d):
for c in cs or []:
course = '{name}[{place}]'.format(name=c['课程名称'], place=c['课程地点'])
for week in c['上课周数']:
day = first_day + timedelta(weeks=week - 1, days=i)
start, end = time_table[j]
item = (week, day + start, day + end, course)
schedule.append(item)
schedule.sort()
if compress:
new_schedule = [schedule[0]]
for i in range(1, len(schedule)):
sch = schedule[i]
# 同一天的连续课程
if new_schedule[-1][1].date() == sch[1].date() and new_schedule[-1][3] == sch[3]:
# 更新结束时间
old_item = new_schedule.pop()
# week, start, end, course
new_item = (old_item[0], old_item[1], sch[2], old_item[3])
else:
new_item = sch
new_schedule.append(new_item)
return new_schedule
return schedule | python | def curriculum2schedule(curriculum, first_day, compress=False, time_table=None):
"""
将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表
:param curriculum: 课表
:param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29)
:param compress: 压缩连续的课时为一个
:param time_table: 每天上课的时间表, 形如 ``((start timedelta, end timedelta), ...)`` 的 11 × 2 的矩阵
:return: [(datetime.datetime, str) ...]
"""
schedule = []
time_table = time_table or (
(timedelta(hours=8), timedelta(hours=8, minutes=50)),
(timedelta(hours=9), timedelta(hours=9, minutes=50)),
(timedelta(hours=10, minutes=10), timedelta(hours=11)),
(timedelta(hours=11, minutes=10), timedelta(hours=12)),
(timedelta(hours=14), timedelta(hours=14, minutes=50)),
(timedelta(hours=15), timedelta(hours=15, minutes=50)),
(timedelta(hours=16), timedelta(hours=16, minutes=50)),
(timedelta(hours=17), timedelta(hours=17, minutes=50)),
(timedelta(hours=19), timedelta(hours=19, minutes=50)),
(timedelta(hours=19, minutes=50), timedelta(hours=20, minutes=40)),
(timedelta(hours=20, minutes=40), timedelta(hours=21, minutes=30))
)
for i, d in enumerate(curriculum):
for j, cs in enumerate(d):
for c in cs or []:
course = '{name}[{place}]'.format(name=c['课程名称'], place=c['课程地点'])
for week in c['上课周数']:
day = first_day + timedelta(weeks=week - 1, days=i)
start, end = time_table[j]
item = (week, day + start, day + end, course)
schedule.append(item)
schedule.sort()
if compress:
new_schedule = [schedule[0]]
for i in range(1, len(schedule)):
sch = schedule[i]
# 同一天的连续课程
if new_schedule[-1][1].date() == sch[1].date() and new_schedule[-1][3] == sch[3]:
# 更新结束时间
old_item = new_schedule.pop()
# week, start, end, course
new_item = (old_item[0], old_item[1], sch[2], old_item[3])
else:
new_item = sch
new_schedule.append(new_item)
return new_schedule
return schedule | [
"def",
"curriculum2schedule",
"(",
"curriculum",
",",
"first_day",
",",
"compress",
"=",
"False",
",",
"time_table",
"=",
"None",
")",
":",
"schedule",
"=",
"[",
"]",
"time_table",
"=",
"time_table",
"or",
"(",
"(",
"timedelta",
"(",
"hours",
"=",
"8",
")",
",",
"timedelta",
"(",
"hours",
"=",
"8",
",",
"minutes",
"=",
"50",
")",
")",
",",
"(",
"timedelta",
"(",
"hours",
"=",
"9",
")",
",",
"timedelta",
"(",
"hours",
"=",
"9",
",",
"minutes",
"=",
"50",
")",
")",
",",
"(",
"timedelta",
"(",
"hours",
"=",
"10",
",",
"minutes",
"=",
"10",
")",
",",
"timedelta",
"(",
"hours",
"=",
"11",
")",
")",
",",
"(",
"timedelta",
"(",
"hours",
"=",
"11",
",",
"minutes",
"=",
"10",
")",
",",
"timedelta",
"(",
"hours",
"=",
"12",
")",
")",
",",
"(",
"timedelta",
"(",
"hours",
"=",
"14",
")",
",",
"timedelta",
"(",
"hours",
"=",
"14",
",",
"minutes",
"=",
"50",
")",
")",
",",
"(",
"timedelta",
"(",
"hours",
"=",
"15",
")",
",",
"timedelta",
"(",
"hours",
"=",
"15",
",",
"minutes",
"=",
"50",
")",
")",
",",
"(",
"timedelta",
"(",
"hours",
"=",
"16",
")",
",",
"timedelta",
"(",
"hours",
"=",
"16",
",",
"minutes",
"=",
"50",
")",
")",
",",
"(",
"timedelta",
"(",
"hours",
"=",
"17",
")",
",",
"timedelta",
"(",
"hours",
"=",
"17",
",",
"minutes",
"=",
"50",
")",
")",
",",
"(",
"timedelta",
"(",
"hours",
"=",
"19",
")",
",",
"timedelta",
"(",
"hours",
"=",
"19",
",",
"minutes",
"=",
"50",
")",
")",
",",
"(",
"timedelta",
"(",
"hours",
"=",
"19",
",",
"minutes",
"=",
"50",
")",
",",
"timedelta",
"(",
"hours",
"=",
"20",
",",
"minutes",
"=",
"40",
")",
")",
",",
"(",
"timedelta",
"(",
"hours",
"=",
"20",
",",
"minutes",
"=",
"40",
")",
",",
"timedelta",
"(",
"hours",
"=",
"21",
",",
"minutes",
"=",
"30",
")",
")",
")",
"for",
"i",
",",
"d",
"in",
"enumerate",
"(",
"curriculum",
")",
":",
"for",
"j",
",",
"cs",
"in",
"enumerate",
"(",
"d",
")",
":",
"for",
"c",
"in",
"cs",
"or",
"[",
"]",
":",
"course",
"=",
"'{name}[{place}]'",
".",
"format",
"(",
"name",
"=",
"c",
"[",
"'课程名称'], place",
"=",
"c",
"'课程地点",
"'",
"]",
")",
"",
"",
"",
"for",
"week",
"in",
"c",
"[",
"'上课周数']:",
"",
"",
"day",
"=",
"first_day",
"+",
"timedelta",
"(",
"weeks",
"=",
"week",
"-",
"1",
",",
"days",
"=",
"i",
")",
"start",
",",
"end",
"=",
"time_table",
"[",
"j",
"]",
"item",
"=",
"(",
"week",
",",
"day",
"+",
"start",
",",
"day",
"+",
"end",
",",
"course",
")",
"schedule",
".",
"append",
"(",
"item",
")",
"schedule",
".",
"sort",
"(",
")",
"if",
"compress",
":",
"new_schedule",
"=",
"[",
"schedule",
"[",
"0",
"]",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"schedule",
")",
")",
":",
"sch",
"=",
"schedule",
"[",
"i",
"]",
"# 同一天的连续课程",
"if",
"new_schedule",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
".",
"date",
"(",
")",
"==",
"sch",
"[",
"1",
"]",
".",
"date",
"(",
")",
"and",
"new_schedule",
"[",
"-",
"1",
"]",
"[",
"3",
"]",
"==",
"sch",
"[",
"3",
"]",
":",
"# 更新结束时间",
"old_item",
"=",
"new_schedule",
".",
"pop",
"(",
")",
"# week, start, end, course",
"new_item",
"=",
"(",
"old_item",
"[",
"0",
"]",
",",
"old_item",
"[",
"1",
"]",
",",
"sch",
"[",
"2",
"]",
",",
"old_item",
"[",
"3",
"]",
")",
"else",
":",
"new_item",
"=",
"sch",
"new_schedule",
".",
"append",
"(",
"new_item",
")",
"return",
"new_schedule",
"return",
"schedule"
] | 将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表
:param curriculum: 课表
:param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29)
:param compress: 压缩连续的课时为一个
:param time_table: 每天上课的时间表, 形如 ``((start timedelta, end timedelta), ...)`` 的 11 × 2 的矩阵
:return: [(datetime.datetime, str) ...] | [
"将课程表转换为上课时间表",
"如果",
"compress",
"=",
"False",
"结果是未排序的",
"否则为压缩并排序后的上课时间表"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L198-L248 |
duguyue100/minesweeper | scripts/ms-gui.py | ms_game_main | def ms_game_main(board_width, board_height, num_mines, port, ip_add):
"""Main function for Mine Sweeper Game.
Parameters
----------
board_width : int
the width of the board (> 0)
board_height : int
the height of the board (> 0)
num_mines : int
the number of mines, cannot be larger than
(board_width x board_height)
port : int
UDP port number, default is 5678
ip_add : string
the ip address for receiving the command,
default is localhost.
"""
ms_game = MSGame(board_width, board_height, num_mines,
port=port, ip_add=ip_add)
ms_app = QApplication([])
ms_window = QWidget()
ms_window.setAutoFillBackground(True)
ms_window.setWindowTitle("Mine Sweeper")
ms_layout = QGridLayout()
ms_window.setLayout(ms_layout)
fun_wg = gui.ControlWidget()
grid_wg = gui.GameWidget(ms_game, fun_wg)
remote_thread = gui.RemoteControlThread()
def update_grid_remote(move_msg):
"""Update grid from remote control."""
if grid_wg.ms_game.game_status == 2:
grid_wg.ms_game.play_move_msg(str(move_msg))
grid_wg.update_grid()
remote_thread.transfer.connect(update_grid_remote)
def reset_button_state():
"""Reset button state."""
grid_wg.reset_game()
fun_wg.reset_button.clicked.connect(reset_button_state)
ms_layout.addWidget(fun_wg, 0, 0)
ms_layout.addWidget(grid_wg, 1, 0)
remote_thread.control_start(grid_wg.ms_game)
ms_window.show()
ms_app.exec_() | python | def ms_game_main(board_width, board_height, num_mines, port, ip_add):
"""Main function for Mine Sweeper Game.
Parameters
----------
board_width : int
the width of the board (> 0)
board_height : int
the height of the board (> 0)
num_mines : int
the number of mines, cannot be larger than
(board_width x board_height)
port : int
UDP port number, default is 5678
ip_add : string
the ip address for receiving the command,
default is localhost.
"""
ms_game = MSGame(board_width, board_height, num_mines,
port=port, ip_add=ip_add)
ms_app = QApplication([])
ms_window = QWidget()
ms_window.setAutoFillBackground(True)
ms_window.setWindowTitle("Mine Sweeper")
ms_layout = QGridLayout()
ms_window.setLayout(ms_layout)
fun_wg = gui.ControlWidget()
grid_wg = gui.GameWidget(ms_game, fun_wg)
remote_thread = gui.RemoteControlThread()
def update_grid_remote(move_msg):
"""Update grid from remote control."""
if grid_wg.ms_game.game_status == 2:
grid_wg.ms_game.play_move_msg(str(move_msg))
grid_wg.update_grid()
remote_thread.transfer.connect(update_grid_remote)
def reset_button_state():
"""Reset button state."""
grid_wg.reset_game()
fun_wg.reset_button.clicked.connect(reset_button_state)
ms_layout.addWidget(fun_wg, 0, 0)
ms_layout.addWidget(grid_wg, 1, 0)
remote_thread.control_start(grid_wg.ms_game)
ms_window.show()
ms_app.exec_() | [
"def",
"ms_game_main",
"(",
"board_width",
",",
"board_height",
",",
"num_mines",
",",
"port",
",",
"ip_add",
")",
":",
"ms_game",
"=",
"MSGame",
"(",
"board_width",
",",
"board_height",
",",
"num_mines",
",",
"port",
"=",
"port",
",",
"ip_add",
"=",
"ip_add",
")",
"ms_app",
"=",
"QApplication",
"(",
"[",
"]",
")",
"ms_window",
"=",
"QWidget",
"(",
")",
"ms_window",
".",
"setAutoFillBackground",
"(",
"True",
")",
"ms_window",
".",
"setWindowTitle",
"(",
"\"Mine Sweeper\"",
")",
"ms_layout",
"=",
"QGridLayout",
"(",
")",
"ms_window",
".",
"setLayout",
"(",
"ms_layout",
")",
"fun_wg",
"=",
"gui",
".",
"ControlWidget",
"(",
")",
"grid_wg",
"=",
"gui",
".",
"GameWidget",
"(",
"ms_game",
",",
"fun_wg",
")",
"remote_thread",
"=",
"gui",
".",
"RemoteControlThread",
"(",
")",
"def",
"update_grid_remote",
"(",
"move_msg",
")",
":",
"\"\"\"Update grid from remote control.\"\"\"",
"if",
"grid_wg",
".",
"ms_game",
".",
"game_status",
"==",
"2",
":",
"grid_wg",
".",
"ms_game",
".",
"play_move_msg",
"(",
"str",
"(",
"move_msg",
")",
")",
"grid_wg",
".",
"update_grid",
"(",
")",
"remote_thread",
".",
"transfer",
".",
"connect",
"(",
"update_grid_remote",
")",
"def",
"reset_button_state",
"(",
")",
":",
"\"\"\"Reset button state.\"\"\"",
"grid_wg",
".",
"reset_game",
"(",
")",
"fun_wg",
".",
"reset_button",
".",
"clicked",
".",
"connect",
"(",
"reset_button_state",
")",
"ms_layout",
".",
"addWidget",
"(",
"fun_wg",
",",
"0",
",",
"0",
")",
"ms_layout",
".",
"addWidget",
"(",
"grid_wg",
",",
"1",
",",
"0",
")",
"remote_thread",
".",
"control_start",
"(",
"grid_wg",
".",
"ms_game",
")",
"ms_window",
".",
"show",
"(",
")",
"ms_app",
".",
"exec_",
"(",
")"
] | Main function for Mine Sweeper Game.
Parameters
----------
board_width : int
the width of the board (> 0)
board_height : int
the height of the board (> 0)
num_mines : int
the number of mines, cannot be larger than
(board_width x board_height)
port : int
UDP port number, default is 5678
ip_add : string
the ip address for receiving the command,
default is localhost. | [
"Main",
"function",
"for",
"Mine",
"Sweeper",
"Game",
"."
] | train | https://github.com/duguyue100/minesweeper/blob/38b1910f4c34d0275ac10a300285aba6f1d91d61/scripts/ms-gui.py#L21-L74 |
earlzo/hfut | examples/curriculum_calendar.py | schedule2calendar | def schedule2calendar(schedule, name='课表', using_todo=True):
"""
将上课时间表转换为 icalendar
:param schedule: 上课时间表
:param name: 日历名称
:param using_todo: 使用 ``icalendar.Todo`` 而不是 ``icalendar.Event`` 作为活动类
:return: icalendar.Calendar()
"""
# https://zh.wikipedia.org/wiki/ICalendar
# http://icalendar.readthedocs.io/en/latest
# https://tools.ietf.org/html/rfc5545
cal = icalendar.Calendar()
cal.add('X-WR-TIMEZONE', 'Asia/Shanghai')
cal.add('X-WR-CALNAME', name)
cls = icalendar.Todo if using_todo else icalendar.Event
for week, start, end, data in schedule:
# "事件"组件更具通用性, Google 日历不支持"待办"组件
item = cls(
SUMMARY='第{:02d}周-{}'.format(week, data),
DTSTART=icalendar.vDatetime(start),
DTEND=icalendar.vDatetime(end),
DESCRIPTION='起始于 {}, 结束于 {}'.format(start.strftime('%H:%M'), end.strftime('%H:%M'))
)
now = datetime.now()
# 这个状态"事件"组件是没有的, 对于待办列表类应用有作用
# https://tools.ietf.org/html/rfc5545#section-3.2.12
if using_todo:
if start < now < end:
item.add('STATUS', 'IN-PROCESS')
elif now > end:
item.add('STATUS', 'COMPLETED')
cal.add_component(item)
return cal | python | def schedule2calendar(schedule, name='课表', using_todo=True):
"""
将上课时间表转换为 icalendar
:param schedule: 上课时间表
:param name: 日历名称
:param using_todo: 使用 ``icalendar.Todo`` 而不是 ``icalendar.Event`` 作为活动类
:return: icalendar.Calendar()
"""
# https://zh.wikipedia.org/wiki/ICalendar
# http://icalendar.readthedocs.io/en/latest
# https://tools.ietf.org/html/rfc5545
cal = icalendar.Calendar()
cal.add('X-WR-TIMEZONE', 'Asia/Shanghai')
cal.add('X-WR-CALNAME', name)
cls = icalendar.Todo if using_todo else icalendar.Event
for week, start, end, data in schedule:
# "事件"组件更具通用性, Google 日历不支持"待办"组件
item = cls(
SUMMARY='第{:02d}周-{}'.format(week, data),
DTSTART=icalendar.vDatetime(start),
DTEND=icalendar.vDatetime(end),
DESCRIPTION='起始于 {}, 结束于 {}'.format(start.strftime('%H:%M'), end.strftime('%H:%M'))
)
now = datetime.now()
# 这个状态"事件"组件是没有的, 对于待办列表类应用有作用
# https://tools.ietf.org/html/rfc5545#section-3.2.12
if using_todo:
if start < now < end:
item.add('STATUS', 'IN-PROCESS')
elif now > end:
item.add('STATUS', 'COMPLETED')
cal.add_component(item)
return cal | [
"def",
"schedule2calendar",
"(",
"schedule",
",",
"name",
"=",
"'课表', us",
"i",
"g_todo=Tru",
"e",
"):",
"",
"",
"# https://zh.wikipedia.org/wiki/ICalendar",
"# http://icalendar.readthedocs.io/en/latest",
"# https://tools.ietf.org/html/rfc5545",
"cal",
"=",
"icalendar",
".",
"Calendar",
"(",
")",
"cal",
".",
"add",
"(",
"'X-WR-TIMEZONE'",
",",
"'Asia/Shanghai'",
")",
"cal",
".",
"add",
"(",
"'X-WR-CALNAME'",
",",
"name",
")",
"cls",
"=",
"icalendar",
".",
"Todo",
"if",
"using_todo",
"else",
"icalendar",
".",
"Event",
"for",
"week",
",",
"start",
",",
"end",
",",
"data",
"in",
"schedule",
":",
"# \"事件\"组件更具通用性, Google 日历不支持\"待办\"组件",
"item",
"=",
"cls",
"(",
"SUMMARY",
"=",
"'第{:02d}周-{}'.for",
"m",
"at(wee",
"k",
", da",
"t",
"),",
"",
"",
"DTSTART",
"=",
"icalendar",
".",
"vDatetime",
"(",
"start",
")",
",",
"DTEND",
"=",
"icalendar",
".",
"vDatetime",
"(",
"end",
")",
",",
"DESCRIPTION",
"=",
"'起始于 {}, 结束于 {}'.format(star",
"t",
".strft",
"i",
"me('%",
"H",
":%M'), e",
"n",
"d.strft",
"i",
"m",
"('%",
"H",
":%M'))",
"",
"",
"",
"",
")",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"# 这个状态\"事件\"组件是没有的, 对于待办列表类应用有作用",
"# https://tools.ietf.org/html/rfc5545#section-3.2.12",
"if",
"using_todo",
":",
"if",
"start",
"<",
"now",
"<",
"end",
":",
"item",
".",
"add",
"(",
"'STATUS'",
",",
"'IN-PROCESS'",
")",
"elif",
"now",
">",
"end",
":",
"item",
".",
"add",
"(",
"'STATUS'",
",",
"'COMPLETED'",
")",
"cal",
".",
"add_component",
"(",
"item",
")",
"return",
"cal"
] | 将上课时间表转换为 icalendar
:param schedule: 上课时间表
:param name: 日历名称
:param using_todo: 使用 ``icalendar.Todo`` 而不是 ``icalendar.Event`` 作为活动类
:return: icalendar.Calendar() | [
"将上课时间表转换为",
"icalendar"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/examples/curriculum_calendar.py#L14-L47 |
duguyue100/minesweeper | minesweeper/msgame.py | MSGame.init_new_game | def init_new_game(self, with_tcp=True):
"""Init a new game.
Parameters
----------
board : MSBoard
define a new board.
game_status : int
define the game status:
0: lose, 1: win, 2: playing
moves : int
how many moves carried out.
"""
self.board = self.create_board(self.board_width, self.board_height,
self.num_mines)
self.game_status = 2
self.num_moves = 0
self.move_history = []
if with_tcp is True:
# init TCP communication.
self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.tcp_socket.bind((self.TCP_IP, self.TCP_PORT))
self.tcp_socket.listen(1) | python | def init_new_game(self, with_tcp=True):
"""Init a new game.
Parameters
----------
board : MSBoard
define a new board.
game_status : int
define the game status:
0: lose, 1: win, 2: playing
moves : int
how many moves carried out.
"""
self.board = self.create_board(self.board_width, self.board_height,
self.num_mines)
self.game_status = 2
self.num_moves = 0
self.move_history = []
if with_tcp is True:
# init TCP communication.
self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.tcp_socket.bind((self.TCP_IP, self.TCP_PORT))
self.tcp_socket.listen(1) | [
"def",
"init_new_game",
"(",
"self",
",",
"with_tcp",
"=",
"True",
")",
":",
"self",
".",
"board",
"=",
"self",
".",
"create_board",
"(",
"self",
".",
"board_width",
",",
"self",
".",
"board_height",
",",
"self",
".",
"num_mines",
")",
"self",
".",
"game_status",
"=",
"2",
"self",
".",
"num_moves",
"=",
"0",
"self",
".",
"move_history",
"=",
"[",
"]",
"if",
"with_tcp",
"is",
"True",
":",
"# init TCP communication.",
"self",
".",
"tcp_socket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"self",
".",
"tcp_socket",
".",
"bind",
"(",
"(",
"self",
".",
"TCP_IP",
",",
"self",
".",
"TCP_PORT",
")",
")",
"self",
".",
"tcp_socket",
".",
"listen",
"(",
"1",
")"
] | Init a new game.
Parameters
----------
board : MSBoard
define a new board.
game_status : int
define the game status:
0: lose, 1: win, 2: playing
moves : int
how many moves carried out. | [
"Init",
"a",
"new",
"game",
"."
] | train | https://github.com/duguyue100/minesweeper/blob/38b1910f4c34d0275ac10a300285aba6f1d91d61/minesweeper/msgame.py#L58-L81 |
duguyue100/minesweeper | minesweeper/msgame.py | MSGame.check_move | def check_move(self, move_type, move_x, move_y):
"""Check if a move is valid.
If the move is not valid, then shut the game.
If the move is valid, then setup a dictionary for the game,
and update move counter.
TODO: maybe instead of shut the game, can end the game or turn it into
a valid move?
Parameters
----------
move_type : string
one of four move types:
"click", "flag", "unflag", "question"
move_x : int
X position of the move
move_y : int
Y position of the move
"""
if move_type not in self.move_types:
raise ValueError("This is not a valid move!")
if move_x < 0 or move_x >= self.board_width:
raise ValueError("This is not a valid X position of the move!")
if move_y < 0 or move_y >= self.board_height:
raise ValueError("This is not a valid Y position of the move!")
move_des = {}
move_des["move_type"] = move_type
move_des["move_x"] = move_x
move_des["move_y"] = move_y
self.num_moves += 1
return move_des | python | def check_move(self, move_type, move_x, move_y):
"""Check if a move is valid.
If the move is not valid, then shut the game.
If the move is valid, then setup a dictionary for the game,
and update move counter.
TODO: maybe instead of shut the game, can end the game or turn it into
a valid move?
Parameters
----------
move_type : string
one of four move types:
"click", "flag", "unflag", "question"
move_x : int
X position of the move
move_y : int
Y position of the move
"""
if move_type not in self.move_types:
raise ValueError("This is not a valid move!")
if move_x < 0 or move_x >= self.board_width:
raise ValueError("This is not a valid X position of the move!")
if move_y < 0 or move_y >= self.board_height:
raise ValueError("This is not a valid Y position of the move!")
move_des = {}
move_des["move_type"] = move_type
move_des["move_x"] = move_x
move_des["move_y"] = move_y
self.num_moves += 1
return move_des | [
"def",
"check_move",
"(",
"self",
",",
"move_type",
",",
"move_x",
",",
"move_y",
")",
":",
"if",
"move_type",
"not",
"in",
"self",
".",
"move_types",
":",
"raise",
"ValueError",
"(",
"\"This is not a valid move!\"",
")",
"if",
"move_x",
"<",
"0",
"or",
"move_x",
">=",
"self",
".",
"board_width",
":",
"raise",
"ValueError",
"(",
"\"This is not a valid X position of the move!\"",
")",
"if",
"move_y",
"<",
"0",
"or",
"move_y",
">=",
"self",
".",
"board_height",
":",
"raise",
"ValueError",
"(",
"\"This is not a valid Y position of the move!\"",
")",
"move_des",
"=",
"{",
"}",
"move_des",
"[",
"\"move_type\"",
"]",
"=",
"move_type",
"move_des",
"[",
"\"move_x\"",
"]",
"=",
"move_x",
"move_des",
"[",
"\"move_y\"",
"]",
"=",
"move_y",
"self",
".",
"num_moves",
"+=",
"1",
"return",
"move_des"
] | Check if a move is valid.
If the move is not valid, then shut the game.
If the move is valid, then setup a dictionary for the game,
and update move counter.
TODO: maybe instead of shut the game, can end the game or turn it into
a valid move?
Parameters
----------
move_type : string
one of four move types:
"click", "flag", "unflag", "question"
move_x : int
X position of the move
move_y : int
Y position of the move | [
"Check",
"if",
"a",
"move",
"is",
"valid",
"."
] | train | https://github.com/duguyue100/minesweeper/blob/38b1910f4c34d0275ac10a300285aba6f1d91d61/minesweeper/msgame.py#L106-L139 |
duguyue100/minesweeper | minesweeper/msgame.py | MSGame.play_move | def play_move(self, move_type, move_x, move_y):
"""Updat board by a given move.
Parameters
----------
move_type : string
one of four move types:
"click", "flag", "unflag", "question"
move_x : int
X position of the move
move_y : int
Y position of the move
"""
# record the move
if self.game_status == 2:
self.move_history.append(self.check_move(move_type, move_x,
move_y))
else:
self.end_game()
# play the move, update the board
if move_type == "click":
self.board.click_field(move_x, move_y)
elif move_type == "flag":
self.board.flag_field(move_x, move_y)
elif move_type == "unflag":
self.board.unflag_field(move_x, move_y)
elif move_type == "question":
self.board.question_field(move_x, move_y)
# check the status, see if end the game
if self.board.check_board() == 0:
self.game_status = 0 # game loses
# self.print_board()
self.end_game()
elif self.board.check_board() == 1:
self.game_status = 1 # game wins
# self.print_board()
self.end_game()
elif self.board.check_board() == 2:
self.game_status = 2 | python | def play_move(self, move_type, move_x, move_y):
"""Updat board by a given move.
Parameters
----------
move_type : string
one of four move types:
"click", "flag", "unflag", "question"
move_x : int
X position of the move
move_y : int
Y position of the move
"""
# record the move
if self.game_status == 2:
self.move_history.append(self.check_move(move_type, move_x,
move_y))
else:
self.end_game()
# play the move, update the board
if move_type == "click":
self.board.click_field(move_x, move_y)
elif move_type == "flag":
self.board.flag_field(move_x, move_y)
elif move_type == "unflag":
self.board.unflag_field(move_x, move_y)
elif move_type == "question":
self.board.question_field(move_x, move_y)
# check the status, see if end the game
if self.board.check_board() == 0:
self.game_status = 0 # game loses
# self.print_board()
self.end_game()
elif self.board.check_board() == 1:
self.game_status = 1 # game wins
# self.print_board()
self.end_game()
elif self.board.check_board() == 2:
self.game_status = 2 | [
"def",
"play_move",
"(",
"self",
",",
"move_type",
",",
"move_x",
",",
"move_y",
")",
":",
"# record the move",
"if",
"self",
".",
"game_status",
"==",
"2",
":",
"self",
".",
"move_history",
".",
"append",
"(",
"self",
".",
"check_move",
"(",
"move_type",
",",
"move_x",
",",
"move_y",
")",
")",
"else",
":",
"self",
".",
"end_game",
"(",
")",
"# play the move, update the board",
"if",
"move_type",
"==",
"\"click\"",
":",
"self",
".",
"board",
".",
"click_field",
"(",
"move_x",
",",
"move_y",
")",
"elif",
"move_type",
"==",
"\"flag\"",
":",
"self",
".",
"board",
".",
"flag_field",
"(",
"move_x",
",",
"move_y",
")",
"elif",
"move_type",
"==",
"\"unflag\"",
":",
"self",
".",
"board",
".",
"unflag_field",
"(",
"move_x",
",",
"move_y",
")",
"elif",
"move_type",
"==",
"\"question\"",
":",
"self",
".",
"board",
".",
"question_field",
"(",
"move_x",
",",
"move_y",
")",
"# check the status, see if end the game",
"if",
"self",
".",
"board",
".",
"check_board",
"(",
")",
"==",
"0",
":",
"self",
".",
"game_status",
"=",
"0",
"# game loses",
"# self.print_board()",
"self",
".",
"end_game",
"(",
")",
"elif",
"self",
".",
"board",
".",
"check_board",
"(",
")",
"==",
"1",
":",
"self",
".",
"game_status",
"=",
"1",
"# game wins",
"# self.print_board()",
"self",
".",
"end_game",
"(",
")",
"elif",
"self",
".",
"board",
".",
"check_board",
"(",
")",
"==",
"2",
":",
"self",
".",
"game_status",
"=",
"2"
] | Updat board by a given move.
Parameters
----------
move_type : string
one of four move types:
"click", "flag", "unflag", "question"
move_x : int
X position of the move
move_y : int
Y position of the move | [
"Updat",
"board",
"by",
"a",
"given",
"move",
"."
] | train | https://github.com/duguyue100/minesweeper/blob/38b1910f4c34d0275ac10a300285aba6f1d91d61/minesweeper/msgame.py#L141-L181 |
duguyue100/minesweeper | minesweeper/msgame.py | MSGame.parse_move | def parse_move(self, move_msg):
"""Parse a move from a string.
Parameters
----------
move_msg : string
a valid message should be in:
"[move type]: [X], [Y]"
Returns
-------
"""
# TODO: some condition check
type_idx = move_msg.index(":")
move_type = move_msg[:type_idx]
pos_idx = move_msg.index(",")
move_x = int(move_msg[type_idx+1:pos_idx])
move_y = int(move_msg[pos_idx+1:])
return move_type, move_x, move_y | python | def parse_move(self, move_msg):
"""Parse a move from a string.
Parameters
----------
move_msg : string
a valid message should be in:
"[move type]: [X], [Y]"
Returns
-------
"""
# TODO: some condition check
type_idx = move_msg.index(":")
move_type = move_msg[:type_idx]
pos_idx = move_msg.index(",")
move_x = int(move_msg[type_idx+1:pos_idx])
move_y = int(move_msg[pos_idx+1:])
return move_type, move_x, move_y | [
"def",
"parse_move",
"(",
"self",
",",
"move_msg",
")",
":",
"# TODO: some condition check",
"type_idx",
"=",
"move_msg",
".",
"index",
"(",
"\":\"",
")",
"move_type",
"=",
"move_msg",
"[",
":",
"type_idx",
"]",
"pos_idx",
"=",
"move_msg",
".",
"index",
"(",
"\",\"",
")",
"move_x",
"=",
"int",
"(",
"move_msg",
"[",
"type_idx",
"+",
"1",
":",
"pos_idx",
"]",
")",
"move_y",
"=",
"int",
"(",
"move_msg",
"[",
"pos_idx",
"+",
"1",
":",
"]",
")",
"return",
"move_type",
",",
"move_x",
",",
"move_y"
] | Parse a move from a string.
Parameters
----------
move_msg : string
a valid message should be in:
"[move type]: [X], [Y]"
Returns
------- | [
"Parse",
"a",
"move",
"from",
"a",
"string",
"."
] | train | https://github.com/duguyue100/minesweeper/blob/38b1910f4c34d0275ac10a300285aba6f1d91d61/minesweeper/msgame.py#L210-L229 |
duguyue100/minesweeper | minesweeper/msgame.py | MSGame.play_move_msg | def play_move_msg(self, move_msg):
"""Another play move function for move message.
Parameters
----------
move_msg : string
a valid message should be in:
"[move type]: [X], [Y]"
"""
move_type, move_x, move_y = self.parse_move(move_msg)
self.play_move(move_type, move_x, move_y) | python | def play_move_msg(self, move_msg):
"""Another play move function for move message.
Parameters
----------
move_msg : string
a valid message should be in:
"[move type]: [X], [Y]"
"""
move_type, move_x, move_y = self.parse_move(move_msg)
self.play_move(move_type, move_x, move_y) | [
"def",
"play_move_msg",
"(",
"self",
",",
"move_msg",
")",
":",
"move_type",
",",
"move_x",
",",
"move_y",
"=",
"self",
".",
"parse_move",
"(",
"move_msg",
")",
"self",
".",
"play_move",
"(",
"move_type",
",",
"move_x",
",",
"move_y",
")"
] | Another play move function for move message.
Parameters
----------
move_msg : string
a valid message should be in:
"[move type]: [X], [Y]" | [
"Another",
"play",
"move",
"function",
"for",
"move",
"message",
"."
] | train | https://github.com/duguyue100/minesweeper/blob/38b1910f4c34d0275ac10a300285aba6f1d91d61/minesweeper/msgame.py#L231-L241 |
duguyue100/minesweeper | minesweeper/msgame.py | MSGame.tcp_accept | def tcp_accept(self):
"""Waiting for a TCP connection."""
self.conn, self.addr = self.tcp_socket.accept()
print("[MESSAGE] The connection is established at: ", self.addr)
self.tcp_send("> ") | python | def tcp_accept(self):
"""Waiting for a TCP connection."""
self.conn, self.addr = self.tcp_socket.accept()
print("[MESSAGE] The connection is established at: ", self.addr)
self.tcp_send("> ") | [
"def",
"tcp_accept",
"(",
"self",
")",
":",
"self",
".",
"conn",
",",
"self",
".",
"addr",
"=",
"self",
".",
"tcp_socket",
".",
"accept",
"(",
")",
"print",
"(",
"\"[MESSAGE] The connection is established at: \"",
",",
"self",
".",
"addr",
")",
"self",
".",
"tcp_send",
"(",
"\"> \"",
")"
] | Waiting for a TCP connection. | [
"Waiting",
"for",
"a",
"TCP",
"connection",
"."
] | train | https://github.com/duguyue100/minesweeper/blob/38b1910f4c34d0275ac10a300285aba6f1d91d61/minesweeper/msgame.py#L243-L247 |
duguyue100/minesweeper | minesweeper/msgame.py | MSGame.tcp_receive | def tcp_receive(self):
"""Receive data from TCP port."""
data = self.conn.recv(self.BUFFER_SIZE)
if type(data) != str:
# Python 3 specific
data = data.decode("utf-8")
return str(data) | python | def tcp_receive(self):
"""Receive data from TCP port."""
data = self.conn.recv(self.BUFFER_SIZE)
if type(data) != str:
# Python 3 specific
data = data.decode("utf-8")
return str(data) | [
"def",
"tcp_receive",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"conn",
".",
"recv",
"(",
"self",
".",
"BUFFER_SIZE",
")",
"if",
"type",
"(",
"data",
")",
"!=",
"str",
":",
"# Python 3 specific",
"data",
"=",
"data",
".",
"decode",
"(",
"\"utf-8\"",
")",
"return",
"str",
"(",
"data",
")"
] | Receive data from TCP port. | [
"Receive",
"data",
"from",
"TCP",
"port",
"."
] | train | https://github.com/duguyue100/minesweeper/blob/38b1910f4c34d0275ac10a300285aba6f1d91d61/minesweeper/msgame.py#L249-L257 |
earlzo/hfut | hfut/parser.py | parse_tr_strs | def parse_tr_strs(trs):
"""
将没有值但有必须要的单元格的值设置为 None
将 <tr> 标签数组内的单元格文字解析出来并返回一个二维列表
:param trs: <tr> 标签或标签数组, 为 :class:`bs4.element.Tag` 对象
:return: 二维列表
"""
tr_strs = []
for tr in trs:
strs = []
for td in tr.find_all('td'):
text = td.get_text(strip=True)
strs.append(text or None)
tr_strs.append(strs)
logger.debug('从行中解析出以下数据\n%s', pformat(tr_strs))
return tr_strs | python | def parse_tr_strs(trs):
"""
将没有值但有必须要的单元格的值设置为 None
将 <tr> 标签数组内的单元格文字解析出来并返回一个二维列表
:param trs: <tr> 标签或标签数组, 为 :class:`bs4.element.Tag` 对象
:return: 二维列表
"""
tr_strs = []
for tr in trs:
strs = []
for td in tr.find_all('td'):
text = td.get_text(strip=True)
strs.append(text or None)
tr_strs.append(strs)
logger.debug('从行中解析出以下数据\n%s', pformat(tr_strs))
return tr_strs | [
"def",
"parse_tr_strs",
"(",
"trs",
")",
":",
"tr_strs",
"=",
"[",
"]",
"for",
"tr",
"in",
"trs",
":",
"strs",
"=",
"[",
"]",
"for",
"td",
"in",
"tr",
".",
"find_all",
"(",
"'td'",
")",
":",
"text",
"=",
"td",
".",
"get_text",
"(",
"strip",
"=",
"True",
")",
"strs",
".",
"append",
"(",
"text",
"or",
"None",
")",
"tr_strs",
".",
"append",
"(",
"strs",
")",
"logger",
".",
"debug",
"(",
"'从行中解析出以下数据\\n%s', pformat(tr_strs))",
"",
"",
"",
"",
"",
"",
"return",
"tr_strs"
] | 将没有值但有必须要的单元格的值设置为 None
将 <tr> 标签数组内的单元格文字解析出来并返回一个二维列表
:param trs: <tr> 标签或标签数组, 为 :class:`bs4.element.Tag` 对象
:return: 二维列表 | [
"将没有值但有必须要的单元格的值设置为",
"None",
"将",
"<tr",
">",
"标签数组内的单元格文字解析出来并返回一个二维列表"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/parser.py#L54-L70 |
earlzo/hfut | hfut/parser.py | flatten_list | def flatten_list(multiply_list):
"""
碾平 list::
>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten_list(a)
[1, 2, 3, 4, 5, 6, 7, 8]
:param multiply_list: 混淆的多层列表
:return: 单层的 list
"""
if isinstance(multiply_list, list):
return [rv for l in multiply_list for rv in flatten_list(l)]
else:
return [multiply_list] | python | def flatten_list(multiply_list):
"""
碾平 list::
>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten_list(a)
[1, 2, 3, 4, 5, 6, 7, 8]
:param multiply_list: 混淆的多层列表
:return: 单层的 list
"""
if isinstance(multiply_list, list):
return [rv for l in multiply_list for rv in flatten_list(l)]
else:
return [multiply_list] | [
"def",
"flatten_list",
"(",
"multiply_list",
")",
":",
"if",
"isinstance",
"(",
"multiply_list",
",",
"list",
")",
":",
"return",
"[",
"rv",
"for",
"l",
"in",
"multiply_list",
"for",
"rv",
"in",
"flatten_list",
"(",
"l",
")",
"]",
"else",
":",
"return",
"[",
"multiply_list",
"]"
] | 碾平 list::
>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten_list(a)
[1, 2, 3, 4, 5, 6, 7, 8]
:param multiply_list: 混淆的多层列表
:return: 单层的 list | [
"碾平",
"list",
"::"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/parser.py#L73-L87 |
earlzo/hfut | hfut/parser.py | dict_list_2_matrix | def dict_list_2_matrix(dict_list, columns):
"""
>>> dict_list_2_matrix([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], ('a', 'b'))
[[1, 2], [3, 4]]
:param dict_list: 字典列表
:param columns: 字典的键
"""
k = len(columns)
n = len(dict_list)
result = [[None] * k for i in range(n)]
for i in range(n):
row = dict_list[i]
for j in range(k):
col = columns[j]
if col in row:
result[i][j] = row[col]
else:
result[i][j] = None
return result | python | def dict_list_2_matrix(dict_list, columns):
"""
>>> dict_list_2_matrix([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], ('a', 'b'))
[[1, 2], [3, 4]]
:param dict_list: 字典列表
:param columns: 字典的键
"""
k = len(columns)
n = len(dict_list)
result = [[None] * k for i in range(n)]
for i in range(n):
row = dict_list[i]
for j in range(k):
col = columns[j]
if col in row:
result[i][j] = row[col]
else:
result[i][j] = None
return result | [
"def",
"dict_list_2_matrix",
"(",
"dict_list",
",",
"columns",
")",
":",
"k",
"=",
"len",
"(",
"columns",
")",
"n",
"=",
"len",
"(",
"dict_list",
")",
"result",
"=",
"[",
"[",
"None",
"]",
"*",
"k",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"row",
"=",
"dict_list",
"[",
"i",
"]",
"for",
"j",
"in",
"range",
"(",
"k",
")",
":",
"col",
"=",
"columns",
"[",
"j",
"]",
"if",
"col",
"in",
"row",
":",
"result",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"row",
"[",
"col",
"]",
"else",
":",
"result",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"None",
"return",
"result"
] | >>> dict_list_2_matrix([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], ('a', 'b'))
[[1, 2], [3, 4]]
:param dict_list: 字典列表
:param columns: 字典的键 | [
">>>",
"dict_list_2_matrix",
"(",
"[",
"{",
"a",
":",
"1",
"b",
":",
"2",
"}",
"{",
"a",
":",
"3",
"b",
":",
"4",
"}",
"]",
"(",
"a",
"b",
"))",
"[[",
"1",
"2",
"]",
"[",
"3",
"4",
"]]"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/parser.py#L106-L126 |
earlzo/hfut | hfut/parser.py | parse_course | def parse_course(course_str):
"""
解析课程表里的课程
:param course_str: 形如 `单片机原理及应用[新安学堂434 (9-15周)]/数字图像处理及应用[新安学堂434 (1-7周)]/` 的课程表数据
"""
# 解析课程单元格
# 所有情况
# 机械原理[一教416 (1-14周)]/
# 程序与算法综合设计[不占用教室 (18周)]/
# 财务管理[一教323 (11-17单周)]/
# 财务管理[一教323 (10-16双周)]/
# 形势与政策(4)[一教220 (2,4,6-7周)]/
p = re.compile(r'(.+?)\[(.+?)\s+\(([\d,-单双]+?)周\)\]/')
courses = p.findall(course_str)
results = []
for course in courses:
d = {'课程名称': course[0], '课程地点': course[1]}
# 解析上课周数
week_str = course[2]
l = week_str.split(',')
weeks = []
for v in l:
m = re.match(r'(\d+)$', v) or re.match(r'(\d+)-(\d+)$', v) or re.match(r'(\d+)-(\d+)(单|双)$', v)
g = m.groups()
gl = len(g)
if gl == 1:
weeks.append(int(g[0]))
elif gl == 2:
weeks.extend([i for i in range(int(g[0]), int(g[1]) + 1)])
else:
weeks.extend([i for i in range(int(g[0]), int(g[1]) + 1, 2)])
d['上课周数'] = weeks
results.append(d)
return results | python | def parse_course(course_str):
"""
解析课程表里的课程
:param course_str: 形如 `单片机原理及应用[新安学堂434 (9-15周)]/数字图像处理及应用[新安学堂434 (1-7周)]/` 的课程表数据
"""
# 解析课程单元格
# 所有情况
# 机械原理[一教416 (1-14周)]/
# 程序与算法综合设计[不占用教室 (18周)]/
# 财务管理[一教323 (11-17单周)]/
# 财务管理[一教323 (10-16双周)]/
# 形势与政策(4)[一教220 (2,4,6-7周)]/
p = re.compile(r'(.+?)\[(.+?)\s+\(([\d,-单双]+?)周\)\]/')
courses = p.findall(course_str)
results = []
for course in courses:
d = {'课程名称': course[0], '课程地点': course[1]}
# 解析上课周数
week_str = course[2]
l = week_str.split(',')
weeks = []
for v in l:
m = re.match(r'(\d+)$', v) or re.match(r'(\d+)-(\d+)$', v) or re.match(r'(\d+)-(\d+)(单|双)$', v)
g = m.groups()
gl = len(g)
if gl == 1:
weeks.append(int(g[0]))
elif gl == 2:
weeks.extend([i for i in range(int(g[0]), int(g[1]) + 1)])
else:
weeks.extend([i for i in range(int(g[0]), int(g[1]) + 1, 2)])
d['上课周数'] = weeks
results.append(d)
return results | [
"def",
"parse_course",
"(",
"course_str",
")",
":",
"# 解析课程单元格",
"# 所有情况",
"# 机械原理[一教416 (1-14周)]/",
"# 程序与算法综合设计[不占用教室 (18周)]/",
"# 财务管理[一教323 (11-17单周)]/",
"# 财务管理[一教323 (10-16双周)]/",
"# 形势与政策(4)[一教220 (2,4,6-7周)]/",
"p",
"=",
"re",
".",
"compile",
"(",
"r'(.+?)\\[(.+?)\\s+\\(([\\d,-单双]+?)周\\)\\]/')",
"",
"courses",
"=",
"p",
".",
"findall",
"(",
"course_str",
")",
"results",
"=",
"[",
"]",
"for",
"course",
"in",
"courses",
":",
"d",
"=",
"{",
"'课程名称': course",
"[",
"], '课程",
"地",
"点",
"'",
":",
"course[1]}",
"",
"",
"",
"",
"",
"",
"# 解析上课周数",
"week_str",
"=",
"course",
"[",
"2",
"]",
"l",
"=",
"week_str",
".",
"split",
"(",
"','",
")",
"weeks",
"=",
"[",
"]",
"for",
"v",
"in",
"l",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'(\\d+)$'",
",",
"v",
")",
"or",
"re",
".",
"match",
"(",
"r'(\\d+)-(\\d+)$'",
",",
"v",
")",
"or",
"re",
".",
"match",
"(",
"r'(\\d+)-(\\d+)(单|双)$', v)",
"",
"",
"",
"g",
"=",
"m",
".",
"groups",
"(",
")",
"gl",
"=",
"len",
"(",
"g",
")",
"if",
"gl",
"==",
"1",
":",
"weeks",
".",
"append",
"(",
"int",
"(",
"g",
"[",
"0",
"]",
")",
")",
"elif",
"gl",
"==",
"2",
":",
"weeks",
".",
"extend",
"(",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"int",
"(",
"g",
"[",
"0",
"]",
")",
",",
"int",
"(",
"g",
"[",
"1",
"]",
")",
"+",
"1",
")",
"]",
")",
"else",
":",
"weeks",
".",
"extend",
"(",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"int",
"(",
"g",
"[",
"0",
"]",
")",
",",
"int",
"(",
"g",
"[",
"1",
"]",
")",
"+",
"1",
",",
"2",
")",
"]",
")",
"d",
"[",
"'上课周数'] = week",
"s",
"",
"",
"results",
".",
"append",
"(",
"d",
")",
"return",
"results"
] | 解析课程表里的课程
:param course_str: 形如 `单片机原理及应用[新安学堂434 (9-15周)]/数字图像处理及应用[新安学堂434 (1-7周)]/` 的课程表数据 | [
"解析课程表里的课程"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/parser.py#L129-L163 |
earlzo/hfut | hfut/shortcut.py | Guest.get_class_students | def get_class_students(self, xqdm, kcdm, jxbh):
"""
教学班查询, 查询指定教学班的所有学生
@structure {'学期': str, '班级名称': str, '学生': [{'姓名': str, '学号': int}]}
:param xqdm: 学期代码
:param kcdm: 课程代码
:param jxbh: 教学班号
"""
return self.query(GetClassStudents(xqdm, kcdm, jxbh)) | python | def get_class_students(self, xqdm, kcdm, jxbh):
"""
教学班查询, 查询指定教学班的所有学生
@structure {'学期': str, '班级名称': str, '学生': [{'姓名': str, '学号': int}]}
:param xqdm: 学期代码
:param kcdm: 课程代码
:param jxbh: 教学班号
"""
return self.query(GetClassStudents(xqdm, kcdm, jxbh)) | [
"def",
"get_class_students",
"(",
"self",
",",
"xqdm",
",",
"kcdm",
",",
"jxbh",
")",
":",
"return",
"self",
".",
"query",
"(",
"GetClassStudents",
"(",
"xqdm",
",",
"kcdm",
",",
"jxbh",
")",
")"
] | 教学班查询, 查询指定教学班的所有学生
@structure {'学期': str, '班级名称': str, '学生': [{'姓名': str, '学号': int}]}
:param xqdm: 学期代码
:param kcdm: 课程代码
:param jxbh: 教学班号 | [
"教学班查询",
"查询指定教学班的所有学生"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L47-L57 |
earlzo/hfut | hfut/shortcut.py | Guest.get_class_info | def get_class_info(self, xqdm, kcdm, jxbh):
"""
获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息
@structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str,
'时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str}
:param xqdm: 学期代码
:param kcdm: 课程代码
:param jxbh: 教学班号
"""
return self.query(GetClassInfo(xqdm, kcdm, jxbh)) | python | def get_class_info(self, xqdm, kcdm, jxbh):
"""
获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息
@structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str,
'时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str}
:param xqdm: 学期代码
:param kcdm: 课程代码
:param jxbh: 教学班号
"""
return self.query(GetClassInfo(xqdm, kcdm, jxbh)) | [
"def",
"get_class_info",
"(",
"self",
",",
"xqdm",
",",
"kcdm",
",",
"jxbh",
")",
":",
"return",
"self",
".",
"query",
"(",
"GetClassInfo",
"(",
"xqdm",
",",
"kcdm",
",",
"jxbh",
")",
")"
] | 获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息
@structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str,
'时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str}
:param xqdm: 学期代码
:param kcdm: 课程代码
:param jxbh: 教学班号 | [
"获取教学班详情",
"包括上课时间地点",
"考查方式",
"老师",
"选中人数",
"课程容量等等信息"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L59-L70 |
earlzo/hfut | hfut/shortcut.py | Guest.search_course | def search_course(self, xqdm, kcdm=None, kcmc=None):
"""
课程查询
@structure [{'任课教师': str, '课程名称': str, '教学班号': str, '课程代码': str, '班级容量': int}]
:param xqdm: 学期代码
:param kcdm: 课程代码
:param kcmc: 课程名称
"""
return self.query(SearchCourse(xqdm, kcdm, kcmc)) | python | def search_course(self, xqdm, kcdm=None, kcmc=None):
"""
课程查询
@structure [{'任课教师': str, '课程名称': str, '教学班号': str, '课程代码': str, '班级容量': int}]
:param xqdm: 学期代码
:param kcdm: 课程代码
:param kcmc: 课程名称
"""
return self.query(SearchCourse(xqdm, kcdm, kcmc)) | [
"def",
"search_course",
"(",
"self",
",",
"xqdm",
",",
"kcdm",
"=",
"None",
",",
"kcmc",
"=",
"None",
")",
":",
"return",
"self",
".",
"query",
"(",
"SearchCourse",
"(",
"xqdm",
",",
"kcdm",
",",
"kcmc",
")",
")"
] | 课程查询
@structure [{'任课教师': str, '课程名称': str, '教学班号': str, '课程代码': str, '班级容量': int}]
:param xqdm: 学期代码
:param kcdm: 课程代码
:param kcmc: 课程名称 | [
"课程查询"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L72-L82 |
earlzo/hfut | hfut/shortcut.py | Guest.get_teaching_plan | def get_teaching_plan(self, xqdm, kclx='b', zydm=''):
"""
专业教学计划查询, 可以查询全校公选课, 此时可以不填 `zydm`
@structure [{'开课单位': str, '学时': int, '课程名称': str, '课程代码': str, '学分': float}]
:param xqdm: 学期代码
:param kclx: 课程类型参数,只有两个值 b:专业必修课, x:全校公选课
:param zydm: 专业代码, 可以从 :meth:`models.StudentSession.get_code` 获得
"""
return self.query(GetTeachingPlan(xqdm, kclx, zydm)) | python | def get_teaching_plan(self, xqdm, kclx='b', zydm=''):
"""
专业教学计划查询, 可以查询全校公选课, 此时可以不填 `zydm`
@structure [{'开课单位': str, '学时': int, '课程名称': str, '课程代码': str, '学分': float}]
:param xqdm: 学期代码
:param kclx: 课程类型参数,只有两个值 b:专业必修课, x:全校公选课
:param zydm: 专业代码, 可以从 :meth:`models.StudentSession.get_code` 获得
"""
return self.query(GetTeachingPlan(xqdm, kclx, zydm)) | [
"def",
"get_teaching_plan",
"(",
"self",
",",
"xqdm",
",",
"kclx",
"=",
"'b'",
",",
"zydm",
"=",
"''",
")",
":",
"return",
"self",
".",
"query",
"(",
"GetTeachingPlan",
"(",
"xqdm",
",",
"kclx",
",",
"zydm",
")",
")"
] | 专业教学计划查询, 可以查询全校公选课, 此时可以不填 `zydm`
@structure [{'开课单位': str, '学时': int, '课程名称': str, '课程代码': str, '学分': float}]
:param xqdm: 学期代码
:param kclx: 课程类型参数,只有两个值 b:专业必修课, x:全校公选课
:param zydm: 专业代码, 可以从 :meth:`models.StudentSession.get_code` 获得 | [
"专业教学计划查询",
"可以查询全校公选课",
"此时可以不填",
"zydm"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L84-L94 |
earlzo/hfut | hfut/shortcut.py | Student.change_password | def change_password(self, new_password):
"""
修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错
@structure bool
:param new_password: 新密码
"""
if self.session.campus == HF:
raise ValueError('合肥校区使用信息中心账号登录, 修改教务密码没有作用')
# 若新密码与原密码相同, 直接返回 True
if new_password == self.session.password:
raise ValueError('原密码与新密码相同')
result = self.query(ChangePassword(self.session.password, new_password))
if result:
self.session.password = new_password
return result | python | def change_password(self, new_password):
"""
修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错
@structure bool
:param new_password: 新密码
"""
if self.session.campus == HF:
raise ValueError('合肥校区使用信息中心账号登录, 修改教务密码没有作用')
# 若新密码与原密码相同, 直接返回 True
if new_password == self.session.password:
raise ValueError('原密码与新密码相同')
result = self.query(ChangePassword(self.session.password, new_password))
if result:
self.session.password = new_password
return result | [
"def",
"change_password",
"(",
"self",
",",
"new_password",
")",
":",
"if",
"self",
".",
"session",
".",
"campus",
"==",
"HF",
":",
"raise",
"ValueError",
"(",
"'合肥校区使用信息中心账号登录, 修改教务密码没有作用')",
"",
"# 若新密码与原密码相同, 直接返回 True",
"if",
"new_password",
"==",
"self",
".",
"session",
".",
"password",
":",
"raise",
"ValueError",
"(",
"'原密码与新密码相同')",
"",
"result",
"=",
"self",
".",
"query",
"(",
"ChangePassword",
"(",
"self",
".",
"session",
".",
"password",
",",
"new_password",
")",
")",
"if",
"result",
":",
"self",
".",
"session",
".",
"password",
"=",
"new_password",
"return",
"result"
] | 修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错
@structure bool
:param new_password: 新密码 | [
"修改教务密码",
"**",
"注意",
"**",
"合肥校区使用信息中心账号登录",
"与教务密码不一致",
"即使修改了也没有作用",
"因此合肥校区帐号调用此接口会直接报错"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L179-L197 |
earlzo/hfut | hfut/shortcut.py | Student.set_telephone | def set_telephone(self, tel):
"""
更新电话
@structure bool
:param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567'
"""
return type(tel)(self.query(SetTelephone(tel))) == tel | python | def set_telephone(self, tel):
"""
更新电话
@structure bool
:param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567'
"""
return type(tel)(self.query(SetTelephone(tel))) == tel | [
"def",
"set_telephone",
"(",
"self",
",",
"tel",
")",
":",
"return",
"type",
"(",
"tel",
")",
"(",
"self",
".",
"query",
"(",
"SetTelephone",
"(",
"tel",
")",
")",
")",
"==",
"tel"
] | 更新电话
@structure bool
:param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567' | [
"更新电话"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L199-L208 |
earlzo/hfut | hfut/shortcut.py | Student.evaluate_course | def evaluate_course(self, kcdm, jxbh,
r101=1, r102=1, r103=1, r104=1, r105=1, r106=1, r107=1, r108=1, r109=1,
r201=3, r202=3, advice=''):
"""
课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好.
默认都是最好的选项
:param kcdm: 课程代码
:param jxbh: 教学班号
:param r101: 教学态度认真,课前准备充分
:param r102: 教授内容充实,要点重点突出
:param r103: 理论联系实际,反映最新成果
:param r104: 教学方法灵活,师生互动得当
:param r105: 运用现代技术,教学手段多样
:param r106: 注重因材施教,加强能力培养
:param r107: 严格要求管理,关心爱护学生
:param r108: 处处为人师表,注重教书育人
:param r109: 教学综合效果
:param r201: 课程内容
:param r202: 课程负担
:param advice: 其他建议,不能超过120字且不能使用分号,单引号,都好
:return:
"""
return self.query(EvaluateCourse(
kcdm, jxbh,
r101, r102, r103, r104, r105, r106, r107, r108, r109,
r201, r202, advice
)) | python | def evaluate_course(self, kcdm, jxbh,
r101=1, r102=1, r103=1, r104=1, r105=1, r106=1, r107=1, r108=1, r109=1,
r201=3, r202=3, advice=''):
"""
课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好.
默认都是最好的选项
:param kcdm: 课程代码
:param jxbh: 教学班号
:param r101: 教学态度认真,课前准备充分
:param r102: 教授内容充实,要点重点突出
:param r103: 理论联系实际,反映最新成果
:param r104: 教学方法灵活,师生互动得当
:param r105: 运用现代技术,教学手段多样
:param r106: 注重因材施教,加强能力培养
:param r107: 严格要求管理,关心爱护学生
:param r108: 处处为人师表,注重教书育人
:param r109: 教学综合效果
:param r201: 课程内容
:param r202: 课程负担
:param advice: 其他建议,不能超过120字且不能使用分号,单引号,都好
:return:
"""
return self.query(EvaluateCourse(
kcdm, jxbh,
r101, r102, r103, r104, r105, r106, r107, r108, r109,
r201, r202, advice
)) | [
"def",
"evaluate_course",
"(",
"self",
",",
"kcdm",
",",
"jxbh",
",",
"r101",
"=",
"1",
",",
"r102",
"=",
"1",
",",
"r103",
"=",
"1",
",",
"r104",
"=",
"1",
",",
"r105",
"=",
"1",
",",
"r106",
"=",
"1",
",",
"r107",
"=",
"1",
",",
"r108",
"=",
"1",
",",
"r109",
"=",
"1",
",",
"r201",
"=",
"3",
",",
"r202",
"=",
"3",
",",
"advice",
"=",
"''",
")",
":",
"return",
"self",
".",
"query",
"(",
"EvaluateCourse",
"(",
"kcdm",
",",
"jxbh",
",",
"r101",
",",
"r102",
",",
"r103",
",",
"r104",
",",
"r105",
",",
"r106",
",",
"r107",
",",
"r108",
",",
"r109",
",",
"r201",
",",
"r202",
",",
"advice",
")",
")"
] | 课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好.
默认都是最好的选项
:param kcdm: 课程代码
:param jxbh: 教学班号
:param r101: 教学态度认真,课前准备充分
:param r102: 教授内容充实,要点重点突出
:param r103: 理论联系实际,反映最新成果
:param r104: 教学方法灵活,师生互动得当
:param r105: 运用现代技术,教学手段多样
:param r106: 注重因材施教,加强能力培养
:param r107: 严格要求管理,关心爱护学生
:param r108: 处处为人师表,注重教书育人
:param r109: 教学综合效果
:param r201: 课程内容
:param r202: 课程负担
:param advice: 其他建议,不能超过120字且不能使用分号,单引号,都好
:return: | [
"课程评价",
"数值为",
"1",
"-",
"5",
"r1",
"类选项",
"1",
"为最好",
"5",
"为最差",
"r2",
"类选项程度由深到浅",
"3",
"为最好",
"."
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L237-L265 |
earlzo/hfut | hfut/shortcut.py | Student.change_course | def change_course(self, select_courses=None, delete_courses=None):
"""
修改个人的课程
@structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}]
:param select_courses: 形如 ``[{'kcdm': '9900039X', 'jxbhs': {'0001', '0002'}}]`` 的课程代码与教学班号列表,
jxbhs 可以为空代表选择所有可选班级
:param delete_courses: 需要删除的课程代码集合, 如 ``{'0200011B'}``
:return: 选课结果, 返回选中的课程教学班列表, 结构与 ``get_selected_courses`` 一致
"""
# 框架重构后调整接口的调用
t = self.get_system_status()
if t['当前轮数'] is None:
raise ValueError('当前为 %s,选课系统尚未开启', t['当前学期'])
if not (select_courses or delete_courses):
raise ValueError('select_courses, delete_courses 参数不能都为空!')
# 参数处理
select_courses = select_courses or []
delete_courses = {l.upper() for l in (delete_courses or [])}
selected_courses = self.get_selected_courses()
selected_kcdms = {course['课程代码'] for course in selected_courses}
# 尝试删除没有被选中的课程会出错
unselected = delete_courses.difference(selected_kcdms)
if unselected:
msg = '无法删除没有被选的课程 {}'.format(unselected)
logger.warning(msg)
# 要提交的 kcdm 数据
kcdms_data = []
# 要提交的 jxbh 数据
jxbhs_data = []
# 必须添加已选课程, 同时去掉要删除的课程
for course in selected_courses:
if course['课程代码'] not in delete_courses:
kcdms_data.append(course['课程代码'])
jxbhs_data.append(course['教学班号'])
# 选课
for kv in select_courses:
kcdm = kv['kcdm'].upper()
jxbhs = set(kv['jxbhs']) if kv.get('jxbhs') else set()
teaching_classes = self.get_course_classes(kcdm)
if not teaching_classes:
logger.warning('课程[%s]没有可选班级', kcdm)
continue
# 反正是统一提交, 不需要判断是否已满
optional_jxbhs = {c['教学班号'] for c in teaching_classes['可选班级']}
if jxbhs:
wrong_jxbhs = jxbhs.difference(optional_jxbhs)
if wrong_jxbhs:
msg = '课程[{}]{}没有教学班号{}'.format(kcdm, teaching_classes['课程名称'], wrong_jxbhs)
logger.warning(msg)
jxbhs = jxbhs.intersection(optional_jxbhs)
else:
jxbhs = optional_jxbhs
for jxbh in jxbhs:
kcdms_data.append(kcdm)
jxbhs_data.append(jxbh)
return self.query(ChangeCourse(self.session.account, select_courses, delete_courses)) | python | def change_course(self, select_courses=None, delete_courses=None):
"""
修改个人的课程
@structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}]
:param select_courses: 形如 ``[{'kcdm': '9900039X', 'jxbhs': {'0001', '0002'}}]`` 的课程代码与教学班号列表,
jxbhs 可以为空代表选择所有可选班级
:param delete_courses: 需要删除的课程代码集合, 如 ``{'0200011B'}``
:return: 选课结果, 返回选中的课程教学班列表, 结构与 ``get_selected_courses`` 一致
"""
# 框架重构后调整接口的调用
t = self.get_system_status()
if t['当前轮数'] is None:
raise ValueError('当前为 %s,选课系统尚未开启', t['当前学期'])
if not (select_courses or delete_courses):
raise ValueError('select_courses, delete_courses 参数不能都为空!')
# 参数处理
select_courses = select_courses or []
delete_courses = {l.upper() for l in (delete_courses or [])}
selected_courses = self.get_selected_courses()
selected_kcdms = {course['课程代码'] for course in selected_courses}
# 尝试删除没有被选中的课程会出错
unselected = delete_courses.difference(selected_kcdms)
if unselected:
msg = '无法删除没有被选的课程 {}'.format(unselected)
logger.warning(msg)
# 要提交的 kcdm 数据
kcdms_data = []
# 要提交的 jxbh 数据
jxbhs_data = []
# 必须添加已选课程, 同时去掉要删除的课程
for course in selected_courses:
if course['课程代码'] not in delete_courses:
kcdms_data.append(course['课程代码'])
jxbhs_data.append(course['教学班号'])
# 选课
for kv in select_courses:
kcdm = kv['kcdm'].upper()
jxbhs = set(kv['jxbhs']) if kv.get('jxbhs') else set()
teaching_classes = self.get_course_classes(kcdm)
if not teaching_classes:
logger.warning('课程[%s]没有可选班级', kcdm)
continue
# 反正是统一提交, 不需要判断是否已满
optional_jxbhs = {c['教学班号'] for c in teaching_classes['可选班级']}
if jxbhs:
wrong_jxbhs = jxbhs.difference(optional_jxbhs)
if wrong_jxbhs:
msg = '课程[{}]{}没有教学班号{}'.format(kcdm, teaching_classes['课程名称'], wrong_jxbhs)
logger.warning(msg)
jxbhs = jxbhs.intersection(optional_jxbhs)
else:
jxbhs = optional_jxbhs
for jxbh in jxbhs:
kcdms_data.append(kcdm)
jxbhs_data.append(jxbh)
return self.query(ChangeCourse(self.session.account, select_courses, delete_courses)) | [
"def",
"change_course",
"(",
"self",
",",
"select_courses",
"=",
"None",
",",
"delete_courses",
"=",
"None",
")",
":",
"# 框架重构后调整接口的调用",
"t",
"=",
"self",
".",
"get_system_status",
"(",
")",
"if",
"t",
"[",
"'当前轮数'] is Non",
"e",
"",
"",
"",
"raise",
"ValueError",
"(",
"'当前为 %s,选课系统尚未开启', t['当前学期'])",
"",
"",
"",
"",
"",
"",
"if",
"not",
"(",
"select_courses",
"or",
"delete_courses",
")",
":",
"raise",
"ValueError",
"(",
"'select_courses, delete_courses 参数不能都为空!')",
"",
"# 参数处理",
"select_courses",
"=",
"select_courses",
"or",
"[",
"]",
"delete_courses",
"=",
"{",
"l",
".",
"upper",
"(",
")",
"for",
"l",
"in",
"(",
"delete_courses",
"or",
"[",
"]",
")",
"}",
"selected_courses",
"=",
"self",
".",
"get_selected_courses",
"(",
")",
"selected_kcdms",
"=",
"{",
"course",
"[",
"'课程代码'] for co",
"u",
"se ",
"n sele",
"te",
"_courses}",
"",
"# 尝试删除没有被选中的课程会出错",
"unselected",
"=",
"delete_courses",
".",
"difference",
"(",
"selected_kcdms",
")",
"if",
"unselected",
":",
"msg",
"=",
"'无法删除没有被选的课程 {}'.format(unselected)",
"",
"",
"",
"",
"",
"logger",
".",
"warning",
"(",
"msg",
")",
"# 要提交的 kcdm 数据",
"kcdms_data",
"=",
"[",
"]",
"# 要提交的 jxbh 数据",
"jxbhs_data",
"=",
"[",
"]",
"# 必须添加已选课程, 同时去掉要删除的课程",
"for",
"course",
"in",
"selected_courses",
":",
"if",
"course",
"[",
"'课程代码'] not in",
" ",
"ele",
"e_",
"ourses:",
"",
"kcdms_data",
".",
"append",
"(",
"course",
"[",
"'课程代码'])",
"",
"",
"jxbhs_data",
".",
"append",
"(",
"course",
"[",
"'教学班号'])",
"",
"",
"# 选课",
"for",
"kv",
"in",
"select_courses",
":",
"kcdm",
"=",
"kv",
"[",
"'kcdm'",
"]",
".",
"upper",
"(",
")",
"jxbhs",
"=",
"set",
"(",
"kv",
"[",
"'jxbhs'",
"]",
")",
"if",
"kv",
".",
"get",
"(",
"'jxbhs'",
")",
"else",
"set",
"(",
")",
"teaching_classes",
"=",
"self",
".",
"get_course_classes",
"(",
"kcdm",
")",
"if",
"not",
"teaching_classes",
":",
"logger",
".",
"warning",
"(",
"'课程[%s]没有可选班级', kcdm)",
"",
"",
"",
"continue",
"# 反正是统一提交, 不需要判断是否已满",
"optional_jxbhs",
"=",
"{",
"c",
"[",
"'教学班号'] for c ",
"i",
" te",
"c",
"in",
"_classes['可选班级']",
"}",
"",
"",
"",
"if",
"jxbhs",
":",
"wrong_jxbhs",
"=",
"jxbhs",
".",
"difference",
"(",
"optional_jxbhs",
")",
"if",
"wrong_jxbhs",
":",
"msg",
"=",
"'课程[{}]{}没有教学班号{}'.format(kcdm, te",
"a",
"ching_",
"c",
"lass",
"e",
"['课程名称'], wrong_",
"j",
"xbhs)",
"",
"",
"",
"",
"logger",
".",
"warning",
"(",
"msg",
")",
"jxbhs",
"=",
"jxbhs",
".",
"intersection",
"(",
"optional_jxbhs",
")",
"else",
":",
"jxbhs",
"=",
"optional_jxbhs",
"for",
"jxbh",
"in",
"jxbhs",
":",
"kcdms_data",
".",
"append",
"(",
"kcdm",
")",
"jxbhs_data",
".",
"append",
"(",
"jxbh",
")",
"return",
"self",
".",
"query",
"(",
"ChangeCourse",
"(",
"self",
".",
"session",
".",
"account",
",",
"select_courses",
",",
"delete_courses",
")",
")"
] | 修改个人的课程
@structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}]
:param select_courses: 形如 ``[{'kcdm': '9900039X', 'jxbhs': {'0001', '0002'}}]`` 的课程代码与教学班号列表,
jxbhs 可以为空代表选择所有可选班级
:param delete_courses: 需要删除的课程代码集合, 如 ``{'0200011B'}``
:return: 选课结果, 返回选中的课程教学班列表, 结构与 ``get_selected_courses`` 一致 | [
"修改个人的课程"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L267-L333 |
earlzo/hfut | hfut/shortcut.py | Student.check_courses | def check_courses(self, kcdms):
"""
检查课程是否被选
@structure [bool]
:param kcdms: 课程代码列表
:return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False
"""
selected_courses = self.get_selected_courses()
selected_kcdms = {course['课程代码'] for course in selected_courses}
result = [True if kcdm in selected_kcdms else False for kcdm in kcdms]
return result | python | def check_courses(self, kcdms):
"""
检查课程是否被选
@structure [bool]
:param kcdms: 课程代码列表
:return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False
"""
selected_courses = self.get_selected_courses()
selected_kcdms = {course['课程代码'] for course in selected_courses}
result = [True if kcdm in selected_kcdms else False for kcdm in kcdms]
return result | [
"def",
"check_courses",
"(",
"self",
",",
"kcdms",
")",
":",
"selected_courses",
"=",
"self",
".",
"get_selected_courses",
"(",
")",
"selected_kcdms",
"=",
"{",
"course",
"[",
"'课程代码'] for co",
"u",
"se ",
"n sele",
"te",
"_courses}",
"",
"result",
"=",
"[",
"True",
"if",
"kcdm",
"in",
"selected_kcdms",
"else",
"False",
"for",
"kcdm",
"in",
"kcdms",
"]",
"return",
"result"
] | 检查课程是否被选
@structure [bool]
:param kcdms: 课程代码列表
:return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False | [
"检查课程是否被选"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L336-L348 |
earlzo/hfut | hfut/shortcut.py | Student.get_selectable_courses | def get_selectable_courses(self, kcdms=None, pool_size=5, dump_result=True, filename='可选课程.json', encoding='utf-8'):
"""
获取所有能够选上的课程的课程班级, 注意这个方法遍历所给出的课程和它们的可选班级, 当选中人数大于等于课程容量时表示不可选.
由于请求非常耗时且一般情况下用不到, 因此默认推荐在第一轮选课结束后到第三轮选课结束之前的时间段使用, 如果你仍然坚持使用, 你将会得到一个警告.
@structure [{'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int,
'教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}],
'课程代码': str, '课程名称': str}]
:param kcdms: 课程代码列表, 默认为所有可选课程的课程代码
:param dump_result: 是否保存结果到本地
:param filename: 保存的文件路径
:param encoding: 文件编码
"""
now = time.time()
t = self.get_system_status()
if not (t['选课计划'][0][1] < now < t['选课计划'][2][1]):
logger.warning('只推荐在第一轮选课结束到第三轮选课结束之间的时间段使用本接口!')
def iter_kcdms():
for l in self.get_optional_courses():
yield l['课程代码']
kcdms = kcdms or iter_kcdms()
def target(kcdm):
course_classes = self.get_course_classes(kcdm)
if not course_classes:
return
course_classes['可选班级'] = [c for c in course_classes['可选班级'] if c['课程容量'] > c['选中人数']]
if len(course_classes['可选班级']) > 0:
return course_classes
# Python 2.7 不支持 with 语法
pool = Pool(pool_size)
result = list(filter(None, pool.map(target, kcdms)))
pool.close()
pool.join()
if dump_result:
json_str = json.dumps(result, ensure_ascii=False, indent=4, sort_keys=True)
with open(filename, 'wb') as fp:
fp.write(json_str.encode(encoding))
logger.info('可选课程结果导出到了:%s', filename)
return result | python | def get_selectable_courses(self, kcdms=None, pool_size=5, dump_result=True, filename='可选课程.json', encoding='utf-8'):
"""
获取所有能够选上的课程的课程班级, 注意这个方法遍历所给出的课程和它们的可选班级, 当选中人数大于等于课程容量时表示不可选.
由于请求非常耗时且一般情况下用不到, 因此默认推荐在第一轮选课结束后到第三轮选课结束之前的时间段使用, 如果你仍然坚持使用, 你将会得到一个警告.
@structure [{'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int,
'教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}],
'课程代码': str, '课程名称': str}]
:param kcdms: 课程代码列表, 默认为所有可选课程的课程代码
:param dump_result: 是否保存结果到本地
:param filename: 保存的文件路径
:param encoding: 文件编码
"""
now = time.time()
t = self.get_system_status()
if not (t['选课计划'][0][1] < now < t['选课计划'][2][1]):
logger.warning('只推荐在第一轮选课结束到第三轮选课结束之间的时间段使用本接口!')
def iter_kcdms():
for l in self.get_optional_courses():
yield l['课程代码']
kcdms = kcdms or iter_kcdms()
def target(kcdm):
course_classes = self.get_course_classes(kcdm)
if not course_classes:
return
course_classes['可选班级'] = [c for c in course_classes['可选班级'] if c['课程容量'] > c['选中人数']]
if len(course_classes['可选班级']) > 0:
return course_classes
# Python 2.7 不支持 with 语法
pool = Pool(pool_size)
result = list(filter(None, pool.map(target, kcdms)))
pool.close()
pool.join()
if dump_result:
json_str = json.dumps(result, ensure_ascii=False, indent=4, sort_keys=True)
with open(filename, 'wb') as fp:
fp.write(json_str.encode(encoding))
logger.info('可选课程结果导出到了:%s', filename)
return result | [
"def",
"get_selectable_courses",
"(",
"self",
",",
"kcdms",
"=",
"None",
",",
"pool_size",
"=",
"5",
",",
"dump_result",
"=",
"True",
",",
"filename",
"=",
"'可选课程.json', encodi",
"n",
"='utf-8'",
")",
":",
"",
"",
"now",
"=",
"time",
".",
"time",
"(",
")",
"t",
"=",
"self",
".",
"get_system_status",
"(",
")",
"if",
"not",
"(",
"t",
"[",
"'选课计划'][0][1] ",
"<",
" ",
"n",
"o",
"w",
" ",
"<",
"t",
"'选课",
"划",
"]",
"[",
"2][1]):",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"logger",
".",
"warning",
"(",
"'只推荐在第一轮选课结束到第三轮选课结束之间的时间段使用本接口!')",
"",
"def",
"iter_kcdms",
"(",
")",
":",
"for",
"l",
"in",
"self",
".",
"get_optional_courses",
"(",
")",
":",
"yield",
"l",
"[",
"'课程代码']",
"",
"kcdms",
"=",
"kcdms",
"or",
"iter_kcdms",
"(",
")",
"def",
"target",
"(",
"kcdm",
")",
":",
"course_classes",
"=",
"self",
".",
"get_course_classes",
"(",
"kcdm",
")",
"if",
"not",
"course_classes",
":",
"return",
"course_classes",
"[",
"'可选班级'] = [c f",
"o",
" ",
" ",
"i",
" co",
"r",
"e_",
"lasses['可选班级']",
" ",
"if c['课程容量'] >",
" ",
"['",
"中",
"人",
"数']]",
"",
"",
"",
"",
"",
"",
"",
"if",
"len",
"(",
"course_classes",
"[",
"'可选班级']) > 0:",
"",
"",
"",
"",
"",
"return",
"course_classes",
"# Python 2.7 不支持 with 语法",
"pool",
"=",
"Pool",
"(",
"pool_size",
")",
"result",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"pool",
".",
"map",
"(",
"target",
",",
"kcdms",
")",
")",
")",
"pool",
".",
"close",
"(",
")",
"pool",
".",
"join",
"(",
")",
"if",
"dump_result",
":",
"json_str",
"=",
"json",
".",
"dumps",
"(",
"result",
",",
"ensure_ascii",
"=",
"False",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"json_str",
".",
"encode",
"(",
"encoding",
")",
")",
"logger",
".",
"info",
"(",
"'可选课程结果导出到了:%s', filename)",
"",
"",
"",
"return",
"result"
] | 获取所有能够选上的课程的课程班级, 注意这个方法遍历所给出的课程和它们的可选班级, 当选中人数大于等于课程容量时表示不可选.
由于请求非常耗时且一般情况下用不到, 因此默认推荐在第一轮选课结束后到第三轮选课结束之前的时间段使用, 如果你仍然坚持使用, 你将会得到一个警告.
@structure [{'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int,
'教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}],
'课程代码': str, '课程名称': str}]
:param kcdms: 课程代码列表, 默认为所有可选课程的课程代码
:param dump_result: 是否保存结果到本地
:param filename: 保存的文件路径
:param encoding: 文件编码 | [
"获取所有能够选上的课程的课程班级",
"注意这个方法遍历所给出的课程和它们的可选班级",
"当选中人数大于等于课程容量时表示不可选",
"."
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L350-L395 |
earlzo/hfut | hfut/session.py | BaseSession.send | def send(self, request, **kwargs):
"""
所有接口用来发送请求的方法, 只是 :meth:`requests.sessions.Session.send` 的一个钩子方法, 用来处理请求前后的工作
"""
response = super(BaseSession, self).send(request, **kwargs)
if ENV['RAISE_FOR_STATUS']:
response.raise_for_status()
parsed = parse.urlparse(response.url)
if parsed.netloc == parse.urlparse(self.host).netloc:
response.encoding = ENV['SITE_ENCODING']
# 快速判断响应 IP 是否被封, 那个警告响应内容长度为 327 或 328, 保留一点余量确保准确
min_length, max_length, pattern = ENV['IP_BANNED_RESPONSE']
if min_length <= len(response.content) <= max_length and pattern.search(response.text):
msg = '当前 IP 已被锁定, 如果可以请尝试切换教务系统地址, 否则请在更换网络环境或等待解封后重试!'
raise IPBanned(msg)
self.histories.append(response)
logger.debug(report_response(response, redirection=kwargs.get('allow_redirects')))
return response | python | def send(self, request, **kwargs):
"""
所有接口用来发送请求的方法, 只是 :meth:`requests.sessions.Session.send` 的一个钩子方法, 用来处理请求前后的工作
"""
response = super(BaseSession, self).send(request, **kwargs)
if ENV['RAISE_FOR_STATUS']:
response.raise_for_status()
parsed = parse.urlparse(response.url)
if parsed.netloc == parse.urlparse(self.host).netloc:
response.encoding = ENV['SITE_ENCODING']
# 快速判断响应 IP 是否被封, 那个警告响应内容长度为 327 或 328, 保留一点余量确保准确
min_length, max_length, pattern = ENV['IP_BANNED_RESPONSE']
if min_length <= len(response.content) <= max_length and pattern.search(response.text):
msg = '当前 IP 已被锁定, 如果可以请尝试切换教务系统地址, 否则请在更换网络环境或等待解封后重试!'
raise IPBanned(msg)
self.histories.append(response)
logger.debug(report_response(response, redirection=kwargs.get('allow_redirects')))
return response | [
"def",
"send",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"super",
"(",
"BaseSession",
",",
"self",
")",
".",
"send",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
"if",
"ENV",
"[",
"'RAISE_FOR_STATUS'",
"]",
":",
"response",
".",
"raise_for_status",
"(",
")",
"parsed",
"=",
"parse",
".",
"urlparse",
"(",
"response",
".",
"url",
")",
"if",
"parsed",
".",
"netloc",
"==",
"parse",
".",
"urlparse",
"(",
"self",
".",
"host",
")",
".",
"netloc",
":",
"response",
".",
"encoding",
"=",
"ENV",
"[",
"'SITE_ENCODING'",
"]",
"# 快速判断响应 IP 是否被封, 那个警告响应内容长度为 327 或 328, 保留一点余量确保准确",
"min_length",
",",
"max_length",
",",
"pattern",
"=",
"ENV",
"[",
"'IP_BANNED_RESPONSE'",
"]",
"if",
"min_length",
"<=",
"len",
"(",
"response",
".",
"content",
")",
"<=",
"max_length",
"and",
"pattern",
".",
"search",
"(",
"response",
".",
"text",
")",
":",
"msg",
"=",
"'当前 IP 已被锁定, 如果可以请尝试切换教务系统地址, 否则请在更换网络环境或等待解封后重试!'",
"raise",
"IPBanned",
"(",
"msg",
")",
"self",
".",
"histories",
".",
"append",
"(",
"response",
")",
"logger",
".",
"debug",
"(",
"report_response",
"(",
"response",
",",
"redirection",
"=",
"kwargs",
".",
"get",
"(",
"'allow_redirects'",
")",
")",
")",
"return",
"response"
] | 所有接口用来发送请求的方法, 只是 :meth:`requests.sessions.Session.send` 的一个钩子方法, 用来处理请求前后的工作 | [
"所有接口用来发送请求的方法",
"只是",
":",
"meth",
":",
"requests",
".",
"sessions",
".",
"Session",
".",
"send",
"的一个钩子方法",
"用来处理请求前后的工作"
] | train | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/session.py#L56-L75 |
duguyue100/minesweeper | minesweeper/msboard.py | MSBoard.init_board | def init_board(self):
"""Init a valid board by given settings.
Parameters
----------
mine_map : numpy.ndarray
the map that defines the mine
0 is empty, 1 is mine
info_map : numpy.ndarray
the map that presents to gamer
0-8 is number of mines in srrounding.
9 is flagged field.
10 is questioned field.
11 is undiscovered field.
12 is a mine field.
"""
self.mine_map = np.zeros((self.board_height, self.board_width),
dtype=np.uint8)
idx_list = np.random.permutation(self.board_width*self.board_height)
idx_list = idx_list[:self.num_mines]
for idx in idx_list:
idx_x = int(idx % self.board_width)
idx_y = int(idx / self.board_width)
self.mine_map[idx_y, idx_x] = 1
self.info_map = np.ones((self.board_height, self.board_width),
dtype=np.uint8)*11 | python | def init_board(self):
"""Init a valid board by given settings.
Parameters
----------
mine_map : numpy.ndarray
the map that defines the mine
0 is empty, 1 is mine
info_map : numpy.ndarray
the map that presents to gamer
0-8 is number of mines in srrounding.
9 is flagged field.
10 is questioned field.
11 is undiscovered field.
12 is a mine field.
"""
self.mine_map = np.zeros((self.board_height, self.board_width),
dtype=np.uint8)
idx_list = np.random.permutation(self.board_width*self.board_height)
idx_list = idx_list[:self.num_mines]
for idx in idx_list:
idx_x = int(idx % self.board_width)
idx_y = int(idx / self.board_width)
self.mine_map[idx_y, idx_x] = 1
self.info_map = np.ones((self.board_height, self.board_width),
dtype=np.uint8)*11 | [
"def",
"init_board",
"(",
"self",
")",
":",
"self",
".",
"mine_map",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"board_height",
",",
"self",
".",
"board_width",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"idx_list",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"self",
".",
"board_width",
"*",
"self",
".",
"board_height",
")",
"idx_list",
"=",
"idx_list",
"[",
":",
"self",
".",
"num_mines",
"]",
"for",
"idx",
"in",
"idx_list",
":",
"idx_x",
"=",
"int",
"(",
"idx",
"%",
"self",
".",
"board_width",
")",
"idx_y",
"=",
"int",
"(",
"idx",
"/",
"self",
".",
"board_width",
")",
"self",
".",
"mine_map",
"[",
"idx_y",
",",
"idx_x",
"]",
"=",
"1",
"self",
".",
"info_map",
"=",
"np",
".",
"ones",
"(",
"(",
"self",
".",
"board_height",
",",
"self",
".",
"board_width",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"*",
"11"
] | Init a valid board by given settings.
Parameters
----------
mine_map : numpy.ndarray
the map that defines the mine
0 is empty, 1 is mine
info_map : numpy.ndarray
the map that presents to gamer
0-8 is number of mines in srrounding.
9 is flagged field.
10 is questioned field.
11 is undiscovered field.
12 is a mine field. | [
"Init",
"a",
"valid",
"board",
"by",
"given",
"settings",
"."
] | train | https://github.com/duguyue100/minesweeper/blob/38b1910f4c34d0275ac10a300285aba6f1d91d61/minesweeper/msboard.py#L46-L74 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.