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
twisted/vertex
vertex/ptcp.py
PTCPConnection.ackSoon
def ackSoon(self): """ Emit an acknowledgement packet soon. """ if self._ackTimer is None: def originateAck(): self._ackTimer = None self.originate(ack=True) self._ackTimer = reactor.callLater(0.1, originateAck) else: self._ackTimer.reset(ACK_DELAY)
python
def ackSoon(self): """ Emit an acknowledgement packet soon. """ if self._ackTimer is None: def originateAck(): self._ackTimer = None self.originate(ack=True) self._ackTimer = reactor.callLater(0.1, originateAck) else: self._ackTimer.reset(ACK_DELAY)
[ "def", "ackSoon", "(", "self", ")", ":", "if", "self", ".", "_ackTimer", "is", "None", ":", "def", "originateAck", "(", ")", ":", "self", ".", "_ackTimer", "=", "None", "self", ".", "originate", "(", "ack", "=", "True", ")", "self", ".", "_ackTimer",...
Emit an acknowledgement packet soon.
[ "Emit", "an", "acknowledgement", "packet", "soon", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/ptcp.py#L638-L648
train
42,900
twisted/vertex
vertex/ptcp.py
PTCPConnection.originate
def originate(self, data='', syn=False, ack=False, fin=False, rst=False): """ Create a packet, enqueue it to be sent, and return it. """ if self._ackTimer is not None: self._ackTimer.cancel() self._ackTimer = None if syn: # We really should be randomizing the ISN but until we finish the # implementations of the various bits of wraparound logic that were # started with relativeSequence assert self.nextSendSeqNum == 0, ( "NSSN = " + repr(self.nextSendSeqNum)) assert self.hostSendISN == 0 p = PTCPPacket.create(self.hostPseudoPort, self.peerPseudoPort, seqNum=(self.nextSendSeqNum + self.hostSendISN) % (2**32), ackNum=self.currentAckNum(), data=data, window=self.recvWindow, syn=syn, ack=ack, fin=fin, rst=rst, destination=self.peerAddressTuple) # do we want to enqueue this packet for retransmission? sl = p.segmentLength() self.nextSendSeqNum += sl if p.mustRetransmit(): # print self, 'originating retransmittable packet', len(self.retransmissionQueue) if self.retransmissionQueue: if self.retransmissionQueue[-1].fin: raise AssertionError("Sending %r after FIN??!" % (p,)) # print 'putting it on the queue' self.retransmissionQueue.append(p) # print 'and sending it later' self._retransmitLater() if not self.sendWindowRemaining: # len(self.retransmissionQueue) > 5: # print 'oh no my queue is too big' # This is a random number (5) because I ought to be summing the # packet lengths or something. self._writeBufferFull() else: # print 'my queue is still small enough', len(self.retransmissionQueue), self, self.sendWindowRemaining pass self.ptcp.sendPacket(p) return p
python
def originate(self, data='', syn=False, ack=False, fin=False, rst=False): """ Create a packet, enqueue it to be sent, and return it. """ if self._ackTimer is not None: self._ackTimer.cancel() self._ackTimer = None if syn: # We really should be randomizing the ISN but until we finish the # implementations of the various bits of wraparound logic that were # started with relativeSequence assert self.nextSendSeqNum == 0, ( "NSSN = " + repr(self.nextSendSeqNum)) assert self.hostSendISN == 0 p = PTCPPacket.create(self.hostPseudoPort, self.peerPseudoPort, seqNum=(self.nextSendSeqNum + self.hostSendISN) % (2**32), ackNum=self.currentAckNum(), data=data, window=self.recvWindow, syn=syn, ack=ack, fin=fin, rst=rst, destination=self.peerAddressTuple) # do we want to enqueue this packet for retransmission? sl = p.segmentLength() self.nextSendSeqNum += sl if p.mustRetransmit(): # print self, 'originating retransmittable packet', len(self.retransmissionQueue) if self.retransmissionQueue: if self.retransmissionQueue[-1].fin: raise AssertionError("Sending %r after FIN??!" % (p,)) # print 'putting it on the queue' self.retransmissionQueue.append(p) # print 'and sending it later' self._retransmitLater() if not self.sendWindowRemaining: # len(self.retransmissionQueue) > 5: # print 'oh no my queue is too big' # This is a random number (5) because I ought to be summing the # packet lengths or something. self._writeBufferFull() else: # print 'my queue is still small enough', len(self.retransmissionQueue), self, self.sendWindowRemaining pass self.ptcp.sendPacket(p) return p
[ "def", "originate", "(", "self", ",", "data", "=", "''", ",", "syn", "=", "False", ",", "ack", "=", "False", ",", "fin", "=", "False", ",", "rst", "=", "False", ")", ":", "if", "self", ".", "_ackTimer", "is", "not", "None", ":", "self", ".", "_...
Create a packet, enqueue it to be sent, and return it.
[ "Create", "a", "packet", "enqueue", "it", "to", "be", "sent", "and", "return", "it", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/ptcp.py#L650-L695
train
42,901
twisted/vertex
vertex/ptcp.py
PTCPConnection.connectionJustEstablished
def connectionJustEstablished(self): """ We sent out SYN, they acknowledged it. Congratulations, you have a new baby connection. """ assert not self.disconnecting assert not self.disconnected try: p = self.factory.buildProtocol(PTCPAddress( self.peerAddressTuple, self.pseudoPortPair)) p.makeConnection(self) except: log.msg("Exception during PTCP connection setup.") log.err() self.loseConnection() else: self.protocol = p
python
def connectionJustEstablished(self): """ We sent out SYN, they acknowledged it. Congratulations, you have a new baby connection. """ assert not self.disconnecting assert not self.disconnected try: p = self.factory.buildProtocol(PTCPAddress( self.peerAddressTuple, self.pseudoPortPair)) p.makeConnection(self) except: log.msg("Exception during PTCP connection setup.") log.err() self.loseConnection() else: self.protocol = p
[ "def", "connectionJustEstablished", "(", "self", ")", ":", "assert", "not", "self", ".", "disconnecting", "assert", "not", "self", ".", "disconnected", "try", ":", "p", "=", "self", ".", "factory", ".", "buildProtocol", "(", "PTCPAddress", "(", "self", ".", ...
We sent out SYN, they acknowledged it. Congratulations, you have a new baby connection.
[ "We", "sent", "out", "SYN", "they", "acknowledged", "it", ".", "Congratulations", "you", "have", "a", "new", "baby", "connection", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/ptcp.py#L745-L761
train
42,902
twisted/vertex
vertex/ptcp.py
PTCP.connect
def connect(self, factory, host, port, pseudoPort=1): """ Attempt to establish a new connection via PTCP to the given remote address. @param factory: A L{ClientFactory} which will be used to create an L{IProtocol} provider if the connection is successfully set up, or which will have failure callbacks invoked on it otherwise. @param host: The IP address of another listening PTCP port to connect to. @type host: C{str} @param port: The port number of that other listening PTCP port to connect to. @type port: C{int} @param pseudoPort: Not really implemented. Do not pass a value for this parameter or things will break. @return: A L{PTCPConnection} instance representing the new connection, but you really shouldn't use this for anything. Write a protocol! """ sourcePseudoPort = genConnID() % MAX_PSEUDO_PORT conn = self._connections[(pseudoPort, sourcePseudoPort, (host, port)) ] = PTCPConnection( sourcePseudoPort, pseudoPort, self, factory, (host, port)) conn.machine.appActiveOpen() return conn
python
def connect(self, factory, host, port, pseudoPort=1): """ Attempt to establish a new connection via PTCP to the given remote address. @param factory: A L{ClientFactory} which will be used to create an L{IProtocol} provider if the connection is successfully set up, or which will have failure callbacks invoked on it otherwise. @param host: The IP address of another listening PTCP port to connect to. @type host: C{str} @param port: The port number of that other listening PTCP port to connect to. @type port: C{int} @param pseudoPort: Not really implemented. Do not pass a value for this parameter or things will break. @return: A L{PTCPConnection} instance representing the new connection, but you really shouldn't use this for anything. Write a protocol! """ sourcePseudoPort = genConnID() % MAX_PSEUDO_PORT conn = self._connections[(pseudoPort, sourcePseudoPort, (host, port)) ] = PTCPConnection( sourcePseudoPort, pseudoPort, self, factory, (host, port)) conn.machine.appActiveOpen() return conn
[ "def", "connect", "(", "self", ",", "factory", ",", "host", ",", "port", ",", "pseudoPort", "=", "1", ")", ":", "sourcePseudoPort", "=", "genConnID", "(", ")", "%", "MAX_PSEUDO_PORT", "conn", "=", "self", ".", "_connections", "[", "(", "pseudoPort", ",",...
Attempt to establish a new connection via PTCP to the given remote address. @param factory: A L{ClientFactory} which will be used to create an L{IProtocol} provider if the connection is successfully set up, or which will have failure callbacks invoked on it otherwise. @param host: The IP address of another listening PTCP port to connect to. @type host: C{str} @param port: The port number of that other listening PTCP port to connect to. @type port: C{int} @param pseudoPort: Not really implemented. Do not pass a value for this parameter or things will break. @return: A L{PTCPConnection} instance representing the new connection, but you really shouldn't use this for anything. Write a protocol!
[ "Attempt", "to", "establish", "a", "new", "connection", "via", "PTCP", "to", "the", "given", "remote", "address", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/ptcp.py#L871-L901
train
42,903
twisted/vertex
vertex/ptcp.py
PTCP.waitForAllConnectionsToClose
def waitForAllConnectionsToClose(self): """ Wait for all currently-open connections to enter the 'CLOSED' state. Currently this is only usable from test fixtures. """ if not self._connections: return self._stop() return self._allConnectionsClosed.deferred().addBoth(self._stop)
python
def waitForAllConnectionsToClose(self): """ Wait for all currently-open connections to enter the 'CLOSED' state. Currently this is only usable from test fixtures. """ if not self._connections: return self._stop() return self._allConnectionsClosed.deferred().addBoth(self._stop)
[ "def", "waitForAllConnectionsToClose", "(", "self", ")", ":", "if", "not", "self", ".", "_connections", ":", "return", "self", ".", "_stop", "(", ")", "return", "self", ".", "_allConnectionsClosed", ".", "deferred", "(", ")", ".", "addBoth", "(", "self", "...
Wait for all currently-open connections to enter the 'CLOSED' state. Currently this is only usable from test fixtures.
[ "Wait", "for", "all", "currently", "-", "open", "connections", "to", "enter", "the", "CLOSED", "state", ".", "Currently", "this", "is", "only", "usable", "from", "test", "fixtures", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/ptcp.py#L986-L993
train
42,904
twisted/vertex
vertex/q2qstandalone.py
StandaloneQ2Q.setup_Q2Q
def setup_Q2Q(self, path, q2qPortnum=q2q.port, inboundTCPPortnum=q2q.port+1, publicIP=None ): """Set up a Q2Q service. """ store = DirectoryCertificateAndUserStore(path) # store.addPrivateCertificate("kazekage") # store.addUser("kazekage", "username", "password1234") self.attach(q2q.Q2QService( protocolFactoryFactory=IdentityAdminFactory(store).examineRequest, certificateStorage=store, portal=Portal(store, checkers=[store]), q2qPortnum=q2qPortnum, inboundTCPPortnum=inboundTCPPortnum, publicIP=publicIP, ))
python
def setup_Q2Q(self, path, q2qPortnum=q2q.port, inboundTCPPortnum=q2q.port+1, publicIP=None ): """Set up a Q2Q service. """ store = DirectoryCertificateAndUserStore(path) # store.addPrivateCertificate("kazekage") # store.addUser("kazekage", "username", "password1234") self.attach(q2q.Q2QService( protocolFactoryFactory=IdentityAdminFactory(store).examineRequest, certificateStorage=store, portal=Portal(store, checkers=[store]), q2qPortnum=q2qPortnum, inboundTCPPortnum=inboundTCPPortnum, publicIP=publicIP, ))
[ "def", "setup_Q2Q", "(", "self", ",", "path", ",", "q2qPortnum", "=", "q2q", ".", "port", ",", "inboundTCPPortnum", "=", "q2q", ".", "port", "+", "1", ",", "publicIP", "=", "None", ")", ":", "store", "=", "DirectoryCertificateAndUserStore", "(", "path", ...
Set up a Q2Q service.
[ "Set", "up", "a", "Q2Q", "service", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/q2qstandalone.py#L145-L163
train
42,905
bkircher/python-rpm-spec
pyrpm/spec.py
replace_macros
def replace_macros(string, spec=None): """Replace all macros in given string with corresponding values. For example: a string '%{name}-%{version}.tar.gz' will be transformed to 'foo-2.0.tar.gz'. :param string A string containing macros that you want to be replaced :param spec An optional spec file. If given, definitions in that spec file will be used to replace macros. :return A string where all macros in given input are substituted as good as possible. """ if spec: assert isinstance(spec, Spec) def _is_conditional(macro: str) -> bool: return macro.startswith("?") or macro.startswith("!") def _test_conditional(macro: str) -> bool: if macro[0] == "?": return True if macro[0] == "!": return False raise Exception("Given string is not a conditional macro") def _macro_repl(match): macro_name = match.group(1) if _is_conditional(macro_name) and spec: parts = macro_name[1:].split(sep=":", maxsplit=1) assert parts if _test_conditional(macro_name): # ? if hasattr(spec, parts[0]): if len(parts) == 2: return parts[1] return getattr(spec, parts[0], None) return "" else: # ! if not hasattr(spec, parts[0]): if len(parts) == 2: return parts[1] return getattr(spec, parts[0], None) return "" if spec: value = getattr(spec, macro_name, None) if value: return str(value) return match.string[match.start() : match.end()] # Recursively expand macros # Note: If macros are not defined in the spec file, this won't try to # expand them. while True: ret = re.sub(_macro_pattern, _macro_repl, string) if ret != string: string = ret continue return ret
python
def replace_macros(string, spec=None): """Replace all macros in given string with corresponding values. For example: a string '%{name}-%{version}.tar.gz' will be transformed to 'foo-2.0.tar.gz'. :param string A string containing macros that you want to be replaced :param spec An optional spec file. If given, definitions in that spec file will be used to replace macros. :return A string where all macros in given input are substituted as good as possible. """ if spec: assert isinstance(spec, Spec) def _is_conditional(macro: str) -> bool: return macro.startswith("?") or macro.startswith("!") def _test_conditional(macro: str) -> bool: if macro[0] == "?": return True if macro[0] == "!": return False raise Exception("Given string is not a conditional macro") def _macro_repl(match): macro_name = match.group(1) if _is_conditional(macro_name) and spec: parts = macro_name[1:].split(sep=":", maxsplit=1) assert parts if _test_conditional(macro_name): # ? if hasattr(spec, parts[0]): if len(parts) == 2: return parts[1] return getattr(spec, parts[0], None) return "" else: # ! if not hasattr(spec, parts[0]): if len(parts) == 2: return parts[1] return getattr(spec, parts[0], None) return "" if spec: value = getattr(spec, macro_name, None) if value: return str(value) return match.string[match.start() : match.end()] # Recursively expand macros # Note: If macros are not defined in the spec file, this won't try to # expand them. while True: ret = re.sub(_macro_pattern, _macro_repl, string) if ret != string: string = ret continue return ret
[ "def", "replace_macros", "(", "string", ",", "spec", "=", "None", ")", ":", "if", "spec", ":", "assert", "isinstance", "(", "spec", ",", "Spec", ")", "def", "_is_conditional", "(", "macro", ":", "str", ")", "->", "bool", ":", "return", "macro", ".", ...
Replace all macros in given string with corresponding values. For example: a string '%{name}-%{version}.tar.gz' will be transformed to 'foo-2.0.tar.gz'. :param string A string containing macros that you want to be replaced :param spec An optional spec file. If given, definitions in that spec file will be used to replace macros. :return A string where all macros in given input are substituted as good as possible.
[ "Replace", "all", "macros", "in", "given", "string", "with", "corresponding", "values", "." ]
ed0e5180967c87b6d6514ad27f0a8c66c9be4d1c
https://github.com/bkircher/python-rpm-spec/blob/ed0e5180967c87b6d6514ad27f0a8c66c9be4d1c/pyrpm/spec.py#L362-L423
train
42,906
bkircher/python-rpm-spec
pyrpm/spec.py
_Tag.update
def update(self, spec_obj, context, match_obj, line): """Update given spec object and parse context and return them again. :param spec_obj: An instance of Spec class :param context: The parse context :param match_obj: The re.match object :param line: The original line :return: Given updated Spec instance and parse context dictionary. """ assert spec_obj assert context assert match_obj assert line return self.update_impl(spec_obj, context, match_obj, line)
python
def update(self, spec_obj, context, match_obj, line): """Update given spec object and parse context and return them again. :param spec_obj: An instance of Spec class :param context: The parse context :param match_obj: The re.match object :param line: The original line :return: Given updated Spec instance and parse context dictionary. """ assert spec_obj assert context assert match_obj assert line return self.update_impl(spec_obj, context, match_obj, line)
[ "def", "update", "(", "self", ",", "spec_obj", ",", "context", ",", "match_obj", ",", "line", ")", ":", "assert", "spec_obj", "assert", "context", "assert", "match_obj", "assert", "line", "return", "self", ".", "update_impl", "(", "spec_obj", ",", "context",...
Update given spec object and parse context and return them again. :param spec_obj: An instance of Spec class :param context: The parse context :param match_obj: The re.match object :param line: The original line :return: Given updated Spec instance and parse context dictionary.
[ "Update", "given", "spec", "object", "and", "parse", "context", "and", "return", "them", "again", "." ]
ed0e5180967c87b6d6514ad27f0a8c66c9be4d1c
https://github.com/bkircher/python-rpm-spec/blob/ed0e5180967c87b6d6514ad27f0a8c66c9be4d1c/pyrpm/spec.py#L28-L43
train
42,907
bkircher/python-rpm-spec
pyrpm/spec.py
Spec.packages_dict
def packages_dict(self): """All packages in this RPM spec as a dictionary. You can access the individual packages by their package name, e.g., git_spec.packages_dict['git-doc'] """ assert self.packages return dict(zip([package.name for package in self.packages], self.packages))
python
def packages_dict(self): """All packages in this RPM spec as a dictionary. You can access the individual packages by their package name, e.g., git_spec.packages_dict['git-doc'] """ assert self.packages return dict(zip([package.name for package in self.packages], self.packages))
[ "def", "packages_dict", "(", "self", ")", ":", "assert", "self", ".", "packages", "return", "dict", "(", "zip", "(", "[", "package", ".", "name", "for", "package", "in", "self", ".", "packages", "]", ",", "self", ".", "packages", ")", ")" ]
All packages in this RPM spec as a dictionary. You can access the individual packages by their package name, e.g., git_spec.packages_dict['git-doc']
[ "All", "packages", "in", "this", "RPM", "spec", "as", "a", "dictionary", "." ]
ed0e5180967c87b6d6514ad27f0a8c66c9be4d1c
https://github.com/bkircher/python-rpm-spec/blob/ed0e5180967c87b6d6514ad27f0a8c66c9be4d1c/pyrpm/spec.py#L321-L330
train
42,908
bkircher/python-rpm-spec
pyrpm/spec.py
Spec.from_file
def from_file(filename): """Creates a new Spec object from a given file. :param filename: The path to the spec file. :return: A new Spec object. """ spec = Spec() with open(filename, "r", encoding="utf-8") as f: parse_context = {"current_subpackage": None} for line in f: spec, parse_context = _parse(spec, parse_context, line) return spec
python
def from_file(filename): """Creates a new Spec object from a given file. :param filename: The path to the spec file. :return: A new Spec object. """ spec = Spec() with open(filename, "r", encoding="utf-8") as f: parse_context = {"current_subpackage": None} for line in f: spec, parse_context = _parse(spec, parse_context, line) return spec
[ "def", "from_file", "(", "filename", ")", ":", "spec", "=", "Spec", "(", ")", "with", "open", "(", "filename", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "parse_context", "=", "{", "\"current_subpackage\"", ":", "None", "}", ...
Creates a new Spec object from a given file. :param filename: The path to the spec file. :return: A new Spec object.
[ "Creates", "a", "new", "Spec", "object", "from", "a", "given", "file", "." ]
ed0e5180967c87b6d6514ad27f0a8c66c9be4d1c
https://github.com/bkircher/python-rpm-spec/blob/ed0e5180967c87b6d6514ad27f0a8c66c9be4d1c/pyrpm/spec.py#L333-L345
train
42,909
bkircher/python-rpm-spec
pyrpm/spec.py
Spec.from_string
def from_string(string: str): """Creates a new Spec object from a given string. :param string: The contents of a spec file. :return: A new Spec object. """ spec = Spec() parse_context = {"current_subpackage": None} for line in string.splitlines(): spec, parse_context = _parse(spec, parse_context, line) return spec
python
def from_string(string: str): """Creates a new Spec object from a given string. :param string: The contents of a spec file. :return: A new Spec object. """ spec = Spec() parse_context = {"current_subpackage": None} for line in string.splitlines(): spec, parse_context = _parse(spec, parse_context, line) return spec
[ "def", "from_string", "(", "string", ":", "str", ")", ":", "spec", "=", "Spec", "(", ")", "parse_context", "=", "{", "\"current_subpackage\"", ":", "None", "}", "for", "line", "in", "string", ".", "splitlines", "(", ")", ":", "spec", ",", "parse_context"...
Creates a new Spec object from a given string. :param string: The contents of a spec file. :return: A new Spec object.
[ "Creates", "a", "new", "Spec", "object", "from", "a", "given", "string", "." ]
ed0e5180967c87b6d6514ad27f0a8c66c9be4d1c
https://github.com/bkircher/python-rpm-spec/blob/ed0e5180967c87b6d6514ad27f0a8c66c9be4d1c/pyrpm/spec.py#L348-L359
train
42,910
mikeboers/Flask-ACL
flask_acl/core.py
parse_acl
def parse_acl(acl_iter): """Parse a string, or list of ACE definitions, into usable ACEs.""" if isinstance(acl_iter, basestring): acl_iter = [acl_iter] for chunk in acl_iter: if isinstance(chunk, basestring): chunk = chunk.splitlines() chunk = [re.sub(r'#.+', '', line).strip() for line in chunk] chunk = filter(None, chunk) else: chunk = [chunk] for ace in chunk: # If this was provided as a string, then parse the permission set. # Otherwise, use it as-is, which will result in an equality test. if isinstance(ace, basestring): ace = ace.split(None, 2) state, predicate, permission_set = ace yield parse_state(state), parse_predicate(predicate), parse_permission_set(permission_set) else: state, predicate, permission_set = ace yield parse_state(state), parse_predicate(predicate), permission_set
python
def parse_acl(acl_iter): """Parse a string, or list of ACE definitions, into usable ACEs.""" if isinstance(acl_iter, basestring): acl_iter = [acl_iter] for chunk in acl_iter: if isinstance(chunk, basestring): chunk = chunk.splitlines() chunk = [re.sub(r'#.+', '', line).strip() for line in chunk] chunk = filter(None, chunk) else: chunk = [chunk] for ace in chunk: # If this was provided as a string, then parse the permission set. # Otherwise, use it as-is, which will result in an equality test. if isinstance(ace, basestring): ace = ace.split(None, 2) state, predicate, permission_set = ace yield parse_state(state), parse_predicate(predicate), parse_permission_set(permission_set) else: state, predicate, permission_set = ace yield parse_state(state), parse_predicate(predicate), permission_set
[ "def", "parse_acl", "(", "acl_iter", ")", ":", "if", "isinstance", "(", "acl_iter", ",", "basestring", ")", ":", "acl_iter", "=", "[", "acl_iter", "]", "for", "chunk", "in", "acl_iter", ":", "if", "isinstance", "(", "chunk", ",", "basestring", ")", ":", ...
Parse a string, or list of ACE definitions, into usable ACEs.
[ "Parse", "a", "string", "or", "list", "of", "ACE", "definitions", "into", "usable", "ACEs", "." ]
7339b89f96ad8686d1526e25c138244ad912e12d
https://github.com/mikeboers/Flask-ACL/blob/7339b89f96ad8686d1526e25c138244ad912e12d/flask_acl/core.py#L8-L33
train
42,911
mikeboers/Flask-ACL
flask_acl/core.py
iter_object_acl
def iter_object_acl(root): """Child-first discovery of ACEs for an object. Walks the ACL graph via ``__acl_bases__`` and yields the ACEs parsed from ``__acl__`` on each object. """ for obj in iter_object_graph(root): for ace in parse_acl(getattr(obj, '__acl__', ())): yield ace
python
def iter_object_acl(root): """Child-first discovery of ACEs for an object. Walks the ACL graph via ``__acl_bases__`` and yields the ACEs parsed from ``__acl__`` on each object. """ for obj in iter_object_graph(root): for ace in parse_acl(getattr(obj, '__acl__', ())): yield ace
[ "def", "iter_object_acl", "(", "root", ")", ":", "for", "obj", "in", "iter_object_graph", "(", "root", ")", ":", "for", "ace", "in", "parse_acl", "(", "getattr", "(", "obj", ",", "'__acl__'", ",", "(", ")", ")", ")", ":", "yield", "ace" ]
Child-first discovery of ACEs for an object. Walks the ACL graph via ``__acl_bases__`` and yields the ACEs parsed from ``__acl__`` on each object.
[ "Child", "-", "first", "discovery", "of", "ACEs", "for", "an", "object", "." ]
7339b89f96ad8686d1526e25c138244ad912e12d
https://github.com/mikeboers/Flask-ACL/blob/7339b89f96ad8686d1526e25c138244ad912e12d/flask_acl/core.py#L48-L58
train
42,912
mikeboers/Flask-ACL
flask_acl/core.py
get_object_context
def get_object_context(root): """Depth-first discovery of authentication context for an object. Walks the ACL graph via ``__acl_bases__`` and merges the ``__acl_context__`` attributes. """ context = {} for obj in iter_object_graph(root, parents_first=True): context.update(getattr(obj, '__acl_context__', {})) return context
python
def get_object_context(root): """Depth-first discovery of authentication context for an object. Walks the ACL graph via ``__acl_bases__`` and merges the ``__acl_context__`` attributes. """ context = {} for obj in iter_object_graph(root, parents_first=True): context.update(getattr(obj, '__acl_context__', {})) return context
[ "def", "get_object_context", "(", "root", ")", ":", "context", "=", "{", "}", "for", "obj", "in", "iter_object_graph", "(", "root", ",", "parents_first", "=", "True", ")", ":", "context", ".", "update", "(", "getattr", "(", "obj", ",", "'__acl_context__'",...
Depth-first discovery of authentication context for an object. Walks the ACL graph via ``__acl_bases__`` and merges the ``__acl_context__`` attributes.
[ "Depth", "-", "first", "discovery", "of", "authentication", "context", "for", "an", "object", "." ]
7339b89f96ad8686d1526e25c138244ad912e12d
https://github.com/mikeboers/Flask-ACL/blob/7339b89f96ad8686d1526e25c138244ad912e12d/flask_acl/core.py#L61-L72
train
42,913
MycroftAI/mycroft-skills-manager
msm/skills_data.py
load_skills_data
def load_skills_data() -> dict: """Contains info on how skills should be updated""" skills_data_file = expanduser('~/.mycroft/skills.json') if isfile(skills_data_file): try: with open(skills_data_file) as f: return json.load(f) except json.JSONDecodeError: return {} else: return {}
python
def load_skills_data() -> dict: """Contains info on how skills should be updated""" skills_data_file = expanduser('~/.mycroft/skills.json') if isfile(skills_data_file): try: with open(skills_data_file) as f: return json.load(f) except json.JSONDecodeError: return {} else: return {}
[ "def", "load_skills_data", "(", ")", "->", "dict", ":", "skills_data_file", "=", "expanduser", "(", "'~/.mycroft/skills.json'", ")", "if", "isfile", "(", "skills_data_file", ")", ":", "try", ":", "with", "open", "(", "skills_data_file", ")", "as", "f", ":", ...
Contains info on how skills should be updated
[ "Contains", "info", "on", "how", "skills", "should", "be", "updated" ]
5acef240de42e8ceae2e82bc7492ffee33288b00
https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/skills_data.py#L9-L19
train
42,914
MycroftAI/mycroft-skills-manager
msm/skills_data.py
get_skill_entry
def get_skill_entry(name, skills_data) -> dict: """ Find a skill entry in the skills_data and returns it. """ for e in skills_data.get('skills', []): if e.get('name') == name: return e return {}
python
def get_skill_entry(name, skills_data) -> dict: """ Find a skill entry in the skills_data and returns it. """ for e in skills_data.get('skills', []): if e.get('name') == name: return e return {}
[ "def", "get_skill_entry", "(", "name", ",", "skills_data", ")", "->", "dict", ":", "for", "e", "in", "skills_data", ".", "get", "(", "'skills'", ",", "[", "]", ")", ":", "if", "e", ".", "get", "(", "'name'", ")", "==", "name", ":", "return", "e", ...
Find a skill entry in the skills_data and returns it.
[ "Find", "a", "skill", "entry", "in", "the", "skills_data", "and", "returns", "it", "." ]
5acef240de42e8ceae2e82bc7492ffee33288b00
https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/skills_data.py#L28-L33
train
42,915
twisted/vertex
vertex/depserv.py
DependencyService.deploy
def deploy(Class, name=None, uid=None, gid=None, **kw): """ Create an application with the give name, uid, and gid. The application has one child service, an instance of Class configured based on the additional keyword arguments passed. The application is not persistable. @param Class: @param name: @param uid: @param gid: @param kw: @return: """ svc = Class(**kw) if name is None: name = Class.__name__ # Make it easier (possible) to find this service by name later on svc.setName(name) app = service.Application(name, uid=uid, gid=gid) app.addComponent(NotPersistable(app), ignoreClass=True) svc.setServiceParent(app) return app
python
def deploy(Class, name=None, uid=None, gid=None, **kw): """ Create an application with the give name, uid, and gid. The application has one child service, an instance of Class configured based on the additional keyword arguments passed. The application is not persistable. @param Class: @param name: @param uid: @param gid: @param kw: @return: """ svc = Class(**kw) if name is None: name = Class.__name__ # Make it easier (possible) to find this service by name later on svc.setName(name) app = service.Application(name, uid=uid, gid=gid) app.addComponent(NotPersistable(app), ignoreClass=True) svc.setServiceParent(app) return app
[ "def", "deploy", "(", "Class", ",", "name", "=", "None", ",", "uid", "=", "None", ",", "gid", "=", "None", ",", "*", "*", "kw", ")", ":", "svc", "=", "Class", "(", "*", "*", "kw", ")", "if", "name", "is", "None", ":", "name", "=", "Class", ...
Create an application with the give name, uid, and gid. The application has one child service, an instance of Class configured based on the additional keyword arguments passed. The application is not persistable. @param Class: @param name: @param uid: @param gid: @param kw: @return:
[ "Create", "an", "application", "with", "the", "give", "name", "uid", "and", "gid", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/depserv.py#L148-L176
train
42,916
twisted/vertex
vertex/depserv.py
DependencyService.addServer
def addServer(self, normalPort, sslPort, f, name): """ Add a TCP and an SSL server. Name them `name` and `name`+'s'. @param normalPort: @param sslPort: @param f: @param name: """ tcp = internet.TCPServer(normalPort, f) tcp.setName(name) self.servers.append(tcp) if sslPort is not None: ssl = internet.SSLServer(sslPort, f, contextFactory=self.sslfac) ssl.setName(name+'s') self.servers.append(ssl)
python
def addServer(self, normalPort, sslPort, f, name): """ Add a TCP and an SSL server. Name them `name` and `name`+'s'. @param normalPort: @param sslPort: @param f: @param name: """ tcp = internet.TCPServer(normalPort, f) tcp.setName(name) self.servers.append(tcp) if sslPort is not None: ssl = internet.SSLServer(sslPort, f, contextFactory=self.sslfac) ssl.setName(name+'s') self.servers.append(ssl)
[ "def", "addServer", "(", "self", ",", "normalPort", ",", "sslPort", ",", "f", ",", "name", ")", ":", "tcp", "=", "internet", ".", "TCPServer", "(", "normalPort", ",", "f", ")", "tcp", ".", "setName", "(", "name", ")", "self", ".", "servers", ".", "...
Add a TCP and an SSL server. Name them `name` and `name`+'s'. @param normalPort: @param sslPort: @param f: @param name:
[ "Add", "a", "TCP", "and", "an", "SSL", "server", ".", "Name", "them", "name", "and", "name", "+", "s", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/depserv.py#L189-L204
train
42,917
twisted/vertex
vertex/q2q.py
Q2Q._write
def _write(self, body, id): """ Respond to a WRITE command, sending some data over a virtual channel created by VIRTUAL. The answer is simply an acknowledgement, as it is simply meant to note that the write went through without errors. An occurrence of I{Write} on the wire, together with the response generated by this method, might have this apperance:: C: -Command: Write C: -Ask: 1 C: -Length: 13 C: Id: glyph@divmod.com->radix@twistedmatrix.com:q2q-example:0 C: C: HELLO WORLD C: S: -Answer: 1 S: """ if id not in self.connections: raise error.ConnectionDone() connection = self.connections[id] connection.dataReceived(body) return {}
python
def _write(self, body, id): """ Respond to a WRITE command, sending some data over a virtual channel created by VIRTUAL. The answer is simply an acknowledgement, as it is simply meant to note that the write went through without errors. An occurrence of I{Write} on the wire, together with the response generated by this method, might have this apperance:: C: -Command: Write C: -Ask: 1 C: -Length: 13 C: Id: glyph@divmod.com->radix@twistedmatrix.com:q2q-example:0 C: C: HELLO WORLD C: S: -Answer: 1 S: """ if id not in self.connections: raise error.ConnectionDone() connection = self.connections[id] connection.dataReceived(body) return {}
[ "def", "_write", "(", "self", ",", "body", ",", "id", ")", ":", "if", "id", "not", "in", "self", ".", "connections", ":", "raise", "error", ".", "ConnectionDone", "(", ")", "connection", "=", "self", ".", "connections", "[", "id", "]", "connection", ...
Respond to a WRITE command, sending some data over a virtual channel created by VIRTUAL. The answer is simply an acknowledgement, as it is simply meant to note that the write went through without errors. An occurrence of I{Write} on the wire, together with the response generated by this method, might have this apperance:: C: -Command: Write C: -Ask: 1 C: -Length: 13 C: Id: glyph@divmod.com->radix@twistedmatrix.com:q2q-example:0 C: C: HELLO WORLD C: S: -Answer: 1 S:
[ "Respond", "to", "a", "WRITE", "command", "sending", "some", "data", "over", "a", "virtual", "channel", "created", "by", "VIRTUAL", ".", "The", "answer", "is", "simply", "an", "acknowledgement", "as", "it", "is", "simply", "meant", "to", "note", "that", "t...
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/q2q.py#L1134-L1158
train
42,918
twisted/vertex
vertex/q2q.py
Q2Q._close
def _close(self, id): """ Respond to a CLOSE command, dumping some data onto the stream. As with WRITE, this returns an empty acknowledgement. An occurrence of I{Close} on the wire, together with the response generated by this method, might have this apperance:: C: -Command: Close C: -Ask: 1 C: Id: glyph@divmod.com->radix@twistedmatrix.com:q2q-example:0 C: S: -Answer: 1 S: """ # The connection is removed from the mapping by connectionLost. connection = self.connections[id] connection.connectionLost(Failure(CONNECTION_DONE)) return {}
python
def _close(self, id): """ Respond to a CLOSE command, dumping some data onto the stream. As with WRITE, this returns an empty acknowledgement. An occurrence of I{Close} on the wire, together with the response generated by this method, might have this apperance:: C: -Command: Close C: -Ask: 1 C: Id: glyph@divmod.com->radix@twistedmatrix.com:q2q-example:0 C: S: -Answer: 1 S: """ # The connection is removed from the mapping by connectionLost. connection = self.connections[id] connection.connectionLost(Failure(CONNECTION_DONE)) return {}
[ "def", "_close", "(", "self", ",", "id", ")", ":", "# The connection is removed from the mapping by connectionLost.", "connection", "=", "self", ".", "connections", "[", "id", "]", "connection", ".", "connectionLost", "(", "Failure", "(", "CONNECTION_DONE", ")", ")"...
Respond to a CLOSE command, dumping some data onto the stream. As with WRITE, this returns an empty acknowledgement. An occurrence of I{Close} on the wire, together with the response generated by this method, might have this apperance:: C: -Command: Close C: -Ask: 1 C: Id: glyph@divmod.com->radix@twistedmatrix.com:q2q-example:0 C: S: -Answer: 1 S:
[ "Respond", "to", "a", "CLOSE", "command", "dumping", "some", "data", "onto", "the", "stream", ".", "As", "with", "WRITE", "this", "returns", "an", "empty", "acknowledgement", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/q2q.py#L1162-L1181
train
42,919
twisted/vertex
vertex/q2q.py
Q2Q._sign
def _sign(self, certificate_request, password): """ Respond to a request to sign a CSR for a user or agent located within our domain. """ if self.service.portal is None: raise BadCertificateRequest("This agent cannot sign certificates.") subj = certificate_request.getSubject() sk = subj.keys() if 'commonName' not in sk: raise BadCertificateRequest( "Certificate requested with bad subject: %s" % (sk,)) uandd = subj.commonName.split("@") if len(uandd) != 2: raise BadCertificateRequest( "Won't sign certificates for other domains" ) domain = uandd[1] CS = self.service.certificateStorage ourCert = CS.getPrivateCertificate(domain) D = self.service.portal.login( UsernameShadowPassword(subj.commonName, password), self, ivertex.IQ2QUser) def _(ial): (iface, aspect, logout) = ial ser = CS.genSerial(domain) return dict(certificate=aspect.signCertificateRequest( certificate_request, ourCert, ser)) return D.addCallback(_)
python
def _sign(self, certificate_request, password): """ Respond to a request to sign a CSR for a user or agent located within our domain. """ if self.service.portal is None: raise BadCertificateRequest("This agent cannot sign certificates.") subj = certificate_request.getSubject() sk = subj.keys() if 'commonName' not in sk: raise BadCertificateRequest( "Certificate requested with bad subject: %s" % (sk,)) uandd = subj.commonName.split("@") if len(uandd) != 2: raise BadCertificateRequest( "Won't sign certificates for other domains" ) domain = uandd[1] CS = self.service.certificateStorage ourCert = CS.getPrivateCertificate(domain) D = self.service.portal.login( UsernameShadowPassword(subj.commonName, password), self, ivertex.IQ2QUser) def _(ial): (iface, aspect, logout) = ial ser = CS.genSerial(domain) return dict(certificate=aspect.signCertificateRequest( certificate_request, ourCert, ser)) return D.addCallback(_)
[ "def", "_sign", "(", "self", ",", "certificate_request", ",", "password", ")", ":", "if", "self", ".", "service", ".", "portal", "is", "None", ":", "raise", "BadCertificateRequest", "(", "\"This agent cannot sign certificates.\"", ")", "subj", "=", "certificate_re...
Respond to a request to sign a CSR for a user or agent located within our domain.
[ "Respond", "to", "a", "request", "to", "sign", "a", "CSR", "for", "a", "user", "or", "agent", "located", "within", "our", "domain", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/q2q.py#L1185-L1221
train
42,920
twisted/vertex
vertex/q2q.py
Q2Q._retrieveRemoteCertificate
def _retrieveRemoteCertificate(self, From, port=port): """ The entire conversation, starting with TCP handshake and ending at disconnect, to retrieve a foreign domain's certificate for the first time. """ CS = self.service.certificateStorage host = str(From.domainAddress()) p = AMP() p.wrapper = self.wrapper f = protocol.ClientCreator(reactor, lambda: p) connD = f.connectTCP(host, port) def connected(proto): dhost = From.domainAddress() iddom = proto.callRemote(Identify, subject=dhost) def gotCert(identifyBox): theirCert = identifyBox['certificate'] theirIssuer = theirCert.getIssuer().commonName theirName = theirCert.getSubject().commonName if (theirName != str(dhost)): raise VerifyError( "%r claimed it was %r in IDENTIFY response" % (theirName, dhost)) if (theirIssuer != str(dhost)): raise VerifyError( "self-signed %r claimed it was issued by " "%r in IDENTIFY response" % (dhost, theirIssuer)) def storedCert(ignored): return theirCert return CS.storeSelfSignedCertificate( str(dhost), theirCert).addCallback(storedCert) def nothingify(x): proto.transport.loseConnection() return x return iddom.addCallback(gotCert).addBoth(nothingify) connD.addCallback(connected) return connD
python
def _retrieveRemoteCertificate(self, From, port=port): """ The entire conversation, starting with TCP handshake and ending at disconnect, to retrieve a foreign domain's certificate for the first time. """ CS = self.service.certificateStorage host = str(From.domainAddress()) p = AMP() p.wrapper = self.wrapper f = protocol.ClientCreator(reactor, lambda: p) connD = f.connectTCP(host, port) def connected(proto): dhost = From.domainAddress() iddom = proto.callRemote(Identify, subject=dhost) def gotCert(identifyBox): theirCert = identifyBox['certificate'] theirIssuer = theirCert.getIssuer().commonName theirName = theirCert.getSubject().commonName if (theirName != str(dhost)): raise VerifyError( "%r claimed it was %r in IDENTIFY response" % (theirName, dhost)) if (theirIssuer != str(dhost)): raise VerifyError( "self-signed %r claimed it was issued by " "%r in IDENTIFY response" % (dhost, theirIssuer)) def storedCert(ignored): return theirCert return CS.storeSelfSignedCertificate( str(dhost), theirCert).addCallback(storedCert) def nothingify(x): proto.transport.loseConnection() return x return iddom.addCallback(gotCert).addBoth(nothingify) connD.addCallback(connected) return connD
[ "def", "_retrieveRemoteCertificate", "(", "self", ",", "From", ",", "port", "=", "port", ")", ":", "CS", "=", "self", ".", "service", ".", "certificateStorage", "host", "=", "str", "(", "From", ".", "domainAddress", "(", ")", ")", "p", "=", "AMP", "(",...
The entire conversation, starting with TCP handshake and ending at disconnect, to retrieve a foreign domain's certificate for the first time.
[ "The", "entire", "conversation", "starting", "with", "TCP", "handshake", "and", "ending", "at", "disconnect", "to", "retrieve", "a", "foreign", "domain", "s", "certificate", "for", "the", "first", "time", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/q2q.py#L1298-L1335
train
42,921
twisted/vertex
vertex/q2q.py
Q2Q.connect
def connect(self, From, to, protocolName, clientFactory, chooser): """ Issue an INBOUND command, creating a virtual connection to the peer, given identifying information about the endpoint to connect to, and a protocol factory. @param clientFactory: a *Client* ProtocolFactory instance which will generate a protocol upon connect. @return: a Deferred which fires with the protocol instance that was connected, or fails with AttemptsFailed if the connection was not possible. """ publicIP = self._determinePublicIP() A = dict(From=From, to=to, protocol=protocolName) if self.service.dispatcher is not None: # Tell them exactly where they can shove it A['udp_source'] = (publicIP, self.service.sharedUDPPortnum) else: # Don't tell them because we don't know log.msg("dispatcher unavailable when connecting") D = self.callRemote(Inbound, **A) def _connected(answer): listenersD = defer.maybeDeferred(chooser, answer['listeners']) def gotListeners(listeners): allConnectionAttempts = [] for listener in listeners: d = self.attemptConnectionMethods( listener['methods'], listener['id'], From, to, protocolName, clientFactory, ) allConnectionAttempts.append(d) return defer.DeferredList(allConnectionAttempts) listenersD.addCallback(gotListeners) def finishedAllAttempts(results): succeededAny = False failures = [] if not results: return Failure(NoAttemptsMade( "there was no available path for connections " "(%r->%r/%s)" % (From, to, protocolName))) for succeeded, result in results: if succeeded: succeededAny = True randomConnection = result break else: failures.append(result) if not succeededAny: return Failure( AttemptsFailed( [failure.getBriefTraceback() for failure in failures] ) ) # XXX TODO: this connection is really random; connectQ2Q should # not return one of the connections it's made, put it into your # protocol's connectionMade handler return randomConnection return listenersD.addCallback(finishedAllAttempts) return D.addCallback(_connected)
python
def connect(self, From, to, protocolName, clientFactory, chooser): """ Issue an INBOUND command, creating a virtual connection to the peer, given identifying information about the endpoint to connect to, and a protocol factory. @param clientFactory: a *Client* ProtocolFactory instance which will generate a protocol upon connect. @return: a Deferred which fires with the protocol instance that was connected, or fails with AttemptsFailed if the connection was not possible. """ publicIP = self._determinePublicIP() A = dict(From=From, to=to, protocol=protocolName) if self.service.dispatcher is not None: # Tell them exactly where they can shove it A['udp_source'] = (publicIP, self.service.sharedUDPPortnum) else: # Don't tell them because we don't know log.msg("dispatcher unavailable when connecting") D = self.callRemote(Inbound, **A) def _connected(answer): listenersD = defer.maybeDeferred(chooser, answer['listeners']) def gotListeners(listeners): allConnectionAttempts = [] for listener in listeners: d = self.attemptConnectionMethods( listener['methods'], listener['id'], From, to, protocolName, clientFactory, ) allConnectionAttempts.append(d) return defer.DeferredList(allConnectionAttempts) listenersD.addCallback(gotListeners) def finishedAllAttempts(results): succeededAny = False failures = [] if not results: return Failure(NoAttemptsMade( "there was no available path for connections " "(%r->%r/%s)" % (From, to, protocolName))) for succeeded, result in results: if succeeded: succeededAny = True randomConnection = result break else: failures.append(result) if not succeededAny: return Failure( AttemptsFailed( [failure.getBriefTraceback() for failure in failures] ) ) # XXX TODO: this connection is really random; connectQ2Q should # not return one of the connections it's made, put it into your # protocol's connectionMade handler return randomConnection return listenersD.addCallback(finishedAllAttempts) return D.addCallback(_connected)
[ "def", "connect", "(", "self", ",", "From", ",", "to", ",", "protocolName", ",", "clientFactory", ",", "chooser", ")", ":", "publicIP", "=", "self", ".", "_determinePublicIP", "(", ")", "A", "=", "dict", "(", "From", "=", "From", ",", "to", "=", "to"...
Issue an INBOUND command, creating a virtual connection to the peer, given identifying information about the endpoint to connect to, and a protocol factory. @param clientFactory: a *Client* ProtocolFactory instance which will generate a protocol upon connect. @return: a Deferred which fires with the protocol instance that was connected, or fails with AttemptsFailed if the connection was not possible.
[ "Issue", "an", "INBOUND", "command", "creating", "a", "virtual", "connection", "to", "the", "peer", "given", "identifying", "information", "about", "the", "endpoint", "to", "connect", "to", "and", "a", "protocol", "factory", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/q2q.py#L1440-L1515
train
42,922
twisted/vertex
vertex/q2q.py
DefaultCertificateStore.requestAvatarId
def requestAvatarId(self, credentials): """ Return the ID associated with these credentials. @param credentials: something which implements one of the interfaces in self.credentialInterfaces. @return: a Deferred which will fire a string which identifies an avatar, an empty tuple to specify an authenticated anonymous user (provided as checkers.ANONYMOUS) or fire a Failure(UnauthorizedLogin). @see: L{twisted.cred.credentials} """ username, domain = credentials.username.split("@") key = self.users.key(domain, username) if key is None: return defer.fail(UnauthorizedLogin()) def _cbPasswordChecked(passwordIsCorrect): if passwordIsCorrect: return username + '@' + domain else: raise UnauthorizedLogin() return defer.maybeDeferred(credentials.checkPassword, key).addCallback(_cbPasswordChecked)
python
def requestAvatarId(self, credentials): """ Return the ID associated with these credentials. @param credentials: something which implements one of the interfaces in self.credentialInterfaces. @return: a Deferred which will fire a string which identifies an avatar, an empty tuple to specify an authenticated anonymous user (provided as checkers.ANONYMOUS) or fire a Failure(UnauthorizedLogin). @see: L{twisted.cred.credentials} """ username, domain = credentials.username.split("@") key = self.users.key(domain, username) if key is None: return defer.fail(UnauthorizedLogin()) def _cbPasswordChecked(passwordIsCorrect): if passwordIsCorrect: return username + '@' + domain else: raise UnauthorizedLogin() return defer.maybeDeferred(credentials.checkPassword, key).addCallback(_cbPasswordChecked)
[ "def", "requestAvatarId", "(", "self", ",", "credentials", ")", ":", "username", ",", "domain", "=", "credentials", ".", "username", ".", "split", "(", "\"@\"", ")", "key", "=", "self", ".", "users", ".", "key", "(", "domain", ",", "username", ")", "if...
Return the ID associated with these credentials. @param credentials: something which implements one of the interfaces in self.credentialInterfaces. @return: a Deferred which will fire a string which identifies an avatar, an empty tuple to specify an authenticated anonymous user (provided as checkers.ANONYMOUS) or fire a Failure(UnauthorizedLogin). @see: L{twisted.cred.credentials}
[ "Return", "the", "ID", "associated", "with", "these", "credentials", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/q2q.py#L1910-L1935
train
42,923
twisted/vertex
vertex/q2q.py
DefaultCertificateStore.addPrivateCertificate
def addPrivateCertificate(self, subjectName, existingCertificate=None): """ Add a PrivateCertificate object to this store for this subjectName. If existingCertificate is None, add a new self-signed certificate. """ if existingCertificate is None: assert '@' not in subjectName, "Don't self-sign user certs!" mainDN = DistinguishedName(commonName=subjectName) mainKey = KeyPair.generate() mainCertReq = mainKey.certificateRequest(mainDN) mainCertData = mainKey.signCertificateRequest( mainDN, mainCertReq, lambda dn: True, self.genSerial(subjectName) ) mainCert = mainKey.newCertificate(mainCertData) else: mainCert = existingCertificate self.localStore[subjectName] = mainCert
python
def addPrivateCertificate(self, subjectName, existingCertificate=None): """ Add a PrivateCertificate object to this store for this subjectName. If existingCertificate is None, add a new self-signed certificate. """ if existingCertificate is None: assert '@' not in subjectName, "Don't self-sign user certs!" mainDN = DistinguishedName(commonName=subjectName) mainKey = KeyPair.generate() mainCertReq = mainKey.certificateRequest(mainDN) mainCertData = mainKey.signCertificateRequest( mainDN, mainCertReq, lambda dn: True, self.genSerial(subjectName) ) mainCert = mainKey.newCertificate(mainCertData) else: mainCert = existingCertificate self.localStore[subjectName] = mainCert
[ "def", "addPrivateCertificate", "(", "self", ",", "subjectName", ",", "existingCertificate", "=", "None", ")", ":", "if", "existingCertificate", "is", "None", ":", "assert", "'@'", "not", "in", "subjectName", ",", "\"Don't self-sign user certs!\"", "mainDN", "=", ...
Add a PrivateCertificate object to this store for this subjectName. If existingCertificate is None, add a new self-signed certificate.
[ "Add", "a", "PrivateCertificate", "object", "to", "this", "store", "for", "this", "subjectName", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/q2q.py#L1979-L1998
train
42,924
twisted/vertex
vertex/q2q.py
Q2QService.iterconnections
def iterconnections(self): """ Iterator of all connections associated with this service, whether cached or not. For testing purposes only. """ return itertools.chain( self.secureConnectionCache.cachedConnections.itervalues(), iter(self.subConnections), (self.dispatcher or ()) and self.dispatcher.iterconnections())
python
def iterconnections(self): """ Iterator of all connections associated with this service, whether cached or not. For testing purposes only. """ return itertools.chain( self.secureConnectionCache.cachedConnections.itervalues(), iter(self.subConnections), (self.dispatcher or ()) and self.dispatcher.iterconnections())
[ "def", "iterconnections", "(", "self", ")", ":", "return", "itertools", ".", "chain", "(", "self", ".", "secureConnectionCache", ".", "cachedConnections", ".", "itervalues", "(", ")", ",", "iter", "(", "self", ".", "subConnections", ")", ",", "(", "self", ...
Iterator of all connections associated with this service, whether cached or not. For testing purposes only.
[ "Iterator", "of", "all", "connections", "associated", "with", "this", "service", "whether", "cached", "or", "not", ".", "For", "testing", "purposes", "only", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/q2q.py#L2242-L2250
train
42,925
twisted/vertex
vertex/q2q.py
Q2QService.listenQ2Q
def listenQ2Q(self, fromAddress, protocolsToFactories, serverDescription): """ Right now this is really only useful in the client implementation, since it is transient. protocolFactoryFactory is used for persistent listeners. """ myDomain = fromAddress.domainAddress() D = self.getSecureConnection(fromAddress, myDomain) def _secured(proto): lfm = self.localFactoriesMapping def startup(listenResult): for protocol, factory in protocolsToFactories.iteritems(): key = (fromAddress, protocol) if key not in lfm: lfm[key] = [] lfm[key].append((factory, serverDescription)) factory.doStart() def shutdown(): for protocol, factory in protocolsToFactories.iteritems(): lfm[fromAddress, protocol].remove( (factory, serverDescription)) factory.doStop() proto.notifyOnConnectionLost(shutdown) return listenResult if self.dispatcher is not None: gp = proto.transport.getPeer() udpAddress = (gp.host, gp.port) pubUDPDeferred = self._retrievePublicUDPPortNumber(udpAddress) else: pubUDPDeferred = defer.succeed(None) def _gotPubUDPPort(publicAddress): self._publicUDPAddress = publicAddress return proto.listen(fromAddress, protocolsToFactories.keys(), serverDescription).addCallback(startup) pubUDPDeferred.addCallback(_gotPubUDPPort) return pubUDPDeferred D.addCallback(_secured) return D
python
def listenQ2Q(self, fromAddress, protocolsToFactories, serverDescription): """ Right now this is really only useful in the client implementation, since it is transient. protocolFactoryFactory is used for persistent listeners. """ myDomain = fromAddress.domainAddress() D = self.getSecureConnection(fromAddress, myDomain) def _secured(proto): lfm = self.localFactoriesMapping def startup(listenResult): for protocol, factory in protocolsToFactories.iteritems(): key = (fromAddress, protocol) if key not in lfm: lfm[key] = [] lfm[key].append((factory, serverDescription)) factory.doStart() def shutdown(): for protocol, factory in protocolsToFactories.iteritems(): lfm[fromAddress, protocol].remove( (factory, serverDescription)) factory.doStop() proto.notifyOnConnectionLost(shutdown) return listenResult if self.dispatcher is not None: gp = proto.transport.getPeer() udpAddress = (gp.host, gp.port) pubUDPDeferred = self._retrievePublicUDPPortNumber(udpAddress) else: pubUDPDeferred = defer.succeed(None) def _gotPubUDPPort(publicAddress): self._publicUDPAddress = publicAddress return proto.listen(fromAddress, protocolsToFactories.keys(), serverDescription).addCallback(startup) pubUDPDeferred.addCallback(_gotPubUDPPort) return pubUDPDeferred D.addCallback(_secured) return D
[ "def", "listenQ2Q", "(", "self", ",", "fromAddress", ",", "protocolsToFactories", ",", "serverDescription", ")", ":", "myDomain", "=", "fromAddress", ".", "domainAddress", "(", ")", "D", "=", "self", ".", "getSecureConnection", "(", "fromAddress", ",", "myDomain...
Right now this is really only useful in the client implementation, since it is transient. protocolFactoryFactory is used for persistent listeners.
[ "Right", "now", "this", "is", "really", "only", "useful", "in", "the", "client", "implementation", "since", "it", "is", "transient", ".", "protocolFactoryFactory", "is", "used", "for", "persistent", "listeners", "." ]
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/q2q.py#L2341-L2383
train
42,926
twisted/vertex
vertex/q2q.py
Q2QService.requestCertificateForAddress
def requestCertificateForAddress(self, fromAddress, sharedSecret): """ Connect to the authoritative server for the domain part of the given address and obtain a certificate signed by the root certificate for that domain, then store that certificate in my local certificate storage. @param fromAddress: an address that this service is authorized to use, and should store a separate private certificate for. @param sharedSecret: a str that represents a secret shared between the user of this service and their account on the server running on the domain part of the fromAddress. @return: a Deferred which fires None when the certificate has been successfully retrieved, and errbacks if it cannot be retrieved. """ kp = KeyPair.generate() subject = DistinguishedName(commonName=str(fromAddress)) reqobj = kp.requestObject(subject) # Create worthless, self-signed certificate for the moment, it will be # replaced later. # attemptAddress = q2q.Q2QAddress(fromAddress.domain, # fromAddress.resource + '+attempt') # fakeSubj = DistinguishedName(commonName=str(attemptAddress)) fakereq = kp.requestObject(subject) ssigned = kp.signRequestObject(subject, fakereq, 1) certpair = PrivateCertificate.fromCertificateAndKeyPair fakecert = certpair(ssigned, kp) apc = self.certificateStorage.addPrivateCertificate gettingSecureConnection = self.getSecureConnection( fromAddress, fromAddress.domainAddress(), authorize=False, usePrivateCertificate=fakecert, ) def gotSecureConnection(secured): return secured.callRemote( Sign, certificate_request=reqobj, password=sharedSecret) gettingSecureConnection.addCallback(gotSecureConnection) def gotSignResponse(signResponse): cert = signResponse['certificate'] privcert = certpair(cert, kp) apc(str(fromAddress), privcert) return signResponse return gettingSecureConnection.addCallback(gotSignResponse)
python
def requestCertificateForAddress(self, fromAddress, sharedSecret): """ Connect to the authoritative server for the domain part of the given address and obtain a certificate signed by the root certificate for that domain, then store that certificate in my local certificate storage. @param fromAddress: an address that this service is authorized to use, and should store a separate private certificate for. @param sharedSecret: a str that represents a secret shared between the user of this service and their account on the server running on the domain part of the fromAddress. @return: a Deferred which fires None when the certificate has been successfully retrieved, and errbacks if it cannot be retrieved. """ kp = KeyPair.generate() subject = DistinguishedName(commonName=str(fromAddress)) reqobj = kp.requestObject(subject) # Create worthless, self-signed certificate for the moment, it will be # replaced later. # attemptAddress = q2q.Q2QAddress(fromAddress.domain, # fromAddress.resource + '+attempt') # fakeSubj = DistinguishedName(commonName=str(attemptAddress)) fakereq = kp.requestObject(subject) ssigned = kp.signRequestObject(subject, fakereq, 1) certpair = PrivateCertificate.fromCertificateAndKeyPair fakecert = certpair(ssigned, kp) apc = self.certificateStorage.addPrivateCertificate gettingSecureConnection = self.getSecureConnection( fromAddress, fromAddress.domainAddress(), authorize=False, usePrivateCertificate=fakecert, ) def gotSecureConnection(secured): return secured.callRemote( Sign, certificate_request=reqobj, password=sharedSecret) gettingSecureConnection.addCallback(gotSecureConnection) def gotSignResponse(signResponse): cert = signResponse['certificate'] privcert = certpair(cert, kp) apc(str(fromAddress), privcert) return signResponse return gettingSecureConnection.addCallback(gotSignResponse)
[ "def", "requestCertificateForAddress", "(", "self", ",", "fromAddress", ",", "sharedSecret", ")", ":", "kp", "=", "KeyPair", ".", "generate", "(", ")", "subject", "=", "DistinguishedName", "(", "commonName", "=", "str", "(", "fromAddress", ")", ")", "reqobj", ...
Connect to the authoritative server for the domain part of the given address and obtain a certificate signed by the root certificate for that domain, then store that certificate in my local certificate storage. @param fromAddress: an address that this service is authorized to use, and should store a separate private certificate for. @param sharedSecret: a str that represents a secret shared between the user of this service and their account on the server running on the domain part of the fromAddress. @return: a Deferred which fires None when the certificate has been successfully retrieved, and errbacks if it cannot be retrieved.
[ "Connect", "to", "the", "authoritative", "server", "for", "the", "domain", "part", "of", "the", "given", "address", "and", "obtain", "a", "certificate", "signed", "by", "the", "root", "certificate", "for", "that", "domain", "then", "store", "that", "certificat...
feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/q2q.py#L2386-L2432
train
42,927
MycroftAI/mycroft-skills-manager
msm/skill_entry.py
_backup_previous_version
def _backup_previous_version(func: Callable = None): """Private decorator to back up previous skill folder""" @wraps(func) def wrapper(self, *args, **kwargs): self.old_path = None if self.is_local: self.old_path = join(gettempdir(), self.name) if exists(self.old_path): rmtree(self.old_path) shutil.copytree(self.path, self.old_path) try: func(self, *args, **kwargs) # Modified skill or GitError should not restore working copy except (SkillModified, GitError, GitException): raise except Exception: LOG.info('Problem performing action. Restoring skill to ' 'previous state...') if exists(self.path): rmtree(self.path) if self.old_path and exists(self.old_path): shutil.copytree(self.old_path, self.path) self.is_local = exists(self.path) raise return wrapper
python
def _backup_previous_version(func: Callable = None): """Private decorator to back up previous skill folder""" @wraps(func) def wrapper(self, *args, **kwargs): self.old_path = None if self.is_local: self.old_path = join(gettempdir(), self.name) if exists(self.old_path): rmtree(self.old_path) shutil.copytree(self.path, self.old_path) try: func(self, *args, **kwargs) # Modified skill or GitError should not restore working copy except (SkillModified, GitError, GitException): raise except Exception: LOG.info('Problem performing action. Restoring skill to ' 'previous state...') if exists(self.path): rmtree(self.path) if self.old_path and exists(self.old_path): shutil.copytree(self.old_path, self.path) self.is_local = exists(self.path) raise return wrapper
[ "def", "_backup_previous_version", "(", "func", ":", "Callable", "=", "None", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "old_path", "=", "None", "if", ...
Private decorator to back up previous skill folder
[ "Private", "decorator", "to", "back", "up", "previous", "skill", "folder" ]
5acef240de42e8ceae2e82bc7492ffee33288b00
https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/skill_entry.py#L69-L96
train
42,928
MycroftAI/mycroft-skills-manager
msm/skill_entry.py
SkillEntry.attach
def attach(self, remote_entry): """Attach a remote entry to a local entry""" self.name = remote_entry.name self.sha = remote_entry.sha self.url = remote_entry.url self.author = remote_entry.author return self
python
def attach(self, remote_entry): """Attach a remote entry to a local entry""" self.name = remote_entry.name self.sha = remote_entry.sha self.url = remote_entry.url self.author = remote_entry.author return self
[ "def", "attach", "(", "self", ",", "remote_entry", ")", ":", "self", ".", "name", "=", "remote_entry", ".", "name", "self", ".", "sha", "=", "remote_entry", ".", "sha", "self", ".", "url", "=", "remote_entry", ".", "url", "self", ".", "author", "=", ...
Attach a remote entry to a local entry
[ "Attach", "a", "remote", "entry", "to", "a", "local", "entry" ]
5acef240de42e8ceae2e82bc7492ffee33288b00
https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/skill_entry.py#L136-L142
train
42,929
mikeboers/Flask-ACL
flask_acl/permission.py
parse_permission_set
def parse_permission_set(input): """Lookup a permission set name in the defined permissions. Requires a Flask app context. """ # Priority goes to the user's parsers. if isinstance(input, basestring): for func in current_acl_manager.permission_set_parsers: res = func(input) if res is not None: input = res break if isinstance(input, basestring): try: return current_acl_manager.permission_sets[input] except KeyError: raise ValueError('unknown permission set %r' % input) return input
python
def parse_permission_set(input): """Lookup a permission set name in the defined permissions. Requires a Flask app context. """ # Priority goes to the user's parsers. if isinstance(input, basestring): for func in current_acl_manager.permission_set_parsers: res = func(input) if res is not None: input = res break if isinstance(input, basestring): try: return current_acl_manager.permission_sets[input] except KeyError: raise ValueError('unknown permission set %r' % input) return input
[ "def", "parse_permission_set", "(", "input", ")", ":", "# Priority goes to the user's parsers.", "if", "isinstance", "(", "input", ",", "basestring", ")", ":", "for", "func", "in", "current_acl_manager", ".", "permission_set_parsers", ":", "res", "=", "func", "(", ...
Lookup a permission set name in the defined permissions. Requires a Flask app context.
[ "Lookup", "a", "permission", "set", "name", "in", "the", "defined", "permissions", "." ]
7339b89f96ad8686d1526e25c138244ad912e12d
https://github.com/mikeboers/Flask-ACL/blob/7339b89f96ad8686d1526e25c138244ad912e12d/flask_acl/permission.py#L21-L42
train
42,930
mikeboers/Flask-ACL
flask_acl/permission.py
is_permission_in_set
def is_permission_in_set(perm, perm_set): """Test if a permission is in the given set. :param perm: The permission object to check for. :param perm_set: The set to check in. If a ``str``, the permission is checked for equality. If a container, the permission is looked for in the set. If a function, the permission is passed to the "set". """ if isinstance(perm_set, basestring): return perm == perm_set elif isinstance(perm_set, Container): return perm in perm_set elif isinstance(perm_set, Callable): return perm_set(perm) else: raise TypeError('permission set must be a string, container, or callable')
python
def is_permission_in_set(perm, perm_set): """Test if a permission is in the given set. :param perm: The permission object to check for. :param perm_set: The set to check in. If a ``str``, the permission is checked for equality. If a container, the permission is looked for in the set. If a function, the permission is passed to the "set". """ if isinstance(perm_set, basestring): return perm == perm_set elif isinstance(perm_set, Container): return perm in perm_set elif isinstance(perm_set, Callable): return perm_set(perm) else: raise TypeError('permission set must be a string, container, or callable')
[ "def", "is_permission_in_set", "(", "perm", ",", "perm_set", ")", ":", "if", "isinstance", "(", "perm_set", ",", "basestring", ")", ":", "return", "perm", "==", "perm_set", "elif", "isinstance", "(", "perm_set", ",", "Container", ")", ":", "return", "perm", ...
Test if a permission is in the given set. :param perm: The permission object to check for. :param perm_set: The set to check in. If a ``str``, the permission is checked for equality. If a container, the permission is looked for in the set. If a function, the permission is passed to the "set".
[ "Test", "if", "a", "permission", "is", "in", "the", "given", "set", "." ]
7339b89f96ad8686d1526e25c138244ad912e12d
https://github.com/mikeboers/Flask-ACL/blob/7339b89f96ad8686d1526e25c138244ad912e12d/flask_acl/permission.py#L45-L62
train
42,931
MattBroach/DjangoRestMultipleModels
drf_multiple_model/mixins.py
BaseMultipleModelMixin.check_query_data
def check_query_data(self, query_data): """ All items in a `querylist` must at least have `queryset` key and a `serializer_class` key. Any querylist item lacking both those keys will raise a ValidationError """ for key in self.required_keys: if key not in query_data: raise ValidationError( 'All items in the {} querylist attribute should contain a ' '`{}` key'.format(self.__class__.__name__, key) )
python
def check_query_data(self, query_data): """ All items in a `querylist` must at least have `queryset` key and a `serializer_class` key. Any querylist item lacking both those keys will raise a ValidationError """ for key in self.required_keys: if key not in query_data: raise ValidationError( 'All items in the {} querylist attribute should contain a ' '`{}` key'.format(self.__class__.__name__, key) )
[ "def", "check_query_data", "(", "self", ",", "query_data", ")", ":", "for", "key", "in", "self", ".", "required_keys", ":", "if", "key", "not", "in", "query_data", ":", "raise", "ValidationError", "(", "'All items in the {} querylist attribute should contain a '", "...
All items in a `querylist` must at least have `queryset` key and a `serializer_class` key. Any querylist item lacking both those keys will raise a ValidationError
[ "All", "items", "in", "a", "querylist", "must", "at", "least", "have", "queryset", "key", "and", "a", "serializer_class", "key", ".", "Any", "querylist", "item", "lacking", "both", "those", "keys", "will", "raise", "a", "ValidationError" ]
893969ed38d614a5e2f060e560824fa7c5c49cfd
https://github.com/MattBroach/DjangoRestMultipleModels/blob/893969ed38d614a5e2f060e560824fa7c5c49cfd/drf_multiple_model/mixins.py#L30-L41
train
42,932
MattBroach/DjangoRestMultipleModels
drf_multiple_model/mixins.py
BaseMultipleModelMixin.load_queryset
def load_queryset(self, query_data, request, *args, **kwargs): """ Fetches the queryset and runs any necessary filtering, both built-in rest_framework filters and custom filters passed into the querylist """ queryset = query_data.get('queryset', []) if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() # run rest_framework filters queryset = self.filter_queryset(queryset) # run custom filters filter_fn = query_data.get('filter_fn', None) if filter_fn is not None: queryset = filter_fn(queryset, request, *args, **kwargs) page = self.paginate_queryset(queryset) self.is_paginated = page is not None return page if page is not None else queryset
python
def load_queryset(self, query_data, request, *args, **kwargs): """ Fetches the queryset and runs any necessary filtering, both built-in rest_framework filters and custom filters passed into the querylist """ queryset = query_data.get('queryset', []) if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() # run rest_framework filters queryset = self.filter_queryset(queryset) # run custom filters filter_fn = query_data.get('filter_fn', None) if filter_fn is not None: queryset = filter_fn(queryset, request, *args, **kwargs) page = self.paginate_queryset(queryset) self.is_paginated = page is not None return page if page is not None else queryset
[ "def", "load_queryset", "(", "self", ",", "query_data", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "queryset", "=", "query_data", ".", "get", "(", "'queryset'", ",", "[", "]", ")", "if", "isinstance", "(", "queryset", ",", "...
Fetches the queryset and runs any necessary filtering, both built-in rest_framework filters and custom filters passed into the querylist
[ "Fetches", "the", "queryset", "and", "runs", "any", "necessary", "filtering", "both", "built", "-", "in", "rest_framework", "filters", "and", "custom", "filters", "passed", "into", "the", "querylist" ]
893969ed38d614a5e2f060e560824fa7c5c49cfd
https://github.com/MattBroach/DjangoRestMultipleModels/blob/893969ed38d614a5e2f060e560824fa7c5c49cfd/drf_multiple_model/mixins.py#L43-L66
train
42,933
MattBroach/DjangoRestMultipleModels
drf_multiple_model/mixins.py
FlatMultipleModelMixin.initial
def initial(self, request, *args, **kwargs): """ Overrides DRF's `initial` in order to set the `_sorting_field` from corresponding property in view. Protected property is required in order to support overriding of `sorting_field` via `@property`, we do this after original `initial` has been ran in order to make sure that view has all its properties set up. """ super(FlatMultipleModelMixin, self).initial(request, *args, **kwargs) assert not (self.sorting_field and self.sorting_fields), \ '{} should either define ``sorting_field`` or ``sorting_fields`` property, not both.' \ .format(self.__class__.__name__) if self.sorting_field: warnings.warn( '``sorting_field`` property is pending its deprecation. Use ``sorting_fields`` instead.', DeprecationWarning ) self.sorting_fields = [self.sorting_field] self._sorting_fields = self.sorting_fields
python
def initial(self, request, *args, **kwargs): """ Overrides DRF's `initial` in order to set the `_sorting_field` from corresponding property in view. Protected property is required in order to support overriding of `sorting_field` via `@property`, we do this after original `initial` has been ran in order to make sure that view has all its properties set up. """ super(FlatMultipleModelMixin, self).initial(request, *args, **kwargs) assert not (self.sorting_field and self.sorting_fields), \ '{} should either define ``sorting_field`` or ``sorting_fields`` property, not both.' \ .format(self.__class__.__name__) if self.sorting_field: warnings.warn( '``sorting_field`` property is pending its deprecation. Use ``sorting_fields`` instead.', DeprecationWarning ) self.sorting_fields = [self.sorting_field] self._sorting_fields = self.sorting_fields
[ "def", "initial", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "FlatMultipleModelMixin", ",", "self", ")", ".", "initial", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "assert", ...
Overrides DRF's `initial` in order to set the `_sorting_field` from corresponding property in view. Protected property is required in order to support overriding of `sorting_field` via `@property`, we do this after original `initial` has been ran in order to make sure that view has all its properties set up.
[ "Overrides", "DRF", "s", "initial", "in", "order", "to", "set", "the", "_sorting_field", "from", "corresponding", "property", "in", "view", ".", "Protected", "property", "is", "required", "in", "order", "to", "support", "overriding", "of", "sorting_field", "via"...
893969ed38d614a5e2f060e560824fa7c5c49cfd
https://github.com/MattBroach/DjangoRestMultipleModels/blob/893969ed38d614a5e2f060e560824fa7c5c49cfd/drf_multiple_model/mixins.py#L178-L194
train
42,934
MattBroach/DjangoRestMultipleModels
drf_multiple_model/mixins.py
FlatMultipleModelMixin.add_to_results
def add_to_results(self, data, label, results): """ Adds the label to the results, as needed, then appends the data to the running results tab """ for datum in data: if label is not None: datum.update({'type': label}) results.append(datum) return results
python
def add_to_results(self, data, label, results): """ Adds the label to the results, as needed, then appends the data to the running results tab """ for datum in data: if label is not None: datum.update({'type': label}) results.append(datum) return results
[ "def", "add_to_results", "(", "self", ",", "data", ",", "label", ",", "results", ")", ":", "for", "datum", "in", "data", ":", "if", "label", "is", "not", "None", ":", "datum", ".", "update", "(", "{", "'type'", ":", "label", "}", ")", "results", "....
Adds the label to the results, as needed, then appends the data to the running results tab
[ "Adds", "the", "label", "to", "the", "results", "as", "needed", "then", "appends", "the", "data", "to", "the", "running", "results", "tab" ]
893969ed38d614a5e2f060e560824fa7c5c49cfd
https://github.com/MattBroach/DjangoRestMultipleModels/blob/893969ed38d614a5e2f060e560824fa7c5c49cfd/drf_multiple_model/mixins.py#L209-L220
train
42,935
MattBroach/DjangoRestMultipleModels
drf_multiple_model/mixins.py
FlatMultipleModelMixin.prepare_sorting_fields
def prepare_sorting_fields(self): """ Determine sorting direction and sorting field based on request query parameters and sorting options of self """ if self.sorting_parameter_name in self.request.query_params: # Extract sorting parameter from query string self._sorting_fields = [ _.strip() for _ in self.request.query_params.get(self.sorting_parameter_name).split(',') ] if self._sorting_fields: # Create a list of sorting parameters. Each parameter is a tuple: (field:str, descending:bool) self._sorting_fields = [ (self.sorting_fields_map.get(field.lstrip('-'), field.lstrip('-')), field[0] == '-') for field in self._sorting_fields ]
python
def prepare_sorting_fields(self): """ Determine sorting direction and sorting field based on request query parameters and sorting options of self """ if self.sorting_parameter_name in self.request.query_params: # Extract sorting parameter from query string self._sorting_fields = [ _.strip() for _ in self.request.query_params.get(self.sorting_parameter_name).split(',') ] if self._sorting_fields: # Create a list of sorting parameters. Each parameter is a tuple: (field:str, descending:bool) self._sorting_fields = [ (self.sorting_fields_map.get(field.lstrip('-'), field.lstrip('-')), field[0] == '-') for field in self._sorting_fields ]
[ "def", "prepare_sorting_fields", "(", "self", ")", ":", "if", "self", ".", "sorting_parameter_name", "in", "self", ".", "request", ".", "query_params", ":", "# Extract sorting parameter from query string", "self", ".", "_sorting_fields", "=", "[", "_", ".", "strip",...
Determine sorting direction and sorting field based on request query parameters and sorting options of self
[ "Determine", "sorting", "direction", "and", "sorting", "field", "based", "on", "request", "query", "parameters", "and", "sorting", "options", "of", "self" ]
893969ed38d614a5e2f060e560824fa7c5c49cfd
https://github.com/MattBroach/DjangoRestMultipleModels/blob/893969ed38d614a5e2f060e560824fa7c5c49cfd/drf_multiple_model/mixins.py#L259-L275
train
42,936
MattBroach/DjangoRestMultipleModels
drf_multiple_model/mixins.py
ObjectMultipleModelMixin.get_label
def get_label(self, queryset, query_data): """ Gets option label for each datum. Can be used for type identification of individual serialized objects """ if query_data.get('label', False): return query_data['label'] try: return queryset.model.__name__ except AttributeError: return query_data['queryset'].model.__name__
python
def get_label(self, queryset, query_data): """ Gets option label for each datum. Can be used for type identification of individual serialized objects """ if query_data.get('label', False): return query_data['label'] try: return queryset.model.__name__ except AttributeError: return query_data['queryset'].model.__name__
[ "def", "get_label", "(", "self", ",", "queryset", ",", "query_data", ")", ":", "if", "query_data", ".", "get", "(", "'label'", ",", "False", ")", ":", "return", "query_data", "[", "'label'", "]", "try", ":", "return", "queryset", ".", "model", ".", "__...
Gets option label for each datum. Can be used for type identification of individual serialized objects
[ "Gets", "option", "label", "for", "each", "datum", ".", "Can", "be", "used", "for", "type", "identification", "of", "individual", "serialized", "objects" ]
893969ed38d614a5e2f060e560824fa7c5c49cfd
https://github.com/MattBroach/DjangoRestMultipleModels/blob/893969ed38d614a5e2f060e560824fa7c5c49cfd/drf_multiple_model/mixins.py#L324-L335
train
42,937
python-useful-helpers/threaded
setup.py
_extension
def _extension(modpath: str) -> setuptools.Extension: """Make setuptools.Extension.""" return setuptools.Extension(modpath, [modpath.replace(".", "/") + ".py"])
python
def _extension(modpath: str) -> setuptools.Extension: """Make setuptools.Extension.""" return setuptools.Extension(modpath, [modpath.replace(".", "/") + ".py"])
[ "def", "_extension", "(", "modpath", ":", "str", ")", "->", "setuptools", ".", "Extension", ":", "return", "setuptools", ".", "Extension", "(", "modpath", ",", "[", "modpath", ".", "replace", "(", "\".\"", ",", "\"/\"", ")", "+", "\".py\"", "]", ")" ]
Make setuptools.Extension.
[ "Make", "setuptools", ".", "Extension", "." ]
c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a
https://github.com/python-useful-helpers/threaded/blob/c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a/setup.py#L53-L55
train
42,938
alfredodeza/remoto
remoto/process.py
extend_env
def extend_env(conn, arguments): """ get the remote environment's env so we can explicitly add the path without wiping out everything """ # retrieve the remote environment variables for the host try: result = conn.gateway.remote_exec("import os; channel.send(os.environ.copy())") env = result.receive() except Exception: conn.logger.exception('failed to retrieve the remote environment variables') env = {} # get the $PATH and extend it (do not overwrite) path = env.get('PATH', '') env['PATH'] = path + '/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin' arguments['env'] = env if arguments.get('extend_env'): for key, value in arguments['extend_env'].items(): arguments['env'][key] = value arguments.pop('extend_env') return arguments
python
def extend_env(conn, arguments): """ get the remote environment's env so we can explicitly add the path without wiping out everything """ # retrieve the remote environment variables for the host try: result = conn.gateway.remote_exec("import os; channel.send(os.environ.copy())") env = result.receive() except Exception: conn.logger.exception('failed to retrieve the remote environment variables') env = {} # get the $PATH and extend it (do not overwrite) path = env.get('PATH', '') env['PATH'] = path + '/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin' arguments['env'] = env if arguments.get('extend_env'): for key, value in arguments['extend_env'].items(): arguments['env'][key] = value arguments.pop('extend_env') return arguments
[ "def", "extend_env", "(", "conn", ",", "arguments", ")", ":", "# retrieve the remote environment variables for the host", "try", ":", "result", "=", "conn", ".", "gateway", ".", "remote_exec", "(", "\"import os; channel.send(os.environ.copy())\"", ")", "env", "=", "resu...
get the remote environment's env so we can explicitly add the path without wiping out everything
[ "get", "the", "remote", "environment", "s", "env", "so", "we", "can", "explicitly", "add", "the", "path", "without", "wiping", "out", "everything" ]
b7625e571a4b6c83f9589a1e9ad07354e42bf0d3
https://github.com/alfredodeza/remoto/blob/b7625e571a4b6c83f9589a1e9ad07354e42bf0d3/remoto/process.py#L77-L98
train
42,939
alfredodeza/remoto
remoto/process.py
run
def run(conn, command, exit=False, timeout=None, **kw): """ A real-time-logging implementation of a remote subprocess.Popen call where a command is just executed on the remote end and no other handling is done. :param conn: A connection oject :param command: The command to pass in to the remote subprocess.Popen :param exit: If this call should close the connection at the end :param timeout: How many seconds to wait after no remote data is received (defaults to wait for ever) """ stop_on_error = kw.pop('stop_on_error', True) if not kw.get('env'): # get the remote environment's env so we can explicitly add # the path without wiping out everything kw = extend_env(conn, kw) command = conn.cmd(command) timeout = timeout or conn.global_timeout conn.logger.info('Running command: %s' % ' '.join(admin_command(conn.sudo, command))) result = conn.execute(_remote_run, cmd=command, **kw) try: reporting(conn, result, timeout) except Exception: remote_trace = traceback.format_exc() remote_error = RemoteError(remote_trace) if remote_error.exception_name == 'RuntimeError': conn.logger.error(remote_error.exception_line) else: for tb_line in remote_trace.split('\n'): conn.logger.error(tb_line) if stop_on_error: raise RuntimeError( 'Failed to execute command: %s' % ' '.join(command) ) if exit: conn.exit()
python
def run(conn, command, exit=False, timeout=None, **kw): """ A real-time-logging implementation of a remote subprocess.Popen call where a command is just executed on the remote end and no other handling is done. :param conn: A connection oject :param command: The command to pass in to the remote subprocess.Popen :param exit: If this call should close the connection at the end :param timeout: How many seconds to wait after no remote data is received (defaults to wait for ever) """ stop_on_error = kw.pop('stop_on_error', True) if not kw.get('env'): # get the remote environment's env so we can explicitly add # the path without wiping out everything kw = extend_env(conn, kw) command = conn.cmd(command) timeout = timeout or conn.global_timeout conn.logger.info('Running command: %s' % ' '.join(admin_command(conn.sudo, command))) result = conn.execute(_remote_run, cmd=command, **kw) try: reporting(conn, result, timeout) except Exception: remote_trace = traceback.format_exc() remote_error = RemoteError(remote_trace) if remote_error.exception_name == 'RuntimeError': conn.logger.error(remote_error.exception_line) else: for tb_line in remote_trace.split('\n'): conn.logger.error(tb_line) if stop_on_error: raise RuntimeError( 'Failed to execute command: %s' % ' '.join(command) ) if exit: conn.exit()
[ "def", "run", "(", "conn", ",", "command", ",", "exit", "=", "False", ",", "timeout", "=", "None", ",", "*", "*", "kw", ")", ":", "stop_on_error", "=", "kw", ".", "pop", "(", "'stop_on_error'", ",", "True", ")", "if", "not", "kw", ".", "get", "("...
A real-time-logging implementation of a remote subprocess.Popen call where a command is just executed on the remote end and no other handling is done. :param conn: A connection oject :param command: The command to pass in to the remote subprocess.Popen :param exit: If this call should close the connection at the end :param timeout: How many seconds to wait after no remote data is received (defaults to wait for ever)
[ "A", "real", "-", "time", "-", "logging", "implementation", "of", "a", "remote", "subprocess", ".", "Popen", "call", "where", "a", "command", "is", "just", "executed", "on", "the", "remote", "end", "and", "no", "other", "handling", "is", "done", "." ]
b7625e571a4b6c83f9589a1e9ad07354e42bf0d3
https://github.com/alfredodeza/remoto/blob/b7625e571a4b6c83f9589a1e9ad07354e42bf0d3/remoto/process.py#L101-L138
train
42,940
TadLeonard/tfatool
tfatool/sync.py
_write_file_safely
def _write_file_safely(local_path, fileinfo, response): """attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error""" try: _write_file(local_path, fileinfo, response) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial file".format( e.__class__.__name__, local_path)) os.remove(local_path) raise e
python
def _write_file_safely(local_path, fileinfo, response): """attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error""" try: _write_file(local_path, fileinfo, response) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial file".format( e.__class__.__name__, local_path)) os.remove(local_path) raise e
[ "def", "_write_file_safely", "(", "local_path", ",", "fileinfo", ",", "response", ")", ":", "try", ":", "_write_file", "(", "local_path", ",", "fileinfo", ",", "response", ")", "except", "BaseException", "as", "e", ":", "logger", ".", "warning", "(", "\"{} i...
attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error
[ "attempts", "to", "stream", "a", "remote", "file", "into", "a", "local", "file", "object", "removes", "the", "local", "file", "if", "it", "s", "interrupted", "by", "any", "error" ]
12da2807b5fb538c5317ef255d846b32ceb174d0
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L215-L225
train
42,941
TadLeonard/tfatool
tfatool/sync.py
up_by_files
def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None): """Sync a given list of local files to `remote_dir` dir""" if remote_files is None: remote_files = command.map_files_raw(remote_dir=remote_dir) for local_file in to_sync: _sync_local_file(local_file, remote_dir, remote_files)
python
def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None): """Sync a given list of local files to `remote_dir` dir""" if remote_files is None: remote_files = command.map_files_raw(remote_dir=remote_dir) for local_file in to_sync: _sync_local_file(local_file, remote_dir, remote_files)
[ "def", "up_by_files", "(", "to_sync", ",", "remote_dir", "=", "DEFAULT_REMOTE_DIR", ",", "remote_files", "=", "None", ")", ":", "if", "remote_files", "is", "None", ":", "remote_files", "=", "command", ".", "map_files_raw", "(", "remote_dir", "=", "remote_dir", ...
Sync a given list of local files to `remote_dir` dir
[ "Sync", "a", "given", "list", "of", "local", "files", "to", "remote_dir", "dir" ]
12da2807b5fb538c5317ef255d846b32ceb174d0
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L289-L294
train
42,942
TadLeonard/tfatool
tfatool/sync.py
_upload_file_safely
def _upload_file_safely(fileinfo, remote_dir): """attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error""" try: upload.upload_file(fileinfo.path, remote_dir=remote_dir) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial remote file".format( e.__class__.__name__, fileinfo.path)) upload.delete_file(fileinfo.path) raise e
python
def _upload_file_safely(fileinfo, remote_dir): """attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error""" try: upload.upload_file(fileinfo.path, remote_dir=remote_dir) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial remote file".format( e.__class__.__name__, fileinfo.path)) upload.delete_file(fileinfo.path) raise e
[ "def", "_upload_file_safely", "(", "fileinfo", ",", "remote_dir", ")", ":", "try", ":", "upload", ".", "upload_file", "(", "fileinfo", ".", "path", ",", "remote_dir", "=", "remote_dir", ")", "except", "BaseException", "as", "e", ":", "logger", ".", "warning"...
attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error
[ "attempts", "to", "upload", "a", "local", "file", "to", "FlashAir", "tries", "to", "remove", "the", "remote", "file", "if", "interrupted", "by", "any", "error" ]
12da2807b5fb538c5317ef255d846b32ceb174d0
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L344-L354
train
42,943
ApproxEng/approxeng.input
src/python/approxeng/input/__init__.py
map_into_range
def map_into_range(low, high, raw_value): """ Map an input function into an output value, clamping such that the magnitude of the output is at most 1.0 :param low: The value in the input range corresponding to zero. :param high: The value in the input range corresponding to 1.0 or -1.0, depending on whether this is higher or lower than the low value respectively. :param raw_value: An input value :return: Mapped output value """ value = float(raw_value) if low < high: if value < low: return 0 elif value > high: return 1.0 elif low > high: if value > low: return 0 elif value < high: return -1.0 return (value - low) / abs(high - low)
python
def map_into_range(low, high, raw_value): """ Map an input function into an output value, clamping such that the magnitude of the output is at most 1.0 :param low: The value in the input range corresponding to zero. :param high: The value in the input range corresponding to 1.0 or -1.0, depending on whether this is higher or lower than the low value respectively. :param raw_value: An input value :return: Mapped output value """ value = float(raw_value) if low < high: if value < low: return 0 elif value > high: return 1.0 elif low > high: if value > low: return 0 elif value < high: return -1.0 return (value - low) / abs(high - low)
[ "def", "map_into_range", "(", "low", ",", "high", ",", "raw_value", ")", ":", "value", "=", "float", "(", "raw_value", ")", "if", "low", "<", "high", ":", "if", "value", "<", "low", ":", "return", "0", "elif", "value", ">", "high", ":", "return", "...
Map an input function into an output value, clamping such that the magnitude of the output is at most 1.0 :param low: The value in the input range corresponding to zero. :param high: The value in the input range corresponding to 1.0 or -1.0, depending on whether this is higher or lower than the low value respectively. :param raw_value: An input value :return: Mapped output value
[ "Map", "an", "input", "function", "into", "an", "output", "value", "clamping", "such", "that", "the", "magnitude", "of", "the", "output", "is", "at", "most", "1", ".", "0" ]
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/__init__.py#L12-L37
train
42,944
ApproxEng/approxeng.input
src/python/approxeng/input/__init__.py
map_dual_axis
def map_dual_axis(low, high, centre, dead_zone, hot_zone, value): """ Map an axis with a central dead zone and hot zones at each end to a range from -1.0 to 1.0. This in effect uses two calls to map_single_axis, choosing whether to use centre and low, or centre and high as the low and high values in that call based on which side of the centre value the input value falls. This is the call that handles mapping of values on regular joysticks where there's a centre point to which the physical control returns when no input is being made. :param low: The raw value corresponding to the strongest negative input (stick far left / down). :param high: The raw value corresponding to the strongest positive input (stick far right / up). :param centre: The raw value corresponding to the resting position of the axis when no user interaction is happening. :param dead_zone: The proportion of each (positive and negative) part of the motion away from the centre which should result in an output of 0.0 :param hot_zone: The proportion of each (positive and negative) part of the motion away from each extreme end of the range which should result in 1.0 or -1.0 being returned (depending on whether we're on the high or low side of the centre point) :param value: The raw value to map :return: The filtered and clamped value, from -1.0 at low to 1.0 at high, with a centre as specified mapping to 0.0 """ if value <= centre: return map_single_axis(centre, low, dead_zone, hot_zone, value) else: return map_single_axis(centre, high, dead_zone, hot_zone, value)
python
def map_dual_axis(low, high, centre, dead_zone, hot_zone, value): """ Map an axis with a central dead zone and hot zones at each end to a range from -1.0 to 1.0. This in effect uses two calls to map_single_axis, choosing whether to use centre and low, or centre and high as the low and high values in that call based on which side of the centre value the input value falls. This is the call that handles mapping of values on regular joysticks where there's a centre point to which the physical control returns when no input is being made. :param low: The raw value corresponding to the strongest negative input (stick far left / down). :param high: The raw value corresponding to the strongest positive input (stick far right / up). :param centre: The raw value corresponding to the resting position of the axis when no user interaction is happening. :param dead_zone: The proportion of each (positive and negative) part of the motion away from the centre which should result in an output of 0.0 :param hot_zone: The proportion of each (positive and negative) part of the motion away from each extreme end of the range which should result in 1.0 or -1.0 being returned (depending on whether we're on the high or low side of the centre point) :param value: The raw value to map :return: The filtered and clamped value, from -1.0 at low to 1.0 at high, with a centre as specified mapping to 0.0 """ if value <= centre: return map_single_axis(centre, low, dead_zone, hot_zone, value) else: return map_single_axis(centre, high, dead_zone, hot_zone, value)
[ "def", "map_dual_axis", "(", "low", ",", "high", ",", "centre", ",", "dead_zone", ",", "hot_zone", ",", "value", ")", ":", "if", "value", "<=", "centre", ":", "return", "map_single_axis", "(", "centre", ",", "low", ",", "dead_zone", ",", "hot_zone", ",",...
Map an axis with a central dead zone and hot zones at each end to a range from -1.0 to 1.0. This in effect uses two calls to map_single_axis, choosing whether to use centre and low, or centre and high as the low and high values in that call based on which side of the centre value the input value falls. This is the call that handles mapping of values on regular joysticks where there's a centre point to which the physical control returns when no input is being made. :param low: The raw value corresponding to the strongest negative input (stick far left / down). :param high: The raw value corresponding to the strongest positive input (stick far right / up). :param centre: The raw value corresponding to the resting position of the axis when no user interaction is happening. :param dead_zone: The proportion of each (positive and negative) part of the motion away from the centre which should result in an output of 0.0 :param hot_zone: The proportion of each (positive and negative) part of the motion away from each extreme end of the range which should result in 1.0 or -1.0 being returned (depending on whether we're on the high or low side of the centre point) :param value: The raw value to map :return: The filtered and clamped value, from -1.0 at low to 1.0 at high, with a centre as specified mapping to 0.0
[ "Map", "an", "axis", "with", "a", "central", "dead", "zone", "and", "hot", "zones", "at", "each", "end", "to", "a", "range", "from", "-", "1", ".", "0", "to", "1", ".", "0", ".", "This", "in", "effect", "uses", "two", "calls", "to", "map_single_axi...
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/__init__.py#L75-L104
train
42,945
ApproxEng/approxeng.input
src/python/approxeng/input/__init__.py
Axes.axis_updated
def axis_updated(self, event: InputEvent, prefix=None): """ Called to process an absolute axis event from evdev, this is called internally by the controller implementations :internal: :param event: The evdev event to process :param prefix: If present, a named prefix that should be applied to the event code when searching for the axis """ if prefix is not None: axis = self.axes_by_code.get(prefix + str(event.code)) else: axis = self.axes_by_code.get(event.code) if axis is not None: axis.receive_device_value(event.value) else: logger.debug('Unknown axis code {} ({}), value {}'.format(event.code, prefix, event.value))
python
def axis_updated(self, event: InputEvent, prefix=None): """ Called to process an absolute axis event from evdev, this is called internally by the controller implementations :internal: :param event: The evdev event to process :param prefix: If present, a named prefix that should be applied to the event code when searching for the axis """ if prefix is not None: axis = self.axes_by_code.get(prefix + str(event.code)) else: axis = self.axes_by_code.get(event.code) if axis is not None: axis.receive_device_value(event.value) else: logger.debug('Unknown axis code {} ({}), value {}'.format(event.code, prefix, event.value))
[ "def", "axis_updated", "(", "self", ",", "event", ":", "InputEvent", ",", "prefix", "=", "None", ")", ":", "if", "prefix", "is", "not", "None", ":", "axis", "=", "self", ".", "axes_by_code", ".", "get", "(", "prefix", "+", "str", "(", "event", ".", ...
Called to process an absolute axis event from evdev, this is called internally by the controller implementations :internal: :param event: The evdev event to process :param prefix: If present, a named prefix that should be applied to the event code when searching for the axis
[ "Called", "to", "process", "an", "absolute", "axis", "event", "from", "evdev", "this", "is", "called", "internally", "by", "the", "controller", "implementations" ]
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/__init__.py#L338-L356
train
42,946
ApproxEng/approxeng.input
src/python/approxeng/input/__init__.py
Axes.set_axis_centres
def set_axis_centres(self, *args): """ Sets the centre points for each axis to the current value for that axis. This centre value is used when computing the value for the axis and is subtracted before applying any scaling. This will only be applied to CentredAxis instances """ for axis in self.axes_by_code.values(): if isinstance(axis, CentredAxis): axis.centre = axis.value
python
def set_axis_centres(self, *args): """ Sets the centre points for each axis to the current value for that axis. This centre value is used when computing the value for the axis and is subtracted before applying any scaling. This will only be applied to CentredAxis instances """ for axis in self.axes_by_code.values(): if isinstance(axis, CentredAxis): axis.centre = axis.value
[ "def", "set_axis_centres", "(", "self", ",", "*", "args", ")", ":", "for", "axis", "in", "self", ".", "axes_by_code", ".", "values", "(", ")", ":", "if", "isinstance", "(", "axis", ",", "CentredAxis", ")", ":", "axis", ".", "centre", "=", "axis", "."...
Sets the centre points for each axis to the current value for that axis. This centre value is used when computing the value for the axis and is subtracted before applying any scaling. This will only be applied to CentredAxis instances
[ "Sets", "the", "centre", "points", "for", "each", "axis", "to", "the", "current", "value", "for", "that", "axis", ".", "This", "centre", "value", "is", "used", "when", "computing", "the", "value", "for", "the", "axis", "and", "is", "subtracted", "before", ...
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/__init__.py#L358-L366
train
42,947
ApproxEng/approxeng.input
src/python/approxeng/input/__init__.py
Axes.names
def names(self) -> [str]: """ The snames of all axis objects """ return sorted([name for name in self.axes_by_sname.keys() if name is not ''])
python
def names(self) -> [str]: """ The snames of all axis objects """ return sorted([name for name in self.axes_by_sname.keys() if name is not ''])
[ "def", "names", "(", "self", ")", "->", "[", "str", "]", ":", "return", "sorted", "(", "[", "name", "for", "name", "in", "self", ".", "axes_by_sname", ".", "keys", "(", ")", "if", "name", "is", "not", "''", "]", ")" ]
The snames of all axis objects
[ "The", "snames", "of", "all", "axis", "objects" ]
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/__init__.py#L379-L383
train
42,948
ApproxEng/approxeng.input
src/python/approxeng/input/__init__.py
TriggerAxis._input_to_raw_value
def _input_to_raw_value(self, value: int) -> float: """ Convert the value read from evdev to a 0.0 to 1.0 range. :internal: :param value: a value ranging from the defined minimum to the defined maximum value. :return: 0.0 at minimum, 1.0 at maximum, linearly interpolating between those two points. """ return (float(value) - self.min_raw_value) / self.max_raw_value
python
def _input_to_raw_value(self, value: int) -> float: """ Convert the value read from evdev to a 0.0 to 1.0 range. :internal: :param value: a value ranging from the defined minimum to the defined maximum value. :return: 0.0 at minimum, 1.0 at maximum, linearly interpolating between those two points. """ return (float(value) - self.min_raw_value) / self.max_raw_value
[ "def", "_input_to_raw_value", "(", "self", ",", "value", ":", "int", ")", "->", "float", ":", "return", "(", "float", "(", "value", ")", "-", "self", ".", "min_raw_value", ")", "/", "self", ".", "max_raw_value" ]
Convert the value read from evdev to a 0.0 to 1.0 range. :internal: :param value: a value ranging from the defined minimum to the defined maximum value. :return: 0.0 at minimum, 1.0 at maximum, linearly interpolating between those two points.
[ "Convert", "the", "value", "read", "from", "evdev", "to", "a", "0", ".", "0", "to", "1", ".", "0", "range", "." ]
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/__init__.py#L513-L524
train
42,949
ApproxEng/approxeng.input
src/python/approxeng/input/__init__.py
Buttons.button_pressed
def button_pressed(self, key_code, prefix=None): """ Called from the controller classes to update the state of this button manager when a button is pressed. :internal: :param key_code: The code specified when populating Button instances :param prefix: Applied to key code if present """ if prefix is not None: state = self.buttons_by_code.get(prefix + str(key_code)) else: state = self.buttons_by_code.get(key_code) if state is not None: for handler in state.button_handlers: handler(state.button) state.is_pressed = True state.last_pressed = time() state.was_pressed_since_last_check = True else: logger.debug('Unknown button code {} ({})'.format(key_code, prefix))
python
def button_pressed(self, key_code, prefix=None): """ Called from the controller classes to update the state of this button manager when a button is pressed. :internal: :param key_code: The code specified when populating Button instances :param prefix: Applied to key code if present """ if prefix is not None: state = self.buttons_by_code.get(prefix + str(key_code)) else: state = self.buttons_by_code.get(key_code) if state is not None: for handler in state.button_handlers: handler(state.button) state.is_pressed = True state.last_pressed = time() state.was_pressed_since_last_check = True else: logger.debug('Unknown button code {} ({})'.format(key_code, prefix))
[ "def", "button_pressed", "(", "self", ",", "key_code", ",", "prefix", "=", "None", ")", ":", "if", "prefix", "is", "not", "None", ":", "state", "=", "self", ".", "buttons_by_code", ".", "get", "(", "prefix", "+", "str", "(", "key_code", ")", ")", "el...
Called from the controller classes to update the state of this button manager when a button is pressed. :internal: :param key_code: The code specified when populating Button instances :param prefix: Applied to key code if present
[ "Called", "from", "the", "controller", "classes", "to", "update", "the", "state", "of", "this", "button", "manager", "when", "a", "button", "is", "pressed", "." ]
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/__init__.py#L879-L901
train
42,950
ApproxEng/approxeng.input
src/python/approxeng/input/__init__.py
Buttons.button_released
def button_released(self, key_code, prefix=None): """ Called from the controller classes to update the state of this button manager when a button is released. :internal: :param key_code: The code specified when populating Button instance :param prefix: Applied to key code if present """ if prefix is not None: state = self.buttons_by_code.get(prefix + str(key_code)) else: state = self.buttons_by_code.get(key_code) if state is not None: state.is_pressed = False state.last_pressed = None
python
def button_released(self, key_code, prefix=None): """ Called from the controller classes to update the state of this button manager when a button is released. :internal: :param key_code: The code specified when populating Button instance :param prefix: Applied to key code if present """ if prefix is not None: state = self.buttons_by_code.get(prefix + str(key_code)) else: state = self.buttons_by_code.get(key_code) if state is not None: state.is_pressed = False state.last_pressed = None
[ "def", "button_released", "(", "self", ",", "key_code", ",", "prefix", "=", "None", ")", ":", "if", "prefix", "is", "not", "None", ":", "state", "=", "self", ".", "buttons_by_code", ".", "get", "(", "prefix", "+", "str", "(", "key_code", ")", ")", "e...
Called from the controller classes to update the state of this button manager when a button is released. :internal: :param key_code: The code specified when populating Button instance :param prefix: Applied to key code if present
[ "Called", "from", "the", "controller", "classes", "to", "update", "the", "state", "of", "this", "button", "manager", "when", "a", "button", "is", "released", "." ]
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/__init__.py#L903-L920
train
42,951
ApproxEng/approxeng.input
src/python/approxeng/input/__init__.py
Buttons.check_presses
def check_presses(self): """ Return the set of Buttons which have been pressed since this call was last made, clearing it as we do. :return: A ButtonPresses instance which contains buttons which were pressed since this call was last made. """ pressed = [] for button, state in self.buttons.items(): if state.was_pressed_since_last_check: pressed.append(button) state.was_pressed_since_last_check = False self.__presses = ButtonPresses(pressed) return self.__presses
python
def check_presses(self): """ Return the set of Buttons which have been pressed since this call was last made, clearing it as we do. :return: A ButtonPresses instance which contains buttons which were pressed since this call was last made. """ pressed = [] for button, state in self.buttons.items(): if state.was_pressed_since_last_check: pressed.append(button) state.was_pressed_since_last_check = False self.__presses = ButtonPresses(pressed) return self.__presses
[ "def", "check_presses", "(", "self", ")", ":", "pressed", "=", "[", "]", "for", "button", ",", "state", "in", "self", ".", "buttons", ".", "items", "(", ")", ":", "if", "state", ".", "was_pressed_since_last_check", ":", "pressed", ".", "append", "(", "...
Return the set of Buttons which have been pressed since this call was last made, clearing it as we do. :return: A ButtonPresses instance which contains buttons which were pressed since this call was last made.
[ "Return", "the", "set", "of", "Buttons", "which", "have", "been", "pressed", "since", "this", "call", "was", "last", "made", "clearing", "it", "as", "we", "do", "." ]
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/__init__.py#L945-L958
train
42,952
ApproxEng/approxeng.input
src/python/approxeng/input/__init__.py
Buttons.held
def held(self, sname): """ Determines whether a button is currently held, identifying it by standard name :param sname: The standard name of the button :return: None if the button is not held down, or is not available, otherwise the number of seconds as a floating point value since it was pressed """ state = self.buttons_by_sname.get(sname) if state is not None: if state.is_pressed and state.last_pressed is not None: return time() - state.last_pressed return None
python
def held(self, sname): """ Determines whether a button is currently held, identifying it by standard name :param sname: The standard name of the button :return: None if the button is not held down, or is not available, otherwise the number of seconds as a floating point value since it was pressed """ state = self.buttons_by_sname.get(sname) if state is not None: if state.is_pressed and state.last_pressed is not None: return time() - state.last_pressed return None
[ "def", "held", "(", "self", ",", "sname", ")", ":", "state", "=", "self", ".", "buttons_by_sname", ".", "get", "(", "sname", ")", "if", "state", "is", "not", "None", ":", "if", "state", ".", "is_pressed", "and", "state", ".", "last_pressed", "is", "n...
Determines whether a button is currently held, identifying it by standard name :param sname: The standard name of the button :return: None if the button is not held down, or is not available, otherwise the number of seconds as a floating point value since it was pressed
[ "Determines", "whether", "a", "button", "is", "currently", "held", "identifying", "it", "by", "standard", "name" ]
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/__init__.py#L960-L974
train
42,953
python-useful-helpers/threaded
threaded/class_decorator.py
BaseDecorator._func
def _func(self) -> typing.Optional[typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]]: """Get wrapped function. :rtype: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]] """ return self.__func
python
def _func(self) -> typing.Optional[typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]]: """Get wrapped function. :rtype: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]] """ return self.__func
[ "def", "_func", "(", "self", ")", "->", "typing", ".", "Optional", "[", "typing", ".", "Callable", "[", "...", ",", "typing", ".", "Union", "[", "\"typing.Awaitable[typing.Any]\"", ",", "typing", ".", "Any", "]", "]", "]", ":", "return", "self", ".", "...
Get wrapped function. :rtype: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]]
[ "Get", "wrapped", "function", "." ]
c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a
https://github.com/python-useful-helpers/threaded/blob/c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a/threaded/class_decorator.py#L89-L94
train
42,954
python-useful-helpers/threaded
threaded/class_decorator.py
BaseDecorator._await_if_required
def _await_if_required( target: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]] ) -> typing.Callable[..., typing.Any]: """Await result if coroutine was returned.""" @functools.wraps(target) def wrapper(*args, **kwargs): # type: (typing.Any, typing.Any) -> typing.Any """Decorator/wrapper.""" result = target(*args, **kwargs) if asyncio.iscoroutine(result): loop = asyncio.new_event_loop() result = loop.run_until_complete(result) loop.close() return result return wrapper
python
def _await_if_required( target: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]] ) -> typing.Callable[..., typing.Any]: """Await result if coroutine was returned.""" @functools.wraps(target) def wrapper(*args, **kwargs): # type: (typing.Any, typing.Any) -> typing.Any """Decorator/wrapper.""" result = target(*args, **kwargs) if asyncio.iscoroutine(result): loop = asyncio.new_event_loop() result = loop.run_until_complete(result) loop.close() return result return wrapper
[ "def", "_await_if_required", "(", "target", ":", "typing", ".", "Callable", "[", "...", ",", "typing", ".", "Union", "[", "\"typing.Awaitable[typing.Any]\"", ",", "typing", ".", "Any", "]", "]", ")", "->", "typing", ".", "Callable", "[", "...", ",", "typin...
Await result if coroutine was returned.
[ "Await", "result", "if", "coroutine", "was", "returned", "." ]
c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a
https://github.com/python-useful-helpers/threaded/blob/c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a/threaded/class_decorator.py#L127-L142
train
42,955
ApproxEng/approxeng.input
src/python/approxeng/input/controllers.py
unique_name
def unique_name(device: InputDevice) -> str: """ Construct a unique name for the device based on, in order if available, the uniq ID, the phys ID and finally a concatenation of vendor, product, version and filename. :param device: An InputDevice instance to query :return: A string containing as unique as possible a name for the physical entity represented by the device """ if device.uniq: return device.uniq elif device.phys: return device.phys.split('/')[0] return '{}-{}-{}-{}'.format(device.info.vendor, device.info.product, device.info.version, device.path)
python
def unique_name(device: InputDevice) -> str: """ Construct a unique name for the device based on, in order if available, the uniq ID, the phys ID and finally a concatenation of vendor, product, version and filename. :param device: An InputDevice instance to query :return: A string containing as unique as possible a name for the physical entity represented by the device """ if device.uniq: return device.uniq elif device.phys: return device.phys.split('/')[0] return '{}-{}-{}-{}'.format(device.info.vendor, device.info.product, device.info.version, device.path)
[ "def", "unique_name", "(", "device", ":", "InputDevice", ")", "->", "str", ":", "if", "device", ".", "uniq", ":", "return", "device", ".", "uniq", "elif", "device", ".", "phys", ":", "return", "device", ".", "phys", ".", "split", "(", "'/'", ")", "["...
Construct a unique name for the device based on, in order if available, the uniq ID, the phys ID and finally a concatenation of vendor, product, version and filename. :param device: An InputDevice instance to query :return: A string containing as unique as possible a name for the physical entity represented by the device
[ "Construct", "a", "unique", "name", "for", "the", "device", "based", "on", "in", "order", "if", "available", "the", "uniq", "ID", "the", "phys", "ID", "and", "finally", "a", "concatenation", "of", "vendor", "product", "version", "and", "filename", "." ]
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/controllers.py#L115-L129
train
42,956
ApproxEng/approxeng.input
src/python/approxeng/input/controllers.py
find_matching_controllers
def find_matching_controllers(*requirements, **kwargs) -> [ControllerDiscovery]: """ Find a sequence of controllers which match the supplied requirements, or raise an error if no such controllers exist. :param requirements: Zero or more ControllerRequirement instances defining the requirements for controllers. If no item is passed it will be treated as a single requirement with no filters applied and will therefore match the first controller found. :return: A sequence of the same length as the supplied requirements array containing ControllerDiscovery instances which match the requirements supplied. :raises: ControllerNotFoundError if no appropriately matching controllers can be located """ requirements = list(requirements) if requirements is None or len(requirements) == 0: requirements = [ControllerRequirement()] def pop_controller(r: ControllerRequirement, discoveries: [ControllerDiscovery]) -> ControllerDiscovery: """ Find a single controller matching the supplied requirement from a list of ControllerDiscovery instances :param r: The ControllerRequirement to match :param discoveries: The [ControllerDiscovery] to search :return: A matching ControllerDiscovery. Modifies the supplied list of discoveries, removing the found item. :raises: ControllerNotFoundError if no matching controller can be found """ for index, d in enumerate(discoveries): if r.accept(d): return discoveries.pop(index) raise ControllerNotFoundError() all_controllers = find_all_controllers(**kwargs) try: return list(pop_controller(r, all_controllers) for r in requirements) except ControllerNotFoundError as exception: logger.info('Unable to satisfy controller requirements' + ', required {}, found {}'.format(requirements, find_all_controllers(**kwargs))) raise exception
python
def find_matching_controllers(*requirements, **kwargs) -> [ControllerDiscovery]: """ Find a sequence of controllers which match the supplied requirements, or raise an error if no such controllers exist. :param requirements: Zero or more ControllerRequirement instances defining the requirements for controllers. If no item is passed it will be treated as a single requirement with no filters applied and will therefore match the first controller found. :return: A sequence of the same length as the supplied requirements array containing ControllerDiscovery instances which match the requirements supplied. :raises: ControllerNotFoundError if no appropriately matching controllers can be located """ requirements = list(requirements) if requirements is None or len(requirements) == 0: requirements = [ControllerRequirement()] def pop_controller(r: ControllerRequirement, discoveries: [ControllerDiscovery]) -> ControllerDiscovery: """ Find a single controller matching the supplied requirement from a list of ControllerDiscovery instances :param r: The ControllerRequirement to match :param discoveries: The [ControllerDiscovery] to search :return: A matching ControllerDiscovery. Modifies the supplied list of discoveries, removing the found item. :raises: ControllerNotFoundError if no matching controller can be found """ for index, d in enumerate(discoveries): if r.accept(d): return discoveries.pop(index) raise ControllerNotFoundError() all_controllers = find_all_controllers(**kwargs) try: return list(pop_controller(r, all_controllers) for r in requirements) except ControllerNotFoundError as exception: logger.info('Unable to satisfy controller requirements' + ', required {}, found {}'.format(requirements, find_all_controllers(**kwargs))) raise exception
[ "def", "find_matching_controllers", "(", "*", "requirements", ",", "*", "*", "kwargs", ")", "->", "[", "ControllerDiscovery", "]", ":", "requirements", "=", "list", "(", "requirements", ")", "if", "requirements", "is", "None", "or", "len", "(", "requirements",...
Find a sequence of controllers which match the supplied requirements, or raise an error if no such controllers exist. :param requirements: Zero or more ControllerRequirement instances defining the requirements for controllers. If no item is passed it will be treated as a single requirement with no filters applied and will therefore match the first controller found. :return: A sequence of the same length as the supplied requirements array containing ControllerDiscovery instances which match the requirements supplied. :raises: ControllerNotFoundError if no appropriately matching controllers can be located
[ "Find", "a", "sequence", "of", "controllers", "which", "match", "the", "supplied", "requirements", "or", "raise", "an", "error", "if", "no", "such", "controllers", "exist", "." ]
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/controllers.py#L132-L176
train
42,957
ApproxEng/approxeng.input
src/python/approxeng/input/controllers.py
print_devices
def print_devices(): """ Simple test function which prints out all devices found by evdev """ def device_verbose_info(device: InputDevice) -> {}: """ Gather and format as much info as possible about the supplied InputDevice. Used mostly for debugging at this point. :param device: An InputDevice to examine :return: A dict containing as much information as possible about the input device. """ def axis_name(axis_code): try: return ecodes.ABS[axis_code] except KeyError: return 'EXTENDED_CODE_{}'.format(axis_code) def rel_axis_name(axis_code): try: return ecodes.REL[axis_code] except KeyError: return 'EXTENDED_CODE_{}'.format(axis_code) axes = None if has_abs_axes(device): axes = { axis_name(axis_code): {'code': axis_code, 'min': axis_info.min, 'max': axis_info.max, 'fuzz': axis_info.fuzz, 'flat': axis_info.flat, 'res': axis_info.resolution} for axis_code, axis_info in device.capabilities().get(3)} rel_axes = None if has_rel_axes(device): print(device.capabilities().get(2)) rel_axes = { rel_axis_name(axis_code): {'code': axis_code} for axis_code in device.capabilities().get(2)} buttons = None if has_buttons(device): buttons = {code: names for (names, code) in dict(util.resolve_ecodes_dict({1: device.capabilities().get(1)})).get(('EV_KEY', 1))} return {'fn': device.fn, 'path': device.path, 'name': device.name, 'phys': device.phys, 'uniq': device.uniq, 'vendor': device.info.vendor, 'product': device.info.product, 'version': device.info.version, 'bus': device.info.bustype, 'axes': axes, 'rel_axes': rel_axes, 'buttons': buttons, 'unique_name': unique_name(device)} def has_abs_axes(device): return device.capabilities().get(3) is not None def has_rel_axes(device): return device.capabilities().get(2) is not None def has_buttons(device): return device.capabilities().get(1) is not None _check_import() for d in [InputDevice(fn) for fn in list_devices()]: if has_abs_axes(d) or has_rel_axes(d): pp = pprint.PrettyPrinter(indent=2, width=100) pp.pprint(device_verbose_info(d))
python
def print_devices(): """ Simple test function which prints out all devices found by evdev """ def device_verbose_info(device: InputDevice) -> {}: """ Gather and format as much info as possible about the supplied InputDevice. Used mostly for debugging at this point. :param device: An InputDevice to examine :return: A dict containing as much information as possible about the input device. """ def axis_name(axis_code): try: return ecodes.ABS[axis_code] except KeyError: return 'EXTENDED_CODE_{}'.format(axis_code) def rel_axis_name(axis_code): try: return ecodes.REL[axis_code] except KeyError: return 'EXTENDED_CODE_{}'.format(axis_code) axes = None if has_abs_axes(device): axes = { axis_name(axis_code): {'code': axis_code, 'min': axis_info.min, 'max': axis_info.max, 'fuzz': axis_info.fuzz, 'flat': axis_info.flat, 'res': axis_info.resolution} for axis_code, axis_info in device.capabilities().get(3)} rel_axes = None if has_rel_axes(device): print(device.capabilities().get(2)) rel_axes = { rel_axis_name(axis_code): {'code': axis_code} for axis_code in device.capabilities().get(2)} buttons = None if has_buttons(device): buttons = {code: names for (names, code) in dict(util.resolve_ecodes_dict({1: device.capabilities().get(1)})).get(('EV_KEY', 1))} return {'fn': device.fn, 'path': device.path, 'name': device.name, 'phys': device.phys, 'uniq': device.uniq, 'vendor': device.info.vendor, 'product': device.info.product, 'version': device.info.version, 'bus': device.info.bustype, 'axes': axes, 'rel_axes': rel_axes, 'buttons': buttons, 'unique_name': unique_name(device)} def has_abs_axes(device): return device.capabilities().get(3) is not None def has_rel_axes(device): return device.capabilities().get(2) is not None def has_buttons(device): return device.capabilities().get(1) is not None _check_import() for d in [InputDevice(fn) for fn in list_devices()]: if has_abs_axes(d) or has_rel_axes(d): pp = pprint.PrettyPrinter(indent=2, width=100) pp.pprint(device_verbose_info(d))
[ "def", "print_devices", "(", ")", ":", "def", "device_verbose_info", "(", "device", ":", "InputDevice", ")", "->", "{", "}", ":", "\"\"\"\n Gather and format as much info as possible about the supplied InputDevice. Used mostly for debugging at this point.\n\n :param dev...
Simple test function which prints out all devices found by evdev
[ "Simple", "test", "function", "which", "prints", "out", "all", "devices", "found", "by", "evdev" ]
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/controllers.py#L226-L291
train
42,958
ApproxEng/approxeng.input
src/python/approxeng/input/controllers.py
print_controllers
def print_controllers(): """ Pretty-print all controllers found """ _check_import() pp = pprint.PrettyPrinter(indent=2) for discovery in find_all_controllers(): pp.pprint(discovery.controller)
python
def print_controllers(): """ Pretty-print all controllers found """ _check_import() pp = pprint.PrettyPrinter(indent=2) for discovery in find_all_controllers(): pp.pprint(discovery.controller)
[ "def", "print_controllers", "(", ")", ":", "_check_import", "(", ")", "pp", "=", "pprint", ".", "PrettyPrinter", "(", "indent", "=", "2", ")", "for", "discovery", "in", "find_all_controllers", "(", ")", ":", "pp", ".", "pprint", "(", "discovery", ".", "c...
Pretty-print all controllers found
[ "Pretty", "-", "print", "all", "controllers", "found" ]
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/controllers.py#L294-L301
train
42,959
ApproxEng/approxeng.input
src/python/approxeng/input/controllers.py
ControllerRequirement.accept
def accept(self, discovery: ControllerDiscovery): """ Returns True if the supplied ControllerDiscovery matches this requirement, False otherwise """ if self.require_class is not None and not isinstance(discovery.controller, self.require_class): return False if self.snames is not None: all_controls = discovery.controller.buttons.names + discovery.controller.axes.names for sname in self.snames: if sname not in all_controls: return False return True
python
def accept(self, discovery: ControllerDiscovery): """ Returns True if the supplied ControllerDiscovery matches this requirement, False otherwise """ if self.require_class is not None and not isinstance(discovery.controller, self.require_class): return False if self.snames is not None: all_controls = discovery.controller.buttons.names + discovery.controller.axes.names for sname in self.snames: if sname not in all_controls: return False return True
[ "def", "accept", "(", "self", ",", "discovery", ":", "ControllerDiscovery", ")", ":", "if", "self", ".", "require_class", "is", "not", "None", "and", "not", "isinstance", "(", "discovery", ".", "controller", ",", "self", ".", "require_class", ")", ":", "re...
Returns True if the supplied ControllerDiscovery matches this requirement, False otherwise
[ "Returns", "True", "if", "the", "supplied", "ControllerDiscovery", "matches", "this", "requirement", "False", "otherwise" ]
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/controllers.py#L94-L105
train
42,960
TadLeonard/tfatool
tfatool/config.py
post
def post(param_map, url=URL): """Posts a `param_map` created with `config` to the FlashAir config.cgi entrypoint""" prepped_request = _prep_post(url=url, **param_map) return cgi.send(prepped_request)
python
def post(param_map, url=URL): """Posts a `param_map` created with `config` to the FlashAir config.cgi entrypoint""" prepped_request = _prep_post(url=url, **param_map) return cgi.send(prepped_request)
[ "def", "post", "(", "param_map", ",", "url", "=", "URL", ")", ":", "prepped_request", "=", "_prep_post", "(", "url", "=", "url", ",", "*", "*", "param_map", ")", "return", "cgi", ".", "send", "(", "prepped_request", ")" ]
Posts a `param_map` created with `config` to the FlashAir config.cgi entrypoint
[ "Posts", "a", "param_map", "created", "with", "config", "to", "the", "FlashAir", "config", ".", "cgi", "entrypoint" ]
12da2807b5fb538c5317ef255d846b32ceb174d0
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/config.py#L24-L28
train
42,961
TadLeonard/tfatool
tfatool/config.py
_validate_timeout
def _validate_timeout(seconds: float): """Creates an int from 60000 to 4294967294 that represents a valid millisecond wireless LAN timeout""" val = int(seconds * 1000) assert 60000 <= val <= 4294967294, "Bad value: {}".format(val) return val
python
def _validate_timeout(seconds: float): """Creates an int from 60000 to 4294967294 that represents a valid millisecond wireless LAN timeout""" val = int(seconds * 1000) assert 60000 <= val <= 4294967294, "Bad value: {}".format(val) return val
[ "def", "_validate_timeout", "(", "seconds", ":", "float", ")", ":", "val", "=", "int", "(", "seconds", "*", "1000", ")", "assert", "60000", "<=", "val", "<=", "4294967294", ",", "\"Bad value: {}\"", ".", "format", "(", "val", ")", "return", "val" ]
Creates an int from 60000 to 4294967294 that represents a valid millisecond wireless LAN timeout
[ "Creates", "an", "int", "from", "60000", "to", "4294967294", "that", "represents", "a", "valid", "millisecond", "wireless", "LAN", "timeout" ]
12da2807b5fb538c5317ef255d846b32ceb174d0
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/config.py#L48-L53
train
42,962
TadLeonard/tfatool
tfatool/util.py
parse_datetime
def parse_datetime(datetime_input): """The arrow library is sadly not good enough to parse certain date strings. It even gives unexpected results for partial date strings such as '2015-01' or just '2015', which I think should be seen as 'the first moment of 2014'. This function should overcome those limitations.""" date_els, time_els = _split_datetime(datetime_input) date_vals = _parse_date(date_els) time_vals = _parse_time(time_els) vals = tuple(date_vals) + tuple(time_vals) return arrow.get(*vals)
python
def parse_datetime(datetime_input): """The arrow library is sadly not good enough to parse certain date strings. It even gives unexpected results for partial date strings such as '2015-01' or just '2015', which I think should be seen as 'the first moment of 2014'. This function should overcome those limitations.""" date_els, time_els = _split_datetime(datetime_input) date_vals = _parse_date(date_els) time_vals = _parse_time(time_els) vals = tuple(date_vals) + tuple(time_vals) return arrow.get(*vals)
[ "def", "parse_datetime", "(", "datetime_input", ")", ":", "date_els", ",", "time_els", "=", "_split_datetime", "(", "datetime_input", ")", "date_vals", "=", "_parse_date", "(", "date_els", ")", "time_vals", "=", "_parse_time", "(", "time_els", ")", "vals", "=", ...
The arrow library is sadly not good enough to parse certain date strings. It even gives unexpected results for partial date strings such as '2015-01' or just '2015', which I think should be seen as 'the first moment of 2014'. This function should overcome those limitations.
[ "The", "arrow", "library", "is", "sadly", "not", "good", "enough", "to", "parse", "certain", "date", "strings", ".", "It", "even", "gives", "unexpected", "results", "for", "partial", "date", "strings", "such", "as", "2015", "-", "01", "or", "just", "2015",...
12da2807b5fb538c5317ef255d846b32ceb174d0
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/util.py#L7-L17
train
42,963
ApproxEng/approxeng.input
src/python/approxeng/input/dualshock3.py
DualShock3.set_led
def set_led(self, led_number, led_value): """ Set front-panel controller LEDs. The DS3 controller has four, labelled, LEDs on the front panel that can be either on or off. :param led_number: Integer between 1 and 4 :param led_value: Value, set to 0 to turn the LED off, 1 to turn it on """ if 1 > led_number > 4: return write_led_value(hw_id=self.device_unique_name, led_name='sony{}'.format(led_number), value=led_value)
python
def set_led(self, led_number, led_value): """ Set front-panel controller LEDs. The DS3 controller has four, labelled, LEDs on the front panel that can be either on or off. :param led_number: Integer between 1 and 4 :param led_value: Value, set to 0 to turn the LED off, 1 to turn it on """ if 1 > led_number > 4: return write_led_value(hw_id=self.device_unique_name, led_name='sony{}'.format(led_number), value=led_value)
[ "def", "set_led", "(", "self", ",", "led_number", ",", "led_value", ")", ":", "if", "1", ">", "led_number", ">", "4", ":", "return", "write_led_value", "(", "hw_id", "=", "self", ".", "device_unique_name", ",", "led_name", "=", "'sony{}'", ".", "format", ...
Set front-panel controller LEDs. The DS3 controller has four, labelled, LEDs on the front panel that can be either on or off. :param led_number: Integer between 1 and 4 :param led_value: Value, set to 0 to turn the LED off, 1 to turn it on
[ "Set", "front", "-", "panel", "controller", "LEDs", ".", "The", "DS3", "controller", "has", "four", "labelled", "LEDs", "on", "the", "front", "panel", "that", "can", "be", "either", "on", "or", "off", "." ]
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/dualshock3.py#L64-L76
train
42,964
alfredodeza/remoto
remoto/util.py
admin_command
def admin_command(sudo, command): """ If sudo is needed, make sure the command is prepended correctly, otherwise return the command as it came. :param sudo: A boolean representing the intention of having a sudo command (or not) :param command: A list of the actual command to execute with Popen. """ if sudo: if not isinstance(command, list): command = [command] return ['sudo'] + [cmd for cmd in command] return command
python
def admin_command(sudo, command): """ If sudo is needed, make sure the command is prepended correctly, otherwise return the command as it came. :param sudo: A boolean representing the intention of having a sudo command (or not) :param command: A list of the actual command to execute with Popen. """ if sudo: if not isinstance(command, list): command = [command] return ['sudo'] + [cmd for cmd in command] return command
[ "def", "admin_command", "(", "sudo", ",", "command", ")", ":", "if", "sudo", ":", "if", "not", "isinstance", "(", "command", ",", "list", ")", ":", "command", "=", "[", "command", "]", "return", "[", "'sudo'", "]", "+", "[", "cmd", "for", "cmd", "i...
If sudo is needed, make sure the command is prepended correctly, otherwise return the command as it came. :param sudo: A boolean representing the intention of having a sudo command (or not) :param command: A list of the actual command to execute with Popen.
[ "If", "sudo", "is", "needed", "make", "sure", "the", "command", "is", "prepended", "correctly", "otherwise", "return", "the", "command", "as", "it", "came", "." ]
b7625e571a4b6c83f9589a1e9ad07354e42bf0d3
https://github.com/alfredodeza/remoto/blob/b7625e571a4b6c83f9589a1e9ad07354e42bf0d3/remoto/util.py#L3-L16
train
42,965
TadLeonard/tfatool
tfatool/upload.py
_encode_time
def _encode_time(mtime: float): """Encode a mtime float as a 32-bit FAT time""" dt = arrow.get(mtime) dt = dt.to("local") date_val = ((dt.year - 1980) << 9) | (dt.month << 5) | dt.day secs = dt.second + dt.microsecond / 10**6 time_val = (dt.hour << 11) | (dt.minute << 5) | math.floor(secs / 2) return (date_val << 16) | time_val
python
def _encode_time(mtime: float): """Encode a mtime float as a 32-bit FAT time""" dt = arrow.get(mtime) dt = dt.to("local") date_val = ((dt.year - 1980) << 9) | (dt.month << 5) | dt.day secs = dt.second + dt.microsecond / 10**6 time_val = (dt.hour << 11) | (dt.minute << 5) | math.floor(secs / 2) return (date_val << 16) | time_val
[ "def", "_encode_time", "(", "mtime", ":", "float", ")", ":", "dt", "=", "arrow", ".", "get", "(", "mtime", ")", "dt", "=", "dt", ".", "to", "(", "\"local\"", ")", "date_val", "=", "(", "(", "dt", ".", "year", "-", "1980", ")", "<<", "9", ")", ...
Encode a mtime float as a 32-bit FAT time
[ "Encode", "a", "mtime", "float", "as", "a", "32", "-", "bit", "FAT", "time" ]
12da2807b5fb538c5317ef255d846b32ceb174d0
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/upload.py#L84-L91
train
42,966
python-useful-helpers/threaded
threaded/_threadpooled.py
threadpooled
def threadpooled( # noqa: F811 func: typing.Optional[typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]] = None, *, loop_getter: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] = None, loop_getter_need_context: bool = False, ) -> typing.Union[ ThreadPooled, typing.Callable[..., "typing.Union[concurrent.futures.Future[typing.Any], typing.Awaitable[typing.Any]]"], ]: """Post function to ThreadPoolExecutor. :param func: function to wrap :type func: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]] :param loop_getter: Method to get event loop, if wrap in asyncio task :type loop_getter: typing.Union[ None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop ] :param loop_getter_need_context: Loop getter requires function context :type loop_getter_need_context: bool :return: ThreadPooled instance, if called as function or argumented decorator, else callable wrapper :rtype: typing.Union[ThreadPooled, typing.Callable[..., typing.Union[concurrent.futures.Future, typing.Awaitable]]] """ if func is None: return ThreadPooled(func=func, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context) return ThreadPooled( # type: ignore func=None, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context )(func)
python
def threadpooled( # noqa: F811 func: typing.Optional[typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]] = None, *, loop_getter: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] = None, loop_getter_need_context: bool = False, ) -> typing.Union[ ThreadPooled, typing.Callable[..., "typing.Union[concurrent.futures.Future[typing.Any], typing.Awaitable[typing.Any]]"], ]: """Post function to ThreadPoolExecutor. :param func: function to wrap :type func: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]] :param loop_getter: Method to get event loop, if wrap in asyncio task :type loop_getter: typing.Union[ None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop ] :param loop_getter_need_context: Loop getter requires function context :type loop_getter_need_context: bool :return: ThreadPooled instance, if called as function or argumented decorator, else callable wrapper :rtype: typing.Union[ThreadPooled, typing.Callable[..., typing.Union[concurrent.futures.Future, typing.Awaitable]]] """ if func is None: return ThreadPooled(func=func, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context) return ThreadPooled( # type: ignore func=None, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context )(func)
[ "def", "threadpooled", "(", "# noqa: F811", "func", ":", "typing", ".", "Optional", "[", "typing", ".", "Callable", "[", "...", ",", "typing", ".", "Union", "[", "\"typing.Awaitable[typing.Any]\"", ",", "typing", ".", "Any", "]", "]", "]", "=", "None", ","...
Post function to ThreadPoolExecutor. :param func: function to wrap :type func: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]] :param loop_getter: Method to get event loop, if wrap in asyncio task :type loop_getter: typing.Union[ None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop ] :param loop_getter_need_context: Loop getter requires function context :type loop_getter_need_context: bool :return: ThreadPooled instance, if called as function or argumented decorator, else callable wrapper :rtype: typing.Union[ThreadPooled, typing.Callable[..., typing.Union[concurrent.futures.Future, typing.Awaitable]]]
[ "Post", "function", "to", "ThreadPoolExecutor", "." ]
c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a
https://github.com/python-useful-helpers/threaded/blob/c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a/threaded/_threadpooled.py#L208-L236
train
42,967
python-useful-helpers/threaded
threaded/_threadpooled.py
ThreadPooled.configure
def configure(cls: typing.Type["ThreadPooled"], max_workers: typing.Optional[int] = None) -> None: """Pool executor create and configure. :param max_workers: Maximum workers :type max_workers: typing.Optional[int] """ if isinstance(cls.__executor, ThreadPoolExecutor): if cls.__executor.max_workers == max_workers: return cls.__executor.shutdown() cls.__executor = ThreadPoolExecutor(max_workers=max_workers)
python
def configure(cls: typing.Type["ThreadPooled"], max_workers: typing.Optional[int] = None) -> None: """Pool executor create and configure. :param max_workers: Maximum workers :type max_workers: typing.Optional[int] """ if isinstance(cls.__executor, ThreadPoolExecutor): if cls.__executor.max_workers == max_workers: return cls.__executor.shutdown() cls.__executor = ThreadPoolExecutor(max_workers=max_workers)
[ "def", "configure", "(", "cls", ":", "typing", ".", "Type", "[", "\"ThreadPooled\"", "]", ",", "max_workers", ":", "typing", ".", "Optional", "[", "int", "]", "=", "None", ")", "->", "None", ":", "if", "isinstance", "(", "cls", ".", "__executor", ",", ...
Pool executor create and configure. :param max_workers: Maximum workers :type max_workers: typing.Optional[int]
[ "Pool", "executor", "create", "and", "configure", "." ]
c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a
https://github.com/python-useful-helpers/threaded/blob/c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a/threaded/_threadpooled.py#L40-L51
train
42,968
python-useful-helpers/threaded
threaded/_threadpooled.py
ThreadPooled.executor
def executor(self) -> "ThreadPoolExecutor": """Executor instance. :rtype: ThreadPoolExecutor """ if not isinstance(self.__executor, ThreadPoolExecutor) or self.__executor.is_shutdown: self.configure() return self.__executor
python
def executor(self) -> "ThreadPoolExecutor": """Executor instance. :rtype: ThreadPoolExecutor """ if not isinstance(self.__executor, ThreadPoolExecutor) or self.__executor.is_shutdown: self.configure() return self.__executor
[ "def", "executor", "(", "self", ")", "->", "\"ThreadPoolExecutor\"", ":", "if", "not", "isinstance", "(", "self", ".", "__executor", ",", "ThreadPoolExecutor", ")", "or", "self", ".", "__executor", ".", "is_shutdown", ":", "self", ".", "configure", "(", ")",...
Executor instance. :rtype: ThreadPoolExecutor
[ "Executor", "instance", "." ]
c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a
https://github.com/python-useful-helpers/threaded/blob/c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a/threaded/_threadpooled.py#L60-L67
train
42,969
python-useful-helpers/threaded
threaded/_threadpooled.py
ThreadPooled.loop_getter
def loop_getter( self ) -> typing.Optional[typing.Union[typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop]]: """Loop getter. :rtype: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] """ return self.__loop_getter
python
def loop_getter( self ) -> typing.Optional[typing.Union[typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop]]: """Loop getter. :rtype: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] """ return self.__loop_getter
[ "def", "loop_getter", "(", "self", ")", "->", "typing", ".", "Optional", "[", "typing", ".", "Union", "[", "typing", ".", "Callable", "[", "...", ",", "asyncio", ".", "AbstractEventLoop", "]", ",", "asyncio", ".", "AbstractEventLoop", "]", "]", ":", "ret...
Loop getter. :rtype: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop]
[ "Loop", "getter", "." ]
c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a
https://github.com/python-useful-helpers/threaded/blob/c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a/threaded/_threadpooled.py#L98-L105
train
42,970
alfredodeza/remoto
remoto/backends/__init__.py
needs_ssh
def needs_ssh(hostname, _socket=None): """ Obtains remote hostname of the socket and cuts off the domain part of its FQDN. """ if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']: return False _socket = _socket or socket fqdn = _socket.getfqdn() if hostname == fqdn: return False local_hostname = _socket.gethostname() local_short_hostname = local_hostname.split('.')[0] if local_hostname == hostname or local_short_hostname == hostname: return False return True
python
def needs_ssh(hostname, _socket=None): """ Obtains remote hostname of the socket and cuts off the domain part of its FQDN. """ if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']: return False _socket = _socket or socket fqdn = _socket.getfqdn() if hostname == fqdn: return False local_hostname = _socket.gethostname() local_short_hostname = local_hostname.split('.')[0] if local_hostname == hostname or local_short_hostname == hostname: return False return True
[ "def", "needs_ssh", "(", "hostname", ",", "_socket", "=", "None", ")", ":", "if", "hostname", ".", "lower", "(", ")", "in", "[", "'localhost'", ",", "'127.0.0.1'", ",", "'127.0.1.1'", "]", ":", "return", "False", "_socket", "=", "_socket", "or", "socket"...
Obtains remote hostname of the socket and cuts off the domain part of its FQDN.
[ "Obtains", "remote", "hostname", "of", "the", "socket", "and", "cuts", "off", "the", "domain", "part", "of", "its", "FQDN", "." ]
b7625e571a4b6c83f9589a1e9ad07354e42bf0d3
https://github.com/alfredodeza/remoto/blob/b7625e571a4b6c83f9589a1e9ad07354e42bf0d3/remoto/backends/__init__.py#L277-L292
train
42,971
alfredodeza/remoto
remoto/backends/__init__.py
get_python_executable
def get_python_executable(conn): """ Try to determine the remote Python version so that it can be used when executing. Avoids the problem of different Python versions, or distros that do not use ``python`` but do ``python3`` """ # executables in order of preference: executables = ['python3', 'python', 'python2.7'] for executable in executables: conn.logger.debug('trying to determine remote python executable with %s' % executable) out, err, code = check(conn, ['which', executable]) if code: conn.logger.warning('skipping %s, was not found in path' % executable) else: try: return out[0].strip() except IndexError: conn.logger.warning('could not parse stdout: %s' % out) # if all fails, we just return whatever the main connection had conn.logger.info('Falling back to using interpreter: %s' % conn.interpreter) return conn.interpreter
python
def get_python_executable(conn): """ Try to determine the remote Python version so that it can be used when executing. Avoids the problem of different Python versions, or distros that do not use ``python`` but do ``python3`` """ # executables in order of preference: executables = ['python3', 'python', 'python2.7'] for executable in executables: conn.logger.debug('trying to determine remote python executable with %s' % executable) out, err, code = check(conn, ['which', executable]) if code: conn.logger.warning('skipping %s, was not found in path' % executable) else: try: return out[0].strip() except IndexError: conn.logger.warning('could not parse stdout: %s' % out) # if all fails, we just return whatever the main connection had conn.logger.info('Falling back to using interpreter: %s' % conn.interpreter) return conn.interpreter
[ "def", "get_python_executable", "(", "conn", ")", ":", "# executables in order of preference:", "executables", "=", "[", "'python3'", ",", "'python'", ",", "'python2.7'", "]", "for", "executable", "in", "executables", ":", "conn", ".", "logger", ".", "debug", "(",...
Try to determine the remote Python version so that it can be used when executing. Avoids the problem of different Python versions, or distros that do not use ``python`` but do ``python3``
[ "Try", "to", "determine", "the", "remote", "Python", "version", "so", "that", "it", "can", "be", "used", "when", "executing", ".", "Avoids", "the", "problem", "of", "different", "Python", "versions", "or", "distros", "that", "do", "not", "use", "python", "...
b7625e571a4b6c83f9589a1e9ad07354e42bf0d3
https://github.com/alfredodeza/remoto/blob/b7625e571a4b6c83f9589a1e9ad07354e42bf0d3/remoto/backends/__init__.py#L295-L316
train
42,972
alfredodeza/remoto
remoto/backends/__init__.py
BaseConnection.import_module
def import_module(self, module): """ Allows remote execution of a local module. Depending on the ``remote_import_system`` attribute it may use execnet's implementation or remoto's own based on JSON. .. note:: It is not possible to use execnet's remote execution model on connections that aren't SSH or Local. """ if self.remote_import_system is not None: if self.remote_import_system == 'json': self.remote_module = JsonModuleExecute(self, module, self.logger) else: self.remote_module = LegacyModuleExecute(self.gateway, module, self.logger) else: self.remote_module = LegacyModuleExecute(self.gateway, module, self.logger) return self.remote_module
python
def import_module(self, module): """ Allows remote execution of a local module. Depending on the ``remote_import_system`` attribute it may use execnet's implementation or remoto's own based on JSON. .. note:: It is not possible to use execnet's remote execution model on connections that aren't SSH or Local. """ if self.remote_import_system is not None: if self.remote_import_system == 'json': self.remote_module = JsonModuleExecute(self, module, self.logger) else: self.remote_module = LegacyModuleExecute(self.gateway, module, self.logger) else: self.remote_module = LegacyModuleExecute(self.gateway, module, self.logger) return self.remote_module
[ "def", "import_module", "(", "self", ",", "module", ")", ":", "if", "self", ".", "remote_import_system", "is", "not", "None", ":", "if", "self", ".", "remote_import_system", "==", "'json'", ":", "self", ".", "remote_module", "=", "JsonModuleExecute", "(", "s...
Allows remote execution of a local module. Depending on the ``remote_import_system`` attribute it may use execnet's implementation or remoto's own based on JSON. .. note:: It is not possible to use execnet's remote execution model on connections that aren't SSH or Local.
[ "Allows", "remote", "execution", "of", "a", "local", "module", ".", "Depending", "on", "the", "remote_import_system", "attribute", "it", "may", "use", "execnet", "s", "implementation", "or", "remoto", "s", "own", "based", "on", "JSON", "." ]
b7625e571a4b6c83f9589a1e9ad07354e42bf0d3
https://github.com/alfredodeza/remoto/blob/b7625e571a4b6c83f9589a1e9ad07354e42bf0d3/remoto/backends/__init__.py#L114-L130
train
42,973
alfredodeza/remoto
remoto/connection.py
get
def get(name, fallback='ssh'): """ Retrieve the matching backend class from a string. If no backend can be matched, it raises an error. >>> get('ssh') <class 'remoto.backends.BaseConnection'> >>> get() <class 'remoto.backends.BaseConnection'> >>> get('non-existent') <class 'remoto.backends.BaseConnection'> >>> get('non-existent', 'openshift') <class 'remoto.backends.openshift.OpenshiftConnection'> """ mapping = { 'ssh': ssh.SshConnection, 'oc': openshift.OpenshiftConnection, 'openshift': openshift.OpenshiftConnection, 'kubernetes': kubernetes.KubernetesConnection, 'k8s': kubernetes.KubernetesConnection, 'local': local.LocalConnection, 'popen': local.LocalConnection, 'localhost': local.LocalConnection, 'docker': docker.DockerConnection, 'podman': podman.PodmanConnection, } if not name: # fallsback to just plain local/ssh name = 'ssh' name = name.strip().lower() connection_class = mapping.get(name) if not connection_class: logger.warning('no connection backend found for: "%s"' % name) if fallback: logger.info('falling back to "%s"' % fallback) # this assumes that ``fallback`` is a valid mapping name return mapping.get(fallback) return connection_class
python
def get(name, fallback='ssh'): """ Retrieve the matching backend class from a string. If no backend can be matched, it raises an error. >>> get('ssh') <class 'remoto.backends.BaseConnection'> >>> get() <class 'remoto.backends.BaseConnection'> >>> get('non-existent') <class 'remoto.backends.BaseConnection'> >>> get('non-existent', 'openshift') <class 'remoto.backends.openshift.OpenshiftConnection'> """ mapping = { 'ssh': ssh.SshConnection, 'oc': openshift.OpenshiftConnection, 'openshift': openshift.OpenshiftConnection, 'kubernetes': kubernetes.KubernetesConnection, 'k8s': kubernetes.KubernetesConnection, 'local': local.LocalConnection, 'popen': local.LocalConnection, 'localhost': local.LocalConnection, 'docker': docker.DockerConnection, 'podman': podman.PodmanConnection, } if not name: # fallsback to just plain local/ssh name = 'ssh' name = name.strip().lower() connection_class = mapping.get(name) if not connection_class: logger.warning('no connection backend found for: "%s"' % name) if fallback: logger.info('falling back to "%s"' % fallback) # this assumes that ``fallback`` is a valid mapping name return mapping.get(fallback) return connection_class
[ "def", "get", "(", "name", ",", "fallback", "=", "'ssh'", ")", ":", "mapping", "=", "{", "'ssh'", ":", "ssh", ".", "SshConnection", ",", "'oc'", ":", "openshift", ".", "OpenshiftConnection", ",", "'openshift'", ":", "openshift", ".", "OpenshiftConnection", ...
Retrieve the matching backend class from a string. If no backend can be matched, it raises an error. >>> get('ssh') <class 'remoto.backends.BaseConnection'> >>> get() <class 'remoto.backends.BaseConnection'> >>> get('non-existent') <class 'remoto.backends.BaseConnection'> >>> get('non-existent', 'openshift') <class 'remoto.backends.openshift.OpenshiftConnection'>
[ "Retrieve", "the", "matching", "backend", "class", "from", "a", "string", ".", "If", "no", "backend", "can", "be", "matched", "it", "raises", "an", "error", "." ]
b7625e571a4b6c83f9589a1e9ad07354e42bf0d3
https://github.com/alfredodeza/remoto/blob/b7625e571a4b6c83f9589a1e9ad07354e42bf0d3/remoto/connection.py#L10-L48
train
42,974
ApproxEng/approxeng.input
src/python/approxeng/input/dualshock4.py
DualShock4.set_leds
def set_leds(self, hue: float = 0.0, saturation: float = 1.0, value: float = 1.0): """ The DualShock4 has an LED bar on the front of the controller. This function allows you to set the value of this bar. Note that the controller must be connected for this to work, if it's not the call will just be ignored. :param hue: The hue of the colour, defaults to 0, specified as a floating point value between 0.0 and 1.0. :param saturation: Saturation of the colour, defaults to 1.0, specified as a floating point value between 0.0 and 1.0. :param value: Value of the colour (i.e. how bright the light is overall), defaults to 1.0, specified as a floating point value between 0.0 and 1.0 """ r, g, b = hsv_to_rgb(hue, saturation, value) write_led_value(self.device_unique_name, 'red', r * 255.0) write_led_value(self.device_unique_name, 'green', g * 255.0) write_led_value(self.device_unique_name, 'blue', b * 255.0)
python
def set_leds(self, hue: float = 0.0, saturation: float = 1.0, value: float = 1.0): """ The DualShock4 has an LED bar on the front of the controller. This function allows you to set the value of this bar. Note that the controller must be connected for this to work, if it's not the call will just be ignored. :param hue: The hue of the colour, defaults to 0, specified as a floating point value between 0.0 and 1.0. :param saturation: Saturation of the colour, defaults to 1.0, specified as a floating point value between 0.0 and 1.0. :param value: Value of the colour (i.e. how bright the light is overall), defaults to 1.0, specified as a floating point value between 0.0 and 1.0 """ r, g, b = hsv_to_rgb(hue, saturation, value) write_led_value(self.device_unique_name, 'red', r * 255.0) write_led_value(self.device_unique_name, 'green', g * 255.0) write_led_value(self.device_unique_name, 'blue', b * 255.0)
[ "def", "set_leds", "(", "self", ",", "hue", ":", "float", "=", "0.0", ",", "saturation", ":", "float", "=", "1.0", ",", "value", ":", "float", "=", "1.0", ")", ":", "r", ",", "g", ",", "b", "=", "hsv_to_rgb", "(", "hue", ",", "saturation", ",", ...
The DualShock4 has an LED bar on the front of the controller. This function allows you to set the value of this bar. Note that the controller must be connected for this to work, if it's not the call will just be ignored. :param hue: The hue of the colour, defaults to 0, specified as a floating point value between 0.0 and 1.0. :param saturation: Saturation of the colour, defaults to 1.0, specified as a floating point value between 0.0 and 1.0. :param value: Value of the colour (i.e. how bright the light is overall), defaults to 1.0, specified as a floating point value between 0.0 and 1.0
[ "The", "DualShock4", "has", "an", "LED", "bar", "on", "the", "front", "of", "the", "controller", ".", "This", "function", "allows", "you", "to", "set", "the", "value", "of", "this", "bar", ".", "Note", "that", "the", "controller", "must", "be", "connecte...
0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef
https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/dualshock4.py#L78-L94
train
42,975
TadLeonard/tfatool
tfatool/command.py
memory_changed
def memory_changed(url=URL): """Returns True if memory has been written to, False otherwise""" response = _get(Operation.memory_changed, url) try: return int(response.text) == 1 except ValueError: raise IOError("Likely no FlashAir connection, " "memory changed CGI command failed")
python
def memory_changed(url=URL): """Returns True if memory has been written to, False otherwise""" response = _get(Operation.memory_changed, url) try: return int(response.text) == 1 except ValueError: raise IOError("Likely no FlashAir connection, " "memory changed CGI command failed")
[ "def", "memory_changed", "(", "url", "=", "URL", ")", ":", "response", "=", "_get", "(", "Operation", ".", "memory_changed", ",", "url", ")", "try", ":", "return", "int", "(", "response", ".", "text", ")", "==", "1", "except", "ValueError", ":", "raise...
Returns True if memory has been written to, False otherwise
[ "Returns", "True", "if", "memory", "has", "been", "written", "to", "False", "otherwise" ]
12da2807b5fb538c5317ef255d846b32ceb174d0
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/command.py#L46-L53
train
42,976
TadLeonard/tfatool
tfatool/command.py
_get
def _get(operation: Operation, url=URL, **params): """HTTP GET of the FlashAir command.cgi entrypoint""" prepped_request = _prep_get(operation, url=url, **params) return cgi.send(prepped_request)
python
def _get(operation: Operation, url=URL, **params): """HTTP GET of the FlashAir command.cgi entrypoint""" prepped_request = _prep_get(operation, url=url, **params) return cgi.send(prepped_request)
[ "def", "_get", "(", "operation", ":", "Operation", ",", "url", "=", "URL", ",", "*", "*", "params", ")", ":", "prepped_request", "=", "_prep_get", "(", "operation", ",", "url", "=", "url", ",", "*", "*", "params", ")", "return", "cgi", ".", "send", ...
HTTP GET of the FlashAir command.cgi entrypoint
[ "HTTP", "GET", "of", "the", "FlashAir", "command", ".", "cgi", "entrypoint" ]
12da2807b5fb538c5317ef255d846b32ceb174d0
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/command.py#L147-L150
train
42,977
python-useful-helpers/threaded
threaded/_asynciotask.py
asynciotask
def asynciotask( # noqa: F811 func: typing.Optional[typing.Callable[..., "typing.Awaitable[typing.Any]"]] = None, *, loop_getter: typing.Union[ typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop ] = asyncio.get_event_loop, loop_getter_need_context: bool = False, ) -> typing.Union[AsyncIOTask, typing.Callable[..., "asyncio.Task[typing.Any]"]]: """Wrap function in future and return. :param func: Function to wrap :type func: typing.Optional[typing.Callable[..., typing.Awaitable]] :param loop_getter: Method to get event loop, if wrap in asyncio task :type loop_getter: typing.Union[ typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop ] :param loop_getter_need_context: Loop getter requires function context :type loop_getter_need_context: bool :return: AsyncIOTask instance, if called as function or argumented decorator, else callable wrapper :rtype: typing.Union[AsyncIOTask, typing.Callable[..., asyncio.Task]] """ if func is None: return AsyncIOTask(func=func, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context) return AsyncIOTask( # type: ignore func=None, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context )(func)
python
def asynciotask( # noqa: F811 func: typing.Optional[typing.Callable[..., "typing.Awaitable[typing.Any]"]] = None, *, loop_getter: typing.Union[ typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop ] = asyncio.get_event_loop, loop_getter_need_context: bool = False, ) -> typing.Union[AsyncIOTask, typing.Callable[..., "asyncio.Task[typing.Any]"]]: """Wrap function in future and return. :param func: Function to wrap :type func: typing.Optional[typing.Callable[..., typing.Awaitable]] :param loop_getter: Method to get event loop, if wrap in asyncio task :type loop_getter: typing.Union[ typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop ] :param loop_getter_need_context: Loop getter requires function context :type loop_getter_need_context: bool :return: AsyncIOTask instance, if called as function or argumented decorator, else callable wrapper :rtype: typing.Union[AsyncIOTask, typing.Callable[..., asyncio.Task]] """ if func is None: return AsyncIOTask(func=func, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context) return AsyncIOTask( # type: ignore func=None, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context )(func)
[ "def", "asynciotask", "(", "# noqa: F811", "func", ":", "typing", ".", "Optional", "[", "typing", ".", "Callable", "[", "...", ",", "\"typing.Awaitable[typing.Any]\"", "]", "]", "=", "None", ",", "*", ",", "loop_getter", ":", "typing", ".", "Union", "[", "...
Wrap function in future and return. :param func: Function to wrap :type func: typing.Optional[typing.Callable[..., typing.Awaitable]] :param loop_getter: Method to get event loop, if wrap in asyncio task :type loop_getter: typing.Union[ typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop ] :param loop_getter_need_context: Loop getter requires function context :type loop_getter_need_context: bool :return: AsyncIOTask instance, if called as function or argumented decorator, else callable wrapper :rtype: typing.Union[AsyncIOTask, typing.Callable[..., asyncio.Task]]
[ "Wrap", "function", "in", "future", "and", "return", "." ]
c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a
https://github.com/python-useful-helpers/threaded/blob/c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a/threaded/_asynciotask.py#L147-L173
train
42,978
python-useful-helpers/threaded
threaded/_threaded.py
threaded
def threaded( # noqa: F811 name: typing.Optional[typing.Union[str, typing.Callable[..., typing.Any]]] = None, daemon: bool = False, started: bool = False, ) -> typing.Union[Threaded, typing.Callable[..., threading.Thread]]: """Run function in separate thread. :param name: New thread name. If callable: use as wrapped function. If none: use wrapped function name. :type name: typing.Union[None, str, typing.Callable] :param daemon: Daemonize thread. :type daemon: bool :param started: Return started thread :type started: bool :return: Threaded instance, if called as function or argumented decorator, else callable wraper :rtype: typing.Union[Threaded, typing.Callable[..., threading.Thread]] """ if callable(name): func, name = (name, "Threaded: " + getattr(name, "__name__", str(hash(name)))) return Threaded(name=name, daemon=daemon, started=started)(func) # type: ignore return Threaded(name=name, daemon=daemon, started=started)
python
def threaded( # noqa: F811 name: typing.Optional[typing.Union[str, typing.Callable[..., typing.Any]]] = None, daemon: bool = False, started: bool = False, ) -> typing.Union[Threaded, typing.Callable[..., threading.Thread]]: """Run function in separate thread. :param name: New thread name. If callable: use as wrapped function. If none: use wrapped function name. :type name: typing.Union[None, str, typing.Callable] :param daemon: Daemonize thread. :type daemon: bool :param started: Return started thread :type started: bool :return: Threaded instance, if called as function or argumented decorator, else callable wraper :rtype: typing.Union[Threaded, typing.Callable[..., threading.Thread]] """ if callable(name): func, name = (name, "Threaded: " + getattr(name, "__name__", str(hash(name)))) return Threaded(name=name, daemon=daemon, started=started)(func) # type: ignore return Threaded(name=name, daemon=daemon, started=started)
[ "def", "threaded", "(", "# noqa: F811", "name", ":", "typing", ".", "Optional", "[", "typing", ".", "Union", "[", "str", ",", "typing", ".", "Callable", "[", "...", ",", "typing", ".", "Any", "]", "]", "]", "=", "None", ",", "daemon", ":", "bool", ...
Run function in separate thread. :param name: New thread name. If callable: use as wrapped function. If none: use wrapped function name. :type name: typing.Union[None, str, typing.Callable] :param daemon: Daemonize thread. :type daemon: bool :param started: Return started thread :type started: bool :return: Threaded instance, if called as function or argumented decorator, else callable wraper :rtype: typing.Union[Threaded, typing.Callable[..., threading.Thread]]
[ "Run", "function", "in", "separate", "thread", "." ]
c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a
https://github.com/python-useful-helpers/threaded/blob/c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a/threaded/_threaded.py#L142-L163
train
42,979
openid/JWTConnect-Python-OidcMsg
src/oidcmsg/time_util.py
before
def before(point): """ True if point datetime specification is before now """ if not point: return True if isinstance(point, str): point = str_to_time(point) elif isinstance(point, int): point = time.gmtime(point) return time.gmtime() < point
python
def before(point): """ True if point datetime specification is before now """ if not point: return True if isinstance(point, str): point = str_to_time(point) elif isinstance(point, int): point = time.gmtime(point) return time.gmtime() < point
[ "def", "before", "(", "point", ")", ":", "if", "not", "point", ":", "return", "True", "if", "isinstance", "(", "point", ",", "str", ")", ":", "point", "=", "str_to_time", "(", "point", ")", "elif", "isinstance", "(", "point", ",", "int", ")", ":", ...
True if point datetime specification is before now
[ "True", "if", "point", "datetime", "specification", "is", "before", "now" ]
58ade5eb67131abfb99f38b6a92d43b697c9f2fa
https://github.com/openid/JWTConnect-Python-OidcMsg/blob/58ade5eb67131abfb99f38b6a92d43b697c9f2fa/src/oidcmsg/time_util.py#L291-L301
train
42,980
openid/JWTConnect-Python-OidcMsg
src/oidcmsg/time_util.py
epoch_in_a_while
def epoch_in_a_while(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0): """ Return the number of seconds since epoch a while from now. :param days: :param seconds: :param microseconds: :param milliseconds: :param minutes: :param hours: :param weeks: :return: Seconds since epoch (1970-01-01) """ dt = time_in_a_while(days, seconds, microseconds, milliseconds, minutes, hours, weeks) return int((dt - datetime(1970, 1, 1)).total_seconds())
python
def epoch_in_a_while(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0): """ Return the number of seconds since epoch a while from now. :param days: :param seconds: :param microseconds: :param milliseconds: :param minutes: :param hours: :param weeks: :return: Seconds since epoch (1970-01-01) """ dt = time_in_a_while(days, seconds, microseconds, milliseconds, minutes, hours, weeks) return int((dt - datetime(1970, 1, 1)).total_seconds())
[ "def", "epoch_in_a_while", "(", "days", "=", "0", ",", "seconds", "=", "0", ",", "microseconds", "=", "0", ",", "milliseconds", "=", "0", ",", "minutes", "=", "0", ",", "hours", "=", "0", ",", "weeks", "=", "0", ")", ":", "dt", "=", "time_in_a_whil...
Return the number of seconds since epoch a while from now. :param days: :param seconds: :param microseconds: :param milliseconds: :param minutes: :param hours: :param weeks: :return: Seconds since epoch (1970-01-01)
[ "Return", "the", "number", "of", "seconds", "since", "epoch", "a", "while", "from", "now", "." ]
58ade5eb67131abfb99f38b6a92d43b697c9f2fa
https://github.com/openid/JWTConnect-Python-OidcMsg/blob/58ade5eb67131abfb99f38b6a92d43b697c9f2fa/src/oidcmsg/time_util.py#L345-L362
train
42,981
openid/JWTConnect-Python-OidcMsg
src/oidcmsg/message.py
Message.set_defaults
def set_defaults(self): """ Based on specification set a parameters value to the default value. """ for key, val in self.c_default.items(): self._dict[key] = val
python
def set_defaults(self): """ Based on specification set a parameters value to the default value. """ for key, val in self.c_default.items(): self._dict[key] = val
[ "def", "set_defaults", "(", "self", ")", ":", "for", "key", ",", "val", "in", "self", ".", "c_default", ".", "items", "(", ")", ":", "self", ".", "_dict", "[", "key", "]", "=", "val" ]
Based on specification set a parameters value to the default value.
[ "Based", "on", "specification", "set", "a", "parameters", "value", "to", "the", "default", "value", "." ]
58ade5eb67131abfb99f38b6a92d43b697c9f2fa
https://github.com/openid/JWTConnect-Python-OidcMsg/blob/58ade5eb67131abfb99f38b6a92d43b697c9f2fa/src/oidcmsg/message.py#L72-L77
train
42,982
openid/JWTConnect-Python-OidcMsg
src/oidcmsg/message.py
Message.to_dict
def to_dict(self, lev=0): """ Return a dictionary representation of the class :return: A dict """ _spec = self.c_param _res = {} lev += 1 for key, val in self._dict.items(): try: (_, req, _ser, _, null_allowed) = _spec[str(key)] except KeyError: try: _key, lang = key.split("#") (_, req, _ser, _, null_allowed) = _spec[_key] except (ValueError, KeyError): try: (_, req, _ser, _, null_allowed) = _spec['*'] except KeyError: _ser = None if _ser: val = _ser(val, "dict", lev) if isinstance(val, Message): _res[key] = val.to_dict(lev + 1) elif isinstance(val, list) and isinstance( next(iter(val or []), None), Message): _res[key] = [v.to_dict(lev) for v in val] else: _res[key] = val return _res
python
def to_dict(self, lev=0): """ Return a dictionary representation of the class :return: A dict """ _spec = self.c_param _res = {} lev += 1 for key, val in self._dict.items(): try: (_, req, _ser, _, null_allowed) = _spec[str(key)] except KeyError: try: _key, lang = key.split("#") (_, req, _ser, _, null_allowed) = _spec[_key] except (ValueError, KeyError): try: (_, req, _ser, _, null_allowed) = _spec['*'] except KeyError: _ser = None if _ser: val = _ser(val, "dict", lev) if isinstance(val, Message): _res[key] = val.to_dict(lev + 1) elif isinstance(val, list) and isinstance( next(iter(val or []), None), Message): _res[key] = [v.to_dict(lev) for v in val] else: _res[key] = val return _res
[ "def", "to_dict", "(", "self", ",", "lev", "=", "0", ")", ":", "_spec", "=", "self", ".", "c_param", "_res", "=", "{", "}", "lev", "+=", "1", "for", "key", ",", "val", "in", "self", ".", "_dict", ".", "items", "(", ")", ":", "try", ":", "(", ...
Return a dictionary representation of the class :return: A dict
[ "Return", "a", "dictionary", "representation", "of", "the", "class" ]
58ade5eb67131abfb99f38b6a92d43b697c9f2fa
https://github.com/openid/JWTConnect-Python-OidcMsg/blob/58ade5eb67131abfb99f38b6a92d43b697c9f2fa/src/oidcmsg/message.py#L234-L269
train
42,983
openid/JWTConnect-Python-OidcMsg
src/oidcmsg/message.py
Message.from_dict
def from_dict(self, dictionary, **kwargs): """ Direct translation, so the value for one key might be a list or a single value. :param dictionary: The info :return: A class instance or raise an exception on error """ _spec = self.c_param for key, val in dictionary.items(): # Earlier versions of python don't like unicode strings as # variable names if val == "" or val == [""]: continue skey = str(key) try: (vtyp, req, _, _deser, null_allowed) = _spec[key] except KeyError: # might be a parameter with a lang tag try: _key, lang = skey.split("#") except ValueError: try: (vtyp, _, _, _deser, null_allowed) = _spec['*'] if val is None: self._dict[key] = val continue except KeyError: self._dict[key] = val continue else: try: (vtyp, req, _, _deser, null_allowed) = _spec[_key] except KeyError: try: (vtyp, _, _, _deser, null_allowed) = _spec['*'] if val is None: self._dict[key] = val continue except KeyError: self._dict[key] = val continue self._add_value(skey, vtyp, key, val, _deser, null_allowed) return self
python
def from_dict(self, dictionary, **kwargs): """ Direct translation, so the value for one key might be a list or a single value. :param dictionary: The info :return: A class instance or raise an exception on error """ _spec = self.c_param for key, val in dictionary.items(): # Earlier versions of python don't like unicode strings as # variable names if val == "" or val == [""]: continue skey = str(key) try: (vtyp, req, _, _deser, null_allowed) = _spec[key] except KeyError: # might be a parameter with a lang tag try: _key, lang = skey.split("#") except ValueError: try: (vtyp, _, _, _deser, null_allowed) = _spec['*'] if val is None: self._dict[key] = val continue except KeyError: self._dict[key] = val continue else: try: (vtyp, req, _, _deser, null_allowed) = _spec[_key] except KeyError: try: (vtyp, _, _, _deser, null_allowed) = _spec['*'] if val is None: self._dict[key] = val continue except KeyError: self._dict[key] = val continue self._add_value(skey, vtyp, key, val, _deser, null_allowed) return self
[ "def", "from_dict", "(", "self", ",", "dictionary", ",", "*", "*", "kwargs", ")", ":", "_spec", "=", "self", ".", "c_param", "for", "key", ",", "val", "in", "dictionary", ".", "items", "(", ")", ":", "# Earlier versions of python don't like unicode strings as"...
Direct translation, so the value for one key might be a list or a single value. :param dictionary: The info :return: A class instance or raise an exception on error
[ "Direct", "translation", "so", "the", "value", "for", "one", "key", "might", "be", "a", "list", "or", "a", "single", "value", "." ]
58ade5eb67131abfb99f38b6a92d43b697c9f2fa
https://github.com/openid/JWTConnect-Python-OidcMsg/blob/58ade5eb67131abfb99f38b6a92d43b697c9f2fa/src/oidcmsg/message.py#L271-L318
train
42,984
openid/JWTConnect-Python-OidcMsg
src/oidcmsg/message.py
Message.to_jwt
def to_jwt(self, key=None, algorithm="", lev=0, lifetime=0): """ Create a signed JWT representation of the class instance :param key: The signing key :param algorithm: The signature algorithm to use :param lev: :param lifetime: The lifetime of the JWS :return: A signed JWT """ _jws = JWS(self.to_json(lev), alg=algorithm) return _jws.sign_compact(key)
python
def to_jwt(self, key=None, algorithm="", lev=0, lifetime=0): """ Create a signed JWT representation of the class instance :param key: The signing key :param algorithm: The signature algorithm to use :param lev: :param lifetime: The lifetime of the JWS :return: A signed JWT """ _jws = JWS(self.to_json(lev), alg=algorithm) return _jws.sign_compact(key)
[ "def", "to_jwt", "(", "self", ",", "key", "=", "None", ",", "algorithm", "=", "\"\"", ",", "lev", "=", "0", ",", "lifetime", "=", "0", ")", ":", "_jws", "=", "JWS", "(", "self", ".", "to_json", "(", "lev", ")", ",", "alg", "=", "algorithm", ")"...
Create a signed JWT representation of the class instance :param key: The signing key :param algorithm: The signature algorithm to use :param lev: :param lifetime: The lifetime of the JWS :return: A signed JWT
[ "Create", "a", "signed", "JWT", "representation", "of", "the", "class", "instance" ]
58ade5eb67131abfb99f38b6a92d43b697c9f2fa
https://github.com/openid/JWTConnect-Python-OidcMsg/blob/58ade5eb67131abfb99f38b6a92d43b697c9f2fa/src/oidcmsg/message.py#L462-L474
train
42,985
openid/JWTConnect-Python-OidcMsg
src/oidcmsg/message.py
Message.verify
def verify(self, **kwargs): """ Make sure all the required values are there and that the values are of the correct type """ _spec = self.c_param try: _allowed = self.c_allowed_values except KeyError: _allowed = {} for (attribute, (typ, required, _, _, na)) in _spec.items(): if attribute == "*": continue try: val = self._dict[attribute] except KeyError: if required: raise MissingRequiredAttribute("%s" % attribute) continue else: if typ == bool: pass elif not val: if required: raise MissingRequiredAttribute("%s" % attribute) continue try: _allowed_val = _allowed[attribute] except KeyError: pass else: if not self._type_check(typ, _allowed_val, val, na): raise NotAllowedValue(val) return True
python
def verify(self, **kwargs): """ Make sure all the required values are there and that the values are of the correct type """ _spec = self.c_param try: _allowed = self.c_allowed_values except KeyError: _allowed = {} for (attribute, (typ, required, _, _, na)) in _spec.items(): if attribute == "*": continue try: val = self._dict[attribute] except KeyError: if required: raise MissingRequiredAttribute("%s" % attribute) continue else: if typ == bool: pass elif not val: if required: raise MissingRequiredAttribute("%s" % attribute) continue try: _allowed_val = _allowed[attribute] except KeyError: pass else: if not self._type_check(typ, _allowed_val, val, na): raise NotAllowedValue(val) return True
[ "def", "verify", "(", "self", ",", "*", "*", "kwargs", ")", ":", "_spec", "=", "self", ".", "c_param", "try", ":", "_allowed", "=", "self", ".", "c_allowed_values", "except", "KeyError", ":", "_allowed", "=", "{", "}", "for", "(", "attribute", ",", "...
Make sure all the required values are there and that the values are of the correct type
[ "Make", "sure", "all", "the", "required", "values", "are", "there", "and", "that", "the", "values", "are", "of", "the", "correct", "type" ]
58ade5eb67131abfb99f38b6a92d43b697c9f2fa
https://github.com/openid/JWTConnect-Python-OidcMsg/blob/58ade5eb67131abfb99f38b6a92d43b697c9f2fa/src/oidcmsg/message.py#L585-L622
train
42,986
openid/JWTConnect-Python-OidcMsg
src/oidcmsg/message.py
Message.to_jwe
def to_jwe(self, keys, enc, alg, lev=0): """ Place the information in this instance in a JSON object. Make that JSON object the body of a JWT. Then encrypt that JWT using the specified algorithms and the given keys. Return the encrypted JWT. :param keys: list or KeyJar instance :param enc: Content Encryption Algorithm :param alg: Key Management Algorithm :param lev: Used for JSON construction :return: An encrypted JWT. If encryption failed an exception will be raised. """ _jwe = JWE(self.to_json(lev), alg=alg, enc=enc) return _jwe.encrypt(keys)
python
def to_jwe(self, keys, enc, alg, lev=0): """ Place the information in this instance in a JSON object. Make that JSON object the body of a JWT. Then encrypt that JWT using the specified algorithms and the given keys. Return the encrypted JWT. :param keys: list or KeyJar instance :param enc: Content Encryption Algorithm :param alg: Key Management Algorithm :param lev: Used for JSON construction :return: An encrypted JWT. If encryption failed an exception will be raised. """ _jwe = JWE(self.to_json(lev), alg=alg, enc=enc) return _jwe.encrypt(keys)
[ "def", "to_jwe", "(", "self", ",", "keys", ",", "enc", ",", "alg", ",", "lev", "=", "0", ")", ":", "_jwe", "=", "JWE", "(", "self", ".", "to_json", "(", "lev", ")", ",", "alg", "=", "alg", ",", "enc", "=", "enc", ")", "return", "_jwe", ".", ...
Place the information in this instance in a JSON object. Make that JSON object the body of a JWT. Then encrypt that JWT using the specified algorithms and the given keys. Return the encrypted JWT. :param keys: list or KeyJar instance :param enc: Content Encryption Algorithm :param alg: Key Management Algorithm :param lev: Used for JSON construction :return: An encrypted JWT. If encryption failed an exception will be raised.
[ "Place", "the", "information", "in", "this", "instance", "in", "a", "JSON", "object", ".", "Make", "that", "JSON", "object", "the", "body", "of", "a", "JWT", ".", "Then", "encrypt", "that", "JWT", "using", "the", "specified", "algorithms", "and", "the", ...
58ade5eb67131abfb99f38b6a92d43b697c9f2fa
https://github.com/openid/JWTConnect-Python-OidcMsg/blob/58ade5eb67131abfb99f38b6a92d43b697c9f2fa/src/oidcmsg/message.py#L774-L789
train
42,987
openid/JWTConnect-Python-OidcMsg
src/oidcmsg/message.py
Message.from_jwe
def from_jwe(self, msg, keys): """ Decrypt an encrypted JWT and load the JSON object that was the body of the JWT into this object. :param msg: An encrypted JWT :param keys: Possibly usable keys. :type keys: list or KeyJar instance :return: The decrypted message. If decryption failed an exception will be raised. """ jwe = JWE() _res = jwe.decrypt(msg, keys) return self.from_json(_res.decode())
python
def from_jwe(self, msg, keys): """ Decrypt an encrypted JWT and load the JSON object that was the body of the JWT into this object. :param msg: An encrypted JWT :param keys: Possibly usable keys. :type keys: list or KeyJar instance :return: The decrypted message. If decryption failed an exception will be raised. """ jwe = JWE() _res = jwe.decrypt(msg, keys) return self.from_json(_res.decode())
[ "def", "from_jwe", "(", "self", ",", "msg", ",", "keys", ")", ":", "jwe", "=", "JWE", "(", ")", "_res", "=", "jwe", ".", "decrypt", "(", "msg", ",", "keys", ")", "return", "self", ".", "from_json", "(", "_res", ".", "decode", "(", ")", ")" ]
Decrypt an encrypted JWT and load the JSON object that was the body of the JWT into this object. :param msg: An encrypted JWT :param keys: Possibly usable keys. :type keys: list or KeyJar instance :return: The decrypted message. If decryption failed an exception will be raised.
[ "Decrypt", "an", "encrypted", "JWT", "and", "load", "the", "JSON", "object", "that", "was", "the", "body", "of", "the", "JWT", "into", "this", "object", "." ]
58ade5eb67131abfb99f38b6a92d43b697c9f2fa
https://github.com/openid/JWTConnect-Python-OidcMsg/blob/58ade5eb67131abfb99f38b6a92d43b697c9f2fa/src/oidcmsg/message.py#L791-L805
train
42,988
openid/JWTConnect-Python-OidcMsg
src/oidcmsg/message.py
Message.weed
def weed(self): """ Get rid of key value pairs that are not standard """ _ext = [k for k in self._dict.keys() if k not in self.c_param] for k in _ext: del self._dict[k]
python
def weed(self): """ Get rid of key value pairs that are not standard """ _ext = [k for k in self._dict.keys() if k not in self.c_param] for k in _ext: del self._dict[k]
[ "def", "weed", "(", "self", ")", ":", "_ext", "=", "[", "k", "for", "k", "in", "self", ".", "_dict", ".", "keys", "(", ")", "if", "k", "not", "in", "self", ".", "c_param", "]", "for", "k", "in", "_ext", ":", "del", "self", ".", "_dict", "[", ...
Get rid of key value pairs that are not standard
[ "Get", "rid", "of", "key", "value", "pairs", "that", "are", "not", "standard" ]
58ade5eb67131abfb99f38b6a92d43b697c9f2fa
https://github.com/openid/JWTConnect-Python-OidcMsg/blob/58ade5eb67131abfb99f38b6a92d43b697c9f2fa/src/oidcmsg/message.py#L810-L816
train
42,989
openid/JWTConnect-Python-OidcMsg
src/oidcmsg/message.py
Message.rm_blanks
def rm_blanks(self): """ Get rid of parameters that has no value. """ _blanks = [k for k in self._dict.keys() if not self._dict[k]] for key in _blanks: del self._dict[key]
python
def rm_blanks(self): """ Get rid of parameters that has no value. """ _blanks = [k for k in self._dict.keys() if not self._dict[k]] for key in _blanks: del self._dict[key]
[ "def", "rm_blanks", "(", "self", ")", ":", "_blanks", "=", "[", "k", "for", "k", "in", "self", ".", "_dict", ".", "keys", "(", ")", "if", "not", "self", ".", "_dict", "[", "k", "]", "]", "for", "key", "in", "_blanks", ":", "del", "self", ".", ...
Get rid of parameters that has no value.
[ "Get", "rid", "of", "parameters", "that", "has", "no", "value", "." ]
58ade5eb67131abfb99f38b6a92d43b697c9f2fa
https://github.com/openid/JWTConnect-Python-OidcMsg/blob/58ade5eb67131abfb99f38b6a92d43b697c9f2fa/src/oidcmsg/message.py#L818-L824
train
42,990
noirbizarre/bumpr
bumpr/log.py
ansi
def ansi(color, text): """Wrap text in an ansi escape sequence""" code = COLOR_CODES[color] return '\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)
python
def ansi(color, text): """Wrap text in an ansi escape sequence""" code = COLOR_CODES[color] return '\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)
[ "def", "ansi", "(", "color", ",", "text", ")", ":", "code", "=", "COLOR_CODES", "[", "color", "]", "return", "'\\033[1;{0}m{1}{2}'", ".", "format", "(", "code", ",", "text", ",", "RESET_TERM", ")" ]
Wrap text in an ansi escape sequence
[ "Wrap", "text", "in", "an", "ansi", "escape", "sequence" ]
221dbb3deaf1cae7922f6a477f3d29d6bf0c0035
https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/bumpr/log.py#L39-L42
train
42,991
abilian/abilian-core
abilian/services/security/service.py
require_flush
def require_flush(fun): """Decorator for methods that need to query security. It ensures all security related operations are flushed to DB, but avoids unneeded flushes. """ @wraps(fun) def ensure_flushed(service, *args, **kwargs): if service.app_state.needs_db_flush: session = db.session() if not session._flushing and any( isinstance(m, (RoleAssignment, SecurityAudit)) for models in (session.new, session.dirty, session.deleted) for m in models ): session.flush() service.app_state.needs_db_flush = False return fun(service, *args, **kwargs) return ensure_flushed
python
def require_flush(fun): """Decorator for methods that need to query security. It ensures all security related operations are flushed to DB, but avoids unneeded flushes. """ @wraps(fun) def ensure_flushed(service, *args, **kwargs): if service.app_state.needs_db_flush: session = db.session() if not session._flushing and any( isinstance(m, (RoleAssignment, SecurityAudit)) for models in (session.new, session.dirty, session.deleted) for m in models ): session.flush() service.app_state.needs_db_flush = False return fun(service, *args, **kwargs) return ensure_flushed
[ "def", "require_flush", "(", "fun", ")", ":", "@", "wraps", "(", "fun", ")", "def", "ensure_flushed", "(", "service", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "service", ".", "app_state", ".", "needs_db_flush", ":", "session", "=", ...
Decorator for methods that need to query security. It ensures all security related operations are flushed to DB, but avoids unneeded flushes.
[ "Decorator", "for", "methods", "that", "need", "to", "query", "security", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/security/service.py#L57-L78
train
42,992
abilian/abilian-core
abilian/services/security/service.py
SecurityService._current_user_manager
def _current_user_manager(self, session=None): """Return the current user, or SYSTEM user.""" if session is None: session = db.session() try: user = g.user except Exception: return session.query(User).get(0) if sa.orm.object_session(user) is not session: # this can happen when called from a celery task during development # (with CELERY_ALWAYS_EAGER=True): the task SA session is not # app.db.session, and we should not attach this object to # the other session, because it can make weird, hard-to-debug # errors related to session.identity_map. return session.query(User).get(user.id) else: return user
python
def _current_user_manager(self, session=None): """Return the current user, or SYSTEM user.""" if session is None: session = db.session() try: user = g.user except Exception: return session.query(User).get(0) if sa.orm.object_session(user) is not session: # this can happen when called from a celery task during development # (with CELERY_ALWAYS_EAGER=True): the task SA session is not # app.db.session, and we should not attach this object to # the other session, because it can make weird, hard-to-debug # errors related to session.identity_map. return session.query(User).get(user.id) else: return user
[ "def", "_current_user_manager", "(", "self", ",", "session", "=", "None", ")", ":", "if", "session", "is", "None", ":", "session", "=", "db", ".", "session", "(", ")", "try", ":", "user", "=", "g", ".", "user", "except", "Exception", ":", "return", "...
Return the current user, or SYSTEM user.
[ "Return", "the", "current", "user", "or", "SYSTEM", "user", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/security/service.py#L150-L168
train
42,993
abilian/abilian-core
abilian/services/security/service.py
SecurityService.get_roles
def get_roles(self, principal, object=None, no_group_roles=False): """Get all the roles attached to given `principal`, on a given `object`. :param principal: a :class:`User` or :class:`Group` :param object: an :class:`Entity` :param no_group_roles: If `True`, return only direct roles, not roles acquired through group membership. """ assert principal if hasattr(principal, "is_anonymous") and principal.is_anonymous: return [AnonymousRole] query = db.session.query(RoleAssignment.role) if isinstance(principal, Group): filter_principal = RoleAssignment.group == principal else: filter_principal = RoleAssignment.user == principal if not no_group_roles: groups = [g.id for g in principal.groups] if groups: filter_principal |= RoleAssignment.group_id.in_(groups) query = query.filter(filter_principal) if object is not None: assert isinstance(object, Entity) query = query.filter(RoleAssignment.object == object) roles = {i[0] for i in query.all()} if object is not None: for attr, role in (("creator", Creator), ("owner", Owner)): if getattr(object, attr) == principal: roles.add(role) return list(roles)
python
def get_roles(self, principal, object=None, no_group_roles=False): """Get all the roles attached to given `principal`, on a given `object`. :param principal: a :class:`User` or :class:`Group` :param object: an :class:`Entity` :param no_group_roles: If `True`, return only direct roles, not roles acquired through group membership. """ assert principal if hasattr(principal, "is_anonymous") and principal.is_anonymous: return [AnonymousRole] query = db.session.query(RoleAssignment.role) if isinstance(principal, Group): filter_principal = RoleAssignment.group == principal else: filter_principal = RoleAssignment.user == principal if not no_group_roles: groups = [g.id for g in principal.groups] if groups: filter_principal |= RoleAssignment.group_id.in_(groups) query = query.filter(filter_principal) if object is not None: assert isinstance(object, Entity) query = query.filter(RoleAssignment.object == object) roles = {i[0] for i in query.all()} if object is not None: for attr, role in (("creator", Creator), ("owner", Owner)): if getattr(object, attr) == principal: roles.add(role) return list(roles)
[ "def", "get_roles", "(", "self", ",", "principal", ",", "object", "=", "None", ",", "no_group_roles", "=", "False", ")", ":", "assert", "principal", "if", "hasattr", "(", "principal", ",", "\"is_anonymous\"", ")", "and", "principal", ".", "is_anonymous", ":"...
Get all the roles attached to given `principal`, on a given `object`. :param principal: a :class:`User` or :class:`Group` :param object: an :class:`Entity` :param no_group_roles: If `True`, return only direct roles, not roles acquired through group membership.
[ "Get", "all", "the", "roles", "attached", "to", "given", "principal", "on", "a", "given", "object", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/security/service.py#L210-L247
train
42,994
abilian/abilian-core
abilian/services/security/service.py
SecurityService.get_principals
def get_principals( self, role, anonymous=True, users=True, groups=True, object=None, as_list=True ): """Return all users which are assigned given role.""" if not isinstance(role, Role): role = Role(role) assert role assert users or groups query = RoleAssignment.query.filter_by(role=role) if not anonymous: query = query.filter(RoleAssignment.anonymous == False) if not users: query = query.filter(RoleAssignment.user == None) elif not groups: query = query.filter(RoleAssignment.group == None) query = query.filter(RoleAssignment.object == object) principals = {(ra.user or ra.group) for ra in query.all()} if object is not None and role in (Creator, Owner): p = object.creator if role == Creator else object.owner if p: principals.add(p) if not as_list: return principals return list(principals)
python
def get_principals( self, role, anonymous=True, users=True, groups=True, object=None, as_list=True ): """Return all users which are assigned given role.""" if not isinstance(role, Role): role = Role(role) assert role assert users or groups query = RoleAssignment.query.filter_by(role=role) if not anonymous: query = query.filter(RoleAssignment.anonymous == False) if not users: query = query.filter(RoleAssignment.user == None) elif not groups: query = query.filter(RoleAssignment.group == None) query = query.filter(RoleAssignment.object == object) principals = {(ra.user or ra.group) for ra in query.all()} if object is not None and role in (Creator, Owner): p = object.creator if role == Creator else object.owner if p: principals.add(p) if not as_list: return principals return list(principals)
[ "def", "get_principals", "(", "self", ",", "role", ",", "anonymous", "=", "True", ",", "users", "=", "True", ",", "groups", "=", "True", ",", "object", "=", "None", ",", "as_list", "=", "True", ")", ":", "if", "not", "isinstance", "(", "role", ",", ...
Return all users which are assigned given role.
[ "Return", "all", "users", "which", "are", "assigned", "given", "role", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/security/service.py#L250-L278
train
42,995
abilian/abilian-core
abilian/web/assets/mixin.py
AssetManagerMixin.register_asset
def register_asset(self, type_, *assets): """Register webassets bundle to be served on all pages. :param type_: `"css"`, `"js-top"` or `"js""`. :param assets: a path to file, a :ref:`webassets.Bundle <webassets:bundles>` instance or a callable that returns a :ref:`webassets.Bundle <webassets:bundles>` instance. :raises KeyError: if `type_` is not supported. """ supported = list(self._assets_bundles.keys()) if type_ not in supported: msg = "Invalid type: {}. Valid types: {}".format( repr(type_), ", ".join(sorted(supported)) ) raise KeyError(msg) for asset in assets: if not isinstance(asset, Bundle) and callable(asset): asset = asset() self._assets_bundles[type_].setdefault("bundles", []).append(asset)
python
def register_asset(self, type_, *assets): """Register webassets bundle to be served on all pages. :param type_: `"css"`, `"js-top"` or `"js""`. :param assets: a path to file, a :ref:`webassets.Bundle <webassets:bundles>` instance or a callable that returns a :ref:`webassets.Bundle <webassets:bundles>` instance. :raises KeyError: if `type_` is not supported. """ supported = list(self._assets_bundles.keys()) if type_ not in supported: msg = "Invalid type: {}. Valid types: {}".format( repr(type_), ", ".join(sorted(supported)) ) raise KeyError(msg) for asset in assets: if not isinstance(asset, Bundle) and callable(asset): asset = asset() self._assets_bundles[type_].setdefault("bundles", []).append(asset)
[ "def", "register_asset", "(", "self", ",", "type_", ",", "*", "assets", ")", ":", "supported", "=", "list", "(", "self", ".", "_assets_bundles", ".", "keys", "(", ")", ")", "if", "type_", "not", "in", "supported", ":", "msg", "=", "\"Invalid type: {}. Va...
Register webassets bundle to be served on all pages. :param type_: `"css"`, `"js-top"` or `"js""`. :param assets: a path to file, a :ref:`webassets.Bundle <webassets:bundles>` instance or a callable that returns a :ref:`webassets.Bundle <webassets:bundles>` instance. :raises KeyError: if `type_` is not supported.
[ "Register", "webassets", "bundle", "to", "be", "served", "on", "all", "pages", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/assets/mixin.py#L115-L138
train
42,996
abilian/abilian-core
abilian/web/assets/mixin.py
AssetManagerMixin.register_base_assets
def register_base_assets(self): """Register assets needed by Abilian. This is done in a separate method in order to allow applications to redefine it at will. """ from abilian.web import assets as bundles self.register_asset("css", bundles.LESS) self.register_asset("js-top", bundles.TOP_JS) self.register_asset("js", bundles.JS) self.register_i18n_js(*bundles.JS_I18N)
python
def register_base_assets(self): """Register assets needed by Abilian. This is done in a separate method in order to allow applications to redefine it at will. """ from abilian.web import assets as bundles self.register_asset("css", bundles.LESS) self.register_asset("js-top", bundles.TOP_JS) self.register_asset("js", bundles.JS) self.register_i18n_js(*bundles.JS_I18N)
[ "def", "register_base_assets", "(", "self", ")", ":", "from", "abilian", ".", "web", "import", "assets", "as", "bundles", "self", ".", "register_asset", "(", "\"css\"", ",", "bundles", ".", "LESS", ")", "self", ".", "register_asset", "(", "\"js-top\"", ",", ...
Register assets needed by Abilian. This is done in a separate method in order to allow applications to redefine it at will.
[ "Register", "assets", "needed", "by", "Abilian", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/assets/mixin.py#L160-L171
train
42,997
abilian/abilian-core
abilian/web/views/images.py
user_photo_url
def user_photo_url(user, size): """Return url to use for this user.""" endpoint, kwargs = user_url_args(user, size) return url_for(endpoint, **kwargs)
python
def user_photo_url(user, size): """Return url to use for this user.""" endpoint, kwargs = user_url_args(user, size) return url_for(endpoint, **kwargs)
[ "def", "user_photo_url", "(", "user", ",", "size", ")", ":", "endpoint", ",", "kwargs", "=", "user_url_args", "(", "user", ",", "size", ")", "return", "url_for", "(", "endpoint", ",", "*", "*", "kwargs", ")" ]
Return url to use for this user.
[ "Return", "url", "to", "use", "for", "this", "user", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/views/images.py#L224-L227
train
42,998
abilian/abilian-core
abilian/web/admin/panels/dashboard.py
newlogins
def newlogins(sessions): """Brand new logins each day, and total of users each day. :return: data, total 2 lists of dictionaries of the following format [{'x':epoch, 'y': value},] """ if not sessions: return [], [] users = {} dates = {} for session in sessions: user = session.user # time value is discarded to aggregate on days only date = session.started_at.strftime("%Y/%m/%d") # keep the info only it's the first time we encounter a user if user not in users: users[user] = date # build the list of users on a given day if date not in dates: dates[date] = [user] else: dates[date].append(user) data = [] total = [] previous = 0 for date in sorted(dates.keys()): # print u"{} : {}".format(date, len(dates[date])) date_epoch = unix_time_millis(datetime.strptime(date, "%Y/%m/%d")) data.append({"x": date_epoch, "y": len(dates[date])}) previous += len(dates[date]) total.append({"x": date_epoch, "y": previous}) return data, total
python
def newlogins(sessions): """Brand new logins each day, and total of users each day. :return: data, total 2 lists of dictionaries of the following format [{'x':epoch, 'y': value},] """ if not sessions: return [], [] users = {} dates = {} for session in sessions: user = session.user # time value is discarded to aggregate on days only date = session.started_at.strftime("%Y/%m/%d") # keep the info only it's the first time we encounter a user if user not in users: users[user] = date # build the list of users on a given day if date not in dates: dates[date] = [user] else: dates[date].append(user) data = [] total = [] previous = 0 for date in sorted(dates.keys()): # print u"{} : {}".format(date, len(dates[date])) date_epoch = unix_time_millis(datetime.strptime(date, "%Y/%m/%d")) data.append({"x": date_epoch, "y": len(dates[date])}) previous += len(dates[date]) total.append({"x": date_epoch, "y": previous}) return data, total
[ "def", "newlogins", "(", "sessions", ")", ":", "if", "not", "sessions", ":", "return", "[", "]", ",", "[", "]", "users", "=", "{", "}", "dates", "=", "{", "}", "for", "session", "in", "sessions", ":", "user", "=", "session", ".", "user", "# time va...
Brand new logins each day, and total of users each day. :return: data, total 2 lists of dictionaries of the following format [{'x':epoch, 'y': value},]
[ "Brand", "new", "logins", "each", "day", "and", "total", "of", "users", "each", "day", "." ]
0a71275bf108c3d51e13ca9e093c0249235351e3
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/admin/panels/dashboard.py#L111-L145
train
42,999