partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
run
Start a pyros node. :param interface: the interface implementation (ROS, Mock, ZMP, etc.) :param config: the config file path, absolute, or relative to working directory :param logfile: the logfile path, absolute, or relative to working directory :param ros_args: the ros arguments (useful to absorb addi...
pyros/__main__.py
def run(interface, config, logfile, ros_args): """ Start a pyros node. :param interface: the interface implementation (ROS, Mock, ZMP, etc.) :param config: the config file path, absolute, or relative to working directory :param logfile: the logfile path, absolute, or relative to working directory ...
def run(interface, config, logfile, ros_args): """ Start a pyros node. :param interface: the interface implementation (ROS, Mock, ZMP, etc.) :param config: the config file path, absolute, or relative to working directory :param logfile: the logfile path, absolute, or relative to working directory ...
[ "Start", "a", "pyros", "node", ".", ":", "param", "interface", ":", "the", "interface", "implementation", "(", "ROS", "Mock", "ZMP", "etc", ".", ")", ":", "param", "config", ":", "the", "config", "file", "path", "absolute", "or", "relative", "to", "worki...
pyros-dev/pyros
python
https://github.com/pyros-dev/pyros/blob/59f6c8848a66481a4039cbf28b7673428181842e/pyros/__main__.py#L207-L225
[ "def", "run", "(", "interface", ",", "config", ",", "logfile", ",", "ros_args", ")", ":", "logging", ".", "info", "(", "'pyros started with : interface {interface} config {config} logfile {logfile} ros_args {ros_args}'", ".", "format", "(", "interface", "=", "interface", ...
59f6c8848a66481a4039cbf28b7673428181842e
train
nickmask
store nick, user, host in kwargs if prefix is correct format
bottom/unpack.py
def nickmask(prefix: str, kwargs: Dict[str, Any]) -> None: """ store nick, user, host in kwargs if prefix is correct format """ if "!" in prefix and "@" in prefix: # From a user kwargs["nick"], remainder = prefix.split("!", 1) kwargs["user"], kwargs["host"] = remainder.split("@", 1) ...
def nickmask(prefix: str, kwargs: Dict[str, Any]) -> None: """ store nick, user, host in kwargs if prefix is correct format """ if "!" in prefix and "@" in prefix: # From a user kwargs["nick"], remainder = prefix.split("!", 1) kwargs["user"], kwargs["host"] = remainder.split("@", 1) ...
[ "store", "nick", "user", "host", "in", "kwargs", "if", "prefix", "is", "correct", "format" ]
numberoverzero/bottom
python
https://github.com/numberoverzero/bottom/blob/9ba5f8e22d4990071e3606256e9bc1f64ec989fe/bottom/unpack.py#L175-L183
[ "def", "nickmask", "(", "prefix", ":", "str", ",", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "if", "\"!\"", "in", "prefix", "and", "\"@\"", "in", "prefix", ":", "# From a user", "kwargs", "[", "\"nick\"", "]", ",", ...
9ba5f8e22d4990071e3606256e9bc1f64ec989fe
train
split_line
Parse message according to rfc 2812 for routing
bottom/unpack.py
def split_line(msg: str) -> Tuple[str, str, List[str]]: """ Parse message according to rfc 2812 for routing """ match = RE_IRCLINE.match(msg) if not match: raise ValueError("Invalid line") prefix = match.group("prefix") or "" command = match.group("command") params = (match.group("param...
def split_line(msg: str) -> Tuple[str, str, List[str]]: """ Parse message according to rfc 2812 for routing """ match = RE_IRCLINE.match(msg) if not match: raise ValueError("Invalid line") prefix = match.group("prefix") or "" command = match.group("command") params = (match.group("param...
[ "Parse", "message", "according", "to", "rfc", "2812", "for", "routing" ]
numberoverzero/bottom
python
https://github.com/numberoverzero/bottom/blob/9ba5f8e22d4990071e3606256e9bc1f64ec989fe/bottom/unpack.py#L190-L204
[ "def", "split_line", "(", "msg", ":", "str", ")", "->", "Tuple", "[", "str", ",", "str", ",", "List", "[", "str", "]", "]", ":", "match", "=", "RE_IRCLINE", ".", "match", "(", "msg", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "\"...
9ba5f8e22d4990071e3606256e9bc1f64ec989fe
train
b
Return `present` value (default to `field`) if `field` in `kwargs` and Truthy, otherwise return `missing` value
bottom/pack.py
def b(field: str, kwargs: Dict[str, Any], present: Optional[Any] = None, missing: Any = '') -> str: """ Return `present` value (default to `field`) if `field` in `kwargs` and Truthy, otherwise return `missing` value """ if kwargs.get(field): return field if present is None else str(pre...
def b(field: str, kwargs: Dict[str, Any], present: Optional[Any] = None, missing: Any = '') -> str: """ Return `present` value (default to `field`) if `field` in `kwargs` and Truthy, otherwise return `missing` value """ if kwargs.get(field): return field if present is None else str(pre...
[ "Return", "present", "value", "(", "default", "to", "field", ")", "if", "field", "in", "kwargs", "and", "Truthy", "otherwise", "return", "missing", "value" ]
numberoverzero/bottom
python
https://github.com/numberoverzero/bottom/blob/9ba5f8e22d4990071e3606256e9bc1f64ec989fe/bottom/pack.py#L7-L15
[ "def", "b", "(", "field", ":", "str", ",", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", ",", "present", ":", "Optional", "[", "Any", "]", "=", "None", ",", "missing", ":", "Any", "=", "''", ")", "->", "str", ":", "if", "kwargs", ".", "...
9ba5f8e22d4990071e3606256e9bc1f64ec989fe
train
f
Alias for more readable command construction
bottom/pack.py
def f(field: str, kwargs: Dict[str, Any], default: Optional[Any] = None) -> str: """ Alias for more readable command construction """ if default is not None: return str(kwargs.get(field, default)) return str(kwargs[field])
def f(field: str, kwargs: Dict[str, Any], default: Optional[Any] = None) -> str: """ Alias for more readable command construction """ if default is not None: return str(kwargs.get(field, default)) return str(kwargs[field])
[ "Alias", "for", "more", "readable", "command", "construction" ]
numberoverzero/bottom
python
https://github.com/numberoverzero/bottom/blob/9ba5f8e22d4990071e3606256e9bc1f64ec989fe/bottom/pack.py#L18-L23
[ "def", "f", "(", "field", ":", "str", ",", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", ",", "default", ":", "Optional", "[", "Any", "]", "=", "None", ")", "->", "str", ":", "if", "default", "is", "not", "None", ":", "return", "str", "("...
9ba5f8e22d4990071e3606256e9bc1f64ec989fe
train
pack
Util for joining multiple fields with commas
bottom/pack.py
def pack(field: str, kwargs: Dict[str, Any], default: Optional[Any] = None, sep: str=',') -> str: """ Util for joining multiple fields with commas """ if default is not None: value = kwargs.get(field, default) else: value = kwargs[field] if isinstance(value, str): return...
def pack(field: str, kwargs: Dict[str, Any], default: Optional[Any] = None, sep: str=',') -> str: """ Util for joining multiple fields with commas """ if default is not None: value = kwargs.get(field, default) else: value = kwargs[field] if isinstance(value, str): return...
[ "Util", "for", "joining", "multiple", "fields", "with", "commas" ]
numberoverzero/bottom
python
https://github.com/numberoverzero/bottom/blob/9ba5f8e22d4990071e3606256e9bc1f64ec989fe/bottom/pack.py#L26-L38
[ "def", "pack", "(", "field", ":", "str", ",", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", ",", "default", ":", "Optional", "[", "Any", "]", "=", "None", ",", "sep", ":", "str", "=", "','", ")", "->", "str", ":", "if", "default", "is", ...
9ba5f8e22d4990071e3606256e9bc1f64ec989fe
train
pack_command
Pack a command to send to an IRC server
bottom/pack.py
def pack_command(command: str, **kwargs: Any) -> str: """ Pack a command to send to an IRC server """ if not command: raise ValueError("Must provide a command") if not isinstance(command, str): raise ValueError("Command must be a string") command = command.upper() # ================...
def pack_command(command: str, **kwargs: Any) -> str: """ Pack a command to send to an IRC server """ if not command: raise ValueError("Must provide a command") if not isinstance(command, str): raise ValueError("Command must be a string") command = command.upper() # ================...
[ "Pack", "a", "command", "to", "send", "to", "an", "IRC", "server" ]
numberoverzero/bottom
python
https://github.com/numberoverzero/bottom/blob/9ba5f8e22d4990071e3606256e9bc1f64ec989fe/bottom/pack.py#L41-L547
[ "def", "pack_command", "(", "command", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "str", ":", "if", "not", "command", ":", "raise", "ValueError", "(", "\"Must provide a command\"", ")", "if", "not", "isinstance", "(", "command", ",", "st...
9ba5f8e22d4990071e3606256e9bc1f64ec989fe
train
RawClient.connect
Open a connection to the defined server.
bottom/client.py
async def connect(self) -> None: """Open a connection to the defined server.""" def protocol_factory() -> Protocol: return Protocol(client=self) _, protocol = await self.loop.create_connection( protocol_factory, host=self.host, port=self.port, ...
async def connect(self) -> None: """Open a connection to the defined server.""" def protocol_factory() -> Protocol: return Protocol(client=self) _, protocol = await self.loop.create_connection( protocol_factory, host=self.host, port=self.port, ...
[ "Open", "a", "connection", "to", "the", "defined", "server", "." ]
numberoverzero/bottom
python
https://github.com/numberoverzero/bottom/blob/9ba5f8e22d4990071e3606256e9bc1f64ec989fe/bottom/client.py#L69-L87
[ "async", "def", "connect", "(", "self", ")", "->", "None", ":", "def", "protocol_factory", "(", ")", "->", "Protocol", ":", "return", "Protocol", "(", "client", "=", "self", ")", "_", ",", "protocol", "=", "await", "self", ".", "loop", ".", "create_con...
9ba5f8e22d4990071e3606256e9bc1f64ec989fe
train
RawClient.trigger
Trigger all handlers for an event to (asynchronously) execute
bottom/client.py
def trigger(self, event: str, **kwargs: Any) -> None: """Trigger all handlers for an event to (asynchronously) execute""" event = event.upper() for func in self._event_handlers[event]: self.loop.create_task(func(**kwargs)) # This will unblock anyone that is awaiting on the ne...
def trigger(self, event: str, **kwargs: Any) -> None: """Trigger all handlers for an event to (asynchronously) execute""" event = event.upper() for func in self._event_handlers[event]: self.loop.create_task(func(**kwargs)) # This will unblock anyone that is awaiting on the ne...
[ "Trigger", "all", "handlers", "for", "an", "event", "to", "(", "asynchronously", ")", "execute" ]
numberoverzero/bottom
python
https://github.com/numberoverzero/bottom/blob/9ba5f8e22d4990071e3606256e9bc1f64ec989fe/bottom/client.py#L94-L104
[ "def", "trigger", "(", "self", ",", "event", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "event", "=", "event", ".", "upper", "(", ")", "for", "func", "in", "self", ".", "_event_handlers", "[", "event", "]", ":", "sel...
9ba5f8e22d4990071e3606256e9bc1f64ec989fe
train
RawClient.on
Decorate a function to be invoked when the given event occurs. The function may be a coroutine. Your function should accept **kwargs in case an event is triggered with unexpected kwargs. Example ------- import asyncio import bottom client = bottom.Client(...) ...
bottom/client.py
def on(self, event: str, func: Optional[Callable] = None) -> Callable: """ Decorate a function to be invoked when the given event occurs. The function may be a coroutine. Your function should accept **kwargs in case an event is triggered with unexpected kwargs. Example ...
def on(self, event: str, func: Optional[Callable] = None) -> Callable: """ Decorate a function to be invoked when the given event occurs. The function may be a coroutine. Your function should accept **kwargs in case an event is triggered with unexpected kwargs. Example ...
[ "Decorate", "a", "function", "to", "be", "invoked", "when", "the", "given", "event", "occurs", "." ]
numberoverzero/bottom
python
https://github.com/numberoverzero/bottom/blob/9ba5f8e22d4990071e3606256e9bc1f64ec989fe/bottom/client.py#L110-L142
[ "def", "on", "(", "self", ",", "event", ":", "str", ",", "func", ":", "Optional", "[", "Callable", "]", "=", "None", ")", "->", "Callable", ":", "if", "func", "is", "None", ":", "return", "functools", ".", "partial", "(", "self", ".", "on", ",", ...
9ba5f8e22d4990071e3606256e9bc1f64ec989fe
train
Client.send
Send a message to the server. .. code-block:: python client.send("nick", nick="weatherbot") client.send("privmsg", target="#python", message="Hello, World!")
bottom/client.py
def send(self, command: str, **kwargs: Any) -> None: """ Send a message to the server. .. code-block:: python client.send("nick", nick="weatherbot") client.send("privmsg", target="#python", message="Hello, World!") """ packed_command = pack_command(comm...
def send(self, command: str, **kwargs: Any) -> None: """ Send a message to the server. .. code-block:: python client.send("nick", nick="weatherbot") client.send("privmsg", target="#python", message="Hello, World!") """ packed_command = pack_command(comm...
[ "Send", "a", "message", "to", "the", "server", "." ]
numberoverzero/bottom
python
https://github.com/numberoverzero/bottom/blob/9ba5f8e22d4990071e3606256e9bc1f64ec989fe/bottom/client.py#L170-L181
[ "def", "send", "(", "self", ",", "command", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "packed_command", "=", "pack_command", "(", "command", ",", "*", "*", "kwargs", ")", ".", "strip", "(", ")", "self", ".", "send_raw...
9ba5f8e22d4990071e3606256e9bc1f64ec989fe
train
Router._handle
client callback entrance
examples/regex.py
def _handle(self, nick, target, message, **kwargs): """ client callback entrance """ for regex, (func, pattern) in self.routes.items(): match = regex.match(message) if match: self.client.loop.create_task( func(nick, target, message, match, **kw...
def _handle(self, nick, target, message, **kwargs): """ client callback entrance """ for regex, (func, pattern) in self.routes.items(): match = regex.match(message) if match: self.client.loop.create_task( func(nick, target, message, match, **kw...
[ "client", "callback", "entrance" ]
numberoverzero/bottom
python
https://github.com/numberoverzero/bottom/blob/9ba5f8e22d4990071e3606256e9bc1f64ec989fe/examples/regex.py#L12-L18
[ "def", "_handle", "(", "self", ",", "nick", ",", "target", ",", "message", ",", "*", "*", "kwargs", ")", ":", "for", "regex", ",", "(", "func", ",", "pattern", ")", "in", "self", ".", "routes", ".", "items", "(", ")", ":", "match", "=", "regex", ...
9ba5f8e22d4990071e3606256e9bc1f64ec989fe
train
main
parse commandline arguments and print result
examples/owget.py
def main(): """parse commandline arguments and print result""" fcodes = collections.OrderedDict(( ('f.i', protocol.FLG_FORMAT_FDI), ('fi', protocol.FLG_FORMAT_FI), ('f.i.c', protocol.FLG_FORMAT_FDIDC), ('f.ic', protocol.FLG_FORMAT_FDIC), ('fi.c', protocol.FLG_FORMAT_FIDC...
def main(): """parse commandline arguments and print result""" fcodes = collections.OrderedDict(( ('f.i', protocol.FLG_FORMAT_FDI), ('fi', protocol.FLG_FORMAT_FI), ('f.i.c', protocol.FLG_FORMAT_FDIDC), ('f.ic', protocol.FLG_FORMAT_FDIC), ('fi.c', protocol.FLG_FORMAT_FIDC...
[ "parse", "commandline", "arguments", "and", "print", "result" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/examples/owget.py#L38-L170
[ "def", "main", "(", ")", ":", "fcodes", "=", "collections", ".", "OrderedDict", "(", "(", "(", "'f.i'", ",", "protocol", ".", "FLG_FORMAT_FDI", ")", ",", "(", "'fi'", ",", "protocol", ".", "FLG_FORMAT_FI", ")", ",", "(", "'f.i.c'", ",", "protocol", "."...
190afea6a72705772b942d7929bc0aa6561043e0
train
main
parse commandline arguments and print result
diags/stress_t.py
def main(): """parse commandline arguments and print result""" # # setup command line parsing a la argpase # parser = argparse.ArgumentParser() # positional args parser.add_argument('uri', metavar='URI', nargs='?', default='/', help='[owserver:]//hostname:port/path'...
def main(): """parse commandline arguments and print result""" # # setup command line parsing a la argpase # parser = argparse.ArgumentParser() # positional args parser.add_argument('uri', metavar='URI', nargs='?', default='/', help='[owserver:]//hostname:port/path'...
[ "parse", "commandline", "arguments", "and", "print", "result" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/diags/stress_t.py#L64-L112
[ "def", "main", "(", ")", ":", "#", "# setup command line parsing a la argpase", "#", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "# positional args", "parser", ".", "add_argument", "(", "'uri'", ",", "metavar", "=", "'URI'", ",", "nargs", "=", ...
190afea6a72705772b942d7929bc0aa6561043e0
train
Client.build_url
Constructs the url for a cheddar API resource
sharpy/client.py
def build_url(self, path, params=None): ''' Constructs the url for a cheddar API resource ''' url = u'%s/%s/productCode/%s' % ( self.endpoint, path, self.product_code, ) if params: for key, value in params.items(): ...
def build_url(self, path, params=None): ''' Constructs the url for a cheddar API resource ''' url = u'%s/%s/productCode/%s' % ( self.endpoint, path, self.product_code, ) if params: for key, value in params.items(): ...
[ "Constructs", "the", "url", "for", "a", "cheddar", "API", "resource" ]
SeanOC/sharpy
python
https://github.com/SeanOC/sharpy/blob/935943ca86034255f0a93c1a84734814be176ed4/sharpy/client.py#L33-L46
[ "def", "build_url", "(", "self", ",", "path", ",", "params", "=", "None", ")", ":", "url", "=", "u'%s/%s/productCode/%s'", "%", "(", "self", ".", "endpoint", ",", "path", ",", "self", ".", "product_code", ",", ")", "if", "params", ":", "for", "key", ...
935943ca86034255f0a93c1a84734814be176ed4
train
Client.make_request
Makes a request to the cheddar api using the authentication and configuration settings available.
sharpy/client.py
def make_request(self, path, params=None, data=None, method=None): ''' Makes a request to the cheddar api using the authentication and configuration settings available. ''' # Setup values url = self.build_url(path, params) client_log.debug('Requesting: %s' % url)...
def make_request(self, path, params=None, data=None, method=None): ''' Makes a request to the cheddar api using the authentication and configuration settings available. ''' # Setup values url = self.build_url(path, params) client_log.debug('Requesting: %s' % url)...
[ "Makes", "a", "request", "to", "the", "cheddar", "api", "using", "the", "authentication", "and", "configuration", "settings", "available", "." ]
SeanOC/sharpy
python
https://github.com/SeanOC/sharpy/blob/935943ca86034255f0a93c1a84734814be176ed4/sharpy/client.py#L70-L125
[ "def", "make_request", "(", "self", ",", "path", ",", "params", "=", "None", ",", "data", "=", "None", ",", "method", "=", "None", ")", ":", "# Setup values", "url", "=", "self", ".", "build_url", "(", "path", ",", "params", ")", "client_log", ".", "...
935943ca86034255f0a93c1a84734814be176ed4
train
main
parse commandline arguments and print result
examples/walk.py
def main(): """parse commandline arguments and print result""" # # setup command line parsing a la argpase # parser = argparse.ArgumentParser() # positional args parser.add_argument('uri', metavar='URI', nargs='?', default='/', help='[owserver:]//server:port/entity'...
def main(): """parse commandline arguments and print result""" # # setup command line parsing a la argpase # parser = argparse.ArgumentParser() # positional args parser.add_argument('uri', metavar='URI', nargs='?', default='/', help='[owserver:]//server:port/entity'...
[ "parse", "commandline", "arguments", "and", "print", "result" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/examples/walk.py#L38-L124
[ "def", "main", "(", ")", ":", "#", "# setup command line parsing a la argpase", "#", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "# positional args", "parser", ".", "add_argument", "(", "'uri'", ",", "metavar", "=", "'URI'", ",", "nargs", "=", ...
190afea6a72705772b942d7929bc0aa6561043e0
train
proxy
factory function that returns a proxy object for an owserver at host, port.
src/pyownet/protocol.py
def proxy(host='localhost', port=4304, flags=0, persistent=False, verbose=False, ): """factory function that returns a proxy object for an owserver at host, port. """ # resolve host name/port try: gai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM, ...
def proxy(host='localhost', port=4304, flags=0, persistent=False, verbose=False, ): """factory function that returns a proxy object for an owserver at host, port. """ # resolve host name/port try: gai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM, ...
[ "factory", "function", "that", "returns", "a", "proxy", "object", "for", "an", "owserver", "at", "host", "port", "." ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/src/pyownet/protocol.py#L708-L750
[ "def", "proxy", "(", "host", "=", "'localhost'", ",", "port", "=", "4304", ",", "flags", "=", "0", ",", "persistent", "=", "False", ",", "verbose", "=", "False", ",", ")", ":", "# resolve host name/port", "try", ":", "gai", "=", "socket", ".", "getaddr...
190afea6a72705772b942d7929bc0aa6561043e0
train
clone
factory function for cloning a proxy object
src/pyownet/protocol.py
def clone(proxy, persistent=True): """factory function for cloning a proxy object""" if not isinstance(proxy, _Proxy): raise TypeError('argument is not a Proxy object') if persistent: pclass = _PersistentProxy else: pclass = _Proxy return pclass(proxy._family, proxy._socka...
def clone(proxy, persistent=True): """factory function for cloning a proxy object""" if not isinstance(proxy, _Proxy): raise TypeError('argument is not a Proxy object') if persistent: pclass = _PersistentProxy else: pclass = _Proxy return pclass(proxy._family, proxy._socka...
[ "factory", "function", "for", "cloning", "a", "proxy", "object" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/src/pyownet/protocol.py#L753-L765
[ "def", "clone", "(", "proxy", ",", "persistent", "=", "True", ")", ":", "if", "not", "isinstance", "(", "proxy", ",", "_Proxy", ")", ":", "raise", "TypeError", "(", "'argument is not a Proxy object'", ")", "if", "persistent", ":", "pclass", "=", "_Persistent...
190afea6a72705772b942d7929bc0aa6561043e0
train
_OwnetConnection.shutdown
shutdown connection
src/pyownet/protocol.py
def shutdown(self): """shutdown connection""" if self.verbose: print(self.socket.getsockname(), 'xx', self.peername) try: self.socket.shutdown(socket.SHUT_RDWR) except IOError as err: assert err.errno is _ENOTCONN, "unexpected IOError: %s" % err ...
def shutdown(self): """shutdown connection""" if self.verbose: print(self.socket.getsockname(), 'xx', self.peername) try: self.socket.shutdown(socket.SHUT_RDWR) except IOError as err: assert err.errno is _ENOTCONN, "unexpected IOError: %s" % err ...
[ "shutdown", "connection" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/src/pyownet/protocol.py#L391-L403
[ "def", "shutdown", "(", "self", ")", ":", "if", "self", ".", "verbose", ":", "print", "(", "self", ".", "socket", ".", "getsockname", "(", ")", ",", "'xx'", ",", "self", ".", "peername", ")", "try", ":", "self", ".", "socket", ".", "shutdown", "(",...
190afea6a72705772b942d7929bc0aa6561043e0
train
_OwnetConnection.req
send message to server and return response
src/pyownet/protocol.py
def req(self, msgtype, payload, flags, size=0, offset=0, timeout=0): """send message to server and return response""" if timeout < 0: raise ValueError("timeout cannot be negative!") tohead = _ToServerHeader(payload=len(payload), type=msgtype, flags=...
def req(self, msgtype, payload, flags, size=0, offset=0, timeout=0): """send message to server and return response""" if timeout < 0: raise ValueError("timeout cannot be negative!") tohead = _ToServerHeader(payload=len(payload), type=msgtype, flags=...
[ "send", "message", "to", "server", "and", "return", "response" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/src/pyownet/protocol.py#L408-L436
[ "def", "req", "(", "self", ",", "msgtype", ",", "payload", ",", "flags", ",", "size", "=", "0", ",", "offset", "=", "0", ",", "timeout", "=", "0", ")", ":", "if", "timeout", "<", "0", ":", "raise", "ValueError", "(", "\"timeout cannot be negative!\"", ...
190afea6a72705772b942d7929bc0aa6561043e0
train
_OwnetConnection._send_msg
send message to server
src/pyownet/protocol.py
def _send_msg(self, header, payload): """send message to server""" if self.verbose: print('->', repr(header)) print('..', repr(payload)) assert header.payload == len(payload) try: sent = self.socket.send(header + payload) except IOError as err...
def _send_msg(self, header, payload): """send message to server""" if self.verbose: print('->', repr(header)) print('..', repr(payload)) assert header.payload == len(payload) try: sent = self.socket.send(header + payload) except IOError as err...
[ "send", "message", "to", "server" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/src/pyownet/protocol.py#L438-L456
[ "def", "_send_msg", "(", "self", ",", "header", ",", "payload", ")", ":", "if", "self", ".", "verbose", ":", "print", "(", "'->'", ",", "repr", "(", "header", ")", ")", "print", "(", "'..'", ",", "repr", "(", "payload", ")", ")", "assert", "header"...
190afea6a72705772b942d7929bc0aa6561043e0
train
_OwnetConnection._read_msg
read message from server
src/pyownet/protocol.py
def _read_msg(self): """read message from server""" # # NOTE: # '_recv_socket(nbytes)' was implemented as # 'socket.recv(nbytes, socket.MSG_WAITALL)' # but socket.MSG_WAITALL proved not reliable # def _recv_socket(nbytes): """read nbytes byte...
def _read_msg(self): """read message from server""" # # NOTE: # '_recv_socket(nbytes)' was implemented as # 'socket.recv(nbytes, socket.MSG_WAITALL)' # but socket.MSG_WAITALL proved not reliable # def _recv_socket(nbytes): """read nbytes byte...
[ "read", "message", "from", "server" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/src/pyownet/protocol.py#L458-L519
[ "def", "_read_msg", "(", "self", ")", ":", "#", "# NOTE:", "# '_recv_socket(nbytes)' was implemented as", "# 'socket.recv(nbytes, socket.MSG_WAITALL)'", "# but socket.MSG_WAITALL proved not reliable", "#", "def", "_recv_socket", "(", "nbytes", ")", ":", "\"\"\"read nbytes bytes f...
190afea6a72705772b942d7929bc0aa6561043e0
train
_Proxy.sendmess
retcode, data = sendmess(msgtype, payload) send generic message and returns retcode, data
src/pyownet/protocol.py
def sendmess(self, msgtype, payload, flags=0, size=0, offset=0, timeout=0): """ retcode, data = sendmess(msgtype, payload) send generic message and returns retcode, data """ flags |= self.flags assert not (flags & FLG_PERSISTENCE) with self._new_connection() as conn: ...
def sendmess(self, msgtype, payload, flags=0, size=0, offset=0, timeout=0): """ retcode, data = sendmess(msgtype, payload) send generic message and returns retcode, data """ flags |= self.flags assert not (flags & FLG_PERSISTENCE) with self._new_connection() as conn: ...
[ "retcode", "data", "=", "sendmess", "(", "msgtype", "payload", ")", "send", "generic", "message", "and", "returns", "retcode", "data" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/src/pyownet/protocol.py#L563-L575
[ "def", "sendmess", "(", "self", ",", "msgtype", ",", "payload", ",", "flags", "=", "0", ",", "size", "=", "0", ",", "offset", "=", "0", ",", "timeout", "=", "0", ")", ":", "flags", "|=", "self", ".", "flags", "assert", "not", "(", "flags", "&", ...
190afea6a72705772b942d7929bc0aa6561043e0
train
_Proxy.ping
sends a NOP packet and waits response; returns None
src/pyownet/protocol.py
def ping(self): """sends a NOP packet and waits response; returns None""" ret, data = self.sendmess(MSG_NOP, bytes()) if data or ret > 0: raise ProtocolError('invalid reply to ping message') if ret < 0: raise OwnetError(-ret, self.errmess[-ret])
def ping(self): """sends a NOP packet and waits response; returns None""" ret, data = self.sendmess(MSG_NOP, bytes()) if data or ret > 0: raise ProtocolError('invalid reply to ping message') if ret < 0: raise OwnetError(-ret, self.errmess[-ret])
[ "sends", "a", "NOP", "packet", "and", "waits", "response", ";", "returns", "None" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/src/pyownet/protocol.py#L577-L584
[ "def", "ping", "(", "self", ")", ":", "ret", ",", "data", "=", "self", ".", "sendmess", "(", "MSG_NOP", ",", "bytes", "(", ")", ")", "if", "data", "or", "ret", ">", "0", ":", "raise", "ProtocolError", "(", "'invalid reply to ping message'", ")", "if", ...
190afea6a72705772b942d7929bc0aa6561043e0
train
_Proxy.present
returns True if there is an entity at path
src/pyownet/protocol.py
def present(self, path, timeout=0): """returns True if there is an entity at path""" ret, data = self.sendmess(MSG_PRESENCE, str2bytez(path), timeout=timeout) assert ret <= 0 and not data, (ret, data) if ret < 0: return False else: ...
def present(self, path, timeout=0): """returns True if there is an entity at path""" ret, data = self.sendmess(MSG_PRESENCE, str2bytez(path), timeout=timeout) assert ret <= 0 and not data, (ret, data) if ret < 0: return False else: ...
[ "returns", "True", "if", "there", "is", "an", "entity", "at", "path" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/src/pyownet/protocol.py#L586-L595
[ "def", "present", "(", "self", ",", "path", ",", "timeout", "=", "0", ")", ":", "ret", ",", "data", "=", "self", ".", "sendmess", "(", "MSG_PRESENCE", ",", "str2bytez", "(", "path", ")", ",", "timeout", "=", "timeout", ")", "assert", "ret", "<=", "...
190afea6a72705772b942d7929bc0aa6561043e0
train
_Proxy.dir
list entities at path
src/pyownet/protocol.py
def dir(self, path='/', slash=True, bus=False, timeout=0): """list entities at path""" if slash: msg = MSG_DIRALLSLASH else: msg = MSG_DIRALL if bus: flags = self.flags | FLG_BUS_RET else: flags = self.flags & ~FLG_BUS_RET ...
def dir(self, path='/', slash=True, bus=False, timeout=0): """list entities at path""" if slash: msg = MSG_DIRALLSLASH else: msg = MSG_DIRALL if bus: flags = self.flags | FLG_BUS_RET else: flags = self.flags & ~FLG_BUS_RET ...
[ "list", "entities", "at", "path" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/src/pyownet/protocol.py#L597-L615
[ "def", "dir", "(", "self", ",", "path", "=", "'/'", ",", "slash", "=", "True", ",", "bus", "=", "False", ",", "timeout", "=", "0", ")", ":", "if", "slash", ":", "msg", "=", "MSG_DIRALLSLASH", "else", ":", "msg", "=", "MSG_DIRALL", "if", "bus", ":...
190afea6a72705772b942d7929bc0aa6561043e0
train
_Proxy.read
read data at path
src/pyownet/protocol.py
def read(self, path, size=MAX_PAYLOAD, offset=0, timeout=0): """read data at path""" if size > MAX_PAYLOAD: raise ValueError("size cannot exceed %d" % MAX_PAYLOAD) ret, data = self.sendmess(MSG_READ, str2bytez(path), size=size, offset=offset, timeo...
def read(self, path, size=MAX_PAYLOAD, offset=0, timeout=0): """read data at path""" if size > MAX_PAYLOAD: raise ValueError("size cannot exceed %d" % MAX_PAYLOAD) ret, data = self.sendmess(MSG_READ, str2bytez(path), size=size, offset=offset, timeo...
[ "read", "data", "at", "path" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/src/pyownet/protocol.py#L617-L627
[ "def", "read", "(", "self", ",", "path", ",", "size", "=", "MAX_PAYLOAD", ",", "offset", "=", "0", ",", "timeout", "=", "0", ")", ":", "if", "size", ">", "MAX_PAYLOAD", ":", "raise", "ValueError", "(", "\"size cannot exceed %d\"", "%", "MAX_PAYLOAD", ")"...
190afea6a72705772b942d7929bc0aa6561043e0
train
_Proxy.write
write data at path path is a string, data binary; it is responsability of the caller ensure proper encoding.
src/pyownet/protocol.py
def write(self, path, data, offset=0, timeout=0): """write data at path path is a string, data binary; it is responsability of the caller ensure proper encoding. """ # fixme: check of path type delayed to str2bytez if not isinstance(data, (bytes, bytearray, )): ...
def write(self, path, data, offset=0, timeout=0): """write data at path path is a string, data binary; it is responsability of the caller ensure proper encoding. """ # fixme: check of path type delayed to str2bytez if not isinstance(data, (bytes, bytearray, )): ...
[ "write", "data", "at", "path" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/src/pyownet/protocol.py#L629-L645
[ "def", "write", "(", "self", ",", "path", ",", "data", ",", "offset", "=", "0", ",", "timeout", "=", "0", ")", ":", "# fixme: check of path type delayed to str2bytez", "if", "not", "isinstance", "(", "data", ",", "(", "bytes", ",", "bytearray", ",", ")", ...
190afea6a72705772b942d7929bc0aa6561043e0
train
_PersistentProxy.sendmess
retcode, data = sendmess(msgtype, payload) send generic message and returns retcode, data
src/pyownet/protocol.py
def sendmess(self, msgtype, payload, flags=0, size=0, offset=0, timeout=0): """ retcode, data = sendmess(msgtype, payload) send generic message and returns retcode, data """ # reuse last valid connection or create new conn = self.conn or self._new_connection() # ...
def sendmess(self, msgtype, payload, flags=0, size=0, offset=0, timeout=0): """ retcode, data = sendmess(msgtype, payload) send generic message and returns retcode, data """ # reuse last valid connection or create new conn = self.conn or self._new_connection() # ...
[ "retcode", "data", "=", "sendmess", "(", "msgtype", "payload", ")", "send", "generic", "message", "and", "returns", "retcode", "data" ]
miccoli/pyownet
python
https://github.com/miccoli/pyownet/blob/190afea6a72705772b942d7929bc0aa6561043e0/src/pyownet/protocol.py#L679-L701
[ "def", "sendmess", "(", "self", ",", "msgtype", ",", "payload", ",", "flags", "=", "0", ",", "size", "=", "0", ",", "offset", "=", "0", ",", "timeout", "=", "0", ")", ":", "# reuse last valid connection or create new", "conn", "=", "self", ".", "conn", ...
190afea6a72705772b942d7929bc0aa6561043e0
train
CheddarProduct.get_customers
Returns all customers. Sometimes they are too much and cause internal server errors on CG. API call permits post parameters for filtering which tends to fix this https://cheddargetter.com/developers#all-customers filter_data Will be processed by urlencode and can be used f...
sharpy/product.py
def get_customers(self, filter_data=None): ''' Returns all customers. Sometimes they are too much and cause internal server errors on CG. API call permits post parameters for filtering which tends to fix this https://cheddargetter.com/developers#all-customers filter_da...
def get_customers(self, filter_data=None): ''' Returns all customers. Sometimes they are too much and cause internal server errors on CG. API call permits post parameters for filtering which tends to fix this https://cheddargetter.com/developers#all-customers filter_da...
[ "Returns", "all", "customers", ".", "Sometimes", "they", "are", "too", "much", "and", "cause", "internal", "server", "errors", "on", "CG", ".", "API", "call", "permits", "post", "parameters", "for", "filtering", "which", "tends", "to", "fix", "this", "https"...
SeanOC/sharpy
python
https://github.com/SeanOC/sharpy/blob/935943ca86034255f0a93c1a84734814be176ed4/sharpy/product.py#L214-L241
[ "def", "get_customers", "(", "self", ",", "filter_data", "=", "None", ")", ":", "customers", "=", "[", "]", "try", ":", "response", "=", "self", ".", "client", ".", "make_request", "(", "path", "=", "'customers/get'", ",", "data", "=", "filter_data", ")"...
935943ca86034255f0a93c1a84734814be176ed4
train
CheddarProduct.delete_all_customers
This method does exactly what you think it does. Calling this method deletes all customer data in your cheddar product and the configured gateway. This action cannot be undone. DO NOT RUN THIS UNLESS YOU REALLY, REALLY, REALLY MEAN TO!
sharpy/product.py
def delete_all_customers(self): ''' This method does exactly what you think it does. Calling this method deletes all customer data in your cheddar product and the configured gateway. This action cannot be undone. DO NOT RUN THIS UNLESS YOU REALLY, REALLY, REALLY MEAN T...
def delete_all_customers(self): ''' This method does exactly what you think it does. Calling this method deletes all customer data in your cheddar product and the configured gateway. This action cannot be undone. DO NOT RUN THIS UNLESS YOU REALLY, REALLY, REALLY MEAN T...
[ "This", "method", "does", "exactly", "what", "you", "think", "it", "does", ".", "Calling", "this", "method", "deletes", "all", "customer", "data", "in", "your", "cheddar", "product", "and", "the", "configured", "gateway", ".", "This", "action", "cannot", "be...
SeanOC/sharpy
python
https://github.com/SeanOC/sharpy/blob/935943ca86034255f0a93c1a84734814be176ed4/sharpy/product.py#L254-L265
[ "def", "delete_all_customers", "(", "self", ")", ":", "response", "=", "self", ".", "client", ".", "make_request", "(", "path", "=", "'customers/delete-all/confirm/%d'", "%", "int", "(", "time", "(", ")", ")", ",", "method", "=", "'POST'", ")" ]
935943ca86034255f0a93c1a84734814be176ed4
train
PricingPlan.initial_bill_date
An estimated initial bill date for an account created today, based on available plan info.
sharpy/product.py
def initial_bill_date(self): ''' An estimated initial bill date for an account created today, based on available plan info. ''' time_to_start = None if self.initial_bill_count_unit == 'months': time_to_start = relativedelta(months=self.initial_bill_co...
def initial_bill_date(self): ''' An estimated initial bill date for an account created today, based on available plan info. ''' time_to_start = None if self.initial_bill_count_unit == 'months': time_to_start = relativedelta(months=self.initial_bill_co...
[ "An", "estimated", "initial", "bill", "date", "for", "an", "account", "created", "today", "based", "on", "available", "plan", "info", "." ]
SeanOC/sharpy
python
https://github.com/SeanOC/sharpy/blob/935943ca86034255f0a93c1a84734814be176ed4/sharpy/product.py#L331-L345
[ "def", "initial_bill_date", "(", "self", ")", ":", "time_to_start", "=", "None", "if", "self", ".", "initial_bill_count_unit", "==", "'months'", ":", "time_to_start", "=", "relativedelta", "(", "months", "=", "self", ".", "initial_bill_count", ")", "else", ":", ...
935943ca86034255f0a93c1a84734814be176ed4
train
Customer.charge
Add an arbitrary charge or credit to a customer's account. A positive number will create a charge. A negative number will create a credit. each_amount is normalized to a Decimal with a precision of 2 as that is the level of precision which the cheddar API supports.
sharpy/product.py
def charge(self, code, each_amount, quantity=1, description=None): ''' Add an arbitrary charge or credit to a customer's account. A positive number will create a charge. A negative number will create a credit. each_amount is normalized to a Decimal with a precision of 2 as tha...
def charge(self, code, each_amount, quantity=1, description=None): ''' Add an arbitrary charge or credit to a customer's account. A positive number will create a charge. A negative number will create a credit. each_amount is normalized to a Decimal with a precision of 2 as tha...
[ "Add", "an", "arbitrary", "charge", "or", "credit", "to", "a", "customer", "s", "account", ".", "A", "positive", "number", "will", "create", "a", "charge", ".", "A", "negative", "number", "will", "create", "a", "credit", ".", "each_amount", "is", "normaliz...
SeanOC/sharpy
python
https://github.com/SeanOC/sharpy/blob/935943ca86034255f0a93c1a84734814be176ed4/sharpy/product.py#L482-L505
[ "def", "charge", "(", "self", ",", "code", ",", "each_amount", ",", "quantity", "=", "1", ",", "description", "=", "None", ")", ":", "each_amount", "=", "Decimal", "(", "each_amount", ")", "each_amount", "=", "each_amount", ".", "quantize", "(", "Decimal",...
935943ca86034255f0a93c1a84734814be176ed4
train
Customer.create_one_time_invoice
Charges should be a list of charges to execute immediately. Each value in the charges diectionary should be a dictionary with the following keys: code Your code for this charge. This code will be displayed in the user's invoice and is limited to 36 characters. ...
sharpy/product.py
def create_one_time_invoice(self, charges): ''' Charges should be a list of charges to execute immediately. Each value in the charges diectionary should be a dictionary with the following keys: code Your code for this charge. This code will be displayed in the ...
def create_one_time_invoice(self, charges): ''' Charges should be a list of charges to execute immediately. Each value in the charges diectionary should be a dictionary with the following keys: code Your code for this charge. This code will be displayed in the ...
[ "Charges", "should", "be", "a", "list", "of", "charges", "to", "execute", "immediately", ".", "Each", "value", "in", "the", "charges", "diectionary", "should", "be", "a", "dictionary", "with", "the", "following", "keys", ":" ]
SeanOC/sharpy
python
https://github.com/SeanOC/sharpy/blob/935943ca86034255f0a93c1a84734814be176ed4/sharpy/product.py#L507-L542
[ "def", "create_one_time_invoice", "(", "self", ",", "charges", ")", ":", "data", "=", "{", "}", "for", "n", ",", "charge", "in", "enumerate", "(", "charges", ")", ":", "each_amount", "=", "Decimal", "(", "charge", "[", "'each_amount'", "]", ")", "each_am...
935943ca86034255f0a93c1a84734814be176ed4
train
Item.set
Set the item's quantity to the passed in amount. If nothing is passed in, a quantity of 1 is assumed. If a decimal value is passsed in, it is rounded to the 4th decimal place as that is the level of precision which the Cheddar API accepts.
sharpy/product.py
def set(self, quantity): ''' Set the item's quantity to the passed in amount. If nothing is passed in, a quantity of 1 is assumed. If a decimal value is passsed in, it is rounded to the 4th decimal place as that is the level of precision which the Cheddar API accepts. ...
def set(self, quantity): ''' Set the item's quantity to the passed in amount. If nothing is passed in, a quantity of 1 is assumed. If a decimal value is passsed in, it is rounded to the 4th decimal place as that is the level of precision which the Cheddar API accepts. ...
[ "Set", "the", "item", "s", "quantity", "to", "the", "passed", "in", "amount", ".", "If", "nothing", "is", "passed", "in", "a", "quantity", "of", "1", "is", "assumed", ".", "If", "a", "decimal", "value", "is", "passsed", "in", "it", "is", "rounded", "...
SeanOC/sharpy
python
https://github.com/SeanOC/sharpy/blob/935943ca86034255f0a93c1a84734814be176ed4/sharpy/product.py#L746-L766
[ "def", "set", "(", "self", ",", "quantity", ")", ":", "data", "=", "{", "}", "data", "[", "'quantity'", "]", "=", "self", ".", "_normalize_quantity", "(", "quantity", ")", "response", "=", "self", ".", "subscription", ".", "customer", ".", "product", "...
935943ca86034255f0a93c1a84734814be176ed4
train
Name.deep_compare
Compares each field of the name one at a time to see if they match. Each name field has context-specific comparison logic. :param Name other: other Name for comparison :return bool: whether the two names are compatible
whoswho/model.py
def deep_compare(self, other, settings): """ Compares each field of the name one at a time to see if they match. Each name field has context-specific comparison logic. :param Name other: other Name for comparison :return bool: whether the two names are compatible """ ...
def deep_compare(self, other, settings): """ Compares each field of the name one at a time to see if they match. Each name field has context-specific comparison logic. :param Name other: other Name for comparison :return bool: whether the two names are compatible """ ...
[ "Compares", "each", "field", "of", "the", "name", "one", "at", "a", "time", "to", "see", "if", "they", "match", ".", "Each", "name", "field", "has", "context", "-", "specific", "comparison", "logic", "." ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/model.py#L25-L39
[ "def", "deep_compare", "(", "self", ",", "other", ",", "settings", ")", ":", "if", "not", "self", ".", "_is_compatible_with", "(", "other", ")", ":", "return", "False", "first", ",", "middle", ",", "last", "=", "self", ".", "_compare_components", "(", "o...
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
Name.ratio_deep_compare
Compares each field of the name one at a time to see if they match. Each name field has context-specific comparison logic. :param Name other: other Name for comparison :return int: sequence ratio match (out of 100)
whoswho/model.py
def ratio_deep_compare(self, other, settings): """ Compares each field of the name one at a time to see if they match. Each name field has context-specific comparison logic. :param Name other: other Name for comparison :return int: sequence ratio match (out of 100) """ ...
def ratio_deep_compare(self, other, settings): """ Compares each field of the name one at a time to see if they match. Each name field has context-specific comparison logic. :param Name other: other Name for comparison :return int: sequence ratio match (out of 100) """ ...
[ "Compares", "each", "field", "of", "the", "name", "one", "at", "a", "time", "to", "see", "if", "they", "match", ".", "Each", "name", "field", "has", "context", "-", "specific", "comparison", "logic", "." ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/model.py#L41-L63
[ "def", "ratio_deep_compare", "(", "self", ",", "other", ",", "settings", ")", ":", "if", "not", "self", ".", "_is_compatible_with", "(", "other", ")", ":", "return", "0", "first", ",", "middle", ",", "last", "=", "self", ".", "_compare_components", "(", ...
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
Name._is_compatible_with
Return True if names are not incompatible. This checks that the gender of titles and compatibility of suffixes
whoswho/model.py
def _is_compatible_with(self, other): """ Return True if names are not incompatible. This checks that the gender of titles and compatibility of suffixes """ title = self._compare_title(other) suffix = self._compare_suffix(other) return title and suffix
def _is_compatible_with(self, other): """ Return True if names are not incompatible. This checks that the gender of titles and compatibility of suffixes """ title = self._compare_title(other) suffix = self._compare_suffix(other) return title and suffix
[ "Return", "True", "if", "names", "are", "not", "incompatible", "." ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/model.py#L65-L75
[ "def", "_is_compatible_with", "(", "self", ",", "other", ")", ":", "title", "=", "self", ".", "_compare_title", "(", "other", ")", "suffix", "=", "self", ".", "_compare_suffix", "(", "other", ")", "return", "title", "and", "suffix" ]
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
Name._compare_title
Return False if titles have different gender associations
whoswho/model.py
def _compare_title(self, other): """Return False if titles have different gender associations""" # If title is omitted, assume a match if not self.title or not other.title: return True titles = set(self.title_list + other.title_list) return not (titles & MALE_TITLE...
def _compare_title(self, other): """Return False if titles have different gender associations""" # If title is omitted, assume a match if not self.title or not other.title: return True titles = set(self.title_list + other.title_list) return not (titles & MALE_TITLE...
[ "Return", "False", "if", "titles", "have", "different", "gender", "associations" ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/model.py#L77-L86
[ "def", "_compare_title", "(", "self", ",", "other", ")", ":", "# If title is omitted, assume a match", "if", "not", "self", ".", "title", "or", "not", "other", ".", "title", ":", "return", "True", "titles", "=", "set", "(", "self", ".", "title_list", "+", ...
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
Name._compare_suffix
Return false if suffixes are mutually exclusive
whoswho/model.py
def _compare_suffix(self, other): """Return false if suffixes are mutually exclusive""" # If suffix is omitted, assume a match if not self.suffix or not other.suffix: return True # Check if more than one unique suffix suffix_set = set(self.suffix_list + other.suffix...
def _compare_suffix(self, other): """Return false if suffixes are mutually exclusive""" # If suffix is omitted, assume a match if not self.suffix or not other.suffix: return True # Check if more than one unique suffix suffix_set = set(self.suffix_list + other.suffix...
[ "Return", "false", "if", "suffixes", "are", "mutually", "exclusive" ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/model.py#L88-L103
[ "def", "_compare_suffix", "(", "self", ",", "other", ")", ":", "# If suffix is omitted, assume a match", "if", "not", "self", ".", "suffix", "or", "not", "other", ".", "suffix", ":", "return", "True", "# Check if more than one unique suffix", "suffix_set", "=", "set...
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
Name._compare_components
Return comparison of first, middle, and last components
whoswho/model.py
def _compare_components(self, other, settings, ratio=False): """Return comparison of first, middle, and last components""" first = compare_name_component( self.first_list, other.first_list, settings['first'], ratio, ) if settings['check_n...
def _compare_components(self, other, settings, ratio=False): """Return comparison of first, middle, and last components""" first = compare_name_component( self.first_list, other.first_list, settings['first'], ratio, ) if settings['check_n...
[ "Return", "comparison", "of", "first", "middle", "and", "last", "components" ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/model.py#L105-L159
[ "def", "_compare_components", "(", "self", ",", "other", ",", "settings", ",", "ratio", "=", "False", ")", ":", "first", "=", "compare_name_component", "(", "self", ".", "first_list", ",", "other", ".", "first_list", ",", "settings", "[", "'first'", "]", "...
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
Name._determine_weights
Return weights of name components based on whether or not they were omitted
whoswho/model.py
def _determine_weights(self, other, settings): """ Return weights of name components based on whether or not they were omitted """ # TODO: Reduce weight for matches by prefix or initials first_is_used = settings['first']['required'] or \ self.first and other...
def _determine_weights(self, other, settings): """ Return weights of name components based on whether or not they were omitted """ # TODO: Reduce weight for matches by prefix or initials first_is_used = settings['first']['required'] or \ self.first and other...
[ "Return", "weights", "of", "name", "components", "based", "on", "whether", "or", "not", "they", "were", "omitted" ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/model.py#L161-L181
[ "def", "_determine_weights", "(", "self", ",", "other", ",", "settings", ")", ":", "# TODO: Reduce weight for matches by prefix or initials", "first_is_used", "=", "settings", "[", "'first'", "]", "[", "'required'", "]", "or", "self", ".", "first", "and", "other", ...
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
Limiter.init_app
:param app: :class:`sanic.Sanic` instance to rate limit.
sanic_limiter/extension.py
def init_app(self, app): """ :param app: :class:`sanic.Sanic` instance to rate limit. """ self.enabled = app.config.setdefault(C.ENABLED, True) self._swallow_errors = app.config.setdefault( C.SWALLOW_ERRORS, self._swallow_errors ) self._storage_options...
def init_app(self, app): """ :param app: :class:`sanic.Sanic` instance to rate limit. """ self.enabled = app.config.setdefault(C.ENABLED, True) self._swallow_errors = app.config.setdefault( C.SWALLOW_ERRORS, self._swallow_errors ) self._storage_options...
[ ":", "param", "app", ":", ":", "class", ":", "sanic", ".", "Sanic", "instance", "to", "rate", "limit", "." ]
bohea/sanic-limiter
python
https://github.com/bohea/sanic-limiter/blob/54c9fc4a3a3f1a9bb69367262637d07701ae5694/sanic_limiter/extension.py#L116-L147
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "self", ".", "enabled", "=", "app", ".", "config", ".", "setdefault", "(", "C", ".", "ENABLED", ",", "True", ")", "self", ".", "_swallow_errors", "=", "app", ".", "config", ".", "setdefault", "(",...
54c9fc4a3a3f1a9bb69367262637d07701ae5694
train
Limiter.limit
decorator to be used for rate limiting individual routes. :param limit_value: rate limit string or a callable that returns a string. :ref:`ratelimit-string` for more details. :param function key_func: function/lambda to extract the unique identifier for the rate limit. defaults to rem...
sanic_limiter/extension.py
def limit(self, limit_value, key_func=None, per_method=False, methods=None, error_message=None, exempt_when=None): """ decorator to be used for rate limiting individual routes. :param limit_value: rate limit string or a callable that returns a string. :ref:`ratelimit-stri...
def limit(self, limit_value, key_func=None, per_method=False, methods=None, error_message=None, exempt_when=None): """ decorator to be used for rate limiting individual routes. :param limit_value: rate limit string or a callable that returns a string. :ref:`ratelimit-stri...
[ "decorator", "to", "be", "used", "for", "rate", "limiting", "individual", "routes", "." ]
bohea/sanic-limiter
python
https://github.com/bohea/sanic-limiter/blob/54c9fc4a3a3f1a9bb69367262637d07701ae5694/sanic_limiter/extension.py#L297-L316
[ "def", "limit", "(", "self", ",", "limit_value", ",", "key_func", "=", "None", ",", "per_method", "=", "False", ",", "methods", "=", "None", ",", "error_message", "=", "None", ",", "exempt_when", "=", "None", ")", ":", "return", "self", ".", "__limit_dec...
54c9fc4a3a3f1a9bb69367262637d07701ae5694
train
Limiter.shared_limit
decorator to be applied to multiple routes sharing the same rate limit. :param limit_value: rate limit string or a callable that returns a string. :ref:`ratelimit-string` for more details. :param scope: a string or callable that returns a string for defining the rate limiting scope. ...
sanic_limiter/extension.py
def shared_limit(self, limit_value, scope, key_func=None, error_message=None, exempt_when=None): """ decorator to be applied to multiple routes sharing the same rate limit. :param limit_value: rate limit string or a callable that returns a string. :ref:`ratelimit-s...
def shared_limit(self, limit_value, scope, key_func=None, error_message=None, exempt_when=None): """ decorator to be applied to multiple routes sharing the same rate limit. :param limit_value: rate limit string or a callable that returns a string. :ref:`ratelimit-s...
[ "decorator", "to", "be", "applied", "to", "multiple", "routes", "sharing", "the", "same", "rate", "limit", "." ]
bohea/sanic-limiter
python
https://github.com/bohea/sanic-limiter/blob/54c9fc4a3a3f1a9bb69367262637d07701ae5694/sanic_limiter/extension.py#L318-L335
[ "def", "shared_limit", "(", "self", ",", "limit_value", ",", "scope", ",", "key_func", "=", "None", ",", "error_message", "=", "None", ",", "exempt_when", "=", "None", ")", ":", "return", "self", ".", "__limit_decorator", "(", "limit_value", ",", "key_func",...
54c9fc4a3a3f1a9bb69367262637d07701ae5694
train
Limiter.reset
resets the storage if it supports being reset
sanic_limiter/extension.py
def reset(self): """ resets the storage if it supports being reset """ try: self._storage.reset() self.logger.info("Storage has been reset and all limits cleared") except NotImplementedError: self.logger.warning("This storage type does not supp...
def reset(self): """ resets the storage if it supports being reset """ try: self._storage.reset() self.logger.info("Storage has been reset and all limits cleared") except NotImplementedError: self.logger.warning("This storage type does not supp...
[ "resets", "the", "storage", "if", "it", "supports", "being", "reset" ]
bohea/sanic-limiter
python
https://github.com/bohea/sanic-limiter/blob/54c9fc4a3a3f1a9bb69367262637d07701ae5694/sanic_limiter/extension.py#L358-L366
[ "def", "reset", "(", "self", ")", ":", "try", ":", "self", ".", "_storage", ".", "reset", "(", ")", "self", ".", "logger", ".", "info", "(", "\"Storage has been reset and all limits cleared\"", ")", "except", "NotImplementedError", ":", "self", ".", "logger", ...
54c9fc4a3a3f1a9bb69367262637d07701ae5694
train
get_soup
Returns a bs4 object of the page requested
hn/utils.py
def get_soup(page=''): """ Returns a bs4 object of the page requested """ content = requests.get('%s/%s' % (BASE_URL, page)).text return BeautifulSoup(content)
def get_soup(page=''): """ Returns a bs4 object of the page requested """ content = requests.get('%s/%s' % (BASE_URL, page)).text return BeautifulSoup(content)
[ "Returns", "a", "bs4", "object", "of", "the", "page", "requested" ]
karan/HackerNewsAPI
python
https://github.com/karan/HackerNewsAPI/blob/0e2df2e28f3a6090559eacdefdb99f4d6780ddf5/hn/utils.py#L9-L14
[ "def", "get_soup", "(", "page", "=", "''", ")", ":", "content", "=", "requests", ".", "get", "(", "'%s/%s'", "%", "(", "BASE_URL", ",", "page", ")", ")", ".", "text", "return", "BeautifulSoup", "(", "content", ")" ]
0e2df2e28f3a6090559eacdefdb99f4d6780ddf5
train
match
Takes two names and returns true if they describe the same person. :param string fullname1: first human name :param string fullname2: second human name :param string strictness: strictness settings to use :param dict options: custom strictness settings updates :return bool: the names match
whoswho/who.py
def match(fullname1, fullname2, strictness='default', options=None): """ Takes two names and returns true if they describe the same person. :param string fullname1: first human name :param string fullname2: second human name :param string strictness: strictness settings to use :param dict optio...
def match(fullname1, fullname2, strictness='default', options=None): """ Takes two names and returns true if they describe the same person. :param string fullname1: first human name :param string fullname2: second human name :param string strictness: strictness settings to use :param dict optio...
[ "Takes", "two", "names", "and", "returns", "true", "if", "they", "describe", "the", "same", "person", "." ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/who.py#L8-L28
[ "def", "match", "(", "fullname1", ",", "fullname2", ",", "strictness", "=", "'default'", ",", "options", "=", "None", ")", ":", "if", "options", "is", "not", "None", ":", "settings", "=", "deepcopy", "(", "SETTINGS", "[", "strictness", "]", ")", "deep_up...
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
ratio
Takes two names and returns true if they describe the same person. Uses difflib's sequence matching on a per-field basis for names :param string fullname1: first human name :param string fullname2: second human name :param string strictness: strictness settings to use :param dict options: custom st...
whoswho/who.py
def ratio(fullname1, fullname2, strictness='default', options=None): """ Takes two names and returns true if they describe the same person. Uses difflib's sequence matching on a per-field basis for names :param string fullname1: first human name :param string fullname2: second human name :param...
def ratio(fullname1, fullname2, strictness='default', options=None): """ Takes two names and returns true if they describe the same person. Uses difflib's sequence matching on a per-field basis for names :param string fullname1: first human name :param string fullname2: second human name :param...
[ "Takes", "two", "names", "and", "returns", "true", "if", "they", "describe", "the", "same", "person", ".", "Uses", "difflib", "s", "sequence", "matching", "on", "a", "per", "-", "field", "basis", "for", "names" ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/who.py#L31-L52
[ "def", "ratio", "(", "fullname1", ",", "fullname2", ",", "strictness", "=", "'default'", ",", "options", "=", "None", ")", ":", "if", "options", "is", "not", "None", ":", "settings", "=", "deepcopy", "(", "SETTINGS", "[", "strictness", "]", ")", "deep_up...
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
HN._get_zipped_rows
Returns all 'tr' tag rows as a list of tuples. Each tuple is for a single story.
hn/hn.py
def _get_zipped_rows(self, soup): """ Returns all 'tr' tag rows as a list of tuples. Each tuple is for a single story. """ # the table with all submissions table = soup.findChildren('table')[2] # get all rows but last 2 rows = table.findChildren(['...
def _get_zipped_rows(self, soup): """ Returns all 'tr' tag rows as a list of tuples. Each tuple is for a single story. """ # the table with all submissions table = soup.findChildren('table')[2] # get all rows but last 2 rows = table.findChildren(['...
[ "Returns", "all", "tr", "tag", "rows", "as", "a", "list", "of", "tuples", ".", "Each", "tuple", "is", "for", "a", "single", "story", "." ]
karan/HackerNewsAPI
python
https://github.com/karan/HackerNewsAPI/blob/0e2df2e28f3a6090559eacdefdb99f4d6780ddf5/hn/hn.py#L36-L55
[ "def", "_get_zipped_rows", "(", "self", ",", "soup", ")", ":", "# the table with all submissions\r", "table", "=", "soup", ".", "findChildren", "(", "'table'", ")", "[", "2", "]", "# get all rows but last 2\r", "rows", "=", "table", ".", "findChildren", "(", "["...
0e2df2e28f3a6090559eacdefdb99f4d6780ddf5
train
HN._build_story
Builds and returns a list of stories (dicts) from the passed source.
hn/hn.py
def _build_story(self, all_rows): """ Builds and returns a list of stories (dicts) from the passed source. """ # list to hold all stories all_stories = [] for (info, detail) in all_rows: #-- Get the into about a story --# # split in 3 c...
def _build_story(self, all_rows): """ Builds and returns a list of stories (dicts) from the passed source. """ # list to hold all stories all_stories = [] for (info, detail) in all_rows: #-- Get the into about a story --# # split in 3 c...
[ "Builds", "and", "returns", "a", "list", "of", "stories", "(", "dicts", ")", "from", "the", "passed", "source", "." ]
karan/HackerNewsAPI
python
https://github.com/karan/HackerNewsAPI/blob/0e2df2e28f3a6090559eacdefdb99f4d6780ddf5/hn/hn.py#L57-L138
[ "def", "_build_story", "(", "self", ",", "all_rows", ")", ":", "# list to hold all stories\r", "all_stories", "=", "[", "]", "for", "(", "info", ",", "detail", ")", "in", "all_rows", ":", "#-- Get the into about a story --#\r", "# split in 3 cells\r", "info_cells", ...
0e2df2e28f3a6090559eacdefdb99f4d6780ddf5
train
HN.get_stories
Yields a list of stories from the passed page of HN. 'story_type' can be: \t'' = top stories (homepage) (default) \t'news2' = page 2 of top stories \t'newest' = most recent stories \t'best' = best stories 'limit' is the number of stories required from the...
hn/hn.py
def get_stories(self, story_type='', limit=30): """ Yields a list of stories from the passed page of HN. 'story_type' can be: \t'' = top stories (homepage) (default) \t'news2' = page 2 of top stories \t'newest' = most recent stories \t'best' = best...
def get_stories(self, story_type='', limit=30): """ Yields a list of stories from the passed page of HN. 'story_type' can be: \t'' = top stories (homepage) (default) \t'news2' = page 2 of top stories \t'newest' = most recent stories \t'best' = best...
[ "Yields", "a", "list", "of", "stories", "from", "the", "passed", "page", "of", "HN", ".", "story_type", "can", "be", ":", "\\", "t", "=", "top", "stories", "(", "homepage", ")", "(", "default", ")", "\\", "t", "news2", "=", "page", "2", "of", "top"...
karan/HackerNewsAPI
python
https://github.com/karan/HackerNewsAPI/blob/0e2df2e28f3a6090559eacdefdb99f4d6780ddf5/hn/hn.py#L140-L175
[ "def", "get_stories", "(", "self", ",", "story_type", "=", "''", ",", "limit", "=", "30", ")", ":", "if", "limit", "is", "None", "or", "limit", "<", "1", "or", "limit", ">", "30", ":", "# we need at least 30 items\r", "limit", "=", "30", "stories_found",...
0e2df2e28f3a6090559eacdefdb99f4d6780ddf5
train
HN.get_leaders
Return the leaders of Hacker News
hn/hn.py
def get_leaders(self, limit=10): """ Return the leaders of Hacker News """ if limit is None: limit = 10 soup = get_soup('leaders') table = soup.find('table') leaders_table = table.find_all('table')[1] listleaders = leaders_table.find_all('tr')[2:] ...
def get_leaders(self, limit=10): """ Return the leaders of Hacker News """ if limit is None: limit = 10 soup = get_soup('leaders') table = soup.find('table') leaders_table = table.find_all('table')[1] listleaders = leaders_table.find_all('tr')[2:] ...
[ "Return", "the", "leaders", "of", "Hacker", "News" ]
karan/HackerNewsAPI
python
https://github.com/karan/HackerNewsAPI/blob/0e2df2e28f3a6090559eacdefdb99f4d6780ddf5/hn/hn.py#L177-L191
[ "def", "get_leaders", "(", "self", ",", "limit", "=", "10", ")", ":", "if", "limit", "is", "None", ":", "limit", "=", "10", "soup", "=", "get_soup", "(", "'leaders'", ")", "table", "=", "soup", ".", "find", "(", "'table'", ")", "leaders_table", "=", ...
0e2df2e28f3a6090559eacdefdb99f4d6780ddf5
train
Story._get_next_page
Get the relative url of the next page (The "More" link at the bottom of the page)
hn/hn.py
def _get_next_page(self, soup, current_page): """ Get the relative url of the next page (The "More" link at the bottom of the page) """ # Get the table with all the comments: if current_page == 1: table = soup.findChildren('table')[3] elif cu...
def _get_next_page(self, soup, current_page): """ Get the relative url of the next page (The "More" link at the bottom of the page) """ # Get the table with all the comments: if current_page == 1: table = soup.findChildren('table')[3] elif cu...
[ "Get", "the", "relative", "url", "of", "the", "next", "page", "(", "The", "More", "link", "at", "the", "bottom", "of", "the", "page", ")" ]
karan/HackerNewsAPI
python
https://github.com/karan/HackerNewsAPI/blob/0e2df2e28f3a6090559eacdefdb99f4d6780ddf5/hn/hn.py#L221-L238
[ "def", "_get_next_page", "(", "self", ",", "soup", ",", "current_page", ")", ":", "# Get the table with all the comments:\r", "if", "current_page", "==", "1", ":", "table", "=", "soup", ".", "findChildren", "(", "'table'", ")", "[", "3", "]", "elif", "current_...
0e2df2e28f3a6090559eacdefdb99f4d6780ddf5
train
Story._build_comments
For the story, builds and returns a list of Comment objects.
hn/hn.py
def _build_comments(self, soup): """ For the story, builds and returns a list of Comment objects. """ comments = [] current_page = 1 while True: # Get the table holding all comments: if current_page == 1: table = soup.f...
def _build_comments(self, soup): """ For the story, builds and returns a list of Comment objects. """ comments = [] current_page = 1 while True: # Get the table holding all comments: if current_page == 1: table = soup.f...
[ "For", "the", "story", "builds", "and", "returns", "a", "list", "of", "Comment", "objects", "." ]
karan/HackerNewsAPI
python
https://github.com/karan/HackerNewsAPI/blob/0e2df2e28f3a6090559eacdefdb99f4d6780ddf5/hn/hn.py#L240-L346
[ "def", "_build_comments", "(", "self", ",", "soup", ")", ":", "comments", "=", "[", "]", "current_page", "=", "1", "while", "True", ":", "# Get the table holding all comments:\r", "if", "current_page", "==", "1", ":", "table", "=", "soup", ".", "findChildren",...
0e2df2e28f3a6090559eacdefdb99f4d6780ddf5
train
Story.fromid
Initializes an instance of Story for given item_id. It is assumed that the story referenced by item_id is valid and does not raise any HTTP errors. item_id is an int.
hn/hn.py
def fromid(self, item_id): """ Initializes an instance of Story for given item_id. It is assumed that the story referenced by item_id is valid and does not raise any HTTP errors. item_id is an int. """ if not item_id: raise Exception('Need an i...
def fromid(self, item_id): """ Initializes an instance of Story for given item_id. It is assumed that the story referenced by item_id is valid and does not raise any HTTP errors. item_id is an int. """ if not item_id: raise Exception('Need an i...
[ "Initializes", "an", "instance", "of", "Story", "for", "given", "item_id", ".", "It", "is", "assumed", "that", "the", "story", "referenced", "by", "item_id", "is", "valid", "and", "does", "not", "raise", "any", "HTTP", "errors", ".", "item_id", "is", "an",...
karan/HackerNewsAPI
python
https://github.com/karan/HackerNewsAPI/blob/0e2df2e28f3a6090559eacdefdb99f4d6780ddf5/hn/hn.py#L349-L402
[ "def", "fromid", "(", "self", ",", "item_id", ")", ":", "if", "not", "item_id", ":", "raise", "Exception", "(", "'Need an item_id for a story'", ")", "# get details about a particular story\r", "soup", "=", "get_item_soup", "(", "item_id", ")", "# this post has not be...
0e2df2e28f3a6090559eacdefdb99f4d6780ddf5
train
compare_name_component
Compare a list of names from a name component based on settings
whoswho/utils.py
def compare_name_component(list1, list2, settings, use_ratio=False): """ Compare a list of names from a name component based on settings """ if not list1[0] or not list2[0]: not_required = not settings['required'] return not_required * 100 if use_ratio else not_required if len(list1...
def compare_name_component(list1, list2, settings, use_ratio=False): """ Compare a list of names from a name component based on settings """ if not list1[0] or not list2[0]: not_required = not settings['required'] return not_required * 100 if use_ratio else not_required if len(list1...
[ "Compare", "a", "list", "of", "names", "from", "a", "name", "component", "based", "on", "settings" ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/utils.py#L12-L24
[ "def", "compare_name_component", "(", "list1", ",", "list2", ",", "settings", ",", "use_ratio", "=", "False", ")", ":", "if", "not", "list1", "[", "0", "]", "or", "not", "list2", "[", "0", "]", ":", "not_required", "=", "not", "settings", "[", "'requir...
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
equate_initial
Evaluates whether names match, or one name is the initial of the other
whoswho/utils.py
def equate_initial(name1, name2): """ Evaluates whether names match, or one name is the initial of the other """ if len(name1) == 0 or len(name2) == 0: return False if len(name1) == 1 or len(name2) == 1: return name1[0] == name2[0] return name1 == name2
def equate_initial(name1, name2): """ Evaluates whether names match, or one name is the initial of the other """ if len(name1) == 0 or len(name2) == 0: return False if len(name1) == 1 or len(name2) == 1: return name1[0] == name2[0] return name1 == name2
[ "Evaluates", "whether", "names", "match", "or", "one", "name", "is", "the", "initial", "of", "the", "other" ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/utils.py#L61-L71
[ "def", "equate_initial", "(", "name1", ",", "name2", ")", ":", "if", "len", "(", "name1", ")", "==", "0", "or", "len", "(", "name2", ")", "==", "0", ":", "return", "False", "if", "len", "(", "name1", ")", "==", "1", "or", "len", "(", "name2", "...
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
equate_prefix
Evaluates whether names match, or one name prefixes another
whoswho/utils.py
def equate_prefix(name1, name2): """ Evaluates whether names match, or one name prefixes another """ if len(name1) == 0 or len(name2) == 0: return False return name1.startswith(name2) or name2.startswith(name1)
def equate_prefix(name1, name2): """ Evaluates whether names match, or one name prefixes another """ if len(name1) == 0 or len(name2) == 0: return False return name1.startswith(name2) or name2.startswith(name1)
[ "Evaluates", "whether", "names", "match", "or", "one", "name", "prefixes", "another" ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/utils.py#L74-L82
[ "def", "equate_prefix", "(", "name1", ",", "name2", ")", ":", "if", "len", "(", "name1", ")", "==", "0", "or", "len", "(", "name2", ")", "==", "0", ":", "return", "False", "return", "name1", ".", "startswith", "(", "name2", ")", "or", "name2", ".",...
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
equate_nickname
Evaluates whether names match based on common nickname patterns This is not currently used in any name comparison
whoswho/utils.py
def equate_nickname(name1, name2): """ Evaluates whether names match based on common nickname patterns This is not currently used in any name comparison """ # Convert '-ie' and '-y' to the root name nickname_regex = r'(.)\1(y|ie)$' root_regex = r'\1' name1 = re.sub(nickname_regex, root...
def equate_nickname(name1, name2): """ Evaluates whether names match based on common nickname patterns This is not currently used in any name comparison """ # Convert '-ie' and '-y' to the root name nickname_regex = r'(.)\1(y|ie)$' root_regex = r'\1' name1 = re.sub(nickname_regex, root...
[ "Evaluates", "whether", "names", "match", "based", "on", "common", "nickname", "patterns" ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/utils.py#L85-L101
[ "def", "equate_nickname", "(", "name1", ",", "name2", ")", ":", "# Convert '-ie' and '-y' to the root name", "nickname_regex", "=", "r'(.)\\1(y|ie)$'", "root_regex", "=", "r'\\1'", "name1", "=", "re", ".", "sub", "(", "nickname_regex", ",", "root_regex", ",", "name1...
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
make_ascii
Converts unicode-specific characters to their equivalent ascii
whoswho/utils.py
def make_ascii(word): """ Converts unicode-specific characters to their equivalent ascii """ if sys.version_info < (3, 0, 0): word = unicode(word) else: word = str(word) normalized = unicodedata.normalize('NFKD', word) return normalized.encode('ascii', 'ignore').decode('utf...
def make_ascii(word): """ Converts unicode-specific characters to their equivalent ascii """ if sys.version_info < (3, 0, 0): word = unicode(word) else: word = str(word) normalized = unicodedata.normalize('NFKD', word) return normalized.encode('ascii', 'ignore').decode('utf...
[ "Converts", "unicode", "-", "specific", "characters", "to", "their", "equivalent", "ascii" ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/utils.py#L104-L115
[ "def", "make_ascii", "(", "word", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ",", "0", ")", ":", "word", "=", "unicode", "(", "word", ")", "else", ":", "word", "=", "str", "(", "word", ")", "normalized", "=", "unicodedat...
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
seq_ratio
Returns sequence match ratio for two words
whoswho/utils.py
def seq_ratio(word1, word2): """ Returns sequence match ratio for two words """ raw_ratio = SequenceMatcher(None, word1, word2).ratio() return int(round(100 * raw_ratio))
def seq_ratio(word1, word2): """ Returns sequence match ratio for two words """ raw_ratio = SequenceMatcher(None, word1, word2).ratio() return int(round(100 * raw_ratio))
[ "Returns", "sequence", "match", "ratio", "for", "two", "words" ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/utils.py#L126-L131
[ "def", "seq_ratio", "(", "word1", ",", "word2", ")", ":", "raw_ratio", "=", "SequenceMatcher", "(", "None", ",", "word1", ",", "word2", ")", ".", "ratio", "(", ")", "return", "int", "(", "round", "(", "100", "*", "raw_ratio", ")", ")" ]
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
deep_update_dict
Updates the values in a nested dict, while unspecified values will remain unchanged
whoswho/utils.py
def deep_update_dict(default, options): """ Updates the values in a nested dict, while unspecified values will remain unchanged """ for key in options.keys(): default_setting = default.get(key) new_setting = options.get(key) if isinstance(default_setting, dict): d...
def deep_update_dict(default, options): """ Updates the values in a nested dict, while unspecified values will remain unchanged """ for key in options.keys(): default_setting = default.get(key) new_setting = options.get(key) if isinstance(default_setting, dict): d...
[ "Updates", "the", "values", "in", "a", "nested", "dict", "while", "unspecified", "values", "will", "remain", "unchanged" ]
rliebz/whoswho
python
https://github.com/rliebz/whoswho/blob/0c411e418c240fcec6ea0a23d15bd003056c65d0/whoswho/utils.py#L134-L145
[ "def", "deep_update_dict", "(", "default", ",", "options", ")", ":", "for", "key", "in", "options", ".", "keys", "(", ")", ":", "default_setting", "=", "default", ".", "get", "(", "key", ")", "new_setting", "=", "options", ".", "get", "(", "key", ")", ...
0c411e418c240fcec6ea0a23d15bd003056c65d0
train
template_to_base_path
Get base output path for a list of songs for download.
gmusicapi_scripts/gmsync.py
def template_to_base_path(template, google_songs): """Get base output path for a list of songs for download.""" if template == os.getcwd() or template == '%suggested%': base_path = os.getcwd() else: template = os.path.abspath(template) song_paths = [template_to_filepath(template, song) for song in google_song...
def template_to_base_path(template, google_songs): """Get base output path for a list of songs for download.""" if template == os.getcwd() or template == '%suggested%': base_path = os.getcwd() else: template = os.path.abspath(template) song_paths = [template_to_filepath(template, song) for song in google_song...
[ "Get", "base", "output", "path", "for", "a", "list", "of", "songs", "for", "download", "." ]
thebigmunch/gmusicapi-scripts
python
https://github.com/thebigmunch/gmusicapi-scripts/blob/5492593db20efb0ea5ad5dcf1b2e1a0e4d0349e8/gmusicapi_scripts/gmsync.py#L74-L84
[ "def", "template_to_base_path", "(", "template", ",", "google_songs", ")", ":", "if", "template", "==", "os", ".", "getcwd", "(", ")", "or", "template", "==", "'%suggested%'", ":", "base_path", "=", "os", ".", "getcwd", "(", ")", "else", ":", "template", ...
5492593db20efb0ea5ad5dcf1b2e1a0e4d0349e8
train
BitString.random
Create a bit string of the given length, with the probability of each bit being set equal to bit_prob, which defaults to .5. Usage: # Create a random BitString of length 10 with mostly zeros. bits = BitString.random(10, bit_prob=.1) Arguments: length: An int...
xcs/_python_bitstrings.py
def random(cls, length, bit_prob=.5): """Create a bit string of the given length, with the probability of each bit being set equal to bit_prob, which defaults to .5. Usage: # Create a random BitString of length 10 with mostly zeros. bits = BitString.random(10, bit_prob=....
def random(cls, length, bit_prob=.5): """Create a bit string of the given length, with the probability of each bit being set equal to bit_prob, which defaults to .5. Usage: # Create a random BitString of length 10 with mostly zeros. bits = BitString.random(10, bit_prob=....
[ "Create", "a", "bit", "string", "of", "the", "given", "length", "with", "the", "probability", "of", "each", "bit", "being", "set", "equal", "to", "bit_prob", "which", "defaults", "to", ".", "5", "." ]
hosford42/xcs
python
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/_python_bitstrings.py#L151-L178
[ "def", "random", "(", "cls", ",", "length", ",", "bit_prob", "=", ".5", ")", ":", "assert", "isinstance", "(", "length", ",", "int", ")", "and", "length", ">=", "0", "assert", "isinstance", "(", "bit_prob", ",", "(", "int", ",", "float", ")", ")", ...
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5
train
BitString.crossover_template
Create a crossover template with the given number of points. The crossover template can be used as a mask to crossover two bitstrings of the same length. Usage: assert len(parent1) == len(parent2) template = BitString.crossover_template(len(parent1)) inv_temp...
xcs/_python_bitstrings.py
def crossover_template(cls, length, points=2): """Create a crossover template with the given number of points. The crossover template can be used as a mask to crossover two bitstrings of the same length. Usage: assert len(parent1) == len(parent2) template = BitSt...
def crossover_template(cls, length, points=2): """Create a crossover template with the given number of points. The crossover template can be used as a mask to crossover two bitstrings of the same length. Usage: assert len(parent1) == len(parent2) template = BitSt...
[ "Create", "a", "crossover", "template", "with", "the", "given", "number", "of", "points", ".", "The", "crossover", "template", "can", "be", "used", "as", "a", "mask", "to", "crossover", "two", "bitstrings", "of", "the", "same", "length", "." ]
hosford42/xcs
python
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/_python_bitstrings.py#L181-L224
[ "def", "crossover_template", "(", "cls", ",", "length", ",", "points", "=", "2", ")", ":", "assert", "isinstance", "(", "length", ",", "int", ")", "and", "length", ">=", "0", "assert", "isinstance", "(", "points", ",", "int", ")", "and", "points", ">="...
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5
train
BitString.count
Returns the number of bits set to True in the bit string. Usage: assert BitString('00110').count() == 2 Arguments: None Return: An int, the number of bits with value 1.
xcs/_python_bitstrings.py
def count(self): """Returns the number of bits set to True in the bit string. Usage: assert BitString('00110').count() == 2 Arguments: None Return: An int, the number of bits with value 1. """ result = 0 bits = self._bits while bi...
def count(self): """Returns the number of bits set to True in the bit string. Usage: assert BitString('00110').count() == 2 Arguments: None Return: An int, the number of bits with value 1. """ result = 0 bits = self._bits while bi...
[ "Returns", "the", "number", "of", "bits", "set", "to", "True", "in", "the", "bit", "string", "." ]
hosford42/xcs
python
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/_python_bitstrings.py#L283-L298
[ "def", "count", "(", "self", ")", ":", "result", "=", "0", "bits", "=", "self", ".", "_bits", "while", "bits", ":", "result", "+=", "bits", "%", "2", "bits", ">>=", "1", "return", "result" ]
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5
train
Connection.drain_events
Wait for an event on any channel.
carrot/backends/pyamqplib.py
def drain_events(self, allowed_methods=None, timeout=None): """Wait for an event on any channel.""" return self.wait_multi(self.channels.values(), timeout=timeout)
def drain_events(self, allowed_methods=None, timeout=None): """Wait for an event on any channel.""" return self.wait_multi(self.channels.values(), timeout=timeout)
[ "Wait", "for", "an", "event", "on", "any", "channel", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pyamqplib.py#L30-L32
[ "def", "drain_events", "(", "self", ",", "allowed_methods", "=", "None", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "wait_multi", "(", "self", ".", "channels", ".", "values", "(", ")", ",", "timeout", "=", "timeout", ")" ]
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Connection.wait_multi
Wait for an event on a channel.
carrot/backends/pyamqplib.py
def wait_multi(self, channels, allowed_methods=None, timeout=None): """Wait for an event on a channel.""" chanmap = dict((chan.channel_id, chan) for chan in channels) chanid, method_sig, args, content = self._wait_multiple( chanmap.keys(), allowed_methods, timeout=timeout) ...
def wait_multi(self, channels, allowed_methods=None, timeout=None): """Wait for an event on a channel.""" chanmap = dict((chan.channel_id, chan) for chan in channels) chanid, method_sig, args, content = self._wait_multiple( chanmap.keys(), allowed_methods, timeout=timeout) ...
[ "Wait", "for", "an", "event", "on", "a", "channel", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pyamqplib.py#L34-L58
[ "def", "wait_multi", "(", "self", ",", "channels", ",", "allowed_methods", "=", "None", ",", "timeout", "=", "None", ")", ":", "chanmap", "=", "dict", "(", "(", "chan", ".", "channel_id", ",", "chan", ")", "for", "chan", "in", "channels", ")", "chanid"...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.establish_connection
Establish connection to the AMQP broker.
carrot/backends/pyamqplib.py
def establish_connection(self): """Establish connection to the AMQP broker.""" conninfo = self.connection if not conninfo.hostname: raise KeyError("Missing hostname for AMQP connection.") if conninfo.userid is None: raise KeyError("Missing user id for AMQP connect...
def establish_connection(self): """Establish connection to the AMQP broker.""" conninfo = self.connection if not conninfo.hostname: raise KeyError("Missing hostname for AMQP connection.") if conninfo.userid is None: raise KeyError("Missing user id for AMQP connect...
[ "Establish", "connection", "to", "the", "AMQP", "broker", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pyamqplib.py#L198-L215
[ "def", "establish_connection", "(", "self", ")", ":", "conninfo", "=", "self", ".", "connection", "if", "not", "conninfo", ".", "hostname", ":", "raise", "KeyError", "(", "\"Missing hostname for AMQP connection.\"", ")", "if", "conninfo", ".", "userid", "is", "N...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.queue_exists
Check if a queue has been declared. :rtype bool:
carrot/backends/pyamqplib.py
def queue_exists(self, queue): """Check if a queue has been declared. :rtype bool: """ try: self.channel.queue_declare(queue=queue, passive=True) except AMQPChannelException, e: if e.amqp_reply_code == 404: return False raise ...
def queue_exists(self, queue): """Check if a queue has been declared. :rtype bool: """ try: self.channel.queue_declare(queue=queue, passive=True) except AMQPChannelException, e: if e.amqp_reply_code == 404: return False raise ...
[ "Check", "if", "a", "queue", "has", "been", "declared", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pyamqplib.py#L221-L234
[ "def", "queue_exists", "(", "self", ",", "queue", ")", ":", "try", ":", "self", ".", "channel", ".", "queue_declare", "(", "queue", "=", "queue", ",", "passive", "=", "True", ")", "except", "AMQPChannelException", ",", "e", ":", "if", "e", ".", "amqp_r...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.queue_delete
Delete queue by name.
carrot/backends/pyamqplib.py
def queue_delete(self, queue, if_unused=False, if_empty=False): """Delete queue by name.""" return self.channel.queue_delete(queue, if_unused, if_empty)
def queue_delete(self, queue, if_unused=False, if_empty=False): """Delete queue by name.""" return self.channel.queue_delete(queue, if_unused, if_empty)
[ "Delete", "queue", "by", "name", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pyamqplib.py#L236-L238
[ "def", "queue_delete", "(", "self", ",", "queue", ",", "if_unused", "=", "False", ",", "if_empty", "=", "False", ")", ":", "return", "self", ".", "channel", ".", "queue_delete", "(", "queue", ",", "if_unused", ",", "if_empty", ")" ]
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.queue_declare
Declare a named queue.
carrot/backends/pyamqplib.py
def queue_declare(self, queue, durable, exclusive, auto_delete, warn_if_exists=False, arguments=None): """Declare a named queue.""" if warn_if_exists and self.queue_exists(queue): warnings.warn(QueueAlreadyExistsWarning( QueueAlreadyExistsWarning.__doc__)) ...
def queue_declare(self, queue, durable, exclusive, auto_delete, warn_if_exists=False, arguments=None): """Declare a named queue.""" if warn_if_exists and self.queue_exists(queue): warnings.warn(QueueAlreadyExistsWarning( QueueAlreadyExistsWarning.__doc__)) ...
[ "Declare", "a", "named", "queue", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pyamqplib.py#L245-L256
[ "def", "queue_declare", "(", "self", ",", "queue", ",", "durable", ",", "exclusive", ",", "auto_delete", ",", "warn_if_exists", "=", "False", ",", "arguments", "=", "None", ")", ":", "if", "warn_if_exists", "and", "self", ".", "queue_exists", "(", "queue", ...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.exchange_declare
Declare an named exchange.
carrot/backends/pyamqplib.py
def exchange_declare(self, exchange, type, durable, auto_delete): """Declare an named exchange.""" return self.channel.exchange_declare(exchange=exchange, type=type, durable=durable, ...
def exchange_declare(self, exchange, type, durable, auto_delete): """Declare an named exchange.""" return self.channel.exchange_declare(exchange=exchange, type=type, durable=durable, ...
[ "Declare", "an", "named", "exchange", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pyamqplib.py#L258-L263
[ "def", "exchange_declare", "(", "self", ",", "exchange", ",", "type", ",", "durable", ",", "auto_delete", ")", ":", "return", "self", ".", "channel", ".", "exchange_declare", "(", "exchange", "=", "exchange", ",", "type", "=", "type", ",", "durable", "=", ...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.queue_bind
Bind queue to an exchange using a routing key.
carrot/backends/pyamqplib.py
def queue_bind(self, queue, exchange, routing_key, arguments=None): """Bind queue to an exchange using a routing key.""" return self.channel.queue_bind(queue=queue, exchange=exchange, routing_key=routing_key, ...
def queue_bind(self, queue, exchange, routing_key, arguments=None): """Bind queue to an exchange using a routing key.""" return self.channel.queue_bind(queue=queue, exchange=exchange, routing_key=routing_key, ...
[ "Bind", "queue", "to", "an", "exchange", "using", "a", "routing", "key", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pyamqplib.py#L265-L270
[ "def", "queue_bind", "(", "self", ",", "queue", ",", "exchange", ",", "routing_key", ",", "arguments", "=", "None", ")", ":", "return", "self", ".", "channel", ".", "queue_bind", "(", "queue", "=", "queue", ",", "exchange", "=", "exchange", ",", "routing...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.get
Receive a message from a declared queue by name. :returns: A :class:`Message` object if a message was received, ``None`` otherwise. If ``None`` was returned, it probably means there was no messages waiting on the queue.
carrot/backends/pyamqplib.py
def get(self, queue, no_ack=False): """Receive a message from a declared queue by name. :returns: A :class:`Message` object if a message was received, ``None`` otherwise. If ``None`` was returned, it probably means there was no messages waiting on the queue. """ ...
def get(self, queue, no_ack=False): """Receive a message from a declared queue by name. :returns: A :class:`Message` object if a message was received, ``None`` otherwise. If ``None`` was returned, it probably means there was no messages waiting on the queue. """ ...
[ "Receive", "a", "message", "from", "a", "declared", "queue", "by", "name", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pyamqplib.py#L276-L287
[ "def", "get", "(", "self", ",", "queue", ",", "no_ack", "=", "False", ")", ":", "raw_message", "=", "self", ".", "channel", ".", "basic_get", "(", "queue", ",", "no_ack", "=", "no_ack", ")", "if", "not", "raw_message", ":", "return", "None", "return", ...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.consume
Returns an iterator that waits for one message at a time.
carrot/backends/pyamqplib.py
def consume(self, limit=None): """Returns an iterator that waits for one message at a time.""" for total_message_count in count(): if limit and total_message_count >= limit: raise StopIteration if not self.channel.is_open: raise StopIteration ...
def consume(self, limit=None): """Returns an iterator that waits for one message at a time.""" for total_message_count in count(): if limit and total_message_count >= limit: raise StopIteration if not self.channel.is_open: raise StopIteration ...
[ "Returns", "an", "iterator", "that", "waits", "for", "one", "message", "at", "a", "time", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pyamqplib.py#L298-L308
[ "def", "consume", "(", "self", ",", "limit", "=", "None", ")", ":", "for", "total_message_count", "in", "count", "(", ")", ":", "if", "limit", "and", "total_message_count", ">=", "limit", ":", "raise", "StopIteration", "if", "not", "self", ".", "channel", ...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.cancel
Cancel a channel by consumer tag.
carrot/backends/pyamqplib.py
def cancel(self, consumer_tag): """Cancel a channel by consumer tag.""" if not self.channel.connection: return self.channel.basic_cancel(consumer_tag)
def cancel(self, consumer_tag): """Cancel a channel by consumer tag.""" if not self.channel.connection: return self.channel.basic_cancel(consumer_tag)
[ "Cancel", "a", "channel", "by", "consumer", "tag", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pyamqplib.py#L310-L314
[ "def", "cancel", "(", "self", ",", "consumer_tag", ")", ":", "if", "not", "self", ".", "channel", ".", "connection", ":", "return", "self", ".", "channel", ".", "basic_cancel", "(", "consumer_tag", ")" ]
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.close
Close the channel if open.
carrot/backends/pyamqplib.py
def close(self): """Close the channel if open.""" if self._channel and self._channel.is_open: self._channel.close() self._channel_ref = None
def close(self): """Close the channel if open.""" if self._channel and self._channel.is_open: self._channel.close() self._channel_ref = None
[ "Close", "the", "channel", "if", "open", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pyamqplib.py#L316-L320
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_channel", "and", "self", ".", "_channel", ".", "is_open", ":", "self", ".", "_channel", ".", "close", "(", ")", "self", ".", "_channel_ref", "=", "None" ]
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.qos
Request specific Quality of Service.
carrot/backends/pyamqplib.py
def qos(self, prefetch_size, prefetch_count, apply_global=False): """Request specific Quality of Service.""" self.channel.basic_qos(prefetch_size, prefetch_count, apply_global)
def qos(self, prefetch_size, prefetch_count, apply_global=False): """Request specific Quality of Service.""" self.channel.basic_qos(prefetch_size, prefetch_count, apply_global)
[ "Request", "specific", "Quality", "of", "Service", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pyamqplib.py#L357-L360
[ "def", "qos", "(", "self", ",", "prefetch_size", ",", "prefetch_count", ",", "apply_global", "=", "False", ")", ":", "self", ".", "channel", ".", "basic_qos", "(", "prefetch_size", ",", "prefetch_count", ",", "apply_global", ")" ]
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.channel
If no channel exists, a new one is requested.
carrot/backends/librabbitmq.py
def channel(self): """If no channel exists, a new one is requested.""" if not self._channel: self._channel_ref = weakref.ref(self.connection.get_channel()) return self._channel
def channel(self): """If no channel exists, a new one is requested.""" if not self._channel: self._channel_ref = weakref.ref(self.connection.get_channel()) return self._channel
[ "If", "no", "channel", "exists", "a", "new", "one", "is", "requested", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/librabbitmq.py#L88-L92
[ "def", "channel", "(", "self", ")", ":", "if", "not", "self", ".", "_channel", ":", "self", ".", "_channel_ref", "=", "weakref", ".", "ref", "(", "self", ".", "connection", ".", "get_channel", "(", ")", ")", "return", "self", ".", "_channel" ]
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.establish_connection
Establish connection to the AMQP broker.
carrot/backends/librabbitmq.py
def establish_connection(self): """Establish connection to the AMQP broker.""" conninfo = self.connection if not conninfo.hostname: raise KeyError("Missing hostname for AMQP connection.") if conninfo.userid is None: raise KeyError("Missing user id for AMQP connect...
def establish_connection(self): """Establish connection to the AMQP broker.""" conninfo = self.connection if not conninfo.hostname: raise KeyError("Missing hostname for AMQP connection.") if conninfo.userid is None: raise KeyError("Missing user id for AMQP connect...
[ "Establish", "connection", "to", "the", "AMQP", "broker", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/librabbitmq.py#L94-L110
[ "def", "establish_connection", "(", "self", ")", ":", "conninfo", "=", "self", ".", "connection", "if", "not", "conninfo", ".", "hostname", ":", "raise", "KeyError", "(", "\"Missing hostname for AMQP connection.\"", ")", "if", "conninfo", ".", "userid", "is", "N...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.declare_consumer
Declare a consumer.
carrot/backends/librabbitmq.py
def declare_consumer(self, queue, no_ack, callback, consumer_tag, nowait=False): """Declare a consumer.""" return self.channel.basic_consume(queue=queue, no_ack=no_ack, callback=callback, ...
def declare_consumer(self, queue, no_ack, callback, consumer_tag, nowait=False): """Declare a consumer.""" return self.channel.basic_consume(queue=queue, no_ack=no_ack, callback=callback, ...
[ "Declare", "a", "consumer", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/librabbitmq.py#L167-L173
[ "def", "declare_consumer", "(", "self", ",", "queue", ",", "no_ack", ",", "callback", ",", "consumer_tag", ",", "nowait", "=", "False", ")", ":", "return", "self", ".", "channel", ".", "basic_consume", "(", "queue", "=", "queue", ",", "no_ack", "=", "no_...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.consume
Returns an iterator that waits for one message at a time.
carrot/backends/librabbitmq.py
def consume(self, limit=None): """Returns an iterator that waits for one message at a time.""" for total_message_count in count(): if limit and total_message_count >= limit: raise StopIteration if not self.channel.is_open: raise StopIteration ...
def consume(self, limit=None): """Returns an iterator that waits for one message at a time.""" for total_message_count in count(): if limit and total_message_count >= limit: raise StopIteration if not self.channel.is_open: raise StopIteration ...
[ "Returns", "an", "iterator", "that", "waits", "for", "one", "message", "at", "a", "time", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/librabbitmq.py#L175-L185
[ "def", "consume", "(", "self", ",", "limit", "=", "None", ")", ":", "for", "total_message_count", "in", "count", "(", ")", ":", "if", "limit", "and", "total_message_count", ">=", "limit", ":", "raise", "StopIteration", "if", "not", "self", ".", "channel", ...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.cancel
Cancel a channel by consumer tag.
carrot/backends/librabbitmq.py
def cancel(self, consumer_tag): """Cancel a channel by consumer tag.""" if not self.channel.conn: return self.channel.basic_cancel(consumer_tag)
def cancel(self, consumer_tag): """Cancel a channel by consumer tag.""" if not self.channel.conn: return self.channel.basic_cancel(consumer_tag)
[ "Cancel", "a", "channel", "by", "consumer", "tag", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/librabbitmq.py#L187-L191
[ "def", "cancel", "(", "self", ",", "consumer_tag", ")", ":", "if", "not", "self", ".", "channel", ".", "conn", ":", "return", "self", ".", "channel", ".", "basic_cancel", "(", "consumer_tag", ")" ]
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.prepare_message
Encapsulate data into a AMQP message.
carrot/backends/librabbitmq.py
def prepare_message(self, message_data, delivery_mode, priority=None, content_type=None, content_encoding=None): """Encapsulate data into a AMQP message.""" return amqp.Message(message_data, properties={ "delivery_mode": delivery_mode, "priority": priority...
def prepare_message(self, message_data, delivery_mode, priority=None, content_type=None, content_encoding=None): """Encapsulate data into a AMQP message.""" return amqp.Message(message_data, properties={ "delivery_mode": delivery_mode, "priority": priority...
[ "Encapsulate", "data", "into", "a", "AMQP", "message", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/librabbitmq.py#L211-L218
[ "def", "prepare_message", "(", "self", ",", "message_data", ",", "delivery_mode", ",", "priority", "=", "None", ",", "content_type", "=", "None", ",", "content_encoding", "=", "None", ")", ":", "return", "amqp", ".", "Message", "(", "message_data", ",", "pro...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
raw_encode
Special case serializer.
carrot/serialization.py
def raw_encode(data): """Special case serializer.""" content_type = 'application/data' payload = data if isinstance(payload, unicode): content_encoding = 'utf-8' payload = payload.encode(content_encoding) else: content_encoding = 'binary' return content_type, content_enco...
def raw_encode(data): """Special case serializer.""" content_type = 'application/data' payload = data if isinstance(payload, unicode): content_encoding = 'utf-8' payload = payload.encode(content_encoding) else: content_encoding = 'binary' return content_type, content_enco...
[ "Special", "case", "serializer", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/serialization.py#L202-L211
[ "def", "raw_encode", "(", "data", ")", ":", "content_type", "=", "'application/data'", "payload", "=", "data", "if", "isinstance", "(", "payload", ",", "unicode", ")", ":", "content_encoding", "=", "'utf-8'", "payload", "=", "payload", ".", "encode", "(", "c...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
register_json
Register a encoder/decoder for JSON serialization.
carrot/serialization.py
def register_json(): """Register a encoder/decoder for JSON serialization.""" from anyjson import serialize as json_serialize from anyjson import deserialize as json_deserialize registry.register('json', json_serialize, json_deserialize, content_type='application/json', ...
def register_json(): """Register a encoder/decoder for JSON serialization.""" from anyjson import serialize as json_serialize from anyjson import deserialize as json_deserialize registry.register('json', json_serialize, json_deserialize, content_type='application/json', ...
[ "Register", "a", "encoder", "/", "decoder", "for", "JSON", "serialization", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/serialization.py#L214-L221
[ "def", "register_json", "(", ")", ":", "from", "anyjson", "import", "serialize", "as", "json_serialize", "from", "anyjson", "import", "deserialize", "as", "json_deserialize", "registry", ".", "register", "(", "'json'", ",", "json_serialize", ",", "json_deserialize",...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
register_yaml
Register a encoder/decoder for YAML serialization. It is slower than JSON, but allows for more data types to be serialized. Useful if you need to send data such as dates
carrot/serialization.py
def register_yaml(): """Register a encoder/decoder for YAML serialization. It is slower than JSON, but allows for more data types to be serialized. Useful if you need to send data such as dates""" try: import yaml registry.register('yaml', yaml.safe_dump, yaml.safe_load, ...
def register_yaml(): """Register a encoder/decoder for YAML serialization. It is slower than JSON, but allows for more data types to be serialized. Useful if you need to send data such as dates""" try: import yaml registry.register('yaml', yaml.safe_dump, yaml.safe_load, ...
[ "Register", "a", "encoder", "/", "decoder", "for", "YAML", "serialization", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/serialization.py#L224-L241
[ "def", "register_yaml", "(", ")", ":", "try", ":", "import", "yaml", "registry", ".", "register", "(", "'yaml'", ",", "yaml", ".", "safe_dump", ",", "yaml", ".", "safe_load", ",", "content_type", "=", "'application/x-yaml'", ",", "content_encoding", "=", "'u...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
register_pickle
The fastest serialization method, but restricts you to python clients.
carrot/serialization.py
def register_pickle(): """The fastest serialization method, but restricts you to python clients.""" import cPickle registry.register('pickle', cPickle.dumps, cPickle.loads, content_type='application/x-python-serialize', content_encoding='binary')
def register_pickle(): """The fastest serialization method, but restricts you to python clients.""" import cPickle registry.register('pickle', cPickle.dumps, cPickle.loads, content_type='application/x-python-serialize', content_encoding='binary')
[ "The", "fastest", "serialization", "method", "but", "restricts", "you", "to", "python", "clients", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/serialization.py#L244-L250
[ "def", "register_pickle", "(", ")", ":", "import", "cPickle", "registry", ".", "register", "(", "'pickle'", ",", "cPickle", ".", "dumps", ",", "cPickle", ".", "loads", ",", "content_type", "=", "'application/x-python-serialize'", ",", "content_encoding", "=", "'...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
register_msgpack
See http://msgpack.sourceforge.net/
carrot/serialization.py
def register_msgpack(): """See http://msgpack.sourceforge.net/""" try: import msgpack registry.register('msgpack', msgpack.packs, msgpack.unpacks, content_type='application/x-msgpack', content_encoding='binary') except ImportError: def not_available(*...
def register_msgpack(): """See http://msgpack.sourceforge.net/""" try: import msgpack registry.register('msgpack', msgpack.packs, msgpack.unpacks, content_type='application/x-msgpack', content_encoding='binary') except ImportError: def not_available(*...
[ "See", "http", ":", "//", "msgpack", ".", "sourceforge", ".", "net", "/" ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/serialization.py#L253-L269
[ "def", "register_msgpack", "(", ")", ":", "try", ":", "import", "msgpack", "registry", ".", "register", "(", "'msgpack'", ",", "msgpack", ".", "packs", ",", "msgpack", ".", "unpacks", ",", "content_type", "=", "'application/x-msgpack'", ",", "content_encoding", ...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
SerializerRegistry.register
Register a new encoder/decoder. :param name: A convenience name for the serialization method. :param encoder: A method that will be passed a python data structure and should return a string representing the serialized data. If ``None``, then only a decoder will be registered. E...
carrot/serialization.py
def register(self, name, encoder, decoder, content_type, content_encoding='utf-8'): """Register a new encoder/decoder. :param name: A convenience name for the serialization method. :param encoder: A method that will be passed a python data structure and should retu...
def register(self, name, encoder, decoder, content_type, content_encoding='utf-8'): """Register a new encoder/decoder. :param name: A convenience name for the serialization method. :param encoder: A method that will be passed a python data structure and should retu...
[ "Register", "a", "new", "encoder", "/", "decoder", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/serialization.py#L41-L68
[ "def", "register", "(", "self", ",", "name", ",", "encoder", ",", "decoder", ",", "content_type", ",", "content_encoding", "=", "'utf-8'", ")", ":", "if", "encoder", ":", "self", ".", "_encoders", "[", "name", "]", "=", "(", "content_type", ",", "content...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
SerializerRegistry._set_default_serializer
Set the default serialization method used by this library. :param name: The name of the registered serialization method. For example, ``json`` (default), ``pickle``, ``yaml``, or any custom methods registered using :meth:`register`. :raises SerializerNotInstalled: If the serial...
carrot/serialization.py
def _set_default_serializer(self, name): """ Set the default serialization method used by this library. :param name: The name of the registered serialization method. For example, ``json`` (default), ``pickle``, ``yaml``, or any custom methods registered using :meth:`regi...
def _set_default_serializer(self, name): """ Set the default serialization method used by this library. :param name: The name of the registered serialization method. For example, ``json`` (default), ``pickle``, ``yaml``, or any custom methods registered using :meth:`regi...
[ "Set", "the", "default", "serialization", "method", "used", "by", "this", "library", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/serialization.py#L70-L86
[ "def", "_set_default_serializer", "(", "self", ",", "name", ")", ":", "try", ":", "(", "self", ".", "_default_content_type", ",", "self", ".", "_default_content_encoding", ",", "self", ".", "_default_encode", ")", "=", "self", ".", "_encoders", "[", "name", ...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
SerializerRegistry.encode
Serialize a data structure into a string suitable for sending as an AMQP message body. :param data: The message data to send. Can be a list, dictionary or a string. :keyword serializer: An optional string representing the serialization method you want the data marshalle...
carrot/serialization.py
def encode(self, data, serializer=None): """ Serialize a data structure into a string suitable for sending as an AMQP message body. :param data: The message data to send. Can be a list, dictionary or a string. :keyword serializer: An optional string representing ...
def encode(self, data, serializer=None): """ Serialize a data structure into a string suitable for sending as an AMQP message body. :param data: The message data to send. Can be a list, dictionary or a string. :keyword serializer: An optional string representing ...
[ "Serialize", "a", "data", "structure", "into", "a", "string", "suitable", "for", "sending", "as", "an", "AMQP", "message", "body", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/serialization.py#L88-L145
[ "def", "encode", "(", "self", ",", "data", ",", "serializer", "=", "None", ")", ":", "if", "serializer", "==", "\"raw\"", ":", "return", "raw_encode", "(", "data", ")", "if", "serializer", "and", "not", "self", ".", "_encoders", ".", "get", "(", "seria...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
SerializerRegistry.decode
Deserialize a data stream as serialized using ``encode`` based on :param:`content_type`. :param data: The message data to deserialize. :param content_type: The content-type of the data. (e.g., ``application/json``). :param content_encoding: The content-encoding of the data...
carrot/serialization.py
def decode(self, data, content_type, content_encoding): """Deserialize a data stream as serialized using ``encode`` based on :param:`content_type`. :param data: The message data to deserialize. :param content_type: The content-type of the data. (e.g., ``application/json``)....
def decode(self, data, content_type, content_encoding): """Deserialize a data stream as serialized using ``encode`` based on :param:`content_type`. :param data: The message data to deserialize. :param content_type: The content-type of the data. (e.g., ``application/json``)....
[ "Deserialize", "a", "data", "stream", "as", "serialized", "using", "encode", "based", "on", ":", "param", ":", "content_type", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/serialization.py#L147-L174
[ "def", "decode", "(", "self", ",", "data", ",", "content_type", ",", "content_encoding", ")", ":", "content_type", "=", "content_type", "or", "'application/data'", "content_encoding", "=", "(", "content_encoding", "or", "'utf-8'", ")", ".", "lower", "(", ")", ...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Message.ack
Acknowledge this message as being processed., This will remove the message from the queue. :raises MessageStateError: If the message has already been acknowledged/requeued/rejected.
carrot/backends/pystomp.py
def ack(self): """Acknowledge this message as being processed., This will remove the message from the queue. :raises MessageStateError: If the message has already been acknowledged/requeued/rejected. """ if self.acknowledged: raise self.MessageStateError...
def ack(self): """Acknowledge this message as being processed., This will remove the message from the queue. :raises MessageStateError: If the message has already been acknowledged/requeued/rejected. """ if self.acknowledged: raise self.MessageStateError...
[ "Acknowledge", "this", "message", "as", "being", "processed", ".", "This", "will", "remove", "the", "message", "from", "the", "queue", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pystomp.py#L54-L66
[ "def", "ack", "(", "self", ")", ":", "if", "self", ".", "acknowledged", ":", "raise", "self", ".", "MessageStateError", "(", "\"Message already acknowledged with state: %s\"", "%", "self", ".", "_state", ")", "self", ".", "backend", ".", "ack", "(", "self", ...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
Backend.consume
Returns an iterator that waits for one message at a time.
carrot/backends/pystomp.py
def consume(self, limit=None): """Returns an iterator that waits for one message at a time.""" for total_message_count in count(): if limit and total_message_count >= limit: raise StopIteration self.drain_events() yield True
def consume(self, limit=None): """Returns an iterator that waits for one message at a time.""" for total_message_count in count(): if limit and total_message_count >= limit: raise StopIteration self.drain_events() yield True
[ "Returns", "an", "iterator", "that", "waits", "for", "one", "message", "at", "a", "time", "." ]
ask/carrot
python
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/pystomp.py#L136-L142
[ "def", "consume", "(", "self", ",", "limit", "=", "None", ")", ":", "for", "total_message_count", "in", "count", "(", ")", ":", "if", "limit", "and", "total_message_count", ">=", "limit", ":", "raise", "StopIteration", "self", ".", "drain_events", "(", ")"...
5889a25cd2e274642071c9bba39772f4b3e3d9da
train
BitString.random
Create a bit string of the given length, with the probability of each bit being set equal to bit_prob, which defaults to .5. Usage: # Create a random BitString of length 10 with mostly zeros. bits = BitString.random(10, bit_prob=.1) Arguments: length: An int...
xcs/_numpy_bitstrings.py
def random(cls, length, bit_prob=.5): """Create a bit string of the given length, with the probability of each bit being set equal to bit_prob, which defaults to .5. Usage: # Create a random BitString of length 10 with mostly zeros. bits = BitString.random(10, bit_prob=....
def random(cls, length, bit_prob=.5): """Create a bit string of the given length, with the probability of each bit being set equal to bit_prob, which defaults to .5. Usage: # Create a random BitString of length 10 with mostly zeros. bits = BitString.random(10, bit_prob=....
[ "Create", "a", "bit", "string", "of", "the", "given", "length", "with", "the", "probability", "of", "each", "bit", "being", "set", "equal", "to", "bit_prob", "which", "defaults", "to", ".", "5", "." ]
hosford42/xcs
python
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/_numpy_bitstrings.py#L162-L191
[ "def", "random", "(", "cls", ",", "length", ",", "bit_prob", "=", ".5", ")", ":", "assert", "isinstance", "(", "length", ",", "int", ")", "and", "length", ">=", "0", "assert", "isinstance", "(", "bit_prob", ",", "(", "int", ",", "float", ")", ")", ...
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5
train
BitString.crossover_template
Create a crossover template with the given number of points. The crossover template can be used as a mask to crossover two bitstrings of the same length. Usage: assert len(parent1) == len(parent2) template = BitString.crossover_template(len(parent1)) inv_temp...
xcs/_numpy_bitstrings.py
def crossover_template(cls, length, points=2): """Create a crossover template with the given number of points. The crossover template can be used as a mask to crossover two bitstrings of the same length. Usage: assert len(parent1) == len(parent2) template = BitSt...
def crossover_template(cls, length, points=2): """Create a crossover template with the given number of points. The crossover template can be used as a mask to crossover two bitstrings of the same length. Usage: assert len(parent1) == len(parent2) template = BitSt...
[ "Create", "a", "crossover", "template", "with", "the", "given", "number", "of", "points", ".", "The", "crossover", "template", "can", "be", "used", "as", "a", "mask", "to", "crossover", "two", "bitstrings", "of", "the", "same", "length", "." ]
hosford42/xcs
python
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/_numpy_bitstrings.py#L194-L238
[ "def", "crossover_template", "(", "cls", ",", "length", ",", "points", "=", "2", ")", ":", "assert", "isinstance", "(", "length", ",", "int", ")", "and", "length", ">=", "0", "assert", "isinstance", "(", "points", ",", "int", ")", "and", "points", ">="...
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5