repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
robotframework/Rammbock
src/Rammbock/core.py
RammbockCore.new_binary_container
def new_binary_container(self, name): """Defines a new binary container to template. Binary container can only contain binary fields defined with `Bin` keyword. Examples: | New binary container | flags | | bin | 2 | foo | | bin | 6 | bar | | End binary container | """ self._message_stack.append(BinaryContainerTemplate(name, self._current_container))
python
def new_binary_container(self, name): """Defines a new binary container to template. Binary container can only contain binary fields defined with `Bin` keyword. Examples: | New binary container | flags | | bin | 2 | foo | | bin | 6 | bar | | End binary container | """ self._message_stack.append(BinaryContainerTemplate(name, self._current_container))
[ "def", "new_binary_container", "(", "self", ",", "name", ")", ":", "self", ".", "_message_stack", ".", "append", "(", "BinaryContainerTemplate", "(", "name", ",", "self", ".", "_current_container", ")", ")" ]
Defines a new binary container to template. Binary container can only contain binary fields defined with `Bin` keyword. Examples: | New binary container | flags | | bin | 2 | foo | | bin | 6 | bar | | End binary container |
[ "Defines", "a", "new", "binary", "container", "to", "template", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/core.py#L784-L796
train
36,700
robotframework/Rammbock
src/Rammbock/core.py
RammbockCore.end_binary_container
def end_binary_container(self): """End binary container. See `New Binary Container`. """ binary_container = self._message_stack.pop() binary_container.verify() self._add_field(binary_container)
python
def end_binary_container(self): """End binary container. See `New Binary Container`. """ binary_container = self._message_stack.pop() binary_container.verify() self._add_field(binary_container)
[ "def", "end_binary_container", "(", "self", ")", ":", "binary_container", "=", "self", ".", "_message_stack", ".", "pop", "(", ")", "binary_container", ".", "verify", "(", ")", "self", ".", "_add_field", "(", "binary_container", ")" ]
End binary container. See `New Binary Container`.
[ "End", "binary", "container", ".", "See", "New", "Binary", "Container", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/core.py#L801-L806
train
36,701
robotframework/Rammbock
src/Rammbock/core.py
RammbockCore.bin
def bin(self, size, name, value=None): """Add new binary field to template. This keyword has to be called within a binary container. See `New Binary Container`. """ self._add_field(Binary(size, name, value))
python
def bin(self, size, name, value=None): """Add new binary field to template. This keyword has to be called within a binary container. See `New Binary Container`. """ self._add_field(Binary(size, name, value))
[ "def", "bin", "(", "self", ",", "size", ",", "name", ",", "value", "=", "None", ")", ":", "self", ".", "_add_field", "(", "Binary", "(", "size", ",", "name", ",", "value", ")", ")" ]
Add new binary field to template. This keyword has to be called within a binary container. See `New Binary Container`.
[ "Add", "new", "binary", "field", "to", "template", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/core.py#L812-L818
train
36,702
robotframework/Rammbock
src/Rammbock/core.py
RammbockCore.new_union
def new_union(self, type, name): """Defines a new union to template of `type` and `name`. Fields inside the union are alternatives and the length of the union is the length of its longest field. Example: | New union | IntOrAddress | foo | | Chars | 16 | ipAddress | | u32 | int | | End union | """ self._message_stack.append(UnionTemplate(type, name, self._current_container))
python
def new_union(self, type, name): """Defines a new union to template of `type` and `name`. Fields inside the union are alternatives and the length of the union is the length of its longest field. Example: | New union | IntOrAddress | foo | | Chars | 16 | ipAddress | | u32 | int | | End union | """ self._message_stack.append(UnionTemplate(type, name, self._current_container))
[ "def", "new_union", "(", "self", ",", "type", ",", "name", ")", ":", "self", ".", "_message_stack", ".", "append", "(", "UnionTemplate", "(", "type", ",", "name", ",", "self", ".", "_current_container", ")", ")" ]
Defines a new union to template of `type` and `name`. Fields inside the union are alternatives and the length of the union is the length of its longest field. Example: | New union | IntOrAddress | foo | | Chars | 16 | ipAddress | | u32 | int | | End union |
[ "Defines", "a", "new", "union", "to", "template", "of", "type", "and", "name", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/core.py#L823-L835
train
36,703
robotframework/Rammbock
src/Rammbock/core.py
RammbockCore.start_bag
def start_bag(self, name): """Bags are sets of optional elements with an optional count. The optional elements are given each as a `Case` with the accepted count as first argument. The received elements are matched from the list of cases in order. If the the received value does not validate against the case (for example a value of a field does not match expected), then the next case is tried until a match is found. Note that although the received elements are matched in order that the cases are given, the elements dont need to arrive in the same order as the cases are. This example would match int value 42 0-1 times and in value 1 0-2 times. For example 1, 42, 1 would match, as would 1, 1: | Start bag | intBag | | case | 0-1 | u8 | foo | 42 | | case | 0-2 | u8 | bar | 1 | | End bag | A more real world example, where each AVP entry has a type field with a value that is used for matching: | Start bag | avps | | Case | 1 | AVP | result | Result-Code | | Case | 1 | AVP | originHost | Origin-Host | | Case | 1 | AVP | originRealm | Origin-Realm | | Case | 1 | AVP | hostIP | Host-IP-Address | | Case | * | AVP | appId | Vendor-Specific-Application-Id | | Case | 0-1 | AVP | originState | Origin-State | | End bag | For a more complete example on bags, see the [https://github.com/robotframework/Rammbock/blob/master/atest/diameter.robot|diameter.robot] file from Rammbock's acceptance tests. """ self._message_stack.append(BagTemplate(name, self._current_container))
python
def start_bag(self, name): """Bags are sets of optional elements with an optional count. The optional elements are given each as a `Case` with the accepted count as first argument. The received elements are matched from the list of cases in order. If the the received value does not validate against the case (for example a value of a field does not match expected), then the next case is tried until a match is found. Note that although the received elements are matched in order that the cases are given, the elements dont need to arrive in the same order as the cases are. This example would match int value 42 0-1 times and in value 1 0-2 times. For example 1, 42, 1 would match, as would 1, 1: | Start bag | intBag | | case | 0-1 | u8 | foo | 42 | | case | 0-2 | u8 | bar | 1 | | End bag | A more real world example, where each AVP entry has a type field with a value that is used for matching: | Start bag | avps | | Case | 1 | AVP | result | Result-Code | | Case | 1 | AVP | originHost | Origin-Host | | Case | 1 | AVP | originRealm | Origin-Realm | | Case | 1 | AVP | hostIP | Host-IP-Address | | Case | * | AVP | appId | Vendor-Specific-Application-Id | | Case | 0-1 | AVP | originState | Origin-State | | End bag | For a more complete example on bags, see the [https://github.com/robotframework/Rammbock/blob/master/atest/diameter.robot|diameter.robot] file from Rammbock's acceptance tests. """ self._message_stack.append(BagTemplate(name, self._current_container))
[ "def", "start_bag", "(", "self", ",", "name", ")", ":", "self", ".", "_message_stack", ".", "append", "(", "BagTemplate", "(", "name", ",", "self", ".", "_current_container", ")", ")" ]
Bags are sets of optional elements with an optional count. The optional elements are given each as a `Case` with the accepted count as first argument. The received elements are matched from the list of cases in order. If the the received value does not validate against the case (for example a value of a field does not match expected), then the next case is tried until a match is found. Note that although the received elements are matched in order that the cases are given, the elements dont need to arrive in the same order as the cases are. This example would match int value 42 0-1 times and in value 1 0-2 times. For example 1, 42, 1 would match, as would 1, 1: | Start bag | intBag | | case | 0-1 | u8 | foo | 42 | | case | 0-2 | u8 | bar | 1 | | End bag | A more real world example, where each AVP entry has a type field with a value that is used for matching: | Start bag | avps | | Case | 1 | AVP | result | Result-Code | | Case | 1 | AVP | originHost | Origin-Host | | Case | 1 | AVP | originRealm | Origin-Realm | | Case | 1 | AVP | hostIP | Host-IP-Address | | Case | * | AVP | appId | Vendor-Specific-Application-Id | | Case | 0-1 | AVP | originState | Origin-State | | End bag | For a more complete example on bags, see the [https://github.com/robotframework/Rammbock/blob/master/atest/diameter.robot|diameter.robot] file from Rammbock's acceptance tests.
[ "Bags", "are", "sets", "of", "optional", "elements", "with", "an", "optional", "count", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/core.py#L843-L878
train
36,704
robotframework/Rammbock
src/Rammbock/core.py
RammbockCore.value
def value(self, name, value): """Defines a default `value` for a template field identified by `name`. Default values for header fields can be set with header:field syntax. Examples: | Value | foo | 42 | | Value | struct.sub_field | 0xcafe | | Value | header:version | 0x02 | """ if isinstance(value, _StructuredElement): self._struct_fields_as_values(name, value) elif name.startswith('header:'): self._header_values[name.partition(':')[-1]] = value else: self._field_values[name] = value
python
def value(self, name, value): """Defines a default `value` for a template field identified by `name`. Default values for header fields can be set with header:field syntax. Examples: | Value | foo | 42 | | Value | struct.sub_field | 0xcafe | | Value | header:version | 0x02 | """ if isinstance(value, _StructuredElement): self._struct_fields_as_values(name, value) elif name.startswith('header:'): self._header_values[name.partition(':')[-1]] = value else: self._field_values[name] = value
[ "def", "value", "(", "self", ",", "name", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "_StructuredElement", ")", ":", "self", ".", "_struct_fields_as_values", "(", "name", ",", "value", ")", "elif", "name", ".", "startswith", "(", "'he...
Defines a default `value` for a template field identified by `name`. Default values for header fields can be set with header:field syntax. Examples: | Value | foo | 42 | | Value | struct.sub_field | 0xcafe | | Value | header:version | 0x02 |
[ "Defines", "a", "default", "value", "for", "a", "template", "field", "identified", "by", "name", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/core.py#L935-L950
train
36,705
robotframework/Rammbock
src/Rammbock/core.py
RammbockCore.conditional
def conditional(self, condition, name): """Defines a 'condition' when conditional element of 'name' exists if `condition` is true. `condition` can contain multiple conditions combined together using Logical Expressions(&&,||). Example: | Conditional | mycondition == 1 | foo | | u8 | myelement | 42 | | End conditional | | Conditional | condition1 == 1 && condition2 != 2 | bar | | u8 | myelement | 8 | | End condtional | """ self._message_stack.append(ConditionalTemplate(condition, name, self._current_container))
python
def conditional(self, condition, name): """Defines a 'condition' when conditional element of 'name' exists if `condition` is true. `condition` can contain multiple conditions combined together using Logical Expressions(&&,||). Example: | Conditional | mycondition == 1 | foo | | u8 | myelement | 42 | | End conditional | | Conditional | condition1 == 1 && condition2 != 2 | bar | | u8 | myelement | 8 | | End condtional | """ self._message_stack.append(ConditionalTemplate(condition, name, self._current_container))
[ "def", "conditional", "(", "self", ",", "condition", ",", "name", ")", ":", "self", ".", "_message_stack", ".", "append", "(", "ConditionalTemplate", "(", "condition", ",", "name", ",", "self", ".", "_current_container", ")", ")" ]
Defines a 'condition' when conditional element of 'name' exists if `condition` is true. `condition` can contain multiple conditions combined together using Logical Expressions(&&,||). Example: | Conditional | mycondition == 1 | foo | | u8 | myelement | 42 | | End conditional | | Conditional | condition1 == 1 && condition2 != 2 | bar | | u8 | myelement | 8 | | End condtional |
[ "Defines", "a", "condition", "when", "conditional", "element", "of", "name", "exists", "if", "condition", "is", "true", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/core.py#L999-L1013
train
36,706
robotframework/Rammbock
src/Rammbock/core.py
RammbockCore.get_client_unread_messages_count
def get_client_unread_messages_count(self, client_name=None): """Gets count of unread messages from client """ client = self._clients.get_with_name(client_name)[0] return client.get_messages_count_in_buffer()
python
def get_client_unread_messages_count(self, client_name=None): """Gets count of unread messages from client """ client = self._clients.get_with_name(client_name)[0] return client.get_messages_count_in_buffer()
[ "def", "get_client_unread_messages_count", "(", "self", ",", "client_name", "=", "None", ")", ":", "client", "=", "self", ".", "_clients", ".", "get_with_name", "(", "client_name", ")", "[", "0", "]", "return", "client", ".", "get_messages_count_in_buffer", "(",...
Gets count of unread messages from client
[ "Gets", "count", "of", "unread", "messages", "from", "client" ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/core.py#L1021-L1025
train
36,707
robotframework/Rammbock
src/Rammbock/core.py
RammbockCore.get_server_unread_messages_count
def get_server_unread_messages_count(self, server_name=None): """Gets count of unread messages from server """ server = self._servers.get(server_name) return server.get_messages_count_in_buffer()
python
def get_server_unread_messages_count(self, server_name=None): """Gets count of unread messages from server """ server = self._servers.get(server_name) return server.get_messages_count_in_buffer()
[ "def", "get_server_unread_messages_count", "(", "self", ",", "server_name", "=", "None", ")", ":", "server", "=", "self", ".", "_servers", ".", "get", "(", "server_name", ")", "return", "server", ".", "get_messages_count_in_buffer", "(", ")" ]
Gets count of unread messages from server
[ "Gets", "count", "of", "unread", "messages", "from", "server" ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/core.py#L1027-L1031
train
36,708
robotframework/Rammbock
src/Rammbock/binary_tools.py
to_twos_comp
def to_twos_comp(val, bits): """compute the 2's compliment of int value val""" if not val.startswith('-'): return to_int(val) value = _invert(to_bin_str_from_int_string(bits, bin(to_int(val[1:])))) return int(value, 2) + 1
python
def to_twos_comp(val, bits): """compute the 2's compliment of int value val""" if not val.startswith('-'): return to_int(val) value = _invert(to_bin_str_from_int_string(bits, bin(to_int(val[1:])))) return int(value, 2) + 1
[ "def", "to_twos_comp", "(", "val", ",", "bits", ")", ":", "if", "not", "val", ".", "startswith", "(", "'-'", ")", ":", "return", "to_int", "(", "val", ")", "value", "=", "_invert", "(", "to_bin_str_from_int_string", "(", "bits", ",", "bin", "(", "to_in...
compute the 2's compliment of int value val
[ "compute", "the", "2", "s", "compliment", "of", "int", "value", "val" ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/binary_tools.py#L119-L124
train
36,709
robotframework/Rammbock
src/Rammbock/rammbock.py
Rammbock.u8
def u8(self, name, value=None, align=None): """Add an unsigned 1 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(1, name, value, align)
python
def u8(self, name, value=None, align=None): """Add an unsigned 1 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(1, name, value, align)
[ "def", "u8", "(", "self", ",", "name", ",", "value", "=", "None", ",", "align", "=", "None", ")", ":", "self", ".", "uint", "(", "1", ",", "name", ",", "value", ",", "align", ")" ]
Add an unsigned 1 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
[ "Add", "an", "unsigned", "1", "byte", "integer", "field", "to", "template", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/rammbock.py#L68-L72
train
36,710
robotframework/Rammbock
src/Rammbock/rammbock.py
Rammbock.u16
def u16(self, name, value=None, align=None): """Add an unsigned 2 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(2, name, value, align)
python
def u16(self, name, value=None, align=None): """Add an unsigned 2 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(2, name, value, align)
[ "def", "u16", "(", "self", ",", "name", ",", "value", "=", "None", ",", "align", "=", "None", ")", ":", "self", ".", "uint", "(", "2", ",", "name", ",", "value", ",", "align", ")" ]
Add an unsigned 2 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
[ "Add", "an", "unsigned", "2", "byte", "integer", "field", "to", "template", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/rammbock.py#L74-L78
train
36,711
robotframework/Rammbock
src/Rammbock/rammbock.py
Rammbock.u24
def u24(self, name, value=None, align=None): """Add an unsigned 3 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(3, name, value, align)
python
def u24(self, name, value=None, align=None): """Add an unsigned 3 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(3, name, value, align)
[ "def", "u24", "(", "self", ",", "name", ",", "value", "=", "None", ",", "align", "=", "None", ")", ":", "self", ".", "uint", "(", "3", ",", "name", ",", "value", ",", "align", ")" ]
Add an unsigned 3 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
[ "Add", "an", "unsigned", "3", "byte", "integer", "field", "to", "template", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/rammbock.py#L80-L84
train
36,712
robotframework/Rammbock
src/Rammbock/rammbock.py
Rammbock.u32
def u32(self, name, value=None, align=None): """Add an unsigned 4 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(4, name, value, align)
python
def u32(self, name, value=None, align=None): """Add an unsigned 4 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(4, name, value, align)
[ "def", "u32", "(", "self", ",", "name", ",", "value", "=", "None", ",", "align", "=", "None", ")", ":", "self", ".", "uint", "(", "4", ",", "name", ",", "value", ",", "align", ")" ]
Add an unsigned 4 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
[ "Add", "an", "unsigned", "4", "byte", "integer", "field", "to", "template", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/rammbock.py#L86-L90
train
36,713
robotframework/Rammbock
src/Rammbock/rammbock.py
Rammbock.u40
def u40(self, name, value=None, align=None): """Add an unsigned 5 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(5, name, value, align)
python
def u40(self, name, value=None, align=None): """Add an unsigned 5 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(5, name, value, align)
[ "def", "u40", "(", "self", ",", "name", ",", "value", "=", "None", ",", "align", "=", "None", ")", ":", "self", ".", "uint", "(", "5", ",", "name", ",", "value", ",", "align", ")" ]
Add an unsigned 5 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
[ "Add", "an", "unsigned", "5", "byte", "integer", "field", "to", "template", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/rammbock.py#L92-L96
train
36,714
robotframework/Rammbock
src/Rammbock/rammbock.py
Rammbock.u64
def u64(self, name, value=None, align=None): """Add an unsigned 8 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(8, name, value, align)
python
def u64(self, name, value=None, align=None): """Add an unsigned 8 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(8, name, value, align)
[ "def", "u64", "(", "self", ",", "name", ",", "value", "=", "None", ",", "align", "=", "None", ")", ":", "self", ".", "uint", "(", "8", ",", "name", ",", "value", ",", "align", ")" ]
Add an unsigned 8 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
[ "Add", "an", "unsigned", "8", "byte", "integer", "field", "to", "template", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/rammbock.py#L98-L102
train
36,715
robotframework/Rammbock
src/Rammbock/rammbock.py
Rammbock.u128
def u128(self, name, value=None, align=None): """Add an unsigned 16 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(16, name, value, align)
python
def u128(self, name, value=None, align=None): """Add an unsigned 16 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(16, name, value, align)
[ "def", "u128", "(", "self", ",", "name", ",", "value", "=", "None", ",", "align", "=", "None", ")", ":", "self", ".", "uint", "(", "16", ",", "name", ",", "value", ",", "align", ")" ]
Add an unsigned 16 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
[ "Add", "an", "unsigned", "16", "byte", "integer", "field", "to", "template", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/rammbock.py#L104-L108
train
36,716
robotframework/Rammbock
src/Rammbock/rammbock.py
Rammbock.i8
def i8(self, name, value=None, align=None): """Add an 1 byte integer field to template. This is an convenience method that simply calls `Int` keyword with predefined length.""" self.int(1, name, value, align)
python
def i8(self, name, value=None, align=None): """Add an 1 byte integer field to template. This is an convenience method that simply calls `Int` keyword with predefined length.""" self.int(1, name, value, align)
[ "def", "i8", "(", "self", ",", "name", ",", "value", "=", "None", ",", "align", "=", "None", ")", ":", "self", ".", "int", "(", "1", ",", "name", ",", "value", ",", "align", ")" ]
Add an 1 byte integer field to template. This is an convenience method that simply calls `Int` keyword with predefined length.
[ "Add", "an", "1", "byte", "integer", "field", "to", "template", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/rammbock.py#L110-L114
train
36,717
robotframework/Rammbock
src/Rammbock/rammbock.py
Rammbock.i32
def i32(self, name, value=None, align=None): """Add an 32 byte integer field to template. This is an convenience method that simply calls `Int` keyword with predefined length.""" self.int(4, name, value, align)
python
def i32(self, name, value=None, align=None): """Add an 32 byte integer field to template. This is an convenience method that simply calls `Int` keyword with predefined length.""" self.int(4, name, value, align)
[ "def", "i32", "(", "self", ",", "name", ",", "value", "=", "None", ",", "align", "=", "None", ")", ":", "self", ".", "int", "(", "4", ",", "name", ",", "value", ",", "align", ")" ]
Add an 32 byte integer field to template. This is an convenience method that simply calls `Int` keyword with predefined length.
[ "Add", "an", "32", "byte", "integer", "field", "to", "template", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/rammbock.py#L116-L120
train
36,718
robotframework/Rammbock
src/Rammbock/rammbock.py
Rammbock.array
def array(self, size, type, name, *parameters): """Define a new array of given `size` and containing fields of type `type`. `name` if the name of this array element. The `type` is the name of keyword that is executed as the contents of the array and optional extra parameters are passed as arguments to this keyword. Examples: | Array | 8 | u16 | myArray | | u32 | length | | Array | length | someStruct | myArray | <argument for someStruct> | """ self._new_list(size, name) BuiltIn().run_keyword(type, '', *parameters) self._end_list()
python
def array(self, size, type, name, *parameters): """Define a new array of given `size` and containing fields of type `type`. `name` if the name of this array element. The `type` is the name of keyword that is executed as the contents of the array and optional extra parameters are passed as arguments to this keyword. Examples: | Array | 8 | u16 | myArray | | u32 | length | | Array | length | someStruct | myArray | <argument for someStruct> | """ self._new_list(size, name) BuiltIn().run_keyword(type, '', *parameters) self._end_list()
[ "def", "array", "(", "self", ",", "size", ",", "type", ",", "name", ",", "*", "parameters", ")", ":", "self", ".", "_new_list", "(", "size", ",", "name", ")", "BuiltIn", "(", ")", ".", "run_keyword", "(", "type", ",", "''", ",", "*", "parameters", ...
Define a new array of given `size` and containing fields of type `type`. `name` if the name of this array element. The `type` is the name of keyword that is executed as the contents of the array and optional extra parameters are passed as arguments to this keyword. Examples: | Array | 8 | u16 | myArray | | u32 | length | | Array | length | someStruct | myArray | <argument for someStruct> |
[ "Define", "a", "new", "array", "of", "given", "size", "and", "containing", "fields", "of", "type", "type", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/rammbock.py#L122-L136
train
36,719
robotframework/Rammbock
src/Rammbock/rammbock.py
Rammbock.container
def container(self, name, length, type, *parameters): """Define a container with given length. This is a convenience method creating a `Struct` with `length` containing fields defined in `type`. """ self.new_struct('Container', name, 'length=%s' % length) BuiltIn().run_keyword(type, *parameters) self.end_struct()
python
def container(self, name, length, type, *parameters): """Define a container with given length. This is a convenience method creating a `Struct` with `length` containing fields defined in `type`. """ self.new_struct('Container', name, 'length=%s' % length) BuiltIn().run_keyword(type, *parameters) self.end_struct()
[ "def", "container", "(", "self", ",", "name", ",", "length", ",", "type", ",", "*", "parameters", ")", ":", "self", ".", "new_struct", "(", "'Container'", ",", "name", ",", "'length=%s'", "%", "length", ")", "BuiltIn", "(", ")", ".", "run_keyword", "("...
Define a container with given length. This is a convenience method creating a `Struct` with `length` containing fields defined in `type`.
[ "Define", "a", "container", "with", "given", "length", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/rammbock.py#L138-L145
train
36,720
robotframework/Rammbock
src/Rammbock/rammbock.py
Rammbock.case
def case(self, size, kw, *parameters): """An element inside a bag started with `Start Bag`. The first argument is size which can be absolute value like `1`, a range like `0-3`, or just `*` to accept any number of elements. Examples: | Start bag | intBag | | case | 0-1 | u8 | foo | 42 | | case | 0-2 | u8 | bar | 1 | | End bag | """ # TODO: check we are inside a bag! self._start_bag_case(size) BuiltIn().run_keyword(kw, *parameters) self._end_bag_case()
python
def case(self, size, kw, *parameters): """An element inside a bag started with `Start Bag`. The first argument is size which can be absolute value like `1`, a range like `0-3`, or just `*` to accept any number of elements. Examples: | Start bag | intBag | | case | 0-1 | u8 | foo | 42 | | case | 0-2 | u8 | bar | 1 | | End bag | """ # TODO: check we are inside a bag! self._start_bag_case(size) BuiltIn().run_keyword(kw, *parameters) self._end_bag_case()
[ "def", "case", "(", "self", ",", "size", ",", "kw", ",", "*", "parameters", ")", ":", "# TODO: check we are inside a bag!", "self", ".", "_start_bag_case", "(", "size", ")", "BuiltIn", "(", ")", ".", "run_keyword", "(", "kw", ",", "*", "parameters", ")", ...
An element inside a bag started with `Start Bag`. The first argument is size which can be absolute value like `1`, a range like `0-3`, or just `*` to accept any number of elements. Examples: | Start bag | intBag | | case | 0-1 | u8 | foo | 42 | | case | 0-2 | u8 | bar | 1 | | End bag |
[ "An", "element", "inside", "a", "bag", "started", "with", "Start", "Bag", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/rammbock.py#L147-L162
train
36,721
robotframework/Rammbock
src/Rammbock/rammbock.py
Rammbock.embed_seqdiag_sequence
def embed_seqdiag_sequence(self): """Create a message sequence diagram png file to output folder and embed the image to log file. You need to have seqdiag installed to create the sequence diagram. See http://blockdiag.com/en/seqdiag/ """ test_name = BuiltIn().replace_variables('${TEST NAME}') outputdir = BuiltIn().replace_variables('${OUTPUTDIR}') path = os.path.join(outputdir, test_name + '.seqdiag') SeqdiagGenerator().compile(path, self._message_sequence)
python
def embed_seqdiag_sequence(self): """Create a message sequence diagram png file to output folder and embed the image to log file. You need to have seqdiag installed to create the sequence diagram. See http://blockdiag.com/en/seqdiag/ """ test_name = BuiltIn().replace_variables('${TEST NAME}') outputdir = BuiltIn().replace_variables('${OUTPUTDIR}') path = os.path.join(outputdir, test_name + '.seqdiag') SeqdiagGenerator().compile(path, self._message_sequence)
[ "def", "embed_seqdiag_sequence", "(", "self", ")", ":", "test_name", "=", "BuiltIn", "(", ")", ".", "replace_variables", "(", "'${TEST NAME}'", ")", "outputdir", "=", "BuiltIn", "(", ")", ".", "replace_variables", "(", "'${OUTPUTDIR}'", ")", "path", "=", "os",...
Create a message sequence diagram png file to output folder and embed the image to log file. You need to have seqdiag installed to create the sequence diagram. See http://blockdiag.com/en/seqdiag/
[ "Create", "a", "message", "sequence", "diagram", "png", "file", "to", "output", "folder", "and", "embed", "the", "image", "to", "log", "file", "." ]
c906058d055a6f7c68fe1a6096d78c2e3f642b1c
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/rammbock.py#L164-L172
train
36,722
Duke-GCB/DukeDSClient
ddsc/ddsclient.py
DDSClient._check_pypi_version
def _check_pypi_version(self): """ When the version is out of date or we have trouble retrieving it print a error to stderr and pause. """ try: check_version() except VersionException as err: print(str(err), file=sys.stderr) time.sleep(TWO_SECONDS)
python
def _check_pypi_version(self): """ When the version is out of date or we have trouble retrieving it print a error to stderr and pause. """ try: check_version() except VersionException as err: print(str(err), file=sys.stderr) time.sleep(TWO_SECONDS)
[ "def", "_check_pypi_version", "(", "self", ")", ":", "try", ":", "check_version", "(", ")", "except", "VersionException", "as", "err", ":", "print", "(", "str", "(", "err", ")", ",", "file", "=", "sys", ".", "stderr", ")", "time", ".", "sleep", "(", ...
When the version is out of date or we have trouble retrieving it print a error to stderr and pause.
[ "When", "the", "version", "is", "out", "of", "date", "or", "we", "have", "trouble", "retrieving", "it", "print", "a", "error", "to", "stderr", "and", "pause", "." ]
117f68fb9bae82e4c81ea487ad5d61ac350f3726
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/ddsclient.py#L63-L71
train
36,723
twisted/txaws
txaws/client/ssl.py
get_ca_certs
def get_ca_certs(environ=os.environ): """ Retrieve a list of CAs at either the DEFAULT_CERTS_PATH or the env override, TXAWS_CERTS_PATH. In order to find .pem files, this function checks first for presence of the TXAWS_CERTS_PATH environment variable that should point to a directory containing cert files. In the absense of this variable, the module-level DEFAULT_CERTS_PATH will be used instead. Note that both of these variables have have multiple paths in them, just like the familiar PATH environment variable (separated by colons). """ cert_paths = environ.get("TXAWS_CERTS_PATH", DEFAULT_CERTS_PATH).split(":") certificate_authority_map = {} for path in cert_paths: if not path: continue for cert_file_name in glob(os.path.join(path, "*.pem")): # There might be some dead symlinks in there, so let's make sure # it's real. if not os.path.exists(cert_file_name): continue cert_file = open(cert_file_name) data = cert_file.read() cert_file.close() x509 = load_certificate(FILETYPE_PEM, data) digest = x509.digest("sha1") # Now, de-duplicate in case the same cert has multiple names. certificate_authority_map[digest] = x509 values = certificate_authority_map.values() if len(values) == 0: raise exception.CertsNotFoundError("Could not find any .pem files.") return values
python
def get_ca_certs(environ=os.environ): """ Retrieve a list of CAs at either the DEFAULT_CERTS_PATH or the env override, TXAWS_CERTS_PATH. In order to find .pem files, this function checks first for presence of the TXAWS_CERTS_PATH environment variable that should point to a directory containing cert files. In the absense of this variable, the module-level DEFAULT_CERTS_PATH will be used instead. Note that both of these variables have have multiple paths in them, just like the familiar PATH environment variable (separated by colons). """ cert_paths = environ.get("TXAWS_CERTS_PATH", DEFAULT_CERTS_PATH).split(":") certificate_authority_map = {} for path in cert_paths: if not path: continue for cert_file_name in glob(os.path.join(path, "*.pem")): # There might be some dead symlinks in there, so let's make sure # it's real. if not os.path.exists(cert_file_name): continue cert_file = open(cert_file_name) data = cert_file.read() cert_file.close() x509 = load_certificate(FILETYPE_PEM, data) digest = x509.digest("sha1") # Now, de-duplicate in case the same cert has multiple names. certificate_authority_map[digest] = x509 values = certificate_authority_map.values() if len(values) == 0: raise exception.CertsNotFoundError("Could not find any .pem files.") return values
[ "def", "get_ca_certs", "(", "environ", "=", "os", ".", "environ", ")", ":", "cert_paths", "=", "environ", ".", "get", "(", "\"TXAWS_CERTS_PATH\"", ",", "DEFAULT_CERTS_PATH", ")", ".", "split", "(", "\":\"", ")", "certificate_authority_map", "=", "{", "}", "f...
Retrieve a list of CAs at either the DEFAULT_CERTS_PATH or the env override, TXAWS_CERTS_PATH. In order to find .pem files, this function checks first for presence of the TXAWS_CERTS_PATH environment variable that should point to a directory containing cert files. In the absense of this variable, the module-level DEFAULT_CERTS_PATH will be used instead. Note that both of these variables have have multiple paths in them, just like the familiar PATH environment variable (separated by colons).
[ "Retrieve", "a", "list", "of", "CAs", "at", "either", "the", "DEFAULT_CERTS_PATH", "or", "the", "env", "override", "TXAWS_CERTS_PATH", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/client/ssl.py#L86-L119
train
36,724
twisted/txaws
txaws/util.py
iso8601time
def iso8601time(time_tuple): """Format time_tuple as a ISO8601 time string. :param time_tuple: Either None, to use the current time, or a tuple tuple. """ if time_tuple: return time.strftime("%Y-%m-%dT%H:%M:%SZ", time_tuple) else: return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
python
def iso8601time(time_tuple): """Format time_tuple as a ISO8601 time string. :param time_tuple: Either None, to use the current time, or a tuple tuple. """ if time_tuple: return time.strftime("%Y-%m-%dT%H:%M:%SZ", time_tuple) else: return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
[ "def", "iso8601time", "(", "time_tuple", ")", ":", "if", "time_tuple", ":", "return", "time", ".", "strftime", "(", "\"%Y-%m-%dT%H:%M:%SZ\"", ",", "time_tuple", ")", "else", ":", "return", "time", ".", "strftime", "(", "\"%Y-%m-%dT%H:%M:%SZ\"", ",", "time", "....
Format time_tuple as a ISO8601 time string. :param time_tuple: Either None, to use the current time, or a tuple tuple.
[ "Format", "time_tuple", "as", "a", "ISO8601", "time", "string", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/util.py#L39-L47
train
36,725
twisted/txaws
txaws/util.py
parse
def parse(url, defaultPort=True): """ Split the given URL into the scheme, host, port, and path. @type url: C{str} @param url: An URL to parse. @type defaultPort: C{bool} @param defaultPort: Whether to return the default port associated with the scheme in the given url, when the url doesn't specify one. @return: A four-tuple of the scheme, host, port, and path of the URL. All of these are C{str} instances except for port, which is an C{int}. """ url = url.strip() parsed = urlparse(url) scheme = parsed[0] path = urlunparse(("", "") + parsed[2:]) host = parsed[1] if ":" in host: host, port = host.split(":") try: port = int(port) except ValueError: # A non-numeric port was given, it will be replaced with # an appropriate default value if defaultPort is True port = None else: port = None if port is None and defaultPort: if scheme == "https": port = 443 else: port = 80 if path == "": path = "/" return (str(scheme), str(host), port, str(path))
python
def parse(url, defaultPort=True): """ Split the given URL into the scheme, host, port, and path. @type url: C{str} @param url: An URL to parse. @type defaultPort: C{bool} @param defaultPort: Whether to return the default port associated with the scheme in the given url, when the url doesn't specify one. @return: A four-tuple of the scheme, host, port, and path of the URL. All of these are C{str} instances except for port, which is an C{int}. """ url = url.strip() parsed = urlparse(url) scheme = parsed[0] path = urlunparse(("", "") + parsed[2:]) host = parsed[1] if ":" in host: host, port = host.split(":") try: port = int(port) except ValueError: # A non-numeric port was given, it will be replaced with # an appropriate default value if defaultPort is True port = None else: port = None if port is None and defaultPort: if scheme == "https": port = 443 else: port = 80 if path == "": path = "/" return (str(scheme), str(host), port, str(path))
[ "def", "parse", "(", "url", ",", "defaultPort", "=", "True", ")", ":", "url", "=", "url", ".", "strip", "(", ")", "parsed", "=", "urlparse", "(", "url", ")", "scheme", "=", "parsed", "[", "0", "]", "path", "=", "urlunparse", "(", "(", "\"\"", ","...
Split the given URL into the scheme, host, port, and path. @type url: C{str} @param url: An URL to parse. @type defaultPort: C{bool} @param defaultPort: Whether to return the default port associated with the scheme in the given url, when the url doesn't specify one. @return: A four-tuple of the scheme, host, port, and path of the URL. All of these are C{str} instances except for port, which is an C{int}.
[ "Split", "the", "given", "URL", "into", "the", "scheme", "host", "port", "and", "path", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/util.py#L64-L103
train
36,726
Duke-GCB/DukeDSClient
ddsc/core/ddsapi.py
DataServiceAuth.claim_new_token
def claim_new_token(self): """ Update internal state to have a new token using a no authorization data service. """ # Intentionally doing this manually so we don't have a chicken and egg problem with DataServiceApi. headers = { 'Content-Type': ContentType.json, 'User-Agent': self.user_agent_str, } data = { "agent_key": self.config.agent_key, "user_key": self.config.user_key, } url_suffix = "/software_agents/api_token" url = self.config.url + url_suffix response = requests.post(url, headers=headers, data=json.dumps(data)) if response.status_code == 404: if not self.config.agent_key: raise MissingInitialSetupError() else: raise SoftwareAgentNotFoundError() elif response.status_code == 503: raise DataServiceError(response, url_suffix, data) elif response.status_code != 201: raise AuthTokenCreationError(response) resp_json = response.json() self._auth = resp_json['api_token'] self._expires = resp_json['expires_on']
python
def claim_new_token(self): """ Update internal state to have a new token using a no authorization data service. """ # Intentionally doing this manually so we don't have a chicken and egg problem with DataServiceApi. headers = { 'Content-Type': ContentType.json, 'User-Agent': self.user_agent_str, } data = { "agent_key": self.config.agent_key, "user_key": self.config.user_key, } url_suffix = "/software_agents/api_token" url = self.config.url + url_suffix response = requests.post(url, headers=headers, data=json.dumps(data)) if response.status_code == 404: if not self.config.agent_key: raise MissingInitialSetupError() else: raise SoftwareAgentNotFoundError() elif response.status_code == 503: raise DataServiceError(response, url_suffix, data) elif response.status_code != 201: raise AuthTokenCreationError(response) resp_json = response.json() self._auth = resp_json['api_token'] self._expires = resp_json['expires_on']
[ "def", "claim_new_token", "(", "self", ")", ":", "# Intentionally doing this manually so we don't have a chicken and egg problem with DataServiceApi.", "headers", "=", "{", "'Content-Type'", ":", "ContentType", ".", "json", ",", "'User-Agent'", ":", "self", ".", "user_agent_s...
Update internal state to have a new token using a no authorization data service.
[ "Update", "internal", "state", "to", "have", "a", "new", "token", "using", "a", "no", "authorization", "data", "service", "." ]
117f68fb9bae82e4c81ea487ad5d61ac350f3726
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/ddsapi.py#L94-L121
train
36,727
twisted/txaws
txaws/server/resource.py
QueryAPI.handle
def handle(self, request): """Handle an HTTP request for executing an API call. This method authenticates the request checking its signature, and then calls the C{execute} method, passing it a L{Call} object set with the principal for the authenticated user and the generic parameters extracted from the request. @param request: The L{HTTPRequest} to handle. """ request.id = str(uuid4()) deferred = maybeDeferred(self._validate, request) deferred.addCallback(self.execute) def write_response(response): request.setHeader("Content-Length", str(len(response))) request.setHeader("Content-Type", self.content_type) # Prevent browsers from trying to guess a different content type. request.setHeader("X-Content-Type-Options", "nosniff") request.write(response) request.finish() return response def write_error(failure): if failure.check(APIError): status = failure.value.status # Don't log the stack traces for 4xx responses. if status < 400 or status >= 500: log.err(failure) else: log.msg("status: %s message: %s" % ( status, safe_str(failure.value))) body = failure.value.response if body is None: body = self.dump_error(failure.value, request) else: # If the error is a generic one (not an APIError), log the # message , but don't send it back to the client, as it could # contain sensitive information. Send a generic server error # message instead. log.err(failure) body = "Server error" status = 500 request.setResponseCode(status) write_response(body) deferred.addCallback(write_response) deferred.addErrback(write_error) return deferred
python
def handle(self, request): """Handle an HTTP request for executing an API call. This method authenticates the request checking its signature, and then calls the C{execute} method, passing it a L{Call} object set with the principal for the authenticated user and the generic parameters extracted from the request. @param request: The L{HTTPRequest} to handle. """ request.id = str(uuid4()) deferred = maybeDeferred(self._validate, request) deferred.addCallback(self.execute) def write_response(response): request.setHeader("Content-Length", str(len(response))) request.setHeader("Content-Type", self.content_type) # Prevent browsers from trying to guess a different content type. request.setHeader("X-Content-Type-Options", "nosniff") request.write(response) request.finish() return response def write_error(failure): if failure.check(APIError): status = failure.value.status # Don't log the stack traces for 4xx responses. if status < 400 or status >= 500: log.err(failure) else: log.msg("status: %s message: %s" % ( status, safe_str(failure.value))) body = failure.value.response if body is None: body = self.dump_error(failure.value, request) else: # If the error is a generic one (not an APIError), log the # message , but don't send it back to the client, as it could # contain sensitive information. Send a generic server error # message instead. log.err(failure) body = "Server error" status = 500 request.setResponseCode(status) write_response(body) deferred.addCallback(write_response) deferred.addErrback(write_error) return deferred
[ "def", "handle", "(", "self", ",", "request", ")", ":", "request", ".", "id", "=", "str", "(", "uuid4", "(", ")", ")", "deferred", "=", "maybeDeferred", "(", "self", ".", "_validate", ",", "request", ")", "deferred", ".", "addCallback", "(", "self", ...
Handle an HTTP request for executing an API call. This method authenticates the request checking its signature, and then calls the C{execute} method, passing it a L{Call} object set with the principal for the authenticated user and the generic parameters extracted from the request. @param request: The L{HTTPRequest} to handle.
[ "Handle", "an", "HTTP", "request", "for", "executing", "an", "API", "call", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/server/resource.py#L80-L130
train
36,728
twisted/txaws
txaws/server/resource.py
QueryAPI.get_call_arguments
def get_call_arguments(self, request): """ Get call arguments from a request. Override this if you want to use a wire format different from AWS's. The return value is a dictionary with three keys: 'transport_args', 'handler_args', and 'raw_args'. The value of 'transport_args' must be a dictionary with the following keys: - action - access_key_id - timestamp - expires - version - signature_method - signature - signature_version The value of 'handler_args' should be the application arguments that are meant to be passed to the action handler. The value of 'raw_args', the unprocessed arguments, are used for signature verification. This should be the same dictionary of data that the client used to sign the request. Note that this data must not contain the signature itself. """ params = dict((k, v[-1]) for k, v in request.args.iteritems()) args, rest = self.schema.extract(params) # Get rid of Signature so it doesn't mess with signature verification params.pop("Signature") result = { "transport_args": { "action": args.Action, "access_key_id": args.AWSAccessKeyId, "timestamp": args.Timestamp, "expires": args.Expires, "version": args.Version, "signature_method": args.SignatureMethod, "signature": args.Signature, "signature_version": args.SignatureVersion}, "handler_args": rest, "raw_args": params } return result
python
def get_call_arguments(self, request): """ Get call arguments from a request. Override this if you want to use a wire format different from AWS's. The return value is a dictionary with three keys: 'transport_args', 'handler_args', and 'raw_args'. The value of 'transport_args' must be a dictionary with the following keys: - action - access_key_id - timestamp - expires - version - signature_method - signature - signature_version The value of 'handler_args' should be the application arguments that are meant to be passed to the action handler. The value of 'raw_args', the unprocessed arguments, are used for signature verification. This should be the same dictionary of data that the client used to sign the request. Note that this data must not contain the signature itself. """ params = dict((k, v[-1]) for k, v in request.args.iteritems()) args, rest = self.schema.extract(params) # Get rid of Signature so it doesn't mess with signature verification params.pop("Signature") result = { "transport_args": { "action": args.Action, "access_key_id": args.AWSAccessKeyId, "timestamp": args.Timestamp, "expires": args.Expires, "version": args.Version, "signature_method": args.SignatureMethod, "signature": args.Signature, "signature_version": args.SignatureVersion}, "handler_args": rest, "raw_args": params } return result
[ "def", "get_call_arguments", "(", "self", ",", "request", ")", ":", "params", "=", "dict", "(", "(", "k", ",", "v", "[", "-", "1", "]", ")", "for", "k", ",", "v", "in", "request", ".", "args", ".", "iteritems", "(", ")", ")", "args", ",", "rest...
Get call arguments from a request. Override this if you want to use a wire format different from AWS's. The return value is a dictionary with three keys: 'transport_args', 'handler_args', and 'raw_args'. The value of 'transport_args' must be a dictionary with the following keys: - action - access_key_id - timestamp - expires - version - signature_method - signature - signature_version The value of 'handler_args' should be the application arguments that are meant to be passed to the action handler. The value of 'raw_args', the unprocessed arguments, are used for signature verification. This should be the same dictionary of data that the client used to sign the request. Note that this data must not contain the signature itself.
[ "Get", "call", "arguments", "from", "a", "request", ".", "Override", "this", "if", "you", "want", "to", "use", "a", "wire", "format", "different", "from", "AWS", "s", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/server/resource.py#L169-L214
train
36,729
twisted/txaws
txaws/server/resource.py
QueryAPI._validate_generic_parameters
def _validate_generic_parameters(self, args): """Validate the generic request parameters. @param args: Parsed schema arguments. @raises APIError: In the following cases: - Action is not included in C{self.actions} - SignatureVersion is not included in C{self.signature_versions} - Expires and Timestamp are present - Expires is before the current time - Timestamp is older than 15 minutes. """ utc_now = self.get_utc_time() if getattr(self, "actions", None) is not None: # Check the deprecated 'actions' attribute if not args["action"] in self.actions: raise APIError(400, "InvalidAction", "The action %s is not " "valid for this web service." % args["action"]) else: self.registry.check(args["action"], args["version"]) if not args["signature_version"] in self.signature_versions: raise APIError(403, "InvalidSignature", "SignatureVersion '%s' " "not supported" % args["signature_version"]) if args["expires"] and args["timestamp"]: raise APIError(400, "InvalidParameterCombination", "The parameter Timestamp cannot be used with " "the parameter Expires") if args["expires"] and args["expires"] < utc_now: raise APIError(400, "RequestExpired", "Request has expired. Expires date is %s" % ( args["expires"].strftime(self.time_format))) if (args["timestamp"] and args["timestamp"] + timedelta(minutes=15) < utc_now): raise APIError(400, "RequestExpired", "Request has expired. Timestamp date is %s" % ( args["timestamp"].strftime(self.time_format)))
python
def _validate_generic_parameters(self, args): """Validate the generic request parameters. @param args: Parsed schema arguments. @raises APIError: In the following cases: - Action is not included in C{self.actions} - SignatureVersion is not included in C{self.signature_versions} - Expires and Timestamp are present - Expires is before the current time - Timestamp is older than 15 minutes. """ utc_now = self.get_utc_time() if getattr(self, "actions", None) is not None: # Check the deprecated 'actions' attribute if not args["action"] in self.actions: raise APIError(400, "InvalidAction", "The action %s is not " "valid for this web service." % args["action"]) else: self.registry.check(args["action"], args["version"]) if not args["signature_version"] in self.signature_versions: raise APIError(403, "InvalidSignature", "SignatureVersion '%s' " "not supported" % args["signature_version"]) if args["expires"] and args["timestamp"]: raise APIError(400, "InvalidParameterCombination", "The parameter Timestamp cannot be used with " "the parameter Expires") if args["expires"] and args["expires"] < utc_now: raise APIError(400, "RequestExpired", "Request has expired. Expires date is %s" % ( args["expires"].strftime(self.time_format))) if (args["timestamp"] and args["timestamp"] + timedelta(minutes=15) < utc_now): raise APIError(400, "RequestExpired", "Request has expired. Timestamp date is %s" % ( args["timestamp"].strftime(self.time_format)))
[ "def", "_validate_generic_parameters", "(", "self", ",", "args", ")", ":", "utc_now", "=", "self", ".", "get_utc_time", "(", ")", "if", "getattr", "(", "self", ",", "\"actions\"", ",", "None", ")", "is", "not", "None", ":", "# Check the deprecated 'actions' at...
Validate the generic request parameters. @param args: Parsed schema arguments. @raises APIError: In the following cases: - Action is not included in C{self.actions} - SignatureVersion is not included in C{self.signature_versions} - Expires and Timestamp are present - Expires is before the current time - Timestamp is older than 15 minutes.
[ "Validate", "the", "generic", "request", "parameters", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/server/resource.py#L251-L290
train
36,730
twisted/txaws
txaws/server/resource.py
QueryAPI._validate_signature
def _validate_signature(self, request, principal, args, params): """Validate the signature.""" creds = AWSCredentials(principal.access_key, principal.secret_key) endpoint = AWSServiceEndpoint() endpoint.set_method(request.method) endpoint.set_canonical_host(request.getHeader("Host")) path = request.path if self.path is not None: path = "%s/%s" % (self.path.rstrip("/"), path.lstrip("/")) endpoint.set_path(path) signature = Signature(creds, endpoint, params, signature_method=args["signature_method"], signature_version=args["signature_version"] ) if signature.compute() != args["signature"]: raise APIError(403, "SignatureDoesNotMatch", "The request signature we calculated does not " "match the signature you provided. Check your " "key and signing method.")
python
def _validate_signature(self, request, principal, args, params): """Validate the signature.""" creds = AWSCredentials(principal.access_key, principal.secret_key) endpoint = AWSServiceEndpoint() endpoint.set_method(request.method) endpoint.set_canonical_host(request.getHeader("Host")) path = request.path if self.path is not None: path = "%s/%s" % (self.path.rstrip("/"), path.lstrip("/")) endpoint.set_path(path) signature = Signature(creds, endpoint, params, signature_method=args["signature_method"], signature_version=args["signature_version"] ) if signature.compute() != args["signature"]: raise APIError(403, "SignatureDoesNotMatch", "The request signature we calculated does not " "match the signature you provided. Check your " "key and signing method.")
[ "def", "_validate_signature", "(", "self", ",", "request", ",", "principal", ",", "args", ",", "params", ")", ":", "creds", "=", "AWSCredentials", "(", "principal", ".", "access_key", ",", "principal", ".", "secret_key", ")", "endpoint", "=", "AWSServiceEndpoi...
Validate the signature.
[ "Validate", "the", "signature", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/server/resource.py#L299-L317
train
36,731
twisted/txaws
txaws/server/resource.py
QueryAPI.render_GET
def render_GET(self, request): """Handle a GET request.""" if not request.args: request.setHeader("Content-Type", "text/plain") return self.get_status_text() else: self.handle(request) return NOT_DONE_YET
python
def render_GET(self, request): """Handle a GET request.""" if not request.args: request.setHeader("Content-Type", "text/plain") return self.get_status_text() else: self.handle(request) return NOT_DONE_YET
[ "def", "render_GET", "(", "self", ",", "request", ")", ":", "if", "not", "request", ".", "args", ":", "request", ".", "setHeader", "(", "\"Content-Type\"", ",", "\"text/plain\"", ")", "return", "self", ".", "get_status_text", "(", ")", "else", ":", "self",...
Handle a GET request.
[ "Handle", "a", "GET", "request", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/server/resource.py#L323-L330
train
36,732
twisted/txaws
txaws/_auth_v4.py
getSignatureKey
def getSignatureKey(key, dateStamp, regionName, serviceName): """ Generate the signing key for AWS V4 requests. @param key: The secret key to use. @type key: L{bytes} @param dateStamp: The UTC date and time, serialized as an AWS date stamp. @type dateStamp: L{bytes} @param regionName: The name of the region. @type regionName: L{bytes} @param serviceName: The name of the service to which the request will be sent. @type serviceName: L{bytes} @return: The signature. @rtype: L{bytes} """ kDate = sign((b'AWS4' + key), dateStamp) kRegion = sign(kDate, regionName) kService = sign(kRegion, serviceName) kSigning = sign(kService, b'aws4_request') return kSigning
python
def getSignatureKey(key, dateStamp, regionName, serviceName): """ Generate the signing key for AWS V4 requests. @param key: The secret key to use. @type key: L{bytes} @param dateStamp: The UTC date and time, serialized as an AWS date stamp. @type dateStamp: L{bytes} @param regionName: The name of the region. @type regionName: L{bytes} @param serviceName: The name of the service to which the request will be sent. @type serviceName: L{bytes} @return: The signature. @rtype: L{bytes} """ kDate = sign((b'AWS4' + key), dateStamp) kRegion = sign(kDate, regionName) kService = sign(kRegion, serviceName) kSigning = sign(kService, b'aws4_request') return kSigning
[ "def", "getSignatureKey", "(", "key", ",", "dateStamp", ",", "regionName", ",", "serviceName", ")", ":", "kDate", "=", "sign", "(", "(", "b'AWS4'", "+", "key", ")", ",", "dateStamp", ")", "kRegion", "=", "sign", "(", "kDate", ",", "regionName", ")", "k...
Generate the signing key for AWS V4 requests. @param key: The secret key to use. @type key: L{bytes} @param dateStamp: The UTC date and time, serialized as an AWS date stamp. @type dateStamp: L{bytes} @param regionName: The name of the region. @type regionName: L{bytes} @param serviceName: The name of the service to which the request will be sent. @type serviceName: L{bytes} @return: The signature. @rtype: L{bytes}
[ "Generate", "the", "signing", "key", "for", "AWS", "V4", "requests", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/_auth_v4.py#L29-L54
train
36,733
twisted/txaws
txaws/_auth_v4.py
_make_canonical_uri
def _make_canonical_uri(parsed): """ Return the canonical URI for a parsed URL. @param parsed: The parsed URL from which to extract the canonical URI @type parsed: L{urlparse.ParseResult} @return: The canonical URI. @rtype: L{str} """ path = urllib.quote(parsed.path) canonical_parsed = parsed._replace(path=path, params='', query='', fragment='') return urlparse.urlunparse(canonical_parsed)
python
def _make_canonical_uri(parsed): """ Return the canonical URI for a parsed URL. @param parsed: The parsed URL from which to extract the canonical URI @type parsed: L{urlparse.ParseResult} @return: The canonical URI. @rtype: L{str} """ path = urllib.quote(parsed.path) canonical_parsed = parsed._replace(path=path, params='', query='', fragment='') return urlparse.urlunparse(canonical_parsed)
[ "def", "_make_canonical_uri", "(", "parsed", ")", ":", "path", "=", "urllib", ".", "quote", "(", "parsed", ".", "path", ")", "canonical_parsed", "=", "parsed", ".", "_replace", "(", "path", "=", "path", ",", "params", "=", "''", ",", "query", "=", "''"...
Return the canonical URI for a parsed URL. @param parsed: The parsed URL from which to extract the canonical URI @type parsed: L{urlparse.ParseResult} @return: The canonical URI. @rtype: L{str}
[ "Return", "the", "canonical", "URI", "for", "a", "parsed", "URL", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/_auth_v4.py#L86-L100
train
36,734
twisted/txaws
txaws/_auth_v4.py
_make_canonical_query_string
def _make_canonical_query_string(parsed): """ Return the canonical query string for a parsed URL. @param parsed: The parsed URL from which to extract the canonical query string. @type parsed: L{urlparse.ParseResult} @return: The canonical query string. @rtype: L{str} """ query_params = urlparse.parse_qs(parsed.query, keep_blank_values=True) sorted_query_params = sorted((k, v) for k, vs in query_params.items() for v in vs) return urllib.urlencode(sorted_query_params)
python
def _make_canonical_query_string(parsed): """ Return the canonical query string for a parsed URL. @param parsed: The parsed URL from which to extract the canonical query string. @type parsed: L{urlparse.ParseResult} @return: The canonical query string. @rtype: L{str} """ query_params = urlparse.parse_qs(parsed.query, keep_blank_values=True) sorted_query_params = sorted((k, v) for k, vs in query_params.items() for v in vs) return urllib.urlencode(sorted_query_params)
[ "def", "_make_canonical_query_string", "(", "parsed", ")", ":", "query_params", "=", "urlparse", ".", "parse_qs", "(", "parsed", ".", "query", ",", "keep_blank_values", "=", "True", ")", "sorted_query_params", "=", "sorted", "(", "(", "k", ",", "v", ")", "fo...
Return the canonical query string for a parsed URL. @param parsed: The parsed URL from which to extract the canonical query string. @type parsed: L{urlparse.ParseResult} @return: The canonical query string. @rtype: L{str}
[ "Return", "the", "canonical", "query", "string", "for", "a", "parsed", "URL", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/_auth_v4.py#L103-L118
train
36,735
twisted/txaws
txaws/_auth_v4.py
_make_canonical_headers
def _make_canonical_headers(headers, headers_to_sign): """ Return canonicalized headers. @param headers: The request headers. @type headers: L{dict} @param headers_to_sign: A sequence of header names that should be signed. @type headers_to_sign: A sequence of L{bytes} @return: The canonicalized headers. @rtype: L{bytes} """ pairs = [] for name in headers_to_sign: if name not in headers: continue values = headers[name] if not isinstance(values, (list, tuple)): values = [values] comma_values = b','.join(' '.join(line.strip().split()) for value in values for line in value.splitlines()) pairs.append((name.lower(), comma_values)) sorted_pairs = sorted(b'%s:%s' % (name, value) for name, value in sorted(pairs)) return b'\n'.join(sorted_pairs) + b'\n'
python
def _make_canonical_headers(headers, headers_to_sign): """ Return canonicalized headers. @param headers: The request headers. @type headers: L{dict} @param headers_to_sign: A sequence of header names that should be signed. @type headers_to_sign: A sequence of L{bytes} @return: The canonicalized headers. @rtype: L{bytes} """ pairs = [] for name in headers_to_sign: if name not in headers: continue values = headers[name] if not isinstance(values, (list, tuple)): values = [values] comma_values = b','.join(' '.join(line.strip().split()) for value in values for line in value.splitlines()) pairs.append((name.lower(), comma_values)) sorted_pairs = sorted(b'%s:%s' % (name, value) for name, value in sorted(pairs)) return b'\n'.join(sorted_pairs) + b'\n'
[ "def", "_make_canonical_headers", "(", "headers", ",", "headers_to_sign", ")", ":", "pairs", "=", "[", "]", "for", "name", "in", "headers_to_sign", ":", "if", "name", "not", "in", "headers", ":", "continue", "values", "=", "headers", "[", "name", "]", "if"...
Return canonicalized headers. @param headers: The request headers. @type headers: L{dict} @param headers_to_sign: A sequence of header names that should be signed. @type headers_to_sign: A sequence of L{bytes} @return: The canonicalized headers. @rtype: L{bytes}
[ "Return", "canonicalized", "headers", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/_auth_v4.py#L121-L149
train
36,736
twisted/txaws
txaws/_auth_v4.py
_make_signed_headers
def _make_signed_headers(headers, headers_to_sign): """ Return a semicolon-delimited list of headers to sign. @param headers: The request headers. @type headers: L{dict} @param headers_to_sign: A sequence of header names that should be signed. @type headers_to_sign: L{bytes} @return: The semicolon-delimited list of headers. @rtype: L{bytes} """ return b";".join(header.lower() for header in sorted(headers_to_sign) if header in headers)
python
def _make_signed_headers(headers, headers_to_sign): """ Return a semicolon-delimited list of headers to sign. @param headers: The request headers. @type headers: L{dict} @param headers_to_sign: A sequence of header names that should be signed. @type headers_to_sign: L{bytes} @return: The semicolon-delimited list of headers. @rtype: L{bytes} """ return b";".join(header.lower() for header in sorted(headers_to_sign) if header in headers)
[ "def", "_make_signed_headers", "(", "headers", ",", "headers_to_sign", ")", ":", "return", "b\";\"", ".", "join", "(", "header", ".", "lower", "(", ")", "for", "header", "in", "sorted", "(", "headers_to_sign", ")", "if", "header", "in", "headers", ")" ]
Return a semicolon-delimited list of headers to sign. @param headers: The request headers. @type headers: L{dict} @param headers_to_sign: A sequence of header names that should be signed. @type headers_to_sign: L{bytes} @return: The semicolon-delimited list of headers. @rtype: L{bytes}
[ "Return", "a", "semicolon", "-", "delimited", "list", "of", "headers", "to", "sign", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/_auth_v4.py#L152-L167
train
36,737
T-002/pycast
pycast/common/helper.py
linear_interpolation
def linear_interpolation(first, last, steps): """Interpolates all missing values using linear interpolation. :param numeric first: Start value for the interpolation. :param numeric last: End Value for the interpolation :param integer steps: Number of missing values that have to be calculated. :return: Returns a list of floats containing only the missing values. :rtype: list :todo: Define a more general interface! """ result = [] for step in xrange(0, steps): fpart = (steps - step) * first lpart = (step + 1) * last value = (fpart + lpart) / float(steps + 1) result.append(value) return result
python
def linear_interpolation(first, last, steps): """Interpolates all missing values using linear interpolation. :param numeric first: Start value for the interpolation. :param numeric last: End Value for the interpolation :param integer steps: Number of missing values that have to be calculated. :return: Returns a list of floats containing only the missing values. :rtype: list :todo: Define a more general interface! """ result = [] for step in xrange(0, steps): fpart = (steps - step) * first lpart = (step + 1) * last value = (fpart + lpart) / float(steps + 1) result.append(value) return result
[ "def", "linear_interpolation", "(", "first", ",", "last", ",", "steps", ")", ":", "result", "=", "[", "]", "for", "step", "in", "xrange", "(", "0", ",", "steps", ")", ":", "fpart", "=", "(", "steps", "-", "step", ")", "*", "first", "lpart", "=", ...
Interpolates all missing values using linear interpolation. :param numeric first: Start value for the interpolation. :param numeric last: End Value for the interpolation :param integer steps: Number of missing values that have to be calculated. :return: Returns a list of floats containing only the missing values. :rtype: list :todo: Define a more general interface!
[ "Interpolates", "all", "missing", "values", "using", "linear", "interpolation", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/helper.py#L27-L47
train
36,738
Duke-GCB/DukeDSClient
ddsc/core/projectuploader.py
ProjectUploader.visit_file
def visit_file(self, item, parent): """ If file is large add it to the large items to be processed after small task list. else file is small add it to the small task list. """ if self.is_large_file(item): self.large_items.append((item, parent)) else: self.small_item_task_builder.visit_file(item, parent)
python
def visit_file(self, item, parent): """ If file is large add it to the large items to be processed after small task list. else file is small add it to the small task list. """ if self.is_large_file(item): self.large_items.append((item, parent)) else: self.small_item_task_builder.visit_file(item, parent)
[ "def", "visit_file", "(", "self", ",", "item", ",", "parent", ")", ":", "if", "self", ".", "is_large_file", "(", "item", ")", ":", "self", ".", "large_items", ".", "append", "(", "(", "item", ",", "parent", ")", ")", "else", ":", "self", ".", "smal...
If file is large add it to the large items to be processed after small task list. else file is small add it to the small task list.
[ "If", "file", "is", "large", "add", "it", "to", "the", "large", "items", "to", "be", "processed", "after", "small", "task", "list", ".", "else", "file", "is", "small", "add", "it", "to", "the", "small", "task", "list", "." ]
117f68fb9bae82e4c81ea487ad5d61ac350f3726
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/projectuploader.py#L134-L142
train
36,739
Duke-GCB/DukeDSClient
ddsc/core/projectuploader.py
ProjectUploader.upload_large_items
def upload_large_items(self): """ Upload files that were too large. """ for local_file, parent in self.large_items: if local_file.need_to_send: self.process_large_file(local_file, parent)
python
def upload_large_items(self): """ Upload files that were too large. """ for local_file, parent in self.large_items: if local_file.need_to_send: self.process_large_file(local_file, parent)
[ "def", "upload_large_items", "(", "self", ")", ":", "for", "local_file", ",", "parent", "in", "self", ".", "large_items", ":", "if", "local_file", ".", "need_to_send", ":", "self", ".", "process_large_file", "(", "local_file", ",", "parent", ")" ]
Upload files that were too large.
[ "Upload", "files", "that", "were", "too", "large", "." ]
117f68fb9bae82e4c81ea487ad5d61ac350f3726
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/projectuploader.py#L147-L153
train
36,740
Duke-GCB/DukeDSClient
ddsc/core/projectuploader.py
SmallItemUploadTaskBuilder.visit_project
def visit_project(self, item): """ Adds create project command to task runner if project doesn't already exist. """ if not item.remote_id: command = CreateProjectCommand(self.settings, item) self.task_runner_add(None, item, command) else: self.settings.project_id = item.remote_id
python
def visit_project(self, item): """ Adds create project command to task runner if project doesn't already exist. """ if not item.remote_id: command = CreateProjectCommand(self.settings, item) self.task_runner_add(None, item, command) else: self.settings.project_id = item.remote_id
[ "def", "visit_project", "(", "self", ",", "item", ")", ":", "if", "not", "item", ".", "remote_id", ":", "command", "=", "CreateProjectCommand", "(", "self", ".", "settings", ",", "item", ")", "self", ".", "task_runner_add", "(", "None", ",", "item", ",",...
Adds create project command to task runner if project doesn't already exist.
[ "Adds", "create", "project", "command", "to", "task", "runner", "if", "project", "doesn", "t", "already", "exist", "." ]
117f68fb9bae82e4c81ea487ad5d61ac350f3726
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/projectuploader.py#L186-L194
train
36,741
Duke-GCB/DukeDSClient
ddsc/core/projectuploader.py
SmallItemUploadTaskBuilder.visit_folder
def visit_folder(self, item, parent): """ Adds create folder command to task runner if folder doesn't already exist. """ if not item.remote_id: command = CreateFolderCommand(self.settings, item, parent) self.task_runner_add(parent, item, command)
python
def visit_folder(self, item, parent): """ Adds create folder command to task runner if folder doesn't already exist. """ if not item.remote_id: command = CreateFolderCommand(self.settings, item, parent) self.task_runner_add(parent, item, command)
[ "def", "visit_folder", "(", "self", ",", "item", ",", "parent", ")", ":", "if", "not", "item", ".", "remote_id", ":", "command", "=", "CreateFolderCommand", "(", "self", ".", "settings", ",", "item", ",", "parent", ")", "self", ".", "task_runner_add", "(...
Adds create folder command to task runner if folder doesn't already exist.
[ "Adds", "create", "folder", "command", "to", "task", "runner", "if", "folder", "doesn", "t", "already", "exist", "." ]
117f68fb9bae82e4c81ea487ad5d61ac350f3726
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/projectuploader.py#L196-L202
train
36,742
Duke-GCB/DukeDSClient
ddsc/core/projectuploader.py
SmallItemUploadTaskBuilder.visit_file
def visit_file(self, item, parent): """ If file is small add create small file command otherwise raise error. Large files shouldn't be passed to SmallItemUploadTaskBuilder. """ if item.need_to_send: if item.size > self.settings.config.upload_bytes_per_chunk: msg = "Programmer Error: Trying to upload large file as small item size:{} name:{}" raise ValueError(msg.format(item.size, item.name)) else: command = CreateSmallFileCommand(self.settings, item, parent, self.settings.file_upload_post_processor) self.task_runner_add(parent, item, command)
python
def visit_file(self, item, parent): """ If file is small add create small file command otherwise raise error. Large files shouldn't be passed to SmallItemUploadTaskBuilder. """ if item.need_to_send: if item.size > self.settings.config.upload_bytes_per_chunk: msg = "Programmer Error: Trying to upload large file as small item size:{} name:{}" raise ValueError(msg.format(item.size, item.name)) else: command = CreateSmallFileCommand(self.settings, item, parent, self.settings.file_upload_post_processor) self.task_runner_add(parent, item, command)
[ "def", "visit_file", "(", "self", ",", "item", ",", "parent", ")", ":", "if", "item", ".", "need_to_send", ":", "if", "item", ".", "size", ">", "self", ".", "settings", ".", "config", ".", "upload_bytes_per_chunk", ":", "msg", "=", "\"Programmer Error: Try...
If file is small add create small file command otherwise raise error. Large files shouldn't be passed to SmallItemUploadTaskBuilder.
[ "If", "file", "is", "small", "add", "create", "small", "file", "command", "otherwise", "raise", "error", ".", "Large", "files", "shouldn", "t", "be", "passed", "to", "SmallItemUploadTaskBuilder", "." ]
117f68fb9bae82e4c81ea487ad5d61ac350f3726
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/projectuploader.py#L204-L216
train
36,743
pdkit/pdkit
pdkit/tremor_processor.py
TremorProcessor.bradykinesia
def bradykinesia(self, data_frame, method='fft'): """ This method calculates the bradykinesia amplitude of the data frame. It accepts two different methods, \ 'fft' and 'welch'. First the signal gets re-sampled, dc removed and then high pass filtered. :param data_frame: the data frame :type data_frame: pandas.DataFrame :param method: fft or welch. :type method: str :return ampl: the amplitude of the Bradykinesia :rtype ampl: float :return freq: the frequency of the Bradykinesia :rtype freq: float """ try: data_frame_resampled = self.resample_signal(data_frame) data_frame_dc = self.dc_remove_signal(data_frame_resampled) data_frame_filtered = self.filter_signal(data_frame_dc, 'dc_mag_sum_acc') if method == 'fft': data_frame_fft = self.fft_signal(data_frame_filtered) return self.amplitude_by_fft(data_frame_fft) else: return self.amplitude_by_welch(data_frame_filtered) except ValueError as verr: logging.error("TremorProcessor bradykinesia ValueError ->%s", verr.message) except: logging.error("Unexpected error on TemorProcessor bradykinesia: %s", sys.exc_info()[0])
python
def bradykinesia(self, data_frame, method='fft'): """ This method calculates the bradykinesia amplitude of the data frame. It accepts two different methods, \ 'fft' and 'welch'. First the signal gets re-sampled, dc removed and then high pass filtered. :param data_frame: the data frame :type data_frame: pandas.DataFrame :param method: fft or welch. :type method: str :return ampl: the amplitude of the Bradykinesia :rtype ampl: float :return freq: the frequency of the Bradykinesia :rtype freq: float """ try: data_frame_resampled = self.resample_signal(data_frame) data_frame_dc = self.dc_remove_signal(data_frame_resampled) data_frame_filtered = self.filter_signal(data_frame_dc, 'dc_mag_sum_acc') if method == 'fft': data_frame_fft = self.fft_signal(data_frame_filtered) return self.amplitude_by_fft(data_frame_fft) else: return self.amplitude_by_welch(data_frame_filtered) except ValueError as verr: logging.error("TremorProcessor bradykinesia ValueError ->%s", verr.message) except: logging.error("Unexpected error on TemorProcessor bradykinesia: %s", sys.exc_info()[0])
[ "def", "bradykinesia", "(", "self", ",", "data_frame", ",", "method", "=", "'fft'", ")", ":", "try", ":", "data_frame_resampled", "=", "self", ".", "resample_signal", "(", "data_frame", ")", "data_frame_dc", "=", "self", ".", "dc_remove_signal", "(", "data_fra...
This method calculates the bradykinesia amplitude of the data frame. It accepts two different methods, \ 'fft' and 'welch'. First the signal gets re-sampled, dc removed and then high pass filtered. :param data_frame: the data frame :type data_frame: pandas.DataFrame :param method: fft or welch. :type method: str :return ampl: the amplitude of the Bradykinesia :rtype ampl: float :return freq: the frequency of the Bradykinesia :rtype freq: float
[ "This", "method", "calculates", "the", "bradykinesia", "amplitude", "of", "the", "data", "frame", ".", "It", "accepts", "two", "different", "methods", "\\", "fft", "and", "welch", ".", "First", "the", "signal", "gets", "re", "-", "sampled", "dc", "removed", ...
c7120263da2071bb139815fbdb56ca77b544f340
https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/tremor_processor.py#L571-L599
train
36,744
twisted/txaws
txaws/client/gui/gtk.py
main
def main(argv, reactor=None): """Run the client GUI. Typical use: >>> sys.exit(main(sys.argv)) @param argv: The arguments to run it with, e.g. sys.argv. @param reactor: The reactor to use. Must be compatible with gtk as this module uses gtk API"s. @return exitcode: The exit code it returned, as per sys.exit. """ if reactor is None: from twisted.internet import gtk2reactor gtk2reactor.install() from twisted.internet import reactor try: AWSStatusIndicator(reactor) gobject.set_application_name("aws-status") reactor.run() except ValueError: # In this case, the user cancelled, and the exception bubbled to here. pass
python
def main(argv, reactor=None): """Run the client GUI. Typical use: >>> sys.exit(main(sys.argv)) @param argv: The arguments to run it with, e.g. sys.argv. @param reactor: The reactor to use. Must be compatible with gtk as this module uses gtk API"s. @return exitcode: The exit code it returned, as per sys.exit. """ if reactor is None: from twisted.internet import gtk2reactor gtk2reactor.install() from twisted.internet import reactor try: AWSStatusIndicator(reactor) gobject.set_application_name("aws-status") reactor.run() except ValueError: # In this case, the user cancelled, and the exception bubbled to here. pass
[ "def", "main", "(", "argv", ",", "reactor", "=", "None", ")", ":", "if", "reactor", "is", "None", ":", "from", "twisted", ".", "internet", "import", "gtk2reactor", "gtk2reactor", ".", "install", "(", ")", "from", "twisted", ".", "internet", "import", "re...
Run the client GUI. Typical use: >>> sys.exit(main(sys.argv)) @param argv: The arguments to run it with, e.g. sys.argv. @param reactor: The reactor to use. Must be compatible with gtk as this module uses gtk API"s. @return exitcode: The exit code it returned, as per sys.exit.
[ "Run", "the", "client", "GUI", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/client/gui/gtk.py#L233-L254
train
36,745
twisted/txaws
txaws/client/discover/entry_point.py
main
def main(arguments, output=None, testing_mode=None): """ Entry point parses command-line arguments, runs the specified EC2 API method and prints the response to the screen. @param arguments: Command-line arguments, typically retrieved from C{sys.argv}. @param output: Optionally, a stream to write output to. @param testing_mode: Optionally, a condition that specifies whether or not to run in test mode. When the value is true a reactor will not be run or stopped, to prevent interfering with the test suite. """ def run_command(arguments, output, reactor): if output is None: output = sys.stdout try: command = get_command(arguments, output) except UsageError: print >>output, USAGE_MESSAGE.strip() if reactor: reactor.callLater(0, reactor.stop) except Exception, e: print >>output, "ERROR:", str(e) if reactor: reactor.callLater(0, reactor.stop) else: deferred = command.run() if reactor: deferred.addCallback(lambda ignored: reactor.stop()) if not testing_mode: from twisted.internet import reactor reactor.callLater(0, run_command, arguments, output, reactor) reactor.run() else: run_command(arguments, output, None)
python
def main(arguments, output=None, testing_mode=None): """ Entry point parses command-line arguments, runs the specified EC2 API method and prints the response to the screen. @param arguments: Command-line arguments, typically retrieved from C{sys.argv}. @param output: Optionally, a stream to write output to. @param testing_mode: Optionally, a condition that specifies whether or not to run in test mode. When the value is true a reactor will not be run or stopped, to prevent interfering with the test suite. """ def run_command(arguments, output, reactor): if output is None: output = sys.stdout try: command = get_command(arguments, output) except UsageError: print >>output, USAGE_MESSAGE.strip() if reactor: reactor.callLater(0, reactor.stop) except Exception, e: print >>output, "ERROR:", str(e) if reactor: reactor.callLater(0, reactor.stop) else: deferred = command.run() if reactor: deferred.addCallback(lambda ignored: reactor.stop()) if not testing_mode: from twisted.internet import reactor reactor.callLater(0, run_command, arguments, output, reactor) reactor.run() else: run_command(arguments, output, None)
[ "def", "main", "(", "arguments", ",", "output", "=", "None", ",", "testing_mode", "=", "None", ")", ":", "def", "run_command", "(", "arguments", ",", "output", ",", "reactor", ")", ":", "if", "output", "is", "None", ":", "output", "=", "sys", ".", "s...
Entry point parses command-line arguments, runs the specified EC2 API method and prints the response to the screen. @param arguments: Command-line arguments, typically retrieved from C{sys.argv}. @param output: Optionally, a stream to write output to. @param testing_mode: Optionally, a condition that specifies whether or not to run in test mode. When the value is true a reactor will not be run or stopped, to prevent interfering with the test suite.
[ "Entry", "point", "parses", "command", "-", "line", "arguments", "runs", "the", "specified", "EC2", "API", "method", "and", "prints", "the", "response", "to", "the", "screen", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/client/discover/entry_point.py#L142-L178
train
36,746
T-002/pycast
pycast/methods/exponentialsmoothing.py
ExponentialSmoothing.execute
def execute(self, timeSeries): """Creates a new TimeSeries containing the smoothed and forcasted values. :return: TimeSeries object containing the smoothed TimeSeries, including the forecasted values. :rtype: TimeSeries :note: The first normalized value is chosen as the starting point. """ # determine the number of values to forecast, if necessary self._calculate_values_to_forecast(timeSeries) # extract the required parameters, performance improvement alpha = self._parameters["smoothingFactor"] valuesToForecast = self._parameters["valuesToForecast"] # initialize some variables resultList = [] estimator = None lastT = None # "It's always about performance!" append = resultList.append # smooth the existing TimeSeries data for idx in xrange(len(timeSeries)): # get the current to increase performance t = timeSeries[idx] # get the initial estimate if estimator is None: estimator = t[1] continue # add the first value to the resultList without any correction if 0 == len(resultList): append([t[0], estimator]) lastT = t continue # calculate the error made during the last estimation error = lastT[1] - estimator # calculate the new estimator, based on the last occured value, the error and the smoothingFactor estimator = estimator + alpha * error # save the current value for the next iteration lastT = t # add an entry to the result append([t[0], estimator]) # forecast additional values if requested if valuesToForecast > 0: currentTime = resultList[-1][0] normalizedTimeDiff = currentTime - resultList[-2][0] for idx in xrange(valuesToForecast): currentTime += normalizedTimeDiff # reuse everything error = lastT[1] - estimator estimator = estimator + alpha * error # add a forecasted value append([currentTime, estimator]) # set variables for next iteration lastT = resultList[-1] # return a TimeSeries, containing the result return TimeSeries.from_twodim_list(resultList)
python
def execute(self, timeSeries): """Creates a new TimeSeries containing the smoothed and forcasted values. :return: TimeSeries object containing the smoothed TimeSeries, including the forecasted values. :rtype: TimeSeries :note: The first normalized value is chosen as the starting point. """ # determine the number of values to forecast, if necessary self._calculate_values_to_forecast(timeSeries) # extract the required parameters, performance improvement alpha = self._parameters["smoothingFactor"] valuesToForecast = self._parameters["valuesToForecast"] # initialize some variables resultList = [] estimator = None lastT = None # "It's always about performance!" append = resultList.append # smooth the existing TimeSeries data for idx in xrange(len(timeSeries)): # get the current to increase performance t = timeSeries[idx] # get the initial estimate if estimator is None: estimator = t[1] continue # add the first value to the resultList without any correction if 0 == len(resultList): append([t[0], estimator]) lastT = t continue # calculate the error made during the last estimation error = lastT[1] - estimator # calculate the new estimator, based on the last occured value, the error and the smoothingFactor estimator = estimator + alpha * error # save the current value for the next iteration lastT = t # add an entry to the result append([t[0], estimator]) # forecast additional values if requested if valuesToForecast > 0: currentTime = resultList[-1][0] normalizedTimeDiff = currentTime - resultList[-2][0] for idx in xrange(valuesToForecast): currentTime += normalizedTimeDiff # reuse everything error = lastT[1] - estimator estimator = estimator + alpha * error # add a forecasted value append([currentTime, estimator]) # set variables for next iteration lastT = resultList[-1] # return a TimeSeries, containing the result return TimeSeries.from_twodim_list(resultList)
[ "def", "execute", "(", "self", ",", "timeSeries", ")", ":", "# determine the number of values to forecast, if necessary", "self", ".", "_calculate_values_to_forecast", "(", "timeSeries", ")", "# extract the required parameters, performance improvement", "alpha", "=", "self", "....
Creates a new TimeSeries containing the smoothed and forcasted values. :return: TimeSeries object containing the smoothed TimeSeries, including the forecasted values. :rtype: TimeSeries :note: The first normalized value is chosen as the starting point.
[ "Creates", "a", "new", "TimeSeries", "containing", "the", "smoothed", "and", "forcasted", "values", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/exponentialsmoothing.py#L77-L148
train
36,747
T-002/pycast
pycast/methods/exponentialsmoothing.py
HoltMethod._get_parameter_intervals
def _get_parameter_intervals(self): """Returns the intervals for the methods parameter. Only parameters with defined intervals can be used for optimization! :return: Returns a dictionary containing the parameter intervals, using the parameter name as key, while the value hast the following format: [minValue, maxValue, minIntervalClosed, maxIntervalClosed] - minValue Minimal value for the parameter - maxValue Maximal value for the parameter - minIntervalClosed :py:const:`True`, if minValue represents a valid value for the parameter. :py:const:`False` otherwise. - maxIntervalClosed: :py:const:`True`, if maxValue represents a valid value for the parameter. :py:const:`False` otherwise. :rtype: dictionary """ parameterIntervals = {} parameterIntervals["smoothingFactor"] = [0.0, 1.0, False, False] parameterIntervals["trendSmoothingFactor"] = [0.0, 1.0, False, False] return parameterIntervals
python
def _get_parameter_intervals(self): """Returns the intervals for the methods parameter. Only parameters with defined intervals can be used for optimization! :return: Returns a dictionary containing the parameter intervals, using the parameter name as key, while the value hast the following format: [minValue, maxValue, minIntervalClosed, maxIntervalClosed] - minValue Minimal value for the parameter - maxValue Maximal value for the parameter - minIntervalClosed :py:const:`True`, if minValue represents a valid value for the parameter. :py:const:`False` otherwise. - maxIntervalClosed: :py:const:`True`, if maxValue represents a valid value for the parameter. :py:const:`False` otherwise. :rtype: dictionary """ parameterIntervals = {} parameterIntervals["smoothingFactor"] = [0.0, 1.0, False, False] parameterIntervals["trendSmoothingFactor"] = [0.0, 1.0, False, False] return parameterIntervals
[ "def", "_get_parameter_intervals", "(", "self", ")", ":", "parameterIntervals", "=", "{", "}", "parameterIntervals", "[", "\"smoothingFactor\"", "]", "=", "[", "0.0", ",", "1.0", ",", "False", ",", "False", "]", "parameterIntervals", "[", "\"trendSmoothingFactor\"...
Returns the intervals for the methods parameter. Only parameters with defined intervals can be used for optimization! :return: Returns a dictionary containing the parameter intervals, using the parameter name as key, while the value hast the following format: [minValue, maxValue, minIntervalClosed, maxIntervalClosed] - minValue Minimal value for the parameter - maxValue Maximal value for the parameter - minIntervalClosed :py:const:`True`, if minValue represents a valid value for the parameter. :py:const:`False` otherwise. - maxIntervalClosed: :py:const:`True`, if maxValue represents a valid value for the parameter. :py:const:`False` otherwise. :rtype: dictionary
[ "Returns", "the", "intervals", "for", "the", "methods", "parameter", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/exponentialsmoothing.py#L178-L204
train
36,748
T-002/pycast
pycast/methods/exponentialsmoothing.py
HoltWintersMethod._calculate_forecast
def _calculate_forecast(self, originalTimeSeries, smoothedData, seasonValues, lastSmoothingParams): """Calculates the actual forecasted based on the input data. :param TimeSeries timeSeries: TimeSeries containing hte data. :param list smoothedData: Contains the smoothed time series data. :param list seasonValues: Contains the seasonal values for the forecast. :param list lastSmoothingParams: List containing the last [estimator, season value, trend] calculated during smoothing the TimeSeries. :return: Returns a list containing forecasted values """ forecastResults = [] lastEstimator, lastSeasonValue, lastTrend = lastSmoothingParams seasonLength = self.get_parameter("seasonLength") #Forecasting. Determine the time difference between two points for extrapolation currentTime = smoothedData[-1][0] normalizedTimeDiff = currentTime - smoothedData[-2][0] for m in xrange(1, self._parameters["valuesToForecast"] + 1): currentTime += normalizedTimeDiff lastSeasonValue = seasonValues[(len(originalTimeSeries) + m - 2) % seasonLength] forecast = (lastEstimator + m * lastTrend) * lastSeasonValue forecastResults.append([currentTime, forecast]) return forecastResults
python
def _calculate_forecast(self, originalTimeSeries, smoothedData, seasonValues, lastSmoothingParams): """Calculates the actual forecasted based on the input data. :param TimeSeries timeSeries: TimeSeries containing hte data. :param list smoothedData: Contains the smoothed time series data. :param list seasonValues: Contains the seasonal values for the forecast. :param list lastSmoothingParams: List containing the last [estimator, season value, trend] calculated during smoothing the TimeSeries. :return: Returns a list containing forecasted values """ forecastResults = [] lastEstimator, lastSeasonValue, lastTrend = lastSmoothingParams seasonLength = self.get_parameter("seasonLength") #Forecasting. Determine the time difference between two points for extrapolation currentTime = smoothedData[-1][0] normalizedTimeDiff = currentTime - smoothedData[-2][0] for m in xrange(1, self._parameters["valuesToForecast"] + 1): currentTime += normalizedTimeDiff lastSeasonValue = seasonValues[(len(originalTimeSeries) + m - 2) % seasonLength] forecast = (lastEstimator + m * lastTrend) * lastSeasonValue forecastResults.append([currentTime, forecast]) return forecastResults
[ "def", "_calculate_forecast", "(", "self", ",", "originalTimeSeries", ",", "smoothedData", ",", "seasonValues", ",", "lastSmoothingParams", ")", ":", "forecastResults", "=", "[", "]", "lastEstimator", ",", "lastSeasonValue", ",", "lastTrend", "=", "lastSmoothingParams...
Calculates the actual forecasted based on the input data. :param TimeSeries timeSeries: TimeSeries containing hte data. :param list smoothedData: Contains the smoothed time series data. :param list seasonValues: Contains the seasonal values for the forecast. :param list lastSmoothingParams: List containing the last [estimator, season value, trend] calculated during smoothing the TimeSeries. :return: Returns a list containing forecasted values
[ "Calculates", "the", "actual", "forecasted", "based", "on", "the", "input", "data", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/exponentialsmoothing.py#L395-L422
train
36,749
T-002/pycast
pycast/methods/exponentialsmoothing.py
HoltWintersMethod.initSeasonFactors
def initSeasonFactors(self, timeSeries): """ Computes the initial season smoothing factors. :return: Returns a list of season vectors of length "seasonLength". :rtype: list """ seasonLength = self.get_parameter("seasonLength") try: seasonValues = self.get_parameter("seasonValues") assert seasonLength == len(seasonValues), "Preset Season Values have to have to be of season's length" return seasonValues except KeyError: pass seasonValues = [] completeCycles = len(timeSeries) / seasonLength A = {} #cache values for A_j for i in xrange(seasonLength): c_i = 0 for j in xrange(completeCycles): if j not in A: A[j] = self.computeA(j, timeSeries) c_i += timeSeries[(seasonLength * j) + i][1] / A[j] #wikipedia suggests j-1, but we worked with indices in the first place c_i /= completeCycles seasonValues.append(c_i) return seasonValues
python
def initSeasonFactors(self, timeSeries): """ Computes the initial season smoothing factors. :return: Returns a list of season vectors of length "seasonLength". :rtype: list """ seasonLength = self.get_parameter("seasonLength") try: seasonValues = self.get_parameter("seasonValues") assert seasonLength == len(seasonValues), "Preset Season Values have to have to be of season's length" return seasonValues except KeyError: pass seasonValues = [] completeCycles = len(timeSeries) / seasonLength A = {} #cache values for A_j for i in xrange(seasonLength): c_i = 0 for j in xrange(completeCycles): if j not in A: A[j] = self.computeA(j, timeSeries) c_i += timeSeries[(seasonLength * j) + i][1] / A[j] #wikipedia suggests j-1, but we worked with indices in the first place c_i /= completeCycles seasonValues.append(c_i) return seasonValues
[ "def", "initSeasonFactors", "(", "self", ",", "timeSeries", ")", ":", "seasonLength", "=", "self", ".", "get_parameter", "(", "\"seasonLength\"", ")", "try", ":", "seasonValues", "=", "self", ".", "get_parameter", "(", "\"seasonValues\"", ")", "assert", "seasonL...
Computes the initial season smoothing factors. :return: Returns a list of season vectors of length "seasonLength". :rtype: list
[ "Computes", "the", "initial", "season", "smoothing", "factors", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/exponentialsmoothing.py#L424-L451
train
36,750
T-002/pycast
pycast/methods/exponentialsmoothing.py
HoltWintersMethod.initialTrendSmoothingFactors
def initialTrendSmoothingFactors(self, timeSeries): """ Calculate the initial Trend smoothing Factor b0. Explanation: http://en.wikipedia.org/wiki/Exponential_smoothing#Triple_exponential_smoothing :return: Returns the initial trend smoothing factor b0 """ result = 0.0 seasonLength = self.get_parameter("seasonLength") k = min(len(timeSeries) - seasonLength, seasonLength) #In case of only one full season, use average trend of the months that we have twice for i in xrange(0, k): result += (timeSeries[seasonLength + i][1] - timeSeries[i][1]) / seasonLength return result / k
python
def initialTrendSmoothingFactors(self, timeSeries): """ Calculate the initial Trend smoothing Factor b0. Explanation: http://en.wikipedia.org/wiki/Exponential_smoothing#Triple_exponential_smoothing :return: Returns the initial trend smoothing factor b0 """ result = 0.0 seasonLength = self.get_parameter("seasonLength") k = min(len(timeSeries) - seasonLength, seasonLength) #In case of only one full season, use average trend of the months that we have twice for i in xrange(0, k): result += (timeSeries[seasonLength + i][1] - timeSeries[i][1]) / seasonLength return result / k
[ "def", "initialTrendSmoothingFactors", "(", "self", ",", "timeSeries", ")", ":", "result", "=", "0.0", "seasonLength", "=", "self", ".", "get_parameter", "(", "\"seasonLength\"", ")", "k", "=", "min", "(", "len", "(", "timeSeries", ")", "-", "seasonLength", ...
Calculate the initial Trend smoothing Factor b0. Explanation: http://en.wikipedia.org/wiki/Exponential_smoothing#Triple_exponential_smoothing :return: Returns the initial trend smoothing factor b0
[ "Calculate", "the", "initial", "Trend", "smoothing", "Factor", "b0", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/exponentialsmoothing.py#L453-L467
train
36,751
T-002/pycast
pycast/methods/exponentialsmoothing.py
HoltWintersMethod.computeA
def computeA(self, j, timeSeries): """ Calculates A_j. Aj is the average value of x in the jth cycle of your data :return: A_j :rtype: numeric """ seasonLength = self.get_parameter("seasonLength") A_j = 0 for i in range(seasonLength): A_j += timeSeries[(seasonLength * (j)) + i][1] return A_j / seasonLength
python
def computeA(self, j, timeSeries): """ Calculates A_j. Aj is the average value of x in the jth cycle of your data :return: A_j :rtype: numeric """ seasonLength = self.get_parameter("seasonLength") A_j = 0 for i in range(seasonLength): A_j += timeSeries[(seasonLength * (j)) + i][1] return A_j / seasonLength
[ "def", "computeA", "(", "self", ",", "j", ",", "timeSeries", ")", ":", "seasonLength", "=", "self", ".", "get_parameter", "(", "\"seasonLength\"", ")", "A_j", "=", "0", "for", "i", "in", "range", "(", "seasonLength", ")", ":", "A_j", "+=", "timeSeries", ...
Calculates A_j. Aj is the average value of x in the jth cycle of your data :return: A_j :rtype: numeric
[ "Calculates", "A_j", ".", "Aj", "is", "the", "average", "value", "of", "x", "in", "the", "jth", "cycle", "of", "your", "data" ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/exponentialsmoothing.py#L470-L480
train
36,752
pdkit/pdkit
pdkit/gait_processor.py
GaitProcessor.frequency_of_peaks
def frequency_of_peaks(self, x, start_offset=100, end_offset=100): """ This method assess the frequency of the peaks on any given 1-dimensional time series. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :param start_offset: Signal to leave out (of calculations) from the begining of the time series (100 default). :type start_offset: int :param end_offset: Signal to leave out (from calculations) from the end of the time series (100 default). :type end_offset: int :return frequency_of_peaks: The frequency of peaks on the provided time series [measured in Hz]. :rtype frequency_of_peaks: float """ peaks_data = x[start_offset: -end_offset].values maxtab, mintab = peakdet(peaks_data, self.delta) x = np.mean(peaks_data[maxtab[1:,0].astype(int)] - peaks_data[maxtab[:-1,0].astype(int)]) frequency_of_peaks = abs(1/x) return frequency_of_peaks
python
def frequency_of_peaks(self, x, start_offset=100, end_offset=100): """ This method assess the frequency of the peaks on any given 1-dimensional time series. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :param start_offset: Signal to leave out (of calculations) from the begining of the time series (100 default). :type start_offset: int :param end_offset: Signal to leave out (from calculations) from the end of the time series (100 default). :type end_offset: int :return frequency_of_peaks: The frequency of peaks on the provided time series [measured in Hz]. :rtype frequency_of_peaks: float """ peaks_data = x[start_offset: -end_offset].values maxtab, mintab = peakdet(peaks_data, self.delta) x = np.mean(peaks_data[maxtab[1:,0].astype(int)] - peaks_data[maxtab[:-1,0].astype(int)]) frequency_of_peaks = abs(1/x) return frequency_of_peaks
[ "def", "frequency_of_peaks", "(", "self", ",", "x", ",", "start_offset", "=", "100", ",", "end_offset", "=", "100", ")", ":", "peaks_data", "=", "x", "[", "start_offset", ":", "-", "end_offset", "]", ".", "values", "maxtab", ",", "mintab", "=", "peakdet"...
This method assess the frequency of the peaks on any given 1-dimensional time series. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :param start_offset: Signal to leave out (of calculations) from the begining of the time series (100 default). :type start_offset: int :param end_offset: Signal to leave out (from calculations) from the end of the time series (100 default). :type end_offset: int :return frequency_of_peaks: The frequency of peaks on the provided time series [measured in Hz]. :rtype frequency_of_peaks: float
[ "This", "method", "assess", "the", "frequency", "of", "the", "peaks", "on", "any", "given", "1", "-", "dimensional", "time", "series", "." ]
c7120263da2071bb139815fbdb56ca77b544f340
https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/gait_processor.py#L178-L199
train
36,753
pdkit/pdkit
pdkit/gait_processor.py
GaitProcessor.walk_regularity_symmetry
def walk_regularity_symmetry(self, data_frame): """ This method extracts the step and stride regularity and also walk symmetry. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :return step_regularity: Regularity of steps on [x, y, z] coordinates, defined as the consistency of the step-to-step pattern. :rtype step_regularity: numpy.ndarray :return stride_regularity: Regularity of stride on [x, y, z] coordinates, defined as the consistency of the stride-to-stride pattern. :rtype stride_regularity: numpy.ndarray :return walk_symmetry: Symmetry of walk on [x, y, z] coordinates, defined as the difference between step and stride regularity. :rtype walk_symmetry: numpy.ndarray """ def _symmetry(v): maxtab, _ = peakdet(v, self.delta) return maxtab[1][1], maxtab[2][1] step_regularity_x, stride_regularity_x = _symmetry(autocorrelation(data_frame.x)) step_regularity_y, stride_regularity_y = _symmetry(autocorrelation(data_frame.y)) step_regularity_z, stride_regularity_z = _symmetry(autocorrelation(data_frame.z)) symmetry_x = step_regularity_x - stride_regularity_x symmetry_y = step_regularity_y - stride_regularity_y symmetry_z = step_regularity_z - stride_regularity_z step_regularity = np.array([step_regularity_x, step_regularity_y, step_regularity_z]) stride_regularity = np.array([stride_regularity_x, stride_regularity_y, stride_regularity_z]) walk_symmetry = np.array([symmetry_x, symmetry_y, symmetry_z]) return step_regularity, stride_regularity, walk_symmetry
python
def walk_regularity_symmetry(self, data_frame): """ This method extracts the step and stride regularity and also walk symmetry. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :return step_regularity: Regularity of steps on [x, y, z] coordinates, defined as the consistency of the step-to-step pattern. :rtype step_regularity: numpy.ndarray :return stride_regularity: Regularity of stride on [x, y, z] coordinates, defined as the consistency of the stride-to-stride pattern. :rtype stride_regularity: numpy.ndarray :return walk_symmetry: Symmetry of walk on [x, y, z] coordinates, defined as the difference between step and stride regularity. :rtype walk_symmetry: numpy.ndarray """ def _symmetry(v): maxtab, _ = peakdet(v, self.delta) return maxtab[1][1], maxtab[2][1] step_regularity_x, stride_regularity_x = _symmetry(autocorrelation(data_frame.x)) step_regularity_y, stride_regularity_y = _symmetry(autocorrelation(data_frame.y)) step_regularity_z, stride_regularity_z = _symmetry(autocorrelation(data_frame.z)) symmetry_x = step_regularity_x - stride_regularity_x symmetry_y = step_regularity_y - stride_regularity_y symmetry_z = step_regularity_z - stride_regularity_z step_regularity = np.array([step_regularity_x, step_regularity_y, step_regularity_z]) stride_regularity = np.array([stride_regularity_x, stride_regularity_y, stride_regularity_z]) walk_symmetry = np.array([symmetry_x, symmetry_y, symmetry_z]) return step_regularity, stride_regularity, walk_symmetry
[ "def", "walk_regularity_symmetry", "(", "self", ",", "data_frame", ")", ":", "def", "_symmetry", "(", "v", ")", ":", "maxtab", ",", "_", "=", "peakdet", "(", "v", ",", "self", ".", "delta", ")", "return", "maxtab", "[", "1", "]", "[", "1", "]", ","...
This method extracts the step and stride regularity and also walk symmetry. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :return step_regularity: Regularity of steps on [x, y, z] coordinates, defined as the consistency of the step-to-step pattern. :rtype step_regularity: numpy.ndarray :return stride_regularity: Regularity of stride on [x, y, z] coordinates, defined as the consistency of the stride-to-stride pattern. :rtype stride_regularity: numpy.ndarray :return walk_symmetry: Symmetry of walk on [x, y, z] coordinates, defined as the difference between step and stride regularity. :rtype walk_symmetry: numpy.ndarray
[ "This", "method", "extracts", "the", "step", "and", "stride", "regularity", "and", "also", "walk", "symmetry", "." ]
c7120263da2071bb139815fbdb56ca77b544f340
https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/gait_processor.py#L235-L265
train
36,754
pdkit/pdkit
pdkit/gait_processor.py
GaitProcessor.heel_strikes
def heel_strikes(self, x): """ Estimate heel strike times between sign changes in accelerometer data. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return strikes: Heel strike timings measured in seconds. :rtype striles: numpy.ndarray :return strikes_idx: Heel strike timing indices of the time series. :rtype strikes_idx: numpy.ndarray """ # Demean data: data = x.values data -= data.mean() # TODO: fix this # Low-pass filter the AP accelerometer data by the 4th order zero lag # Butterworth filter whose cut frequency is set to 5 Hz: filtered = butter_lowpass_filter(data, self.sampling_frequency, self.cutoff_frequency, self.filter_order) # Find transitional positions where AP accelerometer changes from # positive to negative. transitions = crossings_nonzero_pos2neg(filtered) # Find the peaks of AP acceleration preceding the transitional positions, # and greater than the product of a threshold and the maximum value of # the AP acceleration: strike_indices_smooth = [] filter_threshold = np.abs(self.delta * np.max(filtered)) for i in range(1, np.size(transitions)): segment = range(transitions[i-1], transitions[i]) imax = np.argmax(filtered[segment]) if filtered[segment[imax]] > filter_threshold: strike_indices_smooth.append(segment[imax]) # Compute number of samples between peaks using the real part of the FFT: interpeak = compute_interpeak(data, self.sampling_frequency) decel = np.int(interpeak / 2) # Find maximum peaks close to maximum peaks of smoothed data: strikes_idx = [] for ismooth in strike_indices_smooth: istrike = np.argmax(data[ismooth - decel:ismooth + decel]) istrike = istrike + ismooth - decel strikes_idx.append(istrike) strikes = np.asarray(strikes_idx) strikes -= strikes[0] strikes = strikes / self.sampling_frequency return strikes, np.array(strikes_idx)
python
def heel_strikes(self, x): """ Estimate heel strike times between sign changes in accelerometer data. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return strikes: Heel strike timings measured in seconds. :rtype striles: numpy.ndarray :return strikes_idx: Heel strike timing indices of the time series. :rtype strikes_idx: numpy.ndarray """ # Demean data: data = x.values data -= data.mean() # TODO: fix this # Low-pass filter the AP accelerometer data by the 4th order zero lag # Butterworth filter whose cut frequency is set to 5 Hz: filtered = butter_lowpass_filter(data, self.sampling_frequency, self.cutoff_frequency, self.filter_order) # Find transitional positions where AP accelerometer changes from # positive to negative. transitions = crossings_nonzero_pos2neg(filtered) # Find the peaks of AP acceleration preceding the transitional positions, # and greater than the product of a threshold and the maximum value of # the AP acceleration: strike_indices_smooth = [] filter_threshold = np.abs(self.delta * np.max(filtered)) for i in range(1, np.size(transitions)): segment = range(transitions[i-1], transitions[i]) imax = np.argmax(filtered[segment]) if filtered[segment[imax]] > filter_threshold: strike_indices_smooth.append(segment[imax]) # Compute number of samples between peaks using the real part of the FFT: interpeak = compute_interpeak(data, self.sampling_frequency) decel = np.int(interpeak / 2) # Find maximum peaks close to maximum peaks of smoothed data: strikes_idx = [] for ismooth in strike_indices_smooth: istrike = np.argmax(data[ismooth - decel:ismooth + decel]) istrike = istrike + ismooth - decel strikes_idx.append(istrike) strikes = np.asarray(strikes_idx) strikes -= strikes[0] strikes = strikes / self.sampling_frequency return strikes, np.array(strikes_idx)
[ "def", "heel_strikes", "(", "self", ",", "x", ")", ":", "# Demean data:", "data", "=", "x", ".", "values", "data", "-=", "data", ".", "mean", "(", ")", "# TODO: fix this", "# Low-pass filter the AP accelerometer data by the 4th order zero lag", "# Butterworth filter who...
Estimate heel strike times between sign changes in accelerometer data. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return strikes: Heel strike timings measured in seconds. :rtype striles: numpy.ndarray :return strikes_idx: Heel strike timing indices of the time series. :rtype strikes_idx: numpy.ndarray
[ "Estimate", "heel", "strike", "times", "between", "sign", "changes", "in", "accelerometer", "data", "." ]
c7120263da2071bb139815fbdb56ca77b544f340
https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/gait_processor.py#L314-L364
train
36,755
pdkit/pdkit
pdkit/gait_processor.py
GaitProcessor.gait_regularity_symmetry
def gait_regularity_symmetry(self, x, average_step_duration='autodetect', average_stride_duration='autodetect', unbias=1, normalize=2): """ Compute step and stride regularity and symmetry from accelerometer data with the help of steps and strides. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :param average_step_duration: Average duration of each step using the same time unit as the time series. If this is set to 'autodetect' it will infer this from the time series. :type average_step_duration: float :param average_stride_duration: Average duration of each stride using the same time unit as the time series. If this is set to 'autodetect' it will infer this from the time series. :type average_stride_duration: float :param unbias: Unbiased autocorrelation: divide by range (unbias=1) or by weighted range (unbias=2). :type unbias: int :param int normalize: Normalize: divide by 1st coefficient (normalize=1) or by maximum abs. value (normalize=2). :type normalize: int :return step_regularity: Step regularity measure along axis. :rtype step_regularity: float :return stride_regularity: Stride regularity measure along axis. :rtype stride_regularity: float :return symmetry: Symmetry measure along axis. :rtype symmetry: float """ if (average_step_duration=='autodetect') or (average_stride_duration=='autodetect'): strikes, _ = self.heel_strikes(x) step_durations = [] for i in range(1, np.size(strikes)): step_durations.append(strikes[i] - strikes[i-1]) average_step_duration = np.mean(step_durations) number_of_steps = np.size(strikes) strides1 = strikes[0::2] strides2 = strikes[1::2] stride_durations1 = [] for i in range(1, np.size(strides1)): stride_durations1.append(strides1[i] - strides1[i-1]) stride_durations2 = [] for i in range(1, np.size(strides2)): stride_durations2.append(strides2[i] - strides2[i-1]) strides = [strides1, strides2] stride_durations = [stride_durations1, stride_durations2] average_stride_duration = np.mean((np.mean(stride_durations1), np.mean(stride_durations2))) return self.gait_regularity_symmetry(x, average_step_duration, average_stride_duration) else: coefficients, _ = autocorrelate(x, unbias=1, normalize=2) step_period = np.int(np.round(1 / average_step_duration)) stride_period = np.int(np.round(1 / average_stride_duration)) step_regularity = coefficients[step_period] stride_regularity = coefficients[stride_period] symmetry = np.abs(stride_regularity - step_regularity) return step_regularity, stride_regularity, symmetry
python
def gait_regularity_symmetry(self, x, average_step_duration='autodetect', average_stride_duration='autodetect', unbias=1, normalize=2): """ Compute step and stride regularity and symmetry from accelerometer data with the help of steps and strides. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :param average_step_duration: Average duration of each step using the same time unit as the time series. If this is set to 'autodetect' it will infer this from the time series. :type average_step_duration: float :param average_stride_duration: Average duration of each stride using the same time unit as the time series. If this is set to 'autodetect' it will infer this from the time series. :type average_stride_duration: float :param unbias: Unbiased autocorrelation: divide by range (unbias=1) or by weighted range (unbias=2). :type unbias: int :param int normalize: Normalize: divide by 1st coefficient (normalize=1) or by maximum abs. value (normalize=2). :type normalize: int :return step_regularity: Step regularity measure along axis. :rtype step_regularity: float :return stride_regularity: Stride regularity measure along axis. :rtype stride_regularity: float :return symmetry: Symmetry measure along axis. :rtype symmetry: float """ if (average_step_duration=='autodetect') or (average_stride_duration=='autodetect'): strikes, _ = self.heel_strikes(x) step_durations = [] for i in range(1, np.size(strikes)): step_durations.append(strikes[i] - strikes[i-1]) average_step_duration = np.mean(step_durations) number_of_steps = np.size(strikes) strides1 = strikes[0::2] strides2 = strikes[1::2] stride_durations1 = [] for i in range(1, np.size(strides1)): stride_durations1.append(strides1[i] - strides1[i-1]) stride_durations2 = [] for i in range(1, np.size(strides2)): stride_durations2.append(strides2[i] - strides2[i-1]) strides = [strides1, strides2] stride_durations = [stride_durations1, stride_durations2] average_stride_duration = np.mean((np.mean(stride_durations1), np.mean(stride_durations2))) return self.gait_regularity_symmetry(x, average_step_duration, average_stride_duration) else: coefficients, _ = autocorrelate(x, unbias=1, normalize=2) step_period = np.int(np.round(1 / average_step_duration)) stride_period = np.int(np.round(1 / average_stride_duration)) step_regularity = coefficients[step_period] stride_regularity = coefficients[stride_period] symmetry = np.abs(stride_regularity - step_regularity) return step_regularity, stride_regularity, symmetry
[ "def", "gait_regularity_symmetry", "(", "self", ",", "x", ",", "average_step_duration", "=", "'autodetect'", ",", "average_stride_duration", "=", "'autodetect'", ",", "unbias", "=", "1", ",", "normalize", "=", "2", ")", ":", "if", "(", "average_step_duration", "...
Compute step and stride regularity and symmetry from accelerometer data with the help of steps and strides. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :param average_step_duration: Average duration of each step using the same time unit as the time series. If this is set to 'autodetect' it will infer this from the time series. :type average_step_duration: float :param average_stride_duration: Average duration of each stride using the same time unit as the time series. If this is set to 'autodetect' it will infer this from the time series. :type average_stride_duration: float :param unbias: Unbiased autocorrelation: divide by range (unbias=1) or by weighted range (unbias=2). :type unbias: int :param int normalize: Normalize: divide by 1st coefficient (normalize=1) or by maximum abs. value (normalize=2). :type normalize: int :return step_regularity: Step regularity measure along axis. :rtype step_regularity: float :return stride_regularity: Stride regularity measure along axis. :rtype stride_regularity: float :return symmetry: Symmetry measure along axis. :rtype symmetry: float
[ "Compute", "step", "and", "stride", "regularity", "and", "symmetry", "from", "accelerometer", "data", "with", "the", "help", "of", "steps", "and", "strides", "." ]
c7120263da2071bb139815fbdb56ca77b544f340
https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/gait_processor.py#L366-L428
train
36,756
pdkit/pdkit
pdkit/gait_processor.py
GaitProcessor.gait
def gait(self, x): """ Extract gait features from estimated heel strikes and accelerometer data. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return number_of_steps: Estimated number of steps based on heel strikes [number of steps]. :rtype number_of_steps: int :return velocity: Velocity (if distance is provided) [meters/second]. :rtype velocity: float :return avg_step_length: Average step length (if distance is provided) [meters]. :rtype avg_step_length: float :return avg_stride_length: Average stride length (if distance is provided) [meters]. :rtyoe avg_stride_length: float :return cadence: Number of steps divided by duration [steps/second]. :rtype cadence: float :return array step_durations: Step duration [seconds]. :rtype step_durations: np.ndarray :return float avg_step_duration: Average step duration [seconds]. :rtype avg_step_duration: float :return float sd_step_durations: Standard deviation of step durations [seconds]. :rtype sd_step_durations: np.ndarray :return list strides: Stride timings for each side [seconds]. :rtype strides: numpy.ndarray :return float avg_number_of_strides: Estimated number of strides based on alternating heel strikes [number of strides]. :rtype avg_number_of_strides: float :return list stride_durations: Estimated stride durations [seconds]. :rtype stride_durations: numpy.ndarray :return float avg_stride_duration: Average stride duration [seconds]. :rtype avg_stride_duration: float :return float sd_step_durations: Standard deviation of stride durations [seconds]. :rtype sd_step_duration: float :return float step_regularity: Measure of step regularity along axis [percentage consistency of the step-to-step pattern]. :rtype step_regularity: float :return float stride_regularity: Measure of stride regularity along axis [percentage consistency of the stride-to-stride pattern]. :rtype stride_regularity: float :return float symmetry: Measure of gait symmetry along axis [difference between step and stride regularity]. :rtype symmetry: float """ data = x strikes, _ = self.heel_strikes(data) step_durations = [] for i in range(1, np.size(strikes)): step_durations.append(strikes[i] - strikes[i-1]) avg_step_duration = np.mean(step_durations) sd_step_durations = np.std(step_durations) number_of_steps = np.size(strikes) strides1 = strikes[0::2] strides2 = strikes[1::2] stride_durations1 = [] for i in range(1, np.size(strides1)): stride_durations1.append(strides1[i] - strides1[i-1]) stride_durations2 = [] for i in range(1, np.size(strides2)): stride_durations2.append(strides2[i] - strides2[i-1]) strides = [strides1, strides2] stride_durations = [stride_durations1, stride_durations2] avg_number_of_strides = np.mean([np.size(strides1), np.size(strides2)]) avg_stride_duration = np.mean((np.mean(stride_durations1), np.mean(stride_durations2))) sd_stride_durations = np.mean((np.std(stride_durations1), np.std(stride_durations2))) step_period = np.int(np.round(1 / avg_step_duration)) stride_period = np.int(np.round(1 / avg_stride_duration)) step_regularity, stride_regularity, symmetry = self.gait_regularity_symmetry(data, average_step_duration=avg_step_duration, average_stride_duration=avg_stride_duration) cadence = None if self.duration: cadence = number_of_steps / self.duration velocity = None avg_step_length = None avg_stride_length = None if self.distance: velocity = self.distance / self.duration avg_step_length = number_of_steps / self.distance avg_stride_length = avg_number_of_strides / self.distance return [number_of_steps, cadence, velocity, avg_step_length, avg_stride_length, step_durations, avg_step_duration, sd_step_durations, strides, stride_durations, avg_number_of_strides, avg_stride_duration, sd_stride_durations, step_regularity, stride_regularity, symmetry]
python
def gait(self, x): """ Extract gait features from estimated heel strikes and accelerometer data. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return number_of_steps: Estimated number of steps based on heel strikes [number of steps]. :rtype number_of_steps: int :return velocity: Velocity (if distance is provided) [meters/second]. :rtype velocity: float :return avg_step_length: Average step length (if distance is provided) [meters]. :rtype avg_step_length: float :return avg_stride_length: Average stride length (if distance is provided) [meters]. :rtyoe avg_stride_length: float :return cadence: Number of steps divided by duration [steps/second]. :rtype cadence: float :return array step_durations: Step duration [seconds]. :rtype step_durations: np.ndarray :return float avg_step_duration: Average step duration [seconds]. :rtype avg_step_duration: float :return float sd_step_durations: Standard deviation of step durations [seconds]. :rtype sd_step_durations: np.ndarray :return list strides: Stride timings for each side [seconds]. :rtype strides: numpy.ndarray :return float avg_number_of_strides: Estimated number of strides based on alternating heel strikes [number of strides]. :rtype avg_number_of_strides: float :return list stride_durations: Estimated stride durations [seconds]. :rtype stride_durations: numpy.ndarray :return float avg_stride_duration: Average stride duration [seconds]. :rtype avg_stride_duration: float :return float sd_step_durations: Standard deviation of stride durations [seconds]. :rtype sd_step_duration: float :return float step_regularity: Measure of step regularity along axis [percentage consistency of the step-to-step pattern]. :rtype step_regularity: float :return float stride_regularity: Measure of stride regularity along axis [percentage consistency of the stride-to-stride pattern]. :rtype stride_regularity: float :return float symmetry: Measure of gait symmetry along axis [difference between step and stride regularity]. :rtype symmetry: float """ data = x strikes, _ = self.heel_strikes(data) step_durations = [] for i in range(1, np.size(strikes)): step_durations.append(strikes[i] - strikes[i-1]) avg_step_duration = np.mean(step_durations) sd_step_durations = np.std(step_durations) number_of_steps = np.size(strikes) strides1 = strikes[0::2] strides2 = strikes[1::2] stride_durations1 = [] for i in range(1, np.size(strides1)): stride_durations1.append(strides1[i] - strides1[i-1]) stride_durations2 = [] for i in range(1, np.size(strides2)): stride_durations2.append(strides2[i] - strides2[i-1]) strides = [strides1, strides2] stride_durations = [stride_durations1, stride_durations2] avg_number_of_strides = np.mean([np.size(strides1), np.size(strides2)]) avg_stride_duration = np.mean((np.mean(stride_durations1), np.mean(stride_durations2))) sd_stride_durations = np.mean((np.std(stride_durations1), np.std(stride_durations2))) step_period = np.int(np.round(1 / avg_step_duration)) stride_period = np.int(np.round(1 / avg_stride_duration)) step_regularity, stride_regularity, symmetry = self.gait_regularity_symmetry(data, average_step_duration=avg_step_duration, average_stride_duration=avg_stride_duration) cadence = None if self.duration: cadence = number_of_steps / self.duration velocity = None avg_step_length = None avg_stride_length = None if self.distance: velocity = self.distance / self.duration avg_step_length = number_of_steps / self.distance avg_stride_length = avg_number_of_strides / self.distance return [number_of_steps, cadence, velocity, avg_step_length, avg_stride_length, step_durations, avg_step_duration, sd_step_durations, strides, stride_durations, avg_number_of_strides, avg_stride_duration, sd_stride_durations, step_regularity, stride_regularity, symmetry]
[ "def", "gait", "(", "self", ",", "x", ")", ":", "data", "=", "x", "strikes", ",", "_", "=", "self", ".", "heel_strikes", "(", "data", ")", "step_durations", "=", "[", "]", "for", "i", "in", "range", "(", "1", ",", "np", ".", "size", "(", "strik...
Extract gait features from estimated heel strikes and accelerometer data. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return number_of_steps: Estimated number of steps based on heel strikes [number of steps]. :rtype number_of_steps: int :return velocity: Velocity (if distance is provided) [meters/second]. :rtype velocity: float :return avg_step_length: Average step length (if distance is provided) [meters]. :rtype avg_step_length: float :return avg_stride_length: Average stride length (if distance is provided) [meters]. :rtyoe avg_stride_length: float :return cadence: Number of steps divided by duration [steps/second]. :rtype cadence: float :return array step_durations: Step duration [seconds]. :rtype step_durations: np.ndarray :return float avg_step_duration: Average step duration [seconds]. :rtype avg_step_duration: float :return float sd_step_durations: Standard deviation of step durations [seconds]. :rtype sd_step_durations: np.ndarray :return list strides: Stride timings for each side [seconds]. :rtype strides: numpy.ndarray :return float avg_number_of_strides: Estimated number of strides based on alternating heel strikes [number of strides]. :rtype avg_number_of_strides: float :return list stride_durations: Estimated stride durations [seconds]. :rtype stride_durations: numpy.ndarray :return float avg_stride_duration: Average stride duration [seconds]. :rtype avg_stride_duration: float :return float sd_step_durations: Standard deviation of stride durations [seconds]. :rtype sd_step_duration: float :return float step_regularity: Measure of step regularity along axis [percentage consistency of the step-to-step pattern]. :rtype step_regularity: float :return float stride_regularity: Measure of stride regularity along axis [percentage consistency of the stride-to-stride pattern]. :rtype stride_regularity: float :return float symmetry: Measure of gait symmetry along axis [difference between step and stride regularity]. :rtype symmetry: float
[ "Extract", "gait", "features", "from", "estimated", "heel", "strikes", "and", "accelerometer", "data", "." ]
c7120263da2071bb139815fbdb56ca77b544f340
https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/gait_processor.py#L431-L539
train
36,757
pdkit/pdkit
pdkit/gait_processor.py
GaitProcessor.add_manual_segmentation_to_data_frame
def add_manual_segmentation_to_data_frame(self, data_frame, segmentation_dictionary): """ Utility method to store manual segmentation of gait time series. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :param segmentation_dictionary: A dictionary of the form {'signal_type': [(from, to), (from, to)], ..., 'signal_type': [(from, to), (from, to)]}. The from and to can either be of type numpy.datetime64 or int, depending on how you are segmenting the time series. :type segmentation_dictionary: dict :return: The data_frame with a new column named 'segmentation'. :rtype: pandas.DataFrame """ # add some checks to see if dictionary is in the right format! data_frame['segmentation'] = 'unknown' for i, (k, v) in enumerate(segmentation_dictionary.items()): for start, end in v: if type(start) != np.datetime64: if start < 0: start = 0 if end > data_frame.size: end = data_frame.size start = data_frame.index.values[start] end = data_frame.index.values[end] data_frame.loc[start: end, 'segmentation'] = k return data_frame
python
def add_manual_segmentation_to_data_frame(self, data_frame, segmentation_dictionary): """ Utility method to store manual segmentation of gait time series. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :param segmentation_dictionary: A dictionary of the form {'signal_type': [(from, to), (from, to)], ..., 'signal_type': [(from, to), (from, to)]}. The from and to can either be of type numpy.datetime64 or int, depending on how you are segmenting the time series. :type segmentation_dictionary: dict :return: The data_frame with a new column named 'segmentation'. :rtype: pandas.DataFrame """ # add some checks to see if dictionary is in the right format! data_frame['segmentation'] = 'unknown' for i, (k, v) in enumerate(segmentation_dictionary.items()): for start, end in v: if type(start) != np.datetime64: if start < 0: start = 0 if end > data_frame.size: end = data_frame.size start = data_frame.index.values[start] end = data_frame.index.values[end] data_frame.loc[start: end, 'segmentation'] = k return data_frame
[ "def", "add_manual_segmentation_to_data_frame", "(", "self", ",", "data_frame", ",", "segmentation_dictionary", ")", ":", "# add some checks to see if dictionary is in the right format!", "data_frame", "[", "'segmentation'", "]", "=", "'unknown'", "for", "i", ",", "(", "k",...
Utility method to store manual segmentation of gait time series. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :param segmentation_dictionary: A dictionary of the form {'signal_type': [(from, to), (from, to)], ..., 'signal_type': [(from, to), (from, to)]}. The from and to can either be of type numpy.datetime64 or int, depending on how you are segmenting the time series. :type segmentation_dictionary: dict :return: The data_frame with a new column named 'segmentation'. :rtype: pandas.DataFrame
[ "Utility", "method", "to", "store", "manual", "segmentation", "of", "gait", "time", "series", "." ]
c7120263da2071bb139815fbdb56ca77b544f340
https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/gait_processor.py#L615-L642
train
36,758
twisted/txaws
txaws/client/base.py
error_wrapper
def error_wrapper(error, errorClass): """ We want to see all error messages from cloud services. Amazon's EC2 says that their errors are accompanied either by a 400-series or 500-series HTTP response code. As such, the first thing we want to do is check to see if the error is in that range. If it is, we then need to see if the error message is an EC2 one. In the event that an error is not a Twisted web error nor an EC2 one, the original exception is raised. """ http_status = 0 if error.check(TwistedWebError): xml_payload = error.value.response if error.value.status: http_status = int(error.value.status) else: error.raiseException() if http_status >= 400: if not xml_payload: error.raiseException() try: fallback_error = errorClass( xml_payload, error.value.status, str(error.value), error.value.response) except (ParseError, AWSResponseParseError): error_message = http.RESPONSES.get(http_status) fallback_error = TwistedWebError( http_status, error_message, error.value.response) raise fallback_error elif 200 <= http_status < 300: return str(error.value) else: error.raiseException()
python
def error_wrapper(error, errorClass): """ We want to see all error messages from cloud services. Amazon's EC2 says that their errors are accompanied either by a 400-series or 500-series HTTP response code. As such, the first thing we want to do is check to see if the error is in that range. If it is, we then need to see if the error message is an EC2 one. In the event that an error is not a Twisted web error nor an EC2 one, the original exception is raised. """ http_status = 0 if error.check(TwistedWebError): xml_payload = error.value.response if error.value.status: http_status = int(error.value.status) else: error.raiseException() if http_status >= 400: if not xml_payload: error.raiseException() try: fallback_error = errorClass( xml_payload, error.value.status, str(error.value), error.value.response) except (ParseError, AWSResponseParseError): error_message = http.RESPONSES.get(http_status) fallback_error = TwistedWebError( http_status, error_message, error.value.response) raise fallback_error elif 200 <= http_status < 300: return str(error.value) else: error.raiseException()
[ "def", "error_wrapper", "(", "error", ",", "errorClass", ")", ":", "http_status", "=", "0", "if", "error", ".", "check", "(", "TwistedWebError", ")", ":", "xml_payload", "=", "error", ".", "value", ".", "response", "if", "error", ".", "value", ".", "stat...
We want to see all error messages from cloud services. Amazon's EC2 says that their errors are accompanied either by a 400-series or 500-series HTTP response code. As such, the first thing we want to do is check to see if the error is in that range. If it is, we then need to see if the error message is an EC2 one. In the event that an error is not a Twisted web error nor an EC2 one, the original exception is raised.
[ "We", "want", "to", "see", "all", "error", "messages", "from", "cloud", "services", ".", "Amazon", "s", "EC2", "says", "that", "their", "errors", "are", "accompanied", "either", "by", "a", "400", "-", "series", "or", "500", "-", "series", "HTTP", "respon...
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/client/base.py#L46-L79
train
36,759
twisted/txaws
txaws/client/base.py
BaseQuery._headers
def _headers(self, headers_dict): """ Convert dictionary of headers into twisted.web.client.Headers object. """ return Headers(dict((k,[v]) for (k,v) in headers_dict.items()))
python
def _headers(self, headers_dict): """ Convert dictionary of headers into twisted.web.client.Headers object. """ return Headers(dict((k,[v]) for (k,v) in headers_dict.items()))
[ "def", "_headers", "(", "self", ",", "headers_dict", ")", ":", "return", "Headers", "(", "dict", "(", "(", "k", ",", "[", "v", "]", ")", "for", "(", "k", ",", "v", ")", "in", "headers_dict", ".", "items", "(", ")", ")", ")" ]
Convert dictionary of headers into twisted.web.client.Headers object.
[ "Convert", "dictionary", "of", "headers", "into", "twisted", ".", "web", ".", "client", ".", "Headers", "object", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/client/base.py#L692-L696
train
36,760
twisted/txaws
txaws/client/base.py
BaseQuery._unpack_headers
def _unpack_headers(self, headers): """ Unpack twisted.web.client.Headers object to dict. This is to provide backwards compatability. """ return dict((k,v[0]) for (k,v) in headers.getAllRawHeaders())
python
def _unpack_headers(self, headers): """ Unpack twisted.web.client.Headers object to dict. This is to provide backwards compatability. """ return dict((k,v[0]) for (k,v) in headers.getAllRawHeaders())
[ "def", "_unpack_headers", "(", "self", ",", "headers", ")", ":", "return", "dict", "(", "(", "k", ",", "v", "[", "0", "]", ")", "for", "(", "k", ",", "v", ")", "in", "headers", ".", "getAllRawHeaders", "(", ")", ")" ]
Unpack twisted.web.client.Headers object to dict. This is to provide backwards compatability.
[ "Unpack", "twisted", ".", "web", ".", "client", ".", "Headers", "object", "to", "dict", ".", "This", "is", "to", "provide", "backwards", "compatability", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/client/base.py#L698-L703
train
36,761
twisted/txaws
txaws/client/base.py
BaseQuery.get_request_headers
def get_request_headers(self, *args, **kwds): """ A convenience method for obtaining the headers that were sent to the S3 server. The AWS S3 API depends upon setting headers. This method is provided as a convenience for debugging issues with the S3 communications. """ if self.request_headers: return self._unpack_headers(self.request_headers)
python
def get_request_headers(self, *args, **kwds): """ A convenience method for obtaining the headers that were sent to the S3 server. The AWS S3 API depends upon setting headers. This method is provided as a convenience for debugging issues with the S3 communications. """ if self.request_headers: return self._unpack_headers(self.request_headers)
[ "def", "get_request_headers", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "self", ".", "request_headers", ":", "return", "self", ".", "_unpack_headers", "(", "self", ".", "request_headers", ")" ]
A convenience method for obtaining the headers that were sent to the S3 server. The AWS S3 API depends upon setting headers. This method is provided as a convenience for debugging issues with the S3 communications.
[ "A", "convenience", "method", "for", "obtaining", "the", "headers", "that", "were", "sent", "to", "the", "S3", "server", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/client/base.py#L705-L714
train
36,762
twisted/txaws
txaws/client/base.py
BaseQuery._handle_response
def _handle_response(self, response): """ Handle the HTTP response by memoing the headers and then delivering bytes. """ self.client.status = response.code self.response_headers = response.headers # XXX This workaround (which needs to be improved at that) for possible # bug in Twisted with new client: # http://twistedmatrix.com/trac/ticket/5476 if self._method.upper() == 'HEAD' or response.code == NO_CONTENT: return succeed('') receiver = self.receiver_factory() receiver.finished = d = Deferred() receiver.content_length = response.length response.deliverBody(receiver) if response.code >= 400: d.addCallback(self._fail_response, response) return d
python
def _handle_response(self, response): """ Handle the HTTP response by memoing the headers and then delivering bytes. """ self.client.status = response.code self.response_headers = response.headers # XXX This workaround (which needs to be improved at that) for possible # bug in Twisted with new client: # http://twistedmatrix.com/trac/ticket/5476 if self._method.upper() == 'HEAD' or response.code == NO_CONTENT: return succeed('') receiver = self.receiver_factory() receiver.finished = d = Deferred() receiver.content_length = response.length response.deliverBody(receiver) if response.code >= 400: d.addCallback(self._fail_response, response) return d
[ "def", "_handle_response", "(", "self", ",", "response", ")", ":", "self", ".", "client", ".", "status", "=", "response", ".", "code", "self", ".", "response_headers", "=", "response", ".", "headers", "# XXX This workaround (which needs to be improved at that) for pos...
Handle the HTTP response by memoing the headers and then delivering bytes.
[ "Handle", "the", "HTTP", "response", "by", "memoing", "the", "headers", "and", "then", "delivering", "bytes", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/client/base.py#L716-L734
train
36,763
twisted/txaws
txaws/client/base.py
BaseQuery.get_response_headers
def get_response_headers(self, *args, **kwargs): """ A convenience method for obtaining the headers that were sent from the S3 server. The AWS S3 API depends upon setting headers. This method is used by the head_object API call for getting a S3 object's metadata. """ if self.response_headers: return self._unpack_headers(self.response_headers)
python
def get_response_headers(self, *args, **kwargs): """ A convenience method for obtaining the headers that were sent from the S3 server. The AWS S3 API depends upon setting headers. This method is used by the head_object API call for getting a S3 object's metadata. """ if self.response_headers: return self._unpack_headers(self.response_headers)
[ "def", "get_response_headers", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "response_headers", ":", "return", "self", ".", "_unpack_headers", "(", "self", ".", "response_headers", ")" ]
A convenience method for obtaining the headers that were sent from the S3 server. The AWS S3 API depends upon setting headers. This method is used by the head_object API call for getting a S3 object's metadata.
[ "A", "convenience", "method", "for", "obtaining", "the", "headers", "that", "were", "sent", "from", "the", "S3", "server", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/client/base.py#L740-L749
train
36,764
alphagov/notifications-python-client
notifications_python_client/authentication.py
create_jwt_token
def create_jwt_token(secret, client_id): """ Create JWT token for GOV.UK Notify Tokens have standard header: { "typ": "JWT", "alg": "HS256" } Claims consist of: iss: identifier for the client iat: issued at in epoch seconds (UTC) :param secret: Application signing secret :param client_id: Identifier for the client :return: JWT token for this request """ assert secret, "Missing secret key" assert client_id, "Missing client id" headers = { "typ": __type__, "alg": __algorithm__ } claims = { 'iss': client_id, 'iat': epoch_seconds() } return jwt.encode(payload=claims, key=secret, headers=headers).decode()
python
def create_jwt_token(secret, client_id): """ Create JWT token for GOV.UK Notify Tokens have standard header: { "typ": "JWT", "alg": "HS256" } Claims consist of: iss: identifier for the client iat: issued at in epoch seconds (UTC) :param secret: Application signing secret :param client_id: Identifier for the client :return: JWT token for this request """ assert secret, "Missing secret key" assert client_id, "Missing client id" headers = { "typ": __type__, "alg": __algorithm__ } claims = { 'iss': client_id, 'iat': epoch_seconds() } return jwt.encode(payload=claims, key=secret, headers=headers).decode()
[ "def", "create_jwt_token", "(", "secret", ",", "client_id", ")", ":", "assert", "secret", ",", "\"Missing secret key\"", "assert", "client_id", ",", "\"Missing client id\"", "headers", "=", "{", "\"typ\"", ":", "__type__", ",", "\"alg\"", ":", "__algorithm__", "}"...
Create JWT token for GOV.UK Notify Tokens have standard header: { "typ": "JWT", "alg": "HS256" } Claims consist of: iss: identifier for the client iat: issued at in epoch seconds (UTC) :param secret: Application signing secret :param client_id: Identifier for the client :return: JWT token for this request
[ "Create", "JWT", "token", "for", "GOV", ".", "UK", "Notify" ]
b397aed212acf15b1b1e049da2654d9a230f72d2
https://github.com/alphagov/notifications-python-client/blob/b397aed212acf15b1b1e049da2654d9a230f72d2/notifications_python_client/authentication.py#L25-L56
train
36,765
alphagov/notifications-python-client
notifications_python_client/authentication.py
decode_jwt_token
def decode_jwt_token(token, secret): """ Validates and decodes the JWT token Token checked for - signature of JWT token - token issued date is valid :param token: jwt token :param secret: client specific secret :return boolean: True if valid token, False otherwise :raises TokenIssuerError: if iss field not present :raises TokenIssuedAtError: if iat field not present :raises jwt.DecodeError: If signature validation fails """ try: # check signature of the token decoded_token = jwt.decode( token, key=secret.encode(), verify=True, algorithms=[__algorithm__], leeway=__bound__ ) # token has all the required fields if 'iss' not in decoded_token: raise TokenIssuerError if 'iat' not in decoded_token: raise TokenIssuedAtError # check iat time is within bounds now = epoch_seconds() iat = int(decoded_token['iat']) if now > (iat + __bound__): raise TokenExpiredError("Token has expired", decoded_token) if iat > (now + __bound__): raise TokenExpiredError("Token can not be in the future", decoded_token) return True except jwt.InvalidIssuedAtError: raise TokenExpiredError("Token has invalid iat field", decode_token(token)) except jwt.DecodeError: raise TokenDecodeError
python
def decode_jwt_token(token, secret): """ Validates and decodes the JWT token Token checked for - signature of JWT token - token issued date is valid :param token: jwt token :param secret: client specific secret :return boolean: True if valid token, False otherwise :raises TokenIssuerError: if iss field not present :raises TokenIssuedAtError: if iat field not present :raises jwt.DecodeError: If signature validation fails """ try: # check signature of the token decoded_token = jwt.decode( token, key=secret.encode(), verify=True, algorithms=[__algorithm__], leeway=__bound__ ) # token has all the required fields if 'iss' not in decoded_token: raise TokenIssuerError if 'iat' not in decoded_token: raise TokenIssuedAtError # check iat time is within bounds now = epoch_seconds() iat = int(decoded_token['iat']) if now > (iat + __bound__): raise TokenExpiredError("Token has expired", decoded_token) if iat > (now + __bound__): raise TokenExpiredError("Token can not be in the future", decoded_token) return True except jwt.InvalidIssuedAtError: raise TokenExpiredError("Token has invalid iat field", decode_token(token)) except jwt.DecodeError: raise TokenDecodeError
[ "def", "decode_jwt_token", "(", "token", ",", "secret", ")", ":", "try", ":", "# check signature of the token", "decoded_token", "=", "jwt", ".", "decode", "(", "token", ",", "key", "=", "secret", ".", "encode", "(", ")", ",", "verify", "=", "True", ",", ...
Validates and decodes the JWT token Token checked for - signature of JWT token - token issued date is valid :param token: jwt token :param secret: client specific secret :return boolean: True if valid token, False otherwise :raises TokenIssuerError: if iss field not present :raises TokenIssuedAtError: if iat field not present :raises jwt.DecodeError: If signature validation fails
[ "Validates", "and", "decodes", "the", "JWT", "token", "Token", "checked", "for", "-", "signature", "of", "JWT", "token", "-", "token", "issued", "date", "is", "valid" ]
b397aed212acf15b1b1e049da2654d9a230f72d2
https://github.com/alphagov/notifications-python-client/blob/b397aed212acf15b1b1e049da2654d9a230f72d2/notifications_python_client/authentication.py#L80-L121
train
36,766
apertium/streamparser
streamparser.py
parse
def parse(stream, with_text=False): # type: (Iterator[str], bool) -> Iterator[Union[Tuple[str, LexicalUnit], LexicalUnit]] """Generates lexical units from a character stream. Args: stream (Iterator[str]): A character stream containing lexical units, superblanks and other text. with_text (Optional[bool]): A boolean defining whether to output preceding text with each lexical unit. Yields: :class:`LexicalUnit`: The next lexical unit found in the character stream. (if `with_text` is False) \n *(str, LexicalUnit)* - The next lexical unit found in the character stream and the the text that seperated it from the prior unit in a tuple. (if with_text is True) """ buffer = '' text_buffer = '' in_lexical_unit = False in_superblank = False for char in stream: if in_superblank: if char == ']': in_superblank = False text_buffer += char elif char == '\\': text_buffer += char text_buffer += next(stream) else: text_buffer += char elif in_lexical_unit: if char == '$': if with_text: yield (text_buffer, LexicalUnit(buffer)) else: yield LexicalUnit(buffer) buffer = '' text_buffer = '' in_lexical_unit = False elif char == '\\': buffer += char buffer += next(stream) else: buffer += char else: if char == '[': in_superblank = True text_buffer += char elif char == '^': in_lexical_unit = True elif char == '\\': text_buffer += char text_buffer += next(stream) else: text_buffer += char
python
def parse(stream, with_text=False): # type: (Iterator[str], bool) -> Iterator[Union[Tuple[str, LexicalUnit], LexicalUnit]] """Generates lexical units from a character stream. Args: stream (Iterator[str]): A character stream containing lexical units, superblanks and other text. with_text (Optional[bool]): A boolean defining whether to output preceding text with each lexical unit. Yields: :class:`LexicalUnit`: The next lexical unit found in the character stream. (if `with_text` is False) \n *(str, LexicalUnit)* - The next lexical unit found in the character stream and the the text that seperated it from the prior unit in a tuple. (if with_text is True) """ buffer = '' text_buffer = '' in_lexical_unit = False in_superblank = False for char in stream: if in_superblank: if char == ']': in_superblank = False text_buffer += char elif char == '\\': text_buffer += char text_buffer += next(stream) else: text_buffer += char elif in_lexical_unit: if char == '$': if with_text: yield (text_buffer, LexicalUnit(buffer)) else: yield LexicalUnit(buffer) buffer = '' text_buffer = '' in_lexical_unit = False elif char == '\\': buffer += char buffer += next(stream) else: buffer += char else: if char == '[': in_superblank = True text_buffer += char elif char == '^': in_lexical_unit = True elif char == '\\': text_buffer += char text_buffer += next(stream) else: text_buffer += char
[ "def", "parse", "(", "stream", ",", "with_text", "=", "False", ")", ":", "# type: (Iterator[str], bool) -> Iterator[Union[Tuple[str, LexicalUnit], LexicalUnit]]", "buffer", "=", "''", "text_buffer", "=", "''", "in_lexical_unit", "=", "False", "in_superblank", "=", "False"...
Generates lexical units from a character stream. Args: stream (Iterator[str]): A character stream containing lexical units, superblanks and other text. with_text (Optional[bool]): A boolean defining whether to output preceding text with each lexical unit. Yields: :class:`LexicalUnit`: The next lexical unit found in the character stream. (if `with_text` is False) \n *(str, LexicalUnit)* - The next lexical unit found in the character stream and the the text that seperated it from the prior unit in a tuple. (if with_text is True)
[ "Generates", "lexical", "units", "from", "a", "character", "stream", "." ]
dd9d1566af47b8b2babbc172b42706579d52e422
https://github.com/apertium/streamparser/blob/dd9d1566af47b8b2babbc172b42706579d52e422/streamparser.py#L187-L239
train
36,767
T-002/pycast
pycast/common/timeseries.py
TimeSeries.from_twodim_list
def from_twodim_list(cls, datalist, tsformat=None): """Creates a new TimeSeries instance from the data stored inside a two dimensional list. :param list datalist: List containing multiple iterables with at least two values. The first item will always be used as timestamp in the predefined format, the second represents the value. All other items in those sublists will be ignored. :param string tsformat: Format of the given timestamp. This is used to convert the timestamp into UNIX epochs, if necessary. For valid examples take a look into the :py:func:`time.strptime` documentation. :return: Returns a TimeSeries instance containing the data from datalist. :rtype: TimeSeries """ # create and fill the given TimeSeries ts = TimeSeries() ts.set_timeformat(tsformat) for entry in datalist: ts.add_entry(*entry[:2]) # set the normalization level ts._normalized = ts.is_normalized() ts.sort_timeseries() return ts
python
def from_twodim_list(cls, datalist, tsformat=None): """Creates a new TimeSeries instance from the data stored inside a two dimensional list. :param list datalist: List containing multiple iterables with at least two values. The first item will always be used as timestamp in the predefined format, the second represents the value. All other items in those sublists will be ignored. :param string tsformat: Format of the given timestamp. This is used to convert the timestamp into UNIX epochs, if necessary. For valid examples take a look into the :py:func:`time.strptime` documentation. :return: Returns a TimeSeries instance containing the data from datalist. :rtype: TimeSeries """ # create and fill the given TimeSeries ts = TimeSeries() ts.set_timeformat(tsformat) for entry in datalist: ts.add_entry(*entry[:2]) # set the normalization level ts._normalized = ts.is_normalized() ts.sort_timeseries() return ts
[ "def", "from_twodim_list", "(", "cls", ",", "datalist", ",", "tsformat", "=", "None", ")", ":", "# create and fill the given TimeSeries", "ts", "=", "TimeSeries", "(", ")", "ts", ".", "set_timeformat", "(", "tsformat", ")", "for", "entry", "in", "datalist", ":...
Creates a new TimeSeries instance from the data stored inside a two dimensional list. :param list datalist: List containing multiple iterables with at least two values. The first item will always be used as timestamp in the predefined format, the second represents the value. All other items in those sublists will be ignored. :param string tsformat: Format of the given timestamp. This is used to convert the timestamp into UNIX epochs, if necessary. For valid examples take a look into the :py:func:`time.strptime` documentation. :return: Returns a TimeSeries instance containing the data from datalist. :rtype: TimeSeries
[ "Creates", "a", "new", "TimeSeries", "instance", "from", "the", "data", "stored", "inside", "a", "two", "dimensional", "list", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/timeseries.py#L170-L194
train
36,768
T-002/pycast
pycast/common/timeseries.py
TimeSeries.initialize_from_sql_cursor
def initialize_from_sql_cursor(self, sqlcursor): """Initializes the TimeSeries's data from the given SQL cursor. You need to set the time stamp format using :py:meth:`TimeSeries.set_timeformat`. :param SQLCursor sqlcursor: Cursor that was holds the SQL result for any given "SELECT timestamp, value, ... FROM ..." SQL query. Only the first two attributes of the SQL result will be used. :return: Returns the number of entries added to the TimeSeries. :rtype: integer """ # initialize the result tuples = 0 # add the SQL result to the time series data = sqlcursor.fetchmany() while 0 < len(data): for entry in data: self.add_entry(str(entry[0]), entry[1]) data = sqlcursor.fetchmany() # set the normalization level self._normalized = self._check_normalization # return the number of tuples added to the timeseries. return tuples
python
def initialize_from_sql_cursor(self, sqlcursor): """Initializes the TimeSeries's data from the given SQL cursor. You need to set the time stamp format using :py:meth:`TimeSeries.set_timeformat`. :param SQLCursor sqlcursor: Cursor that was holds the SQL result for any given "SELECT timestamp, value, ... FROM ..." SQL query. Only the first two attributes of the SQL result will be used. :return: Returns the number of entries added to the TimeSeries. :rtype: integer """ # initialize the result tuples = 0 # add the SQL result to the time series data = sqlcursor.fetchmany() while 0 < len(data): for entry in data: self.add_entry(str(entry[0]), entry[1]) data = sqlcursor.fetchmany() # set the normalization level self._normalized = self._check_normalization # return the number of tuples added to the timeseries. return tuples
[ "def", "initialize_from_sql_cursor", "(", "self", ",", "sqlcursor", ")", ":", "# initialize the result", "tuples", "=", "0", "# add the SQL result to the time series", "data", "=", "sqlcursor", ".", "fetchmany", "(", ")", "while", "0", "<", "len", "(", "data", ")"...
Initializes the TimeSeries's data from the given SQL cursor. You need to set the time stamp format using :py:meth:`TimeSeries.set_timeformat`. :param SQLCursor sqlcursor: Cursor that was holds the SQL result for any given "SELECT timestamp, value, ... FROM ..." SQL query. Only the first two attributes of the SQL result will be used. :return: Returns the number of entries added to the TimeSeries. :rtype: integer
[ "Initializes", "the", "TimeSeries", "s", "data", "from", "the", "given", "SQL", "cursor", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/timeseries.py#L196-L223
train
36,769
T-002/pycast
pycast/common/timeseries.py
TimeSeries.convert_timestamp_to_epoch
def convert_timestamp_to_epoch(cls, timestamp, tsformat): """Converts the given timestamp into a float representing UNIX-epochs. :param string timestamp: Timestamp in the defined format. :param string tsformat: Format of the given timestamp. This is used to convert the timestamp into UNIX epochs. For valid examples take a look into the :py:func:`time.strptime` documentation. :return: Returns an float, representing the UNIX-epochs for the given timestamp. :rtype: float """ return time.mktime(time.strptime(timestamp, tsformat))
python
def convert_timestamp_to_epoch(cls, timestamp, tsformat): """Converts the given timestamp into a float representing UNIX-epochs. :param string timestamp: Timestamp in the defined format. :param string tsformat: Format of the given timestamp. This is used to convert the timestamp into UNIX epochs. For valid examples take a look into the :py:func:`time.strptime` documentation. :return: Returns an float, representing the UNIX-epochs for the given timestamp. :rtype: float """ return time.mktime(time.strptime(timestamp, tsformat))
[ "def", "convert_timestamp_to_epoch", "(", "cls", ",", "timestamp", ",", "tsformat", ")", ":", "return", "time", ".", "mktime", "(", "time", ".", "strptime", "(", "timestamp", ",", "tsformat", ")", ")" ]
Converts the given timestamp into a float representing UNIX-epochs. :param string timestamp: Timestamp in the defined format. :param string tsformat: Format of the given timestamp. This is used to convert the timestamp into UNIX epochs. For valid examples take a look into the :py:func:`time.strptime` documentation. :return: Returns an float, representing the UNIX-epochs for the given timestamp. :rtype: float
[ "Converts", "the", "given", "timestamp", "into", "a", "float", "representing", "UNIX", "-", "epochs", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/timeseries.py#L323-L335
train
36,770
T-002/pycast
pycast/common/timeseries.py
TimeSeries.convert_epoch_to_timestamp
def convert_epoch_to_timestamp(cls, timestamp, tsformat): """Converts the given float representing UNIX-epochs into an actual timestamp. :param float timestamp: Timestamp as UNIX-epochs. :param string tsformat: Format of the given timestamp. This is used to convert the timestamp from UNIX epochs. For valid examples take a look into the :py:func:`time.strptime` documentation. :return: Returns the timestamp as defined in format. :rtype: string """ return time.strftime(tsformat, time.gmtime(timestamp))
python
def convert_epoch_to_timestamp(cls, timestamp, tsformat): """Converts the given float representing UNIX-epochs into an actual timestamp. :param float timestamp: Timestamp as UNIX-epochs. :param string tsformat: Format of the given timestamp. This is used to convert the timestamp from UNIX epochs. For valid examples take a look into the :py:func:`time.strptime` documentation. :return: Returns the timestamp as defined in format. :rtype: string """ return time.strftime(tsformat, time.gmtime(timestamp))
[ "def", "convert_epoch_to_timestamp", "(", "cls", ",", "timestamp", ",", "tsformat", ")", ":", "return", "time", ".", "strftime", "(", "tsformat", ",", "time", ".", "gmtime", "(", "timestamp", ")", ")" ]
Converts the given float representing UNIX-epochs into an actual timestamp. :param float timestamp: Timestamp as UNIX-epochs. :param string tsformat: Format of the given timestamp. This is used to convert the timestamp from UNIX epochs. For valid examples take a look into the :py:func:`time.strptime` documentation. :return: Returns the timestamp as defined in format. :rtype: string
[ "Converts", "the", "given", "float", "representing", "UNIX", "-", "epochs", "into", "an", "actual", "timestamp", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/timeseries.py#L338-L349
train
36,771
T-002/pycast
pycast/common/timeseries.py
TimeSeries.sort_timeseries
def sort_timeseries(self, ascending=True): """Sorts the data points within the TimeSeries according to their occurrence inline. :param boolean ascending: Determines if the TimeSeries will be ordered ascending or descending. If this is set to descending once, the ordered parameter defined in :py:meth:`TimeSeries.__init__` will be set to False FOREVER. :return: Returns :py:obj:`self` for convenience. :rtype: TimeSeries """ # the time series is sorted by default if ascending and self._sorted: return sortorder = 1 if not ascending: sortorder = -1 self._predefinedSorted = False self._timeseriesData.sort(key=lambda i: sortorder * i[0]) self._sorted = ascending return self
python
def sort_timeseries(self, ascending=True): """Sorts the data points within the TimeSeries according to their occurrence inline. :param boolean ascending: Determines if the TimeSeries will be ordered ascending or descending. If this is set to descending once, the ordered parameter defined in :py:meth:`TimeSeries.__init__` will be set to False FOREVER. :return: Returns :py:obj:`self` for convenience. :rtype: TimeSeries """ # the time series is sorted by default if ascending and self._sorted: return sortorder = 1 if not ascending: sortorder = -1 self._predefinedSorted = False self._timeseriesData.sort(key=lambda i: sortorder * i[0]) self._sorted = ascending return self
[ "def", "sort_timeseries", "(", "self", ",", "ascending", "=", "True", ")", ":", "# the time series is sorted by default", "if", "ascending", "and", "self", ".", "_sorted", ":", "return", "sortorder", "=", "1", "if", "not", "ascending", ":", "sortorder", "=", "...
Sorts the data points within the TimeSeries according to their occurrence inline. :param boolean ascending: Determines if the TimeSeries will be ordered ascending or descending. If this is set to descending once, the ordered parameter defined in :py:meth:`TimeSeries.__init__` will be set to False FOREVER. :return: Returns :py:obj:`self` for convenience. :rtype: TimeSeries
[ "Sorts", "the", "data", "points", "within", "the", "TimeSeries", "according", "to", "their", "occurrence", "inline", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/timeseries.py#L368-L391
train
36,772
T-002/pycast
pycast/common/timeseries.py
TimeSeries.sorted_timeseries
def sorted_timeseries(self, ascending=True): """Returns a sorted copy of the TimeSeries, preserving the original one. As an assumption this new TimeSeries is not ordered anymore if a new value is added. :param boolean ascending: Determines if the TimeSeries will be ordered ascending or descending. :return: Returns a new TimeSeries instance sorted in the requested order. :rtype: TimeSeries """ sortorder = 1 if not ascending: sortorder = -1 data = sorted(self._timeseriesData, key=lambda i: sortorder * i[0]) newTS = TimeSeries(self._normalized) for entry in data: newTS.add_entry(*entry) newTS._sorted = ascending return newTS
python
def sorted_timeseries(self, ascending=True): """Returns a sorted copy of the TimeSeries, preserving the original one. As an assumption this new TimeSeries is not ordered anymore if a new value is added. :param boolean ascending: Determines if the TimeSeries will be ordered ascending or descending. :return: Returns a new TimeSeries instance sorted in the requested order. :rtype: TimeSeries """ sortorder = 1 if not ascending: sortorder = -1 data = sorted(self._timeseriesData, key=lambda i: sortorder * i[0]) newTS = TimeSeries(self._normalized) for entry in data: newTS.add_entry(*entry) newTS._sorted = ascending return newTS
[ "def", "sorted_timeseries", "(", "self", ",", "ascending", "=", "True", ")", ":", "sortorder", "=", "1", "if", "not", "ascending", ":", "sortorder", "=", "-", "1", "data", "=", "sorted", "(", "self", ".", "_timeseriesData", ",", "key", "=", "lambda", "...
Returns a sorted copy of the TimeSeries, preserving the original one. As an assumption this new TimeSeries is not ordered anymore if a new value is added. :param boolean ascending: Determines if the TimeSeries will be ordered ascending or descending. :return: Returns a new TimeSeries instance sorted in the requested order. :rtype: TimeSeries
[ "Returns", "a", "sorted", "copy", "of", "the", "TimeSeries", "preserving", "the", "original", "one", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/timeseries.py#L393-L416
train
36,773
T-002/pycast
pycast/common/timeseries.py
TimeSeries.normalize
def normalize(self, normalizationLevel="minute", fusionMethod="mean", interpolationMethod="linear"): """Normalizes the TimeSeries data points. If this function is called, the TimeSeries gets ordered ascending automatically. The new timestamps will represent the center of each time bucket. Within a normalized TimeSeries, the temporal distance between two consecutive data points is constant. :param string normalizationLevel: Level of normalization that has to be applied. The available normalization levels are defined in :py:data:`timeseries.NormalizationLevels`. :param string fusionMethod: Normalization method that has to be used if multiple data entries exist within the same normalization bucket. The available methods are defined in :py:data:`timeseries.FusionMethods`. :param string interpolationMethod: Interpolation method that is used if a data entry at a specific time is missing. The available interpolation methods are defined in :py:data:`timeseries.InterpolationMethods`. :raise: Raises a :py:exc:`ValueError` if a normalizationLevel, fusionMethod or interpolationMethod hanve an unknown value. """ # do not normalize the TimeSeries if it is already normalized, either by # definition or a prior call of normalize(*) if self._normalizationLevel == normalizationLevel: if self._normalized: # pragma: no cover return # check if all parameters are defined correctly if normalizationLevel not in NormalizationLevels: raise ValueError("Normalization level %s is unknown." % normalizationLevel) if fusionMethod not in FusionMethods: raise ValueError("Fusion method %s is unknown." % fusionMethod) if interpolationMethod not in InterpolationMethods: raise ValueError("Interpolation method %s is unknown." % interpolationMethod) # (nearly) empty TimeSeries instances do not require normalization if len(self) < 2: self._normalized = True return # get the defined methods and parameter self._normalizationLevel = normalizationLevel normalizationLevel = NormalizationLevels[normalizationLevel] fusionMethod = FusionMethods[fusionMethod] interpolationMethod = InterpolationMethods[interpolationMethod] # sort the TimeSeries self.sort_timeseries() # prepare the required buckets start = self._timeseriesData[0][0] end = self._timeseriesData[-1][0] span = end - start bucketcnt = int(span / normalizationLevel) + 1 buckethalfwidth = normalizationLevel / 2.0 bucketstart = start + buckethalfwidth buckets = [[bucketstart + idx * normalizationLevel] for idx in xrange(bucketcnt)] # Step One: Populate buckets # Initialize the timeseries data iterators tsdStartIdx = 0 tsdEndIdx = 0 tsdlength = len(self) for idx in xrange(bucketcnt): # get the bucket to avoid multiple calls of buckets.__getitem__() bucket = buckets[idx] # get the range for the given bucket bucketend = bucket[0] + buckethalfwidth while tsdEndIdx < tsdlength and self._timeseriesData[tsdEndIdx][0] < bucketend: tsdEndIdx += 1 # continue, if no valid data entries exist if tsdStartIdx == tsdEndIdx: continue # use the given fusion method to calculate the fusioned value values = [i[1] for i in self._timeseriesData[tsdStartIdx:tsdEndIdx]] bucket.append(fusionMethod(values)) # set the new timeseries data index tsdStartIdx = tsdEndIdx # Step Two: Fill missing buckets missingCount = 0 lastIdx = 0 for idx in xrange(bucketcnt): # bucket is empty if 1 == len(buckets[idx]): missingCount += 1 continue # This is the first bucket. The first bucket is not empty by definition! if idx == 0: lastIdx = idx continue # update the lastIdx, if none was missing if 0 == missingCount: lastIdx = idx continue # calculate and fill in missing values missingValues = interpolationMethod(buckets[lastIdx][1], buckets[idx][1], missingCount) for idx2 in xrange(1, missingCount + 1): buckets[lastIdx + idx2].append(missingValues[idx2 - 1]) lastIdx = idx missingCount = 0 self._timeseriesData = buckets # at the end set self._normalized to True self._normalized = True
python
def normalize(self, normalizationLevel="minute", fusionMethod="mean", interpolationMethod="linear"): """Normalizes the TimeSeries data points. If this function is called, the TimeSeries gets ordered ascending automatically. The new timestamps will represent the center of each time bucket. Within a normalized TimeSeries, the temporal distance between two consecutive data points is constant. :param string normalizationLevel: Level of normalization that has to be applied. The available normalization levels are defined in :py:data:`timeseries.NormalizationLevels`. :param string fusionMethod: Normalization method that has to be used if multiple data entries exist within the same normalization bucket. The available methods are defined in :py:data:`timeseries.FusionMethods`. :param string interpolationMethod: Interpolation method that is used if a data entry at a specific time is missing. The available interpolation methods are defined in :py:data:`timeseries.InterpolationMethods`. :raise: Raises a :py:exc:`ValueError` if a normalizationLevel, fusionMethod or interpolationMethod hanve an unknown value. """ # do not normalize the TimeSeries if it is already normalized, either by # definition or a prior call of normalize(*) if self._normalizationLevel == normalizationLevel: if self._normalized: # pragma: no cover return # check if all parameters are defined correctly if normalizationLevel not in NormalizationLevels: raise ValueError("Normalization level %s is unknown." % normalizationLevel) if fusionMethod not in FusionMethods: raise ValueError("Fusion method %s is unknown." % fusionMethod) if interpolationMethod not in InterpolationMethods: raise ValueError("Interpolation method %s is unknown." % interpolationMethod) # (nearly) empty TimeSeries instances do not require normalization if len(self) < 2: self._normalized = True return # get the defined methods and parameter self._normalizationLevel = normalizationLevel normalizationLevel = NormalizationLevels[normalizationLevel] fusionMethod = FusionMethods[fusionMethod] interpolationMethod = InterpolationMethods[interpolationMethod] # sort the TimeSeries self.sort_timeseries() # prepare the required buckets start = self._timeseriesData[0][0] end = self._timeseriesData[-1][0] span = end - start bucketcnt = int(span / normalizationLevel) + 1 buckethalfwidth = normalizationLevel / 2.0 bucketstart = start + buckethalfwidth buckets = [[bucketstart + idx * normalizationLevel] for idx in xrange(bucketcnt)] # Step One: Populate buckets # Initialize the timeseries data iterators tsdStartIdx = 0 tsdEndIdx = 0 tsdlength = len(self) for idx in xrange(bucketcnt): # get the bucket to avoid multiple calls of buckets.__getitem__() bucket = buckets[idx] # get the range for the given bucket bucketend = bucket[0] + buckethalfwidth while tsdEndIdx < tsdlength and self._timeseriesData[tsdEndIdx][0] < bucketend: tsdEndIdx += 1 # continue, if no valid data entries exist if tsdStartIdx == tsdEndIdx: continue # use the given fusion method to calculate the fusioned value values = [i[1] for i in self._timeseriesData[tsdStartIdx:tsdEndIdx]] bucket.append(fusionMethod(values)) # set the new timeseries data index tsdStartIdx = tsdEndIdx # Step Two: Fill missing buckets missingCount = 0 lastIdx = 0 for idx in xrange(bucketcnt): # bucket is empty if 1 == len(buckets[idx]): missingCount += 1 continue # This is the first bucket. The first bucket is not empty by definition! if idx == 0: lastIdx = idx continue # update the lastIdx, if none was missing if 0 == missingCount: lastIdx = idx continue # calculate and fill in missing values missingValues = interpolationMethod(buckets[lastIdx][1], buckets[idx][1], missingCount) for idx2 in xrange(1, missingCount + 1): buckets[lastIdx + idx2].append(missingValues[idx2 - 1]) lastIdx = idx missingCount = 0 self._timeseriesData = buckets # at the end set self._normalized to True self._normalized = True
[ "def", "normalize", "(", "self", ",", "normalizationLevel", "=", "\"minute\"", ",", "fusionMethod", "=", "\"mean\"", ",", "interpolationMethod", "=", "\"linear\"", ")", ":", "# do not normalize the TimeSeries if it is already normalized, either by", "# definition or a prior cal...
Normalizes the TimeSeries data points. If this function is called, the TimeSeries gets ordered ascending automatically. The new timestamps will represent the center of each time bucket. Within a normalized TimeSeries, the temporal distance between two consecutive data points is constant. :param string normalizationLevel: Level of normalization that has to be applied. The available normalization levels are defined in :py:data:`timeseries.NormalizationLevels`. :param string fusionMethod: Normalization method that has to be used if multiple data entries exist within the same normalization bucket. The available methods are defined in :py:data:`timeseries.FusionMethods`. :param string interpolationMethod: Interpolation method that is used if a data entry at a specific time is missing. The available interpolation methods are defined in :py:data:`timeseries.InterpolationMethods`. :raise: Raises a :py:exc:`ValueError` if a normalizationLevel, fusionMethod or interpolationMethod hanve an unknown value.
[ "Normalizes", "the", "TimeSeries", "data", "points", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/timeseries.py#L418-L529
train
36,774
T-002/pycast
pycast/common/timeseries.py
TimeSeries._check_normalization
def _check_normalization(self): """Checks, if the TimeSeries is normalized. :return: Returns :py:const:`True` if all data entries of the TimeSeries have an equal temporal distance, :py:const:`False` otherwise. """ lastDistance = None distance = None for idx in xrange(len(self) - 1): distance = self[idx+1][0] - self[idx][0] # first run if lastDistance is None: lastDistance = distance continue if lastDistance != distance: return False lastDistance = distance return True
python
def _check_normalization(self): """Checks, if the TimeSeries is normalized. :return: Returns :py:const:`True` if all data entries of the TimeSeries have an equal temporal distance, :py:const:`False` otherwise. """ lastDistance = None distance = None for idx in xrange(len(self) - 1): distance = self[idx+1][0] - self[idx][0] # first run if lastDistance is None: lastDistance = distance continue if lastDistance != distance: return False lastDistance = distance return True
[ "def", "_check_normalization", "(", "self", ")", ":", "lastDistance", "=", "None", "distance", "=", "None", "for", "idx", "in", "xrange", "(", "len", "(", "self", ")", "-", "1", ")", ":", "distance", "=", "self", "[", "idx", "+", "1", "]", "[", "0"...
Checks, if the TimeSeries is normalized. :return: Returns :py:const:`True` if all data entries of the TimeSeries have an equal temporal distance, :py:const:`False` otherwise.
[ "Checks", "if", "the", "TimeSeries", "is", "normalized", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/timeseries.py#L542-L563
train
36,775
T-002/pycast
pycast/common/timeseries.py
TimeSeries.sample
def sample(self, percentage): """Samples with replacement from the TimeSeries. Returns the sample and the remaining timeseries. The original timeseries is not changed. :param float percentage: How many percent of the original timeseries should be in the sample :return: A tuple containing (sample, rest) as two TimeSeries. :rtype: tuple(TimeSeries,TimeSeries) :raise: Raises a ValueError if percentage is not in (0.0, 1.0). """ if not (0.0 < percentage < 1.0): raise ValueError("Parameter percentage has to be in (0.0, 1.0).") cls = self.__class__ value_count = int(len(self) * percentage) values = random.sample(self, value_count) sample = cls.from_twodim_list(values) rest_values = self._timeseriesData[:] for value in values: rest_values.remove(value) rest = cls.from_twodim_list(rest_values) return sample, rest
python
def sample(self, percentage): """Samples with replacement from the TimeSeries. Returns the sample and the remaining timeseries. The original timeseries is not changed. :param float percentage: How many percent of the original timeseries should be in the sample :return: A tuple containing (sample, rest) as two TimeSeries. :rtype: tuple(TimeSeries,TimeSeries) :raise: Raises a ValueError if percentage is not in (0.0, 1.0). """ if not (0.0 < percentage < 1.0): raise ValueError("Parameter percentage has to be in (0.0, 1.0).") cls = self.__class__ value_count = int(len(self) * percentage) values = random.sample(self, value_count) sample = cls.from_twodim_list(values) rest_values = self._timeseriesData[:] for value in values: rest_values.remove(value) rest = cls.from_twodim_list(rest_values) return sample, rest
[ "def", "sample", "(", "self", ",", "percentage", ")", ":", "if", "not", "(", "0.0", "<", "percentage", "<", "1.0", ")", ":", "raise", "ValueError", "(", "\"Parameter percentage has to be in (0.0, 1.0).\"", ")", "cls", "=", "self", ".", "__class__", "value_coun...
Samples with replacement from the TimeSeries. Returns the sample and the remaining timeseries. The original timeseries is not changed. :param float percentage: How many percent of the original timeseries should be in the sample :return: A tuple containing (sample, rest) as two TimeSeries. :rtype: tuple(TimeSeries,TimeSeries) :raise: Raises a ValueError if percentage is not in (0.0, 1.0).
[ "Samples", "with", "replacement", "from", "the", "TimeSeries", ".", "Returns", "the", "sample", "and", "the", "remaining", "timeseries", ".", "The", "original", "timeseries", "is", "not", "changed", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/timeseries.py#L592-L618
train
36,776
T-002/pycast
pycast/common/timeseries.py
MultiDimensionalTimeSeries.from_twodim_list
def from_twodim_list(cls, datalist, tsformat=None, dimensions=1): """Creates a new MultiDimensionalTimeSeries instance from the data stored inside a two dimensional list. :param list datalist: List containing multiple iterables with at least two values. The first item will always be used as timestamp in the predefined format, the second is a list, containing the dimension values. :param string format: Format of the given timestamp. This is used to convert the timestamp into UNIX epochs, if necessary. For valid examples take a look into the :py:func:`time.strptime` documentation. :param integer dimensions: Number of dimensions the MultiDimensionalTimeSeries contains. :return: Returns a MultiDimensionalTimeSeries instance containing the data from datalist. :rtype: MultiDimensionalTimeSeries """ # create and fill the given TimeSeries ts = MultiDimensionalTimeSeries(dimensions=dimensions) ts.set_timeformat(tsformat) for entry in datalist: ts.add_entry(entry[0], entry[1]) # set the normalization level ts._normalized = ts.is_normalized() ts.sort_timeseries() return ts
python
def from_twodim_list(cls, datalist, tsformat=None, dimensions=1): """Creates a new MultiDimensionalTimeSeries instance from the data stored inside a two dimensional list. :param list datalist: List containing multiple iterables with at least two values. The first item will always be used as timestamp in the predefined format, the second is a list, containing the dimension values. :param string format: Format of the given timestamp. This is used to convert the timestamp into UNIX epochs, if necessary. For valid examples take a look into the :py:func:`time.strptime` documentation. :param integer dimensions: Number of dimensions the MultiDimensionalTimeSeries contains. :return: Returns a MultiDimensionalTimeSeries instance containing the data from datalist. :rtype: MultiDimensionalTimeSeries """ # create and fill the given TimeSeries ts = MultiDimensionalTimeSeries(dimensions=dimensions) ts.set_timeformat(tsformat) for entry in datalist: ts.add_entry(entry[0], entry[1]) # set the normalization level ts._normalized = ts.is_normalized() ts.sort_timeseries() return ts
[ "def", "from_twodim_list", "(", "cls", ",", "datalist", ",", "tsformat", "=", "None", ",", "dimensions", "=", "1", ")", ":", "# create and fill the given TimeSeries", "ts", "=", "MultiDimensionalTimeSeries", "(", "dimensions", "=", "dimensions", ")", "ts", ".", ...
Creates a new MultiDimensionalTimeSeries instance from the data stored inside a two dimensional list. :param list datalist: List containing multiple iterables with at least two values. The first item will always be used as timestamp in the predefined format, the second is a list, containing the dimension values. :param string format: Format of the given timestamp. This is used to convert the timestamp into UNIX epochs, if necessary. For valid examples take a look into the :py:func:`time.strptime` documentation. :param integer dimensions: Number of dimensions the MultiDimensionalTimeSeries contains. :return: Returns a MultiDimensionalTimeSeries instance containing the data from datalist. :rtype: MultiDimensionalTimeSeries
[ "Creates", "a", "new", "MultiDimensionalTimeSeries", "instance", "from", "the", "data", "stored", "inside", "a", "two", "dimensional", "list", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/timeseries.py#L725-L750
train
36,777
twisted/txaws
txaws/client/_producers.py
FileBodyProducer._writeloop
def _writeloop(self, consumer): """ Return an iterator which reads one chunk of bytes from the input file and writes them to the consumer for each time it is iterated. """ while True: bytes = self._inputFile.read(self._readSize) if not bytes: self._inputFile.close() break consumer.write(bytes) yield None
python
def _writeloop(self, consumer): """ Return an iterator which reads one chunk of bytes from the input file and writes them to the consumer for each time it is iterated. """ while True: bytes = self._inputFile.read(self._readSize) if not bytes: self._inputFile.close() break consumer.write(bytes) yield None
[ "def", "_writeloop", "(", "self", ",", "consumer", ")", ":", "while", "True", ":", "bytes", "=", "self", ".", "_inputFile", ".", "read", "(", "self", ".", "_readSize", ")", "if", "not", "bytes", ":", "self", ".", "_inputFile", ".", "close", "(", ")",...
Return an iterator which reads one chunk of bytes from the input file and writes them to the consumer for each time it is iterated.
[ "Return", "an", "iterator", "which", "reads", "one", "chunk", "of", "bytes", "from", "the", "input", "file", "and", "writes", "them", "to", "the", "consumer", "for", "each", "time", "it", "is", "iterated", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/client/_producers.py#L93-L104
train
36,778
Duke-GCB/DukeDSClient
ddsc/core/upload.py
ProjectUpload.run
def run(self): """ Upload different items within local_project to remote store showing a progress bar. """ progress_printer = ProgressPrinter(self.different_items.total_items(), msg_verb='sending') upload_settings = UploadSettings(self.config, self.remote_store.data_service, progress_printer, self.project_name_or_id, self.file_upload_post_processor) project_uploader = ProjectUploader(upload_settings) project_uploader.run(self.local_project) progress_printer.finished()
python
def run(self): """ Upload different items within local_project to remote store showing a progress bar. """ progress_printer = ProgressPrinter(self.different_items.total_items(), msg_verb='sending') upload_settings = UploadSettings(self.config, self.remote_store.data_service, progress_printer, self.project_name_or_id, self.file_upload_post_processor) project_uploader = ProjectUploader(upload_settings) project_uploader.run(self.local_project) progress_printer.finished()
[ "def", "run", "(", "self", ")", ":", "progress_printer", "=", "ProgressPrinter", "(", "self", ".", "different_items", ".", "total_items", "(", ")", ",", "msg_verb", "=", "'sending'", ")", "upload_settings", "=", "UploadSettings", "(", "self", ".", "config", ...
Upload different items within local_project to remote store showing a progress bar.
[ "Upload", "different", "items", "within", "local_project", "to", "remote", "store", "showing", "a", "progress", "bar", "." ]
117f68fb9bae82e4c81ea487ad5d61ac350f3726
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/upload.py#L53-L62
train
36,779
Duke-GCB/DukeDSClient
ddsc/core/upload.py
ProjectUpload.get_upload_report
def get_upload_report(self): """ Generate and print a report onto stdout. """ project = self.remote_store.fetch_remote_project(self.project_name_or_id, must_exist=True, include_children=False) report = UploadReport(project.name) report.walk_project(self.local_project) return report.get_content()
python
def get_upload_report(self): """ Generate and print a report onto stdout. """ project = self.remote_store.fetch_remote_project(self.project_name_or_id, must_exist=True, include_children=False) report = UploadReport(project.name) report.walk_project(self.local_project) return report.get_content()
[ "def", "get_upload_report", "(", "self", ")", ":", "project", "=", "self", ".", "remote_store", ".", "fetch_remote_project", "(", "self", ".", "project_name_or_id", ",", "must_exist", "=", "True", ",", "include_children", "=", "False", ")", "report", "=", "Upl...
Generate and print a report onto stdout.
[ "Generate", "and", "print", "a", "report", "onto", "stdout", "." ]
117f68fb9bae82e4c81ea487ad5d61ac350f3726
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/upload.py#L89-L98
train
36,780
Duke-GCB/DukeDSClient
ddsc/core/upload.py
ProjectUpload.get_url_msg
def get_url_msg(self): """ Print url to view the project via dds portal. """ msg = 'URL to view project' project_id = self.local_project.remote_id url = '{}: https://{}/#/project/{}'.format(msg, self.config.get_portal_url_base(), project_id) return url
python
def get_url_msg(self): """ Print url to view the project via dds portal. """ msg = 'URL to view project' project_id = self.local_project.remote_id url = '{}: https://{}/#/project/{}'.format(msg, self.config.get_portal_url_base(), project_id) return url
[ "def", "get_url_msg", "(", "self", ")", ":", "msg", "=", "'URL to view project'", "project_id", "=", "self", ".", "local_project", ".", "remote_id", "url", "=", "'{}: https://{}/#/project/{}'", ".", "format", "(", "msg", ",", "self", ".", "config", ".", "get_p...
Print url to view the project via dds portal.
[ "Print", "url", "to", "view", "the", "project", "via", "dds", "portal", "." ]
117f68fb9bae82e4c81ea487ad5d61ac350f3726
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/upload.py#L100-L107
train
36,781
Duke-GCB/DukeDSClient
ddsc/core/fileuploader.py
FileUploadOperations._send_file_external_with_retry
def _send_file_external_with_retry(self, http_verb, host, url, http_headers, chunk): """ Send chunk to host, url using http_verb. If http_verb is PUT and a connection error occurs retry a few times. Pauses between retries. Raises if unsuccessful. """ count = 0 retry_times = 1 if http_verb == 'PUT': retry_times = SEND_EXTERNAL_PUT_RETRY_TIMES while True: try: return self.data_service.send_external(http_verb, host, url, http_headers, chunk) except requests.exceptions.ConnectionError: count += 1 if count < retry_times: if count == 1: # Only show a warning the first time we fail to send a chunk self._show_retry_warning(host) time.sleep(SEND_EXTERNAL_RETRY_SECONDS) self.data_service.recreate_requests_session() else: raise
python
def _send_file_external_with_retry(self, http_verb, host, url, http_headers, chunk): """ Send chunk to host, url using http_verb. If http_verb is PUT and a connection error occurs retry a few times. Pauses between retries. Raises if unsuccessful. """ count = 0 retry_times = 1 if http_verb == 'PUT': retry_times = SEND_EXTERNAL_PUT_RETRY_TIMES while True: try: return self.data_service.send_external(http_verb, host, url, http_headers, chunk) except requests.exceptions.ConnectionError: count += 1 if count < retry_times: if count == 1: # Only show a warning the first time we fail to send a chunk self._show_retry_warning(host) time.sleep(SEND_EXTERNAL_RETRY_SECONDS) self.data_service.recreate_requests_session() else: raise
[ "def", "_send_file_external_with_retry", "(", "self", ",", "http_verb", ",", "host", ",", "url", ",", "http_headers", ",", "chunk", ")", ":", "count", "=", "0", "retry_times", "=", "1", "if", "http_verb", "==", "'PUT'", ":", "retry_times", "=", "SEND_EXTERNA...
Send chunk to host, url using http_verb. If http_verb is PUT and a connection error occurs retry a few times. Pauses between retries. Raises if unsuccessful.
[ "Send", "chunk", "to", "host", "url", "using", "http_verb", ".", "If", "http_verb", "is", "PUT", "and", "a", "connection", "error", "occurs", "retry", "a", "few", "times", ".", "Pauses", "between", "retries", ".", "Raises", "if", "unsuccessful", "." ]
117f68fb9bae82e4c81ea487ad5d61ac350f3726
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/fileuploader.py#L192-L212
train
36,782
Duke-GCB/DukeDSClient
ddsc/core/fileuploader.py
ParallelChunkProcessor.run
def run(self): """ Sends contents of a local file to a remote data service. """ processes = [] progress_queue = ProgressQueue(Queue()) num_chunks = ParallelChunkProcessor.determine_num_chunks(self.config.upload_bytes_per_chunk, self.local_file.size) work_parcels = ParallelChunkProcessor.make_work_parcels(self.config.upload_workers, num_chunks) for (index, num_items) in work_parcels: processes.append(self.make_and_start_process(index, num_items, progress_queue)) wait_for_processes(processes, num_chunks, progress_queue, self.watcher, self.local_file)
python
def run(self): """ Sends contents of a local file to a remote data service. """ processes = [] progress_queue = ProgressQueue(Queue()) num_chunks = ParallelChunkProcessor.determine_num_chunks(self.config.upload_bytes_per_chunk, self.local_file.size) work_parcels = ParallelChunkProcessor.make_work_parcels(self.config.upload_workers, num_chunks) for (index, num_items) in work_parcels: processes.append(self.make_and_start_process(index, num_items, progress_queue)) wait_for_processes(processes, num_chunks, progress_queue, self.watcher, self.local_file)
[ "def", "run", "(", "self", ")", ":", "processes", "=", "[", "]", "progress_queue", "=", "ProgressQueue", "(", "Queue", "(", ")", ")", "num_chunks", "=", "ParallelChunkProcessor", ".", "determine_num_chunks", "(", "self", ".", "config", ".", "upload_bytes_per_c...
Sends contents of a local file to a remote data service.
[ "Sends", "contents", "of", "a", "local", "file", "to", "a", "remote", "data", "service", "." ]
117f68fb9bae82e4c81ea487ad5d61ac350f3726
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/fileuploader.py#L256-L267
train
36,783
Duke-GCB/DukeDSClient
ddsc/core/fileuploader.py
ChunkSender.send
def send(self): """ For each chunk we need to send, create upload url and send bytes. Raises exception on error. """ sent_chunks = 0 chunk_num = self.index with open(self.filename, 'rb') as infile: infile.seek(self.index * self.chunk_size) while sent_chunks != self.num_chunks_to_send: chunk = infile.read(self.chunk_size) self._send_chunk(chunk, chunk_num) self.progress_queue.processed(1) chunk_num += 1 sent_chunks += 1
python
def send(self): """ For each chunk we need to send, create upload url and send bytes. Raises exception on error. """ sent_chunks = 0 chunk_num = self.index with open(self.filename, 'rb') as infile: infile.seek(self.index * self.chunk_size) while sent_chunks != self.num_chunks_to_send: chunk = infile.read(self.chunk_size) self._send_chunk(chunk, chunk_num) self.progress_queue.processed(1) chunk_num += 1 sent_chunks += 1
[ "def", "send", "(", "self", ")", ":", "sent_chunks", "=", "0", "chunk_num", "=", "self", ".", "index", "with", "open", "(", "self", ".", "filename", ",", "'rb'", ")", "as", "infile", ":", "infile", ".", "seek", "(", "self", ".", "index", "*", "self...
For each chunk we need to send, create upload url and send bytes. Raises exception on error.
[ "For", "each", "chunk", "we", "need", "to", "send", "create", "upload", "url", "and", "send", "bytes", ".", "Raises", "exception", "on", "error", "." ]
117f68fb9bae82e4c81ea487ad5d61ac350f3726
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/fileuploader.py#L369-L382
train
36,784
T-002/pycast
pycast/methods/basemethod.py
BaseMethod._in_valid_interval
def _in_valid_interval(self, parameter, value): """Returns if the parameter is within its valid interval. :param string parameter: Name of the parameter that has to be checked. :param numeric value: Value of the parameter. :return: Returns :py:const:`True` it the value for the given parameter is valid, :py:const:`False` otherwise. :rtype: boolean """ # return True, if not interval is defined for the parameter if parameter not in self._parameterIntervals: return True interval = self._parameterIntervals[parameter] if interval[2] and interval[3]: return interval[0] <= value <= interval[1] if not interval[2] and interval[3]: return interval[0] < value <= interval[1] if interval[2] and not interval[3]: return interval[0] <= value < interval[1] #if False == interval[2] and False == interval[3]: return interval[0] < value < interval[1]
python
def _in_valid_interval(self, parameter, value): """Returns if the parameter is within its valid interval. :param string parameter: Name of the parameter that has to be checked. :param numeric value: Value of the parameter. :return: Returns :py:const:`True` it the value for the given parameter is valid, :py:const:`False` otherwise. :rtype: boolean """ # return True, if not interval is defined for the parameter if parameter not in self._parameterIntervals: return True interval = self._parameterIntervals[parameter] if interval[2] and interval[3]: return interval[0] <= value <= interval[1] if not interval[2] and interval[3]: return interval[0] < value <= interval[1] if interval[2] and not interval[3]: return interval[0] <= value < interval[1] #if False == interval[2] and False == interval[3]: return interval[0] < value < interval[1]
[ "def", "_in_valid_interval", "(", "self", ",", "parameter", ",", "value", ")", ":", "# return True, if not interval is defined for the parameter", "if", "parameter", "not", "in", "self", ".", "_parameterIntervals", ":", "return", "True", "interval", "=", "self", ".", ...
Returns if the parameter is within its valid interval. :param string parameter: Name of the parameter that has to be checked. :param numeric value: Value of the parameter. :return: Returns :py:const:`True` it the value for the given parameter is valid, :py:const:`False` otherwise. :rtype: boolean
[ "Returns", "if", "the", "parameter", "is", "within", "its", "valid", "interval", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/basemethod.py#L118-L144
train
36,785
T-002/pycast
pycast/methods/basemethod.py
BaseMethod._get_value_error_message_for_invalid_prarameter
def _get_value_error_message_for_invalid_prarameter(self, parameter, value): """Returns the ValueError message for the given parameter. :param string parameter: Name of the parameter the message has to be created for. :param numeric value: Value outside the parameters interval. :return: Returns a string containing hte message. :rtype: string """ # return if not interval is defined for the parameter if parameter not in self._parameterIntervals: return interval = self._parameterIntervals[parameter] return "%s has to be in %s%s, %s%s. Current value is %s." % ( parameter, BaseMethod._interval_definitions[interval[2]][0], interval[0], interval[1], BaseMethod._interval_definitions[interval[3]][1], value )
python
def _get_value_error_message_for_invalid_prarameter(self, parameter, value): """Returns the ValueError message for the given parameter. :param string parameter: Name of the parameter the message has to be created for. :param numeric value: Value outside the parameters interval. :return: Returns a string containing hte message. :rtype: string """ # return if not interval is defined for the parameter if parameter not in self._parameterIntervals: return interval = self._parameterIntervals[parameter] return "%s has to be in %s%s, %s%s. Current value is %s." % ( parameter, BaseMethod._interval_definitions[interval[2]][0], interval[0], interval[1], BaseMethod._interval_definitions[interval[3]][1], value )
[ "def", "_get_value_error_message_for_invalid_prarameter", "(", "self", ",", "parameter", ",", "value", ")", ":", "# return if not interval is defined for the parameter", "if", "parameter", "not", "in", "self", ".", "_parameterIntervals", ":", "return", "interval", "=", "s...
Returns the ValueError message for the given parameter. :param string parameter: Name of the parameter the message has to be created for. :param numeric value: Value outside the parameters interval. :return: Returns a string containing hte message. :rtype: string
[ "Returns", "the", "ValueError", "message", "for", "the", "given", "parameter", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/basemethod.py#L146-L166
train
36,786
T-002/pycast
pycast/methods/basemethod.py
BaseMethod.set_parameter
def set_parameter(self, name, value): """Sets a parameter for the BaseMethod. :param string name: Name of the parameter that has to be checked. :param numeric value: Value of the parameter. """ if not self._in_valid_interval(name, value): raise ValueError(self._get_value_error_message_for_invalid_prarameter(name, value)) #if name in self._parameters: # print "Parameter %s already existed. It's old value will be replaced with %s" % (name, value) self._parameters[name] = value
python
def set_parameter(self, name, value): """Sets a parameter for the BaseMethod. :param string name: Name of the parameter that has to be checked. :param numeric value: Value of the parameter. """ if not self._in_valid_interval(name, value): raise ValueError(self._get_value_error_message_for_invalid_prarameter(name, value)) #if name in self._parameters: # print "Parameter %s already existed. It's old value will be replaced with %s" % (name, value) self._parameters[name] = value
[ "def", "set_parameter", "(", "self", ",", "name", ",", "value", ")", ":", "if", "not", "self", ".", "_in_valid_interval", "(", "name", ",", "value", ")", ":", "raise", "ValueError", "(", "self", ".", "_get_value_error_message_for_invalid_prarameter", "(", "nam...
Sets a parameter for the BaseMethod. :param string name: Name of the parameter that has to be checked. :param numeric value: Value of the parameter.
[ "Sets", "a", "parameter", "for", "the", "BaseMethod", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/basemethod.py#L168-L180
train
36,787
T-002/pycast
pycast/methods/basemethod.py
BaseMethod.can_be_executed
def can_be_executed(self): """Returns if the method can already be executed. :return: Returns :py:const:`True` if all required parameters where already set, False otherwise. :rtype: boolean """ missingParams = filter(lambda rp: rp not in self._parameters, self._requiredParameters) return len(missingParams) == 0
python
def can_be_executed(self): """Returns if the method can already be executed. :return: Returns :py:const:`True` if all required parameters where already set, False otherwise. :rtype: boolean """ missingParams = filter(lambda rp: rp not in self._parameters, self._requiredParameters) return len(missingParams) == 0
[ "def", "can_be_executed", "(", "self", ")", ":", "missingParams", "=", "filter", "(", "lambda", "rp", ":", "rp", "not", "in", "self", ".", "_parameters", ",", "self", ".", "_requiredParameters", ")", "return", "len", "(", "missingParams", ")", "==", "0" ]
Returns if the method can already be executed. :return: Returns :py:const:`True` if all required parameters where already set, False otherwise. :rtype: boolean
[ "Returns", "if", "the", "method", "can", "already", "be", "executed", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/basemethod.py#L210-L217
train
36,788
T-002/pycast
pycast/methods/basemethod.py
BaseForecastingMethod.set_parameter
def set_parameter(self, name, value): """Sets a parameter for the BaseForecastingMethod. :param string name: Name of the parameter. :param numeric value: Value of the parameter. """ # set the furecast until variable to None if necessary if name == "valuesToForecast": self._forecastUntil = None # continue with the parents implementation return super(BaseForecastingMethod, self).set_parameter(name, value)
python
def set_parameter(self, name, value): """Sets a parameter for the BaseForecastingMethod. :param string name: Name of the parameter. :param numeric value: Value of the parameter. """ # set the furecast until variable to None if necessary if name == "valuesToForecast": self._forecastUntil = None # continue with the parents implementation return super(BaseForecastingMethod, self).set_parameter(name, value)
[ "def", "set_parameter", "(", "self", ",", "name", ",", "value", ")", ":", "# set the furecast until variable to None if necessary", "if", "name", "==", "\"valuesToForecast\"", ":", "self", ".", "_forecastUntil", "=", "None", "# continue with the parents implementation", "...
Sets a parameter for the BaseForecastingMethod. :param string name: Name of the parameter. :param numeric value: Value of the parameter.
[ "Sets", "a", "parameter", "for", "the", "BaseForecastingMethod", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/basemethod.py#L272-L283
train
36,789
T-002/pycast
pycast/methods/basemethod.py
BaseForecastingMethod._calculate_values_to_forecast
def _calculate_values_to_forecast(self, timeSeries): """Calculates the number of values, that need to be forecasted to match the goal set in forecast_until. This sets the parameter "valuesToForecast" and should be called at the beginning of the :py:meth:`BaseMethod.execute` implementation. :param TimeSeries timeSeries: Should be a sorted and normalized TimeSeries instance. :raise: Raises a :py:exc:`ValueError` if the TimeSeries is either not normalized or sorted. """ # do not set anything, if it is not required if self._forecastUntil is None: return # check the TimeSeries for correctness if not timeSeries.is_sorted(): raise ValueError("timeSeries has to be sorted.") if not timeSeries.is_normalized(): raise ValueError("timeSeries has to be normalized.") timediff = timeSeries[-1][0] - timeSeries[-2][0] forecastSpan = self._forecastUntil - timeSeries[-1][0] self.set_parameter("valuesToForecast", int(forecastSpan / timediff) + 1)
python
def _calculate_values_to_forecast(self, timeSeries): """Calculates the number of values, that need to be forecasted to match the goal set in forecast_until. This sets the parameter "valuesToForecast" and should be called at the beginning of the :py:meth:`BaseMethod.execute` implementation. :param TimeSeries timeSeries: Should be a sorted and normalized TimeSeries instance. :raise: Raises a :py:exc:`ValueError` if the TimeSeries is either not normalized or sorted. """ # do not set anything, if it is not required if self._forecastUntil is None: return # check the TimeSeries for correctness if not timeSeries.is_sorted(): raise ValueError("timeSeries has to be sorted.") if not timeSeries.is_normalized(): raise ValueError("timeSeries has to be normalized.") timediff = timeSeries[-1][0] - timeSeries[-2][0] forecastSpan = self._forecastUntil - timeSeries[-1][0] self.set_parameter("valuesToForecast", int(forecastSpan / timediff) + 1)
[ "def", "_calculate_values_to_forecast", "(", "self", ",", "timeSeries", ")", ":", "# do not set anything, if it is not required", "if", "self", ".", "_forecastUntil", "is", "None", ":", "return", "# check the TimeSeries for correctness", "if", "not", "timeSeries", ".", "i...
Calculates the number of values, that need to be forecasted to match the goal set in forecast_until. This sets the parameter "valuesToForecast" and should be called at the beginning of the :py:meth:`BaseMethod.execute` implementation. :param TimeSeries timeSeries: Should be a sorted and normalized TimeSeries instance. :raise: Raises a :py:exc:`ValueError` if the TimeSeries is either not normalized or sorted.
[ "Calculates", "the", "number", "of", "values", "that", "need", "to", "be", "forecasted", "to", "match", "the", "goal", "set", "in", "forecast_until", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/basemethod.py#L300-L322
train
36,790
T-002/pycast
pycast/methods/simplemovingaverage.py
SimpleMovingAverage.execute
def execute(self, timeSeries): """Creates a new TimeSeries containing the SMA values for the predefined windowsize. :param TimeSeries timeSeries: The TimeSeries used to calculate the simple moving average values. :return: TimeSeries object containing the smooth moving average. :rtype: TimeSeries :raise: Raises a :py:exc:`ValueError` wif the defined windowsize is larger than the number of elements in timeSeries :note: This implementation aims to support independent for loop execution. """ windowsize = self._parameters["windowsize"] if len (timeSeries) < windowsize: raise ValueError("windowsize is larger than the number of elements in timeSeries.") tsLength = len(timeSeries) nbrOfLoopRuns = tsLength - windowsize + 1 res = TimeSeries() for idx in xrange(nbrOfLoopRuns): end = idx + windowsize data = timeSeries[idx:end] timestamp = data[windowsize//2][0] value = sum([i[1] for i in data])/windowsize res.add_entry(timestamp, value) res.sort_timeseries() return res
python
def execute(self, timeSeries): """Creates a new TimeSeries containing the SMA values for the predefined windowsize. :param TimeSeries timeSeries: The TimeSeries used to calculate the simple moving average values. :return: TimeSeries object containing the smooth moving average. :rtype: TimeSeries :raise: Raises a :py:exc:`ValueError` wif the defined windowsize is larger than the number of elements in timeSeries :note: This implementation aims to support independent for loop execution. """ windowsize = self._parameters["windowsize"] if len (timeSeries) < windowsize: raise ValueError("windowsize is larger than the number of elements in timeSeries.") tsLength = len(timeSeries) nbrOfLoopRuns = tsLength - windowsize + 1 res = TimeSeries() for idx in xrange(nbrOfLoopRuns): end = idx + windowsize data = timeSeries[idx:end] timestamp = data[windowsize//2][0] value = sum([i[1] for i in data])/windowsize res.add_entry(timestamp, value) res.sort_timeseries() return res
[ "def", "execute", "(", "self", ",", "timeSeries", ")", ":", "windowsize", "=", "self", ".", "_parameters", "[", "\"windowsize\"", "]", "if", "len", "(", "timeSeries", ")", "<", "windowsize", ":", "raise", "ValueError", "(", "\"windowsize is larger than the numbe...
Creates a new TimeSeries containing the SMA values for the predefined windowsize. :param TimeSeries timeSeries: The TimeSeries used to calculate the simple moving average values. :return: TimeSeries object containing the smooth moving average. :rtype: TimeSeries :raise: Raises a :py:exc:`ValueError` wif the defined windowsize is larger than the number of elements in timeSeries :note: This implementation aims to support independent for loop execution.
[ "Creates", "a", "new", "TimeSeries", "containing", "the", "SMA", "values", "for", "the", "predefined", "windowsize", "." ]
8a53505c6d8367e0ea572e8af768e80b29e1cc41
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/simplemovingaverage.py#L79-L111
train
36,791
twisted/txaws
txaws/wsdl.py
NodeItem._create_child
def _create_child(self, tag): """Create a new child element with the given tag.""" return etree.SubElement(self._root, self._get_namespace_tag(tag))
python
def _create_child(self, tag): """Create a new child element with the given tag.""" return etree.SubElement(self._root, self._get_namespace_tag(tag))
[ "def", "_create_child", "(", "self", ",", "tag", ")", ":", "return", "etree", ".", "SubElement", "(", "self", ".", "_root", ",", "self", ".", "_get_namespace_tag", "(", "tag", ")", ")" ]
Create a new child element with the given tag.
[ "Create", "a", "new", "child", "element", "with", "the", "given", "tag", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/wsdl.py#L243-L245
train
36,792
twisted/txaws
txaws/wsdl.py
SequenceSchema.create
def create(self, root=None, namespace=None): """Create a sequence element with the given root. @param root: The C{etree.Element} to root the sequence at, if C{None} a new one will be created.. @result: A L{SequenceItem} with the given root. @raises L{ECResponseError}: If the given C{root} has a bad tag. """ if root is not None: tag = root.tag if root.nsmap: namespace = root.nsmap[None] tag = tag[len(namespace) + 2:] if tag != self.tag: raise WSDLParseError("Expected response with tag '%s', but " "got '%s' instead" % (self.tag, tag)) return SequenceItem(self, root, namespace)
python
def create(self, root=None, namespace=None): """Create a sequence element with the given root. @param root: The C{etree.Element} to root the sequence at, if C{None} a new one will be created.. @result: A L{SequenceItem} with the given root. @raises L{ECResponseError}: If the given C{root} has a bad tag. """ if root is not None: tag = root.tag if root.nsmap: namespace = root.nsmap[None] tag = tag[len(namespace) + 2:] if tag != self.tag: raise WSDLParseError("Expected response with tag '%s', but " "got '%s' instead" % (self.tag, tag)) return SequenceItem(self, root, namespace)
[ "def", "create", "(", "self", ",", "root", "=", "None", ",", "namespace", "=", "None", ")", ":", "if", "root", "is", "not", "None", ":", "tag", "=", "root", ".", "tag", "if", "root", ".", "nsmap", ":", "namespace", "=", "root", ".", "nsmap", "[",...
Create a sequence element with the given root. @param root: The C{etree.Element} to root the sequence at, if C{None} a new one will be created.. @result: A L{SequenceItem} with the given root. @raises L{ECResponseError}: If the given C{root} has a bad tag.
[ "Create", "a", "sequence", "element", "with", "the", "given", "root", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/wsdl.py#L316-L332
train
36,793
twisted/txaws
txaws/wsdl.py
SequenceSchema.set
def set(self, child, min_occurs=1, max_occurs=1): """Set the schema for the sequence children. @param child: The schema that children must match. @param min_occurs: The minimum number of children the sequence must have. @param max_occurs: The maximum number of children the sequence can have. """ if isinstance(child, LeafSchema): raise RuntimeError("Sequence can't have leaf children") if self.child is not None: raise RuntimeError("Sequence has already a child") if min_occurs is None or max_occurs is None: raise RuntimeError("Sequence node without min or max") if isinstance(child, LeafSchema): raise RuntimeError("Sequence node with leaf child type") if not child.tag == "item": raise RuntimeError("Sequence node with bad child tag") self.child = child self.min_occurs = min_occurs self.max_occurs = max_occurs return child
python
def set(self, child, min_occurs=1, max_occurs=1): """Set the schema for the sequence children. @param child: The schema that children must match. @param min_occurs: The minimum number of children the sequence must have. @param max_occurs: The maximum number of children the sequence can have. """ if isinstance(child, LeafSchema): raise RuntimeError("Sequence can't have leaf children") if self.child is not None: raise RuntimeError("Sequence has already a child") if min_occurs is None or max_occurs is None: raise RuntimeError("Sequence node without min or max") if isinstance(child, LeafSchema): raise RuntimeError("Sequence node with leaf child type") if not child.tag == "item": raise RuntimeError("Sequence node with bad child tag") self.child = child self.min_occurs = min_occurs self.max_occurs = max_occurs return child
[ "def", "set", "(", "self", ",", "child", ",", "min_occurs", "=", "1", ",", "max_occurs", "=", "1", ")", ":", "if", "isinstance", "(", "child", ",", "LeafSchema", ")", ":", "raise", "RuntimeError", "(", "\"Sequence can't have leaf children\"", ")", "if", "s...
Set the schema for the sequence children. @param child: The schema that children must match. @param min_occurs: The minimum number of children the sequence must have. @param max_occurs: The maximum number of children the sequence can have.
[ "Set", "the", "schema", "for", "the", "sequence", "children", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/wsdl.py#L341-L364
train
36,794
twisted/txaws
txaws/wsdl.py
SequenceItem.append
def append(self): """Append a new item to the sequence, appending it to the end. @return: The newly created item. @raises L{WSDLParseError}: If the operation would result in having more child elements than the allowed max. """ tag = self._schema.tag children = self._root.getchildren() if len(children) >= self._schema.max_occurs: raise WSDLParseError("Too many items in tag '%s'" % tag) schema = self._schema.child tag = "item" if self._namespace is not None: tag = "{%s}%s" % (self._namespace, tag) child = etree.SubElement(self._root, tag) return schema.create(child)
python
def append(self): """Append a new item to the sequence, appending it to the end. @return: The newly created item. @raises L{WSDLParseError}: If the operation would result in having more child elements than the allowed max. """ tag = self._schema.tag children = self._root.getchildren() if len(children) >= self._schema.max_occurs: raise WSDLParseError("Too many items in tag '%s'" % tag) schema = self._schema.child tag = "item" if self._namespace is not None: tag = "{%s}%s" % (self._namespace, tag) child = etree.SubElement(self._root, tag) return schema.create(child)
[ "def", "append", "(", "self", ")", ":", "tag", "=", "self", ".", "_schema", ".", "tag", "children", "=", "self", ".", "_root", ".", "getchildren", "(", ")", "if", "len", "(", "children", ")", ">=", "self", ".", "_schema", ".", "max_occurs", ":", "r...
Append a new item to the sequence, appending it to the end. @return: The newly created item. @raises L{WSDLParseError}: If the operation would result in having more child elements than the allowed max.
[ "Append", "a", "new", "item", "to", "the", "sequence", "appending", "it", "to", "the", "end", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/wsdl.py#L397-L413
train
36,795
twisted/txaws
txaws/wsdl.py
SequenceItem._get_child
def _get_child(self, children, index): """Return the child with the given index.""" try: return children[index] except IndexError: raise WSDLParseError("Non existing item in tag '%s'" % self._schema.tag)
python
def _get_child(self, children, index): """Return the child with the given index.""" try: return children[index] except IndexError: raise WSDLParseError("Non existing item in tag '%s'" % self._schema.tag)
[ "def", "_get_child", "(", "self", ",", "children", ",", "index", ")", ":", "try", ":", "return", "children", "[", "index", "]", "except", "IndexError", ":", "raise", "WSDLParseError", "(", "\"Non existing item in tag '%s'\"", "%", "self", ".", "_schema", ".", ...
Return the child with the given index.
[ "Return", "the", "child", "with", "the", "given", "index", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/wsdl.py#L452-L458
train
36,796
twisted/txaws
txaws/wsdl.py
WSDLParser._parse_type
def _parse_type(self, element, types): """Parse a 'complexType' element. @param element: The top-level complexType element @param types: A map of the elements of all available complexType's. @return: The schema for the complexType. """ name = element.attrib["name"] type = element.attrib["type"] if not type.startswith("tns:"): raise RuntimeError("Unexpected element type %s" % type) type = type[4:] [children] = types[type][0] types[type][1] = True self._remove_namespace_from_tag(children) if children.tag not in ("sequence", "choice"): raise RuntimeError("Unexpected children type %s" % children.tag) if children[0].attrib["name"] == "item": schema = SequenceSchema(name) else: schema = NodeSchema(name) for child in children: self._remove_namespace_from_tag(child) if child.tag == "element": name, type, min_occurs, max_occurs = self._parse_child(child) if type in self.leaf_types: if max_occurs != 1: raise RuntimeError("Unexpected max value for leaf") if not isinstance(schema, NodeSchema): raise RuntimeError("Attempt to add leaf to a non-node") schema.add(LeafSchema(name), min_occurs=min_occurs) else: if name == "item": # sequence if not isinstance(schema, SequenceSchema): raise RuntimeError("Attempt to set child for " "non-sequence") schema.set(self._parse_type(child, types), min_occurs=min_occurs, max_occurs=max_occurs) else: if max_occurs != 1: raise RuntimeError("Unexpected max for node") if not isinstance(schema, NodeSchema): raise RuntimeError("Unexpected schema type") schema.add(self._parse_type(child, types), min_occurs=min_occurs) elif child.tag == "choice": pass else: raise RuntimeError("Unexpected child type") return schema
python
def _parse_type(self, element, types): """Parse a 'complexType' element. @param element: The top-level complexType element @param types: A map of the elements of all available complexType's. @return: The schema for the complexType. """ name = element.attrib["name"] type = element.attrib["type"] if not type.startswith("tns:"): raise RuntimeError("Unexpected element type %s" % type) type = type[4:] [children] = types[type][0] types[type][1] = True self._remove_namespace_from_tag(children) if children.tag not in ("sequence", "choice"): raise RuntimeError("Unexpected children type %s" % children.tag) if children[0].attrib["name"] == "item": schema = SequenceSchema(name) else: schema = NodeSchema(name) for child in children: self._remove_namespace_from_tag(child) if child.tag == "element": name, type, min_occurs, max_occurs = self._parse_child(child) if type in self.leaf_types: if max_occurs != 1: raise RuntimeError("Unexpected max value for leaf") if not isinstance(schema, NodeSchema): raise RuntimeError("Attempt to add leaf to a non-node") schema.add(LeafSchema(name), min_occurs=min_occurs) else: if name == "item": # sequence if not isinstance(schema, SequenceSchema): raise RuntimeError("Attempt to set child for " "non-sequence") schema.set(self._parse_type(child, types), min_occurs=min_occurs, max_occurs=max_occurs) else: if max_occurs != 1: raise RuntimeError("Unexpected max for node") if not isinstance(schema, NodeSchema): raise RuntimeError("Unexpected schema type") schema.add(self._parse_type(child, types), min_occurs=min_occurs) elif child.tag == "choice": pass else: raise RuntimeError("Unexpected child type") return schema
[ "def", "_parse_type", "(", "self", ",", "element", ",", "types", ")", ":", "name", "=", "element", ".", "attrib", "[", "\"name\"", "]", "type", "=", "element", ".", "attrib", "[", "\"type\"", "]", "if", "not", "type", ".", "startswith", "(", "\"tns:\""...
Parse a 'complexType' element. @param element: The top-level complexType element @param types: A map of the elements of all available complexType's. @return: The schema for the complexType.
[ "Parse", "a", "complexType", "element", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/wsdl.py#L508-L562
train
36,797
twisted/txaws
txaws/wsdl.py
WSDLParser._parse_child
def _parse_child(self, child): """Parse a single child element. @param child: The child C{etree.Element} to parse. @return: A tuple C{(name, type, min_occurs, max_occurs)} with the details about the given child. """ if set(child.attrib) - set(["name", "type", "minOccurs", "maxOccurs"]): raise RuntimeError("Unexpected attribute in child") name = child.attrib["name"] type = child.attrib["type"].split(":")[1] min_occurs = child.attrib.get("minOccurs") max_occurs = child.attrib.get("maxOccurs") if min_occurs is None: min_occurs = "1" min_occurs = int(min_occurs) if max_occurs is None: max_occurs = "1" if max_occurs != "unbounded": max_occurs = int(max_occurs) return name, type, min_occurs, max_occurs
python
def _parse_child(self, child): """Parse a single child element. @param child: The child C{etree.Element} to parse. @return: A tuple C{(name, type, min_occurs, max_occurs)} with the details about the given child. """ if set(child.attrib) - set(["name", "type", "minOccurs", "maxOccurs"]): raise RuntimeError("Unexpected attribute in child") name = child.attrib["name"] type = child.attrib["type"].split(":")[1] min_occurs = child.attrib.get("minOccurs") max_occurs = child.attrib.get("maxOccurs") if min_occurs is None: min_occurs = "1" min_occurs = int(min_occurs) if max_occurs is None: max_occurs = "1" if max_occurs != "unbounded": max_occurs = int(max_occurs) return name, type, min_occurs, max_occurs
[ "def", "_parse_child", "(", "self", ",", "child", ")", ":", "if", "set", "(", "child", ".", "attrib", ")", "-", "set", "(", "[", "\"name\"", ",", "\"type\"", ",", "\"minOccurs\"", ",", "\"maxOccurs\"", "]", ")", ":", "raise", "RuntimeError", "(", "\"Un...
Parse a single child element. @param child: The child C{etree.Element} to parse. @return: A tuple C{(name, type, min_occurs, max_occurs)} with the details about the given child.
[ "Parse", "a", "single", "child", "element", "." ]
5c3317376cd47e536625027e38c3b37840175ce0
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/wsdl.py#L564-L584
train
36,798
Duke-GCB/DukeDSClient
ddsc/core/d4s2.py
CopyActivity.finished
def finished(self): """ Mark the activity as finished """ self.data_service.update_activity(self.id, self.name, self.desc, started_on=self.started, ended_on=self._current_timestamp_str())
python
def finished(self): """ Mark the activity as finished """ self.data_service.update_activity(self.id, self.name, self.desc, started_on=self.started, ended_on=self._current_timestamp_str())
[ "def", "finished", "(", "self", ")", ":", "self", ".", "data_service", ".", "update_activity", "(", "self", ".", "id", ",", "self", ".", "name", ",", "self", ".", "desc", ",", "started_on", "=", "self", ".", "started", ",", "ended_on", "=", "self", "...
Mark the activity as finished
[ "Mark", "the", "activity", "as", "finished" ]
117f68fb9bae82e4c81ea487ad5d61ac350f3726
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/d4s2.py#L413-L419
train
36,799