repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
meejah/txtorcon
txtorcon/stream.py
Stream._notify
def _notify(self, func, *args, **kw): """ Internal helper. Calls the IStreamListener function 'func' with the given args, guarding around errors. """ for x in self.listeners: try: getattr(x, func)(*args, **kw) except Exception: log.err()
python
def _notify(self, func, *args, **kw): """ Internal helper. Calls the IStreamListener function 'func' with the given args, guarding around errors. """ for x in self.listeners: try: getattr(x, func)(*args, **kw) except Exception: log.err()
[ "def", "_notify", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "for", "x", "in", "self", ".", "listeners", ":", "try", ":", "getattr", "(", "x", ",", "func", ")", "(", "*", "args", ",", "*", "*", "kw", ")", "ex...
Internal helper. Calls the IStreamListener function 'func' with the given args, guarding around errors.
[ "Internal", "helper", ".", "Calls", "the", "IStreamListener", "function", "func", "with", "the", "given", "args", "guarding", "around", "errors", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/stream.py#L284-L293
train
209,000
meejah/txtorcon
txtorcon/circuit.py
build_timeout_circuit
def build_timeout_circuit(tor_state, reactor, path, timeout, using_guards=False): """ Build a new circuit within a timeout. CircuitBuildTimedOutError will be raised unless we receive a circuit build result (success or failure) within the `timeout` duration. :returns: a Deferred which fires when the circuit build succeeds (or fails to build). """ timed_circuit = [] d = tor_state.build_circuit(routers=path, using_guards=using_guards) def get_circuit(c): timed_circuit.append(c) return c def trap_cancel(f): f.trap(defer.CancelledError) if timed_circuit: d2 = timed_circuit[0].close() else: d2 = defer.succeed(None) d2.addCallback(lambda _: Failure(CircuitBuildTimedOutError("circuit build timed out"))) return d2 d.addCallback(get_circuit) d.addCallback(lambda circ: circ.when_built()) d.addErrback(trap_cancel) reactor.callLater(timeout, d.cancel) return d
python
def build_timeout_circuit(tor_state, reactor, path, timeout, using_guards=False): """ Build a new circuit within a timeout. CircuitBuildTimedOutError will be raised unless we receive a circuit build result (success or failure) within the `timeout` duration. :returns: a Deferred which fires when the circuit build succeeds (or fails to build). """ timed_circuit = [] d = tor_state.build_circuit(routers=path, using_guards=using_guards) def get_circuit(c): timed_circuit.append(c) return c def trap_cancel(f): f.trap(defer.CancelledError) if timed_circuit: d2 = timed_circuit[0].close() else: d2 = defer.succeed(None) d2.addCallback(lambda _: Failure(CircuitBuildTimedOutError("circuit build timed out"))) return d2 d.addCallback(get_circuit) d.addCallback(lambda circ: circ.when_built()) d.addErrback(trap_cancel) reactor.callLater(timeout, d.cancel) return d
[ "def", "build_timeout_circuit", "(", "tor_state", ",", "reactor", ",", "path", ",", "timeout", ",", "using_guards", "=", "False", ")", ":", "timed_circuit", "=", "[", "]", "d", "=", "tor_state", ".", "build_circuit", "(", "routers", "=", "path", ",", "usin...
Build a new circuit within a timeout. CircuitBuildTimedOutError will be raised unless we receive a circuit build result (success or failure) within the `timeout` duration. :returns: a Deferred which fires when the circuit build succeeds (or fails to build).
[ "Build", "a", "new", "circuit", "within", "a", "timeout", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/circuit.py#L527-L559
train
209,001
meejah/txtorcon
txtorcon/circuit.py
Circuit.age
def age(self, now=None): """ Returns an integer which is the difference in seconds from 'now' to when this circuit was created. Returns None if there is no created-time. """ if not self.time_created: return None if now is None: now = datetime.utcnow() return (now - self.time_created).seconds
python
def age(self, now=None): """ Returns an integer which is the difference in seconds from 'now' to when this circuit was created. Returns None if there is no created-time. """ if not self.time_created: return None if now is None: now = datetime.utcnow() return (now - self.time_created).seconds
[ "def", "age", "(", "self", ",", "now", "=", "None", ")", ":", "if", "not", "self", ".", "time_created", ":", "return", "None", "if", "now", "is", "None", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", "return", "(", "now", "-", "self", "."...
Returns an integer which is the difference in seconds from 'now' to when this circuit was created. Returns None if there is no created-time.
[ "Returns", "an", "integer", "which", "is", "the", "difference", "in", "seconds", "from", "now", "to", "when", "this", "circuit", "was", "created", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/circuit.py#L385-L396
train
209,002
meejah/txtorcon
txtorcon/socks.py
_SocksMachine._parse_version_reply
def _parse_version_reply(self): "waiting for a version reply" if len(self._data) >= 2: reply = self._data[:2] self._data = self._data[2:] (version, method) = struct.unpack('BB', reply) if version == 5 and method in [0x00, 0x02]: self.version_reply(method) else: if version != 5: self.version_error(SocksError( "Expected version 5, got {}".format(version))) else: self.version_error(SocksError( "Wanted method 0 or 2, got {}".format(method)))
python
def _parse_version_reply(self): "waiting for a version reply" if len(self._data) >= 2: reply = self._data[:2] self._data = self._data[2:] (version, method) = struct.unpack('BB', reply) if version == 5 and method in [0x00, 0x02]: self.version_reply(method) else: if version != 5: self.version_error(SocksError( "Expected version 5, got {}".format(version))) else: self.version_error(SocksError( "Wanted method 0 or 2, got {}".format(method)))
[ "def", "_parse_version_reply", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_data", ")", ">=", "2", ":", "reply", "=", "self", ".", "_data", "[", ":", "2", "]", "self", ".", "_data", "=", "self", ".", "_data", "[", "2", ":", "]", "(",...
waiting for a version reply
[ "waiting", "for", "a", "version", "reply" ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/socks.py#L139-L153
train
209,003
meejah/txtorcon
txtorcon/socks.py
_SocksMachine._parse_request_reply
def _parse_request_reply(self): "waiting for a reply to our request" # we need at least 6 bytes of data: 4 for the "header", such # as it is, and 2 more if it's DOMAINNAME (for the size) or 4 # or 16 more if it's an IPv4/6 address reply. plus there's 2 # bytes on the end for the bound port. if len(self._data) < 8: return msg = self._data[:4] # not changing self._data yet, in case we've not got # enough bytes so far. (version, reply, _, typ) = struct.unpack('BBBB', msg) if version != 5: self.reply_error(SocksError( "Expected version 5, got {}".format(version))) return if reply != self.SUCCEEDED: self.reply_error(_create_socks_error(reply)) return reply_dispatcher = { self.REPLY_IPV4: self._parse_ipv4_reply, self.REPLY_HOST: self._parse_domain_name_reply, self.REPLY_IPV6: self._parse_ipv6_reply, } try: method = reply_dispatcher[typ] except KeyError: self.reply_error(SocksError( "Unexpected response type {}".format(typ))) return method()
python
def _parse_request_reply(self): "waiting for a reply to our request" # we need at least 6 bytes of data: 4 for the "header", such # as it is, and 2 more if it's DOMAINNAME (for the size) or 4 # or 16 more if it's an IPv4/6 address reply. plus there's 2 # bytes on the end for the bound port. if len(self._data) < 8: return msg = self._data[:4] # not changing self._data yet, in case we've not got # enough bytes so far. (version, reply, _, typ) = struct.unpack('BBBB', msg) if version != 5: self.reply_error(SocksError( "Expected version 5, got {}".format(version))) return if reply != self.SUCCEEDED: self.reply_error(_create_socks_error(reply)) return reply_dispatcher = { self.REPLY_IPV4: self._parse_ipv4_reply, self.REPLY_HOST: self._parse_domain_name_reply, self.REPLY_IPV6: self._parse_ipv6_reply, } try: method = reply_dispatcher[typ] except KeyError: self.reply_error(SocksError( "Unexpected response type {}".format(typ))) return method()
[ "def", "_parse_request_reply", "(", "self", ")", ":", "# we need at least 6 bytes of data: 4 for the \"header\", such", "# as it is, and 2 more if it's DOMAINNAME (for the size) or 4", "# or 16 more if it's an IPv4/6 address reply. plus there's 2", "# bytes on the end for the bound port.", "if",...
waiting for a reply to our request
[ "waiting", "for", "a", "reply", "to", "our", "request" ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/socks.py#L184-L218
train
209,004
meejah/txtorcon
txtorcon/socks.py
_SocksMachine._make_connection
def _make_connection(self, addr, port): "make our proxy connection" sender = self._create_connection(addr, port) # XXX look out! we're depending on this "sender" implementing # certain Twisted APIs, and the state-machine shouldn't depend # on that. # XXX also, if sender implements producer/consumer stuff, we # should register ourselves (and implement it to) -- but this # should really be taking place outside the state-machine in # "the I/O-doing" stuff self._sender = sender self._when_done.fire(sender)
python
def _make_connection(self, addr, port): "make our proxy connection" sender = self._create_connection(addr, port) # XXX look out! we're depending on this "sender" implementing # certain Twisted APIs, and the state-machine shouldn't depend # on that. # XXX also, if sender implements producer/consumer stuff, we # should register ourselves (and implement it to) -- but this # should really be taking place outside the state-machine in # "the I/O-doing" stuff self._sender = sender self._when_done.fire(sender)
[ "def", "_make_connection", "(", "self", ",", "addr", ",", "port", ")", ":", "sender", "=", "self", ".", "_create_connection", "(", "addr", ",", "port", ")", "# XXX look out! we're depending on this \"sender\" implementing", "# certain Twisted APIs, and the state-machine sho...
make our proxy connection
[ "make", "our", "proxy", "connection" ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/socks.py#L221-L233
train
209,005
meejah/txtorcon
txtorcon/socks.py
_SocksMachine._relay_data
def _relay_data(self): "relay any data we have" if self._data: d = self._data self._data = b'' # XXX this is "doing I/O" in the state-machine and it # really shouldn't be ... probably want a passed-in # "relay_data" callback or similar? self._sender.dataReceived(d)
python
def _relay_data(self): "relay any data we have" if self._data: d = self._data self._data = b'' # XXX this is "doing I/O" in the state-machine and it # really shouldn't be ... probably want a passed-in # "relay_data" callback or similar? self._sender.dataReceived(d)
[ "def", "_relay_data", "(", "self", ")", ":", "if", "self", ".", "_data", ":", "d", "=", "self", ".", "_data", "self", ".", "_data", "=", "b''", "# XXX this is \"doing I/O\" in the state-machine and it", "# really shouldn't be ... probably want a passed-in", "# \"relay_d...
relay any data we have
[ "relay", "any", "data", "we", "have" ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/socks.py#L303-L311
train
209,006
meejah/txtorcon
txtorcon/socks.py
_SocksMachine._send_connect_request
def _send_connect_request(self): "sends CONNECT request" # XXX needs to support v6 ... or something else does host = self._addr.host port = self._addr.port if isinstance(self._addr, (IPv4Address, IPv6Address)): is_v6 = isinstance(self._addr, IPv6Address) self._data_to_send( struct.pack( '!BBBB4sH', 5, # version 0x01, # command 0x00, # reserved 0x04 if is_v6 else 0x01, inet_pton(AF_INET6 if is_v6 else AF_INET, host), port, ) ) else: host = host.encode('ascii') self._data_to_send( struct.pack( '!BBBBB{}sH'.format(len(host)), 5, # version 0x01, # command 0x00, # reserved 0x03, len(host), host, port, ) )
python
def _send_connect_request(self): "sends CONNECT request" # XXX needs to support v6 ... or something else does host = self._addr.host port = self._addr.port if isinstance(self._addr, (IPv4Address, IPv6Address)): is_v6 = isinstance(self._addr, IPv6Address) self._data_to_send( struct.pack( '!BBBB4sH', 5, # version 0x01, # command 0x00, # reserved 0x04 if is_v6 else 0x01, inet_pton(AF_INET6 if is_v6 else AF_INET, host), port, ) ) else: host = host.encode('ascii') self._data_to_send( struct.pack( '!BBBBB{}sH'.format(len(host)), 5, # version 0x01, # command 0x00, # reserved 0x03, len(host), host, port, ) )
[ "def", "_send_connect_request", "(", "self", ")", ":", "# XXX needs to support v6 ... or something else does", "host", "=", "self", ".", "_addr", ".", "host", "port", "=", "self", ".", "_addr", ".", "port", "if", "isinstance", "(", "self", ".", "_addr", ",", "...
sends CONNECT request
[ "sends", "CONNECT", "request" ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/socks.py#L313-L345
train
209,007
meejah/txtorcon
txtorcon/router.py
Router.get_location
def get_location(self): """ Returns a Deferred that fires with a NetLocation object for this router. """ if self._location: return succeed(self._location) if self.ip != 'unknown': self._location = NetLocation(self.ip) else: self._location = NetLocation(None) if not self._location.countrycode and self.ip != 'unknown': # see if Tor is magic and knows more... d = self.controller.get_info_raw('ip-to-country/' + self.ip) d.addCallback(self._set_country) d.addCallback(lambda _: self._location) return d return succeed(self._location)
python
def get_location(self): """ Returns a Deferred that fires with a NetLocation object for this router. """ if self._location: return succeed(self._location) if self.ip != 'unknown': self._location = NetLocation(self.ip) else: self._location = NetLocation(None) if not self._location.countrycode and self.ip != 'unknown': # see if Tor is magic and knows more... d = self.controller.get_info_raw('ip-to-country/' + self.ip) d.addCallback(self._set_country) d.addCallback(lambda _: self._location) return d return succeed(self._location)
[ "def", "get_location", "(", "self", ")", ":", "if", "self", ".", "_location", ":", "return", "succeed", "(", "self", ".", "_location", ")", "if", "self", ".", "ip", "!=", "'unknown'", ":", "self", ".", "_location", "=", "NetLocation", "(", "self", ".",...
Returns a Deferred that fires with a NetLocation object for this router.
[ "Returns", "a", "Deferred", "that", "fires", "with", "a", "NetLocation", "object", "for", "this", "router", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/router.py#L123-L140
train
209,008
meejah/txtorcon
txtorcon/router.py
Router.policy
def policy(self, args): """ setter for the policy descriptor """ word = args[0] if word == 'reject': self.accepted_ports = None self.rejected_ports = [] target = self.rejected_ports elif word == 'accept': self.accepted_ports = [] self.rejected_ports = None target = self.accepted_ports else: raise RuntimeError("Don't understand policy word \"%s\"" % word) for port in args[1].split(','): if '-' in port: (a, b) = port.split('-') target.append(PortRange(int(a), int(b))) else: target.append(int(port))
python
def policy(self, args): """ setter for the policy descriptor """ word = args[0] if word == 'reject': self.accepted_ports = None self.rejected_ports = [] target = self.rejected_ports elif word == 'accept': self.accepted_ports = [] self.rejected_ports = None target = self.accepted_ports else: raise RuntimeError("Don't understand policy word \"%s\"" % word) for port in args[1].split(','): if '-' in port: (a, b) = port.split('-') target.append(PortRange(int(a), int(b))) else: target.append(int(port))
[ "def", "policy", "(", "self", ",", "args", ")", ":", "word", "=", "args", "[", "0", "]", "if", "word", "==", "'reject'", ":", "self", ".", "accepted_ports", "=", "None", "self", ".", "rejected_ports", "=", "[", "]", "target", "=", "self", ".", "rej...
setter for the policy descriptor
[ "setter", "for", "the", "policy", "descriptor" ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/router.py#L246-L270
train
209,009
meejah/txtorcon
txtorcon/router.py
Router.accepts_port
def accepts_port(self, port): """ Query whether this Router will accept the given port. """ if self.rejected_ports is None and self.accepted_ports is None: raise RuntimeError("policy hasn't been set yet") if self.rejected_ports: for x in self.rejected_ports: if port == x: return False return True for x in self.accepted_ports: if port == x: return True return False
python
def accepts_port(self, port): """ Query whether this Router will accept the given port. """ if self.rejected_ports is None and self.accepted_ports is None: raise RuntimeError("policy hasn't been set yet") if self.rejected_ports: for x in self.rejected_ports: if port == x: return False return True for x in self.accepted_ports: if port == x: return True return False
[ "def", "accepts_port", "(", "self", ",", "port", ")", ":", "if", "self", ".", "rejected_ports", "is", "None", "and", "self", ".", "accepted_ports", "is", "None", ":", "raise", "RuntimeError", "(", "\"policy hasn't been set yet\"", ")", "if", "self", ".", "re...
Query whether this Router will accept the given port.
[ "Query", "whether", "this", "Router", "will", "accept", "the", "given", "port", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/router.py#L272-L289
train
209,010
meejah/txtorcon
txtorcon/router.py
Router._set_country
def _set_country(self, c): """ callback if we used Tor's GETINFO ip-to-country """ self.location.countrycode = c.split()[0].split('=')[1].strip().upper()
python
def _set_country(self, c): """ callback if we used Tor's GETINFO ip-to-country """ self.location.countrycode = c.split()[0].split('=')[1].strip().upper()
[ "def", "_set_country", "(", "self", ",", "c", ")", ":", "self", ".", "location", ".", "countrycode", "=", "c", ".", "split", "(", ")", "[", "0", "]", ".", "split", "(", "'='", ")", "[", "1", "]", ".", "strip", "(", ")", ".", "upper", "(", ")"...
callback if we used Tor's GETINFO ip-to-country
[ "callback", "if", "we", "used", "Tor", "s", "GETINFO", "ip", "-", "to", "-", "country" ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/router.py#L291-L296
train
209,011
meejah/txtorcon
txtorcon/endpoints.py
_load_private_key_file
def _load_private_key_file(fname): """ Loads an onion-service private-key from the given file. This can be either a 'key blog' as returned from a previous ADD_ONION call, or a v3 or v2 file as created by Tor when using the HiddenServiceDir directive. In any case, a key-blob suitable for ADD_ONION use is returned. """ with open(fname, "rb") as f: data = f.read() if b"\x00\x00\x00" in data: # v3 private key file blob = data[data.find(b"\x00\x00\x00") + 3:] return u"ED25519-V3:{}".format(b2a_base64(blob.strip()).decode('ascii').strip()) if b"-----BEGIN RSA PRIVATE KEY-----" in data: # v2 RSA key blob = "".join(data.decode('ascii').split('\n')[1:-2]) return u"RSA1024:{}".format(blob) blob = data.decode('ascii').strip() if ':' in blob: kind, key = blob.split(':', 1) if kind in ['ED25519-V3', 'RSA1024']: return blob raise ValueError( "'{}' does not appear to contain v2 or v3 private key data".format( fname, ) )
python
def _load_private_key_file(fname): """ Loads an onion-service private-key from the given file. This can be either a 'key blog' as returned from a previous ADD_ONION call, or a v3 or v2 file as created by Tor when using the HiddenServiceDir directive. In any case, a key-blob suitable for ADD_ONION use is returned. """ with open(fname, "rb") as f: data = f.read() if b"\x00\x00\x00" in data: # v3 private key file blob = data[data.find(b"\x00\x00\x00") + 3:] return u"ED25519-V3:{}".format(b2a_base64(blob.strip()).decode('ascii').strip()) if b"-----BEGIN RSA PRIVATE KEY-----" in data: # v2 RSA key blob = "".join(data.decode('ascii').split('\n')[1:-2]) return u"RSA1024:{}".format(blob) blob = data.decode('ascii').strip() if ':' in blob: kind, key = blob.split(':', 1) if kind in ['ED25519-V3', 'RSA1024']: return blob raise ValueError( "'{}' does not appear to contain v2 or v3 private key data".format( fname, ) )
[ "def", "_load_private_key_file", "(", "fname", ")", ":", "with", "open", "(", "fname", ",", "\"rb\"", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", "if", "b\"\\x00\\x00\\x00\"", "in", "data", ":", "# v3 private key file", "blob", "=", "da...
Loads an onion-service private-key from the given file. This can be either a 'key blog' as returned from a previous ADD_ONION call, or a v3 or v2 file as created by Tor when using the HiddenServiceDir directive. In any case, a key-blob suitable for ADD_ONION use is returned.
[ "Loads", "an", "onion", "-", "service", "private", "-", "key", "from", "the", "given", "file", ".", "This", "can", "be", "either", "a", "key", "blog", "as", "returned", "from", "a", "previous", "ADD_ONION", "call", "or", "a", "v3", "or", "v2", "file", ...
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/endpoints.py#L823-L849
train
209,012
meejah/txtorcon
txtorcon/torconfig.py
HiddenService.config_attributes
def config_attributes(self): """ Helper method used by TorConfig when generating a torrc file. """ rtn = [('HiddenServiceDir', str(self.dir))] if self.conf._supports['HiddenServiceDirGroupReadable'] \ and self.group_readable: rtn.append(('HiddenServiceDirGroupReadable', str(1))) for port in self.ports: rtn.append(('HiddenServicePort', str(port))) if self.version: rtn.append(('HiddenServiceVersion', str(self.version))) for authline in self.authorize_client: rtn.append(('HiddenServiceAuthorizeClient', str(authline))) return rtn
python
def config_attributes(self): """ Helper method used by TorConfig when generating a torrc file. """ rtn = [('HiddenServiceDir', str(self.dir))] if self.conf._supports['HiddenServiceDirGroupReadable'] \ and self.group_readable: rtn.append(('HiddenServiceDirGroupReadable', str(1))) for port in self.ports: rtn.append(('HiddenServicePort', str(port))) if self.version: rtn.append(('HiddenServiceVersion', str(self.version))) for authline in self.authorize_client: rtn.append(('HiddenServiceAuthorizeClient', str(authline))) return rtn
[ "def", "config_attributes", "(", "self", ")", ":", "rtn", "=", "[", "(", "'HiddenServiceDir'", ",", "str", "(", "self", ".", "dir", ")", ")", "]", "if", "self", ".", "conf", ".", "_supports", "[", "'HiddenServiceDirGroupReadable'", "]", "and", "self", "....
Helper method used by TorConfig when generating a torrc file.
[ "Helper", "method", "used", "by", "TorConfig", "when", "generating", "a", "torrc", "file", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/torconfig.py#L393-L408
train
209,013
meejah/txtorcon
txtorcon/torconfig.py
EphemeralHiddenService.add_to_tor
def add_to_tor(self, protocol): ''' Returns a Deferred which fires with 'self' after at least one descriptor has been uploaded. Errback if no descriptor upload succeeds. ''' upload_d = _await_descriptor_upload(protocol, self, progress=None, await_all_uploads=False) # _add_ephemeral_service takes a TorConfig but we don't have # that here .. and also we're just keeping this for # backwards-compatability anyway so instead of trying to # re-use that helper I'm leaving this original code here. So # this is what it supports and that's that: ports = ' '.join(map(lambda x: 'Port=' + x.strip(), self._ports)) cmd = 'ADD_ONION %s %s' % (self._key_blob, ports) ans = yield protocol.queue_command(cmd) ans = find_keywords(ans.split('\n')) self.hostname = ans['ServiceID'] + '.onion' if self._key_blob.startswith('NEW:'): self.private_key = ans['PrivateKey'] else: self.private_key = self._key_blob log.msg('Created hidden-service at', self.hostname) log.msg("Created '{}', waiting for descriptor uploads.".format(self.hostname)) yield upload_d
python
def add_to_tor(self, protocol): ''' Returns a Deferred which fires with 'self' after at least one descriptor has been uploaded. Errback if no descriptor upload succeeds. ''' upload_d = _await_descriptor_upload(protocol, self, progress=None, await_all_uploads=False) # _add_ephemeral_service takes a TorConfig but we don't have # that here .. and also we're just keeping this for # backwards-compatability anyway so instead of trying to # re-use that helper I'm leaving this original code here. So # this is what it supports and that's that: ports = ' '.join(map(lambda x: 'Port=' + x.strip(), self._ports)) cmd = 'ADD_ONION %s %s' % (self._key_blob, ports) ans = yield protocol.queue_command(cmd) ans = find_keywords(ans.split('\n')) self.hostname = ans['ServiceID'] + '.onion' if self._key_blob.startswith('NEW:'): self.private_key = ans['PrivateKey'] else: self.private_key = self._key_blob log.msg('Created hidden-service at', self.hostname) log.msg("Created '{}', waiting for descriptor uploads.".format(self.hostname)) yield upload_d
[ "def", "add_to_tor", "(", "self", ",", "protocol", ")", ":", "upload_d", "=", "_await_descriptor_upload", "(", "protocol", ",", "self", ",", "progress", "=", "None", ",", "await_all_uploads", "=", "False", ")", "# _add_ephemeral_service takes a TorConfig but we don't ...
Returns a Deferred which fires with 'self' after at least one descriptor has been uploaded. Errback if no descriptor upload succeeds.
[ "Returns", "a", "Deferred", "which", "fires", "with", "self", "after", "at", "least", "one", "descriptor", "has", "been", "uploaded", ".", "Errback", "if", "no", "descriptor", "upload", "succeeds", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/torconfig.py#L458-L485
train
209,014
meejah/txtorcon
txtorcon/torconfig.py
EphemeralHiddenService.remove_from_tor
def remove_from_tor(self, protocol): ''' Returns a Deferred which fires with None ''' r = yield protocol.queue_command('DEL_ONION %s' % self.hostname[:-6]) if r.strip() != 'OK': raise RuntimeError('Failed to remove hidden service: "%s".' % r)
python
def remove_from_tor(self, protocol): ''' Returns a Deferred which fires with None ''' r = yield protocol.queue_command('DEL_ONION %s' % self.hostname[:-6]) if r.strip() != 'OK': raise RuntimeError('Failed to remove hidden service: "%s".' % r)
[ "def", "remove_from_tor", "(", "self", ",", "protocol", ")", ":", "r", "=", "yield", "protocol", ".", "queue_command", "(", "'DEL_ONION %s'", "%", "self", ".", "hostname", "[", ":", "-", "6", "]", ")", "if", "r", ".", "strip", "(", ")", "!=", "'OK'",...
Returns a Deferred which fires with None
[ "Returns", "a", "Deferred", "which", "fires", "with", "None" ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/torconfig.py#L488-L494
train
209,015
meejah/txtorcon
txtorcon/torconfig.py
TorConfig.from_protocol
def from_protocol(proto): """ This creates and returns a ready-to-go TorConfig instance from the given protocol, which should be an instance of TorControlProtocol. """ cfg = TorConfig(control=proto) yield cfg.post_bootstrap defer.returnValue(cfg)
python
def from_protocol(proto): """ This creates and returns a ready-to-go TorConfig instance from the given protocol, which should be an instance of TorControlProtocol. """ cfg = TorConfig(control=proto) yield cfg.post_bootstrap defer.returnValue(cfg)
[ "def", "from_protocol", "(", "proto", ")", ":", "cfg", "=", "TorConfig", "(", "control", "=", "proto", ")", "yield", "cfg", ".", "post_bootstrap", "defer", ".", "returnValue", "(", "cfg", ")" ]
This creates and returns a ready-to-go TorConfig instance from the given protocol, which should be an instance of TorControlProtocol.
[ "This", "creates", "and", "returns", "a", "ready", "-", "to", "-", "go", "TorConfig", "instance", "from", "the", "given", "protocol", "which", "should", "be", "an", "instance", "of", "TorControlProtocol", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/torconfig.py#L574-L582
train
209,016
meejah/txtorcon
txtorcon/torconfig.py
TorConfig.socks_endpoint
def socks_endpoint(self, reactor, port=None): """ Returns a TorSocksEndpoint configured to use an already-configured SOCKSPort from the Tor we're connected to. By default, this will be the very first SOCKSPort. :param port: a str, the first part of the SOCKSPort line (that is, a port like "9151" or a Unix socket config like "unix:/path". You may also specify a port as an int. If you need to use a particular port that may or may not already be configured, see the async method :meth:`txtorcon.TorConfig.create_socks_endpoint` """ if len(self.SocksPort) == 0: raise RuntimeError( "No SOCKS ports configured" ) socks_config = None if port is None: socks_config = self.SocksPort[0] else: port = str(port) # in case e.g. an int passed in if ' ' in port: raise ValueError( "Can't specify options; use create_socks_endpoint instead" ) for idx, port_config in enumerate(self.SocksPort): # "SOCKSPort" is a gnarly beast that can have a bunch # of options appended, so we have to split off the # first thing which *should* be the port (or can be a # string like 'unix:') if port_config.split()[0] == port: socks_config = port_config break if socks_config is None: raise RuntimeError( "No SOCKSPort configured for port {}".format(port) ) return _endpoint_from_socksport_line(reactor, socks_config)
python
def socks_endpoint(self, reactor, port=None): """ Returns a TorSocksEndpoint configured to use an already-configured SOCKSPort from the Tor we're connected to. By default, this will be the very first SOCKSPort. :param port: a str, the first part of the SOCKSPort line (that is, a port like "9151" or a Unix socket config like "unix:/path". You may also specify a port as an int. If you need to use a particular port that may or may not already be configured, see the async method :meth:`txtorcon.TorConfig.create_socks_endpoint` """ if len(self.SocksPort) == 0: raise RuntimeError( "No SOCKS ports configured" ) socks_config = None if port is None: socks_config = self.SocksPort[0] else: port = str(port) # in case e.g. an int passed in if ' ' in port: raise ValueError( "Can't specify options; use create_socks_endpoint instead" ) for idx, port_config in enumerate(self.SocksPort): # "SOCKSPort" is a gnarly beast that can have a bunch # of options appended, so we have to split off the # first thing which *should* be the port (or can be a # string like 'unix:') if port_config.split()[0] == port: socks_config = port_config break if socks_config is None: raise RuntimeError( "No SOCKSPort configured for port {}".format(port) ) return _endpoint_from_socksport_line(reactor, socks_config)
[ "def", "socks_endpoint", "(", "self", ",", "reactor", ",", "port", "=", "None", ")", ":", "if", "len", "(", "self", ".", "SocksPort", ")", "==", "0", ":", "raise", "RuntimeError", "(", "\"No SOCKS ports configured\"", ")", "socks_config", "=", "None", "if"...
Returns a TorSocksEndpoint configured to use an already-configured SOCKSPort from the Tor we're connected to. By default, this will be the very first SOCKSPort. :param port: a str, the first part of the SOCKSPort line (that is, a port like "9151" or a Unix socket config like "unix:/path". You may also specify a port as an int. If you need to use a particular port that may or may not already be configured, see the async method :meth:`txtorcon.TorConfig.create_socks_endpoint`
[ "Returns", "a", "TorSocksEndpoint", "configured", "to", "use", "an", "already", "-", "configured", "SOCKSPort", "from", "the", "Tor", "we", "re", "connected", "to", ".", "By", "default", "this", "will", "be", "the", "very", "first", "SOCKSPort", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/torconfig.py#L626-L669
train
209,017
meejah/txtorcon
txtorcon/torconfig.py
TorConfig.attach_protocol
def attach_protocol(self, proto): """ returns a Deferred that fires once we've set this object up to track the protocol. Fails if we already have a protocol. """ if self._protocol is not None: raise RuntimeError("Already have a protocol.") # make sure we have nothing in self.unsaved self.save() self.__dict__['_protocol'] = proto # FIXME some of this is duplicated from ctor del self.__dict__['_accept_all_'] self.__dict__['post_bootstrap'] = defer.Deferred() if proto.post_bootstrap: proto.post_bootstrap.addCallback(self.bootstrap) return self.__dict__['post_bootstrap']
python
def attach_protocol(self, proto): """ returns a Deferred that fires once we've set this object up to track the protocol. Fails if we already have a protocol. """ if self._protocol is not None: raise RuntimeError("Already have a protocol.") # make sure we have nothing in self.unsaved self.save() self.__dict__['_protocol'] = proto # FIXME some of this is duplicated from ctor del self.__dict__['_accept_all_'] self.__dict__['post_bootstrap'] = defer.Deferred() if proto.post_bootstrap: proto.post_bootstrap.addCallback(self.bootstrap) return self.__dict__['post_bootstrap']
[ "def", "attach_protocol", "(", "self", ",", "proto", ")", ":", "if", "self", ".", "_protocol", "is", "not", "None", ":", "raise", "RuntimeError", "(", "\"Already have a protocol.\"", ")", "# make sure we have nothing in self.unsaved", "self", ".", "save", "(", ")"...
returns a Deferred that fires once we've set this object up to track the protocol. Fails if we already have a protocol.
[ "returns", "a", "Deferred", "that", "fires", "once", "we", "ve", "set", "this", "object", "up", "to", "track", "the", "protocol", ".", "Fails", "if", "we", "already", "have", "a", "protocol", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/torconfig.py#L739-L755
train
209,018
meejah/txtorcon
txtorcon/torconfig.py
TorConfig.get_type
def get_type(self, name): """ return the type of a config key. :param: name the key FIXME can we do something more-clever than this for client code to determine what sort of thing a key is? """ # XXX FIXME uhm...how to do all the different types of hidden-services? if name.lower() == 'hiddenservices': return FilesystemOnionService return type(self.parsers[name])
python
def get_type(self, name): """ return the type of a config key. :param: name the key FIXME can we do something more-clever than this for client code to determine what sort of thing a key is? """ # XXX FIXME uhm...how to do all the different types of hidden-services? if name.lower() == 'hiddenservices': return FilesystemOnionService return type(self.parsers[name])
[ "def", "get_type", "(", "self", ",", "name", ")", ":", "# XXX FIXME uhm...how to do all the different types of hidden-services?", "if", "name", ".", "lower", "(", ")", "==", "'hiddenservices'", ":", "return", "FilesystemOnionService", "return", "type", "(", "self", "....
return the type of a config key. :param: name the key FIXME can we do something more-clever than this for client code to determine what sort of thing a key is?
[ "return", "the", "type", "of", "a", "config", "key", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/torconfig.py#L826-L839
train
209,019
meejah/txtorcon
txtorcon/torconfig.py
TorConfig.bootstrap
def bootstrap(self, arg=None): ''' This only takes args so it can be used as a callback. Don't pass an arg, it is ignored. ''' try: d = self.protocol.add_event_listener( 'CONF_CHANGED', self._conf_changed) except RuntimeError: # for Tor versions which don't understand CONF_CHANGED # there's nothing we can really do. log.msg( "Can't listen for CONF_CHANGED event; won't stay up-to-date " "with other clients.") d = defer.succeed(None) d.addCallback(lambda _: self.protocol.get_info_raw("config/names")) d.addCallback(self._do_setup) d.addCallback(self.do_post_bootstrap) d.addErrback(self.do_post_errback)
python
def bootstrap(self, arg=None): ''' This only takes args so it can be used as a callback. Don't pass an arg, it is ignored. ''' try: d = self.protocol.add_event_listener( 'CONF_CHANGED', self._conf_changed) except RuntimeError: # for Tor versions which don't understand CONF_CHANGED # there's nothing we can really do. log.msg( "Can't listen for CONF_CHANGED event; won't stay up-to-date " "with other clients.") d = defer.succeed(None) d.addCallback(lambda _: self.protocol.get_info_raw("config/names")) d.addCallback(self._do_setup) d.addCallback(self.do_post_bootstrap) d.addErrback(self.do_post_errback)
[ "def", "bootstrap", "(", "self", ",", "arg", "=", "None", ")", ":", "try", ":", "d", "=", "self", ".", "protocol", ".", "add_event_listener", "(", "'CONF_CHANGED'", ",", "self", ".", "_conf_changed", ")", "except", "RuntimeError", ":", "# for Tor versions wh...
This only takes args so it can be used as a callback. Don't pass an arg, it is ignored.
[ "This", "only", "takes", "args", "so", "it", "can", "be", "used", "as", "a", "callback", ".", "Don", "t", "pass", "an", "arg", "it", "is", "ignored", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/torconfig.py#L869-L887
train
209,020
meejah/txtorcon
txtorcon/torconfig.py
TorConfig.save
def save(self): """ Save any outstanding items. This returns a Deferred which will errback if Tor was unhappy with anything, or callback with this TorConfig object on success. """ if not self.needs_save(): return defer.succeed(self) args = [] directories = [] for (key, value) in self.unsaved.items(): if key == 'HiddenServices': self.config['HiddenServices'] = value # using a list here because at least one unit-test # cares about order -- and conceivably order *could* # matter here, to Tor... services = list() # authenticated services get flattened into the HiddenServices list... for hs in value: if IOnionClient.providedBy(hs): parent = IOnionClient(hs).parent if parent not in services: services.append(parent) elif isinstance(hs, (EphemeralOnionService, EphemeralHiddenService)): raise ValueError( "Only filesystem based Onion services may be added" " via TorConfig.hiddenservices; ephemeral services" " must be created with 'create_onion_service'." ) else: if hs not in services: services.append(hs) for hs in services: for (k, v) in hs.config_attributes(): if k == 'HiddenServiceDir': if v not in directories: directories.append(v) args.append(k) args.append(v) else: raise RuntimeError("Trying to add hidden service with same HiddenServiceDir: %s" % v) else: args.append(k) args.append(v) continue if isinstance(value, list): for x in value: # FIXME XXX if x is not DEFAULT_VALUE: args.append(key) args.append(str(x)) else: args.append(key) args.append(value) # FIXME in future we should wait for CONF_CHANGED and # update then, right? real_name = self._find_real_name(key) if not isinstance(value, list) and real_name in self.parsers: value = self.parsers[real_name].parse(value) self.config[real_name] = value # FIXME might want to re-think this, but currently there's no # way to put things into a config and get them out again # nicely...unless you just don't assign a protocol if self.protocol: d = self.protocol.set_conf(*args) d.addCallback(self._save_completed) return d else: self._save_completed() return defer.succeed(self)
python
def save(self): """ Save any outstanding items. This returns a Deferred which will errback if Tor was unhappy with anything, or callback with this TorConfig object on success. """ if not self.needs_save(): return defer.succeed(self) args = [] directories = [] for (key, value) in self.unsaved.items(): if key == 'HiddenServices': self.config['HiddenServices'] = value # using a list here because at least one unit-test # cares about order -- and conceivably order *could* # matter here, to Tor... services = list() # authenticated services get flattened into the HiddenServices list... for hs in value: if IOnionClient.providedBy(hs): parent = IOnionClient(hs).parent if parent not in services: services.append(parent) elif isinstance(hs, (EphemeralOnionService, EphemeralHiddenService)): raise ValueError( "Only filesystem based Onion services may be added" " via TorConfig.hiddenservices; ephemeral services" " must be created with 'create_onion_service'." ) else: if hs not in services: services.append(hs) for hs in services: for (k, v) in hs.config_attributes(): if k == 'HiddenServiceDir': if v not in directories: directories.append(v) args.append(k) args.append(v) else: raise RuntimeError("Trying to add hidden service with same HiddenServiceDir: %s" % v) else: args.append(k) args.append(v) continue if isinstance(value, list): for x in value: # FIXME XXX if x is not DEFAULT_VALUE: args.append(key) args.append(str(x)) else: args.append(key) args.append(value) # FIXME in future we should wait for CONF_CHANGED and # update then, right? real_name = self._find_real_name(key) if not isinstance(value, list) and real_name in self.parsers: value = self.parsers[real_name].parse(value) self.config[real_name] = value # FIXME might want to re-think this, but currently there's no # way to put things into a config and get them out again # nicely...unless you just don't assign a protocol if self.protocol: d = self.protocol.set_conf(*args) d.addCallback(self._save_completed) return d else: self._save_completed() return defer.succeed(self)
[ "def", "save", "(", "self", ")", ":", "if", "not", "self", ".", "needs_save", "(", ")", ":", "return", "defer", ".", "succeed", "(", "self", ")", "args", "=", "[", "]", "directories", "=", "[", "]", "for", "(", "key", ",", "value", ")", "in", "...
Save any outstanding items. This returns a Deferred which will errback if Tor was unhappy with anything, or callback with this TorConfig object on success.
[ "Save", "any", "outstanding", "items", ".", "This", "returns", "a", "Deferred", "which", "will", "errback", "if", "Tor", "was", "unhappy", "with", "anything", "or", "callback", "with", "this", "TorConfig", "object", "on", "success", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/torconfig.py#L906-L983
train
209,021
meejah/txtorcon
txtorcon/controller.py
TorProcessProtocol._timeout_expired
def _timeout_expired(self): """ A timeout was supplied during setup, and the time has run out. """ self._did_timeout = True try: self.transport.signalProcess('TERM') except error.ProcessExitedAlready: # XXX why don't we just always do this? self.transport.loseConnection() fail = Failure(RuntimeError("timeout while launching Tor")) self._maybe_notify_connected(fail)
python
def _timeout_expired(self): """ A timeout was supplied during setup, and the time has run out. """ self._did_timeout = True try: self.transport.signalProcess('TERM') except error.ProcessExitedAlready: # XXX why don't we just always do this? self.transport.loseConnection() fail = Failure(RuntimeError("timeout while launching Tor")) self._maybe_notify_connected(fail)
[ "def", "_timeout_expired", "(", "self", ")", ":", "self", ".", "_did_timeout", "=", "True", "try", ":", "self", ".", "transport", ".", "signalProcess", "(", "'TERM'", ")", "except", "error", ".", "ProcessExitedAlready", ":", "# XXX why don't we just always do this...
A timeout was supplied during setup, and the time has run out.
[ "A", "timeout", "was", "supplied", "during", "setup", "and", "the", "time", "has", "run", "out", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/controller.py#L1291-L1303
train
209,022
meejah/txtorcon
txtorcon/controller.py
TorProcessProtocol.cleanup
def cleanup(self): """ Clean up my temporary files. """ all([delete_file_or_tree(f) for f in self.to_delete]) self.to_delete = []
python
def cleanup(self): """ Clean up my temporary files. """ all([delete_file_or_tree(f) for f in self.to_delete]) self.to_delete = []
[ "def", "cleanup", "(", "self", ")", ":", "all", "(", "[", "delete_file_or_tree", "(", "f", ")", "for", "f", "in", "self", ".", "to_delete", "]", ")", "self", ".", "to_delete", "=", "[", "]" ]
Clean up my temporary files.
[ "Clean", "up", "my", "temporary", "files", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/controller.py#L1319-L1325
train
209,023
meejah/txtorcon
txtorcon/controller.py
TorProcessProtocol.progress
def progress(self, percent, tag, summary): """ Can be overridden or monkey-patched if you want to get progress updates yourself. """ if self.progress_updates: self.progress_updates(percent, tag, summary)
python
def progress(self, percent, tag, summary): """ Can be overridden or monkey-patched if you want to get progress updates yourself. """ if self.progress_updates: self.progress_updates(percent, tag, summary)
[ "def", "progress", "(", "self", ",", "percent", ",", "tag", ",", "summary", ")", ":", "if", "self", ".", "progress_updates", ":", "self", ".", "progress_updates", "(", "percent", ",", "tag", ",", "summary", ")" ]
Can be overridden or monkey-patched if you want to get progress updates yourself.
[ "Can", "be", "overridden", "or", "monkey", "-", "patched", "if", "you", "want", "to", "get", "progress", "updates", "yourself", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/controller.py#L1351-L1358
train
209,024
meejah/txtorcon
examples/close_all_circuits.py
main
def main(reactor): """ Close all open streams and circuits in the Tor we connect to """ control_ep = UNIXClientEndpoint(reactor, '/var/run/tor/control') tor = yield txtorcon.connect(reactor, control_ep) state = yield tor.create_state() print("Closing all circuits:") for circuit in list(state.circuits.values()): path = '->'.join(map(lambda r: r.id_hex, circuit.path)) print("Circuit {} through {}".format(circuit.id, path)) for stream in circuit.streams: print(" Stream {} to {}".format(stream.id, stream.target_host)) yield stream.close() print(" closed") yield circuit.close() print("closed") yield tor.quit()
python
def main(reactor): """ Close all open streams and circuits in the Tor we connect to """ control_ep = UNIXClientEndpoint(reactor, '/var/run/tor/control') tor = yield txtorcon.connect(reactor, control_ep) state = yield tor.create_state() print("Closing all circuits:") for circuit in list(state.circuits.values()): path = '->'.join(map(lambda r: r.id_hex, circuit.path)) print("Circuit {} through {}".format(circuit.id, path)) for stream in circuit.streams: print(" Stream {} to {}".format(stream.id, stream.target_host)) yield stream.close() print(" closed") yield circuit.close() print("closed") yield tor.quit()
[ "def", "main", "(", "reactor", ")", ":", "control_ep", "=", "UNIXClientEndpoint", "(", "reactor", ",", "'/var/run/tor/control'", ")", "tor", "=", "yield", "txtorcon", ".", "connect", "(", "reactor", ",", "control_ep", ")", "state", "=", "yield", "tor", ".", ...
Close all open streams and circuits in the Tor we connect to
[ "Close", "all", "open", "streams", "and", "circuits", "in", "the", "Tor", "we", "connect", "to" ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/examples/close_all_circuits.py#L10-L27
train
209,025
meejah/txtorcon
txtorcon/addrmap.py
Addr.update
def update(self, *args): """ deals with an update from Tor; see parsing logic in torcontroller """ gmtexpires = None (name, ip, expires) = args[:3] for arg in args: if arg.lower().startswith('expires='): gmtexpires = arg[8:] if gmtexpires is None: if len(args) == 3: gmtexpires = expires else: if args[2] == 'NEVER': gmtexpires = args[2] else: gmtexpires = args[3] self.name = name # "www.example.com" self.ip = maybe_ip_addr(ip) # IPV4Address instance, or string if self.ip == '<error>': self._expire() return fmt = "%Y-%m-%d %H:%M:%S" # if we already have expiry times, etc then we want to # properly delay our timeout oldexpires = self.expires if gmtexpires.upper() == 'NEVER': # FIXME can I just select a date 100 years in the future instead? self.expires = None else: self.expires = datetime.datetime.strptime(gmtexpires, fmt) self.created = datetime.datetime.utcnow() if self.expires is not None: if oldexpires is None: if self.expires <= self.created: diff = datetime.timedelta(seconds=0) else: diff = self.expires - self.created self.expiry = self.map.scheduler.callLater(diff.seconds, self._expire) else: diff = self.expires - oldexpires self.expiry.delay(diff.seconds)
python
def update(self, *args): """ deals with an update from Tor; see parsing logic in torcontroller """ gmtexpires = None (name, ip, expires) = args[:3] for arg in args: if arg.lower().startswith('expires='): gmtexpires = arg[8:] if gmtexpires is None: if len(args) == 3: gmtexpires = expires else: if args[2] == 'NEVER': gmtexpires = args[2] else: gmtexpires = args[3] self.name = name # "www.example.com" self.ip = maybe_ip_addr(ip) # IPV4Address instance, or string if self.ip == '<error>': self._expire() return fmt = "%Y-%m-%d %H:%M:%S" # if we already have expiry times, etc then we want to # properly delay our timeout oldexpires = self.expires if gmtexpires.upper() == 'NEVER': # FIXME can I just select a date 100 years in the future instead? self.expires = None else: self.expires = datetime.datetime.strptime(gmtexpires, fmt) self.created = datetime.datetime.utcnow() if self.expires is not None: if oldexpires is None: if self.expires <= self.created: diff = datetime.timedelta(seconds=0) else: diff = self.expires - self.created self.expiry = self.map.scheduler.callLater(diff.seconds, self._expire) else: diff = self.expires - oldexpires self.expiry.delay(diff.seconds)
[ "def", "update", "(", "self", ",", "*", "args", ")", ":", "gmtexpires", "=", "None", "(", "name", ",", "ip", ",", "expires", ")", "=", "args", "[", ":", "3", "]", "for", "arg", "in", "args", ":", "if", "arg", ".", "lower", "(", ")", ".", "sta...
deals with an update from Tor; see parsing logic in torcontroller
[ "deals", "with", "an", "update", "from", "Tor", ";", "see", "parsing", "logic", "in", "torcontroller" ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/addrmap.py#L37-L90
train
209,026
meejah/txtorcon
txtorcon/addrmap.py
Addr._expire
def _expire(self): """ callback done via callLater """ del self.map.addr[self.name] self.map.notify("addrmap_expired", *[self.name], **{})
python
def _expire(self): """ callback done via callLater """ del self.map.addr[self.name] self.map.notify("addrmap_expired", *[self.name], **{})
[ "def", "_expire", "(", "self", ")", ":", "del", "self", ".", "map", ".", "addr", "[", "self", ".", "name", "]", "self", ".", "map", ".", "notify", "(", "\"addrmap_expired\"", ",", "*", "[", "self", ".", "name", "]", ",", "*", "*", "{", "}", ")"...
callback done via callLater
[ "callback", "done", "via", "callLater" ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/addrmap.py#L92-L97
train
209,027
meejah/txtorcon
txtorcon/util.py
create_tbb_web_headers
def create_tbb_web_headers(): """ Returns a new `twisted.web.http_headers.Headers` instance populated with tags to mimic Tor Browser. These include values for `User-Agent`, `Accept`, `Accept-Language` and `Accept-Encoding`. """ return Headers({ b"User-Agent": [b"Mozilla/5.0 (Windows NT 6.1; rv:45.0) Gecko/20100101 Firefox/45.0"], b"Accept": [b"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"], b"Accept-Language": [b"en-US,en;q=0.5"], b"Accept-Encoding": [b"gzip, deflate"], })
python
def create_tbb_web_headers(): """ Returns a new `twisted.web.http_headers.Headers` instance populated with tags to mimic Tor Browser. These include values for `User-Agent`, `Accept`, `Accept-Language` and `Accept-Encoding`. """ return Headers({ b"User-Agent": [b"Mozilla/5.0 (Windows NT 6.1; rv:45.0) Gecko/20100101 Firefox/45.0"], b"Accept": [b"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"], b"Accept-Language": [b"en-US,en;q=0.5"], b"Accept-Encoding": [b"gzip, deflate"], })
[ "def", "create_tbb_web_headers", "(", ")", ":", "return", "Headers", "(", "{", "b\"User-Agent\"", ":", "[", "b\"Mozilla/5.0 (Windows NT 6.1; rv:45.0) Gecko/20100101 Firefox/45.0\"", "]", ",", "b\"Accept\"", ":", "[", "b\"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q...
Returns a new `twisted.web.http_headers.Headers` instance populated with tags to mimic Tor Browser. These include values for `User-Agent`, `Accept`, `Accept-Language` and `Accept-Encoding`.
[ "Returns", "a", "new", "twisted", ".", "web", ".", "http_headers", ".", "Headers", "instance", "populated", "with", "tags", "to", "mimic", "Tor", "Browser", ".", "These", "include", "values", "for", "User", "-", "Agent", "Accept", "Accept", "-", "Language", ...
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/util.py#L39-L50
train
209,028
meejah/txtorcon
txtorcon/util.py
version_at_least
def version_at_least(version_string, major, minor, micro, patch): """ This returns True if the version_string represents a Tor version of at least ``major``.``minor``.``micro``.``patch`` version, ignoring any trailing specifiers. """ parts = re.match( r'^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+).*$', version_string, ) for ver, gold in zip(parts.group(1, 2, 3, 4), (major, minor, micro, patch)): if int(ver) < int(gold): return False elif int(ver) > int(gold): return True return True
python
def version_at_least(version_string, major, minor, micro, patch): """ This returns True if the version_string represents a Tor version of at least ``major``.``minor``.``micro``.``patch`` version, ignoring any trailing specifiers. """ parts = re.match( r'^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+).*$', version_string, ) for ver, gold in zip(parts.group(1, 2, 3, 4), (major, minor, micro, patch)): if int(ver) < int(gold): return False elif int(ver) > int(gold): return True return True
[ "def", "version_at_least", "(", "version_string", ",", "major", ",", "minor", ",", "micro", ",", "patch", ")", ":", "parts", "=", "re", ".", "match", "(", "r'^([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+).*$'", ",", "version_string", ",", ")", "for", "ver", ",", "...
This returns True if the version_string represents a Tor version of at least ``major``.``minor``.``micro``.``patch`` version, ignoring any trailing specifiers.
[ "This", "returns", "True", "if", "the", "version_string", "represents", "a", "Tor", "version", "of", "at", "least", "major", ".", "minor", ".", "micro", ".", "patch", "version", "ignoring", "any", "trailing", "specifiers", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/util.py#L53-L68
train
209,029
meejah/txtorcon
txtorcon/util.py
find_tor_binary
def find_tor_binary(globs=('/usr/sbin/', '/usr/bin/', '/Applications/TorBrowser_*.app/Contents/MacOS/'), system_tor=True): """ Tries to find the tor executable using the shell first or in in the paths whose glob-patterns is in the given 'globs'-tuple. :param globs: A tuple of shell-style globs of directories to use to find tor (TODO consider making that globs to actual tor binary?) :param system_tor: This controls whether bash is used to seach for 'tor' or not. If False, we skip that check and use only the 'globs' tuple. """ # Try to find the tor executable using the shell if system_tor: try: proc = subprocess.Popen( ('which tor'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True ) except OSError: pass else: stdout, _ = proc.communicate() if proc.poll() == 0 and stdout != '': return stdout.strip() # the shell may not provide type and tor is usually not on PATH when using # the browser-bundle. Look in specific places for pattern in globs: for path in glob.glob(pattern): torbin = os.path.join(path, 'tor') if is_executable(torbin): return torbin return None
python
def find_tor_binary(globs=('/usr/sbin/', '/usr/bin/', '/Applications/TorBrowser_*.app/Contents/MacOS/'), system_tor=True): """ Tries to find the tor executable using the shell first or in in the paths whose glob-patterns is in the given 'globs'-tuple. :param globs: A tuple of shell-style globs of directories to use to find tor (TODO consider making that globs to actual tor binary?) :param system_tor: This controls whether bash is used to seach for 'tor' or not. If False, we skip that check and use only the 'globs' tuple. """ # Try to find the tor executable using the shell if system_tor: try: proc = subprocess.Popen( ('which tor'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True ) except OSError: pass else: stdout, _ = proc.communicate() if proc.poll() == 0 and stdout != '': return stdout.strip() # the shell may not provide type and tor is usually not on PATH when using # the browser-bundle. Look in specific places for pattern in globs: for path in glob.glob(pattern): torbin = os.path.join(path, 'tor') if is_executable(torbin): return torbin return None
[ "def", "find_tor_binary", "(", "globs", "=", "(", "'/usr/sbin/'", ",", "'/usr/bin/'", ",", "'/Applications/TorBrowser_*.app/Contents/MacOS/'", ")", ",", "system_tor", "=", "True", ")", ":", "# Try to find the tor executable using the shell", "if", "system_tor", ":", "try"...
Tries to find the tor executable using the shell first or in in the paths whose glob-patterns is in the given 'globs'-tuple. :param globs: A tuple of shell-style globs of directories to use to find tor (TODO consider making that globs to actual tor binary?) :param system_tor: This controls whether bash is used to seach for 'tor' or not. If False, we skip that check and use only the 'globs' tuple.
[ "Tries", "to", "find", "the", "tor", "executable", "using", "the", "shell", "first", "or", "in", "in", "the", "paths", "whose", "glob", "-", "patterns", "is", "in", "the", "given", "globs", "-", "tuple", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/util.py#L102-L141
train
209,030
meejah/txtorcon
txtorcon/util.py
maybe_ip_addr
def maybe_ip_addr(addr): """ Tries to return an IPAddress, otherwise returns a string. TODO consider explicitly checking for .exit or .onion at the end? """ if six.PY2 and isinstance(addr, str): addr = unicode(addr) # noqa try: return ipaddress.ip_address(addr) except ValueError: pass return str(addr)
python
def maybe_ip_addr(addr): """ Tries to return an IPAddress, otherwise returns a string. TODO consider explicitly checking for .exit or .onion at the end? """ if six.PY2 and isinstance(addr, str): addr = unicode(addr) # noqa try: return ipaddress.ip_address(addr) except ValueError: pass return str(addr)
[ "def", "maybe_ip_addr", "(", "addr", ")", ":", "if", "six", ".", "PY2", "and", "isinstance", "(", "addr", ",", "str", ")", ":", "addr", "=", "unicode", "(", "addr", ")", "# noqa", "try", ":", "return", "ipaddress", ".", "ip_address", "(", "addr", ")"...
Tries to return an IPAddress, otherwise returns a string. TODO consider explicitly checking for .exit or .onion at the end?
[ "Tries", "to", "return", "an", "IPAddress", "otherwise", "returns", "a", "string", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/util.py#L144-L157
train
209,031
meejah/txtorcon
txtorcon/util.py
delete_file_or_tree
def delete_file_or_tree(*args): """ For every path in args, try to delete it as a file or a directory tree. Ignores deletion errors. """ for f in args: try: os.unlink(f) except OSError: shutil.rmtree(f, ignore_errors=True)
python
def delete_file_or_tree(*args): """ For every path in args, try to delete it as a file or a directory tree. Ignores deletion errors. """ for f in args: try: os.unlink(f) except OSError: shutil.rmtree(f, ignore_errors=True)
[ "def", "delete_file_or_tree", "(", "*", "args", ")", ":", "for", "f", "in", "args", ":", "try", ":", "os", ".", "unlink", "(", "f", ")", "except", "OSError", ":", "shutil", ".", "rmtree", "(", "f", ",", "ignore_errors", "=", "True", ")" ]
For every path in args, try to delete it as a file or a directory tree. Ignores deletion errors.
[ "For", "every", "path", "in", "args", "try", "to", "delete", "it", "as", "a", "file", "or", "a", "directory", "tree", ".", "Ignores", "deletion", "errors", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/util.py#L180-L190
train
209,032
meejah/txtorcon
txtorcon/util.py
available_tcp_port
def available_tcp_port(reactor): """ Returns a Deferred firing an available TCP port on localhost. It does so by listening on port 0; then stopListening and fires the assigned port number. """ endpoint = serverFromString(reactor, 'tcp:0:interface=127.0.0.1') port = yield endpoint.listen(NoOpProtocolFactory()) address = port.getHost() yield port.stopListening() defer.returnValue(address.port)
python
def available_tcp_port(reactor): """ Returns a Deferred firing an available TCP port on localhost. It does so by listening on port 0; then stopListening and fires the assigned port number. """ endpoint = serverFromString(reactor, 'tcp:0:interface=127.0.0.1') port = yield endpoint.listen(NoOpProtocolFactory()) address = port.getHost() yield port.stopListening() defer.returnValue(address.port)
[ "def", "available_tcp_port", "(", "reactor", ")", ":", "endpoint", "=", "serverFromString", "(", "reactor", ",", "'tcp:0:interface=127.0.0.1'", ")", "port", "=", "yield", "endpoint", ".", "listen", "(", "NoOpProtocolFactory", "(", ")", ")", "address", "=", "port...
Returns a Deferred firing an available TCP port on localhost. It does so by listening on port 0; then stopListening and fires the assigned port number.
[ "Returns", "a", "Deferred", "firing", "an", "available", "TCP", "port", "on", "localhost", ".", "It", "does", "so", "by", "listening", "on", "port", "0", ";", "then", "stopListening", "and", "fires", "the", "assigned", "port", "number", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/util.py#L300-L311
train
209,033
meejah/txtorcon
txtorcon/util.py
maybe_coroutine
def maybe_coroutine(obj): """ If 'obj' is a coroutine and we're using Python3, wrap it in ensureDeferred. Otherwise return the original object. (This is to insert in all callback chains from user code, in case that user code is Python3 and used 'async def') """ if six.PY3 and asyncio.iscoroutine(obj): return defer.ensureDeferred(obj) return obj
python
def maybe_coroutine(obj): """ If 'obj' is a coroutine and we're using Python3, wrap it in ensureDeferred. Otherwise return the original object. (This is to insert in all callback chains from user code, in case that user code is Python3 and used 'async def') """ if six.PY3 and asyncio.iscoroutine(obj): return defer.ensureDeferred(obj) return obj
[ "def", "maybe_coroutine", "(", "obj", ")", ":", "if", "six", ".", "PY3", "and", "asyncio", ".", "iscoroutine", "(", "obj", ")", ":", "return", "defer", ".", "ensureDeferred", "(", "obj", ")", "return", "obj" ]
If 'obj' is a coroutine and we're using Python3, wrap it in ensureDeferred. Otherwise return the original object. (This is to insert in all callback chains from user code, in case that user code is Python3 and used 'async def')
[ "If", "obj", "is", "a", "coroutine", "and", "we", "re", "using", "Python3", "wrap", "it", "in", "ensureDeferred", ".", "Otherwise", "return", "the", "original", "object", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/util.py#L380-L390
train
209,034
meejah/txtorcon
txtorcon/util.py
_is_non_public_numeric_address
def _is_non_public_numeric_address(host): """ returns True if 'host' is not public """ # for numeric hostnames, skip RFC1918 addresses, since no Tor exit # node will be able to reach those. Likewise ignore IPv6 addresses. try: a = ipaddress.ip_address(six.text_type(host)) except ValueError: return False # non-numeric, let Tor try it if a.is_loopback or a.is_multicast or a.is_private or a.is_reserved \ or a.is_unspecified: return True # too weird, don't connect return False
python
def _is_non_public_numeric_address(host): """ returns True if 'host' is not public """ # for numeric hostnames, skip RFC1918 addresses, since no Tor exit # node will be able to reach those. Likewise ignore IPv6 addresses. try: a = ipaddress.ip_address(six.text_type(host)) except ValueError: return False # non-numeric, let Tor try it if a.is_loopback or a.is_multicast or a.is_private or a.is_reserved \ or a.is_unspecified: return True # too weird, don't connect return False
[ "def", "_is_non_public_numeric_address", "(", "host", ")", ":", "# for numeric hostnames, skip RFC1918 addresses, since no Tor exit", "# node will be able to reach those. Likewise ignore IPv6 addresses.", "try", ":", "a", "=", "ipaddress", ".", "ip_address", "(", "six", ".", "tex...
returns True if 'host' is not public
[ "returns", "True", "if", "host", "is", "not", "public" ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/util.py#L515-L528
train
209,035
meejah/txtorcon
txtorcon/onion.py
_compute_permanent_id
def _compute_permanent_id(private_key): """ Internal helper. Return an authenticated service's permanent ID given an RSA private key object. The permanent ID is the base32 encoding of the SHA1 hash of the first 10 bytes (80 bits) of the public key. """ pub = private_key.public_key() p = pub.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.PKCS1 ) z = ''.join(p.decode('ascii').strip().split('\n')[1:-1]) b = base64.b64decode(z) h1 = hashlib.new('sha1') h1.update(b) permanent_id = h1.digest()[:10] return base64.b32encode(permanent_id).lower().decode('ascii')
python
def _compute_permanent_id(private_key): """ Internal helper. Return an authenticated service's permanent ID given an RSA private key object. The permanent ID is the base32 encoding of the SHA1 hash of the first 10 bytes (80 bits) of the public key. """ pub = private_key.public_key() p = pub.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.PKCS1 ) z = ''.join(p.decode('ascii').strip().split('\n')[1:-1]) b = base64.b64decode(z) h1 = hashlib.new('sha1') h1.update(b) permanent_id = h1.digest()[:10] return base64.b32encode(permanent_id).lower().decode('ascii')
[ "def", "_compute_permanent_id", "(", "private_key", ")", ":", "pub", "=", "private_key", ".", "public_key", "(", ")", "p", "=", "pub", ".", "public_bytes", "(", "encoding", "=", "serialization", ".", "Encoding", ".", "PEM", ",", "format", "=", "serialization...
Internal helper. Return an authenticated service's permanent ID given an RSA private key object. The permanent ID is the base32 encoding of the SHA1 hash of the first 10 bytes (80 bits) of the public key.
[ "Internal", "helper", ".", "Return", "an", "authenticated", "service", "s", "permanent", "ID", "given", "an", "RSA", "private", "key", "object", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/onion.py#L1053-L1071
train
209,036
meejah/txtorcon
txtorcon/onion.py
_validate_ports
def _validate_ports(reactor, ports): """ Internal helper for Onion services. Validates an incoming list of port mappings and returns a list of strings suitable for passing to other onion-services functions. Accepts 3 different ways of specifying ports: - list of ints: each int is the public port, local port random - list of 2-tuples of ints: (pubic, local) ports. - list of strings like "80 127.0.0.1:1234" This is async in case it needs to ask for a random, unallocated local port. """ if not isinstance(ports, (list, tuple)): raise ValueError("'ports' must be a list of strings, ints or 2-tuples") processed_ports = [] for port in ports: if isinstance(port, (set, list, tuple)): if len(port) != 2: raise ValueError( "'ports' must contain a single int or a 2-tuple of ints" ) remote, local = port try: remote = int(remote) except ValueError: raise ValueError( "'ports' has a tuple with a non-integer " "component: {}".format(port) ) try: local = int(local) except ValueError: if local.startswith('unix:/'): pass else: if ':' not in local: raise ValueError( "local port must be either an integer" " or start with unix:/ or be an IP:port" ) ip, port = local.split(':') if not _is_non_public_numeric_address(ip): log.msg( "'{}' used as onion port doesn't appear to be a " "local, numeric address".format(ip) ) processed_ports.append( "{} {}".format(remote, local) ) else: processed_ports.append( "{} 127.0.0.1:{}".format(remote, local) ) elif isinstance(port, (six.text_type, str)): _validate_single_port_string(port) processed_ports.append(port) else: try: remote = int(port) except (ValueError, TypeError): raise ValueError( "'ports' has a non-integer entry: {}".format(port) ) local = yield available_tcp_port(reactor) processed_ports.append( "{} 127.0.0.1:{}".format(remote, local) ) defer.returnValue(processed_ports)
python
def _validate_ports(reactor, ports): """ Internal helper for Onion services. Validates an incoming list of port mappings and returns a list of strings suitable for passing to other onion-services functions. Accepts 3 different ways of specifying ports: - list of ints: each int is the public port, local port random - list of 2-tuples of ints: (pubic, local) ports. - list of strings like "80 127.0.0.1:1234" This is async in case it needs to ask for a random, unallocated local port. """ if not isinstance(ports, (list, tuple)): raise ValueError("'ports' must be a list of strings, ints or 2-tuples") processed_ports = [] for port in ports: if isinstance(port, (set, list, tuple)): if len(port) != 2: raise ValueError( "'ports' must contain a single int or a 2-tuple of ints" ) remote, local = port try: remote = int(remote) except ValueError: raise ValueError( "'ports' has a tuple with a non-integer " "component: {}".format(port) ) try: local = int(local) except ValueError: if local.startswith('unix:/'): pass else: if ':' not in local: raise ValueError( "local port must be either an integer" " or start with unix:/ or be an IP:port" ) ip, port = local.split(':') if not _is_non_public_numeric_address(ip): log.msg( "'{}' used as onion port doesn't appear to be a " "local, numeric address".format(ip) ) processed_ports.append( "{} {}".format(remote, local) ) else: processed_ports.append( "{} 127.0.0.1:{}".format(remote, local) ) elif isinstance(port, (six.text_type, str)): _validate_single_port_string(port) processed_ports.append(port) else: try: remote = int(port) except (ValueError, TypeError): raise ValueError( "'ports' has a non-integer entry: {}".format(port) ) local = yield available_tcp_port(reactor) processed_ports.append( "{} 127.0.0.1:{}".format(remote, local) ) defer.returnValue(processed_ports)
[ "def", "_validate_ports", "(", "reactor", ",", "ports", ")", ":", "if", "not", "isinstance", "(", "ports", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "ValueError", "(", "\"'ports' must be a list of strings, ints or 2-tuples\"", ")", "processed_ports",...
Internal helper for Onion services. Validates an incoming list of port mappings and returns a list of strings suitable for passing to other onion-services functions. Accepts 3 different ways of specifying ports: - list of ints: each int is the public port, local port random - list of 2-tuples of ints: (pubic, local) ports. - list of strings like "80 127.0.0.1:1234" This is async in case it needs to ask for a random, unallocated local port.
[ "Internal", "helper", "for", "Onion", "services", ".", "Validates", "an", "incoming", "list", "of", "port", "mappings", "and", "returns", "a", "list", "of", "strings", "suitable", "for", "passing", "to", "other", "onion", "-", "services", "functions", "." ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/onion.py#L1320-L1393
train
209,037
meejah/txtorcon
txtorcon/spaghetti.py
Transition.handle
def handle(self, data): """ return next state. May override in a subclass to change behavior or pass a handler method to ctor """ if self.handler: state = self.handler(data) if state is None: return self.next_state return state return self.next_state
python
def handle(self, data): """ return next state. May override in a subclass to change behavior or pass a handler method to ctor """ if self.handler: state = self.handler(data) if state is None: return self.next_state return state return self.next_state
[ "def", "handle", "(", "self", ",", "data", ")", ":", "if", "self", ".", "handler", ":", "state", "=", "self", ".", "handler", "(", "data", ")", "if", "state", "is", "None", ":", "return", "self", ".", "next_state", "return", "state", "return", "self"...
return next state. May override in a subclass to change behavior or pass a handler method to ctor
[ "return", "next", "state", ".", "May", "override", "in", "a", "subclass", "to", "change", "behavior", "or", "pass", "a", "handler", "method", "to", "ctor" ]
14053b95adf0b4bd9dd9c317bece912a26578a93
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/spaghetti.py#L132-L142
train
209,038
fhirschmann/rdp
rdp/__init__.py
pldist
def pldist(point, start, end): """ Calculates the distance from ``point`` to the line given by the points ``start`` and ``end``. :param point: a point :type point: numpy array :param start: a point of the line :type start: numpy array :param end: another point of the line :type end: numpy array """ if np.all(np.equal(start, end)): return np.linalg.norm(point - start) return np.divide( np.abs(np.linalg.norm(np.cross(end - start, start - point))), np.linalg.norm(end - start))
python
def pldist(point, start, end): """ Calculates the distance from ``point`` to the line given by the points ``start`` and ``end``. :param point: a point :type point: numpy array :param start: a point of the line :type start: numpy array :param end: another point of the line :type end: numpy array """ if np.all(np.equal(start, end)): return np.linalg.norm(point - start) return np.divide( np.abs(np.linalg.norm(np.cross(end - start, start - point))), np.linalg.norm(end - start))
[ "def", "pldist", "(", "point", ",", "start", ",", "end", ")", ":", "if", "np", ".", "all", "(", "np", ".", "equal", "(", "start", ",", "end", ")", ")", ":", "return", "np", ".", "linalg", ".", "norm", "(", "point", "-", "start", ")", "return", ...
Calculates the distance from ``point`` to the line given by the points ``start`` and ``end``. :param point: a point :type point: numpy array :param start: a point of the line :type start: numpy array :param end: another point of the line :type end: numpy array
[ "Calculates", "the", "distance", "from", "point", "to", "the", "line", "given", "by", "the", "points", "start", "and", "end", "." ]
715a436f27c2757f15b13dcd38e8a548e7be18b2
https://github.com/fhirschmann/rdp/blob/715a436f27c2757f15b13dcd38e8a548e7be18b2/rdp/__init__.py#L20-L37
train
209,039
fhirschmann/rdp
rdp/__init__.py
rdp
def rdp(M, epsilon=0, dist=pldist, algo="iter", return_mask=False): """ Simplifies a given array of points using the Ramer-Douglas-Peucker algorithm. Example: >>> from rdp import rdp >>> rdp([[1, 1], [2, 2], [3, 3], [4, 4]]) [[1, 1], [4, 4]] This is a convenience wrapper around both :func:`rdp.rdp_iter` and :func:`rdp.rdp_rec` that detects if the input is a numpy array in order to adapt the output accordingly. This means that when it is called using a Python list as argument, a Python list is returned, and in case of an invocation using a numpy array, a NumPy array is returned. The parameter ``return_mask=True`` can be used in conjunction with ``algo="iter"`` to return only the mask of points to keep. Example: >>> from rdp import rdp >>> import numpy as np >>> arr = np.array([1, 1, 2, 2, 3, 3, 4, 4]).reshape(4, 2) >>> arr array([[1, 1], [2, 2], [3, 3], [4, 4]]) >>> mask = rdp(arr, algo="iter", return_mask=True) >>> mask array([ True, False, False, True], dtype=bool) >>> arr[mask] array([[1, 1], [4, 4]]) :param M: a series of points :type M: numpy array with shape ``(n,d)`` where ``n`` is the number of points and ``d`` their dimension :param epsilon: epsilon in the rdp algorithm :type epsilon: float :param dist: distance function :type dist: function with signature ``f(point, start, end)`` -- see :func:`rdp.pldist` :param algo: either ``iter`` for an iterative algorithm or ``rec`` for a recursive algorithm :type algo: string :param return_mask: return mask instead of simplified array :type return_mask: bool """ if algo == "iter": algo = partial(rdp_iter, return_mask=return_mask) elif algo == "rec": if return_mask: raise NotImplementedError("return_mask=True not supported with algo=\"rec\"") algo = rdp_rec if "numpy" in str(type(M)): return algo(M, epsilon, dist) return algo(np.array(M), epsilon, dist).tolist()
python
def rdp(M, epsilon=0, dist=pldist, algo="iter", return_mask=False): """ Simplifies a given array of points using the Ramer-Douglas-Peucker algorithm. Example: >>> from rdp import rdp >>> rdp([[1, 1], [2, 2], [3, 3], [4, 4]]) [[1, 1], [4, 4]] This is a convenience wrapper around both :func:`rdp.rdp_iter` and :func:`rdp.rdp_rec` that detects if the input is a numpy array in order to adapt the output accordingly. This means that when it is called using a Python list as argument, a Python list is returned, and in case of an invocation using a numpy array, a NumPy array is returned. The parameter ``return_mask=True`` can be used in conjunction with ``algo="iter"`` to return only the mask of points to keep. Example: >>> from rdp import rdp >>> import numpy as np >>> arr = np.array([1, 1, 2, 2, 3, 3, 4, 4]).reshape(4, 2) >>> arr array([[1, 1], [2, 2], [3, 3], [4, 4]]) >>> mask = rdp(arr, algo="iter", return_mask=True) >>> mask array([ True, False, False, True], dtype=bool) >>> arr[mask] array([[1, 1], [4, 4]]) :param M: a series of points :type M: numpy array with shape ``(n,d)`` where ``n`` is the number of points and ``d`` their dimension :param epsilon: epsilon in the rdp algorithm :type epsilon: float :param dist: distance function :type dist: function with signature ``f(point, start, end)`` -- see :func:`rdp.pldist` :param algo: either ``iter`` for an iterative algorithm or ``rec`` for a recursive algorithm :type algo: string :param return_mask: return mask instead of simplified array :type return_mask: bool """ if algo == "iter": algo = partial(rdp_iter, return_mask=return_mask) elif algo == "rec": if return_mask: raise NotImplementedError("return_mask=True not supported with algo=\"rec\"") algo = rdp_rec if "numpy" in str(type(M)): return algo(M, epsilon, dist) return algo(np.array(M), epsilon, dist).tolist()
[ "def", "rdp", "(", "M", ",", "epsilon", "=", "0", ",", "dist", "=", "pldist", ",", "algo", "=", "\"iter\"", ",", "return_mask", "=", "False", ")", ":", "if", "algo", "==", "\"iter\"", ":", "algo", "=", "partial", "(", "rdp_iter", ",", "return_mask", ...
Simplifies a given array of points using the Ramer-Douglas-Peucker algorithm. Example: >>> from rdp import rdp >>> rdp([[1, 1], [2, 2], [3, 3], [4, 4]]) [[1, 1], [4, 4]] This is a convenience wrapper around both :func:`rdp.rdp_iter` and :func:`rdp.rdp_rec` that detects if the input is a numpy array in order to adapt the output accordingly. This means that when it is called using a Python list as argument, a Python list is returned, and in case of an invocation using a numpy array, a NumPy array is returned. The parameter ``return_mask=True`` can be used in conjunction with ``algo="iter"`` to return only the mask of points to keep. Example: >>> from rdp import rdp >>> import numpy as np >>> arr = np.array([1, 1, 2, 2, 3, 3, 4, 4]).reshape(4, 2) >>> arr array([[1, 1], [2, 2], [3, 3], [4, 4]]) >>> mask = rdp(arr, algo="iter", return_mask=True) >>> mask array([ True, False, False, True], dtype=bool) >>> arr[mask] array([[1, 1], [4, 4]]) :param M: a series of points :type M: numpy array with shape ``(n,d)`` where ``n`` is the number of points and ``d`` their dimension :param epsilon: epsilon in the rdp algorithm :type epsilon: float :param dist: distance function :type dist: function with signature ``f(point, start, end)`` -- see :func:`rdp.pldist` :param algo: either ``iter`` for an iterative algorithm or ``rec`` for a recursive algorithm :type algo: string :param return_mask: return mask instead of simplified array :type return_mask: bool
[ "Simplifies", "a", "given", "array", "of", "points", "using", "the", "Ramer", "-", "Douglas", "-", "Peucker", "algorithm", "." ]
715a436f27c2757f15b13dcd38e8a548e7be18b2
https://github.com/fhirschmann/rdp/blob/715a436f27c2757f15b13dcd38e8a548e7be18b2/rdp/__init__.py#L124-L182
train
209,040
ppb/pursuedpybear
ppb/engine.py
GameEngine.on_start_scene
def on_start_scene(self, event: StartScene, signal: Callable[[Any], None]): """ Start a new scene. The current scene pauses. """ self.pause_scene() self.start_scene(event.new_scene, event.kwargs)
python
def on_start_scene(self, event: StartScene, signal: Callable[[Any], None]): """ Start a new scene. The current scene pauses. """ self.pause_scene() self.start_scene(event.new_scene, event.kwargs)
[ "def", "on_start_scene", "(", "self", ",", "event", ":", "StartScene", ",", "signal", ":", "Callable", "[", "[", "Any", "]", ",", "None", "]", ")", ":", "self", ".", "pause_scene", "(", ")", "self", ".", "start_scene", "(", "event", ".", "new_scene", ...
Start a new scene. The current scene pauses.
[ "Start", "a", "new", "scene", ".", "The", "current", "scene", "pauses", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/engine.py#L143-L148
train
209,041
ppb/pursuedpybear
ppb/engine.py
GameEngine.on_stop_scene
def on_stop_scene(self, event: events.StopScene, signal: Callable[[Any], None]): """ Stop a running scene. If there's a scene on the stack, it resumes. """ self.stop_scene() if self.current_scene is not None: signal(events.SceneContinued()) else: signal(events.Quit())
python
def on_stop_scene(self, event: events.StopScene, signal: Callable[[Any], None]): """ Stop a running scene. If there's a scene on the stack, it resumes. """ self.stop_scene() if self.current_scene is not None: signal(events.SceneContinued()) else: signal(events.Quit())
[ "def", "on_stop_scene", "(", "self", ",", "event", ":", "events", ".", "StopScene", ",", "signal", ":", "Callable", "[", "[", "Any", "]", ",", "None", "]", ")", ":", "self", ".", "stop_scene", "(", ")", "if", "self", ".", "current_scene", "is", "not"...
Stop a running scene. If there's a scene on the stack, it resumes.
[ "Stop", "a", "running", "scene", ".", "If", "there", "s", "a", "scene", "on", "the", "stack", "it", "resumes", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/engine.py#L150-L158
train
209,042
ppb/pursuedpybear
ppb/engine.py
GameEngine.on_replace_scene
def on_replace_scene(self, event: events.ReplaceScene, signal): """ Replace the running scene with a new one. """ self.stop_scene() self.start_scene(event.new_scene, event.kwargs)
python
def on_replace_scene(self, event: events.ReplaceScene, signal): """ Replace the running scene with a new one. """ self.stop_scene() self.start_scene(event.new_scene, event.kwargs)
[ "def", "on_replace_scene", "(", "self", ",", "event", ":", "events", ".", "ReplaceScene", ",", "signal", ")", ":", "self", ".", "stop_scene", "(", ")", "self", ".", "start_scene", "(", "event", ".", "new_scene", ",", "event", ".", "kwargs", ")" ]
Replace the running scene with a new one.
[ "Replace", "the", "running", "scene", "with", "a", "new", "one", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/engine.py#L160-L165
train
209,043
ppb/pursuedpybear
ppb/engine.py
GameEngine.register
def register(self, event_type: Union[Type, _ellipsis], callback: Callable[[], Any]): """ Register a callback to be applied to an event at time of publishing. Primarily to be used by subsystems. The callback will receive the event. Your code should modify the event in place. It does not need to return it. :param event_type: The class of an event. :param callback: A callable, must accept an event, and return no value. :return: None """ if not isinstance(event_type, type) and event_type is not ...: raise TypeError(f"{type(self)}.register requires event_type to be a type.") if not callable(callback): raise TypeError(f"{type(self)}.register requires callback to be callable.") self.event_extensions[event_type].append(callback)
python
def register(self, event_type: Union[Type, _ellipsis], callback: Callable[[], Any]): """ Register a callback to be applied to an event at time of publishing. Primarily to be used by subsystems. The callback will receive the event. Your code should modify the event in place. It does not need to return it. :param event_type: The class of an event. :param callback: A callable, must accept an event, and return no value. :return: None """ if not isinstance(event_type, type) and event_type is not ...: raise TypeError(f"{type(self)}.register requires event_type to be a type.") if not callable(callback): raise TypeError(f"{type(self)}.register requires callback to be callable.") self.event_extensions[event_type].append(callback)
[ "def", "register", "(", "self", ",", "event_type", ":", "Union", "[", "Type", ",", "_ellipsis", "]", ",", "callback", ":", "Callable", "[", "[", "]", ",", "Any", "]", ")", ":", "if", "not", "isinstance", "(", "event_type", ",", "type", ")", "and", ...
Register a callback to be applied to an event at time of publishing. Primarily to be used by subsystems. The callback will receive the event. Your code should modify the event in place. It does not need to return it. :param event_type: The class of an event. :param callback: A callable, must accept an event, and return no value. :return: None
[ "Register", "a", "callback", "to", "be", "applied", "to", "an", "event", "at", "time", "of", "publishing", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/engine.py#L189-L206
train
209,044
ppb/pursuedpybear
ppb/utils.py
_build_index
def _build_index(): """ Rebuild _module_file_index from sys.modules """ global _module_file_index _module_file_index = { mod.__file__: mod.__name__ for mod in sys.modules.values() if hasattr(mod, '__file__') and hasattr(mod, '__name__') }
python
def _build_index(): """ Rebuild _module_file_index from sys.modules """ global _module_file_index _module_file_index = { mod.__file__: mod.__name__ for mod in sys.modules.values() if hasattr(mod, '__file__') and hasattr(mod, '__name__') }
[ "def", "_build_index", "(", ")", ":", "global", "_module_file_index", "_module_file_index", "=", "{", "mod", ".", "__file__", ":", "mod", ".", "__name__", "for", "mod", "in", "sys", ".", "modules", ".", "values", "(", ")", "if", "hasattr", "(", "mod", ",...
Rebuild _module_file_index from sys.modules
[ "Rebuild", "_module_file_index", "from", "sys", ".", "modules" ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/utils.py#L11-L20
train
209,045
ppb/pursuedpybear
ppb/utils.py
LoggingMixin.logger
def logger(self): """ The logger for this class. """ # This is internal/CPython only/etc # It's also astonishingly faster than alternatives. frame = sys._getframe(1) file_name = frame.f_code.co_filename module_name = _get_module(file_name) return logging.getLogger(module_name)
python
def logger(self): """ The logger for this class. """ # This is internal/CPython only/etc # It's also astonishingly faster than alternatives. frame = sys._getframe(1) file_name = frame.f_code.co_filename module_name = _get_module(file_name) return logging.getLogger(module_name)
[ "def", "logger", "(", "self", ")", ":", "# This is internal/CPython only/etc", "# It's also astonishingly faster than alternatives.", "frame", "=", "sys", ".", "_getframe", "(", "1", ")", "file_name", "=", "frame", ".", "f_code", ".", "co_filename", "module_name", "="...
The logger for this class.
[ "The", "logger", "for", "this", "class", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/utils.py#L40-L50
train
209,046
ppb/pursuedpybear
ppb/features/animation.py
Animation.pause
def pause(self): """ Pause the animation. """ if not self._pause_level: self._paused_time = self._clock() + self._offset self._paused_frame = self.current_frame self._pause_level += 1
python
def pause(self): """ Pause the animation. """ if not self._pause_level: self._paused_time = self._clock() + self._offset self._paused_frame = self.current_frame self._pause_level += 1
[ "def", "pause", "(", "self", ")", ":", "if", "not", "self", ".", "_pause_level", ":", "self", ".", "_paused_time", "=", "self", ".", "_clock", "(", ")", "+", "self", ".", "_offset", "self", ".", "_paused_frame", "=", "self", ".", "current_frame", "self...
Pause the animation.
[ "Pause", "the", "animation", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/features/animation.py#L72-L79
train
209,047
ppb/pursuedpybear
ppb/features/animation.py
Animation.unpause
def unpause(self): """ Unpause the animation. """ self._pause_level -= 1 if not self._pause_level: self._offset = self._paused_time - self._clock()
python
def unpause(self): """ Unpause the animation. """ self._pause_level -= 1 if not self._pause_level: self._offset = self._paused_time - self._clock()
[ "def", "unpause", "(", "self", ")", ":", "self", ".", "_pause_level", "-=", "1", "if", "not", "self", ".", "_pause_level", ":", "self", ".", "_offset", "=", "self", ".", "_paused_time", "-", "self", ".", "_clock", "(", ")" ]
Unpause the animation.
[ "Unpause", "the", "animation", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/features/animation.py#L81-L87
train
209,048
ppb/pursuedpybear
ppb/__init__.py
run
def run(setup: Callable[[BaseScene], None]=None, *, log_level=logging.WARNING, starting_scene=BaseScene): """ Run a small game. The resolution will 800 pixels wide by 600 pixels tall. setup is a callable that accepts a scene and returns None. log_level let's you set the expected log level. Consider logging.DEBUG if something is behaving oddly. starting_scene let's you change the scene used by the engine. """ logging.basicConfig(level=log_level) kwargs = { "resolution": (800, 600), "scene_kwargs": { "set_up": setup, } } with GameEngine(starting_scene, **kwargs) as eng: eng.run()
python
def run(setup: Callable[[BaseScene], None]=None, *, log_level=logging.WARNING, starting_scene=BaseScene): """ Run a small game. The resolution will 800 pixels wide by 600 pixels tall. setup is a callable that accepts a scene and returns None. log_level let's you set the expected log level. Consider logging.DEBUG if something is behaving oddly. starting_scene let's you change the scene used by the engine. """ logging.basicConfig(level=log_level) kwargs = { "resolution": (800, 600), "scene_kwargs": { "set_up": setup, } } with GameEngine(starting_scene, **kwargs) as eng: eng.run()
[ "def", "run", "(", "setup", ":", "Callable", "[", "[", "BaseScene", "]", ",", "None", "]", "=", "None", ",", "*", ",", "log_level", "=", "logging", ".", "WARNING", ",", "starting_scene", "=", "BaseScene", ")", ":", "logging", ".", "basicConfig", "(", ...
Run a small game. The resolution will 800 pixels wide by 600 pixels tall. setup is a callable that accepts a scene and returns None. log_level let's you set the expected log level. Consider logging.DEBUG if something is behaving oddly. starting_scene let's you change the scene used by the engine.
[ "Run", "a", "small", "game", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/__init__.py#L10-L34
train
209,049
ppb/pursuedpybear
ppb/scenes.py
GameObjectCollection.add
def add(self, game_object: Hashable, tags: Iterable[Hashable]=()) -> None: """ Add a game_object to the container. game_object: Any Hashable object. The item to be added. tags: An iterable of Hashable objects. Values that can be used to retrieve a group containing the game_object. Examples: container.add(MyObject()) container.add(MyObject(), tags=("red", "blue") """ if isinstance(tags, (str, bytes)): raise TypeError("You passed a string instead of an iterable, this probably isn't what you intended.\n\nTry making it a tuple.") self.all.add(game_object) for kind in type(game_object).mro(): self.kinds[kind].add(game_object) for tag in tags: self.tags[tag].add(game_object)
python
def add(self, game_object: Hashable, tags: Iterable[Hashable]=()) -> None: """ Add a game_object to the container. game_object: Any Hashable object. The item to be added. tags: An iterable of Hashable objects. Values that can be used to retrieve a group containing the game_object. Examples: container.add(MyObject()) container.add(MyObject(), tags=("red", "blue") """ if isinstance(tags, (str, bytes)): raise TypeError("You passed a string instead of an iterable, this probably isn't what you intended.\n\nTry making it a tuple.") self.all.add(game_object) for kind in type(game_object).mro(): self.kinds[kind].add(game_object) for tag in tags: self.tags[tag].add(game_object)
[ "def", "add", "(", "self", ",", "game_object", ":", "Hashable", ",", "tags", ":", "Iterable", "[", "Hashable", "]", "=", "(", ")", ")", "->", "None", ":", "if", "isinstance", "(", "tags", ",", "(", "str", ",", "bytes", ")", ")", ":", "raise", "Ty...
Add a game_object to the container. game_object: Any Hashable object. The item to be added. tags: An iterable of Hashable objects. Values that can be used to retrieve a group containing the game_object. Examples: container.add(MyObject()) container.add(MyObject(), tags=("red", "blue")
[ "Add", "a", "game_object", "to", "the", "container", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/scenes.py#L35-L55
train
209,050
ppb/pursuedpybear
ppb/scenes.py
GameObjectCollection.get
def get(self, *, kind: Type=None, tag: Hashable=None, **_) -> Iterator: """ Get an iterator of objects by kind or tag. kind: Any type. Pass to get a subset of contained items with the given type. tag: Any Hashable object. Pass to get a subset of contained items with the given tag. Pass both kind and tag to get objects that are both that type and that tag. Examples: container.get(type=MyObject) container.get(tag="red") container.get(type=MyObject, tag="red") """ if kind is None and tag is None: raise TypeError("get() takes at least one keyword-only argument. 'kind' or 'tag'.") kinds = self.all tags = self.all if kind is not None: kinds = self.kinds[kind] if tag is not None: tags = self.tags[tag] return (x for x in kinds.intersection(tags))
python
def get(self, *, kind: Type=None, tag: Hashable=None, **_) -> Iterator: """ Get an iterator of objects by kind or tag. kind: Any type. Pass to get a subset of contained items with the given type. tag: Any Hashable object. Pass to get a subset of contained items with the given tag. Pass both kind and tag to get objects that are both that type and that tag. Examples: container.get(type=MyObject) container.get(tag="red") container.get(type=MyObject, tag="red") """ if kind is None and tag is None: raise TypeError("get() takes at least one keyword-only argument. 'kind' or 'tag'.") kinds = self.all tags = self.all if kind is not None: kinds = self.kinds[kind] if tag is not None: tags = self.tags[tag] return (x for x in kinds.intersection(tags))
[ "def", "get", "(", "self", ",", "*", ",", "kind", ":", "Type", "=", "None", ",", "tag", ":", "Hashable", "=", "None", ",", "*", "*", "_", ")", "->", "Iterator", ":", "if", "kind", "is", "None", "and", "tag", "is", "None", ":", "raise", "TypeErr...
Get an iterator of objects by kind or tag. kind: Any type. Pass to get a subset of contained items with the given type. tag: Any Hashable object. Pass to get a subset of contained items with the given tag. Pass both kind and tag to get objects that are both that type and that tag. Examples: container.get(type=MyObject) container.get(tag="red") container.get(type=MyObject, tag="red")
[ "Get", "an", "iterator", "of", "objects", "by", "kind", "or", "tag", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/scenes.py#L57-L84
train
209,051
ppb/pursuedpybear
ppb/scenes.py
GameObjectCollection.remove
def remove(self, game_object: Hashable) -> None: """ Remove the given object from the container. game_object: A hashable contained by container. Example: container.remove(myObject) """ self.all.remove(game_object) for kind in type(game_object).mro(): self.kinds[kind].remove(game_object) for s in self.tags.values(): s.discard(game_object)
python
def remove(self, game_object: Hashable) -> None: """ Remove the given object from the container. game_object: A hashable contained by container. Example: container.remove(myObject) """ self.all.remove(game_object) for kind in type(game_object).mro(): self.kinds[kind].remove(game_object) for s in self.tags.values(): s.discard(game_object)
[ "def", "remove", "(", "self", ",", "game_object", ":", "Hashable", ")", "->", "None", ":", "self", ".", "all", ".", "remove", "(", "game_object", ")", "for", "kind", "in", "type", "(", "game_object", ")", ".", "mro", "(", ")", ":", "self", ".", "ki...
Remove the given object from the container. game_object: A hashable contained by container. Example: container.remove(myObject)
[ "Remove", "the", "given", "object", "from", "the", "container", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/scenes.py#L86-L99
train
209,052
ppb/pursuedpybear
ppb/scenes.py
BaseScene.change
def change(self) -> Tuple[bool, dict]: """ Default case, override in subclass as necessary. """ next = self.next self.next = None if self.next or not self.running: message = "The Scene.change interface is deprecated. Use the events commands instead." warn(message, DeprecationWarning) return self.running, {"scene_class": next}
python
def change(self) -> Tuple[bool, dict]: """ Default case, override in subclass as necessary. """ next = self.next self.next = None if self.next or not self.running: message = "The Scene.change interface is deprecated. Use the events commands instead." warn(message, DeprecationWarning) return self.running, {"scene_class": next}
[ "def", "change", "(", "self", ")", "->", "Tuple", "[", "bool", ",", "dict", "]", ":", "next", "=", "self", ".", "next", "self", ".", "next", "=", "None", "if", "self", ".", "next", "or", "not", "self", ".", "running", ":", "message", "=", "\"The ...
Default case, override in subclass as necessary.
[ "Default", "case", "override", "in", "subclass", "as", "necessary", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/scenes.py#L144-L154
train
209,053
ppb/pursuedpybear
ppb/scenes.py
BaseScene.add
def add(self, game_object: Hashable, tags: Iterable=())-> None: """ Add a game_object to the scene. game_object: Any GameObject object. The item to be added. tags: An iterable of Hashable objects. Values that can be used to retrieve a group containing the game_object. Examples: scene.add(MyGameObject()) scene.add(MyGameObject(), tags=("red", "blue") """ self.game_objects.add(game_object, tags)
python
def add(self, game_object: Hashable, tags: Iterable=())-> None: """ Add a game_object to the scene. game_object: Any GameObject object. The item to be added. tags: An iterable of Hashable objects. Values that can be used to retrieve a group containing the game_object. Examples: scene.add(MyGameObject()) scene.add(MyGameObject(), tags=("red", "blue") """ self.game_objects.add(game_object, tags)
[ "def", "add", "(", "self", ",", "game_object", ":", "Hashable", ",", "tags", ":", "Iterable", "=", "(", ")", ")", "->", "None", ":", "self", ".", "game_objects", ".", "add", "(", "game_object", ",", "tags", ")" ]
Add a game_object to the scene. game_object: Any GameObject object. The item to be added. tags: An iterable of Hashable objects. Values that can be used to retrieve a group containing the game_object. Examples: scene.add(MyGameObject()) scene.add(MyGameObject(), tags=("red", "blue")
[ "Add", "a", "game_object", "to", "the", "scene", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/scenes.py#L156-L169
train
209,054
ppb/pursuedpybear
ppb/scenes.py
BaseScene.get
def get(self, *, kind: Type=None, tag: Hashable=None, **kwargs) -> Iterator: """ Get an iterator of GameObjects by kind or tag. kind: Any type. Pass to get a subset of contained GameObjects with the given type. tag: Any Hashable object. Pass to get a subset of contained GameObjects with the given tag. Pass both kind and tag to get objects that are both that type and that tag. Examples: scene.get(type=MyGameObject) scene.get(tag="red") scene.get(type=MyGameObject, tag="red") """ return self.game_objects.get(kind=kind, tag=tag, **kwargs)
python
def get(self, *, kind: Type=None, tag: Hashable=None, **kwargs) -> Iterator: """ Get an iterator of GameObjects by kind or tag. kind: Any type. Pass to get a subset of contained GameObjects with the given type. tag: Any Hashable object. Pass to get a subset of contained GameObjects with the given tag. Pass both kind and tag to get objects that are both that type and that tag. Examples: scene.get(type=MyGameObject) scene.get(tag="red") scene.get(type=MyGameObject, tag="red") """ return self.game_objects.get(kind=kind, tag=tag, **kwargs)
[ "def", "get", "(", "self", ",", "*", ",", "kind", ":", "Type", "=", "None", ",", "tag", ":", "Hashable", "=", "None", ",", "*", "*", "kwargs", ")", "->", "Iterator", ":", "return", "self", ".", "game_objects", ".", "get", "(", "kind", "=", "kind"...
Get an iterator of GameObjects by kind or tag. kind: Any type. Pass to get a subset of contained GameObjects with the given type. tag: Any Hashable object. Pass to get a subset of contained GameObjects with the given tag. Pass both kind and tag to get objects that are both that type and that tag. Examples: scene.get(type=MyGameObject) scene.get(tag="red") scene.get(type=MyGameObject, tag="red")
[ "Get", "an", "iterator", "of", "GameObjects", "by", "kind", "or", "tag", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/scenes.py#L171-L190
train
209,055
ppb/pursuedpybear
setup.py
requirements
def requirements(section=None): """Helper for loading dependencies from requirements files.""" if section is None: filename = "requirements.txt" else: filename = f"requirements-{section}.txt" with open(filename) as file: return [line.strip() for line in file]
python
def requirements(section=None): """Helper for loading dependencies from requirements files.""" if section is None: filename = "requirements.txt" else: filename = f"requirements-{section}.txt" with open(filename) as file: return [line.strip() for line in file]
[ "def", "requirements", "(", "section", "=", "None", ")", ":", "if", "section", "is", "None", ":", "filename", "=", "\"requirements.txt\"", "else", ":", "filename", "=", "f\"requirements-{section}.txt\"", "with", "open", "(", "filename", ")", "as", "file", ":",...
Helper for loading dependencies from requirements files.
[ "Helper", "for", "loading", "dependencies", "from", "requirements", "files", "." ]
db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191
https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/setup.py#L5-L13
train
209,056
jcushman/pdfquery
pdfquery/cache.py
BaseCache.set_hash_key
def set_hash_key(self, file): """Calculate and store hash key for file.""" filehasher = hashlib.md5() while True: data = file.read(8192) if not data: break filehasher.update(data) file.seek(0) self.hash_key = filehasher.hexdigest()
python
def set_hash_key(self, file): """Calculate and store hash key for file.""" filehasher = hashlib.md5() while True: data = file.read(8192) if not data: break filehasher.update(data) file.seek(0) self.hash_key = filehasher.hexdigest()
[ "def", "set_hash_key", "(", "self", ",", "file", ")", ":", "filehasher", "=", "hashlib", ".", "md5", "(", ")", "while", "True", ":", "data", "=", "file", ".", "read", "(", "8192", ")", "if", "not", "data", ":", "break", "filehasher", ".", "update", ...
Calculate and store hash key for file.
[ "Calculate", "and", "store", "hash", "key", "for", "file", "." ]
f1c05d15e0c1b7c523a0971bc89b5610d8560f79
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/cache.py#L10-L19
train
209,057
jcushman/pdfquery
pdfquery/pdfquery.py
_box_in_box
def _box_in_box(el, child): """ Return True if child is contained within el. """ return all([ float(el.get('x0')) <= float(child.get('x0')), float(el.get('x1')) >= float(child.get('x1')), float(el.get('y0')) <= float(child.get('y0')), float(el.get('y1')) >= float(child.get('y1')), ])
python
def _box_in_box(el, child): """ Return True if child is contained within el. """ return all([ float(el.get('x0')) <= float(child.get('x0')), float(el.get('x1')) >= float(child.get('x1')), float(el.get('y0')) <= float(child.get('y0')), float(el.get('y1')) >= float(child.get('y1')), ])
[ "def", "_box_in_box", "(", "el", ",", "child", ")", ":", "return", "all", "(", "[", "float", "(", "el", ".", "get", "(", "'x0'", ")", ")", "<=", "float", "(", "child", ".", "get", "(", "'x0'", ")", ")", ",", "float", "(", "el", ".", "get", "(...
Return True if child is contained within el.
[ "Return", "True", "if", "child", "is", "contained", "within", "el", "." ]
f1c05d15e0c1b7c523a0971bc89b5610d8560f79
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L63-L70
train
209,058
jcushman/pdfquery
pdfquery/pdfquery.py
_comp_bbox
def _comp_bbox(el, el2): """ Return 1 if el in el2, -1 if el2 in el, else 0""" # only compare if both elements have x/y coordinates if _comp_bbox_keys_required <= set(el.keys()) and \ _comp_bbox_keys_required <= set(el2.keys()): if _box_in_box(el2, el): return 1 if _box_in_box(el, el2): return -1 return 0
python
def _comp_bbox(el, el2): """ Return 1 if el in el2, -1 if el2 in el, else 0""" # only compare if both elements have x/y coordinates if _comp_bbox_keys_required <= set(el.keys()) and \ _comp_bbox_keys_required <= set(el2.keys()): if _box_in_box(el2, el): return 1 if _box_in_box(el, el2): return -1 return 0
[ "def", "_comp_bbox", "(", "el", ",", "el2", ")", ":", "# only compare if both elements have x/y coordinates\r", "if", "_comp_bbox_keys_required", "<=", "set", "(", "el", ".", "keys", "(", ")", ")", "and", "_comp_bbox_keys_required", "<=", "set", "(", "el2", ".", ...
Return 1 if el in el2, -1 if el2 in el, else 0
[ "Return", "1", "if", "el", "in", "el2", "-", "1", "if", "el2", "in", "el", "else", "0" ]
f1c05d15e0c1b7c523a0971bc89b5610d8560f79
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L74-L83
train
209,059
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery.get_pyquery
def get_pyquery(self, tree=None, page_numbers=None): """ Wrap given tree in pyquery and return. If no tree supplied, will generate one from given page_numbers, or all page numbers. """ if not page_numbers: page_numbers = [] if tree is None: if not page_numbers and self.tree is not None: tree = self.tree else: tree = self.get_tree(page_numbers) if hasattr(tree, 'getroot'): tree = tree.getroot() return PyQuery(tree, css_translator=PDFQueryTranslator())
python
def get_pyquery(self, tree=None, page_numbers=None): """ Wrap given tree in pyquery and return. If no tree supplied, will generate one from given page_numbers, or all page numbers. """ if not page_numbers: page_numbers = [] if tree is None: if not page_numbers and self.tree is not None: tree = self.tree else: tree = self.get_tree(page_numbers) if hasattr(tree, 'getroot'): tree = tree.getroot() return PyQuery(tree, css_translator=PDFQueryTranslator())
[ "def", "get_pyquery", "(", "self", ",", "tree", "=", "None", ",", "page_numbers", "=", "None", ")", ":", "if", "not", "page_numbers", ":", "page_numbers", "=", "[", "]", "if", "tree", "is", "None", ":", "if", "not", "page_numbers", "and", "self", ".", ...
Wrap given tree in pyquery and return. If no tree supplied, will generate one from given page_numbers, or all page numbers.
[ "Wrap", "given", "tree", "in", "pyquery", "and", "return", ".", "If", "no", "tree", "supplied", "will", "generate", "one", "from", "given", "page_numbers", "or", "all", "page", "numbers", "." ]
f1c05d15e0c1b7c523a0971bc89b5610d8560f79
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L439-L454
train
209,060
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery.get_tree
def get_tree(self, *page_numbers): """ Return lxml.etree.ElementTree for entire document, or page numbers given if any. """ cache_key = "_".join(map(str, _flatten(page_numbers))) tree = self._parse_tree_cacher.get(cache_key) if tree is None: # set up root root = parser.makeelement("pdfxml") if self.doc.info: for k, v in list(self.doc.info[0].items()): k = obj_to_string(k) v = obj_to_string(resolve1(v)) try: root.set(k, v) except ValueError as e: # Sometimes keys have a character in them, like ':', # that isn't allowed in XML attribute names. # If that happens we just replace non-word characters # with '_'. if "Invalid attribute name" in e.args[0]: k = re.sub('\W', '_', k) root.set(k, v) # Parse pages and append to root. # If nothing was passed in for page_numbers, we do this for all # pages, but if None was explicitly passed in, we skip it. if not(len(page_numbers) == 1 and page_numbers[0] is None): if page_numbers: pages = [[n, self.get_layout(self.get_page(n))] for n in _flatten(page_numbers)] else: pages = enumerate(self.get_layouts()) for n, page in pages: page = self._xmlize(page) page.set('page_index', obj_to_string(n)) page.set('page_label', self.doc.get_page_number(n)) root.append(page) self._clean_text(root) # wrap root in ElementTree tree = etree.ElementTree(root) self._parse_tree_cacher.set(cache_key, tree) return tree
python
def get_tree(self, *page_numbers): """ Return lxml.etree.ElementTree for entire document, or page numbers given if any. """ cache_key = "_".join(map(str, _flatten(page_numbers))) tree = self._parse_tree_cacher.get(cache_key) if tree is None: # set up root root = parser.makeelement("pdfxml") if self.doc.info: for k, v in list(self.doc.info[0].items()): k = obj_to_string(k) v = obj_to_string(resolve1(v)) try: root.set(k, v) except ValueError as e: # Sometimes keys have a character in them, like ':', # that isn't allowed in XML attribute names. # If that happens we just replace non-word characters # with '_'. if "Invalid attribute name" in e.args[0]: k = re.sub('\W', '_', k) root.set(k, v) # Parse pages and append to root. # If nothing was passed in for page_numbers, we do this for all # pages, but if None was explicitly passed in, we skip it. if not(len(page_numbers) == 1 and page_numbers[0] is None): if page_numbers: pages = [[n, self.get_layout(self.get_page(n))] for n in _flatten(page_numbers)] else: pages = enumerate(self.get_layouts()) for n, page in pages: page = self._xmlize(page) page.set('page_index', obj_to_string(n)) page.set('page_label', self.doc.get_page_number(n)) root.append(page) self._clean_text(root) # wrap root in ElementTree tree = etree.ElementTree(root) self._parse_tree_cacher.set(cache_key, tree) return tree
[ "def", "get_tree", "(", "self", ",", "*", "page_numbers", ")", ":", "cache_key", "=", "\"_\"", ".", "join", "(", "map", "(", "str", ",", "_flatten", "(", "page_numbers", ")", ")", ")", "tree", "=", "self", ".", "_parse_tree_cacher", ".", "get", "(", ...
Return lxml.etree.ElementTree for entire document, or page numbers given if any.
[ "Return", "lxml", ".", "etree", ".", "ElementTree", "for", "entire", "document", "or", "page", "numbers", "given", "if", "any", "." ]
f1c05d15e0c1b7c523a0971bc89b5610d8560f79
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L456-L501
train
209,061
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery._clean_text
def _clean_text(self, branch): """ Remove text from node if same text exists in its children. Apply string formatter if set. """ if branch.text and self.input_text_formatter: branch.text = self.input_text_formatter(branch.text) try: for child in branch: self._clean_text(child) if branch.text and branch.text.find(child.text) >= 0: branch.text = branch.text.replace(child.text, '', 1) except TypeError: # not an iterable node pass
python
def _clean_text(self, branch): """ Remove text from node if same text exists in its children. Apply string formatter if set. """ if branch.text and self.input_text_formatter: branch.text = self.input_text_formatter(branch.text) try: for child in branch: self._clean_text(child) if branch.text and branch.text.find(child.text) >= 0: branch.text = branch.text.replace(child.text, '', 1) except TypeError: # not an iterable node pass
[ "def", "_clean_text", "(", "self", ",", "branch", ")", ":", "if", "branch", ".", "text", "and", "self", ".", "input_text_formatter", ":", "branch", ".", "text", "=", "self", ".", "input_text_formatter", "(", "branch", ".", "text", ")", "try", ":", "for",...
Remove text from node if same text exists in its children. Apply string formatter if set.
[ "Remove", "text", "from", "node", "if", "same", "text", "exists", "in", "its", "children", ".", "Apply", "string", "formatter", "if", "set", "." ]
f1c05d15e0c1b7c523a0971bc89b5610d8560f79
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L503-L516
train
209,062
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery.get_layout
def get_layout(self, page): """ Get PDFMiner Layout object for given page object or page number. """ if type(page) == int: page = self.get_page(page) self.interpreter.process_page(page) layout = self.device.get_result() layout = self._add_annots(layout, page.annots) return layout
python
def get_layout(self, page): """ Get PDFMiner Layout object for given page object or page number. """ if type(page) == int: page = self.get_page(page) self.interpreter.process_page(page) layout = self.device.get_result() layout = self._add_annots(layout, page.annots) return layout
[ "def", "get_layout", "(", "self", ",", "page", ")", ":", "if", "type", "(", "page", ")", "==", "int", ":", "page", "=", "self", ".", "get_page", "(", "page", ")", "self", ".", "interpreter", ".", "process_page", "(", "page", ")", "layout", "=", "se...
Get PDFMiner Layout object for given page object or page number.
[ "Get", "PDFMiner", "Layout", "object", "for", "given", "page", "object", "or", "page", "number", "." ]
f1c05d15e0c1b7c523a0971bc89b5610d8560f79
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L600-L607
train
209,063
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery._cached_pages
def _cached_pages(self, target_page=-1): """ Get a page or all pages from page generator, caching results. This is necessary because PDFMiner searches recursively for pages, so we won't know how many there are until we parse the whole document, which we don't want to do until we need to. """ try: # pdfminer < 20131022 self._pages_iter = self._pages_iter or self.doc.get_pages() except AttributeError: # pdfminer >= 20131022 self._pages_iter = self._pages_iter or \ PDFPage.create_pages(self.doc) if target_page >= 0: while len(self._pages) <= target_page: next_page = next(self._pages_iter) if not next_page: return None next_page.page_number = 0 self._pages += [next_page] try: return self._pages[target_page] except IndexError: return None self._pages += list(self._pages_iter) return self._pages
python
def _cached_pages(self, target_page=-1): """ Get a page or all pages from page generator, caching results. This is necessary because PDFMiner searches recursively for pages, so we won't know how many there are until we parse the whole document, which we don't want to do until we need to. """ try: # pdfminer < 20131022 self._pages_iter = self._pages_iter or self.doc.get_pages() except AttributeError: # pdfminer >= 20131022 self._pages_iter = self._pages_iter or \ PDFPage.create_pages(self.doc) if target_page >= 0: while len(self._pages) <= target_page: next_page = next(self._pages_iter) if not next_page: return None next_page.page_number = 0 self._pages += [next_page] try: return self._pages[target_page] except IndexError: return None self._pages += list(self._pages_iter) return self._pages
[ "def", "_cached_pages", "(", "self", ",", "target_page", "=", "-", "1", ")", ":", "try", ":", "# pdfminer < 20131022\r", "self", ".", "_pages_iter", "=", "self", ".", "_pages_iter", "or", "self", ".", "doc", ".", "get_pages", "(", ")", "except", "Attribute...
Get a page or all pages from page generator, caching results. This is necessary because PDFMiner searches recursively for pages, so we won't know how many there are until we parse the whole document, which we don't want to do until we need to.
[ "Get", "a", "page", "or", "all", "pages", "from", "page", "generator", "caching", "results", ".", "This", "is", "necessary", "because", "PDFMiner", "searches", "recursively", "for", "pages", "so", "we", "won", "t", "know", "how", "many", "there", "are", "u...
f1c05d15e0c1b7c523a0971bc89b5610d8560f79
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L613-L640
train
209,064
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery._add_annots
def _add_annots(self, layout, annots): """Adds annotations to the layout object """ if annots: for annot in resolve1(annots): annot = resolve1(annot) if annot.get('Rect') is not None: annot['bbox'] = annot.pop('Rect') # Rename key annot = self._set_hwxy_attrs(annot) try: annot['URI'] = resolve1(annot['A'])['URI'] except KeyError: pass for k, v in six.iteritems(annot): if not isinstance(v, six.string_types): annot[k] = obj_to_string(v) elem = parser.makeelement('Annot', annot) layout.add(elem) return layout
python
def _add_annots(self, layout, annots): """Adds annotations to the layout object """ if annots: for annot in resolve1(annots): annot = resolve1(annot) if annot.get('Rect') is not None: annot['bbox'] = annot.pop('Rect') # Rename key annot = self._set_hwxy_attrs(annot) try: annot['URI'] = resolve1(annot['A'])['URI'] except KeyError: pass for k, v in six.iteritems(annot): if not isinstance(v, six.string_types): annot[k] = obj_to_string(v) elem = parser.makeelement('Annot', annot) layout.add(elem) return layout
[ "def", "_add_annots", "(", "self", ",", "layout", ",", "annots", ")", ":", "if", "annots", ":", "for", "annot", "in", "resolve1", "(", "annots", ")", ":", "annot", "=", "resolve1", "(", "annot", ")", "if", "annot", ".", "get", "(", "'Rect'", ")", "...
Adds annotations to the layout object
[ "Adds", "annotations", "to", "the", "layout", "object" ]
f1c05d15e0c1b7c523a0971bc89b5610d8560f79
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L642-L660
train
209,065
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery._set_hwxy_attrs
def _set_hwxy_attrs(attr): """Using the bbox attribute, set the h, w, x0, x1, y0, and y1 attributes. """ bbox = attr['bbox'] attr['x0'] = bbox[0] attr['x1'] = bbox[2] attr['y0'] = bbox[1] attr['y1'] = bbox[3] attr['height'] = attr['y1'] - attr['y0'] attr['width'] = attr['x1'] - attr['x0'] return attr
python
def _set_hwxy_attrs(attr): """Using the bbox attribute, set the h, w, x0, x1, y0, and y1 attributes. """ bbox = attr['bbox'] attr['x0'] = bbox[0] attr['x1'] = bbox[2] attr['y0'] = bbox[1] attr['y1'] = bbox[3] attr['height'] = attr['y1'] - attr['y0'] attr['width'] = attr['x1'] - attr['x0'] return attr
[ "def", "_set_hwxy_attrs", "(", "attr", ")", ":", "bbox", "=", "attr", "[", "'bbox'", "]", "attr", "[", "'x0'", "]", "=", "bbox", "[", "0", "]", "attr", "[", "'x1'", "]", "=", "bbox", "[", "2", "]", "attr", "[", "'y0'", "]", "=", "bbox", "[", ...
Using the bbox attribute, set the h, w, x0, x1, y0, and y1 attributes.
[ "Using", "the", "bbox", "attribute", "set", "the", "h", "w", "x0", "x1", "y0", "and", "y1", "attributes", "." ]
f1c05d15e0c1b7c523a0971bc89b5610d8560f79
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L663-L674
train
209,066
Rockhopper-Technologies/enlighten
enlighten/_win_terminal.py
_check_bool
def _check_bool(result, func, args): # pylint: disable=unused-argument """ Used as an error handler for Windows calls Gets last error if call is not successful """ if not result: raise ctypes.WinError(ctypes.get_last_error()) return args
python
def _check_bool(result, func, args): # pylint: disable=unused-argument """ Used as an error handler for Windows calls Gets last error if call is not successful """ if not result: raise ctypes.WinError(ctypes.get_last_error()) return args
[ "def", "_check_bool", "(", "result", ",", "func", ",", "args", ")", ":", "# pylint: disable=unused-argument", "if", "not", "result", ":", "raise", "ctypes", ".", "WinError", "(", "ctypes", ".", "get_last_error", "(", ")", ")", "return", "args" ]
Used as an error handler for Windows calls Gets last error if call is not successful
[ "Used", "as", "an", "error", "handler", "for", "Windows", "calls", "Gets", "last", "error", "if", "call", "is", "not", "successful" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_win_terminal.py#L64-L72
train
209,067
Rockhopper-Technologies/enlighten
enlighten/_win_terminal.py
get_csbi
def get_csbi(filehandle=None): """ Returns a CONSOLE_SCREEN_BUFFER_INFO structure for the given console or stdout """ if filehandle is None: filehandle = msvcrt.get_osfhandle(sys.__stdout__.fileno()) csbi = ConsoleScreenBufferInfo() KERNEL32.GetConsoleScreenBufferInfo(filehandle, ctypes.byref(csbi)) return csbi
python
def get_csbi(filehandle=None): """ Returns a CONSOLE_SCREEN_BUFFER_INFO structure for the given console or stdout """ if filehandle is None: filehandle = msvcrt.get_osfhandle(sys.__stdout__.fileno()) csbi = ConsoleScreenBufferInfo() KERNEL32.GetConsoleScreenBufferInfo(filehandle, ctypes.byref(csbi)) return csbi
[ "def", "get_csbi", "(", "filehandle", "=", "None", ")", ":", "if", "filehandle", "is", "None", ":", "filehandle", "=", "msvcrt", ".", "get_osfhandle", "(", "sys", ".", "__stdout__", ".", "fileno", "(", ")", ")", "csbi", "=", "ConsoleScreenBufferInfo", "(",...
Returns a CONSOLE_SCREEN_BUFFER_INFO structure for the given console or stdout
[ "Returns", "a", "CONSOLE_SCREEN_BUFFER_INFO", "structure", "for", "the", "given", "console", "or", "stdout" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_win_terminal.py#L87-L97
train
209,068
Rockhopper-Technologies/enlighten
enlighten/_win_terminal.py
enable_vt_mode
def enable_vt_mode(filehandle=None): """ Enables virtual terminal processing mode for the given console or stdout """ if filehandle is None: filehandle = msvcrt.get_osfhandle(sys.__stdout__.fileno()) current_mode = wintypes.DWORD() KERNEL32.GetConsoleMode(filehandle, ctypes.byref(current_mode)) new_mode = 0x0004 | current_mode.value KERNEL32.SetConsoleMode(filehandle, new_mode)
python
def enable_vt_mode(filehandle=None): """ Enables virtual terminal processing mode for the given console or stdout """ if filehandle is None: filehandle = msvcrt.get_osfhandle(sys.__stdout__.fileno()) current_mode = wintypes.DWORD() KERNEL32.GetConsoleMode(filehandle, ctypes.byref(current_mode)) new_mode = 0x0004 | current_mode.value KERNEL32.SetConsoleMode(filehandle, new_mode)
[ "def", "enable_vt_mode", "(", "filehandle", "=", "None", ")", ":", "if", "filehandle", "is", "None", ":", "filehandle", "=", "msvcrt", ".", "get_osfhandle", "(", "sys", ".", "__stdout__", ".", "fileno", "(", ")", ")", "current_mode", "=", "wintypes", ".", ...
Enables virtual terminal processing mode for the given console or stdout
[ "Enables", "virtual", "terminal", "processing", "mode", "for", "the", "given", "console", "or", "stdout" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_win_terminal.py#L100-L111
train
209,069
Rockhopper-Technologies/enlighten
enlighten/_win_terminal.py
create_color_method
def create_color_method(color, code): """ Create a function for the given color Done inside this function to keep the variables out of the main scope """ def func(self, content=''): return self._apply_color(code, content) # pylint: disable=protected-access setattr(Terminal, color, func)
python
def create_color_method(color, code): """ Create a function for the given color Done inside this function to keep the variables out of the main scope """ def func(self, content=''): return self._apply_color(code, content) # pylint: disable=protected-access setattr(Terminal, color, func)
[ "def", "create_color_method", "(", "color", ",", "code", ")", ":", "def", "func", "(", "self", ",", "content", "=", "''", ")", ":", "return", "self", ".", "_apply_color", "(", "code", ",", "content", ")", "# pylint: disable=protected-access", "setattr", "(",...
Create a function for the given color Done inside this function to keep the variables out of the main scope
[ "Create", "a", "function", "for", "the", "given", "color", "Done", "inside", "this", "function", "to", "keep", "the", "variables", "out", "of", "the", "main", "scope" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_win_terminal.py#L218-L227
train
209,070
Rockhopper-Technologies/enlighten
enlighten/_win_terminal.py
Terminal._apply_color
def _apply_color(code, content): """ Apply a color code to text """ normal = u'\x1B[0m' seq = u'\x1B[%sm' % code # Replace any normal sequences with this sequence to support nested colors return seq + (normal + seq).join(content.split(normal)) + normal
python
def _apply_color(code, content): """ Apply a color code to text """ normal = u'\x1B[0m' seq = u'\x1B[%sm' % code # Replace any normal sequences with this sequence to support nested colors return seq + (normal + seq).join(content.split(normal)) + normal
[ "def", "_apply_color", "(", "code", ",", "content", ")", ":", "normal", "=", "u'\\x1B[0m'", "seq", "=", "u'\\x1B[%sm'", "%", "code", "# Replace any normal sequences with this sequence to support nested colors", "return", "seq", "+", "(", "normal", "+", "seq", ")", "...
Apply a color code to text
[ "Apply", "a", "color", "code", "to", "text" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_win_terminal.py#L152-L161
train
209,071
Rockhopper-Technologies/enlighten
enlighten/_win_terminal.py
Terminal.color
def color(self, code): """ When color is given as a number, apply that color to the content While this is designed to support 256 color terminals, Windows will approximate this with 16 colors """ def func(content=''): return self._apply_color(u'38;5;%d' % code, content) return func
python
def color(self, code): """ When color is given as a number, apply that color to the content While this is designed to support 256 color terminals, Windows will approximate this with 16 colors """ def func(content=''): return self._apply_color(u'38;5;%d' % code, content) return func
[ "def", "color", "(", "self", ",", "code", ")", ":", "def", "func", "(", "content", "=", "''", ")", ":", "return", "self", ".", "_apply_color", "(", "u'38;5;%d'", "%", "code", ",", "content", ")", "return", "func" ]
When color is given as a number, apply that color to the content While this is designed to support 256 color terminals, Windows will approximate this with 16 colors
[ "When", "color", "is", "given", "as", "a", "number", "apply", "that", "color", "to", "the", "content", "While", "this", "is", "designed", "to", "support", "256", "color", "terminals", "Windows", "will", "approximate", "this", "with", "16", "colors" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_win_terminal.py#L163-L172
train
209,072
Rockhopper-Technologies/enlighten
examples/ftp_downloader.py
download
def download(): """ Download all files from an FTP share """ ftp = ftplib.FTP(SITE) ftp.set_debuglevel(DEBUG) ftp.login(USER, PASSWD) ftp.cwd(DIR) filelist = ftp.nlst() filecounter = MANAGER.counter(total=len(filelist), desc='Downloading', unit='files') for filename in filelist: with Writer(filename, ftp.size(filename), DEST) as writer: ftp.retrbinary('RETR %s' % filename, writer.write) print(filename) filecounter.update() ftp.close()
python
def download(): """ Download all files from an FTP share """ ftp = ftplib.FTP(SITE) ftp.set_debuglevel(DEBUG) ftp.login(USER, PASSWD) ftp.cwd(DIR) filelist = ftp.nlst() filecounter = MANAGER.counter(total=len(filelist), desc='Downloading', unit='files') for filename in filelist: with Writer(filename, ftp.size(filename), DEST) as writer: ftp.retrbinary('RETR %s' % filename, writer.write) print(filename) filecounter.update() ftp.close()
[ "def", "download", "(", ")", ":", "ftp", "=", "ftplib", ".", "FTP", "(", "SITE", ")", "ftp", ".", "set_debuglevel", "(", "DEBUG", ")", "ftp", ".", "login", "(", "USER", ",", "PASSWD", ")", "ftp", ".", "cwd", "(", "DIR", ")", "filelist", "=", "ftp...
Download all files from an FTP share
[ "Download", "all", "files", "from", "an", "FTP", "share" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/examples/ftp_downloader.py#L58-L78
train
209,073
Rockhopper-Technologies/enlighten
examples/ftp_downloader.py
Writer.write
def write(self, block): """ Write to local file and update progress bar """ self.fileobj.write(block) self.status.update(len(block))
python
def write(self, block): """ Write to local file and update progress bar """ self.fileobj.write(block) self.status.update(len(block))
[ "def", "write", "(", "self", ",", "block", ")", ":", "self", ".", "fileobj", ".", "write", "(", "block", ")", "self", ".", "status", ".", "update", "(", "len", "(", "block", ")", ")" ]
Write to local file and update progress bar
[ "Write", "to", "local", "file", "and", "update", "progress", "bar" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/examples/ftp_downloader.py#L50-L55
train
209,074
Rockhopper-Technologies/enlighten
examples/context_manager.py
process_files
def process_files(): """ Use Manager and Counter as context managers """ with enlighten.Manager() as manager: with manager.counter(total=SPLINES, desc='Reticulating:', unit='splines') as retic: for num in range(SPLINES): # pylint: disable=unused-variable time.sleep(random.uniform(0.1, 0.5)) # Random processing time retic.update() with manager.counter(total=LLAMAS, desc='Herding:', unit='llamas') as herd: for num in range(SPLINES): # pylint: disable=unused-variable time.sleep(random.uniform(0.1, 0.5)) # Random processing time herd.update()
python
def process_files(): """ Use Manager and Counter as context managers """ with enlighten.Manager() as manager: with manager.counter(total=SPLINES, desc='Reticulating:', unit='splines') as retic: for num in range(SPLINES): # pylint: disable=unused-variable time.sleep(random.uniform(0.1, 0.5)) # Random processing time retic.update() with manager.counter(total=LLAMAS, desc='Herding:', unit='llamas') as herd: for num in range(SPLINES): # pylint: disable=unused-variable time.sleep(random.uniform(0.1, 0.5)) # Random processing time herd.update()
[ "def", "process_files", "(", ")", ":", "with", "enlighten", ".", "Manager", "(", ")", "as", "manager", ":", "with", "manager", ".", "counter", "(", "total", "=", "SPLINES", ",", "desc", "=", "'Reticulating:'", ",", "unit", "=", "'splines'", ")", "as", ...
Use Manager and Counter as context managers
[ "Use", "Manager", "and", "Counter", "as", "context", "managers" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/examples/context_manager.py#L19-L33
train
209,075
Rockhopper-Technologies/enlighten
setup_helpers.py
print_spelling_errors
def print_spelling_errors(filename, encoding='utf8'): """ Print misspelled words returned by sphinxcontrib-spelling """ filesize = os.stat(filename).st_size if filesize: sys.stdout.write('Misspelled Words:\n') with io.open(filename, encoding=encoding) as wordlist: for line in wordlist: sys.stdout.write(' ' + line) return 1 if filesize else 0
python
def print_spelling_errors(filename, encoding='utf8'): """ Print misspelled words returned by sphinxcontrib-spelling """ filesize = os.stat(filename).st_size if filesize: sys.stdout.write('Misspelled Words:\n') with io.open(filename, encoding=encoding) as wordlist: for line in wordlist: sys.stdout.write(' ' + line) return 1 if filesize else 0
[ "def", "print_spelling_errors", "(", "filename", ",", "encoding", "=", "'utf8'", ")", ":", "filesize", "=", "os", ".", "stat", "(", "filename", ")", ".", "st_size", "if", "filesize", ":", "sys", ".", "stdout", ".", "write", "(", "'Misspelled Words:\\n'", "...
Print misspelled words returned by sphinxcontrib-spelling
[ "Print", "misspelled", "words", "returned", "by", "sphinxcontrib", "-", "spelling" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/setup_helpers.py#L43-L55
train
209,076
Rockhopper-Technologies/enlighten
examples/demo.py
initialize
def initialize(manager, initials=15): """ Simple progress bar example """ # Simulated preparation pbar = manager.counter(total=initials, desc='Initializing:', unit='initials') for num in range(initials): # pylint: disable=unused-variable time.sleep(random.uniform(0.1, 0.5)) # Random processing time pbar.update() pbar.close()
python
def initialize(manager, initials=15): """ Simple progress bar example """ # Simulated preparation pbar = manager.counter(total=initials, desc='Initializing:', unit='initials') for num in range(initials): # pylint: disable=unused-variable time.sleep(random.uniform(0.1, 0.5)) # Random processing time pbar.update() pbar.close()
[ "def", "initialize", "(", "manager", ",", "initials", "=", "15", ")", ":", "# Simulated preparation", "pbar", "=", "manager", ".", "counter", "(", "total", "=", "initials", ",", "desc", "=", "'Initializing:'", ",", "unit", "=", "'initials'", ")", "for", "n...
Simple progress bar example
[ "Simple", "progress", "bar", "example" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/examples/demo.py#L21-L31
train
209,077
Rockhopper-Technologies/enlighten
enlighten/_manager.py
Manager._resize_handler
def _resize_handler(self, *args, **kwarg): # pylint: disable=unused-argument """ Called when a window resize signal is detected Resets the scroll window """ # Make sure only one resize handler is running try: assert self.resize_lock except AssertionError: self.resize_lock = True term = self.term term.clear_cache() newHeight = term.height newWidth = term.width lastHeight = lastWidth = 0 while newHeight != lastHeight or newWidth != lastWidth: lastHeight = newHeight lastWidth = newWidth time.sleep(.2) term.clear_cache() newHeight = term.height newWidth = term.width if newWidth < self.width: offset = (self.scroll_offset - 1) * (1 + self.width // newWidth) term.move_to(0, max(0, newHeight - offset)) self.stream.write(term.clear_eos) self.width = newWidth self._set_scroll_area(force=True) for cter in self.counters: cter.refresh(flush=False) self.stream.flush() self.resize_lock = False
python
def _resize_handler(self, *args, **kwarg): # pylint: disable=unused-argument """ Called when a window resize signal is detected Resets the scroll window """ # Make sure only one resize handler is running try: assert self.resize_lock except AssertionError: self.resize_lock = True term = self.term term.clear_cache() newHeight = term.height newWidth = term.width lastHeight = lastWidth = 0 while newHeight != lastHeight or newWidth != lastWidth: lastHeight = newHeight lastWidth = newWidth time.sleep(.2) term.clear_cache() newHeight = term.height newWidth = term.width if newWidth < self.width: offset = (self.scroll_offset - 1) * (1 + self.width // newWidth) term.move_to(0, max(0, newHeight - offset)) self.stream.write(term.clear_eos) self.width = newWidth self._set_scroll_area(force=True) for cter in self.counters: cter.refresh(flush=False) self.stream.flush() self.resize_lock = False
[ "def", "_resize_handler", "(", "self", ",", "*", "args", ",", "*", "*", "kwarg", ")", ":", "# pylint: disable=unused-argument", "# Make sure only one resize handler is running", "try", ":", "assert", "self", ".", "resize_lock", "except", "AssertionError", ":", "self",...
Called when a window resize signal is detected Resets the scroll window
[ "Called", "when", "a", "window", "resize", "signal", "is", "detected" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_manager.py#L169-L209
train
209,078
Rockhopper-Technologies/enlighten
enlighten/_manager.py
Manager._at_exit
def _at_exit(self): """ Resets terminal to normal configuration """ if self.process_exit: try: term = self.term if self.set_scroll: term.reset() else: term.move_to(0, term.height) self.term.feed() except ValueError: # Possibly closed file handles pass
python
def _at_exit(self): """ Resets terminal to normal configuration """ if self.process_exit: try: term = self.term if self.set_scroll: term.reset() else: term.move_to(0, term.height) self.term.feed() except ValueError: # Possibly closed file handles pass
[ "def", "_at_exit", "(", "self", ")", ":", "if", "self", ".", "process_exit", ":", "try", ":", "term", "=", "self", ".", "term", "if", "self", ".", "set_scroll", ":", "term", ".", "reset", "(", ")", "else", ":", "term", ".", "move_to", "(", "0", "...
Resets terminal to normal configuration
[ "Resets", "terminal", "to", "normal", "configuration" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_manager.py#L255-L274
train
209,079
Rockhopper-Technologies/enlighten
enlighten/_manager.py
Manager.stop
def stop(self): """ Clean up and reset terminal This method should be called when the manager and counters will no longer be needed. Any progress bars that have ``leave`` set to :py:data:`True` or have not been closed will remain on the console. All others will be cleared. Manager and all counters will be disabled. """ if self.enabled: term = self.term stream = self.stream positions = self.counters.values() if not self.no_resize and RESIZE_SUPPORTED: signal.signal(signal.SIGWINCH, self.sigwinch_orig) try: for num in range(self.scroll_offset - 1, 0, -1): if num not in positions: term.move_to(0, term.height - num) stream.write(term.clear_eol) stream.flush() finally: if self.set_scroll: self.term.reset() if self.companion_term: self.companion_term.reset() else: term.move_to(0, term.height) self.process_exit = False self.enabled = False for cter in self.counters: cter.enabled = False # Feed terminal if lowest position isn't cleared if 1 in positions: term.feed()
python
def stop(self): """ Clean up and reset terminal This method should be called when the manager and counters will no longer be needed. Any progress bars that have ``leave`` set to :py:data:`True` or have not been closed will remain on the console. All others will be cleared. Manager and all counters will be disabled. """ if self.enabled: term = self.term stream = self.stream positions = self.counters.values() if not self.no_resize and RESIZE_SUPPORTED: signal.signal(signal.SIGWINCH, self.sigwinch_orig) try: for num in range(self.scroll_offset - 1, 0, -1): if num not in positions: term.move_to(0, term.height - num) stream.write(term.clear_eol) stream.flush() finally: if self.set_scroll: self.term.reset() if self.companion_term: self.companion_term.reset() else: term.move_to(0, term.height) self.process_exit = False self.enabled = False for cter in self.counters: cter.enabled = False # Feed terminal if lowest position isn't cleared if 1 in positions: term.feed()
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "enabled", ":", "term", "=", "self", ".", "term", "stream", "=", "self", ".", "stream", "positions", "=", "self", ".", "counters", ".", "values", "(", ")", "if", "not", "self", ".", "no_resiz...
Clean up and reset terminal This method should be called when the manager and counters will no longer be needed. Any progress bars that have ``leave`` set to :py:data:`True` or have not been closed will remain on the console. All others will be cleared. Manager and all counters will be disabled.
[ "Clean", "up", "and", "reset", "terminal" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_manager.py#L295-L344
train
209,080
Rockhopper-Technologies/enlighten
enlighten/_counter.py
Counter.close
def close(self, clear=False): """ Do final refresh and remove from manager If ``leave`` is True, the default, the effect is the same as :py:meth:`refresh`. """ if clear and not self.leave: self.clear() else: self.refresh() self.manager.remove(self)
python
def close(self, clear=False): """ Do final refresh and remove from manager If ``leave`` is True, the default, the effect is the same as :py:meth:`refresh`. """ if clear and not self.leave: self.clear() else: self.refresh() self.manager.remove(self)
[ "def", "close", "(", "self", ",", "clear", "=", "False", ")", ":", "if", "clear", "and", "not", "self", ".", "leave", ":", "self", ".", "clear", "(", ")", "else", ":", "self", ".", "refresh", "(", ")", "self", ".", "manager", ".", "remove", "(", ...
Do final refresh and remove from manager If ``leave`` is True, the default, the effect is the same as :py:meth:`refresh`.
[ "Do", "final", "refresh", "and", "remove", "from", "manager" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_counter.py#L520-L532
train
209,081
Rockhopper-Technologies/enlighten
examples/multiple_logging.py
process_files
def process_files(manager): """ Process a random number of files on a random number of systems across multiple data centers """ # Get a top level progress bar enterprise = manager.counter(total=DATACENTERS, desc='Processing:', unit='datacenters') # Iterate through data centers for dnum in range(1, DATACENTERS + 1): systems = random.randint(*SYSTEMS) # Random number of systems # Get a child progress bar. leave is False so it can be replaced currCenter = manager.counter(total=systems, desc=' Datacenter %d:' % dnum, unit='systems', leave=False) # Iterate through systems for snum in range(1, systems + 1): # Has no total, so will act as counter. Leave is False system = manager.counter(desc=' System %d:' % snum, unit='files', leave=False) files = random.randint(*FILES) # Random file count # Iterate through files for fnum in range(files): # pylint: disable=unused-variable system.update() # Update count time.sleep(random.uniform(0.0001, 0.0005)) # Random processing time system.close() # Close counter so it gets removed # Log status LOGGER.info('Updated %d files on System %d in Datacenter %d', files, snum, dnum) currCenter.update() # Update count currCenter.close() # Close counter so it gets removed enterprise.update() # Update count enterprise.close()
python
def process_files(manager): """ Process a random number of files on a random number of systems across multiple data centers """ # Get a top level progress bar enterprise = manager.counter(total=DATACENTERS, desc='Processing:', unit='datacenters') # Iterate through data centers for dnum in range(1, DATACENTERS + 1): systems = random.randint(*SYSTEMS) # Random number of systems # Get a child progress bar. leave is False so it can be replaced currCenter = manager.counter(total=systems, desc=' Datacenter %d:' % dnum, unit='systems', leave=False) # Iterate through systems for snum in range(1, systems + 1): # Has no total, so will act as counter. Leave is False system = manager.counter(desc=' System %d:' % snum, unit='files', leave=False) files = random.randint(*FILES) # Random file count # Iterate through files for fnum in range(files): # pylint: disable=unused-variable system.update() # Update count time.sleep(random.uniform(0.0001, 0.0005)) # Random processing time system.close() # Close counter so it gets removed # Log status LOGGER.info('Updated %d files on System %d in Datacenter %d', files, snum, dnum) currCenter.update() # Update count currCenter.close() # Close counter so it gets removed enterprise.update() # Update count enterprise.close()
[ "def", "process_files", "(", "manager", ")", ":", "# Get a top level progress bar", "enterprise", "=", "manager", ".", "counter", "(", "total", "=", "DATACENTERS", ",", "desc", "=", "'Processing:'", ",", "unit", "=", "'datacenters'", ")", "# Iterate through data cen...
Process a random number of files on a random number of systems across multiple data centers
[ "Process", "a", "random", "number", "of", "files", "on", "a", "random", "number", "of", "systems", "across", "multiple", "data", "centers" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/examples/multiple_logging.py#L27-L63
train
209,082
Rockhopper-Technologies/enlighten
examples/multicolored.py
Node._state
def _state(self, variable, num): """ Generic method to randomly determine if state is reached """ value = getattr(self, variable) if value is None: return False if value is True: return True if random.randint(1, num) == num: setattr(self, variable, True) return True return False
python
def _state(self, variable, num): """ Generic method to randomly determine if state is reached """ value = getattr(self, variable) if value is None: return False if value is True: return True if random.randint(1, num) == num: setattr(self, variable, True) return True return False
[ "def", "_state", "(", "self", ",", "variable", ",", "num", ")", ":", "value", "=", "getattr", "(", "self", ",", "variable", ")", "if", "value", "is", "None", ":", "return", "False", "if", "value", "is", "True", ":", "return", "True", "if", "random", ...
Generic method to randomly determine if state is reached
[ "Generic", "method", "to", "randomly", "determine", "if", "state", "is", "reached" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/examples/multicolored.py#L64-L81
train
209,083
Rockhopper-Technologies/enlighten
enlighten/_terminal.py
Terminal.reset
def reset(self): """ Reset scroll window and cursor to default """ self.stream.write(self.normal_cursor) self.stream.write(self.csr(0, self.height)) self.stream.write(self.move(self.height, 0))
python
def reset(self): """ Reset scroll window and cursor to default """ self.stream.write(self.normal_cursor) self.stream.write(self.csr(0, self.height)) self.stream.write(self.move(self.height, 0))
[ "def", "reset", "(", "self", ")", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "normal_cursor", ")", "self", ".", "stream", ".", "write", "(", "self", ".", "csr", "(", "0", ",", "self", ".", "height", ")", ")", "self", ".", "stream...
Reset scroll window and cursor to default
[ "Reset", "scroll", "window", "and", "cursor", "to", "default" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_terminal.py#L35-L42
train
209,084
Rockhopper-Technologies/enlighten
enlighten/_terminal.py
Terminal.move_to
def move_to(self, xpos, ypos): """ Move cursor to specified position """ self.stream.write(self.move(ypos, xpos))
python
def move_to(self, xpos, ypos): """ Move cursor to specified position """ self.stream.write(self.move(ypos, xpos))
[ "def", "move_to", "(", "self", ",", "xpos", ",", "ypos", ")", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "move", "(", "ypos", ",", "xpos", ")", ")" ]
Move cursor to specified position
[ "Move", "cursor", "to", "specified", "position" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_terminal.py#L63-L68
train
209,085
Rockhopper-Technologies/enlighten
enlighten/_terminal.py
Terminal._height_and_width
def _height_and_width(self): """ Override for blessings.Terminal._height_and_width Adds caching """ try: return self._cache['height_and_width'] except KeyError: handw = self._cache['height_and_width'] = super(Terminal, self)._height_and_width() return handw
python
def _height_and_width(self): """ Override for blessings.Terminal._height_and_width Adds caching """ try: return self._cache['height_and_width'] except KeyError: handw = self._cache['height_and_width'] = super(Terminal, self)._height_and_width() return handw
[ "def", "_height_and_width", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_cache", "[", "'height_and_width'", "]", "except", "KeyError", ":", "handw", "=", "self", ".", "_cache", "[", "'height_and_width'", "]", "=", "super", "(", "Terminal", "...
Override for blessings.Terminal._height_and_width Adds caching
[ "Override", "for", "blessings", ".", "Terminal", ".", "_height_and_width", "Adds", "caching" ]
857855f940e6c1bb84d0be849b999a18fff5bf5a
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_terminal.py#L70-L80
train
209,086
twosigma/marbles
marbles/core/marbles/core/_stack.py
get_stack_info
def get_stack_info(): '''Capture locals, module name, filename, and line number from the stacktrace to provide the source of the assertion error and formatted note. ''' stack = traceback.walk_stack(sys._getframe().f_back) # We want locals from the test definition (which always begins # with 'test_' in unittest), which will be at a different # level in the stack depending on how many tests are in each # test case, how many test cases there are, etc. # The branch where we exhaust this loop is not covered # because we always find a test. for frame, _ in stack: # pragma: no branch code = frame.f_code if code.co_name.startswith('test_'): return (frame.f_locals.copy(), frame.f_globals['__name__'], code.co_filename, frame.f_lineno)
python
def get_stack_info(): '''Capture locals, module name, filename, and line number from the stacktrace to provide the source of the assertion error and formatted note. ''' stack = traceback.walk_stack(sys._getframe().f_back) # We want locals from the test definition (which always begins # with 'test_' in unittest), which will be at a different # level in the stack depending on how many tests are in each # test case, how many test cases there are, etc. # The branch where we exhaust this loop is not covered # because we always find a test. for frame, _ in stack: # pragma: no branch code = frame.f_code if code.co_name.startswith('test_'): return (frame.f_locals.copy(), frame.f_globals['__name__'], code.co_filename, frame.f_lineno)
[ "def", "get_stack_info", "(", ")", ":", "stack", "=", "traceback", ".", "walk_stack", "(", "sys", ".", "_getframe", "(", ")", ".", "f_back", ")", "# We want locals from the test definition (which always begins", "# with 'test_' in unittest), which will be at a different", "...
Capture locals, module name, filename, and line number from the stacktrace to provide the source of the assertion error and formatted note.
[ "Capture", "locals", "module", "name", "filename", "and", "line", "number", "from", "the", "stacktrace", "to", "provide", "the", "source", "of", "the", "assertion", "error", "and", "formatted", "note", "." ]
f0c668be8344c70d4d63bc57e82c6f2da43c6925
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/core/marbles/core/_stack.py#L27-L45
train
209,087
twosigma/marbles
marbles/mixins/marbles/mixins/mixins.py
BetweenMixins.assertBetween
def assertBetween(self, obj, lower, upper, strict=True, msg=None): '''Fail if ``obj`` is not between ``lower`` and ``upper``. If ``strict=True`` (default), fail unless ``lower < obj < upper``. If ``strict=False``, fail unless ``lower <= obj <= upper``. This is equivalent to ``self.assertTrue(lower < obj < upper)`` or ``self.assertTrue(lower <= obj <= upper)``, but with a nicer default message. Parameters ---------- obj lower upper strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. ''' if strict: standardMsg = '%s is not strictly between %s and %s' % ( obj, lower, upper) op = operator.lt else: standardMsg = '%s is not between %s and %s' % (obj, lower, upper) op = operator.le if not (op(lower, obj) and op(obj, upper)): self.fail(self._formatMessage(msg, standardMsg))
python
def assertBetween(self, obj, lower, upper, strict=True, msg=None): '''Fail if ``obj`` is not between ``lower`` and ``upper``. If ``strict=True`` (default), fail unless ``lower < obj < upper``. If ``strict=False``, fail unless ``lower <= obj <= upper``. This is equivalent to ``self.assertTrue(lower < obj < upper)`` or ``self.assertTrue(lower <= obj <= upper)``, but with a nicer default message. Parameters ---------- obj lower upper strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. ''' if strict: standardMsg = '%s is not strictly between %s and %s' % ( obj, lower, upper) op = operator.lt else: standardMsg = '%s is not between %s and %s' % (obj, lower, upper) op = operator.le if not (op(lower, obj) and op(obj, upper)): self.fail(self._formatMessage(msg, standardMsg))
[ "def", "assertBetween", "(", "self", ",", "obj", ",", "lower", ",", "upper", ",", "strict", "=", "True", ",", "msg", "=", "None", ")", ":", "if", "strict", ":", "standardMsg", "=", "'%s is not strictly between %s and %s'", "%", "(", "obj", ",", "lower", ...
Fail if ``obj`` is not between ``lower`` and ``upper``. If ``strict=True`` (default), fail unless ``lower < obj < upper``. If ``strict=False``, fail unless ``lower <= obj <= upper``. This is equivalent to ``self.assertTrue(lower < obj < upper)`` or ``self.assertTrue(lower <= obj <= upper)``, but with a nicer default message. Parameters ---------- obj lower upper strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used.
[ "Fail", "if", "obj", "is", "not", "between", "lower", "and", "upper", "." ]
f0c668be8344c70d4d63bc57e82c6f2da43c6925
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L92-L122
train
209,088
twosigma/marbles
marbles/mixins/marbles/mixins/mixins.py
MonotonicMixins.assertMonotonicIncreasing
def assertMonotonicIncreasing(self, sequence, strict=True, msg=None): '''Fail if ``sequence`` is not monotonically increasing. If ``strict=True`` (default), fail unless each element in ``sequence`` is less than the following element as determined by the ``<`` operator. If ``strict=False``, fail unless each element in ``sequence`` is less than or equal to the following element as determined by the ``<=`` operator. .. code-block:: python assert all((i < j) for i, j in zip(sequence, sequence[1:])) assert all((i <= j) for i, j in zip(sequence, sequence[1:])) Parameters ---------- sequence : iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. ''' if not isinstance(sequence, collections.Iterable): raise TypeError('First argument is not iterable') if strict: standardMsg = ('Elements in %s are not strictly monotonically ' 'increasing') % (sequence,) op = operator.lt else: standardMsg = ('Elements in %s are not monotonically ' 'increasing') % (sequence,) op = operator.le if not self._monotonic(op, sequence): self.fail(self._formatMessage(msg, standardMsg))
python
def assertMonotonicIncreasing(self, sequence, strict=True, msg=None): '''Fail if ``sequence`` is not monotonically increasing. If ``strict=True`` (default), fail unless each element in ``sequence`` is less than the following element as determined by the ``<`` operator. If ``strict=False``, fail unless each element in ``sequence`` is less than or equal to the following element as determined by the ``<=`` operator. .. code-block:: python assert all((i < j) for i, j in zip(sequence, sequence[1:])) assert all((i <= j) for i, j in zip(sequence, sequence[1:])) Parameters ---------- sequence : iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. ''' if not isinstance(sequence, collections.Iterable): raise TypeError('First argument is not iterable') if strict: standardMsg = ('Elements in %s are not strictly monotonically ' 'increasing') % (sequence,) op = operator.lt else: standardMsg = ('Elements in %s are not monotonically ' 'increasing') % (sequence,) op = operator.le if not self._monotonic(op, sequence): self.fail(self._formatMessage(msg, standardMsg))
[ "def", "assertMonotonicIncreasing", "(", "self", ",", "sequence", ",", "strict", "=", "True", ",", "msg", "=", "None", ")", ":", "if", "not", "isinstance", "(", "sequence", ",", "collections", ".", "Iterable", ")", ":", "raise", "TypeError", "(", "'First a...
Fail if ``sequence`` is not monotonically increasing. If ``strict=True`` (default), fail unless each element in ``sequence`` is less than the following element as determined by the ``<`` operator. If ``strict=False``, fail unless each element in ``sequence`` is less than or equal to the following element as determined by the ``<=`` operator. .. code-block:: python assert all((i < j) for i, j in zip(sequence, sequence[1:])) assert all((i <= j) for i, j in zip(sequence, sequence[1:])) Parameters ---------- sequence : iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable.
[ "Fail", "if", "sequence", "is", "not", "monotonically", "increasing", "." ]
f0c668be8344c70d4d63bc57e82c6f2da43c6925
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L186-L226
train
209,089
twosigma/marbles
marbles/mixins/marbles/mixins/mixins.py
MonotonicMixins.assertNotMonotonicDecreasing
def assertNotMonotonicDecreasing(self, sequence, strict=True, msg=None): '''Fail if ``sequence`` is monotonically decreasing. If ``strict=True`` (default), fail if each element in ``sequence`` is greater than the following element as determined by the ``>`` operator. If ``strict=False``, fail if each element in ``sequence`` is greater than or equal to the following element as determined by the ``>=`` operator. .. code-block:: python assert not all((i > j) for i, j in zip(sequence, sequence[1:])) assert not all((i >= j) for i, j in zip(sequence, sequence[1:])) Parameters ---------- sequence : iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. ''' if not isinstance(sequence, collections.Iterable): raise TypeError('First argument is not iterable') if strict: standardMsg = ('Elements in %s are strictly monotonically ' 'decreasing') % (sequence,) op = operator.gt else: standardMsg = ('Elements in %s are monotonically ' 'decreasing') % (sequence,) op = operator.ge if self._monotonic(op, sequence): self.fail(self._formatMessage(msg, standardMsg))
python
def assertNotMonotonicDecreasing(self, sequence, strict=True, msg=None): '''Fail if ``sequence`` is monotonically decreasing. If ``strict=True`` (default), fail if each element in ``sequence`` is greater than the following element as determined by the ``>`` operator. If ``strict=False``, fail if each element in ``sequence`` is greater than or equal to the following element as determined by the ``>=`` operator. .. code-block:: python assert not all((i > j) for i, j in zip(sequence, sequence[1:])) assert not all((i >= j) for i, j in zip(sequence, sequence[1:])) Parameters ---------- sequence : iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. ''' if not isinstance(sequence, collections.Iterable): raise TypeError('First argument is not iterable') if strict: standardMsg = ('Elements in %s are strictly monotonically ' 'decreasing') % (sequence,) op = operator.gt else: standardMsg = ('Elements in %s are monotonically ' 'decreasing') % (sequence,) op = operator.ge if self._monotonic(op, sequence): self.fail(self._formatMessage(msg, standardMsg))
[ "def", "assertNotMonotonicDecreasing", "(", "self", ",", "sequence", ",", "strict", "=", "True", ",", "msg", "=", "None", ")", ":", "if", "not", "isinstance", "(", "sequence", ",", "collections", ".", "Iterable", ")", ":", "raise", "TypeError", "(", "'Firs...
Fail if ``sequence`` is monotonically decreasing. If ``strict=True`` (default), fail if each element in ``sequence`` is greater than the following element as determined by the ``>`` operator. If ``strict=False``, fail if each element in ``sequence`` is greater than or equal to the following element as determined by the ``>=`` operator. .. code-block:: python assert not all((i > j) for i, j in zip(sequence, sequence[1:])) assert not all((i >= j) for i, j in zip(sequence, sequence[1:])) Parameters ---------- sequence : iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable.
[ "Fail", "if", "sequence", "is", "monotonically", "decreasing", "." ]
f0c668be8344c70d4d63bc57e82c6f2da43c6925
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L312-L352
train
209,090
twosigma/marbles
marbles/mixins/marbles/mixins/mixins.py
UniqueMixins.assertUnique
def assertUnique(self, container, msg=None): '''Fail if elements in ``container`` are not unique. Parameters ---------- container : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``container`` is not iterable. ''' if not isinstance(container, collections.Iterable): raise TypeError('First argument is not iterable') standardMsg = 'Elements in %s are not unique' % (container,) # We iterate over each element in the container instead of # comparing len(container) == len(set(container)) to allow # for containers that contain unhashable types for idx, elem in enumerate(container): # If elem appears at an earlier or later index position # the elements are not unique if elem in container[:idx] or elem in container[idx+1:]: self.fail(self._formatMessage(msg, standardMsg))
python
def assertUnique(self, container, msg=None): '''Fail if elements in ``container`` are not unique. Parameters ---------- container : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``container`` is not iterable. ''' if not isinstance(container, collections.Iterable): raise TypeError('First argument is not iterable') standardMsg = 'Elements in %s are not unique' % (container,) # We iterate over each element in the container instead of # comparing len(container) == len(set(container)) to allow # for containers that contain unhashable types for idx, elem in enumerate(container): # If elem appears at an earlier or later index position # the elements are not unique if elem in container[:idx] or elem in container[idx+1:]: self.fail(self._formatMessage(msg, standardMsg))
[ "def", "assertUnique", "(", "self", ",", "container", ",", "msg", "=", "None", ")", ":", "if", "not", "isinstance", "(", "container", ",", "collections", ".", "Iterable", ")", ":", "raise", "TypeError", "(", "'First argument is not iterable'", ")", "standardMs...
Fail if elements in ``container`` are not unique. Parameters ---------- container : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``container`` is not iterable.
[ "Fail", "if", "elements", "in", "container", "are", "not", "unique", "." ]
f0c668be8344c70d4d63bc57e82c6f2da43c6925
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L374-L401
train
209,091
twosigma/marbles
marbles/mixins/marbles/mixins/mixins.py
FileMixins._get_or_open_file
def _get_or_open_file(filename): '''If ``filename`` is a string or bytes object, open the ``filename`` and return the file object. If ``filename`` is file-like (i.e., it has 'read' and 'write' attributes, return ``filename``. Parameters ---------- filename : str, bytes, file Raises ------ TypeError If ``filename`` is not a string, bytes, or file-like object. File-likeness is determined by checking for 'read' and 'write' attributes. ''' if isinstance(filename, (str, bytes)): f = open(filename) elif hasattr(filename, 'read') and hasattr(filename, 'write'): f = filename else: raise TypeError('filename must be str or bytes, or a file') return f
python
def _get_or_open_file(filename): '''If ``filename`` is a string or bytes object, open the ``filename`` and return the file object. If ``filename`` is file-like (i.e., it has 'read' and 'write' attributes, return ``filename``. Parameters ---------- filename : str, bytes, file Raises ------ TypeError If ``filename`` is not a string, bytes, or file-like object. File-likeness is determined by checking for 'read' and 'write' attributes. ''' if isinstance(filename, (str, bytes)): f = open(filename) elif hasattr(filename, 'read') and hasattr(filename, 'write'): f = filename else: raise TypeError('filename must be str or bytes, or a file') return f
[ "def", "_get_or_open_file", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "(", "str", ",", "bytes", ")", ")", ":", "f", "=", "open", "(", "filename", ")", "elif", "hasattr", "(", "filename", ",", "'read'", ")", "and", "hasattr", ...
If ``filename`` is a string or bytes object, open the ``filename`` and return the file object. If ``filename`` is file-like (i.e., it has 'read' and 'write' attributes, return ``filename``. Parameters ---------- filename : str, bytes, file Raises ------ TypeError If ``filename`` is not a string, bytes, or file-like object. File-likeness is determined by checking for 'read' and 'write' attributes.
[ "If", "filename", "is", "a", "string", "or", "bytes", "object", "open", "the", "filename", "and", "return", "the", "file", "object", ".", "If", "filename", "is", "file", "-", "like", "(", "i", ".", "e", ".", "it", "has", "read", "and", "write", "attr...
f0c668be8344c70d4d63bc57e82c6f2da43c6925
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L537-L562
train
209,092
twosigma/marbles
marbles/mixins/marbles/mixins/mixins.py
FileMixins.assertFileNameEqual
def assertFileNameEqual(self, filename, name, msg=None): '''Fail if ``filename`` does not have the given ``name`` as determined by the ``==`` operator. Parameters ---------- filename : str, bytes, file-like name : str, byes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fname = self._get_file_name(filename) self.assertEqual(fname, name, msg=msg)
python
def assertFileNameEqual(self, filename, name, msg=None): '''Fail if ``filename`` does not have the given ``name`` as determined by the ``==`` operator. Parameters ---------- filename : str, bytes, file-like name : str, byes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fname = self._get_file_name(filename) self.assertEqual(fname, name, msg=msg)
[ "def", "assertFileNameEqual", "(", "self", ",", "filename", ",", "name", ",", "msg", "=", "None", ")", ":", "fname", "=", "self", ".", "_get_file_name", "(", "filename", ")", "self", ".", "assertEqual", "(", "fname", ",", "name", ",", "msg", "=", "msg"...
Fail if ``filename`` does not have the given ``name`` as determined by the ``==`` operator. Parameters ---------- filename : str, bytes, file-like name : str, byes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
[ "Fail", "if", "filename", "does", "not", "have", "the", "given", "name", "as", "determined", "by", "the", "==", "operator", "." ]
f0c668be8344c70d4d63bc57e82c6f2da43c6925
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L664-L683
train
209,093
twosigma/marbles
marbles/mixins/marbles/mixins/mixins.py
FileMixins.assertFileNameNotEqual
def assertFileNameNotEqual(self, filename, name, msg=None): '''Fail if ``filename`` has the given ``name`` as determined by the ``!=`` operator. Parameters ---------- filename : str, bytes, file-like name : str, byes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fname = self._get_file_name(filename) self.assertNotEqual(fname, name, msg=msg)
python
def assertFileNameNotEqual(self, filename, name, msg=None): '''Fail if ``filename`` has the given ``name`` as determined by the ``!=`` operator. Parameters ---------- filename : str, bytes, file-like name : str, byes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fname = self._get_file_name(filename) self.assertNotEqual(fname, name, msg=msg)
[ "def", "assertFileNameNotEqual", "(", "self", ",", "filename", ",", "name", ",", "msg", "=", "None", ")", ":", "fname", "=", "self", ".", "_get_file_name", "(", "filename", ")", "self", ".", "assertNotEqual", "(", "fname", ",", "name", ",", "msg", "=", ...
Fail if ``filename`` has the given ``name`` as determined by the ``!=`` operator. Parameters ---------- filename : str, bytes, file-like name : str, byes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
[ "Fail", "if", "filename", "has", "the", "given", "name", "as", "determined", "by", "the", "!", "=", "operator", "." ]
f0c668be8344c70d4d63bc57e82c6f2da43c6925
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L685-L704
train
209,094
twosigma/marbles
marbles/mixins/marbles/mixins/mixins.py
FileMixins.assertFileNameRegex
def assertFileNameRegex(self, filename, expected_regex, msg=None): '''Fail unless ``filename`` matches ``expected_regex``. Parameters ---------- filename : str, bytes, file-like expected_regex : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fname = self._get_file_name(filename) self.assertRegex(fname, expected_regex, msg=msg)
python
def assertFileNameRegex(self, filename, expected_regex, msg=None): '''Fail unless ``filename`` matches ``expected_regex``. Parameters ---------- filename : str, bytes, file-like expected_regex : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fname = self._get_file_name(filename) self.assertRegex(fname, expected_regex, msg=msg)
[ "def", "assertFileNameRegex", "(", "self", ",", "filename", ",", "expected_regex", ",", "msg", "=", "None", ")", ":", "fname", "=", "self", ".", "_get_file_name", "(", "filename", ")", "self", ".", "assertRegex", "(", "fname", ",", "expected_regex", ",", "...
Fail unless ``filename`` matches ``expected_regex``. Parameters ---------- filename : str, bytes, file-like expected_regex : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
[ "Fail", "unless", "filename", "matches", "expected_regex", "." ]
f0c668be8344c70d4d63bc57e82c6f2da43c6925
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L706-L724
train
209,095
twosigma/marbles
marbles/mixins/marbles/mixins/mixins.py
FileMixins.assertFileNameNotRegex
def assertFileNameNotRegex(self, filename, expected_regex, msg=None): '''Fail if ``filename`` matches ``expected_regex``. Parameters ---------- filename : str, bytes, file-like expected_regex : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fname = self._get_file_name(filename) self.assertNotRegex(fname, expected_regex, msg=msg)
python
def assertFileNameNotRegex(self, filename, expected_regex, msg=None): '''Fail if ``filename`` matches ``expected_regex``. Parameters ---------- filename : str, bytes, file-like expected_regex : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fname = self._get_file_name(filename) self.assertNotRegex(fname, expected_regex, msg=msg)
[ "def", "assertFileNameNotRegex", "(", "self", ",", "filename", ",", "expected_regex", ",", "msg", "=", "None", ")", ":", "fname", "=", "self", ".", "_get_file_name", "(", "filename", ")", "self", ".", "assertNotRegex", "(", "fname", ",", "expected_regex", ",...
Fail if ``filename`` matches ``expected_regex``. Parameters ---------- filename : str, bytes, file-like expected_regex : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
[ "Fail", "if", "filename", "matches", "expected_regex", "." ]
f0c668be8344c70d4d63bc57e82c6f2da43c6925
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L726-L744
train
209,096
twosigma/marbles
marbles/mixins/marbles/mixins/mixins.py
FileMixins.assertFileTypeEqual
def assertFileTypeEqual(self, filename, extension, msg=None): '''Fail if ``filename`` does not have the given ``extension`` as determined by the ``==`` operator. Parameters ---------- filename : str, bytes, file-like extension : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' ftype = self._get_file_type(filename) self.assertEqual(ftype, extension, msg=msg)
python
def assertFileTypeEqual(self, filename, extension, msg=None): '''Fail if ``filename`` does not have the given ``extension`` as determined by the ``==`` operator. Parameters ---------- filename : str, bytes, file-like extension : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' ftype = self._get_file_type(filename) self.assertEqual(ftype, extension, msg=msg)
[ "def", "assertFileTypeEqual", "(", "self", ",", "filename", ",", "extension", ",", "msg", "=", "None", ")", ":", "ftype", "=", "self", ".", "_get_file_type", "(", "filename", ")", "self", ".", "assertEqual", "(", "ftype", ",", "extension", ",", "msg", "=...
Fail if ``filename`` does not have the given ``extension`` as determined by the ``==`` operator. Parameters ---------- filename : str, bytes, file-like extension : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
[ "Fail", "if", "filename", "does", "not", "have", "the", "given", "extension", "as", "determined", "by", "the", "==", "operator", "." ]
f0c668be8344c70d4d63bc57e82c6f2da43c6925
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L746-L765
train
209,097
twosigma/marbles
marbles/mixins/marbles/mixins/mixins.py
FileMixins.assertFileTypeNotEqual
def assertFileTypeNotEqual(self, filename, extension, msg=None): '''Fail if ``filename`` has the given ``extension`` as determined by the ``!=`` operator. Parameters ---------- filename : str, bytes, file-like extension : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' ftype = self._get_file_type(filename) self.assertNotEqual(ftype, extension, msg=msg)
python
def assertFileTypeNotEqual(self, filename, extension, msg=None): '''Fail if ``filename`` has the given ``extension`` as determined by the ``!=`` operator. Parameters ---------- filename : str, bytes, file-like extension : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' ftype = self._get_file_type(filename) self.assertNotEqual(ftype, extension, msg=msg)
[ "def", "assertFileTypeNotEqual", "(", "self", ",", "filename", ",", "extension", ",", "msg", "=", "None", ")", ":", "ftype", "=", "self", ".", "_get_file_type", "(", "filename", ")", "self", ".", "assertNotEqual", "(", "ftype", ",", "extension", ",", "msg"...
Fail if ``filename`` has the given ``extension`` as determined by the ``!=`` operator. Parameters ---------- filename : str, bytes, file-like extension : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
[ "Fail", "if", "filename", "has", "the", "given", "extension", "as", "determined", "by", "the", "!", "=", "operator", "." ]
f0c668be8344c70d4d63bc57e82c6f2da43c6925
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L767-L786
train
209,098
twosigma/marbles
marbles/mixins/marbles/mixins/mixins.py
FileMixins.assertFileEncodingEqual
def assertFileEncodingEqual(self, filename, encoding, msg=None): '''Fail if ``filename`` is not encoded with the given ``encoding`` as determined by the '==' operator. Parameters ---------- filename : str, bytes, file-like encoding : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fencoding = self._get_file_encoding(filename) fname = self._get_file_name(filename) standardMsg = '%s is not %s encoded' % (fname, encoding) self.assertEqual(fencoding.lower(), encoding.lower(), self._formatMessage(msg, standardMsg))
python
def assertFileEncodingEqual(self, filename, encoding, msg=None): '''Fail if ``filename`` is not encoded with the given ``encoding`` as determined by the '==' operator. Parameters ---------- filename : str, bytes, file-like encoding : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fencoding = self._get_file_encoding(filename) fname = self._get_file_name(filename) standardMsg = '%s is not %s encoded' % (fname, encoding) self.assertEqual(fencoding.lower(), encoding.lower(), self._formatMessage(msg, standardMsg))
[ "def", "assertFileEncodingEqual", "(", "self", ",", "filename", ",", "encoding", ",", "msg", "=", "None", ")", ":", "fencoding", "=", "self", ".", "_get_file_encoding", "(", "filename", ")", "fname", "=", "self", ".", "_get_file_name", "(", "filename", ")", ...
Fail if ``filename`` is not encoded with the given ``encoding`` as determined by the '==' operator. Parameters ---------- filename : str, bytes, file-like encoding : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
[ "Fail", "if", "filename", "is", "not", "encoded", "with", "the", "given", "encoding", "as", "determined", "by", "the", "==", "operator", "." ]
f0c668be8344c70d4d63bc57e82c6f2da43c6925
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L788-L813
train
209,099