repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
1and1/infrascope
src/infrascope/__init__.py
pkg_info
def pkg_info(): """Return project information for setuptools.""" try: doc = __doc__.decode("UTF-8") except (AttributeError, UnicodeError): doc = __doc__ # Python3, or some strangeness return dict( # project data & layout name = __name__.split('.')[0], ## TODO: ve...
python
def pkg_info(): """Return project information for setuptools.""" try: doc = __doc__.decode("UTF-8") except (AttributeError, UnicodeError): doc = __doc__ # Python3, or some strangeness return dict( # project data & layout name = __name__.split('.')[0], ## TODO: ve...
[ "def", "pkg_info", "(", ")", ":", "try", ":", "doc", "=", "__doc__", ".", "decode", "(", "\"UTF-8\"", ")", "except", "(", "AttributeError", ",", "UnicodeError", ")", ":", "doc", "=", "__doc__", "# Python3, or some strangeness", "return", "dict", "(", "# proj...
Return project information for setuptools.
[ "Return", "project", "information", "for", "setuptools", "." ]
train
https://github.com/1and1/infrascope/blob/d7e291917e618a0a3cd6d5bfc20c6b5defd7550c/src/infrascope/__init__.py#L29-L95
diffeo/yakonfig
yakonfig/factory.py
AutoFactory.create
def create(self, configurable, config=None, **kwargs): '''Create a sub-object of this factory. Instantiates the `configurable` object with the current saved :attr:`config`. This essentially translates to ``configurable(**config)``, except services defined in the parent and requ...
python
def create(self, configurable, config=None, **kwargs): '''Create a sub-object of this factory. Instantiates the `configurable` object with the current saved :attr:`config`. This essentially translates to ``configurable(**config)``, except services defined in the parent and requ...
[ "def", "create", "(", "self", ",", "configurable", ",", "config", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# If we got passed a string, find the thing to make.", "if", "isinstance", "(", "configurable", ",", "string_types", ")", ":", "candidates", "=", "...
Create a sub-object of this factory. Instantiates the `configurable` object with the current saved :attr:`config`. This essentially translates to ``configurable(**config)``, except services defined in the parent and requested by `configurable` (by setting the ``services`` attri...
[ "Create", "a", "sub", "-", "object", "of", "this", "factory", "." ]
train
https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/factory.py#L130-L190
diffeo/yakonfig
yakonfig/factory.py
AutoConfigured.from_obj
def from_obj(cls, obj, any_configurable=False): '''Create a proxy object from a callable. If `any_configurable` is true, `obj` takes a parameter named ``config``, and `obj` smells like it implements :class:`yakonfig.Configurable` (it has a :attr:`~yakonfig.Configurable.config_na...
python
def from_obj(cls, obj, any_configurable=False): '''Create a proxy object from a callable. If `any_configurable` is true, `obj` takes a parameter named ``config``, and `obj` smells like it implements :class:`yakonfig.Configurable` (it has a :attr:`~yakonfig.Configurable.config_na...
[ "def", "from_obj", "(", "cls", ",", "obj", ",", "any_configurable", "=", "False", ")", ":", "discovered", "=", "cls", ".", "inspect_obj", "(", "obj", ")", "if", "(", "(", "any_configurable", "and", "'config'", "in", "discovered", "[", "'required'", "]", ...
Create a proxy object from a callable. If `any_configurable` is true, `obj` takes a parameter named ``config``, and `obj` smells like it implements :class:`yakonfig.Configurable` (it has a :attr:`~yakonfig.Configurable.config_name`), then return it directly.
[ "Create", "a", "proxy", "object", "from", "a", "callable", "." ]
train
https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/factory.py#L212-L228
diffeo/yakonfig
yakonfig/factory.py
AutoConfigured.check_config
def check_config(self, config, name=''): '''Check that the configuration for this object is valid. This is a more restrictive check than for most :mod:`yakonfig` objects. It will raise :exc:`yakonfig.ConfigurationError` if `config` contains any keys that are not in the underlying ...
python
def check_config(self, config, name=''): '''Check that the configuration for this object is valid. This is a more restrictive check than for most :mod:`yakonfig` objects. It will raise :exc:`yakonfig.ConfigurationError` if `config` contains any keys that are not in the underlying ...
[ "def", "check_config", "(", "self", ",", "config", ",", "name", "=", "''", ")", ":", "# This is assuming that `config` is the config dictionary of", "# the *config parent*. That is, `config[self.config_name]`", "# exists.", "config", "=", "config", ".", "get", "(", "self", ...
Check that the configuration for this object is valid. This is a more restrictive check than for most :mod:`yakonfig` objects. It will raise :exc:`yakonfig.ConfigurationError` if `config` contains any keys that are not in the underlying callable's parameter list (that is, extra unused ...
[ "Check", "that", "the", "configuration", "for", "this", "object", "is", "valid", "." ]
train
https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/factory.py#L248-L302
diffeo/yakonfig
yakonfig/factory.py
AutoConfigured.inspect_obj
def inspect_obj(obj): '''Learn what there is to be learned from our target. Given an object at `obj`, which must be a function, method or class, return a configuration *discovered* from the name of the object and its parameter list. This function is responsible for doing runtime...
python
def inspect_obj(obj): '''Learn what there is to be learned from our target. Given an object at `obj`, which must be a function, method or class, return a configuration *discovered* from the name of the object and its parameter list. This function is responsible for doing runtime...
[ "def", "inspect_obj", "(", "obj", ")", ":", "skip_params", "=", "0", "if", "inspect", ".", "isfunction", "(", "obj", ")", ":", "name", "=", "obj", ".", "__name__", "inspect_obj", "=", "obj", "skip_params", "=", "0", "elif", "inspect", ".", "ismethod", ...
Learn what there is to be learned from our target. Given an object at `obj`, which must be a function, method or class, return a configuration *discovered* from the name of the object and its parameter list. This function is responsible for doing runtime reflection and providing ...
[ "Learn", "what", "there", "is", "to", "be", "learned", "from", "our", "target", "." ]
train
https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/factory.py#L305-L397
listen-lavender/webcrawl
webcrawl/aboutfile.py
modulepath
def modulepath(filename): """ Find the relative path to its module of a python file if existing. filename string, name of a python file """ filepath = os.path.abspath(filename) prepath = filepath[:filepath.rindex('/')] postpath = '/' if prepath.count('/') == 0 or not os.path.exist...
python
def modulepath(filename): """ Find the relative path to its module of a python file if existing. filename string, name of a python file """ filepath = os.path.abspath(filename) prepath = filepath[:filepath.rindex('/')] postpath = '/' if prepath.count('/') == 0 or not os.path.exist...
[ "def", "modulepath", "(", "filename", ")", ":", "filepath", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "prepath", "=", "filepath", "[", ":", "filepath", ".", "rindex", "(", "'/'", ")", "]", "postpath", "=", "'/'", "if", "prepath", ...
Find the relative path to its module of a python file if existing. filename string, name of a python file
[ "Find", "the", "relative", "path", "to", "its", "module", "of", "a", "python", "file", "if", "existing", "." ]
train
https://github.com/listen-lavender/webcrawl/blob/905dcfa6e6934aac764045660c0efcef28eae1e6/webcrawl/aboutfile.py#L10-L37
the01/python-paps
paps/si/app/message.py
format_message_type
def format_message_type(message_type): """ Get printable version for message type :param message_type: Message type :type message_type: int :return: Printable version :rtype: str """ if message_type == MsgType.NOT_SET: return "NOT_SET" elif message_type == MsgType.ACK: ...
python
def format_message_type(message_type): """ Get printable version for message type :param message_type: Message type :type message_type: int :return: Printable version :rtype: str """ if message_type == MsgType.NOT_SET: return "NOT_SET" elif message_type == MsgType.ACK: ...
[ "def", "format_message_type", "(", "message_type", ")", ":", "if", "message_type", "==", "MsgType", ".", "NOT_SET", ":", "return", "\"NOT_SET\"", "elif", "message_type", "==", "MsgType", ".", "ACK", ":", "return", "\"ACK\"", "elif", "message_type", "==", "MsgTyp...
Get printable version for message type :param message_type: Message type :type message_type: int :return: Printable version :rtype: str
[ "Get", "printable", "version", "for", "message", "type" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L80-L104
the01/python-paps
paps/si/app/message.py
format_data
def format_data(data): """ Format bytes for printing :param data: Bytes :type data: None | bytearray | str :return: Printable version :rtype: unicode """ if data is None: return None return u":".join([u"{:02x}".format(ord(c)) for c in data])
python
def format_data(data): """ Format bytes for printing :param data: Bytes :type data: None | bytearray | str :return: Printable version :rtype: unicode """ if data is None: return None return u":".join([u"{:02x}".format(ord(c)) for c in data])
[ "def", "format_data", "(", "data", ")", ":", "if", "data", "is", "None", ":", "return", "None", "return", "u\":\"", ".", "join", "(", "[", "u\"{:02x}\"", ".", "format", "(", "ord", "(", "c", ")", ")", "for", "c", "in", "data", "]", ")" ]
Format bytes for printing :param data: Bytes :type data: None | bytearray | str :return: Printable version :rtype: unicode
[ "Format", "bytes", "for", "printing" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L107-L118
the01/python-paps
paps/si/app/message.py
guess_message_type
def guess_message_type(message): """ Guess the message type based on the class of message :param message: Message to guess the type for :type message: APPMessage :return: The corresponding message type (MsgType) or None if not found :rtype: None | int """ if isinstance(message, APPConf...
python
def guess_message_type(message): """ Guess the message type based on the class of message :param message: Message to guess the type for :type message: APPMessage :return: The corresponding message type (MsgType) or None if not found :rtype: None | int """ if isinstance(message, APPConf...
[ "def", "guess_message_type", "(", "message", ")", ":", "if", "isinstance", "(", "message", ",", "APPConfigMessage", ")", ":", "return", "MsgType", ".", "CONFIG", "elif", "isinstance", "(", "message", ",", "APPJoinMessage", ")", ":", "return", "MsgType", ".", ...
Guess the message type based on the class of message :param message: Message to guess the type for :type message: APPMessage :return: The corresponding message type (MsgType) or None if not found :rtype: None | int
[ "Guess", "the", "message", "type", "based", "on", "the", "class", "of", "message" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L145-L166
the01/python-paps
paps/si/app/message.py
APPHeader.timestamp_localize
def timestamp_localize(value): """ Save timestamp as utc :param value: Timestamp (in UTC or with tz_info) :type value: float | datetime.datetime :return: Localized timestamp :rtype: float """ if isinstance(value, datetime.datetime): if not val...
python
def timestamp_localize(value): """ Save timestamp as utc :param value: Timestamp (in UTC or with tz_info) :type value: float | datetime.datetime :return: Localized timestamp :rtype: float """ if isinstance(value, datetime.datetime): if not val...
[ "def", "timestamp_localize", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "if", "not", "value", ".", "tzinfo", ":", "value", "=", "pytz", ".", "UTC", ".", "localize", "(", "value", ")", "else", ...
Save timestamp as utc :param value: Timestamp (in UTC or with tz_info) :type value: float | datetime.datetime :return: Localized timestamp :rtype: float
[ "Save", "timestamp", "as", "utc" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L257-L274
the01/python-paps
paps/si/app/message.py
APPHeader.set_timestamp_to_current
def set_timestamp_to_current(self): """ Set timestamp to current time utc :rtype: None """ # Good form to add tzinfo self.timestamp = pytz.UTC.localize(datetime.datetime.utcnow())
python
def set_timestamp_to_current(self): """ Set timestamp to current time utc :rtype: None """ # Good form to add tzinfo self.timestamp = pytz.UTC.localize(datetime.datetime.utcnow())
[ "def", "set_timestamp_to_current", "(", "self", ")", ":", "# Good form to add tzinfo", "self", ".", "timestamp", "=", "pytz", ".", "UTC", ".", "localize", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ")" ]
Set timestamp to current time utc :rtype: None
[ "Set", "timestamp", "to", "current", "time", "utc" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L313-L320
the01/python-paps
paps/si/app/message.py
APPHeader.pack
def pack(self, update_timestamp=False): """ Pack this object into a transmittable format :param update_timestamp: Should the timestamp be updated to current (default: False) :type update_timestamp: bool :return: Packed data :rtype: bytearray :raises V...
python
def pack(self, update_timestamp=False): """ Pack this object into a transmittable format :param update_timestamp: Should the timestamp be updated to current (default: False) :type update_timestamp: bool :return: Packed data :rtype: bytearray :raises V...
[ "def", "pack", "(", "self", ",", "update_timestamp", "=", "False", ")", ":", "if", "self", ".", "device_id", "<=", "Id", ".", "NOT_SET", "or", "not", "isinstance", "(", "self", ".", "device_id", ",", "int", ")", ":", "raise", "ValueError", "(", "\"Inva...
Pack this object into a transmittable format :param update_timestamp: Should the timestamp be updated to current (default: False) :type update_timestamp: bool :return: Packed data :rtype: bytearray :raises ValueError: Invalid device id/message type
[ "Pack", "this", "object", "into", "a", "transmittable", "format" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L322-L359
the01/python-paps
paps/si/app/message.py
APPHeader.unpack
def unpack(cls, data): """ Unpack packed data into an instance :param data: Packed data :type data: str :return: Object instance and remaining data :rtype: (APPHeader, str) """ size = struct.calcsize(APPHeader.fmt_header) ( version, ms...
python
def unpack(cls, data): """ Unpack packed data into an instance :param data: Packed data :type data: str :return: Object instance and remaining data :rtype: (APPHeader, str) """ size = struct.calcsize(APPHeader.fmt_header) ( version, ms...
[ "def", "unpack", "(", "cls", ",", "data", ")", ":", "size", "=", "struct", ".", "calcsize", "(", "APPHeader", ".", "fmt_header", ")", "(", "version", ",", "msg_type", ",", "payload_len", ",", "timestamp", ",", "device_id", ",", "flags", ",", ")", ",", ...
Unpack packed data into an instance :param data: Packed data :type data: str :return: Object instance and remaining data :rtype: (APPHeader, str)
[ "Unpack", "packed", "data", "into", "an", "instance" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L362-L401
the01/python-paps
paps/si/app/message.py
APPMessage.update
def update(self, obj): """ Set this instance up based on another instance :param obj: Instance to copy from :type obj: APPMessage :rtype: None """ if isinstance(obj, APPMessage): self._header = obj._header self._payload = obj._payload
python
def update(self, obj): """ Set this instance up based on another instance :param obj: Instance to copy from :type obj: APPMessage :rtype: None """ if isinstance(obj, APPMessage): self._header = obj._header self._payload = obj._payload
[ "def", "update", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "APPMessage", ")", ":", "self", ".", "_header", "=", "obj", ".", "_header", "self", ".", "_payload", "=", "obj", ".", "_payload" ]
Set this instance up based on another instance :param obj: Instance to copy from :type obj: APPMessage :rtype: None
[ "Set", "this", "instance", "up", "based", "on", "another", "instance" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L477-L487
the01/python-paps
paps/si/app/message.py
APPMessage.payload_set
def payload_set(self, value): """ Set the message payload (and update header) :param value: New payload value :type value: unicode :rtype: None """ self._payload = value self._header.payload_length = len(self._payload)
python
def payload_set(self, value): """ Set the message payload (and update header) :param value: New payload value :type value: unicode :rtype: None """ self._payload = value self._header.payload_length = len(self._payload)
[ "def", "payload_set", "(", "self", ",", "value", ")", ":", "self", ".", "_payload", "=", "value", "self", ".", "_header", ".", "payload_length", "=", "len", "(", "self", ".", "_payload", ")" ]
Set the message payload (and update header) :param value: New payload value :type value: unicode :rtype: None
[ "Set", "the", "message", "payload", "(", "and", "update", "header", ")" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L498-L507
the01/python-paps
paps/si/app/message.py
APPMessage.pack
def pack(self, update_timestamp=False, insert_before_payload=""): """ Pack this object into a transmittable format :param update_timestamp: Should the timestamp be updated to current (default: False) :type update_timestamp: bool :param insert_before_payload: Insert t...
python
def pack(self, update_timestamp=False, insert_before_payload=""): """ Pack this object into a transmittable format :param update_timestamp: Should the timestamp be updated to current (default: False) :type update_timestamp: bool :param insert_before_payload: Insert t...
[ "def", "pack", "(", "self", ",", "update_timestamp", "=", "False", ",", "insert_before_payload", "=", "\"\"", ")", ":", "return", "self", ".", "_header", ".", "pack", "(", "update_timestamp", ")", "+", "insert_before_payload", "+", "self", ".", "_payload" ]
Pack this object into a transmittable format :param update_timestamp: Should the timestamp be updated to current (default: False) :type update_timestamp: bool :param insert_before_payload: Insert this after this data, but before payload (default: "") :type insert...
[ "Pack", "this", "object", "into", "a", "transmittable", "format" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L523-L539
the01/python-paps
paps/si/app/message.py
APPMessage.unpack
def unpack(cls, data): """ Unpack packed data into an instance :param data: Packed data :type data: str :return: Object instance and remaining data :rtype: (APPMessage, str) :raises ProtocolViolation: Data length smaller than payload length """ he...
python
def unpack(cls, data): """ Unpack packed data into an instance :param data: Packed data :type data: str :return: Object instance and remaining data :rtype: (APPMessage, str) :raises ProtocolViolation: Data length smaller than payload length """ he...
[ "def", "unpack", "(", "cls", ",", "data", ")", ":", "header", ",", "data", "=", "APPHeader", ".", "unpack", "(", "data", ")", "if", "len", "(", "data", ")", "<", "header", ".", "payload_length", ":", "raise", "ProtocolViolation", "(", "\"Payload too smal...
Unpack packed data into an instance :param data: Packed data :type data: str :return: Object instance and remaining data :rtype: (APPMessage, str) :raises ProtocolViolation: Data length smaller than payload length
[ "Unpack", "packed", "data", "into", "an", "instance" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L542-L560
the01/python-paps
paps/si/app/message.py
APPDataMessage.payload_set
def payload_set(self, value): """ Set the message payload (and update header) :param value: New payload value :type value: str :rtype: None """ payload = saveJSON(value, pretty=False) super(APPDataMessage, self).payload_set(payload)
python
def payload_set(self, value): """ Set the message payload (and update header) :param value: New payload value :type value: str :rtype: None """ payload = saveJSON(value, pretty=False) super(APPDataMessage, self).payload_set(payload)
[ "def", "payload_set", "(", "self", ",", "value", ")", ":", "payload", "=", "saveJSON", "(", "value", ",", "pretty", "=", "False", ")", "super", "(", "APPDataMessage", ",", "self", ")", ".", "payload_set", "(", "payload", ")" ]
Set the message payload (and update header) :param value: New payload value :type value: str :rtype: None
[ "Set", "the", "message", "payload", "(", "and", "update", "header", ")" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L645-L654
the01/python-paps
paps/si/app/message.py
APPUpdateMessage._pack_people
def _pack_people(people): """ Pack people into a network transmittable format :param people: People to pack :type people: list[paps.people.People] :return: The packed people :rtype: str """ res = bytearray() bits = bytearray([1]) for pers...
python
def _pack_people(people): """ Pack people into a network transmittable format :param people: People to pack :type people: list[paps.people.People] :return: The packed people :rtype: str """ res = bytearray() bits = bytearray([1]) for pers...
[ "def", "_pack_people", "(", "people", ")", ":", "res", "=", "bytearray", "(", ")", "bits", "=", "bytearray", "(", "[", "1", "]", ")", "for", "person", "in", "people", ":", "bits", ".", "extend", "(", "person", ".", "to_bits", "(", ")", ")", "aByte"...
Pack people into a network transmittable format :param people: People to pack :type people: list[paps.people.People] :return: The packed people :rtype: str
[ "Pack", "people", "into", "a", "network", "transmittable", "format" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L723-L745
the01/python-paps
paps/si/app/message.py
APPUpdateMessage.people
def people(self): """ The people list stored in payload (decoded upon every call()) :return: The people :rtype: list[paps.people.People] :raises ProtocolViolation: Failed to find marker Wrong number of bits in payload -> cannot decode into people ...
python
def people(self): """ The people list stored in payload (decoded upon every call()) :return: The people :rtype: list[paps.people.People] :raises ProtocolViolation: Failed to find marker Wrong number of bits in payload -> cannot decode into people ...
[ "def", "people", "(", "self", ")", ":", "people", "=", "[", "]", "bits", "=", "bytearray", "(", ")", "byts", "=", "struct", ".", "unpack", "(", "APPUpdateMessage", ".", "fmt", ".", "format", "(", "len", "(", "self", ".", "payload", ")", ")", ",", ...
The people list stored in payload (decoded upon every call()) :return: The people :rtype: list[paps.people.People] :raises ProtocolViolation: Failed to find marker Wrong number of bits in payload -> cannot decode into people
[ "The", "people", "list", "stored", "in", "payload", "(", "decoded", "upon", "every", "call", "()", ")" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L747-L798
se-esss-litterbox/Pynac
Pynac/Elements.py
Quad.from_dynacRepr
def from_dynacRepr(cls, pynacRepr): """ Construct a ``Quad`` instance from the Pynac lattice element """ L = float(pynacRepr[1][0][0]) B = float(pynacRepr[1][0][1]) aperRadius = float(pynacRepr[1][0][2]) return cls(L, B, aperRadius)
python
def from_dynacRepr(cls, pynacRepr): """ Construct a ``Quad`` instance from the Pynac lattice element """ L = float(pynacRepr[1][0][0]) B = float(pynacRepr[1][0][1]) aperRadius = float(pynacRepr[1][0][2]) return cls(L, B, aperRadius)
[ "def", "from_dynacRepr", "(", "cls", ",", "pynacRepr", ")", ":", "L", "=", "float", "(", "pynacRepr", "[", "1", "]", "[", "0", "]", "[", "0", "]", ")", "B", "=", "float", "(", "pynacRepr", "[", "1", "]", "[", "0", "]", "[", "1", "]", ")", "...
Construct a ``Quad`` instance from the Pynac lattice element
[ "Construct", "a", "Quad", "instance", "from", "the", "Pynac", "lattice", "element" ]
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L46-L53
se-esss-litterbox/Pynac
Pynac/Elements.py
Quad.scaleField
def scaleField(self, scalingFactor): """ Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field. """ self.B = self.B._replace(val=self.B.val * scaling...
python
def scaleField(self, scalingFactor): """ Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field. """ self.B = self.B._replace(val=self.B.val * scaling...
[ "def", "scaleField", "(", "self", ",", "scalingFactor", ")", ":", "self", ".", "B", "=", "self", ".", "B", ".", "_replace", "(", "val", "=", "self", ".", "B", ".", "val", "*", "scalingFactor", ")" ]
Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field.
[ "Adjust", "the", "field", "of", "the", "magnet", "by", "the", "value", "of", "scalingFactor", ".", "The", "adjustment", "is", "multiplicative", "so", "a", "value", "of", "scalingFactor", "=", "1", ".", "0", "will", "result", "in", "no", "change", "of", "...
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L55-L61
se-esss-litterbox/Pynac
Pynac/Elements.py
Quad.setField
def setField(self, new_value): """ Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field. """ self.B = self.B._replace(val=new_value)
python
def setField(self, new_value): """ Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field. """ self.B = self.B._replace(val=new_value)
[ "def", "setField", "(", "self", ",", "new_value", ")", ":", "self", ".", "B", "=", "self", ".", "B", ".", "_replace", "(", "val", "=", "new_value", ")" ]
Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field.
[ "Adjust", "the", "field", "of", "the", "magnet", "by", "the", "value", "of", "scalingFactor", ".", "The", "adjustment", "is", "multiplicative", "so", "a", "value", "of", "scalingFactor", "=", "1", ".", "0", "will", "result", "in", "no", "change", "of", "...
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L63-L69
se-esss-litterbox/Pynac
Pynac/Elements.py
Quad.dynacRepresentation
def dynacRepresentation(self): """ Return the Pynac representation of this quadrupole instance. """ return ['QUADRUPO', [[self.L.val, self.B.val, self.aperRadius.val]]]
python
def dynacRepresentation(self): """ Return the Pynac representation of this quadrupole instance. """ return ['QUADRUPO', [[self.L.val, self.B.val, self.aperRadius.val]]]
[ "def", "dynacRepresentation", "(", "self", ")", ":", "return", "[", "'QUADRUPO'", ",", "[", "[", "self", ".", "L", ".", "val", ",", "self", ".", "B", ".", "val", ",", "self", ".", "aperRadius", ".", "val", "]", "]", "]" ]
Return the Pynac representation of this quadrupole instance.
[ "Return", "the", "Pynac", "representation", "of", "this", "quadrupole", "instance", "." ]
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L71-L75
se-esss-litterbox/Pynac
Pynac/Elements.py
CavityAnalytic.from_dynacRepr
def from_dynacRepr(cls, pynacRepr): """ Construct a ``CavityAnalytic`` instance from the Pynac lattice element """ cavID = int(pynacRepr[1][0][0]) xesln = float(pynacRepr[1][1][0]) phase = float(pynacRepr[1][1][1]) fieldReduction = float(pynacRepr[1][1][2]) ...
python
def from_dynacRepr(cls, pynacRepr): """ Construct a ``CavityAnalytic`` instance from the Pynac lattice element """ cavID = int(pynacRepr[1][0][0]) xesln = float(pynacRepr[1][1][0]) phase = float(pynacRepr[1][1][1]) fieldReduction = float(pynacRepr[1][1][2]) ...
[ "def", "from_dynacRepr", "(", "cls", ",", "pynacRepr", ")", ":", "cavID", "=", "int", "(", "pynacRepr", "[", "1", "]", "[", "0", "]", "[", "0", "]", ")", "xesln", "=", "float", "(", "pynacRepr", "[", "1", "]", "[", "1", "]", "[", "0", "]", ")...
Construct a ``CavityAnalytic`` instance from the Pynac lattice element
[ "Construct", "a", "CavityAnalytic", "instance", "from", "the", "Pynac", "lattice", "element" ]
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L102-L111
se-esss-litterbox/Pynac
Pynac/Elements.py
CavityAnalytic.adjustPhase
def adjustPhase(self, adjustment): """ Adjust the accelerating phase of the cavity by the value of ``adjustment``. The adjustment is additive, so a value of ``scalingFactor = 0.0`` will result in no change of the phase. """ self.phase = self.phase._replace(val = self.phas...
python
def adjustPhase(self, adjustment): """ Adjust the accelerating phase of the cavity by the value of ``adjustment``. The adjustment is additive, so a value of ``scalingFactor = 0.0`` will result in no change of the phase. """ self.phase = self.phase._replace(val = self.phas...
[ "def", "adjustPhase", "(", "self", ",", "adjustment", ")", ":", "self", ".", "phase", "=", "self", ".", "phase", ".", "_replace", "(", "val", "=", "self", ".", "phase", ".", "val", "+", "adjustment", ")" ]
Adjust the accelerating phase of the cavity by the value of ``adjustment``. The adjustment is additive, so a value of ``scalingFactor = 0.0`` will result in no change of the phase.
[ "Adjust", "the", "accelerating", "phase", "of", "the", "cavity", "by", "the", "value", "of", "adjustment", ".", "The", "adjustment", "is", "additive", "so", "a", "value", "of", "scalingFactor", "=", "0", ".", "0", "will", "result", "in", "no", "change", ...
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L113-L119
se-esss-litterbox/Pynac
Pynac/Elements.py
CavityAnalytic.scaleField
def scaleField(self, scalingFactor): """ Adjust the accelerating field of the cavity by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field. """ oldField = self.fieldReduction.val ...
python
def scaleField(self, scalingFactor): """ Adjust the accelerating field of the cavity by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field. """ oldField = self.fieldReduction.val ...
[ "def", "scaleField", "(", "self", ",", "scalingFactor", ")", ":", "oldField", "=", "self", ".", "fieldReduction", ".", "val", "newField", "=", "100.0", "*", "(", "scalingFactor", "*", "(", "1.0", "+", "oldField", "/", "100.0", ")", "-", "1.0", ")", "se...
Adjust the accelerating field of the cavity by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field.
[ "Adjust", "the", "accelerating", "field", "of", "the", "cavity", "by", "the", "value", "of", "scalingFactor", ".", "The", "adjustment", "is", "multiplicative", "so", "a", "value", "of", "scalingFactor", "=", "1", ".", "0", "will", "result", "in", "no", "ch...
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L121-L129
se-esss-litterbox/Pynac
Pynac/Elements.py
CavityAnalytic.dynacRepresentation
def dynacRepresentation(self): """ Return the Dynac representation of this cavity instance. """ return ['CAVMC', [ [self.cavID.val], [self.xesln.val, self.phase.val, self.fieldReduction.val, self.isec.val, 1], ]]
python
def dynacRepresentation(self): """ Return the Dynac representation of this cavity instance. """ return ['CAVMC', [ [self.cavID.val], [self.xesln.val, self.phase.val, self.fieldReduction.val, self.isec.val, 1], ]]
[ "def", "dynacRepresentation", "(", "self", ")", ":", "return", "[", "'CAVMC'", ",", "[", "[", "self", ".", "cavID", ".", "val", "]", ",", "[", "self", ".", "xesln", ".", "val", ",", "self", ".", "phase", ".", "val", ",", "self", ".", "fieldReductio...
Return the Dynac representation of this cavity instance.
[ "Return", "the", "Dynac", "representation", "of", "this", "cavity", "instance", "." ]
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L131-L138
se-esss-litterbox/Pynac
Pynac/Elements.py
AccGap.from_dynacRepr
def from_dynacRepr(cls, pynacRepr): """ Construct a ``AccGap`` instance from the Pynac lattice element """ pynacList = pynacRepr[1][0] L = float(pynacList[3]) TTF = float(pynacList[4]) TTFprime = float(pynacList[5]) TTFprimeprime = float(pynacList[13]) ...
python
def from_dynacRepr(cls, pynacRepr): """ Construct a ``AccGap`` instance from the Pynac lattice element """ pynacList = pynacRepr[1][0] L = float(pynacList[3]) TTF = float(pynacList[4]) TTFprime = float(pynacList[5]) TTFprimeprime = float(pynacList[13]) ...
[ "def", "from_dynacRepr", "(", "cls", ",", "pynacRepr", ")", ":", "pynacList", "=", "pynacRepr", "[", "1", "]", "[", "0", "]", "L", "=", "float", "(", "pynacList", "[", "3", "]", ")", "TTF", "=", "float", "(", "pynacList", "[", "4", "]", ")", "TTF...
Construct a ``AccGap`` instance from the Pynac lattice element
[ "Construct", "a", "AccGap", "instance", "from", "the", "Pynac", "lattice", "element" ]
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L207-L232
se-esss-litterbox/Pynac
Pynac/Elements.py
AccGap.dynacRepresentation
def dynacRepresentation(self): """ Return the Dynac representation of this accelerating gap instance. """ details = [ self.gapID.val, self.energy.val, self.beta.val, self.L.val, self.TTF.val, self.TTFprime.val, ...
python
def dynacRepresentation(self): """ Return the Dynac representation of this accelerating gap instance. """ details = [ self.gapID.val, self.energy.val, self.beta.val, self.L.val, self.TTF.val, self.TTFprime.val, ...
[ "def", "dynacRepresentation", "(", "self", ")", ":", "details", "=", "[", "self", ".", "gapID", ".", "val", ",", "self", ".", "energy", ".", "val", ",", "self", ".", "beta", ".", "val", ",", "self", ".", "L", ".", "val", ",", "self", ".", "TTF", ...
Return the Dynac representation of this accelerating gap instance.
[ "Return", "the", "Dynac", "representation", "of", "this", "accelerating", "gap", "instance", "." ]
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L234-L256
se-esss-litterbox/Pynac
Pynac/Elements.py
Set4DAperture.from_dynacRepr
def from_dynacRepr(cls, pynacRepr): """ Construct a ``Set4DAperture`` instance from the Pynac lattice element """ energyDefnFlag = int(pynacRepr[1][0][0]) energy = float(pynacRepr[1][0][1]) phase = float(pynacRepr[1][0][2]) x = float(pynacRepr[1][0][3]) y ...
python
def from_dynacRepr(cls, pynacRepr): """ Construct a ``Set4DAperture`` instance from the Pynac lattice element """ energyDefnFlag = int(pynacRepr[1][0][0]) energy = float(pynacRepr[1][0][1]) phase = float(pynacRepr[1][0][2]) x = float(pynacRepr[1][0][3]) y ...
[ "def", "from_dynacRepr", "(", "cls", ",", "pynacRepr", ")", ":", "energyDefnFlag", "=", "int", "(", "pynacRepr", "[", "1", "]", "[", "0", "]", "[", "0", "]", ")", "energy", "=", "float", "(", "pynacRepr", "[", "1", "]", "[", "0", "]", "[", "1", ...
Construct a ``Set4DAperture`` instance from the Pynac lattice element
[ "Construct", "a", "Set4DAperture", "instance", "from", "the", "Pynac", "lattice", "element" ]
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L281-L292
se-esss-litterbox/Pynac
Pynac/Elements.py
Set4DAperture.dynacRepresentation
def dynacRepresentation(self): """ Return the Pynac representation of this Set4DAperture instance. """ details = [ self.energyDefnFlag.val, self.energy.val, self.phase.val, self.x.val, self.y.val, self.radius.val, ...
python
def dynacRepresentation(self): """ Return the Pynac representation of this Set4DAperture instance. """ details = [ self.energyDefnFlag.val, self.energy.val, self.phase.val, self.x.val, self.y.val, self.radius.val, ...
[ "def", "dynacRepresentation", "(", "self", ")", ":", "details", "=", "[", "self", ".", "energyDefnFlag", ".", "val", ",", "self", ".", "energy", ".", "val", ",", "self", ".", "phase", ".", "val", ",", "self", ".", "x", ".", "val", ",", "self", ".",...
Return the Pynac representation of this Set4DAperture instance.
[ "Return", "the", "Pynac", "representation", "of", "this", "Set4DAperture", "instance", "." ]
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L294-L306
se-esss-litterbox/Pynac
Pynac/Elements.py
Buncher.dynacRepresentation
def dynacRepresentation(self): """ Return the Pynac representation of this Set4DAperture instance. """ details = [ self.voltage.val, self.phase.val, self.harmonicNum.val, self.apertureRadius.val, ] return ['BUNCHER', [detail...
python
def dynacRepresentation(self): """ Return the Pynac representation of this Set4DAperture instance. """ details = [ self.voltage.val, self.phase.val, self.harmonicNum.val, self.apertureRadius.val, ] return ['BUNCHER', [detail...
[ "def", "dynacRepresentation", "(", "self", ")", ":", "details", "=", "[", "self", ".", "voltage", ".", "val", ",", "self", ".", "phase", ".", "val", ",", "self", ".", "harmonicNum", ".", "val", ",", "self", ".", "apertureRadius", ".", "val", ",", "]"...
Return the Pynac representation of this Set4DAperture instance.
[ "Return", "the", "Pynac", "representation", "of", "this", "Set4DAperture", "instance", "." ]
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L333-L343
se-esss-litterbox/Pynac
Pynac/Elements.py
Steerer.from_dynacRepr
def from_dynacRepr(cls, pynacRepr): """ Construct a ``Steerer`` instance from the Pynac lattice element """ f = float(pynacRepr[1][0][0]) p = 'HV'[int(pynacRepr[1][0][1])] return cls(f, p)
python
def from_dynacRepr(cls, pynacRepr): """ Construct a ``Steerer`` instance from the Pynac lattice element """ f = float(pynacRepr[1][0][0]) p = 'HV'[int(pynacRepr[1][0][1])] return cls(f, p)
[ "def", "from_dynacRepr", "(", "cls", ",", "pynacRepr", ")", ":", "f", "=", "float", "(", "pynacRepr", "[", "1", "]", "[", "0", "]", "[", "0", "]", ")", "p", "=", "'HV'", "[", "int", "(", "pynacRepr", "[", "1", "]", "[", "0", "]", "[", "1", ...
Construct a ``Steerer`` instance from the Pynac lattice element
[ "Construct", "a", "Steerer", "instance", "from", "the", "Pynac", "lattice", "element" ]
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L390-L396
se-esss-litterbox/Pynac
Pynac/Elements.py
Steerer.dynacRepresentation
def dynacRepresentation(self): """ Return the Dynac representation of this steerer instance. """ if self.plane.val == 'H': p = 0 elif self.plane.val == 'V': p = 1 return ['STEER', [[self.field_strength.val], [p]]]
python
def dynacRepresentation(self): """ Return the Dynac representation of this steerer instance. """ if self.plane.val == 'H': p = 0 elif self.plane.val == 'V': p = 1 return ['STEER', [[self.field_strength.val], [p]]]
[ "def", "dynacRepresentation", "(", "self", ")", ":", "if", "self", ".", "plane", ".", "val", "==", "'H'", ":", "p", "=", "0", "elif", "self", ".", "plane", ".", "val", "==", "'V'", ":", "p", "=", "1", "return", "[", "'STEER'", ",", "[", "[", "s...
Return the Dynac representation of this steerer instance.
[ "Return", "the", "Dynac", "representation", "of", "this", "steerer", "instance", "." ]
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L398-L406
se-esss-litterbox/Pynac
Pynac/Elements.py
Steerer.scaleField
def scaleField(self, scalingFactor): """ Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field. """ self.field_strength = self.field_strength._replac...
python
def scaleField(self, scalingFactor): """ Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field. """ self.field_strength = self.field_strength._replac...
[ "def", "scaleField", "(", "self", ",", "scalingFactor", ")", ":", "self", ".", "field_strength", "=", "self", ".", "field_strength", ".", "_replace", "(", "val", "=", "self", ".", "field_strength", ".", "val", "*", "scalingFactor", ")" ]
Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field.
[ "Adjust", "the", "field", "of", "the", "magnet", "by", "the", "value", "of", "scalingFactor", ".", "The", "adjustment", "is", "multiplicative", "so", "a", "value", "of", "scalingFactor", "=", "1", ".", "0", "will", "result", "in", "no", "change", "of", "...
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L408-L416
se-esss-litterbox/Pynac
Pynac/Elements.py
Steerer.setField
def setField(self, new_value): """ Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field. """ self.field_strength = self.field_strength._replace( ...
python
def setField(self, new_value): """ Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field. """ self.field_strength = self.field_strength._replace( ...
[ "def", "setField", "(", "self", ",", "new_value", ")", ":", "self", ".", "field_strength", "=", "self", ".", "field_strength", ".", "_replace", "(", "val", "=", "new_value", ")" ]
Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field.
[ "Adjust", "the", "field", "of", "the", "magnet", "by", "the", "value", "of", "scalingFactor", ".", "The", "adjustment", "is", "multiplicative", "so", "a", "value", "of", "scalingFactor", "=", "1", ".", "0", "will", "result", "in", "no", "change", "of", "...
train
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L418-L426
Archived-Object/ligament
ligament/__init__.py
main
def main(): """ parse command line opts and run a skeleton file when called from the command line, ligament looks in the current working directory for a file called `skeleton.py`. Tasks specified from the command line are then executed in order, and if the -w flag was specified, li...
python
def main(): """ parse command line opts and run a skeleton file when called from the command line, ligament looks in the current working directory for a file called `skeleton.py`. Tasks specified from the command line are then executed in order, and if the -w flag was specified, li...
[ "def", "main", "(", ")", ":", "options", "=", "None", "try", ":", "options", ",", "args", "=", "getopt", ".", "gnu_getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "\"whqv\"", ",", "[", "\"watch\"", ",", "\"help\"", ",", "\"query\"", ",",...
parse command line opts and run a skeleton file when called from the command line, ligament looks in the current working directory for a file called `skeleton.py`. Tasks specified from the command line are then executed in order, and if the -w flag was specified, ligament then watches ...
[ "parse", "command", "line", "opts", "and", "run", "a", "skeleton", "file" ]
train
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/__init__.py#L26-L78
b3j0f/schema
b3j0f/schema/base.py
Schema._getter
def _getter(self, obj): """Called when the parent element tries to get this property value. :param obj: parent object. """ result = None if self._fget_ is not None: result = self._fget_(obj) if result is None: result = getattr(obj, self._attrnam...
python
def _getter(self, obj): """Called when the parent element tries to get this property value. :param obj: parent object. """ result = None if self._fget_ is not None: result = self._fget_(obj) if result is None: result = getattr(obj, self._attrnam...
[ "def", "_getter", "(", "self", ",", "obj", ")", ":", "result", "=", "None", "if", "self", ".", "_fget_", "is", "not", "None", ":", "result", "=", "self", ".", "_fget_", "(", "obj", ")", "if", "result", "is", "None", ":", "result", "=", "getattr", ...
Called when the parent element tries to get this property value. :param obj: parent object.
[ "Called", "when", "the", "parent", "element", "tries", "to", "get", "this", "property", "value", "." ]
train
https://github.com/b3j0f/schema/blob/1c88c23337f5fef50254e65bd407112c43396dd9/b3j0f/schema/base.py#L165-L182
b3j0f/schema
b3j0f/schema/base.py
Schema._setter
def _setter(self, obj, value): """Called when the parent element tries to set this property value. :param obj: parent object. :param value: new value to use. If lambda, updated with the lambda result. """ if isinstance(value, DynamicValue): # execute lambda values. ...
python
def _setter(self, obj, value): """Called when the parent element tries to set this property value. :param obj: parent object. :param value: new value to use. If lambda, updated with the lambda result. """ if isinstance(value, DynamicValue): # execute lambda values. ...
[ "def", "_setter", "(", "self", ",", "obj", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "DynamicValue", ")", ":", "# execute lambda values.", "fvalue", "=", "value", "(", ")", "else", ":", "fvalue", "=", "value", "self", ".", "_validate...
Called when the parent element tries to set this property value. :param obj: parent object. :param value: new value to use. If lambda, updated with the lambda result.
[ "Called", "when", "the", "parent", "element", "tries", "to", "set", "this", "property", "value", "." ]
train
https://github.com/b3j0f/schema/blob/1c88c23337f5fef50254e65bd407112c43396dd9/b3j0f/schema/base.py#L191-L214
b3j0f/schema
b3j0f/schema/base.py
Schema._deleter
def _deleter(self, obj): """Called when the parent element tries to delete this property value. :param obj: parent object. """ if self._fdel_ is not None: self._fdel_(obj) else: delattr(obj, self._attrname()) # notify parent schema about value d...
python
def _deleter(self, obj): """Called when the parent element tries to delete this property value. :param obj: parent object. """ if self._fdel_ is not None: self._fdel_(obj) else: delattr(obj, self._attrname()) # notify parent schema about value d...
[ "def", "_deleter", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "_fdel_", "is", "not", "None", ":", "self", ".", "_fdel_", "(", "obj", ")", "else", ":", "delattr", "(", "obj", ",", "self", ".", "_attrname", "(", ")", ")", "# notify parent ...
Called when the parent element tries to delete this property value. :param obj: parent object.
[ "Called", "when", "the", "parent", "element", "tries", "to", "delete", "this", "property", "value", "." ]
train
https://github.com/b3j0f/schema/blob/1c88c23337f5fef50254e65bd407112c43396dd9/b3j0f/schema/base.py#L223-L236
b3j0f/schema
b3j0f/schema/base.py
Schema._validate
def _validate(self, data, owner=None): """Validate input data in returning an empty list if true. :param data: data to validate with this schema. :param Schema owner: schema owner. :raises: Exception if the data is not validated. """ if isinstance(data, DynamicValue): ...
python
def _validate(self, data, owner=None): """Validate input data in returning an empty list if true. :param data: data to validate with this schema. :param Schema owner: schema owner. :raises: Exception if the data is not validated. """ if isinstance(data, DynamicValue): ...
[ "def", "_validate", "(", "self", ",", "data", ",", "owner", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "DynamicValue", ")", ":", "data", "=", "data", "(", ")", "if", "data", "is", "None", "and", "not", "self", ".", "nullable", ":"...
Validate input data in returning an empty list if true. :param data: data to validate with this schema. :param Schema owner: schema owner. :raises: Exception if the data is not validated.
[ "Validate", "input", "data", "in", "returning", "an", "empty", "list", "if", "true", "." ]
train
https://github.com/b3j0f/schema/blob/1c88c23337f5fef50254e65bd407112c43396dd9/b3j0f/schema/base.py#L244-L283
b3j0f/schema
b3j0f/schema/base.py
Schema.getschemas
def getschemas(cls): """Get inner schemas by name. :return: ordered dict by name. :rtype: OrderedDict """ members = getmembers(cls, lambda member: isinstance(member, Schema)) result = OrderedDict() for name, member in members: result[name] = member ...
python
def getschemas(cls): """Get inner schemas by name. :return: ordered dict by name. :rtype: OrderedDict """ members = getmembers(cls, lambda member: isinstance(member, Schema)) result = OrderedDict() for name, member in members: result[name] = member ...
[ "def", "getschemas", "(", "cls", ")", ":", "members", "=", "getmembers", "(", "cls", ",", "lambda", "member", ":", "isinstance", "(", "member", ",", "Schema", ")", ")", "result", "=", "OrderedDict", "(", ")", "for", "name", ",", "member", "in", "member...
Get inner schemas by name. :return: ordered dict by name. :rtype: OrderedDict
[ "Get", "inner", "schemas", "by", "name", "." ]
train
https://github.com/b3j0f/schema/blob/1c88c23337f5fef50254e65bd407112c43396dd9/b3j0f/schema/base.py#L286-L299
JonLiuFYI/pkdx
pkdx/pkdx/main.py
description
def description(pokemon): """Return a description of the given Pokemon.""" r = requests.get('http://pokeapi.co/' + (pokemon.descriptions.values()[0])) desc = eval(r.text)['description'].replace('Pokmon', 'Pokémon') return desc
python
def description(pokemon): """Return a description of the given Pokemon.""" r = requests.get('http://pokeapi.co/' + (pokemon.descriptions.values()[0])) desc = eval(r.text)['description'].replace('Pokmon', 'Pokémon') return desc
[ "def", "description", "(", "pokemon", ")", ":", "r", "=", "requests", ".", "get", "(", "'http://pokeapi.co/'", "+", "(", "pokemon", ".", "descriptions", ".", "values", "(", ")", "[", "0", "]", ")", ")", "desc", "=", "eval", "(", "r", ".", "text", "...
Return a description of the given Pokemon.
[ "Return", "a", "description", "of", "the", "given", "Pokemon", "." ]
train
https://github.com/JonLiuFYI/pkdx/blob/269e9814df074e0df25972fad04539a644d73a3c/pkdx/pkdx/main.py#L29-L33
JonLiuFYI/pkdx
pkdx/pkdx/main.py
get_ability_desc
def get_ability_desc(ability): """Return the description matching the given ability name. Check abilities.json in the same directory.""" srcpath = path.dirname(__file__) try: f = open(path.join(srcpath, 'abilities.json'), 'r') except IOError: get_abilities() f = open(path.join(sr...
python
def get_ability_desc(ability): """Return the description matching the given ability name. Check abilities.json in the same directory.""" srcpath = path.dirname(__file__) try: f = open(path.join(srcpath, 'abilities.json'), 'r') except IOError: get_abilities() f = open(path.join(sr...
[ "def", "get_ability_desc", "(", "ability", ")", ":", "srcpath", "=", "path", ".", "dirname", "(", "__file__", ")", "try", ":", "f", "=", "open", "(", "path", ".", "join", "(", "srcpath", ",", "'abilities.json'", ")", ",", "'r'", ")", "except", "IOError...
Return the description matching the given ability name. Check abilities.json in the same directory.
[ "Return", "the", "description", "matching", "the", "given", "ability", "name", ".", "Check", "abilities", ".", "json", "in", "the", "same", "directory", "." ]
train
https://github.com/JonLiuFYI/pkdx/blob/269e9814df074e0df25972fad04539a644d73a3c/pkdx/pkdx/main.py#L47-L57
JonLiuFYI/pkdx
pkdx/pkdx/main.py
get_move_data
def get_move_data(move): """Return the index number for the given move name. Check moves.json in the same directory.""" srcpath = path.dirname(__file__) try: f = open(path.join(srcpath, 'moves.json'), 'r') except IOError: get_moves() f = open(path.join(srcpath, 'moves.json'), 'r'...
python
def get_move_data(move): """Return the index number for the given move name. Check moves.json in the same directory.""" srcpath = path.dirname(__file__) try: f = open(path.join(srcpath, 'moves.json'), 'r') except IOError: get_moves() f = open(path.join(srcpath, 'moves.json'), 'r'...
[ "def", "get_move_data", "(", "move", ")", ":", "srcpath", "=", "path", ".", "dirname", "(", "__file__", ")", "try", ":", "f", "=", "open", "(", "path", ".", "join", "(", "srcpath", ",", "'moves.json'", ")", ",", "'r'", ")", "except", "IOError", ":", ...
Return the index number for the given move name. Check moves.json in the same directory.
[ "Return", "the", "index", "number", "for", "the", "given", "move", "name", ".", "Check", "moves", ".", "json", "in", "the", "same", "directory", "." ]
train
https://github.com/JonLiuFYI/pkdx/blob/269e9814df074e0df25972fad04539a644d73a3c/pkdx/pkdx/main.py#L60-L70
fr33jc/bang
bang/deployers/cloud.py
SSHKeyDeployer.register
def register(self): """Registers SSH key with provider.""" log.info('Installing ssh key, %s' % self.name) self.consul.create_ssh_pub_key(self.name, self.key)
python
def register(self): """Registers SSH key with provider.""" log.info('Installing ssh key, %s' % self.name) self.consul.create_ssh_pub_key(self.name, self.key)
[ "def", "register", "(", "self", ")", ":", "log", ".", "info", "(", "'Installing ssh key, %s'", "%", "self", ".", "name", ")", "self", ".", "consul", ".", "create_ssh_pub_key", "(", "self", ".", "name", ",", "self", ".", "key", ")" ]
Registers SSH key with provider.
[ "Registers", "SSH", "key", "with", "provider", "." ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/cloud.py#L61-L64
fr33jc/bang
bang/deployers/cloud.py
ServerDeployer.find_existing
def find_existing(self): """ Searches for existing server instances with matching tags. To match, the existing instances must also be "running". """ instances = self.consul.find_servers(self.tags) maxnames = len(instances) while instances: i = instan...
python
def find_existing(self): """ Searches for existing server instances with matching tags. To match, the existing instances must also be "running". """ instances = self.consul.find_servers(self.tags) maxnames = len(instances) while instances: i = instan...
[ "def", "find_existing", "(", "self", ")", ":", "instances", "=", "self", ".", "consul", ".", "find_servers", "(", "self", ".", "tags", ")", "maxnames", "=", "len", "(", "instances", ")", "while", "instances", ":", "i", "=", "instances", ".", "pop", "("...
Searches for existing server instances with matching tags. To match, the existing instances must also be "running".
[ "Searches", "for", "existing", "server", "instances", "with", "matching", "tags", ".", "To", "match", "the", "existing", "instances", "must", "also", "be", "running", "." ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/cloud.py#L85-L102
fr33jc/bang
bang/deployers/cloud.py
ServerDeployer.wait_for_running
def wait_for_running(self): """Waits for found servers to be operational""" self.server_attrs = self.consul.find_running( self.server_attrs, self.launch_timeout_s, )
python
def wait_for_running(self): """Waits for found servers to be operational""" self.server_attrs = self.consul.find_running( self.server_attrs, self.launch_timeout_s, )
[ "def", "wait_for_running", "(", "self", ")", ":", "self", ".", "server_attrs", "=", "self", ".", "consul", ".", "find_running", "(", "self", ".", "server_attrs", ",", "self", ".", "launch_timeout_s", ",", ")" ]
Waits for found servers to be operational
[ "Waits", "for", "found", "servers", "to", "be", "operational" ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/cloud.py#L104-L109
fr33jc/bang
bang/deployers/cloud.py
ServerDeployer.create
def create(self): """Launches a new server instance.""" self.server_attrs = self.consul.create_server( "%s-%s" % (self.stack.name, self.name), self.disk_image_id, self.instance_type, self.ssh_key_name, tags=self.tags, ...
python
def create(self): """Launches a new server instance.""" self.server_attrs = self.consul.create_server( "%s-%s" % (self.stack.name, self.name), self.disk_image_id, self.instance_type, self.ssh_key_name, tags=self.tags, ...
[ "def", "create", "(", "self", ")", ":", "self", ".", "server_attrs", "=", "self", ".", "consul", ".", "create_server", "(", "\"%s-%s\"", "%", "(", "self", ".", "stack", ".", "name", ",", "self", ".", "name", ")", ",", "self", ".", "disk_image_id", ",...
Launches a new server instance.
[ "Launches", "a", "new", "server", "instance", "." ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/cloud.py#L111-L125
fr33jc/bang
bang/deployers/cloud.py
ServerDeployer.add_to_inventory
def add_to_inventory(self): """Adds host to stack inventory""" if not self.server_attrs: return for addy in self.server_attrs[A.server.PUBLIC_IPS]: self.stack.add_host(addy, self.groups, self.hostvars)
python
def add_to_inventory(self): """Adds host to stack inventory""" if not self.server_attrs: return for addy in self.server_attrs[A.server.PUBLIC_IPS]: self.stack.add_host(addy, self.groups, self.hostvars)
[ "def", "add_to_inventory", "(", "self", ")", ":", "if", "not", "self", ".", "server_attrs", ":", "return", "for", "addy", "in", "self", ".", "server_attrs", "[", "A", ".", "server", ".", "PUBLIC_IPS", "]", ":", "self", ".", "stack", ".", "add_host", "(...
Adds host to stack inventory
[ "Adds", "host", "to", "stack", "inventory" ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/cloud.py#L127-L132
fr33jc/bang
bang/deployers/cloud.py
CloudManagerServerDeployer.define
def define(self): """Defines a new server.""" self.server_def = self.consul.define_server( self.name, self.server_tpl, self.server_tpl_rev, self.instance_type, self.ssh_key_name, tags=self.tags, ...
python
def define(self): """Defines a new server.""" self.server_def = self.consul.define_server( self.name, self.server_tpl, self.server_tpl_rev, self.instance_type, self.ssh_key_name, tags=self.tags, ...
[ "def", "define", "(", "self", ")", ":", "self", ".", "server_def", "=", "self", ".", "consul", ".", "define_server", "(", "self", ".", "name", ",", "self", ".", "server_tpl", ",", "self", ".", "server_tpl_rev", ",", "self", ".", "instance_type", ",", "...
Defines a new server.
[ "Defines", "a", "new", "server", "." ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/cloud.py#L176-L189
fr33jc/bang
bang/deployers/cloud.py
SecurityGroupRulesetDeployer.find_existing
def find_existing(self): """ Finds existing rule in secgroup. Populates ``self.create_these_rules`` and ``self.delete_these_rules``. """ sg = self.consul.find_secgroup(self.name) current = sg.rules log.debug('Current rules: %s' % current) log.debug('Int...
python
def find_existing(self): """ Finds existing rule in secgroup. Populates ``self.create_these_rules`` and ``self.delete_these_rules``. """ sg = self.consul.find_secgroup(self.name) current = sg.rules log.debug('Current rules: %s' % current) log.debug('Int...
[ "def", "find_existing", "(", "self", ")", ":", "sg", "=", "self", ".", "consul", ".", "find_secgroup", "(", "self", ".", "name", ")", "current", "=", "sg", ".", "rules", "log", ".", "debug", "(", "'Current rules: %s'", "%", "current", ")", "log", ".", ...
Finds existing rule in secgroup. Populates ``self.create_these_rules`` and ``self.delete_these_rules``.
[ "Finds", "existing", "rule", "in", "secgroup", "." ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/cloud.py#L231-L260
fr33jc/bang
bang/deployers/cloud.py
SecurityGroupRulesetDeployer.apply_rule_changes
def apply_rule_changes(self): """ Makes the security group rules match what is defined in the Bang config file. """ # TODO: add error handling for rule in self.delete_these_rules: self.consul.delete_secgroup_rule(rule) log.info("Revoked: %s" % rul...
python
def apply_rule_changes(self): """ Makes the security group rules match what is defined in the Bang config file. """ # TODO: add error handling for rule in self.delete_these_rules: self.consul.delete_secgroup_rule(rule) log.info("Revoked: %s" % rul...
[ "def", "apply_rule_changes", "(", "self", ")", ":", "# TODO: add error handling", "for", "rule", "in", "self", ".", "delete_these_rules", ":", "self", ".", "consul", ".", "delete_secgroup_rule", "(", "rule", ")", "log", ".", "info", "(", "\"Revoked: %s\"", "%", ...
Makes the security group rules match what is defined in the Bang config file.
[ "Makes", "the", "security", "group", "rules", "match", "what", "is", "defined", "in", "the", "Bang", "config", "file", "." ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/cloud.py#L262-L275
fr33jc/bang
bang/deployers/cloud.py
BucketDeployer.create
def create(self): """Creates a new bucket""" self.consul.create_bucket("%s-%s" % (self.stack.name, self.name))
python
def create(self): """Creates a new bucket""" self.consul.create_bucket("%s-%s" % (self.stack.name, self.name))
[ "def", "create", "(", "self", ")", ":", "self", ".", "consul", ".", "create_bucket", "(", "\"%s-%s\"", "%", "(", "self", ".", "stack", ".", "name", ",", "self", ".", "name", ")", ")" ]
Creates a new bucket
[ "Creates", "a", "new", "bucket" ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/cloud.py#L285-L287
fr33jc/bang
bang/deployers/cloud.py
DatabaseDeployer.create
def create(self): """Creates a new database""" self.db_attrs = self.consul.create_db( self.instance_name, self.instance_type, self.admin_username, self.admin_password, db_name=self.db_name, storage_size_gb=se...
python
def create(self): """Creates a new database""" self.db_attrs = self.consul.create_db( self.instance_name, self.instance_type, self.admin_username, self.admin_password, db_name=self.db_name, storage_size_gb=se...
[ "def", "create", "(", "self", ")", ":", "self", ".", "db_attrs", "=", "self", ".", "consul", ".", "create_db", "(", "self", ".", "instance_name", ",", "self", ".", "instance_type", ",", "self", ".", "admin_username", ",", "self", ".", "admin_password", "...
Creates a new database
[ "Creates", "a", "new", "database" ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/cloud.py#L313-L323
fr33jc/bang
bang/deployers/cloud.py
DatabaseDeployer.add_to_inventory
def add_to_inventory(self): """Adds db host to stack inventory""" host = self.db_attrs.pop(A.database.HOST) self.stack.add_host( host, self.groups, self.db_attrs )
python
def add_to_inventory(self): """Adds db host to stack inventory""" host = self.db_attrs.pop(A.database.HOST) self.stack.add_host( host, self.groups, self.db_attrs )
[ "def", "add_to_inventory", "(", "self", ")", ":", "host", "=", "self", ".", "db_attrs", ".", "pop", "(", "A", ".", "database", ".", "HOST", ")", "self", ".", "stack", ".", "add_host", "(", "host", ",", "self", ".", "groups", ",", "self", ".", "db_a...
Adds db host to stack inventory
[ "Adds", "db", "host", "to", "stack", "inventory" ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/cloud.py#L325-L332
fr33jc/bang
bang/deployers/cloud.py
LoadBalancerDeployer.create
def create(self): """Creates a new load balancer""" required_nodes = self._get_required_nodes() self.lb_attrs = self.consul.create_lb( self.instance_name, protocol=self.protocol, port=self.port, nodes=required_nodes, ...
python
def create(self): """Creates a new load balancer""" required_nodes = self._get_required_nodes() self.lb_attrs = self.consul.create_lb( self.instance_name, protocol=self.protocol, port=self.port, nodes=required_nodes, ...
[ "def", "create", "(", "self", ")", ":", "required_nodes", "=", "self", ".", "_get_required_nodes", "(", ")", "self", ".", "lb_attrs", "=", "self", ".", "consul", ".", "create_lb", "(", "self", ".", "instance_name", ",", "protocol", "=", "self", ".", "pro...
Creates a new load balancer
[ "Creates", "a", "new", "load", "balancer" ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/cloud.py#L382-L392
fr33jc/bang
bang/deployers/cloud.py
LoadBalancerDeployer.configure_nodes
def configure_nodes(self): """Ensure that the LB's nodes matches the stack""" # Since load balancing runs after server provisioning, # the servers should already be created regardless of # whether this was a preexisting load balancer or not. # We also have the existing nodes, bec...
python
def configure_nodes(self): """Ensure that the LB's nodes matches the stack""" # Since load balancing runs after server provisioning, # the servers should already be created regardless of # whether this was a preexisting load balancer or not. # We also have the existing nodes, bec...
[ "def", "configure_nodes", "(", "self", ")", ":", "# Since load balancing runs after server provisioning,", "# the servers should already be created regardless of", "# whether this was a preexisting load balancer or not.", "# We also have the existing nodes, because add_to_inventory", "# has been...
Ensure that the LB's nodes matches the stack
[ "Ensure", "that", "the", "LB", "s", "nodes", "matches", "the", "stack" ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/cloud.py#L394-L416
fr33jc/bang
bang/deployers/cloud.py
LoadBalancerDeployer.add_to_inventory
def add_to_inventory(self): """Adds lb IPs to stack inventory""" if self.lb_attrs: self.lb_attrs = self.consul.lb_details( self.lb_attrs[A.loadbalancer.ID] ) host = self.lb_attrs['virtualIps'][0]['address'] self.stack.add_lb_sec...
python
def add_to_inventory(self): """Adds lb IPs to stack inventory""" if self.lb_attrs: self.lb_attrs = self.consul.lb_details( self.lb_attrs[A.loadbalancer.ID] ) host = self.lb_attrs['virtualIps'][0]['address'] self.stack.add_lb_sec...
[ "def", "add_to_inventory", "(", "self", ")", ":", "if", "self", ".", "lb_attrs", ":", "self", ".", "lb_attrs", "=", "self", ".", "consul", ".", "lb_details", "(", "self", ".", "lb_attrs", "[", "A", ".", "loadbalancer", ".", "ID", "]", ")", "host", "=...
Adds lb IPs to stack inventory
[ "Adds", "lb", "IPs", "to", "stack", "inventory" ]
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/cloud.py#L425-L437
Archived-Object/ligament
ligament/buildtarget.py
BuildTarget.register_with_context
def register_with_context(self, myname, context): """ registers this build target (exclusively) with a given context """ if self.context is not None: raise Exception("attempted to register BuildTarget with multiple " "BuildContexts") context.register_tas...
python
def register_with_context(self, myname, context): """ registers this build target (exclusively) with a given context """ if self.context is not None: raise Exception("attempted to register BuildTarget with multiple " "BuildContexts") context.register_tas...
[ "def", "register_with_context", "(", "self", ",", "myname", ",", "context", ")", ":", "if", "self", ".", "context", "is", "not", "None", ":", "raise", "Exception", "(", "\"attempted to register BuildTarget with multiple \"", "\"BuildContexts\"", ")", "context", ".",...
registers this build target (exclusively) with a given context
[ "registers", "this", "build", "target", "(", "exclusively", ")", "with", "a", "given", "context" ]
train
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/buildtarget.py#L58-L74
Archived-Object/ligament
ligament/buildtarget.py
BuildTarget.resolve_dependencies
def resolve_dependencies(self): """ evaluate each of the data dependencies of this build target, returns the resulting dict""" return dict( [((key, self.data_dependencies[key]) if type(self.data_dependencies[key]) != DeferredDependency else (key, s...
python
def resolve_dependencies(self): """ evaluate each of the data dependencies of this build target, returns the resulting dict""" return dict( [((key, self.data_dependencies[key]) if type(self.data_dependencies[key]) != DeferredDependency else (key, s...
[ "def", "resolve_dependencies", "(", "self", ")", ":", "return", "dict", "(", "[", "(", "(", "key", ",", "self", ".", "data_dependencies", "[", "key", "]", ")", "if", "type", "(", "self", ".", "data_dependencies", "[", "key", "]", ")", "!=", "DeferredDe...
evaluate each of the data dependencies of this build target, returns the resulting dict
[ "evaluate", "each", "of", "the", "data", "dependencies", "of", "this", "build", "target", "returns", "the", "resulting", "dict" ]
train
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/buildtarget.py#L76-L83
Archived-Object/ligament
ligament/buildtarget.py
BuildTarget.resolve_and_build
def resolve_and_build(self): """ resolves the dependencies of this build target and builds it """ pdebug("resolving and building task '%s'" % self.name, groups=["build_task"]) indent_text(indent="++2") toret = self.build(**self.resolve_dependencies()) indent_text(...
python
def resolve_and_build(self): """ resolves the dependencies of this build target and builds it """ pdebug("resolving and building task '%s'" % self.name, groups=["build_task"]) indent_text(indent="++2") toret = self.build(**self.resolve_dependencies()) indent_text(...
[ "def", "resolve_and_build", "(", "self", ")", ":", "pdebug", "(", "\"resolving and building task '%s'\"", "%", "self", ".", "name", ",", "groups", "=", "[", "\"build_task\"", "]", ")", "indent_text", "(", "indent", "=", "\"++2\"", ")", "toret", "=", "self", ...
resolves the dependencies of this build target and builds it
[ "resolves", "the", "dependencies", "of", "this", "build", "target", "and", "builds", "it" ]
train
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/buildtarget.py#L85-L92
ironfroggy/django-better-cache
bettercache/middleware.py
BetterCacheMiddleware.process_request
def process_request(self, request): """ Checks whether the page is already cached and returns the cached version if available. """ celery_task = getattr(request, '_cache_update_cache', False) if not request.method in ('GET', 'HEAD'): request._cache_update_cac...
python
def process_request(self, request): """ Checks whether the page is already cached and returns the cached version if available. """ celery_task = getattr(request, '_cache_update_cache', False) if not request.method in ('GET', 'HEAD'): request._cache_update_cac...
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "celery_task", "=", "getattr", "(", "request", ",", "'_cache_update_cache'", ",", "False", ")", "if", "not", "request", ".", "method", "in", "(", "'GET'", ",", "'HEAD'", ")", ":", "request", ...
Checks whether the page is already cached and returns the cached version if available.
[ "Checks", "whether", "the", "page", "is", "already", "cached", "and", "returns", "the", "cached", "version", "if", "available", "." ]
train
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/middleware.py#L25-L54
ironfroggy/django-better-cache
bettercache/middleware.py
BetterCacheMiddleware.process_response
def process_response(self, request, response): """ Sets the cache and deals with caching headers if needed """ if not self.should_cache(request, response): # We don't need to update the cache, just return return response response = self.patch_headers(response) ...
python
def process_response(self, request, response): """ Sets the cache and deals with caching headers if needed """ if not self.should_cache(request, response): # We don't need to update the cache, just return return response response = self.patch_headers(response) ...
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "if", "not", "self", ".", "should_cache", "(", "request", ",", "response", ")", ":", "# We don't need to update the cache, just return", "return", "response", "response", "=", "self...
Sets the cache and deals with caching headers if needed
[ "Sets", "the", "cache", "and", "deals", "with", "caching", "headers", "if", "needed" ]
train
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/middleware.py#L56-L66
ironfroggy/django-better-cache
bettercache/objects.py
CacheModel.keys
def keys(self): """Create an ordered dict of the names and values of key fields.""" keys = OrderedDict() def order_key(_): (k, v) = _ cache_key = getattr(type(self), k) return cache_key.order items = [(k, getattr(type(self), k)) for k in...
python
def keys(self): """Create an ordered dict of the names and values of key fields.""" keys = OrderedDict() def order_key(_): (k, v) = _ cache_key = getattr(type(self), k) return cache_key.order items = [(k, getattr(type(self), k)) for k in...
[ "def", "keys", "(", "self", ")", ":", "keys", "=", "OrderedDict", "(", ")", "def", "order_key", "(", "_", ")", ":", "(", "k", ",", "v", ")", "=", "_", "cache_key", "=", "getattr", "(", "type", "(", "self", ")", ",", "k", ")", "return", "cache_k...
Create an ordered dict of the names and values of key fields.
[ "Create", "an", "ordered", "dict", "of", "the", "names", "and", "values", "of", "key", "fields", "." ]
train
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/objects.py#L69-L89
ironfroggy/django-better-cache
bettercache/objects.py
CacheModel.serialize
def serialize(self): """Serialize all the fields into one string.""" keys = self._all_keys() serdata = {} for fieldname, value in self._data.items(): serdata[fieldname] = getattr(type(self), fieldname).python_to_cache(value) return json.dumps(serdata)
python
def serialize(self): """Serialize all the fields into one string.""" keys = self._all_keys() serdata = {} for fieldname, value in self._data.items(): serdata[fieldname] = getattr(type(self), fieldname).python_to_cache(value) return json.dumps(serdata)
[ "def", "serialize", "(", "self", ")", ":", "keys", "=", "self", ".", "_all_keys", "(", ")", "serdata", "=", "{", "}", "for", "fieldname", ",", "value", "in", "self", ".", "_data", ".", "items", "(", ")", ":", "serdata", "[", "fieldname", "]", "=", ...
Serialize all the fields into one string.
[ "Serialize", "all", "the", "fields", "into", "one", "string", "." ]
train
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/objects.py#L110-L117
ironfroggy/django-better-cache
bettercache/objects.py
CacheModel.deserialize
def deserialize(cls, string): """Reconstruct a previously serialized string back into an instance of a ``CacheModel``.""" data = json.loads(string) for fieldname, value in data.items(): data[fieldname] = getattr(cls, fieldname).cache_to_python(value) return cls(**data)
python
def deserialize(cls, string): """Reconstruct a previously serialized string back into an instance of a ``CacheModel``.""" data = json.loads(string) for fieldname, value in data.items(): data[fieldname] = getattr(cls, fieldname).cache_to_python(value) return cls(**data)
[ "def", "deserialize", "(", "cls", ",", "string", ")", ":", "data", "=", "json", ".", "loads", "(", "string", ")", "for", "fieldname", ",", "value", "in", "data", ".", "items", "(", ")", ":", "data", "[", "fieldname", "]", "=", "getattr", "(", "cls"...
Reconstruct a previously serialized string back into an instance of a ``CacheModel``.
[ "Reconstruct", "a", "previously", "serialized", "string", "back", "into", "an", "instance", "of", "a", "CacheModel", "." ]
train
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/objects.py#L120-L126
ironfroggy/django-better-cache
bettercache/objects.py
CacheModel.save
def save(self, expires=None): """Save a copy of the object into the cache.""" if expires is None: expires = self.expires s = self.serialize() key = self._key(self._all_keys()) _cache.set(key, s, expires)
python
def save(self, expires=None): """Save a copy of the object into the cache.""" if expires is None: expires = self.expires s = self.serialize() key = self._key(self._all_keys()) _cache.set(key, s, expires)
[ "def", "save", "(", "self", ",", "expires", "=", "None", ")", ":", "if", "expires", "is", "None", ":", "expires", "=", "self", ".", "expires", "s", "=", "self", ".", "serialize", "(", ")", "key", "=", "self", ".", "_key", "(", "self", ".", "_all_...
Save a copy of the object into the cache.
[ "Save", "a", "copy", "of", "the", "object", "into", "the", "cache", "." ]
train
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/objects.py#L128-L135
ironfroggy/django-better-cache
bettercache/objects.py
CacheModel.get
def get(cls, **kwargs): """Get a copy of the type from the cache and reconstruct it.""" data = cls._get(**kwargs) if data is None: new = cls() new.from_miss(**kwargs) return new return cls.deserialize(data)
python
def get(cls, **kwargs): """Get a copy of the type from the cache and reconstruct it.""" data = cls._get(**kwargs) if data is None: new = cls() new.from_miss(**kwargs) return new return cls.deserialize(data)
[ "def", "get", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "data", "=", "cls", ".", "_get", "(", "*", "*", "kwargs", ")", "if", "data", "is", "None", ":", "new", "=", "cls", "(", ")", "new", ".", "from_miss", "(", "*", "*", "kwargs", ")", ...
Get a copy of the type from the cache and reconstruct it.
[ "Get", "a", "copy", "of", "the", "type", "from", "the", "cache", "and", "reconstruct", "it", "." ]
train
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/objects.py#L144-L152
ironfroggy/django-better-cache
bettercache/objects.py
CacheModel.get_or_create
def get_or_create(cls, **kwargs): """Get a copy of the type from the cache, or create a new one.""" data = cls._get(**kwargs) if data is None: return cls(**kwargs), True return cls.deserialize(data), False
python
def get_or_create(cls, **kwargs): """Get a copy of the type from the cache, or create a new one.""" data = cls._get(**kwargs) if data is None: return cls(**kwargs), True return cls.deserialize(data), False
[ "def", "get_or_create", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "data", "=", "cls", ".", "_get", "(", "*", "*", "kwargs", ")", "if", "data", "is", "None", ":", "return", "cls", "(", "*", "*", "kwargs", ")", ",", "True", "return", "cls", ...
Get a copy of the type from the cache, or create a new one.
[ "Get", "a", "copy", "of", "the", "type", "from", "the", "cache", "or", "create", "a", "new", "one", "." ]
train
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/objects.py#L155-L161
ironfroggy/django-better-cache
bettercache/objects.py
CacheModel.from_miss
def from_miss(self, **kwargs): """Called to initialize an instance when it is not found in the cache. For example, if your CacheModel should pull data from the database to populate the cache, ... def from_miss(self, username): user = User.objects.get(us...
python
def from_miss(self, **kwargs): """Called to initialize an instance when it is not found in the cache. For example, if your CacheModel should pull data from the database to populate the cache, ... def from_miss(self, username): user = User.objects.get(us...
[ "def", "from_miss", "(", "self", ",", "*", "*", "kwargs", ")", ":", "raise", "type", "(", "self", ")", ".", "Missing", "(", "type", "(", "self", ")", "(", "*", "*", "kwargs", ")", ".", "key", "(", ")", ")" ]
Called to initialize an instance when it is not found in the cache. For example, if your CacheModel should pull data from the database to populate the cache, ... def from_miss(self, username): user = User.objects.get(username=username) self.emai...
[ "Called", "to", "initialize", "an", "instance", "when", "it", "is", "not", "found", "in", "the", "cache", "." ]
train
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/objects.py#L163-L177
ironfroggy/django-better-cache
bettercache/objects.py
CacheModel.delete
def delete(self): """Deleting any existing copy of this object from the cache.""" key = self._key(self._all_keys()) _cache.delete(key)
python
def delete(self): """Deleting any existing copy of this object from the cache.""" key = self._key(self._all_keys()) _cache.delete(key)
[ "def", "delete", "(", "self", ")", ":", "key", "=", "self", ".", "_key", "(", "self", ".", "_all_keys", "(", ")", ")", "_cache", ".", "delete", "(", "key", ")" ]
Deleting any existing copy of this object from the cache.
[ "Deleting", "any", "existing", "copy", "of", "this", "object", "from", "the", "cache", "." ]
train
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/objects.py#L179-L183
political-memory/django-representatives-votes
representatives_votes/models.py
Dossier.chambers
def chambers(self): """ Return distinct chambers. You probably want to prefetch documents__chamber before calling that. """ # Use sorted() because using order_by will hit the database no matter # what was prefetched return set(sorted([d.chamber for d in self.docu...
python
def chambers(self): """ Return distinct chambers. You probably want to prefetch documents__chamber before calling that. """ # Use sorted() because using order_by will hit the database no matter # what was prefetched return set(sorted([d.chamber for d in self.docu...
[ "def", "chambers", "(", "self", ")", ":", "# Use sorted() because using order_by will hit the database no matter", "# what was prefetched", "return", "set", "(", "sorted", "(", "[", "d", ".", "chamber", "for", "d", "in", "self", ".", "documents", ".", "all", "(", ...
Return distinct chambers. You probably want to prefetch documents__chamber before calling that.
[ "Return", "distinct", "chambers", ".", "You", "probably", "want", "to", "prefetch", "documents__chamber", "before", "calling", "that", "." ]
train
https://github.com/political-memory/django-representatives-votes/blob/97f9f29deefec05f18e51f6c38270b791b921bac/representatives_votes/models.py#L18-L26
KungAlex/pbkdf2helper
pbkdf2helper/helper.py
encode
def encode(password, algorithm, salt, iterations): """ Encode a Password :param password: Password :param algorithm :param salt: Salt :param iterations: iterations :return: PBKDF2 hashed Password """ hash = hashlib.pbkdf2_hmac(digest().name, password.encode(), salt.encode(), iteratio...
python
def encode(password, algorithm, salt, iterations): """ Encode a Password :param password: Password :param algorithm :param salt: Salt :param iterations: iterations :return: PBKDF2 hashed Password """ hash = hashlib.pbkdf2_hmac(digest().name, password.encode(), salt.encode(), iteratio...
[ "def", "encode", "(", "password", ",", "algorithm", ",", "salt", ",", "iterations", ")", ":", "hash", "=", "hashlib", ".", "pbkdf2_hmac", "(", "digest", "(", ")", ".", "name", ",", "password", ".", "encode", "(", ")", ",", "salt", ".", "encode", "(",...
Encode a Password :param password: Password :param algorithm :param salt: Salt :param iterations: iterations :return: PBKDF2 hashed Password
[ "Encode", "a", "Password", ":", "param", "password", ":", "Password", ":", "param", "algorithm", ":", "param", "salt", ":", "Salt", ":", "param", "iterations", ":", "iterations", ":", "return", ":", "PBKDF2", "hashed", "Password" ]
train
https://github.com/KungAlex/pbkdf2helper/blob/4719878d6f8cada486415b111ed72164b4ac6f57/pbkdf2helper/helper.py#L39-L50
KungAlex/pbkdf2helper
pbkdf2helper/helper.py
verify
def verify(password, encoded): """ Verify a Password :param password: :param encoded: :return: True or False """ algorithm, iterations, salt, h = split(encoded) to_verify = encode(password, algorithm, salt, int(iterations)) return hmac.compare_digest(to_verify.encode(), encoded.enco...
python
def verify(password, encoded): """ Verify a Password :param password: :param encoded: :return: True or False """ algorithm, iterations, salt, h = split(encoded) to_verify = encode(password, algorithm, salt, int(iterations)) return hmac.compare_digest(to_verify.encode(), encoded.enco...
[ "def", "verify", "(", "password", ",", "encoded", ")", ":", "algorithm", ",", "iterations", ",", "salt", ",", "h", "=", "split", "(", "encoded", ")", "to_verify", "=", "encode", "(", "password", ",", "algorithm", ",", "salt", ",", "int", "(", "iteratio...
Verify a Password :param password: :param encoded: :return: True or False
[ "Verify", "a", "Password", ":", "param", "password", ":", ":", "param", "encoded", ":", ":", "return", ":", "True", "or", "False" ]
train
https://github.com/KungAlex/pbkdf2helper/blob/4719878d6f8cada486415b111ed72164b4ac6f57/pbkdf2helper/helper.py#L53-L63
KungAlex/pbkdf2helper
pbkdf2helper/helper.py
split
def split(encoded): """ Split a PBKDF2 hashed Password into algorithm, iterations, salt and hash :param encoded: PBKDF2 hashed Password :return: algorithm, iterations, salt, hash """ algorithm, iterations, salt, h = encoded.split('$', 3) return algorithm, iterations, salt, h
python
def split(encoded): """ Split a PBKDF2 hashed Password into algorithm, iterations, salt and hash :param encoded: PBKDF2 hashed Password :return: algorithm, iterations, salt, hash """ algorithm, iterations, salt, h = encoded.split('$', 3) return algorithm, iterations, salt, h
[ "def", "split", "(", "encoded", ")", ":", "algorithm", ",", "iterations", ",", "salt", ",", "h", "=", "encoded", ".", "split", "(", "'$'", ",", "3", ")", "return", "algorithm", ",", "iterations", ",", "salt", ",", "h" ]
Split a PBKDF2 hashed Password into algorithm, iterations, salt and hash :param encoded: PBKDF2 hashed Password :return: algorithm, iterations, salt, hash
[ "Split", "a", "PBKDF2", "hashed", "Password", "into", "algorithm", "iterations", "salt", "and", "hash", ":", "param", "encoded", ":", "PBKDF2", "hashed", "Password", ":", "return", ":", "algorithm", "iterations", "salt", "hash" ]
train
https://github.com/KungAlex/pbkdf2helper/blob/4719878d6f8cada486415b111ed72164b4ac6f57/pbkdf2helper/helper.py#L66-L73
pydron/twistit
twistit/_yieldefer.py
yieldefer
def yieldefer(function): """ Replacement for :func:`defer.inlineCallbacks` that supports cancellation. """ defer.inlineCallbacks return lambda *args, **kwargs: _yielddefer(function, *args, **kwargs)
python
def yieldefer(function): """ Replacement for :func:`defer.inlineCallbacks` that supports cancellation. """ defer.inlineCallbacks return lambda *args, **kwargs: _yielddefer(function, *args, **kwargs)
[ "def", "yieldefer", "(", "function", ")", ":", "defer", ".", "inlineCallbacks", "return", "lambda", "*", "args", ",", "*", "*", "kwargs", ":", "_yielddefer", "(", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Replacement for :func:`defer.inlineCallbacks` that supports cancellation.
[ "Replacement", "for", ":", "func", ":", "defer", ".", "inlineCallbacks", "that", "supports", "cancellation", "." ]
train
https://github.com/pydron/twistit/blob/23ac43b830083fd32c400fcdfa5300e302769c74/twistit/_yieldefer.py#L24-L29
pydron/twistit
twistit/_yieldefer.py
_yielddefer
def _yielddefer(function, *args, **kwargs): """ Called if a function decorated with :func:`yieldefer` is invoked. """ try: retval = function(*args, **kwargs) except: return defer.fail() if isinstance(retval, defer.Deferred): return retval if not (hasattr(ret...
python
def _yielddefer(function, *args, **kwargs): """ Called if a function decorated with :func:`yieldefer` is invoked. """ try: retval = function(*args, **kwargs) except: return defer.fail() if isinstance(retval, defer.Deferred): return retval if not (hasattr(ret...
[ "def", "_yielddefer", "(", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "retval", "=", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", ":", "return", "defer", ".", "fail", "(", ")", "if", "isi...
Called if a function decorated with :func:`yieldefer` is invoked.
[ "Called", "if", "a", "function", "decorated", "with", ":", "func", ":", "yieldefer", "is", "invoked", "." ]
train
https://github.com/pydron/twistit/blob/23ac43b830083fd32c400fcdfa5300e302769c74/twistit/_yieldefer.py#L31-L94
diffeo/yakonfig
yakonfig/merge.py
overlay_config
def overlay_config(base, overlay): '''Overlay one configuration over another. This overlays `overlay` on top of `base` as follows: * If either isn't a dictionary, returns `overlay`. * Any key in `base` not present in `overlay` is present in the result with its original value. * Any key in `o...
python
def overlay_config(base, overlay): '''Overlay one configuration over another. This overlays `overlay` on top of `base` as follows: * If either isn't a dictionary, returns `overlay`. * Any key in `base` not present in `overlay` is present in the result with its original value. * Any key in `o...
[ "def", "overlay_config", "(", "base", ",", "overlay", ")", ":", "if", "not", "isinstance", "(", "base", ",", "collections", ".", "Mapping", ")", ":", "return", "overlay", "if", "not", "isinstance", "(", "overlay", ",", "collections", ".", "Mapping", ")", ...
Overlay one configuration over another. This overlays `overlay` on top of `base` as follows: * If either isn't a dictionary, returns `overlay`. * Any key in `base` not present in `overlay` is present in the result with its original value. * Any key in `overlay` with value :const:`None` is not pr...
[ "Overlay", "one", "configuration", "over", "another", "." ]
train
https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/merge.py#L20-L64
diffeo/yakonfig
yakonfig/merge.py
diff_config
def diff_config(base, target): '''Find the differences between two configurations. This finds a delta configuration from `base` to `target`, such that calling :func:`overlay_config` with `base` and the result of this function yields `target`. This works as follows: * If both are identical (of any...
python
def diff_config(base, target): '''Find the differences between two configurations. This finds a delta configuration from `base` to `target`, such that calling :func:`overlay_config` with `base` and the result of this function yields `target`. This works as follows: * If both are identical (of any...
[ "def", "diff_config", "(", "base", ",", "target", ")", ":", "if", "not", "isinstance", "(", "base", ",", "collections", ".", "Mapping", ")", ":", "if", "base", "==", "target", ":", "return", "{", "}", "return", "target", "if", "not", "isinstance", "(",...
Find the differences between two configurations. This finds a delta configuration from `base` to `target`, such that calling :func:`overlay_config` with `base` and the result of this function yields `target`. This works as follows: * If both are identical (of any type), returns an empty dictionary. ...
[ "Find", "the", "differences", "between", "two", "configurations", "." ]
train
https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/merge.py#L67-L110
pyros-dev/pyros-common
pyros_interfaces_mock/mockmessage.py
populate_instance
def populate_instance(msg, inst): """ :param msg: contains the values to use to populate inst. :param inst: message class instance to populate. :return: an instance of the provided message class, with its fields populated according to the values in msg """ return _to_inst(msg, type(inst).__name_...
python
def populate_instance(msg, inst): """ :param msg: contains the values to use to populate inst. :param inst: message class instance to populate. :return: an instance of the provided message class, with its fields populated according to the values in msg """ return _to_inst(msg, type(inst).__name_...
[ "def", "populate_instance", "(", "msg", ",", "inst", ")", ":", "return", "_to_inst", "(", "msg", ",", "type", "(", "inst", ")", ".", "__name__", ",", "type", "(", "inst", ")", ".", "__name__", ",", "inst", ")" ]
:param msg: contains the values to use to populate inst. :param inst: message class instance to populate. :return: an instance of the provided message class, with its fields populated according to the values in msg
[ ":", "param", "msg", ":", "contains", "the", "values", "to", "use", "to", "populate", "inst", ".", ":", "param", "inst", ":", "message", "class", "instance", "to", "populate", ".", ":", "return", ":", "an", "instance", "of", "the", "provided", "message",...
train
https://github.com/pyros-dev/pyros-common/blob/0709538b8777ec055ea31f59cdca5bebaaabb04e/pyros_interfaces_mock/mockmessage.py#L75-L81
krukas/Trionyx
trionyx/trionyx/views/accounts.py
UpdateUserAccountView.get
def get(self, request, *args, **kwargs): """Add user id to kwargs""" kwargs['pk'] = request.user.id self.kwargs['pk'] = request.user.id return super().get(request, *args, **kwargs)
python
def get(self, request, *args, **kwargs): """Add user id to kwargs""" kwargs['pk'] = request.user.id self.kwargs['pk'] = request.user.id return super().get(request, *args, **kwargs)
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'pk'", "]", "=", "request", ".", "user", ".", "id", "self", ".", "kwargs", "[", "'pk'", "]", "=", "request", ".", "user", ".", "id",...
Add user id to kwargs
[ "Add", "user", "id", "to", "kwargs" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/accounts.py#L38-L42
krukas/Trionyx
trionyx/trionyx/views/accounts.py
UpdateUserAccountView.post
def post(self, request, *args, **kwargs): """Add user id to kwargs""" kwargs['pk'] = request.user.id self.kwargs['pk'] = request.user.id return super().post(request, *args, **kwargs)
python
def post(self, request, *args, **kwargs): """Add user id to kwargs""" kwargs['pk'] = request.user.id self.kwargs['pk'] = request.user.id return super().post(request, *args, **kwargs)
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'pk'", "]", "=", "request", ".", "user", ".", "id", "self", ".", "kwargs", "[", "'pk'", "]", "=", "request", ".", "user", ".", "id"...
Add user id to kwargs
[ "Add", "user", "id", "to", "kwargs" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/accounts.py#L44-L48
harlowja/constructs
constructs/tree.py
pformat
def pformat(tree): """Recursively formats a tree into a nice string representation. Example Input: yahoo = tt.Tree(tt.Node("CEO")) yahoo.root.add(tt.Node("Infra")) yahoo.root[0].add(tt.Node("Boss")) yahoo.root[0][0].add(tt.Node("Me")) yahoo.root.add(tt.Node("Mobile")) yahoo.root.a...
python
def pformat(tree): """Recursively formats a tree into a nice string representation. Example Input: yahoo = tt.Tree(tt.Node("CEO")) yahoo.root.add(tt.Node("Infra")) yahoo.root[0].add(tt.Node("Boss")) yahoo.root[0][0].add(tt.Node("Me")) yahoo.root.add(tt.Node("Mobile")) yahoo.root.a...
[ "def", "pformat", "(", "tree", ")", ":", "if", "tree", ".", "empty", "(", ")", ":", "return", "''", "buf", "=", "six", ".", "StringIO", "(", ")", "for", "line", "in", "_pformat", "(", "tree", ".", "root", ",", "0", ")", ":", "buf", ".", "write"...
Recursively formats a tree into a nice string representation. Example Input: yahoo = tt.Tree(tt.Node("CEO")) yahoo.root.add(tt.Node("Infra")) yahoo.root[0].add(tt.Node("Boss")) yahoo.root[0][0].add(tt.Node("Me")) yahoo.root.add(tt.Node("Mobile")) yahoo.root.add(tt.Node("Mail")) E...
[ "Recursively", "formats", "a", "tree", "into", "a", "nice", "string", "representation", "." ]
train
https://github.com/harlowja/constructs/blob/53f20a8422bbd56294d5c0161081cb5875511fab/constructs/tree.py#L172-L196
harlowja/constructs
constructs/tree.py
Node.path_iter
def path_iter(self, include_self=True): """Yields back the path from this node to the root node.""" if include_self: node = self else: node = self.parent while node is not None: yield node node = node.parent
python
def path_iter(self, include_self=True): """Yields back the path from this node to the root node.""" if include_self: node = self else: node = self.parent while node is not None: yield node node = node.parent
[ "def", "path_iter", "(", "self", ",", "include_self", "=", "True", ")", ":", "if", "include_self", ":", "node", "=", "self", "else", ":", "node", "=", "self", ".", "parent", "while", "node", "is", "not", "None", ":", "yield", "node", "node", "=", "no...
Yields back the path from this node to the root node.
[ "Yields", "back", "the", "path", "from", "this", "node", "to", "the", "root", "node", "." ]
train
https://github.com/harlowja/constructs/blob/53f20a8422bbd56294d5c0161081cb5875511fab/constructs/tree.py#L101-L109
harlowja/constructs
constructs/tree.py
Node.child_count
def child_count(self, only_direct=True): """Returns how many children this node has, either only the direct children of this node or inclusive of all children nodes of this node. """ if not only_direct: count = 0 for _node in self.dfs_iter(): count...
python
def child_count(self, only_direct=True): """Returns how many children this node has, either only the direct children of this node or inclusive of all children nodes of this node. """ if not only_direct: count = 0 for _node in self.dfs_iter(): count...
[ "def", "child_count", "(", "self", ",", "only_direct", "=", "True", ")", ":", "if", "not", "only_direct", ":", "count", "=", "0", "for", "_node", "in", "self", ".", "dfs_iter", "(", ")", ":", "count", "+=", "1", "return", "count", "return", "len", "(...
Returns how many children this node has, either only the direct children of this node or inclusive of all children nodes of this node.
[ "Returns", "how", "many", "children", "this", "node", "has", "either", "only", "the", "direct", "children", "of", "this", "node", "or", "inclusive", "of", "all", "children", "nodes", "of", "this", "node", "." ]
train
https://github.com/harlowja/constructs/blob/53f20a8422bbd56294d5c0161081cb5875511fab/constructs/tree.py#L119-L128
harlowja/constructs
constructs/tree.py
Node.index
def index(self, item): """Finds the child index of a given item, searchs in added order.""" index_at = None for (i, child) in enumerate(self._children): if child.item == item: index_at = i break if index_at is None: raise ValueError...
python
def index(self, item): """Finds the child index of a given item, searchs in added order.""" index_at = None for (i, child) in enumerate(self._children): if child.item == item: index_at = i break if index_at is None: raise ValueError...
[ "def", "index", "(", "self", ",", "item", ")", ":", "index_at", "=", "None", "for", "(", "i", ",", "child", ")", "in", "enumerate", "(", "self", ".", "_children", ")", ":", "if", "child", ".", "item", "==", "item", ":", "index_at", "=", "i", "bre...
Finds the child index of a given item, searchs in added order.
[ "Finds", "the", "child", "index", "of", "a", "given", "item", "searchs", "in", "added", "order", "." ]
train
https://github.com/harlowja/constructs/blob/53f20a8422bbd56294d5c0161081cb5875511fab/constructs/tree.py#L135-L144
mgk/thingamon
thingamon/thing.py
Thing.publish_state
def publish_state(self, state): """Publish thing state to AWS IoT. Args: state (dict): object state. Must be JSON serializable (i.e., not have circular references). """ message = json.dumps({'state': {'reported': state}}) self.client.publish(self.topi...
python
def publish_state(self, state): """Publish thing state to AWS IoT. Args: state (dict): object state. Must be JSON serializable (i.e., not have circular references). """ message = json.dumps({'state': {'reported': state}}) self.client.publish(self.topi...
[ "def", "publish_state", "(", "self", ",", "state", ")", ":", "message", "=", "json", ".", "dumps", "(", "{", "'state'", ":", "{", "'reported'", ":", "state", "}", "}", ")", "self", ".", "client", ".", "publish", "(", "self", ".", "topic", ",", "mes...
Publish thing state to AWS IoT. Args: state (dict): object state. Must be JSON serializable (i.e., not have circular references).
[ "Publish", "thing", "state", "to", "AWS", "IoT", "." ]
train
https://github.com/mgk/thingamon/blob/3f7d68dc2131c347473af15cd5f7d4b669407c6b/thingamon/thing.py#L28-L37
CitrineInformatics/dftparse
dftparse/vasp/eigenval_parser.py
_is_kpoint
def _is_kpoint(line): """Is this line the start of a new k-point block""" # Try to parse the k-point; false otherwise toks = line.split() # k-point header lines have 4 tokens if len(toks) != 4: return False try: # K-points are centered at the origin xs = [float(x) for x ...
python
def _is_kpoint(line): """Is this line the start of a new k-point block""" # Try to parse the k-point; false otherwise toks = line.split() # k-point header lines have 4 tokens if len(toks) != 4: return False try: # K-points are centered at the origin xs = [float(x) for x ...
[ "def", "_is_kpoint", "(", "line", ")", ":", "# Try to parse the k-point; false otherwise", "toks", "=", "line", ".", "split", "(", ")", "# k-point header lines have 4 tokens", "if", "len", "(", "toks", ")", "!=", "4", ":", "return", "False", "try", ":", "# K-poi...
Is this line the start of a new k-point block
[ "Is", "this", "line", "the", "start", "of", "a", "new", "k", "-", "point", "block" ]
train
https://github.com/CitrineInformatics/dftparse/blob/53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d/dftparse/vasp/eigenval_parser.py#L4-L19
CitrineInformatics/dftparse
dftparse/vasp/eigenval_parser.py
_parse_kpoint
def _parse_kpoint(line, lines): """Parse the k-point and then continue to iterate over the band energies and occupations""" toks = line.split() kpoint = [float(x) for x in toks[:3]] weight = float(toks[-1]) newline = next(lines) bands_up = [] occ_up = [] bands_down = [] occ_down = [...
python
def _parse_kpoint(line, lines): """Parse the k-point and then continue to iterate over the band energies and occupations""" toks = line.split() kpoint = [float(x) for x in toks[:3]] weight = float(toks[-1]) newline = next(lines) bands_up = [] occ_up = [] bands_down = [] occ_down = [...
[ "def", "_parse_kpoint", "(", "line", ",", "lines", ")", ":", "toks", "=", "line", ".", "split", "(", ")", "kpoint", "=", "[", "float", "(", "x", ")", "for", "x", "in", "toks", "[", ":", "3", "]", "]", "weight", "=", "float", "(", "toks", "[", ...
Parse the k-point and then continue to iterate over the band energies and occupations
[ "Parse", "the", "k", "-", "point", "and", "then", "continue", "to", "iterate", "over", "the", "band", "energies", "and", "occupations" ]
train
https://github.com/CitrineInformatics/dftparse/blob/53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d/dftparse/vasp/eigenval_parser.py#L22-L71
wtsi-hgi/python-baton-wrapper
baton/_baton/api.py
connect_to_irods_with_baton
def connect_to_irods_with_baton(baton_binaries_directory: str, skip_baton_binaries_validation: bool=False) \ -> Connection: """ Convenience method to create a pseudo connection to iRODS. :param baton_binaries_directory: see `Connection.__init__` :param skip_baton_binaries_validation: see `Connec...
python
def connect_to_irods_with_baton(baton_binaries_directory: str, skip_baton_binaries_validation: bool=False) \ -> Connection: """ Convenience method to create a pseudo connection to iRODS. :param baton_binaries_directory: see `Connection.__init__` :param skip_baton_binaries_validation: see `Connec...
[ "def", "connect_to_irods_with_baton", "(", "baton_binaries_directory", ":", "str", ",", "skip_baton_binaries_validation", ":", "bool", "=", "False", ")", "->", "Connection", ":", "return", "Connection", "(", "baton_binaries_directory", ",", "skip_baton_binaries_validation",...
Convenience method to create a pseudo connection to iRODS. :param baton_binaries_directory: see `Connection.__init__` :param skip_baton_binaries_validation: see `Connection.__init__` :return: pseudo connection to iRODS
[ "Convenience", "method", "to", "create", "a", "pseudo", "connection", "to", "iRODS", ".", ":", "param", "baton_binaries_directory", ":", "see", "Connection", ".", "__init__", ":", "param", "skip_baton_binaries_validation", ":", "see", "Connection", ".", "__init__", ...
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/_baton/api.py#L21-L29
Celeo/Pycord
pycord/__init__.py
WebSocketEvent.parse
def parse(cls, op): """Gets the enum for the op code Args: op: value of the op code (will be casted to int) Returns: The enum that matches the op code """ for event in cls: if event.value == int(op): return event retur...
python
def parse(cls, op): """Gets the enum for the op code Args: op: value of the op code (will be casted to int) Returns: The enum that matches the op code """ for event in cls: if event.value == int(op): return event retur...
[ "def", "parse", "(", "cls", ",", "op", ")", ":", "for", "event", "in", "cls", ":", "if", "event", ".", "value", "==", "int", "(", "op", ")", ":", "return", "event", "return", "None" ]
Gets the enum for the op code Args: op: value of the op code (will be casted to int) Returns: The enum that matches the op code
[ "Gets", "the", "enum", "for", "the", "op", "code" ]
train
https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L45-L57
Celeo/Pycord
pycord/__init__.py
WebSocketKeepAlive.run
def run(self): """Runs the thread This method handles sending the heartbeat to the Discord websocket server, so the connection can remain open and the bot remain online for those commands that require it to be. Args: None """ while self.should_run: ...
python
def run(self): """Runs the thread This method handles sending the heartbeat to the Discord websocket server, so the connection can remain open and the bot remain online for those commands that require it to be. Args: None """ while self.should_run: ...
[ "def", "run", "(", "self", ")", ":", "while", "self", ".", "should_run", ":", "try", ":", "self", ".", "logger", ".", "debug", "(", "'Sending heartbeat, seq '", "+", "last_sequence", ")", "self", ".", "ws", ".", "send", "(", "json", ".", "dumps", "(", ...
Runs the thread This method handles sending the heartbeat to the Discord websocket server, so the connection can remain open and the bot remain online for those commands that require it to be. Args: None
[ "Runs", "the", "thread" ]
train
https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L87-L109
Celeo/Pycord
pycord/__init__.py
Pycord._setup_logger
def _setup_logger(self, logging_level: int, log_to_console: bool): """Sets up the internal logger Args: logging_level: what logging level to use log_to_console: whether or not to log to the console """ self.logger = logging.getLogger('discord') self.logge...
python
def _setup_logger(self, logging_level: int, log_to_console: bool): """Sets up the internal logger Args: logging_level: what logging level to use log_to_console: whether or not to log to the console """ self.logger = logging.getLogger('discord') self.logge...
[ "def", "_setup_logger", "(", "self", ",", "logging_level", ":", "int", ",", "log_to_console", ":", "bool", ")", ":", "self", ".", "logger", "=", "logging", ".", "getLogger", "(", "'discord'", ")", "self", ".", "logger", ".", "handlers", "=", "[", "]", ...
Sets up the internal logger Args: logging_level: what logging level to use log_to_console: whether or not to log to the console
[ "Sets", "up", "the", "internal", "logger" ]
train
https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L181-L200
Celeo/Pycord
pycord/__init__.py
Pycord._query
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \ -> Union[List[Dict[str, Any]], Dict[str, Any], None]: """Make an HTTP request Args: path: the URI path (not including the base url, start with the first uri segment,...
python
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \ -> Union[List[Dict[str, Any]], Dict[str, Any], None]: """Make an HTTP request Args: path: the URI path (not including the base url, start with the first uri segment,...
[ "def", "_query", "(", "self", ",", "path", ":", "str", ",", "method", ":", "str", ",", "data", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", "expected_status", ":", "int", "=", "200", ")", "->", "Union", "[", "List", "[", "Dict", ...
Make an HTTP request Args: path: the URI path (not including the base url, start with the first uri segment, like 'users/...') method: the HTTP method to use (GET, POST, PATCH, ...) data: the data to send as JSON data expected_status: expected HTT...
[ "Make", "an", "HTTP", "request" ]
train
https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L221-L252
Celeo/Pycord
pycord/__init__.py
Pycord._ws_on_message
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]): """Callback for receiving messages from the websocket connection This method receives ALL events from the websocket connection, some of which are used for the initial authentication flow, some of which are used for ma...
python
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]): """Callback for receiving messages from the websocket connection This method receives ALL events from the websocket connection, some of which are used for the initial authentication flow, some of which are used for ma...
[ "def", "_ws_on_message", "(", "self", ",", "ws", ":", "websocket", ".", "WebSocketApp", ",", "raw", ":", "Union", "[", "str", ",", "bytes", "]", ")", ":", "if", "isinstance", "(", "raw", ",", "bytes", ")", ":", "decoded", "=", "zlib", ".", "decompres...
Callback for receiving messages from the websocket connection This method receives ALL events from the websocket connection, some of which are used for the initial authentication flow, some of which are used for maintaining the connection, some of which are for notifying this client of user sta...
[ "Callback", "for", "receiving", "messages", "from", "the", "websocket", "connection" ]
train
https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L269-L317
Celeo/Pycord
pycord/__init__.py
Pycord._ws_on_error
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception): """Callback for receiving errors from the websocket connection Args: ws: websocket connection error: exception raised """ self.logger.error(f'Got error from websocket connection: {str(error)}')
python
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception): """Callback for receiving errors from the websocket connection Args: ws: websocket connection error: exception raised """ self.logger.error(f'Got error from websocket connection: {str(error)}')
[ "def", "_ws_on_error", "(", "self", ",", "ws", ":", "websocket", ".", "WebSocketApp", ",", "error", ":", "Exception", ")", ":", "self", ".", "logger", ".", "error", "(", "f'Got error from websocket connection: {str(error)}'", ")" ]
Callback for receiving errors from the websocket connection Args: ws: websocket connection error: exception raised
[ "Callback", "for", "receiving", "errors", "from", "the", "websocket", "connection" ]
train
https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L319-L326
Celeo/Pycord
pycord/__init__.py
Pycord._ws_on_close
def _ws_on_close(self, ws: websocket.WebSocketApp): """Callback for closing the websocket connection Args: ws: websocket connection (now closed) """ self.connected = False self.logger.error('Websocket closed') self._reconnect_websocket()
python
def _ws_on_close(self, ws: websocket.WebSocketApp): """Callback for closing the websocket connection Args: ws: websocket connection (now closed) """ self.connected = False self.logger.error('Websocket closed') self._reconnect_websocket()
[ "def", "_ws_on_close", "(", "self", ",", "ws", ":", "websocket", ".", "WebSocketApp", ")", ":", "self", ".", "connected", "=", "False", "self", ".", "logger", ".", "error", "(", "'Websocket closed'", ")", "self", ".", "_reconnect_websocket", "(", ")" ]
Callback for closing the websocket connection Args: ws: websocket connection (now closed)
[ "Callback", "for", "closing", "the", "websocket", "connection" ]
train
https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L328-L336
Celeo/Pycord
pycord/__init__.py
Pycord._ws_on_open
def _ws_on_open(self, ws: websocket.WebSocketApp): """Callback for sending the initial authentication data This "payload" contains the required data to authenticate this websocket client as a suitable bot connection to the Discord websocket. Args: ws: websocket connection ...
python
def _ws_on_open(self, ws: websocket.WebSocketApp): """Callback for sending the initial authentication data This "payload" contains the required data to authenticate this websocket client as a suitable bot connection to the Discord websocket. Args: ws: websocket connection ...
[ "def", "_ws_on_open", "(", "self", ",", "ws", ":", "websocket", ".", "WebSocketApp", ")", ":", "payload", "=", "{", "'op'", ":", "WebSocketEvent", ".", "IDENTIFY", ".", "value", ",", "'d'", ":", "{", "'token'", ":", "self", ".", "token", ",", "'propert...
Callback for sending the initial authentication data This "payload" contains the required data to authenticate this websocket client as a suitable bot connection to the Discord websocket. Args: ws: websocket connection
[ "Callback", "for", "sending", "the", "initial", "authentication", "data" ]
train
https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L338-L364