repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
cnelson/python-fleet | fleet/v1/objects/unit.py | Unit.destroy | python | def destroy(self):
# if this unit didn't come from fleet, we can't destroy it
if not self._is_live():
raise RuntimeError('A unit must be submitted to fleet before it can destroyed.')
return self._client.destroy_unit(self.name) | Remove a unit from the fleet cluster
Returns:
True: The unit was removed
Raises:
fleet.v1.errors.APIError: Fleet returned a response code >= 400 | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/objects/unit.py#L304-L319 | [
"def _is_live(self):\n \"\"\"Checks to see if this unit came from fleet, or was created locally\n\n Only units with a .name property (set by the server), and _client property are considered 'live'\n\n Returns:\n True: The object is live\n False: The object is not\n\n \"\"\"\n if 'name' ... | class Unit(FleetObject):
"""This object represents a Unit in Fleet
Create and modify Unit entities to communicate to fleet the desired state of the cluster.
This simply declares what should be happening; the backend system still has to react to the changes in
this desired state. The actual state of the... |
cnelson/python-fleet | fleet/v1/objects/unit.py | Unit.set_desired_state | python | def set_desired_state(self, state):
if state not in self._STATES:
raise ValueError(
'state must be one of: {0}'.format(
self._STATES
))
# update our internal structure
self._data['desiredState'] = state
# if we have a name... | Update the desired state of a unit.
Args:
state (str): The desired state for the unit, must be one of ``_STATES``
Returns:
str: The updated state
Raises:
fleet.v1.errors.APIError: Fleet returned a response code >= 400
ValueError: An invalid val... | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/objects/unit.py#L321-L350 | [
"def _is_live(self):\n \"\"\"Checks to see if this unit came from fleet, or was created locally\n\n Only units with a .name property (set by the server), and _client property are considered 'live'\n\n Returns:\n True: The object is live\n False: The object is not\n\n \"\"\"\n if 'name' ... | class Unit(FleetObject):
"""This object represents a Unit in Fleet
Create and modify Unit entities to communicate to fleet the desired state of the cluster.
This simply declares what should be happening; the backend system still has to react to the changes in
this desired state. The actual state of the... |
cnelson/python-fleet | fleet/v1/client.py | SSHTunnel.forward_tcp | python | def forward_tcp(self, host, port):
return self.transport.open_channel(
'direct-tcpip',
(host, port),
self.transport.getpeername()
) | Open a connection to host:port via an ssh tunnel.
Args:
host (str): The host to connect to.
port (int): The port to connect to.
Returns:
A socket-like object that is connected to the provided host:port. | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/client.py#L97-L113 | null | class SSHTunnel(object):
"""Use paramiko to setup local "ssh -L" tunnels for Client to use"""
def __init__(
self,
host,
username=None,
port=22,
timeout=10,
known_hosts_file=None,
strict_host_key_checking=True
):
"""Connect to the SSH server, a... |
cnelson/python-fleet | fleet/v1/client.py | Client._split_hostport | python | def _split_hostport(self, hostport, default_port=None):
try:
(host, port) = hostport.split(':', 1)
except ValueError: # no colon in the string so make our own port
host = hostport
if default_port is None:
raise ValueError('No port found in hostport,... | Split a string in the format of '<host>:<port>' into it's component parts
default_port will be used if a port is not included in the string
Args:
str ('<host>' or '<host>:<port>'): A string to split into it's parts
Returns:
two item tuple: (host, port)
Raises:... | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/client.py#L296-L328 | null | class Client(object):
"""A python wrapper for the fleet v1 API
The fleet v1 API is documented here: https://github.com/coreos/fleet/blob/master/Documentation/api-v1.md
"""
_API = 'fleet'
_VERSION = 'v1'
_STATES = ['inactive', 'loaded', 'launched']
def __init__(
self,
endpo... |
cnelson/python-fleet | fleet/v1/client.py | Client._endpoint_to_target | python | def _endpoint_to_target(self, endpoint):
parsed = urlparse.urlparse(endpoint)
scheme = parsed[0]
hostport = parsed[1]
if 'unix' in scheme:
return (None, None, unquote(hostport))
if scheme == 'https':
target_port = 443
else:
target_por... | Convert a URL into a host / port, or into a path to a unix domain socket
Args:
endpoint (str): A URL parsable by urlparse
Returns:
3 item tuple: (host, port, path).
host and port will None, and path will be not None if a a unix domain socket URL is passed
... | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/client.py#L330-L355 | null | class Client(object):
"""A python wrapper for the fleet v1 API
The fleet v1 API is documented here: https://github.com/coreos/fleet/blob/master/Documentation/api-v1.md
"""
_API = 'fleet'
_VERSION = 'v1'
_STATES = ['inactive', 'loaded', 'launched']
def __init__(
self,
endpo... |
cnelson/python-fleet | fleet/v1/client.py | Client._get_proxy_info | python | def _get_proxy_info(self, _=None):
# parse the fleet endpoint url, to establish a tunnel to that host
(target_host, target_port, target_path) = self._endpoint_to_target(self._endpoint)
# implement the proxy_info interface from httplib which requires
# that we accept a scheme, and return... | Generate a ProxyInfo class from a connected SSH transport
Args:
_ (None): Ignored. This is just here as the ProxyInfo spec requires it.
Returns:
SSHTunnelProxyInfo: A ProxyInfo with an active socket tunneled through SSH | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/client.py#L357-L385 | null | class Client(object):
"""A python wrapper for the fleet v1 API
The fleet v1 API is documented here: https://github.com/coreos/fleet/blob/master/Documentation/api-v1.md
"""
_API = 'fleet'
_VERSION = 'v1'
_STATES = ['inactive', 'loaded', 'launched']
def __init__(
self,
endpo... |
cnelson/python-fleet | fleet/v1/client.py | Client._single_request | python | def _single_request(self, method, *args, **kwargs):
# The auto generated client binding require instantiating each object you want to call a method on
# For example to make a request to /machines for the list of machines you would do:
# self._service.Machines().List(**kwargs)
# This cod... | Make a single request to the fleet API endpoint
Args:
method (str): A dot delimited string indicating the method to call. Example: 'Machines.List'
*args: Passed directly to the method being called.
**kwargs: Passed directly to the method being called.
Returns:
... | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/client.py#L387-L435 | null | class Client(object):
"""A python wrapper for the fleet v1 API
The fleet v1 API is documented here: https://github.com/coreos/fleet/blob/master/Documentation/api-v1.md
"""
_API = 'fleet'
_VERSION = 'v1'
_STATES = ['inactive', 'loaded', 'launched']
def __init__(
self,
endpo... |
cnelson/python-fleet | fleet/v1/client.py | Client._request | python | def _request(self, method, *args, **kwargs):
# This is set to False and not None so that the while loop below will execute at least once
next_page_token = False
while next_page_token is not None:
# If bool(next_page_token), then include it in the request
# We do this so... | Make a request with automatic pagination handling
Args:
method (str): A dot delimited string indicating the method to call. Example: 'Machines.List'
*args: Passed directly to the method being called.
**kwargs: Passed directly to the method being called.
... | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/client.py#L437-L475 | [
"def _single_request(self, method, *args, **kwargs):\n \"\"\"Make a single request to the fleet API endpoint\n\n Args:\n method (str): A dot delimited string indicating the method to call. Example: 'Machines.List'\n *args: Passed directly to the method being called.\n **kwargs: Passed di... | class Client(object):
"""A python wrapper for the fleet v1 API
The fleet v1 API is documented here: https://github.com/coreos/fleet/blob/master/Documentation/api-v1.md
"""
_API = 'fleet'
_VERSION = 'v1'
_STATES = ['inactive', 'loaded', 'launched']
def __init__(
self,
endpo... |
cnelson/python-fleet | fleet/v1/client.py | Client.create_unit | python | def create_unit(self, name, unit):
self._single_request('Units.Set', unitName=name, body={
'desiredState': unit.desiredState,
'options': unit.options
})
return self.get_unit(name) | Create a new Unit in the cluster
Create and modify Unit entities to communicate to fleet the desired state of the cluster.
This simply declares what should be happening; the backend system still has to react to
the changes in this desired state. The actual state of the system is communicated wi... | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/client.py#L477-L503 | [
"def _single_request(self, method, *args, **kwargs):\n \"\"\"Make a single request to the fleet API endpoint\n\n Args:\n method (str): A dot delimited string indicating the method to call. Example: 'Machines.List'\n *args: Passed directly to the method being called.\n **kwargs: Passed di... | class Client(object):
"""A python wrapper for the fleet v1 API
The fleet v1 API is documented here: https://github.com/coreos/fleet/blob/master/Documentation/api-v1.md
"""
_API = 'fleet'
_VERSION = 'v1'
_STATES = ['inactive', 'loaded', 'launched']
def __init__(
self,
endpo... |
cnelson/python-fleet | fleet/v1/client.py | Client.set_unit_desired_state | python | def set_unit_desired_state(self, unit, desired_state):
if desired_state not in self._STATES:
raise ValueError('state must be one of: {0}'.format(
self._STATES
))
# if we are given an object, grab it's name property
# otherwise, convert to unicode
... | Update the desired state of a unit running in the cluster
Args:
unit (str, Unit): The Unit, or name of the unit to update
desired_state: State the user wishes the Unit to be in
("inactive", "loaded", or "launched")
Returns:
Unit: The unit t... | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/client.py#L505-L538 | [
"def _single_request(self, method, *args, **kwargs):\n \"\"\"Make a single request to the fleet API endpoint\n\n Args:\n method (str): A dot delimited string indicating the method to call. Example: 'Machines.List'\n *args: Passed directly to the method being called.\n **kwargs: Passed di... | class Client(object):
"""A python wrapper for the fleet v1 API
The fleet v1 API is documented here: https://github.com/coreos/fleet/blob/master/Documentation/api-v1.md
"""
_API = 'fleet'
_VERSION = 'v1'
_STATES = ['inactive', 'loaded', 'launched']
def __init__(
self,
endpo... |
cnelson/python-fleet | fleet/v1/client.py | Client.destroy_unit | python | def destroy_unit(self, unit):
# if we are given an object, grab it's name property
# otherwise, convert to unicode
if isinstance(unit, Unit):
unit = unit.name
else:
unit = str(unit)
self._single_request('Units.Delete', unitName=unit)
return True | Delete a unit from the cluster
Args:
unit (str, Unit): The Unit, or name of the unit to delete
Returns:
True: The unit was deleted
Raises:
fleet.v1.errors.APIError: Fleet returned a response code >= 400 | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/client.py#L540-L562 | [
"def _single_request(self, method, *args, **kwargs):\n \"\"\"Make a single request to the fleet API endpoint\n\n Args:\n method (str): A dot delimited string indicating the method to call. Example: 'Machines.List'\n *args: Passed directly to the method being called.\n **kwargs: Passed di... | class Client(object):
"""A python wrapper for the fleet v1 API
The fleet v1 API is documented here: https://github.com/coreos/fleet/blob/master/Documentation/api-v1.md
"""
_API = 'fleet'
_VERSION = 'v1'
_STATES = ['inactive', 'loaded', 'launched']
def __init__(
self,
endpo... |
cnelson/python-fleet | fleet/v1/client.py | Client.list_units | python | def list_units(self):
for page in self._request('Units.List'):
for unit in page.get('units', []):
yield Unit(client=self, data=unit) | Return the current list of the Units in the fleet cluster
Yields:
Unit: The next Unit in the cluster
Raises:
fleet.v1.errors.APIError: Fleet returned a response code >= 400 | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/client.py#L564-L576 | [
"def _request(self, method, *args, **kwargs):\n \"\"\"Make a request with automatic pagination handling\n\n Args:\n method (str): A dot delimited string indicating the method to call. Example: 'Machines.List'\n *args: Passed directly to the method being called.\n **kwargs: Passed directl... | class Client(object):
"""A python wrapper for the fleet v1 API
The fleet v1 API is documented here: https://github.com/coreos/fleet/blob/master/Documentation/api-v1.md
"""
_API = 'fleet'
_VERSION = 'v1'
_STATES = ['inactive', 'loaded', 'launched']
def __init__(
self,
endpo... |
cnelson/python-fleet | fleet/v1/client.py | Client.get_unit | python | def get_unit(self, name):
return Unit(client=self, data=self._single_request('Units.Get', unitName=name)) | Retreive a specifi unit from the fleet cluster by name
Args:
name (str): If specified, only this unit name is returned
Returns:
Unit: The unit identified by ``name`` in the fleet cluster
Raises:
fleet.v1.errors.APIError: Fleet returned a response code >= 40... | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/client.py#L578-L591 | [
"def _single_request(self, method, *args, **kwargs):\n \"\"\"Make a single request to the fleet API endpoint\n\n Args:\n method (str): A dot delimited string indicating the method to call. Example: 'Machines.List'\n *args: Passed directly to the method being called.\n **kwargs: Passed di... | class Client(object):
"""A python wrapper for the fleet v1 API
The fleet v1 API is documented here: https://github.com/coreos/fleet/blob/master/Documentation/api-v1.md
"""
_API = 'fleet'
_VERSION = 'v1'
_STATES = ['inactive', 'loaded', 'launched']
def __init__(
self,
endpo... |
cnelson/python-fleet | fleet/v1/client.py | Client.list_unit_states | python | def list_unit_states(self, machine_id=None, unit_name=None):
for page in self._request('UnitState.List', machineID=machine_id, unitName=unit_name):
for state in page.get('states', []):
yield UnitState(data=state) | Return the current UnitState for the fleet cluster
Args:
machine_id (str): filter all UnitState objects to those
originating from a specific machine
unit_name (str): filter all UnitState objects to those related
to a specific... | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/client.py#L593-L612 | [
"def _request(self, method, *args, **kwargs):\n \"\"\"Make a request with automatic pagination handling\n\n Args:\n method (str): A dot delimited string indicating the method to call. Example: 'Machines.List'\n *args: Passed directly to the method being called.\n **kwargs: Passed directl... | class Client(object):
"""A python wrapper for the fleet v1 API
The fleet v1 API is documented here: https://github.com/coreos/fleet/blob/master/Documentation/api-v1.md
"""
_API = 'fleet'
_VERSION = 'v1'
_STATES = ['inactive', 'loaded', 'launched']
def __init__(
self,
endpo... |
cnelson/python-fleet | fleet/v1/client.py | Client.list_machines | python | def list_machines(self):
# loop through each page of results
for page in self._request('Machines.List'):
# return each machine in the current page
for machine in page.get('machines', []):
yield Machine(data=machine) | Retrieve a list of machines in the fleet cluster
Yields:
Machine: The next machine in the cluster
Raises:
fleet.v1.errors.APIError: Fleet returned a response code >= 400 | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/client.py#L614-L628 | [
"def _request(self, method, *args, **kwargs):\n \"\"\"Make a request with automatic pagination handling\n\n Args:\n method (str): A dot delimited string indicating the method to call. Example: 'Machines.List'\n *args: Passed directly to the method being called.\n **kwargs: Passed directl... | class Client(object):
"""A python wrapper for the fleet v1 API
The fleet v1 API is documented here: https://github.com/coreos/fleet/blob/master/Documentation/api-v1.md
"""
_API = 'fleet'
_VERSION = 'v1'
_STATES = ['inactive', 'loaded', 'launched']
def __init__(
self,
endpo... |
cnelson/python-fleet | fleet/http/unix_socket.py | UnixConnectionWithTimeout.connect | python | def connect(self):
"""Connect to the unix domain socket, which is passed to us as self.host
This is in host because the format we use for the unix domain socket is:
http+unix://%2Fpath%2Fto%2Fsocket.sock
"""
try:
self.sock = socket.socket(socket.AF_UNIX, s... | Connect to the unix domain socket, which is passed to us as self.host
This is in host because the format we use for the unix domain socket is:
http+unix://%2Fpath%2Fto%2Fsocket.sock | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/http/unix_socket.py#L37-L57 | [
"def has_timeout(timeout): # pragma: no cover\n if hasattr(socket, '_GLOBAL_DEFAULT_TIMEOUT'):\n return (timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT)\n return (timeout is not None)\n"
] | class UnixConnectionWithTimeout(httplib.HTTPConnection):
"""
HTTP over UNIX Domain Sockets
"""
def __init__(self, host, port=None, strict=None, timeout=None, proxy_info=None):
httplib.HTTPConnection.__init__(self, host, port)
self.timeout = timeout
def connect(self):
"""Con... |
ascribe/pyspool | spool/wallet.py | Wallet.address_from_path | python | def address_from_path(self, path=None):
path = path if path else self._unique_hierarchical_string()
return path, self.wallet.subkey_for_path(path).address() | Args:
path (str): Path for the HD wallet. If path is ``None`` it
will generate a unique path based on time.
Returns:
A ``tuple`` with the path and leaf address. | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/wallet.py#L42-L53 | [
"def _unique_hierarchical_string(self):\n \"\"\"\n Returns:\n str: a representation of time such as::\n\n '2014/2/23/15/26/8/9877978'\n\n The last part (microsecond) is needed to avoid duplicates in\n rapid-fire transactions e.g. ``> 1`` edition.\n\n \"\"\"\n t = datetime.now()\n... | class Wallet(object):
"""
Represents a BIP32 wallet.
Attributes:
wallet (BIP32Node): :class:`BIP32NOde` instance.
root_address (Tuple[str]): Root address of the HD Wallet.
"""
def __init__(self, password, testnet=False):
"""
Initializes a BIP32 wallet.
Add... |
ascribe/pyspool | spool/wallet.py | Wallet._unique_hierarchical_string | python | def _unique_hierarchical_string(self):
t = datetime.now()
return '%s/%s/%s/%s/%s/%s/%s' % (t.year, t.month, t.day, t.hour,
t.minute, t.second, t.microsecond) | Returns:
str: a representation of time such as::
'2014/2/23/15/26/8/9877978'
The last part (microsecond) is needed to avoid duplicates in
rapid-fire transactions e.g. ``> 1`` edition. | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/wallet.py#L55-L68 | null | class Wallet(object):
"""
Represents a BIP32 wallet.
Attributes:
wallet (BIP32Node): :class:`BIP32NOde` instance.
root_address (Tuple[str]): Root address of the HD Wallet.
"""
def __init__(self, password, testnet=False):
"""
Initializes a BIP32 wallet.
Add... |
ascribe/pyspool | spool/ownership.py | Ownership.can_transfer | python | def can_transfer(self):
# 1. The address needs to own the edition
chain = BlockchainSpider.chain(self._tree, self.edition_number)
if len(chain) == 0:
self.reason = 'The edition number {} does not exist in the blockchain'.format(self.edition_number)
return False
... | bool: :const:`True` if :attr:`address` can transfer the edition
:attr:`edition_number` of :attr:`piece_address` else :const:`False`. | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/ownership.py#L85-L104 | [
"def chain(tree, edition_number):\n \"\"\"\n Args:\n tree (dict): Tree history of all editions of a piece.\n edition_number (int): The edition number to check for.\n In the case of a piece (master edition), an empty\n string (``''``) or zero (``0``) can be passed.\n\n Re... | class Ownership(object):
"""
Checks the actions that an address can make on a piece.
Attributes:
address (str): Bitcoin address to check ownership over
:attr:`piece_address`.
piece_address (str): Bitcoin address of the piece to check.
edition_number (int): The edition nu... |
ascribe/pyspool | spool/ownership.py | Ownership.can_unconsign | python | def can_unconsign(self):
chain = BlockchainSpider.chain(self._tree, self.edition_number)
if len(chain) == 0:
self.reason = 'Master edition not yet registered'
return False
chain = BlockchainSpider.strip_loan(chain)
action = chain[-1]['action']
piece_addre... | bool: :const:`True` if :attr:`address` can unconsign the edition
:attr:`edition_number` of :attr:`piece_address` else :const:`False`.
If the last transaction is a consignment of the edition to the user. | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/ownership.py#L125-L148 | [
"def chain(tree, edition_number):\n \"\"\"\n Args:\n tree (dict): Tree history of all editions of a piece.\n edition_number (int): The edition number to check for.\n In the case of a piece (master edition), an empty\n string (``''``) or zero (``0``) can be passed.\n\n Re... | class Ownership(object):
"""
Checks the actions that an address can make on a piece.
Attributes:
address (str): Bitcoin address to check ownership over
:attr:`piece_address`.
piece_address (str): Bitcoin address of the piece to check.
edition_number (int): The edition nu... |
ascribe/pyspool | spool/ownership.py | Ownership.can_register | python | def can_register(self):
chain = BlockchainSpider.chain(self._tree, REGISTERED_PIECE_CODE)
# edition 0 should only have two transactions: REGISTER and EDITIONS
if len(chain) == 0:
self.reason = 'Master edition not yet registered'
return False
chain = BlockchainSp... | bool: :const:`True` if :attr:`address` can register the edition
:attr:`edition_number` of :attr:`piece_address` else :const:`False`.
In order to register an edition:
1. The master piece needs to be registered.
2. The number of editions needs to be registered.
3. The :attr:`edit... | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/ownership.py#L151-L188 | [
"def chain(tree, edition_number):\n \"\"\"\n Args:\n tree (dict): Tree history of all editions of a piece.\n edition_number (int): The edition number to check for.\n In the case of a piece (master edition), an empty\n string (``''``) or zero (``0``) can be passed.\n\n Re... | class Ownership(object):
"""
Checks the actions that an address can make on a piece.
Attributes:
address (str): Bitcoin address to check ownership over
:attr:`piece_address`.
piece_address (str): Bitcoin address of the piece to check.
edition_number (int): The edition nu... |
ascribe/pyspool | spool/ownership.py | Ownership.can_editions | python | def can_editions(self):
chain = BlockchainSpider.chain(self._tree, REGISTERED_PIECE_CODE)
if len(chain) == 0:
self.reason = 'Master edition not yet registered'
return False
number_editions = chain[0]['number_editions']
if number_editions != 0:
self.r... | bool: :const:`True` if :attr:`address` can register the number of
editions of :attr:`piece_address` else :const:`False`.
In order to register the number of editions:
1. There needs to a least one transaction for the :attr:`piece_address`
(the registration of the master edition).
... | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/ownership.py#L208-L236 | [
"def chain(tree, edition_number):\n \"\"\"\n Args:\n tree (dict): Tree history of all editions of a piece.\n edition_number (int): The edition number to check for.\n In the case of a piece (master edition), an empty\n string (``''``) or zero (``0``) can be passed.\n\n Re... | class Ownership(object):
"""
Checks the actions that an address can make on a piece.
Attributes:
address (str): Bitcoin address to check ownership over
:attr:`piece_address`.
piece_address (str): Bitcoin address of the piece to check.
edition_number (int): The edition nu... |
ascribe/pyspool | spool/spoolverb.py | Spoolverb.from_verb | python | def from_verb(cls, verb):
pattern = r'^(?P<meta>[A-Z]+)(?P<version>\d+)(?P<action>[A-Z]+)(?P<arg1>\d+)?(\/(?P<arg2>\d+))?$'
try:
verb = verb.decode()
except AttributeError:
pass
match = re.match(pattern, verb)
if not match:
raise SpoolverbError... | Constructs a :class:`Spoolverb` instance from the string
representation of the given verb.
Args:
verb (str): representation of the verb e.g.:
``'ASCRIBESPOOL01LOAN12/150526150528'``. Can also be in
binary format (:obj:`bytes`): ``b'ASCRIBESPOOL01PIECE'``.
... | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/spoolverb.py#L72-L117 | null | class Spoolverb(object):
"""
Allows for easy creation of the verb to be encoded on the
``op_return`` of all SPOOL transactions.
Attributes:
supported_actions (List[str]): Actions supported by the SPOOL
protocol.
"""
supported_actions = ['REGISTER', 'CONSIGN', 'TRANSFER', 'L... |
ascribe/pyspool | spool/spoolverb.py | Spoolverb.loan | python | def loan(self):
return '{}{}LOAN{}/{}{}'.format(self.meta, self.version, self.edition_number,
self.loan_start, self.loan_end) | str: representation of the ``LOAN`` spoolverb. E.g.:
``'ASCRIBESPOOL01LOAN1/150526150528'``. | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/spoolverb.py#L168-L174 | null | class Spoolverb(object):
"""
Allows for easy creation of the verb to be encoded on the
``op_return`` of all SPOOL transactions.
Attributes:
supported_actions (List[str]): Actions supported by the SPOOL
protocol.
"""
supported_actions = ['REGISTER', 'CONSIGN', 'TRANSFER', 'L... |
ascribe/pyspool | spool/spool.py | Spool.register_piece | python | def register_piece(self, from_address, to_address, hash, password, min_confirmations=6, sync=False, ownership=True):
file_hash, file_hash_metadata = hash
path, from_address = from_address
verb = Spoolverb()
unsigned_tx = self.simple_spool_transaction(from_address,
... | Register a piece
Args:
from_address (Tuple[str]): Federation address. All register transactions
originate from the the Federation wallet
to_address (str): Address registering the edition
hash (Tuple[str]): Hash of the piece. (file_hash, file_hash_metadata)
... | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/spool.py#L99-L133 | [
"def simple_spool_transaction(self, from_address, to, op_return, min_confirmations=6):\n \"\"\"\n Utililty function to create the spool transactions. Selects the inputs,\n encodes the op_return and constructs the transaction.\n\n Args:\n from_address (str): Address originating the transaction\n ... | class Spool(object):
"""
Class that contains all Spool methods.
In the SPOOL implementation there is no notion of users only addresses.
All addresses come from BIP32 HD wallets. This makes it easier to manage all the keys
since we can retrieve everything we need from a master secret (namely the pri... |
ascribe/pyspool | spool/spool.py | Spool.refill_main_wallet | python | def refill_main_wallet(self, from_address, to_address, nfees, ntokens, password, min_confirmations=6, sync=False):
path, from_address = from_address
unsigned_tx = self._t.simple_transaction(from_address,
[(to_address, self.fee)] * nfees + [(to_address, se... | Refill the Federation wallet with tokens and fees. This keeps the federation wallet clean.
Dealing with exact values simplifies the transactions. No need to calculate change. Easier to keep track of the
unspents and prevent double spends that would result in transactions being rejected by the bitcoin ne... | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/spool.py#L390-L417 | null | class Spool(object):
"""
Class that contains all Spool methods.
In the SPOOL implementation there is no notion of users only addresses.
All addresses come from BIP32 HD wallets. This makes it easier to manage all the keys
since we can retrieve everything we need from a master secret (namely the pri... |
ascribe/pyspool | spool/spool.py | Spool.refill | python | def refill(self, from_address, to_address, nfees, ntokens, password, min_confirmations=6, sync=False):
path, from_address = from_address
verb = Spoolverb()
# nfees + 1: nfees to refill plus one fee for the refill transaction itself
inputs = self.select_inputs(from_address, nfees + 1, nto... | Refill wallets with the necessary fuel to perform spool transactions
Args:
from_address (Tuple[str]): Federation wallet address. Fuels the wallets with tokens and fees. All transactions to wallets
holding a particular piece should come from the Federation wallet
to_addre... | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/spool.py#L420-L449 | [
"def select_inputs(self, address, nfees, ntokens, min_confirmations=6):\n \"\"\"\n Selects the inputs for the spool transaction.\n\n Args:\n address (str): bitcoin address to select inputs for\n nfees (int): number of fees\n ntokens (int): number of tokens\n min_confirmations (O... | class Spool(object):
"""
Class that contains all Spool methods.
In the SPOOL implementation there is no notion of users only addresses.
All addresses come from BIP32 HD wallets. This makes it easier to manage all the keys
since we can retrieve everything we need from a master secret (namely the pri... |
ascribe/pyspool | spool/spool.py | Spool.simple_spool_transaction | python | def simple_spool_transaction(self, from_address, to, op_return, min_confirmations=6):
# list of addresses to send
ntokens = len(to)
nfees = old_div(self._t.estimate_fee(ntokens, 2), self.fee)
inputs = self.select_inputs(from_address, nfees, ntokens, min_confirmations=min_confirmations)
... | Utililty function to create the spool transactions. Selects the inputs,
encodes the op_return and constructs the transaction.
Args:
from_address (str): Address originating the transaction
to (str): list of addresses to receive tokens (file_hash, file_hash_metadata, ...)
... | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/spool.py#L451-L475 | [
"def select_inputs(self, address, nfees, ntokens, min_confirmations=6):\n \"\"\"\n Selects the inputs for the spool transaction.\n\n Args:\n address (str): bitcoin address to select inputs for\n nfees (int): number of fees\n ntokens (int): number of tokens\n min_confirmations (O... | class Spool(object):
"""
Class that contains all Spool methods.
In the SPOOL implementation there is no notion of users only addresses.
All addresses come from BIP32 HD wallets. This makes it easier to manage all the keys
since we can retrieve everything we need from a master secret (namely the pri... |
ascribe/pyspool | spool/spool.py | Spool.select_inputs | python | def select_inputs(self, address, nfees, ntokens, min_confirmations=6):
unspents = self._t.get(address, min_confirmations=min_confirmations)['unspents']
unspents = [u for u in unspents if u not in self._spents.queue]
if len(unspents) == 0:
raise Exception("No spendable outputs found")... | Selects the inputs for the spool transaction.
Args:
address (str): bitcoin address to select inputs for
nfees (int): number of fees
ntokens (int): number of tokens
min_confirmations (Optional[int]): minimum number of required
confirmations; defaul... | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/spool.py#L477-L502 | null | class Spool(object):
"""
Class that contains all Spool methods.
In the SPOOL implementation there is no notion of users only addresses.
All addresses come from BIP32 HD wallets. This makes it easier to manage all the keys
since we can retrieve everything we need from a master secret (namely the pri... |
ascribe/pyspool | spool/spoolex.py | BlockchainSpider.history | python | def history(self, hash):
txs = self._t.get(hash, max_transactions=10000)['transactions']
tree = defaultdict(list)
number_editions = 0
for tx in txs:
_tx = self._t.get(tx['txid'])
txid = _tx['txid']
verb_str = BlockchainSpider.check_script(_tx['vouts']... | Retrieve the ownership tree of all editions of a piece given the hash.
Args:
hash (str): Hash of the file to check. Can be created with the
:class:`File` class
Returns:
dict: Ownsership tree of all editions of a piece.
.. note:: For now we only support ... | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/spoolex.py#L70-L118 | [
"def check_script(vouts):\n \"\"\"\n Looks into the vouts list of a transaction\n and returns the ``op_return`` if one exists.\n\n Args;\n vouts (list): List of outputs of a transaction.\n\n Returns:\n str: String representation of the ``op_return``.\n\n Raises:\n Exception: I... | class BlockchainSpider(object):
"""
Spool blockchain explorer. Retrieves from the blockchain
the chain of ownership of a hash created with the
`SPOOL <https://github.com/ascribe/spool>`_ protocol.
"""
def __init__(self, testnet=False, service='blockr', username='', password='', host='', port='... |
ascribe/pyspool | spool/spoolex.py | BlockchainSpider.chain | python | def chain(tree, edition_number):
# return the chain for an edition_number sorted by the timestamp
return sorted(tree.get(edition_number, []), key=lambda d: d['timestamp_utc']) | Args:
tree (dict): Tree history of all editions of a piece.
edition_number (int): The edition number to check for.
In the case of a piece (master edition), an empty
string (``''``) or zero (``0``) can be passed.
Returns:
list: The chain of own... | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/spoolex.py#L121-L135 | null | class BlockchainSpider(object):
"""
Spool blockchain explorer. Retrieves from the blockchain
the chain of ownership of a hash created with the
`SPOOL <https://github.com/ascribe/spool>`_ protocol.
"""
def __init__(self, testnet=False, service='blockr', username='', password='', host='', port='... |
ascribe/pyspool | spool/spoolex.py | BlockchainSpider.check_script | python | def check_script(vouts):
for vout in [v for v in vouts[::-1] if v['hex'].startswith('6a')]:
verb = BlockchainSpider.decode_op_return(vout['hex'])
action = Spoolverb.from_verb(verb).action
if action in Spoolverb.supported_actions:
return verb
raise Exce... | Looks into the vouts list of a transaction
and returns the ``op_return`` if one exists.
Args;
vouts (list): List of outputs of a transaction.
Returns:
str: String representation of the ``op_return``.
Raises:
Exception: If no ``vout`` having a suppor... | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/spoolex.py#L185-L206 | [
"def decode_op_return(op_return_hex):\n \"\"\"\n Decodes the given ``op_return`` hexadecimal\n string representation into a string (:obj:`str`).\n\n Args:\n op_return_hex (str): Hexadecimal string\n representation of the ``op_return``.\n\n Returns:\n str: String representatio... | class BlockchainSpider(object):
"""
Spool blockchain explorer. Retrieves from the blockchain
the chain of ownership of a hash created with the
`SPOOL <https://github.com/ascribe/spool>`_ protocol.
"""
def __init__(self, testnet=False, service='blockr', username='', password='', host='', port='... |
ascribe/pyspool | spool/spoolex.py | BlockchainSpider._get_addresses | python | def _get_addresses(tx):
from_address = set([vin['address'] for vin in tx['vins']])
if len(from_address) != 1:
raise InvalidTransactionError("Transaction should have inputs " \
"from only one address {}".format(from_address))
# order vouts. d... | Checks for the from, to, and piece address of a SPOOL transaction.
Args:
tx (dict): Transaction payload, as returned by
:meth:`transactions.Transactions.get()`.
.. note:: Formats as returned by JSON-RPC API
``decoderawtransaction`` have yet to be supported.
... | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/spoolex.py#L209-L235 | null | class BlockchainSpider(object):
"""
Spool blockchain explorer. Retrieves from the blockchain
the chain of ownership of a hash created with the
`SPOOL <https://github.com/ascribe/spool>`_ protocol.
"""
def __init__(self, testnet=False, service='blockr', username='', password='', host='', port='... |
ascribe/pyspool | spool/spoolex.py | BlockchainSpider._get_time_utc | python | def _get_time_utc(time_utc_str):
dt = datetime.strptime(time_utc_str, TIME_FORMAT)
return int(calendar.timegm(dt.utctimetuple())) | Convert a string representation of the time (as returned by
blockr.io api) into unix timestamp.
Args:
time_utc_str (str): String representation of the time, with the
format: `'%Y-%m-%dT%H:%M:%S %Z'`.
Returns:
int: Unix timestamp. | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/spoolex.py#L238-L252 | null | class BlockchainSpider(object):
"""
Spool blockchain explorer. Retrieves from the blockchain
the chain of ownership of a hash created with the
`SPOOL <https://github.com/ascribe/spool>`_ protocol.
"""
def __init__(self, testnet=False, service='blockr', username='', password='', host='', port='... |
ascribe/pyspool | spool/file.py | File._calculate_hash | python | def _calculate_hash(self, filename, **kwargs):
with open(filename, 'rb') as f:
file_hash = hashlib.md5(f.read()).hexdigest()
if kwargs:
data = str(
[urepr(kwargs[k]) for k in sorted(kwargs)] + [file_hash])
else:
data = file_hash
addre... | Calculates the hash of the file and the hash of the file + metadata
(passed in ``kwargs``).
Args:
filename (str): Name of the file
testnet (bool): testnet flag. Defaults to False
**kwargs: Additional metadata to be encoded with the file. Only
the valu... | train | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/file.py#L67-L101 | null | class File(object):
"""
Class used to calculate the hash of a file and the hash of the file +
metadata to be included on the blockchain
"""
def __init__(self, filename, testnet=False, **kwargs):
"""
Args:
filename (str): Name of the file
testnet (bool): test... |
joequant/cryptoexchange | cryptoexchange/util/bitmex-generate-api-key.py | BitMEX.create_key | python | def create_key(self):
print("Creating key. Please input the following options:")
name = input("Key name (optional): ")
print("To make this key more secure, you should restrict the IP addresses that can use it. ")
print("To use with all IPs, leave blank or use 0.0.0.0/0.")
print("... | Create an API key. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/util/bitmex-generate-api-key.py#L74-L91 | [
"def _curl_bitmex(self, api, query=None, postdict=None, timeout=3, verb=None):\n url = self.base_url + api\n if query:\n url = url + \"?\" + urlencode(query)\n if postdict:\n postdata = urlencode(postdict).encode(\"utf-8\")\n request = Request(url, postdata)\n else:\n request... | class BitMEX(object):
def __init__(self, email=None, password=None, otpToken=None):
self.base_url = (BITMEX_TESTNET if USE_TESTNET else BITMEX_PRODUCTION) + "/api/v1"
self.accessToken = None
self.accessToken = self._curl_bitmex("/user/login",
post... |
joequant/cryptoexchange | cryptoexchange/util/bitmex-generate-api-key.py | BitMEX.list_keys | python | def list_keys(self):
keys = self._curl_bitmex("/apiKey/")
print(json.dumps(keys, sort_keys=True, indent=4)) | List your API Keys. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/util/bitmex-generate-api-key.py#L93-L96 | [
"def _curl_bitmex(self, api, query=None, postdict=None, timeout=3, verb=None):\n url = self.base_url + api\n if query:\n url = url + \"?\" + urlencode(query)\n if postdict:\n postdata = urlencode(postdict).encode(\"utf-8\")\n request = Request(url, postdata)\n else:\n request... | class BitMEX(object):
def __init__(self, email=None, password=None, otpToken=None):
self.base_url = (BITMEX_TESTNET if USE_TESTNET else BITMEX_PRODUCTION) + "/api/v1"
self.accessToken = None
self.accessToken = self._curl_bitmex("/user/login",
post... |
joequant/cryptoexchange | cryptoexchange/util/bitmex-generate-api-key.py | BitMEX.enable_key | python | def enable_key(self):
print("This command will enable a disabled key.")
apiKeyID = input("API Key ID: ")
try:
key = self._curl_bitmex("/apiKey/enable",
postdict={"apiKeyID": apiKeyID})
print("Key with ID %s enabled." % key["id"])
... | Enable an existing API Key. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/util/bitmex-generate-api-key.py#L98-L108 | [
"def enable_key(self):\n \"\"\"Enable an existing API Key.\"\"\"\n print(\"This command will enable a disabled key.\")\n apiKeyID = input(\"API Key ID: \")\n try:\n key = self._curl_bitmex(\"/apiKey/enable\",\n postdict={\"apiKeyID\": apiKeyID})\n print(\"Key... | class BitMEX(object):
def __init__(self, email=None, password=None, otpToken=None):
self.base_url = (BITMEX_TESTNET if USE_TESTNET else BITMEX_PRODUCTION) + "/api/v1"
self.accessToken = None
self.accessToken = self._curl_bitmex("/user/login",
post... |
joequant/cryptoexchange | cryptoexchange/util/bitmex-generate-api-key.py | BitMEX.disable_key | python | def disable_key(self):
print("This command will disable a enabled key.")
apiKeyID = input("API Key ID: ")
try:
key = self._curl_bitmex("/apiKey/disable",
postdict={"apiKeyID": apiKeyID})
print("Key with ID %s disabled." % key["id"])
... | Disable an existing API Key. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/util/bitmex-generate-api-key.py#L110-L120 | [
"def disable_key(self):\n \"\"\"Disable an existing API Key.\"\"\"\n print(\"This command will disable a enabled key.\")\n apiKeyID = input(\"API Key ID: \")\n try:\n key = self._curl_bitmex(\"/apiKey/disable\",\n postdict={\"apiKeyID\": apiKeyID})\n print(\"... | class BitMEX(object):
def __init__(self, email=None, password=None, otpToken=None):
self.base_url = (BITMEX_TESTNET if USE_TESTNET else BITMEX_PRODUCTION) + "/api/v1"
self.accessToken = None
self.accessToken = self._curl_bitmex("/user/login",
post... |
joequant/cryptoexchange | cryptoexchange/util/bitmex-generate-api-key.py | BitMEX.delete_key | python | def delete_key(self):
print("This command will delete an API key.")
apiKeyID = input("API Key ID: ")
try:
self._curl_bitmex("/apiKey/",
postdict={"apiKeyID": apiKeyID}, verb='DELETE')
print("Key with ID %s disabled." % apiKeyID)
excep... | Delete an existing API Key. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/util/bitmex-generate-api-key.py#L122-L132 | [
"def delete_key(self):\n \"\"\"Delete an existing API Key.\"\"\"\n print(\"This command will delete an API key.\")\n apiKeyID = input(\"API Key ID: \")\n try:\n self._curl_bitmex(\"/apiKey/\",\n postdict={\"apiKeyID\": apiKeyID}, verb='DELETE')\n print(\"Key with I... | class BitMEX(object):
def __init__(self, email=None, password=None, otpToken=None):
self.base_url = (BITMEX_TESTNET if USE_TESTNET else BITMEX_PRODUCTION) + "/api/v1"
self.accessToken = None
self.accessToken = self._curl_bitmex("/user/login",
post... |
joequant/cryptoexchange | cryptoexchange/bitmex.py | BitMEX.authenticate | python | def authenticate(self):
if self.apiKey:
return
loginResponse = self._curl_bitmex(
api="user/login",
postdict={'email': self.login, 'password': self.password, 'token': self.otpToken})
self.token = loginResponse['id']
self.session.headers.update({'access... | Set BitMEX authentication information. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/bitmex.py#L115-L123 | [
" def _curl_bitmex(self, api, query=None, postdict=None, timeout=3, verb=None):\n \"\"\"Send a request to BitMEX Servers.\"\"\"\n # Handle URL\n url = self.base_url + api\n\n # Default to POST if data is attached, GET otherwise\n if not verb:\n verb = 'POST' if postd... | class BitMEX(object):
"""BitMEX API Connector."""
def __init__(self, base_url=None, login=None, password=None, otpToken=None,
apiKey=None, apiSecret=None, orderIDPrefix='mm_bitmex_'):
"""Init connector."""
self.logger = logging.getLogger('root')
self.base_url = base_ur... |
joequant/cryptoexchange | cryptoexchange/bitmex.py | BitMEX.authentication_required | python | def authentication_required(function):
def wrapped(self, *args, **kwargs):
if not (self.token or self.apiKey):
msg = "You must be authenticated to use this method"
raise AuthenticationError(msg)
else:
return function(self, *args, **kwargs)
... | Annotation for methods that require auth. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/bitmex.py#L125-L133 | null | class BitMEX(object):
"""BitMEX API Connector."""
def __init__(self, base_url=None, login=None, password=None, otpToken=None,
apiKey=None, apiSecret=None, orderIDPrefix='mm_bitmex_'):
"""Init connector."""
self.logger = logging.getLogger('root')
self.base_url = base_ur... |
joequant/cryptoexchange | cryptoexchange/bitmex.py | BitMEX.place_order | python | def place_order(self, quantity, symbol, price):
if price < 0:
raise Exception("Price must be positive.")
endpoint = "order"
# Generate a unique clOrdID with our prefix so we can identify it.
clOrdID = self.orderIDPrefix + base64.b64encode(uuid.uuid4().bytes).decode('ascii').... | Place an order. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/bitmex.py#L140-L154 | [
" def _curl_bitmex(self, api, query=None, postdict=None, timeout=3, verb=None):\n \"\"\"Send a request to BitMEX Servers.\"\"\"\n # Handle URL\n url = self.base_url + api\n\n # Default to POST if data is attached, GET otherwise\n if not verb:\n verb = 'POST' if postd... | class BitMEX(object):
"""BitMEX API Connector."""
def __init__(self, base_url=None, login=None, password=None, otpToken=None,
apiKey=None, apiSecret=None, orderIDPrefix='mm_bitmex_'):
"""Init connector."""
self.logger = logging.getLogger('root')
self.base_url = base_ur... |
joequant/cryptoexchange | cryptoexchange/bitmex.py | BitMEX.open_orders | python | def open_orders(self, symbol=None):
api = "order"
query = {'ordStatus.isTerminated': False }
if symbol != None:
query['symbol'] =symbol
orders = self._curl_bitmex(
api=api,
query={'filter': json.dumps(query)},
verb="GET"
)
r... | Get open orders via HTTP. Used on close to ensure we catch them all. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/bitmex.py#L157-L168 | [
" def _curl_bitmex(self, api, query=None, postdict=None, timeout=3, verb=None):\n \"\"\"Send a request to BitMEX Servers.\"\"\"\n # Handle URL\n url = self.base_url + api\n\n # Default to POST if data is attached, GET otherwise\n if not verb:\n verb = 'POST' if postd... | class BitMEX(object):
"""BitMEX API Connector."""
def __init__(self, base_url=None, login=None, password=None, otpToken=None,
apiKey=None, apiSecret=None, orderIDPrefix='mm_bitmex_'):
"""Init connector."""
self.logger = logging.getLogger('root')
self.base_url = base_ur... |
joequant/cryptoexchange | cryptoexchange/bitmex.py | BitMEX.cancel | python | def cancel(self, orderID):
api = "order"
postdict = {
'orderID': orderID,
}
return self._curl_bitmex(api=api, postdict=postdict, verb="DELETE") | Cancel an existing order. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/bitmex.py#L173-L179 | [
" def _curl_bitmex(self, api, query=None, postdict=None, timeout=3, verb=None):\n \"\"\"Send a request to BitMEX Servers.\"\"\"\n # Handle URL\n url = self.base_url + api\n\n # Default to POST if data is attached, GET otherwise\n if not verb:\n verb = 'POST' if postd... | class BitMEX(object):
"""BitMEX API Connector."""
def __init__(self, base_url=None, login=None, password=None, otpToken=None,
apiKey=None, apiSecret=None, orderIDPrefix='mm_bitmex_'):
"""Init connector."""
self.logger = logging.getLogger('root')
self.base_url = base_ur... |
joequant/cryptoexchange | cryptoexchange/bitmex.py | BitMEX._curl_bitmex | python | def _curl_bitmex(self, api, query=None, postdict=None, timeout=3, verb=None):
# Handle URL
url = self.base_url + api
# Default to POST if data is attached, GET otherwise
if not verb:
verb = 'POST' if postdict else 'GET'
# Auth: Use Access Token by default, API Key/S... | Send a request to BitMEX Servers. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/bitmex.py#L181-L253 | [
" def _curl_bitmex(self, api, query=None, postdict=None, timeout=3, verb=None):\n \"\"\"Send a request to BitMEX Servers.\"\"\"\n # Handle URL\n url = self.base_url + api\n\n # Default to POST if data is attached, GET otherwise\n if not verb:\n verb = 'POST' if postd... | class BitMEX(object):
"""BitMEX API Connector."""
def __init__(self, base_url=None, login=None, password=None, otpToken=None,
apiKey=None, apiSecret=None, orderIDPrefix='mm_bitmex_'):
"""Init connector."""
self.logger = logging.getLogger('root')
self.base_url = base_ur... |
joequant/cryptoexchange | cryptoexchange/api796.py | getUserInfoError | python | def getUserInfoError(sAccessToken):
import urllib.request, urllib.parse, urllib.error
payload = urllib.parse.urlencode({'access_token': sAccessToken})
c = http.client.HTTPSConnection('796.com')
c.request("GET", "/v1/user/get_info?"+payload)
r = c.getresponse()
data = r.read()
jsonDict = json... | May be return {u'msg': u'Access_token repealed', u'errno': u'-102', u'data': []} | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/api796.py#L69-L80 | null | #!/usr/bin/env python3
#-*- coding:utf-8 -*-
"""
796 API Trading Example/DEMO in Python
After getToken.
"""
import urllib.request, urllib.error, urllib.parse
import time
import base64
import hashlib
import hmac
import http.client
import json
import os
def get_796_token(appid,apikey,secretkey):
timestam... |
joequant/cryptoexchange | cryptoexchange/bitmex_ws.py | generate_signature | python | def generate_signature(secret, verb, url, nonce, data):
# Parse the url so we can remove the base and extract just the path.
parsedURL = urllib.parse.urlparse(url)
path = parsedURL.path
if parsedURL.query:
path = path + '?' + parsedURL.query
# print "Computing HMAC: %s" % verb + path + str(... | Generate a request signature compatible with BitMEX. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/bitmex_ws.py#L31-L45 | null | #!/usr/bin/env python3
import sys
import websocket
import threading
import traceback
from time import sleep
import json
import string
import logging
import urllib.parse
import math
import time
import hmac
import hashlib
def generate_nonce():
return int(round(time.time() * 1000))
# Generates an API signature.
# A ... |
joequant/cryptoexchange | cryptoexchange/bitmex_ws.py | BitMEXWebsocket.get_ticker | python | def get_ticker(self):
'''Return a ticker object. Generated from quote and trade.'''
lastQuote = self.data['quote'][-1]
lastTrade = self.data['trade'][-1]
ticker = {
"last": lastTrade['price'],
"buy": lastQuote['bidPrice'],
"sell": lastQuote['askPrice']... | Return a ticker object. Generated from quote and trade. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/bitmex_ws.py#L92-L105 | null | class BitMEXWebsocket():
def __init__(self, endpoint="", symbol="XBU24H", API_KEY=None, API_SECRET=None, LOGIN=None, PASSWORD=None):
'''Connect to the websocket and initialize data stores.'''
self.logger = logging.getLogger('root')
self.logger.debug("Initializing WebSocket.")
self.e... |
joequant/cryptoexchange | cryptoexchange/bitmex_ws.py | BitMEXWebsocket.__connect | python | def __connect(self, wsURL, symbol):
'''Connect to the websocket in a thread.'''
self.logger.debug("Starting thread")
self.ws = websocket.WebSocketApp(wsURL,
on_message=self.__on_message,
on_close=self.__on_close,
... | Connect to the websocket in a thread. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/bitmex_ws.py#L121-L146 | [
"def exit(self):\n self.exited = True\n self.ws.close()\n",
"def __get_auth(self):\n '''Return auth headers. Will use API Keys if present in settings.'''\n if self.api_key == None and self.login == None:\n self.logger.error(\"No authentication provided! Unable to connect.\")\n sys.exit(1... | class BitMEXWebsocket():
def __init__(self, endpoint="", symbol="XBU24H", API_KEY=None, API_SECRET=None, LOGIN=None, PASSWORD=None):
'''Connect to the websocket and initialize data stores.'''
self.logger = logging.getLogger('root')
self.logger.debug("Initializing WebSocket.")
self.e... |
joequant/cryptoexchange | cryptoexchange/bitmex_ws.py | BitMEXWebsocket.__get_auth | python | def __get_auth(self):
'''Return auth headers. Will use API Keys if present in settings.'''
if self.api_key == None and self.login == None:
self.logger.error("No authentication provided! Unable to connect.")
sys.exit(1)
if self.api_key == None:
self.logger.inf... | Return auth headers. Will use API Keys if present in settings. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/bitmex_ws.py#L148-L169 | null | class BitMEXWebsocket():
def __init__(self, endpoint="", symbol="XBU24H", API_KEY=None, API_SECRET=None, LOGIN=None, PASSWORD=None):
'''Connect to the websocket and initialize data stores.'''
self.logger = logging.getLogger('root')
self.logger.debug("Initializing WebSocket.")
self.e... |
joequant/cryptoexchange | cryptoexchange/bitmex_ws.py | BitMEXWebsocket.__push_symbol | python | def __push_symbol(self, symbol):
'''Ask the websocket for a symbol push. Gets instrument, orderBook, quote, and trade'''
self.__send_command("getSymbol", symbol)
while not {'instrument', 'trade', 'orderBook25'} <= set(self.data):
sleep(0.1) | Ask the websocket for a symbol push. Gets instrument, orderBook, quote, and trade | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/bitmex_ws.py#L186-L190 | [
"def __send_command(self, command, args=[]):\n '''Send a raw command.'''\n self.ws.send(json.dumps({\"op\": command, \"args\": args}))\n"
] | class BitMEXWebsocket():
def __init__(self, endpoint="", symbol="XBU24H", API_KEY=None, API_SECRET=None, LOGIN=None, PASSWORD=None):
'''Connect to the websocket and initialize data stores.'''
self.logger = logging.getLogger('root')
self.logger.debug("Initializing WebSocket.")
self.e... |
joequant/cryptoexchange | cryptoexchange/bitmex_ws.py | BitMEXWebsocket.__send_command | python | def __send_command(self, command, args=[]):
'''Send a raw command.'''
self.ws.send(json.dumps({"op": command, "args": args})) | Send a raw command. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/bitmex_ws.py#L192-L194 | null | class BitMEXWebsocket():
def __init__(self, endpoint="", symbol="XBU24H", API_KEY=None, API_SECRET=None, LOGIN=None, PASSWORD=None):
'''Connect to the websocket and initialize data stores.'''
self.logger = logging.getLogger('root')
self.logger.debug("Initializing WebSocket.")
self.e... |
joequant/cryptoexchange | cryptoexchange/bitmex_ws.py | BitMEXWebsocket.__on_message | python | def __on_message(self, ws, message):
'''Handler for parsing WS messages.'''
message = json.loads(message)
self.logger.debug(json.dumps(message))
table = message['table'] if 'table' in message else None
action = message['action'] if 'action' in message else None
try:
... | Handler for parsing WS messages. | train | https://github.com/joequant/cryptoexchange/blob/6690fbd9a2ba00e40d7484425808c84d44233f0c/cryptoexchange/bitmex_ws.py#L196-L245 | null | class BitMEXWebsocket():
def __init__(self, endpoint="", symbol="XBU24H", API_KEY=None, API_SECRET=None, LOGIN=None, PASSWORD=None):
'''Connect to the websocket and initialize data stores.'''
self.logger = logging.getLogger('root')
self.logger.debug("Initializing WebSocket.")
self.e... |
ilblackdragon/django-misc | misc/managers.py | SoftDeleteManager.filter | python | def filter(self, *args, **kwargs):
if 'pk' in kwargs or 'id' in kwargs:
return self.all_with_deleted().filter(*args, **kwargs)
return self.get_query_set().filter(*args, **kwargs) | If id or pk was specified as a kwargs, return even if it's deleteted. | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/managers.py#L43-L47 | [
"def get_query_set(self):\n\treturn SoftDeleteQuerySet(self.model, using=self._db).alive()\n",
"def all_with_deleted(self):\n\treturn SoftDeleteQuerySet(self.model, using=self._db)\n"
] | class SoftDeleteManager(models.Manager):
"""Manager provides soft deletion of records.
Your model must have BooleanField or LiveField "alive".
"""
def get_query_set(self):
return SoftDeleteQuerySet(self.model, using=self._db).alive()
def all_with_deleted(self):
return SoftDeleteQuerySet(self.model, using=se... |
ilblackdragon/django-misc | misc/parser.py | XlsReader.formatrow | python | def formatrow(self, types, values, wanttupledate):
## Data Type Codes:
## EMPTY 0
## TEXT 1 a Unicode string
## NUMBER 2 float
## DATE 3 float
## BOOLEAN 4 int; 1 means TRUE, 0 means FALSE
## ERROR 5
returnrow = []
for i in range(len(types))... | Internal function used to clean up the incoming excel data | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/parser.py#L21-L54 | null | class XlsReader(Reader):
def __init__(self, fileName):
super(XlsReader, self).__init__(self)
self.__book__ = xlrd.open_workbook(fileName)
self.__sheet__ = self.__book__._sheet_list[0]
self.__row__ = 0
def readline(self):
try:
types,values = self.__sheet__.r... |
ilblackdragon/django-misc | misc/utils.py | str_to_class | python | def str_to_class(class_name):
mod_str, cls_str = class_name.rsplit('.', 1)
mod = __import__(mod_str, globals(), locals(), [''])
cls = getattr(mod, cls_str)
return cls | Returns a class based on class name | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/utils.py#L44-L51 | null | # -*- coding: utf-8 -*-
import os
import string
import re
from django.conf import settings
from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, load_backend
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponse
from django.utils.encoding import smart_str, force_unicode... |
ilblackdragon/django-misc | misc/utils.py | get_hierarchy_uploader | python | def get_hierarchy_uploader(root):
# Workaround to avoid Django 1.7 makemigrations wierd behaviour:
# More details: https://code.djangoproject.com/ticket/22436
import sys
if len(sys.argv) > 1 and sys.argv[1] in ('makemigrations', 'migrate'):
# Hide ourselves from Django migrations
return ... | Returns uploader, that uses get_hierarch_path to store files | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/utils.py#L75-L90 | null | # -*- coding: utf-8 -*-
import os
import string
import re
from django.conf import settings
from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, load_backend
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponse
from django.utils.encoding import smart_str, force_unicode... |
ilblackdragon/django-misc | misc/views.py | handler500 | python | def handler500(request, template_name='500.html'):
t = loader.get_template(template_name) # You need to create a 500.html template.
return http.HttpResponseServerError(t.render(Context({
'MEDIA_URL': settings.MEDIA_URL,
'STATIC_URL': settings.STATIC_URL
}))) | 500 error handler.
Templates: `500.html`
Context:
MEDIA_URL
Path of static media (e.g. "media.example.org")
STATIC_URL | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/views.py#L22-L36 | null | # -*- coding: utf-8 -*-
from django import http
from django.conf import settings
from django.dispatch import Signal
from django.template import Context, loader
from django.shortcuts import redirect
# Django 1.7 Removed custom profiles
try:
from django.contrib.auth.models import SiteProfileNotAvailable
except Impor... |
ilblackdragon/django-misc | misc/views.py | handler404 | python | def handler404(request, template_name='404.html'):
t = loader.get_template(template_name) # You need to create a 404.html template.
return http.HttpResponseNotFound(t.render(Context({
'MEDIA_URL': settings.MEDIA_URL,
'STATIC_URL': settings.STATIC_URL
}))) | 404 error handler.
Templates: `404.html`
Context:
MEDIA_URL
Path of static media (e.g. "media.example.org")
STATIC_URL | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/views.py#L38-L52 | null | # -*- coding: utf-8 -*-
from django import http
from django.conf import settings
from django.dispatch import Signal
from django.template import Context, loader
from django.shortcuts import redirect
# Django 1.7 Removed custom profiles
try:
from django.contrib.auth.models import SiteProfileNotAvailable
except Impor... |
ilblackdragon/django-misc | misc/decorators.py | to_template | python | def to_template(template_name=None):
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
result = view_func(request, *args, **kwargs)
if isinstance(result, dict):
return TemplateResponse(request, result.pop('TEMPLATE', template_name), result)
... | Decorator for simple call TemplateResponse
Examples:
@to_template("test.html")
def test(request):
return {'test': 100}
@to_template
def test2(request):
return {'test': 100, 'TEMPLATE': 'test.html'}
@to_template
def test2(request, template_name='test.html'):
return {... | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/decorators.py#L12-L36 | null | from functools import update_wrapper, wraps
from django.conf import settings
from django.core.cache import cache
from django.utils.decorators import available_attrs
if 'coffin' in settings.INSTALLED_APPS:
from coffin.template.response import TemplateResponse
else:
from django.template.response import Template... |
ilblackdragon/django-misc | misc/decorators.py | receiver | python | def receiver(signal, **kwargs):
def _decorator(func):
signal.connect(func, **kwargs)
return func
return _decorator | Introduced in Django 1.3 (django.dispatch.receiver)
A decorator for connecting receivers to signals. Used by passing in the
signal and keyword arguments to connect::
@receiver(post_save, sender=MyModel)
def signal_receiver(sender, **kwargs):
do_stuff() | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/decorators.py#L40-L54 | null | from functools import update_wrapper, wraps
from django.conf import settings
from django.core.cache import cache
from django.utils.decorators import available_attrs
if 'coffin' in settings.INSTALLED_APPS:
from coffin.template.response import TemplateResponse
else:
from django.template.response import Template... |
ilblackdragon/django-misc | misc/templatetags/misc_tags.py | find_element | python | def find_element(list, index, index2=1):
for x in list:
if x[0] == index:
return x[index2]
return None | When you have list like: a = [(0, 10), (1, 20), (2, 30)] and you need to get value from tuple with first value == index
Usage:
{% find_element 1 %} will return 20 | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/templatetags/misc_tags.py#L27-L36 | null | # -*- coding: utf-8 -*-
from django.template.base import Library, Token, TOKEN_BLOCK, Node, Variable, VariableDoesNotExist
from django.conf import settings
from django.template.defaultfilters import stringfilter
register = Library()
@register.filter
@stringfilter
def cutafter(text, length):
if len(text) > int(len... |
ilblackdragon/django-misc | misc/templatetags/misc_tags.py | get_dict | python | def get_dict(parser, token):
bits = token.contents.split(' ')
return GetDict(bits[1], bits[2], ((len(bits) > 3) and bits[3]) or '', ((len(bits) > 4) and bits[4]) or '', ((len(bits) > 5) and bits[5]) or '') | Call {% get_dict dict key default_key %} or {% get_dict dict key %}
Return value from dict of key element. If there are no key in get_dict it returns default_key (or '')
Return value will be in parameter 'value' | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/templatetags/misc_tags.py#L39-L46 | null | # -*- coding: utf-8 -*-
from django.template.base import Library, Token, TOKEN_BLOCK, Node, Variable, VariableDoesNotExist
from django.conf import settings
from django.template.defaultfilters import stringfilter
register = Library()
@register.filter
@stringfilter
def cutafter(text, length):
if len(text) > int(len... |
ilblackdragon/django-misc | misc/templatetags/misc_tags.py | filter | python | def filter(parser, token):
bits = token.contents.split(' ')
return FilterTag(bits[1], bits[2:]) | Filter tag for Query sets. Use with set tag =)
{% set filter posts status 0 drafts %} | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/templatetags/misc_tags.py#L166-L172 | null | # -*- coding: utf-8 -*-
from django.template.base import Library, Token, TOKEN_BLOCK, Node, Variable, VariableDoesNotExist
from django.conf import settings
from django.template.defaultfilters import stringfilter
register = Library()
@register.filter
@stringfilter
def cutafter(text, length):
if len(text) > int(len... |
ilblackdragon/django-misc | misc/templatetags/misc_tags.py | CallableVariable._resolve_lookup | python | def _resolve_lookup(self, context):
current = context
try: # catch-all for silent variable failures
for bit in self.lookups:
if callable(current):
if getattr(current, 'alters_data', False):
current = settings.TEMPLATE_STRING_IF_INVA... | Performs resolution of a real variable (i.e. not a literal) against the
given context.
As indicated by the method's name, this method is an implementation
detail and shouldn't be called by external code. Use Variable.resolve()
instead. | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/templatetags/misc_tags.py#L77-L119 | null | class CallableVariable(Variable):
|
ilblackdragon/django-misc | misc/admin.py | admin_tagify | python | def admin_tagify(short_description=None, allow_tags=True):
def tagify(func):
func.allow_tags = bool(allow_tags)
if short_description:
func.short_description = short_description
return func
return tagify | Decorator that add short_description and allow_tags to ModelAdmin list_display function.
Example:
class AlbumAdmin(admin.ModelAdmin):
list_display = ['title', 'year',... | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/admin.py#L4-L23 | null | from django.contrib import admin
from django.contrib.admin.views.main import ChangeList
def admin_tagify(short_description=None, allow_tags=True):
"""
Decorator that add short_description and allow_tags to ModelAdmin list_display function.
Example:
class AlbumAdmin(admin.ModelAdmin): ... |
ilblackdragon/django-misc | misc/admin.py | foreign_field_func | python | def foreign_field_func(field_name, short_description=None, admin_order_field=None):
"""
Allow to use ForeignKey field attributes at list_display in a simple way.
Example:
from misc.admin import foreign_field_func as ff
class SongAdmin(admin.ModelAdmin): ... | Allow to use ForeignKey field attributes at list_display in a simple way.
Example:
from misc.admin import foreign_field_func as ff
class SongAdmin(admin.ModelAdmin):
... | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/admin.py#L26-L52 | null | from django.contrib import admin
from django.contrib.admin.views.main import ChangeList
def admin_tagify(short_description=None, allow_tags=True):
"""
Decorator that add short_description and allow_tags to ModelAdmin list_display function.
Example:
class AlbumAdmin(admin.ModelAdmin): ... |
ilblackdragon/django-misc | misc/admin.py | SoftDeleteAdmin.queryset | python | def queryset(self, request):
query_set = self.model._default_manager.all_with_deleted()
ordering = self.ordering or ()
if ordering:
query_set = query_set.order_by(*ordering)
return query_set | Returns a Queryset of all model instances that can be edited by the
admin site. This is used by changelist_view. | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/admin.py#L99-L106 | null | class SoftDeleteAdmin(admin.ModelAdmin):
"""Custom admin page for models with SoftDeleteManager."""
list_display = ('id', '__unicode__', 'alive', )
list_filter = ('alive', )
|
ilblackdragon/django-misc | misc/templatetags/share_buttons.py | current_site_url | python | def current_site_url():
protocol = getattr(settings, 'MY_SITE_PROTOCOL', 'https')
port = getattr(settings, 'MY_SITE_PORT', '')
url = '%s://%s' % (protocol, settings.SITE_DOMAIN)
if port:
url += ':%s' % port
return url | Returns fully qualified URL (no trailing slash) for the current site. | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/templatetags/share_buttons.py#L23-L30 | null | # -*- coding: utf-8 -*-
import urllib
import hashlib
from django.conf import settings
from django.contrib.sites.models import Site
from django.utils.translation import get_language_from_request, ugettext
if 'coffin' in settings.INSTALLED_APPS:
from coffin.template import Library
from jinja2 import Markup as ... |
ilblackdragon/django-misc | misc/json_encode.py | json_encode | python | def json_encode(data):
def _any(data):
ret = None
# Opps, we used to check if it is of type list, but that fails
# i.e. in the case of django.newforms.utils.ErrorList, which extends
# the type "list". Oh man, that was a dumb mistake!
if isinstance(data, list):
r... | The main issues with django's default json serializer is that properties that
had been added to an object dynamically are being ignored (and it also has
problems with some models). | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/json_encode.py#L24-L84 | [
"def _any(data):\n ret = None\n # Opps, we used to check if it is of type list, but that fails \n # i.e. in the case of django.newforms.utils.ErrorList, which extends\n # the type \"list\". Oh man, that was a dumb mistake!\n if isinstance(data, list):\n ret = _list(data)\n # Same as for lis... | from django.conf import settings
from django.core.serializers.json import DateTimeAwareJSONEncoder
from django.core.serializers import serialize
from django.db import models
from django.http import HttpResponse
from django.utils.encoding import force_unicode
from django.utils.functional import Promise
#Fix for Django ... |
ilblackdragon/django-misc | misc/json_encode.py | json_template | python | def json_template(data, template_name, template_context):
html = render_to_string(template_name, template_context)
data = data or {}
data['html'] = html
return HttpResponse(json_encode(data), content_type='application/json') | Old style, use JSONTemplateResponse instead of this. | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/json_encode.py#L89-L95 | [
"def json_encode(data):\n \"\"\"\n The main issues with django's default json serializer is that properties that\n had been added to an object dynamically are being ignored (and it also has \n problems with some models).\n \"\"\"\n\n def _any(data):\n ret = None\n # Opps, we used to ... | from django.conf import settings
from django.core.serializers.json import DateTimeAwareJSONEncoder
from django.core.serializers import serialize
from django.db import models
from django.http import HttpResponse
from django.utils.encoding import force_unicode
from django.utils.functional import Promise
#Fix for Django ... |
ilblackdragon/django-misc | misc/management/utils.py | handle_lock | python | def handle_lock(handle):
def wrapper(self, *args, **options):
def on_interrupt(signum, frame):
# It's necessary to release lockfile
sys.exit()
signal.signal(signal.SIGTERM, on_interrupt)
start_time = time.time()
try:
verbosity = int(options.g... | Decorate the handle method with a file lock to ensure there is only ever
one process running at any one time. | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/management/utils.py#L24-L83 | null | """
A decorator for management commands (or any class method) to ensure that there is
only ever one process running the method at any one time.
Requires lockfile - (pip install lockfile)
Author: Ross Lawley
"""
import logging
import os
import signal
import sys
import time
from lockfile import FileLock, AlreadyLocke... |
jtmoulia/switchboard-python | examples/lamsonworker.py | main | python | def main(url, lamson_host, lamson_port, lamson_debug):
try:
worker = LamsonWorker(url=url,
lamson_host=lamson_host,
lamson_port=lamson_port,
lamson_debug=lamson_debug)
worker.connect()
worker.run_foreve... | Create, connect, and block on the Lamson worker. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/examples/lamsonworker.py#L47-L59 | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
This Switchboard worker delivers emails to Lamson.
"""
__author__ = u"Thomas Moulia <jtmoulia@pocketknife.io>"
__copyright__ = u"Copyright © 2014, ThusFresh Inc All rights reserved."
import switchboard
from lamson import server
import logging
logging.basicConfig(l... |
jtmoulia/switchboard-python | examples/lamsonworker.py | LamsonWorker.received_new | python | def received_new(self, msg):
logger.info("Receiving msg, delivering to Lamson...")
logger.debug("Relaying msg to lamson: From: %s, To: %s",
msg['From'], msg['To'])
self._relay.deliver(msg) | As new messages arrive, deliver them to the lamson relay. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/examples/lamsonworker.py#L37-L44 | null | class LamsonWorker(switchboard.Fetcher):
def __init__(self, lamson_host='127.0.0.1', lamson_port=8823, lamson_debug=0,
*args, **kwargs):
super(LamsonWorker, self).__init__(*args, **kwargs)
self._relay = server.Relay(lamson_host, port=lamson_port, debug=lamson_debug)
def opened... |
jtmoulia/switchboard-python | aplus/__init__.py | _isPromise | python | def _isPromise(obj):
return hasattr(obj, "fulfill") and \
_isFunction(getattr(obj, "fulfill")) and \
hasattr(obj, "reject") and \
_isFunction(getattr(obj, "reject")) and \
hasattr(obj, "then") and \
_isFunction(getattr(obj, "then")) | A utility function to determine if the specified
object is a promise using "duck typing". | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/aplus/__init__.py#L261-L271 | [
"def _isFunction(v):\n \"\"\"\n A utility function to determine if the specified\n value is a function.\n \"\"\"\n if v==None:\n return False\n if hasattr(v, \"__call__\"):\n return True\n return False\n"
] | from threading import Thread
class Promise:
"""
This is a class that attempts to comply with the
Promises/A+ specification and test suite:
http://promises-aplus.github.io/promises-spec/
"""
# These are the potential states of a promise
PENDING = -1
REJECTED = 0
FULFILLED = 1
... |
jtmoulia/switchboard-python | aplus/__init__.py | listPromise | python | def listPromise(*args):
ret = Promise()
def handleSuccess(v, ret):
for arg in args:
if not arg.isFulfilled():
return
value = map(lambda p: p.value, args)
ret.fulfill(value)
for arg in args:
arg.addCallback(lambda v: handleSuccess(v, ret))
... | A special function that takes a bunch of promises
and turns them into a promise for a vector of values.
In other words, this turns an list of promises for values
into a promise for a list of values. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/aplus/__init__.py#L273-L297 | [
"def handleSuccess(v, ret):\n for arg in args:\n if not arg.isFulfilled():\n return\n\n value = map(lambda p: p.value, args)\n ret.fulfill(value)\n"
] | from threading import Thread
class Promise:
"""
This is a class that attempts to comply with the
Promises/A+ specification and test suite:
http://promises-aplus.github.io/promises-spec/
"""
# These are the potential states of a promise
PENDING = -1
REJECTED = 0
FULFILLED = 1
... |
jtmoulia/switchboard-python | aplus/__init__.py | dictPromise | python | def dictPromise(m):
ret = Promise()
def handleSuccess(v, ret):
for p in m.values():
if not p.isFulfilled():
return
value = {}
for k in m:
value[k] = m[k].value
ret.fulfill(value)
for p in m.values():
p.addCallback(lambda v: h... | A special function that takes a dictionary of promises
and turns them into a promise for a dictionary of values.
In other words, this turns an dictionary of promises for values
into a promise for a dictionary of values. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/aplus/__init__.py#L299-L325 | [
"def handleSuccess(v, ret):\n for p in m.values():\n if not p.isFulfilled():\n return\n\n value = {}\n for k in m:\n value[k] = m[k].value\n ret.fulfill(value)\n"
] | from threading import Thread
class Promise:
"""
This is a class that attempts to comply with the
Promises/A+ specification and test suite:
http://promises-aplus.github.io/promises-spec/
"""
# These are the potential states of a promise
PENDING = -1
REJECTED = 0
FULFILLED = 1
... |
jtmoulia/switchboard-python | aplus/__init__.py | Promise.fulfill | python | def fulfill(self, value):
assert self._state==self.PENDING
self._state=self.FULFILLED;
self.value = value
for callback in self._callbacks:
try:
callback(value)
except Exception:
# Ignore errors in callbacks
pass
... | Fulfill the promise with a given value. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/aplus/__init__.py#L26-L45 | null | class Promise:
"""
This is a class that attempts to comply with the
Promises/A+ specification and test suite:
http://promises-aplus.github.io/promises-spec/
"""
# These are the potential states of a promise
PENDING = -1
REJECTED = 0
FULFILLED = 1
def __init__(self):
""... |
jtmoulia/switchboard-python | aplus/__init__.py | Promise.reject | python | def reject(self, reason):
assert self._state==self.PENDING
self._state=self.REJECTED;
self.reason = reason
for errback in self._errbacks:
try:
errback(reason)
except Exception:
# Ignore errors in callbacks
pass
... | Reject this promise for a given reason. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/aplus/__init__.py#L47-L66 | null | class Promise:
"""
This is a class that attempts to comply with the
Promises/A+ specification and test suite:
http://promises-aplus.github.io/promises-spec/
"""
# These are the potential states of a promise
PENDING = -1
REJECTED = 0
FULFILLED = 1
def __init__(self):
""... |
jtmoulia/switchboard-python | aplus/__init__.py | Promise.get | python | def get(self, timeout=None):
self.wait(timeout)
if self._state==self.FULFILLED:
return self.value
else:
raise ValueError("Calculation didn't yield a value") | Get the value of the promise, waiting if necessary. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/aplus/__init__.py#L80-L86 | [
"def wait(self, timeout=None):\n \"\"\"\n An implementation of the wait method which doesn't involve\n polling but instead utilizes a \"real\" synchronization\n scheme.\n \"\"\"\n import threading\n\n if self._state!=self.PENDING:\n return\n\n e = threading.Event()\n self.addCallba... | class Promise:
"""
This is a class that attempts to comply with the
Promises/A+ specification and test suite:
http://promises-aplus.github.io/promises-spec/
"""
# These are the potential states of a promise
PENDING = -1
REJECTED = 0
FULFILLED = 1
def __init__(self):
""... |
jtmoulia/switchboard-python | aplus/__init__.py | Promise.wait | python | def wait(self, timeout=None):
import threading
if self._state!=self.PENDING:
return
e = threading.Event()
self.addCallback(lambda v: e.set())
self.addErrback(lambda r: e.set())
e.wait(timeout) | An implementation of the wait method which doesn't involve
polling but instead utilizes a "real" synchronization
scheme. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/aplus/__init__.py#L88-L102 | [
"def addCallback(self, f):\n \"\"\"\n Add a callback for when this promis is fulfilled. Note that\n if you intend to use the value of the promise somehow in\n the callback, it is more convenient to use the 'then' method.\n \"\"\"\n self._callbacks.append(f)\n",
"def addErrback(self, f):\n \"... | class Promise:
"""
This is a class that attempts to comply with the
Promises/A+ specification and test suite:
http://promises-aplus.github.io/promises-spec/
"""
# These are the potential states of a promise
PENDING = -1
REJECTED = 0
FULFILLED = 1
def __init__(self):
""... |
jtmoulia/switchboard-python | aplus/__init__.py | Promise.then | python | def then(self, success=None, failure=None):
ret = Promise()
def callAndFulfill(v):
"""
A callback to be invoked if the "self promise"
is fulfilled.
"""
try:
# From 3.2.1, don't call non-functions values
if _isFu... | This method takes two optional arguments. The first argument
is used if the "self promise" is fulfilled and the other is
used if the "self promise" is rejected. In either case, this
method returns another promise that effectively represents
the result of either the first of the second ... | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/aplus/__init__.py#L121-L248 | [
"def _isFunction(v):\n \"\"\"\n A utility function to determine if the specified\n value is a function.\n \"\"\"\n if v==None:\n return False\n if hasattr(v, \"__call__\"):\n return True\n return False\n",
"def _isPromise(obj):\n \"\"\"\n A utility function to determine if... | class Promise:
"""
This is a class that attempts to comply with the
Promises/A+ specification and test suite:
http://promises-aplus.github.io/promises-spec/
"""
# These are the potential states of a promise
PENDING = -1
REJECTED = 0
FULFILLED = 1
def __init__(self):
""... |
jtmoulia/switchboard-python | examples/apnsworker.py | main | python | def main(cert, key, pushtoken, url):
try:
worker = APNSWorker(cert=cert, key=key, pushtoken=pushtoken, url=url)
worker.connect()
worker.run_forever()
except KeyboardInterrupt:
worker.close() | Create, connect, and block on the listener worker. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/examples/apnsworker.py#L94-L101 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
APNSWorker is a Switchboard worker that collects incoming emails,
uses them to create a push notification, and then sends them to
an iOS device.
./apnsworker.py --help
"""
__author__ = u"Thomas Moulia <jtmoulia@pocketknife.io>"
__copyright__ = u"Copyright © 2014,... |
jtmoulia/switchboard-python | examples/apnsworker.py | APNSWorker.opened | python | def opened(self):
def post_setup((cmds, resps)):
"""Post setup callback."""
logger.info("Setup complete, listening...")
self.send_cmds(('connect', CONN_SPEC),
('watchMailboxes', {'account': ACCOUNT,
'list': ['INBO... | Connect to the websocket, and ensure the account is connected and
the INBOX is being watched, and then start watchingAll. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/examples/apnsworker.py#L44-L55 | null | class APNSWorker(switchboard.Client):
"""A Switchboard worker that will listen for new emails across all
accounts. For each new email it wil fetch additional information,
form it into a push notification, and send it to the client.
"""
def __init__(self, cert, key, pushtoken=None, use_sandbox=True,... |
jtmoulia/switchboard-python | examples/twilioworker.py | main | python | def main(sid, token, to, from_, url):
try:
worker = APNSWorker(sid=sid, token=token, to=to, from_=from_, url=url)
worker.connect()
worker.run_forever()
except KeyboardInterrupt:
worker.close() | Create, connect, and block on the listener worker. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/examples/twilioworker.py#L78-L85 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A worker which collects messages from Switchboard and sends a text
message via Twilio to the provided mobile number.
./twilioworker.py --help
"""
__author__ = u"Thomas Moulia <jtmoulia@pocketknife.io>"
__copyright__ = u"Copyright © 2014, ThusFresh, Inc. All rights ... |
jtmoulia/switchboard-python | switchboard/__init__.py | _take | python | def _take(d, key, default=None):
if key in d:
cmd = d[key]
del d[key]
return cmd
else:
return default | If the key is present in dictionary, remove it and return it's
value. If it is not present, return None. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/switchboard/__init__.py#L141-L151 | null | # -*- coding: utf-8 -*-
"""
A Switchboard worker/client implementation.
"""
__author__ = u"Thomas Moulia <jtmoulia@pocketknife.io>"
__copyright__ = u"Copyright © 2014, ThusFresh, Inc. All rights reserved."
from ws4py.client.threadedclient import WebSocketClient
import aplus
import json
import email
import logging
... |
jtmoulia/switchboard-python | switchboard/__init__.py | _get_cmds_id | python | def _get_cmds_id(*cmds):
tags = [cmd[2] if len(cmd) == 3 else None for cmd in cmds]
if [tag for tag in tags if tag != None]:
return tuple(tags)
else:
return None | Returns an identifier for a group of partially tagged commands.
If there are no tagged commands, returns None. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/switchboard/__init__.py#L154-L163 | null | # -*- coding: utf-8 -*-
"""
A Switchboard worker/client implementation.
"""
__author__ = u"Thomas Moulia <jtmoulia@pocketknife.io>"
__copyright__ = u"Copyright © 2014, ThusFresh, Inc. All rights reserved."
from ws4py.client.threadedclient import WebSocketClient
import aplus
import json
import email
import logging
... |
jtmoulia/switchboard-python | switchboard/__init__.py | Client.received_message | python | def received_message(self, msg):
logger.debug("Received message: %s", msg)
if msg.is_binary:
raise ValueError("Binary messages not supported")
resps = json.loads(msg.data)
cmd_group = _get_cmds_id(*resps)
if cmd_group:
(cmds, promise) = self._cmd_groups[c... | Handle receiving a message by checking whether it is in response
to a command or unsolicited, and dispatching it to the appropriate
object method. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/switchboard/__init__.py#L46-L66 | [
"def _get_cmds_id(*cmds):\n \"\"\"\n Returns an identifier for a group of partially tagged commands.\n If there are no tagged commands, returns None.\n \"\"\"\n tags = [cmd[2] if len(cmd) == 3 else None for cmd in cmds]\n if [tag for tag in tags if tag != None]:\n return tuple(tags)\n el... | class Client(WebSocketClient):
"""
Base behavior shared between workers and clients.
"""
def __init__(self, *args, **kwargs):
super(Client, self).__init__(*args, **kwargs)
self._tag = 0
self._cmd_groups = {}
# WebSocketClient Hooks
# ---------------------
def opene... |
jtmoulia/switchboard-python | switchboard/__init__.py | Client._tag_cmds | python | def _tag_cmds(self, *cmds):
for (method, args) in cmds:
tagged_cmd = [method, args, self._tag]
self._tag = self._tag + 1
yield tagged_cmd | Yields tagged commands. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/switchboard/__init__.py#L80-L87 | null | class Client(WebSocketClient):
"""
Base behavior shared between workers and clients.
"""
def __init__(self, *args, **kwargs):
super(Client, self).__init__(*args, **kwargs)
self._tag = 0
self._cmd_groups = {}
# WebSocketClient Hooks
# ---------------------
def opene... |
jtmoulia/switchboard-python | switchboard/__init__.py | Client.send_cmds | python | def send_cmds(self, *cmds):
promise = aplus.Promise()
tagged_cmds = list(self._tag_cmds(*cmds))
logger.debug("Sending cmds: %s", tagged_cmds)
cmd_group = _get_cmds_id(*tagged_cmds)
self._cmd_groups[cmd_group] = (tagged_cmds, promise)
self.send(json.dumps(tagged_cmds))
... | Tags and sends the commands to the Switchboard server, returning
None.
Each cmd be a 2-tuple where the first element is the method name,
and the second is the arguments, e.g. ("connect", {"host": ...}). | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/switchboard/__init__.py#L89-L104 | [
"def _get_cmds_id(*cmds):\n \"\"\"\n Returns an identifier for a group of partially tagged commands.\n If there are no tagged commands, returns None.\n \"\"\"\n tags = [cmd[2] if len(cmd) == 3 else None for cmd in cmds]\n if [tag for tag in tags if tag != None]:\n return tuple(tags)\n el... | class Client(WebSocketClient):
"""
Base behavior shared between workers and clients.
"""
def __init__(self, *args, **kwargs):
super(Client, self).__init__(*args, **kwargs)
self._tag = 0
self._cmd_groups = {}
# WebSocketClient Hooks
# ---------------------
def opene... |
jtmoulia/switchboard-python | examples/listener.py | main | python | def main(url):
try:
listener = ListenerWorker(url)
listener.connect()
listener.run_forever()
except KeyboardInterrupt:
listener.close() | Create, connect, and block on the listener worker. | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/examples/listener.py#L59-L66 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
__author__ = u"Thomas Moulia <jtmoulia@pocketknife.io>"
__copyright__ = u"Copyright © 2014, ThusFresh, Inc. All rights reserved."
import switchboard
import thread
import email
import argparse
import logging
logging.basicConfig(level=logging.INFO)
logger = loggi... |
jhermann/rudiments | src/rudiments/security.py | Credentials.auth_pair | python | def auth_pair(self, force_console=False):
if not self.auth_valid():
self._get_auth(force_console)
return (self.user, self.password) | Return username/password tuple, possibly prompting the user for them. | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/security.py#L56-L60 | [
"def auth_valid(self):\n \"\"\"Return bool indicating whether full credentials were provided.\"\"\"\n return bool(self.user and self.password)\n"
] | class Credentials(object):
"""Look up and provide authN credentials (username / password) from common sources."""
URL_RE = re.compile(r'^(http|https|ftp|ftps)://') # covers the common use cases
NETRC_FILE = None # use the default, unless changed for test purposes
AUTH_MEMOIZE_INPUT = {} # remember m... |
jhermann/rudiments | src/rudiments/security.py | Credentials._get_auth | python | def _get_auth(self, force_console=False):
if not self.target:
raise ValueError("Unspecified target ({!r})".format(self.target))
elif not force_console and self.URL_RE.match(self.target):
auth_url = urlparse(self.target)
source = 'url'
if auth_url.username:... | Try to get login auth from known sources. | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/security.py#L66-L87 | null | class Credentials(object):
"""Look up and provide authN credentials (username / password) from common sources."""
URL_RE = re.compile(r'^(http|https|ftp|ftps)://') # covers the common use cases
NETRC_FILE = None # use the default, unless changed for test purposes
AUTH_MEMOIZE_INPUT = {} # remember m... |
jhermann/rudiments | src/rudiments/security.py | Credentials._get_auth_from_console | python | def _get_auth_from_console(self, realm):
self.user, self.password = self.AUTH_MEMOIZE_INPUT.get(realm, (self.user, None))
if not self.auth_valid():
if not self.user:
login = getpass.getuser()
self.user = self._raw_input('Username for "{}" [{}]: '.format(realm,... | Prompt for the user and password. | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/security.py#L89-L99 | null | class Credentials(object):
"""Look up and provide authN credentials (username / password) from common sources."""
URL_RE = re.compile(r'^(http|https|ftp|ftps)://') # covers the common use cases
NETRC_FILE = None # use the default, unless changed for test purposes
AUTH_MEMOIZE_INPUT = {} # remember m... |
jhermann/rudiments | src/rudiments/security.py | Credentials._get_auth_from_netrc | python | def _get_auth_from_netrc(self, hostname):
try:
hostauth = netrc(self.NETRC_FILE)
except IOError as cause:
if cause.errno != errno.ENOENT:
raise
return None
except NetrcParseError as cause:
raise # TODO: Map to common base class, so... | Try to find login auth in ``~/.netrc``. | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/security.py#L101-L127 | null | class Credentials(object):
"""Look up and provide authN credentials (username / password) from common sources."""
URL_RE = re.compile(r'^(http|https|ftp|ftps)://') # covers the common use cases
NETRC_FILE = None # use the default, unless changed for test purposes
AUTH_MEMOIZE_INPUT = {} # remember m... |
jhermann/rudiments | src/rudiments/security.py | Credentials._get_auth_from_keyring | python | def _get_auth_from_keyring(self):
if not keyring:
return None
# Take user from URL if available, else the OS login name
password = self._get_password_from_keyring(self.user or getpass.getuser())
if password is not None:
self.user = self.user or getpass.getuser()
... | Try to get credentials using `keyring <https://github.com/jaraco/keyring>`_. | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/security.py#L133-L144 | null | class Credentials(object):
"""Look up and provide authN credentials (username / password) from common sources."""
URL_RE = re.compile(r'^(http|https|ftp|ftps)://') # covers the common use cases
NETRC_FILE = None # use the default, unless changed for test purposes
AUTH_MEMOIZE_INPUT = {} # remember m... |
jhermann/rudiments | src/rudiments/reamed/click.py | pretty_path | python | def pretty_path(path, _home_re=re.compile('^' + re.escape(os.path.expanduser('~') + os.sep))):
path = format_filename(path)
path = _home_re.sub('~' + os.sep, path)
return path | Prettify path for humans, and make it Unicode. | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/reamed/click.py#L39-L43 | null | # -*- coding: utf-8 -*-
# pylint: disable=bad-continuation
""" ‘Double Click’ – Extensions to `Click <http://click.pocoo.org/4/>`_.
"""
# Copyright © 2015 Jürgen Hermann <jh@web.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# ... |
jhermann/rudiments | src/rudiments/reamed/click.py | serror | python | def serror(message, *args, **kwargs):
if args or kwargs:
message = message.format(*args, **kwargs)
return secho(message, fg='white', bg='red', bold=True) | Print a styled error message, while using any arguments to format the message. | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/reamed/click.py#L46-L50 | null | # -*- coding: utf-8 -*-
# pylint: disable=bad-continuation
""" ‘Double Click’ – Extensions to `Click <http://click.pocoo.org/4/>`_.
"""
# Copyright © 2015 Jürgen Hermann <jh@web.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# ... |
jhermann/rudiments | src/rudiments/reamed/click.py | AliasedGroup.get_command | python | def get_command(self, ctx, cmd_name):
cmd_name = self.MAP.get(cmd_name, cmd_name)
return super(AliasedGroup, self).get_command(ctx, cmd_name) | Map some aliases to their 'real' names. | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/reamed/click.py#L72-L75 | null | class AliasedGroup(Group):
""" A command group with alias names.
Inherit from this class and define a ``MAP`` class variable,
which is a mapping from alias names to canonical command names.
Then use that derived class as the ``cls`` parameter for a
``click.group`` decorator.
"""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.