id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
26,700
juju/python-libjuju
juju/client/connection.py
_macaroons_for_domain
def _macaroons_for_domain(cookies, domain): '''Return any macaroons from the given cookie jar that apply to the given domain name.''' req = urllib.request.Request('https://' + domain + '/') cookies.add_cookie_header(req) return httpbakery.extract_macaroons(req)
python
def _macaroons_for_domain(cookies, domain): '''Return any macaroons from the given cookie jar that apply to the given domain name.''' req = urllib.request.Request('https://' + domain + '/') cookies.add_cookie_header(req) return httpbakery.extract_macaroons(req)
[ "def", "_macaroons_for_domain", "(", "cookies", ",", "domain", ")", ":", "req", "=", "urllib", ".", "request", ".", "Request", "(", "'https://'", "+", "domain", "+", "'/'", ")", "cookies", ".", "add_cookie_header", "(", "req", ")", "return", "httpbakery", ...
Return any macaroons from the given cookie jar that apply to the given domain name.
[ "Return", "any", "macaroons", "from", "the", "given", "cookie", "jar", "that", "apply", "to", "the", "given", "domain", "name", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L596-L601
26,701
juju/python-libjuju
juju/client/connection.py
Monitor.status
def status(self): """ Determine the status of the connection and receiver, and return ERROR, CONNECTED, or DISCONNECTED as appropriate. For simplicity, we only consider ourselves to be connected after the Connection class has setup a receiver task. This only happens after the websocket is open, and the connection isn't usable until that receiver has been started. """ connection = self.connection() # the connection instance was destroyed but someone kept # a separate reference to the monitor for some reason if not connection: return self.DISCONNECTED # connection cleanly disconnected or not yet opened if not connection.ws: return self.DISCONNECTED # close called but not yet complete if self.close_called.is_set(): return self.DISCONNECTING # connection closed uncleanly (we didn't call connection.close) stopped = connection._receiver_task.stopped.is_set() if stopped or not connection.ws.open: return self.ERROR # everything is fine! return self.CONNECTED
python
def status(self): connection = self.connection() # the connection instance was destroyed but someone kept # a separate reference to the monitor for some reason if not connection: return self.DISCONNECTED # connection cleanly disconnected or not yet opened if not connection.ws: return self.DISCONNECTED # close called but not yet complete if self.close_called.is_set(): return self.DISCONNECTING # connection closed uncleanly (we didn't call connection.close) stopped = connection._receiver_task.stopped.is_set() if stopped or not connection.ws.open: return self.ERROR # everything is fine! return self.CONNECTED
[ "def", "status", "(", "self", ")", ":", "connection", "=", "self", ".", "connection", "(", ")", "# the connection instance was destroyed but someone kept", "# a separate reference to the monitor for some reason", "if", "not", "connection", ":", "return", "self", ".", "DIS...
Determine the status of the connection and receiver, and return ERROR, CONNECTED, or DISCONNECTED as appropriate. For simplicity, we only consider ourselves to be connected after the Connection class has setup a receiver task. This only happens after the websocket is open, and the connection isn't usable until that receiver has been started.
[ "Determine", "the", "status", "of", "the", "connection", "and", "receiver", "and", "return", "ERROR", "CONNECTED", "or", "DISCONNECTED", "as", "appropriate", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L46-L78
26,702
juju/python-libjuju
juju/client/connection.py
Connection._pinger
async def _pinger(self): ''' A Controller can time us out if we are silent for too long. This is especially true in JaaS, which has a fairly strict timeout. To prevent timing out, we send a ping every ten seconds. ''' async def _do_ping(): try: await pinger_facade.Ping() await asyncio.sleep(10, loop=self.loop) except CancelledError: pass pinger_facade = client.PingerFacade.from_connection(self) try: while True: await utils.run_with_interrupt( _do_ping(), self.monitor.close_called, loop=self.loop) if self.monitor.close_called.is_set(): break except websockets.exceptions.ConnectionClosed: # The connection has closed - we can't do anything # more until the connection is restarted. log.debug('ping failed because of closed connection') pass
python
async def _pinger(self): ''' A Controller can time us out if we are silent for too long. This is especially true in JaaS, which has a fairly strict timeout. To prevent timing out, we send a ping every ten seconds. ''' async def _do_ping(): try: await pinger_facade.Ping() await asyncio.sleep(10, loop=self.loop) except CancelledError: pass pinger_facade = client.PingerFacade.from_connection(self) try: while True: await utils.run_with_interrupt( _do_ping(), self.monitor.close_called, loop=self.loop) if self.monitor.close_called.is_set(): break except websockets.exceptions.ConnectionClosed: # The connection has closed - we can't do anything # more until the connection is restarted. log.debug('ping failed because of closed connection') pass
[ "async", "def", "_pinger", "(", "self", ")", ":", "async", "def", "_do_ping", "(", ")", ":", "try", ":", "await", "pinger_facade", ".", "Ping", "(", ")", "await", "asyncio", ".", "sleep", "(", "10", ",", "loop", "=", "self", ".", "loop", ")", "exce...
A Controller can time us out if we are silent for too long. This is especially true in JaaS, which has a fairly strict timeout. To prevent timing out, we send a ping every ten seconds.
[ "A", "Controller", "can", "time", "us", "out", "if", "we", "are", "silent", "for", "too", "long", ".", "This", "is", "especially", "true", "in", "JaaS", "which", "has", "a", "fairly", "strict", "timeout", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L250-L278
26,703
juju/python-libjuju
juju/client/connection.py
Connection._http_headers
def _http_headers(self): """Return dictionary of http headers necessary for making an http connection to the endpoint of this Connection. :return: Dictionary of headers """ if not self.usertag: return {} creds = u'{}:{}'.format( self.usertag, self.password or '' ) token = base64.b64encode(creds.encode()) return { 'Authorization': 'Basic {}'.format(token.decode()) }
python
def _http_headers(self): if not self.usertag: return {} creds = u'{}:{}'.format( self.usertag, self.password or '' ) token = base64.b64encode(creds.encode()) return { 'Authorization': 'Basic {}'.format(token.decode()) }
[ "def", "_http_headers", "(", "self", ")", ":", "if", "not", "self", ".", "usertag", ":", "return", "{", "}", "creds", "=", "u'{}:{}'", ".", "format", "(", "self", ".", "usertag", ",", "self", ".", "password", "or", "''", ")", "token", "=", "base64", ...
Return dictionary of http headers necessary for making an http connection to the endpoint of this Connection. :return: Dictionary of headers
[ "Return", "dictionary", "of", "http", "headers", "necessary", "for", "making", "an", "http", "connection", "to", "the", "endpoint", "of", "this", "Connection", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L350-L367
26,704
juju/python-libjuju
juju/client/connection.py
Connection.https_connection
def https_connection(self): """Return an https connection to this Connection's endpoint. Returns a 3-tuple containing:: 1. The :class:`HTTPSConnection` instance 2. Dictionary of auth headers to be used with the connection 3. The root url path (str) to be used for requests. """ endpoint = self.endpoint host, remainder = endpoint.split(':', 1) port = remainder if '/' in remainder: port, _ = remainder.split('/', 1) conn = HTTPSConnection( host, int(port), context=self._get_ssl(self.cacert), ) path = ( "/model/{}".format(self.uuid) if self.uuid else "" ) return conn, self._http_headers(), path
python
def https_connection(self): endpoint = self.endpoint host, remainder = endpoint.split(':', 1) port = remainder if '/' in remainder: port, _ = remainder.split('/', 1) conn = HTTPSConnection( host, int(port), context=self._get_ssl(self.cacert), ) path = ( "/model/{}".format(self.uuid) if self.uuid else "" ) return conn, self._http_headers(), path
[ "def", "https_connection", "(", "self", ")", ":", "endpoint", "=", "self", ".", "endpoint", "host", ",", "remainder", "=", "endpoint", ".", "split", "(", "':'", ",", "1", ")", "port", "=", "remainder", "if", "'/'", "in", "remainder", ":", "port", ",", ...
Return an https connection to this Connection's endpoint. Returns a 3-tuple containing:: 1. The :class:`HTTPSConnection` instance 2. Dictionary of auth headers to be used with the connection 3. The root url path (str) to be used for requests.
[ "Return", "an", "https", "connection", "to", "this", "Connection", "s", "endpoint", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L369-L394
26,705
juju/python-libjuju
juju/client/connection.py
Connection.connect_params
def connect_params(self): """Return a tuple of parameters suitable for passing to Connection.connect that can be used to make a new connection to the same controller (and model if specified. The first element in the returned tuple holds the endpoint argument; the other holds a dict of the keyword args. """ return { 'endpoint': self.endpoint, 'uuid': self.uuid, 'username': self.username, 'password': self.password, 'cacert': self.cacert, 'bakery_client': self.bakery_client, 'loop': self.loop, 'max_frame_size': self.max_frame_size, }
python
def connect_params(self): return { 'endpoint': self.endpoint, 'uuid': self.uuid, 'username': self.username, 'password': self.password, 'cacert': self.cacert, 'bakery_client': self.bakery_client, 'loop': self.loop, 'max_frame_size': self.max_frame_size, }
[ "def", "connect_params", "(", "self", ")", ":", "return", "{", "'endpoint'", ":", "self", ".", "endpoint", ",", "'uuid'", ":", "self", ".", "uuid", ",", "'username'", ":", "self", ".", "username", ",", "'password'", ":", "self", ".", "password", ",", "...
Return a tuple of parameters suitable for passing to Connection.connect that can be used to make a new connection to the same controller (and model if specified. The first element in the returned tuple holds the endpoint argument; the other holds a dict of the keyword args.
[ "Return", "a", "tuple", "of", "parameters", "suitable", "for", "passing", "to", "Connection", ".", "connect", "that", "can", "be", "used", "to", "make", "a", "new", "connection", "to", "the", "same", "controller", "(", "and", "model", "if", "specified", "....
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L403-L419
26,706
juju/python-libjuju
juju/client/connection.py
Connection.controller
async def controller(self): """Return a Connection to the controller at self.endpoint """ return await Connection.connect( self.endpoint, username=self.username, password=self.password, cacert=self.cacert, bakery_client=self.bakery_client, loop=self.loop, max_frame_size=self.max_frame_size, )
python
async def controller(self): return await Connection.connect( self.endpoint, username=self.username, password=self.password, cacert=self.cacert, bakery_client=self.bakery_client, loop=self.loop, max_frame_size=self.max_frame_size, )
[ "async", "def", "controller", "(", "self", ")", ":", "return", "await", "Connection", ".", "connect", "(", "self", ".", "endpoint", ",", "username", "=", "self", ".", "username", ",", "password", "=", "self", ".", "password", ",", "cacert", "=", "self", ...
Return a Connection to the controller at self.endpoint
[ "Return", "a", "Connection", "to", "the", "controller", "at", "self", ".", "endpoint" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L421-L432
26,707
juju/python-libjuju
juju/client/connection.py
Connection.reconnect
async def reconnect(self): """ Force a reconnection. """ monitor = self.monitor if monitor.reconnecting.locked() or monitor.close_called.is_set(): return async with monitor.reconnecting: await self.close() await self._connect_with_login([(self.endpoint, self.cacert)])
python
async def reconnect(self): monitor = self.monitor if monitor.reconnecting.locked() or monitor.close_called.is_set(): return async with monitor.reconnecting: await self.close() await self._connect_with_login([(self.endpoint, self.cacert)])
[ "async", "def", "reconnect", "(", "self", ")", ":", "monitor", "=", "self", ".", "monitor", "if", "monitor", ".", "reconnecting", ".", "locked", "(", ")", "or", "monitor", ".", "close_called", ".", "is_set", "(", ")", ":", "return", "async", "with", "m...
Force a reconnection.
[ "Force", "a", "reconnection", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connection.py#L434-L442
26,708
juju/python-libjuju
juju/client/connector.py
Connector.connect
async def connect(self, **kwargs): """Connect to an arbitrary Juju model. kwargs are passed through to Connection.connect() """ kwargs.setdefault('loop', self.loop) kwargs.setdefault('max_frame_size', self.max_frame_size) kwargs.setdefault('bakery_client', self.bakery_client) if 'macaroons' in kwargs: if not kwargs['bakery_client']: kwargs['bakery_client'] = httpbakery.Client() if not kwargs['bakery_client'].cookies: kwargs['bakery_client'].cookies = GoCookieJar() jar = kwargs['bakery_client'].cookies for macaroon in kwargs.pop('macaroons'): jar.set_cookie(go_to_py_cookie(macaroon)) self._connection = await Connection.connect(**kwargs)
python
async def connect(self, **kwargs): kwargs.setdefault('loop', self.loop) kwargs.setdefault('max_frame_size', self.max_frame_size) kwargs.setdefault('bakery_client', self.bakery_client) if 'macaroons' in kwargs: if not kwargs['bakery_client']: kwargs['bakery_client'] = httpbakery.Client() if not kwargs['bakery_client'].cookies: kwargs['bakery_client'].cookies = GoCookieJar() jar = kwargs['bakery_client'].cookies for macaroon in kwargs.pop('macaroons'): jar.set_cookie(go_to_py_cookie(macaroon)) self._connection = await Connection.connect(**kwargs)
[ "async", "def", "connect", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'loop'", ",", "self", ".", "loop", ")", "kwargs", ".", "setdefault", "(", "'max_frame_size'", ",", "self", ".", "max_frame_size", ")", "kwargs",...
Connect to an arbitrary Juju model. kwargs are passed through to Connection.connect()
[ "Connect", "to", "an", "arbitrary", "Juju", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connector.py#L52-L68
26,709
juju/python-libjuju
juju/client/connector.py
Connector.connect_controller
async def connect_controller(self, controller_name=None): """Connect to a controller by name. If the name is empty, it connect to the current controller. """ if not controller_name: controller_name = self.jujudata.current_controller() if not controller_name: raise JujuConnectionError('No current controller') controller = self.jujudata.controllers()[controller_name] # TODO change Connection so we can pass all the endpoints # instead of just the first. endpoint = controller['api-endpoints'][0] accounts = self.jujudata.accounts().get(controller_name, {}) await self.connect( endpoint=endpoint, uuid=None, username=accounts.get('user'), password=accounts.get('password'), cacert=controller.get('ca-cert'), bakery_client=self.bakery_client_for_controller(controller_name), ) self.controller_name = controller_name
python
async def connect_controller(self, controller_name=None): if not controller_name: controller_name = self.jujudata.current_controller() if not controller_name: raise JujuConnectionError('No current controller') controller = self.jujudata.controllers()[controller_name] # TODO change Connection so we can pass all the endpoints # instead of just the first. endpoint = controller['api-endpoints'][0] accounts = self.jujudata.accounts().get(controller_name, {}) await self.connect( endpoint=endpoint, uuid=None, username=accounts.get('user'), password=accounts.get('password'), cacert=controller.get('ca-cert'), bakery_client=self.bakery_client_for_controller(controller_name), ) self.controller_name = controller_name
[ "async", "def", "connect_controller", "(", "self", ",", "controller_name", "=", "None", ")", ":", "if", "not", "controller_name", ":", "controller_name", "=", "self", ".", "jujudata", ".", "current_controller", "(", ")", "if", "not", "controller_name", ":", "r...
Connect to a controller by name. If the name is empty, it connect to the current controller.
[ "Connect", "to", "a", "controller", "by", "name", ".", "If", "the", "name", "is", "empty", "it", "connect", "to", "the", "current", "controller", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connector.py#L78-L101
26,710
juju/python-libjuju
juju/client/connector.py
Connector.bakery_client_for_controller
def bakery_client_for_controller(self, controller_name): '''Make a copy of the bakery client with a the appropriate controller's cookiejar in it. ''' bakery_client = self.bakery_client if bakery_client: bakery_client = copy.copy(bakery_client) else: bakery_client = httpbakery.Client() bakery_client.cookies = self.jujudata.cookies_for_controller( controller_name) return bakery_client
python
def bakery_client_for_controller(self, controller_name): '''Make a copy of the bakery client with a the appropriate controller's cookiejar in it. ''' bakery_client = self.bakery_client if bakery_client: bakery_client = copy.copy(bakery_client) else: bakery_client = httpbakery.Client() bakery_client.cookies = self.jujudata.cookies_for_controller( controller_name) return bakery_client
[ "def", "bakery_client_for_controller", "(", "self", ",", "controller_name", ")", ":", "bakery_client", "=", "self", ".", "bakery_client", "if", "bakery_client", ":", "bakery_client", "=", "copy", ".", "copy", "(", "bakery_client", ")", "else", ":", "bakery_client"...
Make a copy of the bakery client with a the appropriate controller's cookiejar in it.
[ "Make", "a", "copy", "of", "the", "bakery", "client", "with", "a", "the", "appropriate", "controller", "s", "cookiejar", "in", "it", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connector.py#L145-L156
26,711
juju/python-libjuju
juju/provisioner.py
SSHProvisioner._get_ssh_client
def _get_ssh_client(self, host, user, key): """Return a connected Paramiko ssh object. :param str host: The host to connect to. :param str user: The user to connect as. :param str key: The private key to authenticate with. :return: object: A paramiko.SSHClient :raises: :class:`paramiko.ssh_exception.SSHException` if the connection failed """ ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) pkey = None # Read the private key into a paramiko.RSAKey if os.path.exists(key): with open(key, 'r') as f: pkey = paramiko.RSAKey.from_private_key(f) ####################################################################### # There is a bug in some versions of OpenSSH 4.3 (CentOS/RHEL5) where # # the server may not send the SSH_MSG_USERAUTH_BANNER message except # # when responding to an auth_none request. For example, paramiko will # # attempt to use password authentication when a password is set, but # # the server could deny that, instead requesting keyboard-interactive.# # The hack to workaround this is to attempt a reconnect, which will # # receive the right banner, and authentication can proceed. See the # # following for more info: # # https://github.com/paramiko/paramiko/issues/432 # # https://github.com/paramiko/paramiko/pull/438 # ####################################################################### try: ssh.connect(host, port=22, username=user, pkey=pkey) except paramiko.ssh_exception.SSHException as e: if 'Error reading SSH protocol banner' == str(e): # Once more, with feeling ssh.connect(host, port=22, username=user, pkey=pkey) else: # Reraise the original exception raise e return ssh
python
def _get_ssh_client(self, host, user, key): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) pkey = None # Read the private key into a paramiko.RSAKey if os.path.exists(key): with open(key, 'r') as f: pkey = paramiko.RSAKey.from_private_key(f) ####################################################################### # There is a bug in some versions of OpenSSH 4.3 (CentOS/RHEL5) where # # the server may not send the SSH_MSG_USERAUTH_BANNER message except # # when responding to an auth_none request. For example, paramiko will # # attempt to use password authentication when a password is set, but # # the server could deny that, instead requesting keyboard-interactive.# # The hack to workaround this is to attempt a reconnect, which will # # receive the right banner, and authentication can proceed. See the # # following for more info: # # https://github.com/paramiko/paramiko/issues/432 # # https://github.com/paramiko/paramiko/pull/438 # ####################################################################### try: ssh.connect(host, port=22, username=user, pkey=pkey) except paramiko.ssh_exception.SSHException as e: if 'Error reading SSH protocol banner' == str(e): # Once more, with feeling ssh.connect(host, port=22, username=user, pkey=pkey) else: # Reraise the original exception raise e return ssh
[ "def", "_get_ssh_client", "(", "self", ",", "host", ",", "user", ",", "key", ")", ":", "ssh", "=", "paramiko", ".", "SSHClient", "(", ")", "ssh", ".", "set_missing_host_key_policy", "(", "paramiko", ".", "AutoAddPolicy", "(", ")", ")", "pkey", "=", "None...
Return a connected Paramiko ssh object. :param str host: The host to connect to. :param str user: The user to connect as. :param str key: The private key to authenticate with. :return: object: A paramiko.SSHClient :raises: :class:`paramiko.ssh_exception.SSHException` if the connection failed
[ "Return", "a", "connected", "Paramiko", "ssh", "object", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/provisioner.py#L72-L117
26,712
juju/python-libjuju
juju/provisioner.py
SSHProvisioner._run_command
def _run_command(self, ssh, cmd, pty=True): """Run a command remotely via SSH. :param object ssh: The SSHClient :param str cmd: The command to execute :param list cmd: The `shlex.split` command to execute :param bool pty: Whether to allocate a pty :return: tuple: The stdout and stderr of the command execution :raises: :class:`CalledProcessError` if the command fails """ if isinstance(cmd, str): cmd = shlex.split(cmd) if type(cmd) is not list: cmd = [cmd] cmds = ' '.join(cmd) stdin, stdout, stderr = ssh.exec_command(cmds, get_pty=pty) retcode = stdout.channel.recv_exit_status() if retcode > 0: output = stderr.read().strip() raise CalledProcessError(returncode=retcode, cmd=cmd, output=output) return ( stdout.read().decode('utf-8').strip(), stderr.read().decode('utf-8').strip() )
python
def _run_command(self, ssh, cmd, pty=True): if isinstance(cmd, str): cmd = shlex.split(cmd) if type(cmd) is not list: cmd = [cmd] cmds = ' '.join(cmd) stdin, stdout, stderr = ssh.exec_command(cmds, get_pty=pty) retcode = stdout.channel.recv_exit_status() if retcode > 0: output = stderr.read().strip() raise CalledProcessError(returncode=retcode, cmd=cmd, output=output) return ( stdout.read().decode('utf-8').strip(), stderr.read().decode('utf-8').strip() )
[ "def", "_run_command", "(", "self", ",", "ssh", ",", "cmd", ",", "pty", "=", "True", ")", ":", "if", "isinstance", "(", "cmd", ",", "str", ")", ":", "cmd", "=", "shlex", ".", "split", "(", "cmd", ")", "if", "type", "(", "cmd", ")", "is", "not",...
Run a command remotely via SSH. :param object ssh: The SSHClient :param str cmd: The command to execute :param list cmd: The `shlex.split` command to execute :param bool pty: Whether to allocate a pty :return: tuple: The stdout and stderr of the command execution :raises: :class:`CalledProcessError` if the command fails
[ "Run", "a", "command", "remotely", "via", "SSH", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/provisioner.py#L119-L148
26,713
juju/python-libjuju
juju/provisioner.py
SSHProvisioner._init_ubuntu_user
def _init_ubuntu_user(self): """Initialize the ubuntu user. :return: bool: If the initialization was successful :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the authentication fails """ # TODO: Test this on an image without the ubuntu user setup. auth_user = self.user ssh = None try: # Run w/o allocating a pty, so we fail if sudo prompts for a passwd ssh = self._get_ssh_client( self.host, "ubuntu", self.private_key_path, ) stdout, stderr = self._run_command(ssh, "sudo -n true", pty=False) except paramiko.ssh_exception.AuthenticationException as e: raise e else: auth_user = "ubuntu" finally: if ssh: ssh.close() # if the above fails, run the init script as the authenticated user # Infer the public key public_key = None public_key_path = "{}.pub".format(self.private_key_path) if not os.path.exists(public_key_path): raise FileNotFoundError( "Public key '{}' doesn't exist.".format(public_key_path) ) with open(public_key_path, "r") as f: public_key = f.readline() script = INITIALIZE_UBUNTU_SCRIPT.format(public_key) try: ssh = self._get_ssh_client( self.host, auth_user, self.private_key_path, ) self._run_command( ssh, ["sudo", "/bin/bash -c " + shlex.quote(script)], pty=True ) except paramiko.ssh_exception.AuthenticationException as e: raise e finally: ssh.close() return True
python
def _init_ubuntu_user(self): # TODO: Test this on an image without the ubuntu user setup. auth_user = self.user ssh = None try: # Run w/o allocating a pty, so we fail if sudo prompts for a passwd ssh = self._get_ssh_client( self.host, "ubuntu", self.private_key_path, ) stdout, stderr = self._run_command(ssh, "sudo -n true", pty=False) except paramiko.ssh_exception.AuthenticationException as e: raise e else: auth_user = "ubuntu" finally: if ssh: ssh.close() # if the above fails, run the init script as the authenticated user # Infer the public key public_key = None public_key_path = "{}.pub".format(self.private_key_path) if not os.path.exists(public_key_path): raise FileNotFoundError( "Public key '{}' doesn't exist.".format(public_key_path) ) with open(public_key_path, "r") as f: public_key = f.readline() script = INITIALIZE_UBUNTU_SCRIPT.format(public_key) try: ssh = self._get_ssh_client( self.host, auth_user, self.private_key_path, ) self._run_command( ssh, ["sudo", "/bin/bash -c " + shlex.quote(script)], pty=True ) except paramiko.ssh_exception.AuthenticationException as e: raise e finally: ssh.close() return True
[ "def", "_init_ubuntu_user", "(", "self", ")", ":", "# TODO: Test this on an image without the ubuntu user setup.", "auth_user", "=", "self", ".", "user", "ssh", "=", "None", "try", ":", "# Run w/o allocating a pty, so we fail if sudo prompts for a passwd", "ssh", "=", "self",...
Initialize the ubuntu user. :return: bool: If the initialization was successful :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the authentication fails
[ "Initialize", "the", "ubuntu", "user", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/provisioner.py#L150-L212
26,714
juju/python-libjuju
juju/provisioner.py
SSHProvisioner._detect_hardware_and_os
def _detect_hardware_and_os(self, ssh): """Detect the target hardware capabilities and OS series. :param object ssh: The SSHClient :return: str: A raw string containing OS and hardware information. """ info = { 'series': '', 'arch': '', 'cpu-cores': '', 'mem': '', } stdout, stderr = self._run_command( ssh, ["sudo", "/bin/bash -c " + shlex.quote(DETECTION_SCRIPT)], pty=True, ) lines = stdout.split("\n") info['series'] = lines[0].strip() info['arch'] = normalize_arch(lines[1].strip()) memKb = re.split(r'\s+', lines[2])[1] # Convert megabytes -> kilobytes info['mem'] = round(int(memKb) / 1024) # Detect available CPUs recorded = {} for line in lines[3:]: physical_id = "" print(line) if line.find("physical id") == 0: physical_id = line.split(":")[1].strip() elif line.find("cpu cores") == 0: cores = line.split(":")[1].strip() if physical_id not in recorded.keys(): info['cpu-cores'] += cores recorded[physical_id] = True return info
python
def _detect_hardware_and_os(self, ssh): info = { 'series': '', 'arch': '', 'cpu-cores': '', 'mem': '', } stdout, stderr = self._run_command( ssh, ["sudo", "/bin/bash -c " + shlex.quote(DETECTION_SCRIPT)], pty=True, ) lines = stdout.split("\n") info['series'] = lines[0].strip() info['arch'] = normalize_arch(lines[1].strip()) memKb = re.split(r'\s+', lines[2])[1] # Convert megabytes -> kilobytes info['mem'] = round(int(memKb) / 1024) # Detect available CPUs recorded = {} for line in lines[3:]: physical_id = "" print(line) if line.find("physical id") == 0: physical_id = line.split(":")[1].strip() elif line.find("cpu cores") == 0: cores = line.split(":")[1].strip() if physical_id not in recorded.keys(): info['cpu-cores'] += cores recorded[physical_id] = True return info
[ "def", "_detect_hardware_and_os", "(", "self", ",", "ssh", ")", ":", "info", "=", "{", "'series'", ":", "''", ",", "'arch'", ":", "''", ",", "'cpu-cores'", ":", "''", ",", "'mem'", ":", "''", ",", "}", "stdout", ",", "stderr", "=", "self", ".", "_r...
Detect the target hardware capabilities and OS series. :param object ssh: The SSHClient :return: str: A raw string containing OS and hardware information.
[ "Detect", "the", "target", "hardware", "capabilities", "and", "OS", "series", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/provisioner.py#L214-L258
26,715
juju/python-libjuju
juju/provisioner.py
SSHProvisioner.provision_machine
def provision_machine(self): """Perform the initial provisioning of the target machine. :return: bool: The client.AddMachineParams :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails """ params = client.AddMachineParams() if self._init_ubuntu_user(): try: ssh = self._get_ssh_client( self.host, self.user, self.private_key_path ) hw = self._detect_hardware_and_os(ssh) params.series = hw['series'] params.instance_id = "manual:{}".format(self.host) params.nonce = "manual:{}:{}".format( self.host, str(uuid.uuid4()), # a nop for Juju w/manual machines ) params.hardware_characteristics = { 'arch': hw['arch'], 'mem': int(hw['mem']), 'cpu-cores': int(hw['cpu-cores']), } params.addresses = [{ 'value': self.host, 'type': 'ipv4', 'scope': 'public', }] except paramiko.ssh_exception.AuthenticationException as e: raise e finally: ssh.close() return params
python
def provision_machine(self): params = client.AddMachineParams() if self._init_ubuntu_user(): try: ssh = self._get_ssh_client( self.host, self.user, self.private_key_path ) hw = self._detect_hardware_and_os(ssh) params.series = hw['series'] params.instance_id = "manual:{}".format(self.host) params.nonce = "manual:{}:{}".format( self.host, str(uuid.uuid4()), # a nop for Juju w/manual machines ) params.hardware_characteristics = { 'arch': hw['arch'], 'mem': int(hw['mem']), 'cpu-cores': int(hw['cpu-cores']), } params.addresses = [{ 'value': self.host, 'type': 'ipv4', 'scope': 'public', }] except paramiko.ssh_exception.AuthenticationException as e: raise e finally: ssh.close() return params
[ "def", "provision_machine", "(", "self", ")", ":", "params", "=", "client", ".", "AddMachineParams", "(", ")", "if", "self", ".", "_init_ubuntu_user", "(", ")", ":", "try", ":", "ssh", "=", "self", ".", "_get_ssh_client", "(", "self", ".", "host", ",", ...
Perform the initial provisioning of the target machine. :return: bool: The client.AddMachineParams :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails
[ "Perform", "the", "initial", "provisioning", "of", "the", "target", "machine", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/provisioner.py#L260-L301
26,716
juju/python-libjuju
juju/provisioner.py
SSHProvisioner._run_configure_script
def _run_configure_script(self, script): """Run the script to install the Juju agent on the target machine. :param str script: The script returned by the ProvisioningScript API :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails """ _, tmpFile = tempfile.mkstemp() with open(tmpFile, 'w') as f: f.write(script) try: # get ssh client ssh = self._get_ssh_client( self.host, "ubuntu", self.private_key_path, ) # copy the local copy of the script to the remote machine sftp = paramiko.SFTPClient.from_transport(ssh.get_transport()) sftp.put( tmpFile, tmpFile, ) # run the provisioning script stdout, stderr = self._run_command( ssh, "sudo /bin/bash {}".format(tmpFile), ) except paramiko.ssh_exception.AuthenticationException as e: raise e finally: os.remove(tmpFile) ssh.close()
python
def _run_configure_script(self, script): _, tmpFile = tempfile.mkstemp() with open(tmpFile, 'w') as f: f.write(script) try: # get ssh client ssh = self._get_ssh_client( self.host, "ubuntu", self.private_key_path, ) # copy the local copy of the script to the remote machine sftp = paramiko.SFTPClient.from_transport(ssh.get_transport()) sftp.put( tmpFile, tmpFile, ) # run the provisioning script stdout, stderr = self._run_command( ssh, "sudo /bin/bash {}".format(tmpFile), ) except paramiko.ssh_exception.AuthenticationException as e: raise e finally: os.remove(tmpFile) ssh.close()
[ "def", "_run_configure_script", "(", "self", ",", "script", ")", ":", "_", ",", "tmpFile", "=", "tempfile", ".", "mkstemp", "(", ")", "with", "open", "(", "tmpFile", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "script", ")", "try", ":"...
Run the script to install the Juju agent on the target machine. :param str script: The script returned by the ProvisioningScript API :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails
[ "Run", "the", "script", "to", "install", "the", "Juju", "agent", "on", "the", "target", "machine", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/provisioner.py#L329-L366
26,717
juju/python-libjuju
juju/annotationhelper.py
_get_annotations
async def _get_annotations(entity_tag, connection): """Get annotations for the specified entity :return dict: The annotations for the entity """ facade = client.AnnotationsFacade.from_connection(connection) result = (await facade.Get([{"tag": entity_tag}])).results[0] if result.error is not None: raise JujuError(result.error) return result.annotations
python
async def _get_annotations(entity_tag, connection): facade = client.AnnotationsFacade.from_connection(connection) result = (await facade.Get([{"tag": entity_tag}])).results[0] if result.error is not None: raise JujuError(result.error) return result.annotations
[ "async", "def", "_get_annotations", "(", "entity_tag", ",", "connection", ")", ":", "facade", "=", "client", ".", "AnnotationsFacade", ".", "from_connection", "(", "connection", ")", "result", "=", "(", "await", "facade", ".", "Get", "(", "[", "{", "\"tag\""...
Get annotations for the specified entity :return dict: The annotations for the entity
[ "Get", "annotations", "for", "the", "specified", "entity" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/annotationhelper.py#L9-L18
26,718
juju/python-libjuju
juju/annotationhelper.py
_set_annotations
async def _set_annotations(entity_tag, annotations, connection): """Set annotations on the specified entity. :param annotations map[string]string: the annotations as key/value pairs. """ # TODO: ensure annotations is dict with only string keys # and values. log.debug('Updating annotations on %s', entity_tag) facade = client.AnnotationsFacade.from_connection(connection) args = client.EntityAnnotations( entity=entity_tag, annotations=annotations, ) return await facade.Set([args])
python
async def _set_annotations(entity_tag, annotations, connection): # TODO: ensure annotations is dict with only string keys # and values. log.debug('Updating annotations on %s', entity_tag) facade = client.AnnotationsFacade.from_connection(connection) args = client.EntityAnnotations( entity=entity_tag, annotations=annotations, ) return await facade.Set([args])
[ "async", "def", "_set_annotations", "(", "entity_tag", ",", "annotations", ",", "connection", ")", ":", "# TODO: ensure annotations is dict with only string keys", "# and values.", "log", ".", "debug", "(", "'Updating annotations on %s'", ",", "entity_tag", ")", "facade", ...
Set annotations on the specified entity. :param annotations map[string]string: the annotations as key/value pairs.
[ "Set", "annotations", "on", "the", "specified", "entity", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/annotationhelper.py#L21-L35
26,719
juju/python-libjuju
juju/relation.py
Relation.matches
def matches(self, *specs): """ Check if this relation matches relationship specs. Relation specs are strings that would be given to Juju to establish a relation, and should be in the form ``<application>[:<endpoint_name>]`` where the ``:<endpoint_name>`` suffix is optional. If the suffix is omitted, this relation will match on any endpoint as long as the given application is involved. In other words, this relation will match a spec if that spec could have created this relation. :return: True if all specs match. """ for spec in specs: if ':' in spec: app_name, endpoint_name = spec.split(':') else: app_name, endpoint_name = spec, None for endpoint in self.endpoints: if app_name == endpoint.application.name and \ endpoint_name in (endpoint.name, None): # found a match for this spec, so move to next one break else: # no match for this spec return False return True
python
def matches(self, *specs): for spec in specs: if ':' in spec: app_name, endpoint_name = spec.split(':') else: app_name, endpoint_name = spec, None for endpoint in self.endpoints: if app_name == endpoint.application.name and \ endpoint_name in (endpoint.name, None): # found a match for this spec, so move to next one break else: # no match for this spec return False return True
[ "def", "matches", "(", "self", ",", "*", "specs", ")", ":", "for", "spec", "in", "specs", ":", "if", "':'", "in", "spec", ":", "app_name", ",", "endpoint_name", "=", "spec", ".", "split", "(", "':'", ")", "else", ":", "app_name", ",", "endpoint_name"...
Check if this relation matches relationship specs. Relation specs are strings that would be given to Juju to establish a relation, and should be in the form ``<application>[:<endpoint_name>]`` where the ``:<endpoint_name>`` suffix is optional. If the suffix is omitted, this relation will match on any endpoint as long as the given application is involved. In other words, this relation will match a spec if that spec could have created this relation. :return: True if all specs match.
[ "Check", "if", "this", "relation", "matches", "relationship", "specs", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/relation.py#L84-L112
26,720
juju/python-libjuju
juju/client/overrides.py
ResourcesFacade.AddPendingResources
async def AddPendingResources(self, application_tag, charm_url, resources): """Fix the calling signature of AddPendingResources. The ResourcesFacade doesn't conform to the standard facade pattern in the Juju source, which leads to the schemagened code not matching up properly with the actual calling convention in the API. There is work planned to fix this in Juju, but we have to work around it for now. application_tag : str charm_url : str resources : typing.Sequence<+T_co>[~CharmResource]<~CharmResource> Returns -> typing.Union[_ForwardRef('ErrorResult'), typing.Sequence<+T_co>[str]] """ # map input types to rpc msg _params = dict() msg = dict(type='Resources', request='AddPendingResources', version=1, params=_params) _params['tag'] = application_tag _params['url'] = charm_url _params['resources'] = resources reply = await self.rpc(msg) return reply
python
async def AddPendingResources(self, application_tag, charm_url, resources): # map input types to rpc msg _params = dict() msg = dict(type='Resources', request='AddPendingResources', version=1, params=_params) _params['tag'] = application_tag _params['url'] = charm_url _params['resources'] = resources reply = await self.rpc(msg) return reply
[ "async", "def", "AddPendingResources", "(", "self", ",", "application_tag", ",", "charm_url", ",", "resources", ")", ":", "# map input types to rpc msg", "_params", "=", "dict", "(", ")", "msg", "=", "dict", "(", "type", "=", "'Resources'", ",", "request", "="...
Fix the calling signature of AddPendingResources. The ResourcesFacade doesn't conform to the standard facade pattern in the Juju source, which leads to the schemagened code not matching up properly with the actual calling convention in the API. There is work planned to fix this in Juju, but we have to work around it for now. application_tag : str charm_url : str resources : typing.Sequence<+T_co>[~CharmResource]<~CharmResource> Returns -> typing.Union[_ForwardRef('ErrorResult'), typing.Sequence<+T_co>[str]]
[ "Fix", "the", "calling", "signature", "of", "AddPendingResources", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/overrides.py#L65-L89
26,721
juju/python-libjuju
juju/cloud.py
Cloud.bootstrap
def bootstrap( self, controller_name, region=None, agent_version=None, auto_upgrade=False, bootstrap_constraints=None, bootstrap_series=None, config=None, constraints=None, credential=None, default_model=None, keep_broken=False, metadata_source=None, no_gui=False, to=None, upload_tools=False): """Initialize a cloud environment. :param str controller_name: Name of controller to create :param str region: Cloud region in which to bootstrap :param str agent_version: Version of tools to use for Juju agents :param bool auto_upgrade: Upgrade to latest path release tools on first bootstrap :param bootstrap_constraints: Constraints for the bootstrap machine :type bootstrap_constraints: :class:`juju.Constraints` :param str bootstrap_series: Series of the bootstrap machine :param dict config: Controller configuration :param constraints: Default constraints for all future workload machines :type constraints: :class:`juju.Constraints` :param credential: Credential to use when bootstrapping :type credential: :class:`juju.Credential` :param str default_model: Name to give the default model :param bool keep_broken: Don't destroy model if bootstrap fails :param str metadata_source: Local path to use as tools and/or metadata source :param bool no_gui: Don't install the Juju GUI in the controller when bootstrapping :param str to: Placement directive for bootstrap node (typically used with MAAS) :param bool upload_tools: Upload local version of tools before bootstrapping """ raise NotImplementedError()
python
def bootstrap( self, controller_name, region=None, agent_version=None, auto_upgrade=False, bootstrap_constraints=None, bootstrap_series=None, config=None, constraints=None, credential=None, default_model=None, keep_broken=False, metadata_source=None, no_gui=False, to=None, upload_tools=False): raise NotImplementedError()
[ "def", "bootstrap", "(", "self", ",", "controller_name", ",", "region", "=", "None", ",", "agent_version", "=", "None", ",", "auto_upgrade", "=", "False", ",", "bootstrap_constraints", "=", "None", ",", "bootstrap_series", "=", "None", ",", "config", "=", "N...
Initialize a cloud environment. :param str controller_name: Name of controller to create :param str region: Cloud region in which to bootstrap :param str agent_version: Version of tools to use for Juju agents :param bool auto_upgrade: Upgrade to latest path release tools on first bootstrap :param bootstrap_constraints: Constraints for the bootstrap machine :type bootstrap_constraints: :class:`juju.Constraints` :param str bootstrap_series: Series of the bootstrap machine :param dict config: Controller configuration :param constraints: Default constraints for all future workload machines :type constraints: :class:`juju.Constraints` :param credential: Credential to use when bootstrapping :type credential: :class:`juju.Credential` :param str default_model: Name to give the default model :param bool keep_broken: Don't destroy model if bootstrap fails :param str metadata_source: Local path to use as tools and/or metadata source :param bool no_gui: Don't install the Juju GUI in the controller when bootstrapping :param str to: Placement directive for bootstrap node (typically used with MAAS) :param bool upload_tools: Upload local version of tools before bootstrapping
[ "Initialize", "a", "cloud", "environment", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/cloud.py#L29-L65
26,722
juju/python-libjuju
juju/unit.py
Unit.machine
def machine(self): """Get the machine object for this unit. """ machine_id = self.safe_data['machine-id'] if machine_id: return self.model.machines.get(machine_id, None) else: return None
python
def machine(self): machine_id = self.safe_data['machine-id'] if machine_id: return self.model.machines.get(machine_id, None) else: return None
[ "def", "machine", "(", "self", ")", ":", "machine_id", "=", "self", ".", "safe_data", "[", "'machine-id'", "]", "if", "machine_id", ":", "return", "self", ".", "model", ".", "machines", ".", "get", "(", "machine_id", ",", "None", ")", "else", ":", "ret...
Get the machine object for this unit.
[ "Get", "the", "machine", "object", "for", "this", "unit", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/unit.py#L56-L64
26,723
juju/python-libjuju
juju/unit.py
Unit.run
async def run(self, command, timeout=None): """Run command on this unit. :param str command: The command to run :param int timeout: Time, in seconds, to wait before command is considered failed :returns: A :class:`juju.action.Action` instance. """ action = client.ActionFacade.from_connection(self.connection) log.debug( 'Running `%s` on %s', command, self.name) if timeout: # Convert seconds to nanoseconds timeout = int(timeout * 1000000000) res = await action.Run( [], command, [], timeout, [self.name], ) return await self.model.wait_for_action(res.results[0].action.tag)
python
async def run(self, command, timeout=None): action = client.ActionFacade.from_connection(self.connection) log.debug( 'Running `%s` on %s', command, self.name) if timeout: # Convert seconds to nanoseconds timeout = int(timeout * 1000000000) res = await action.Run( [], command, [], timeout, [self.name], ) return await self.model.wait_for_action(res.results[0].action.tag)
[ "async", "def", "run", "(", "self", ",", "command", ",", "timeout", "=", "None", ")", ":", "action", "=", "client", ".", "ActionFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Running `%s` on %s'", ",", "...
Run command on this unit. :param str command: The command to run :param int timeout: Time, in seconds, to wait before command is considered failed :returns: A :class:`juju.action.Action` instance.
[ "Run", "command", "on", "this", "unit", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/unit.py#L122-L147
26,724
juju/python-libjuju
juju/unit.py
Unit.run_action
async def run_action(self, action_name, **params): """Run an action on this unit. :param str action_name: Name of action to run :param **params: Action parameters :returns: A :class:`juju.action.Action` instance. Note that this only enqueues the action. You will need to call ``action.wait()`` on the resulting `Action` instance if you wish to block until the action is complete. """ action_facade = client.ActionFacade.from_connection(self.connection) log.debug('Starting action `%s` on %s', action_name, self.name) res = await action_facade.Enqueue([client.Action( name=action_name, parameters=params, receiver=self.tag, )]) action = res.results[0].action error = res.results[0].error if error and error.code == 'not found': raise ValueError('Action `%s` not found on %s' % (action_name, self.name)) elif error: raise Exception('Unknown action error: %s' % error.serialize()) action_id = action.tag[len('action-'):] log.debug('Action started as %s', action_id) # we mustn't use wait_for_action because that blocks until the # action is complete, rather than just being in the model return await self.model._wait_for_new('action', action_id)
python
async def run_action(self, action_name, **params): action_facade = client.ActionFacade.from_connection(self.connection) log.debug('Starting action `%s` on %s', action_name, self.name) res = await action_facade.Enqueue([client.Action( name=action_name, parameters=params, receiver=self.tag, )]) action = res.results[0].action error = res.results[0].error if error and error.code == 'not found': raise ValueError('Action `%s` not found on %s' % (action_name, self.name)) elif error: raise Exception('Unknown action error: %s' % error.serialize()) action_id = action.tag[len('action-'):] log.debug('Action started as %s', action_id) # we mustn't use wait_for_action because that blocks until the # action is complete, rather than just being in the model return await self.model._wait_for_new('action', action_id)
[ "async", "def", "run_action", "(", "self", ",", "action_name", ",", "*", "*", "params", ")", ":", "action_facade", "=", "client", ".", "ActionFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Starting action `%...
Run an action on this unit. :param str action_name: Name of action to run :param **params: Action parameters :returns: A :class:`juju.action.Action` instance. Note that this only enqueues the action. You will need to call ``action.wait()`` on the resulting `Action` instance if you wish to block until the action is complete.
[ "Run", "an", "action", "on", "this", "unit", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/unit.py#L149-L181
26,725
juju/python-libjuju
juju/unit.py
Unit.scp_to
async def scp_to(self, source, destination, user='ubuntu', proxy=False, scp_opts=''): """Transfer files to this unit. :param str source: Local path of file(s) to transfer :param str destination: Remote destination of transferred files :param str user: Remote username :param bool proxy: Proxy through the Juju API server :param scp_opts: Additional options to the `scp` command :type scp_opts: str or list """ await self.machine.scp_to(source, destination, user=user, proxy=proxy, scp_opts=scp_opts)
python
async def scp_to(self, source, destination, user='ubuntu', proxy=False, scp_opts=''): await self.machine.scp_to(source, destination, user=user, proxy=proxy, scp_opts=scp_opts)
[ "async", "def", "scp_to", "(", "self", ",", "source", ",", "destination", ",", "user", "=", "'ubuntu'", ",", "proxy", "=", "False", ",", "scp_opts", "=", "''", ")", ":", "await", "self", ".", "machine", ".", "scp_to", "(", "source", ",", "destination",...
Transfer files to this unit. :param str source: Local path of file(s) to transfer :param str destination: Remote destination of transferred files :param str user: Remote username :param bool proxy: Proxy through the Juju API server :param scp_opts: Additional options to the `scp` command :type scp_opts: str or list
[ "Transfer", "files", "to", "this", "unit", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/unit.py#L183-L195
26,726
juju/python-libjuju
juju/unit.py
Unit.get_metrics
async def get_metrics(self): """Get metrics for the unit. :return: Dictionary of metrics for this unit. """ metrics = await self.model.get_metrics(self.tag) return metrics[self.name]
python
async def get_metrics(self): metrics = await self.model.get_metrics(self.tag) return metrics[self.name]
[ "async", "def", "get_metrics", "(", "self", ")", ":", "metrics", "=", "await", "self", ".", "model", ".", "get_metrics", "(", "self", ".", "tag", ")", "return", "metrics", "[", "self", ".", "name", "]" ]
Get metrics for the unit. :return: Dictionary of metrics for this unit.
[ "Get", "metrics", "for", "the", "unit", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/unit.py#L275-L282
26,727
juju/python-libjuju
juju/constraints.py
parse
def parse(constraints): """ Constraints must be expressed as a string containing only spaces and key value pairs joined by an '='. """ if not constraints: return None if type(constraints) is dict: # Fowards compatibilty: already parsed return constraints constraints = { normalize_key(k): ( normalize_list_value(v) if k in LIST_KEYS else normalize_value(v) ) for k, v in [s.split("=") for s in constraints.split(" ")]} return constraints
python
def parse(constraints): if not constraints: return None if type(constraints) is dict: # Fowards compatibilty: already parsed return constraints constraints = { normalize_key(k): ( normalize_list_value(v) if k in LIST_KEYS else normalize_value(v) ) for k, v in [s.split("=") for s in constraints.split(" ")]} return constraints
[ "def", "parse", "(", "constraints", ")", ":", "if", "not", "constraints", ":", "return", "None", "if", "type", "(", "constraints", ")", "is", "dict", ":", "# Fowards compatibilty: already parsed", "return", "constraints", "constraints", "=", "{", "normalize_key", ...
Constraints must be expressed as a string containing only spaces and key value pairs joined by an '='.
[ "Constraints", "must", "be", "expressed", "as", "a", "string", "containing", "only", "spaces", "and", "key", "value", "pairs", "joined", "by", "an", "=", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/constraints.py#L38-L57
26,728
juju/python-libjuju
juju/application.py
Application.add_relation
async def add_relation(self, local_relation, remote_relation): """Add a relation to another application. :param str local_relation: Name of relation on this application :param str remote_relation: Name of relation on the other application in the form '<application>[:<relation_name>]' """ if ':' not in local_relation: local_relation = '{}:{}'.format(self.name, local_relation) return await self.model.add_relation(local_relation, remote_relation)
python
async def add_relation(self, local_relation, remote_relation): if ':' not in local_relation: local_relation = '{}:{}'.format(self.name, local_relation) return await self.model.add_relation(local_relation, remote_relation)
[ "async", "def", "add_relation", "(", "self", ",", "local_relation", ",", "remote_relation", ")", ":", "if", "':'", "not", "in", "local_relation", ":", "local_relation", "=", "'{}:{}'", ".", "format", "(", "self", ".", "name", ",", "local_relation", ")", "ret...
Add a relation to another application. :param str local_relation: Name of relation on this application :param str remote_relation: Name of relation on the other application in the form '<application>[:<relation_name>]'
[ "Add", "a", "relation", "to", "another", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L91-L102
26,729
juju/python-libjuju
juju/application.py
Application.add_unit
async def add_unit(self, count=1, to=None): """Add one or more units to this application. :param int count: Number of units to add :param str to: Placement directive, e.g.:: '23' - machine 23 'lxc:7' - new lxc container on machine 7 '24/lxc/3' - lxc container 3 or machine 24 If None, a new machine is provisioned. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Adding %s unit%s to %s', count, '' if count == 1 else 's', self.name) result = await app_facade.AddUnits( application=self.name, placement=parse_placement(to) if to else None, num_units=count, ) return await asyncio.gather(*[ asyncio.ensure_future(self.model._wait_for_new('unit', unit_id)) for unit_id in result.units ])
python
async def add_unit(self, count=1, to=None): app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Adding %s unit%s to %s', count, '' if count == 1 else 's', self.name) result = await app_facade.AddUnits( application=self.name, placement=parse_placement(to) if to else None, num_units=count, ) return await asyncio.gather(*[ asyncio.ensure_future(self.model._wait_for_new('unit', unit_id)) for unit_id in result.units ])
[ "async", "def", "add_unit", "(", "self", ",", "count", "=", "1", ",", "to", "=", "None", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Adding %s u...
Add one or more units to this application. :param int count: Number of units to add :param str to: Placement directive, e.g.:: '23' - machine 23 'lxc:7' - new lxc container on machine 7 '24/lxc/3' - lxc container 3 or machine 24 If None, a new machine is provisioned.
[ "Add", "one", "or", "more", "units", "to", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L104-L131
26,730
juju/python-libjuju
juju/application.py
Application.destroy_relation
async def destroy_relation(self, local_relation, remote_relation): """Remove a relation to another application. :param str local_relation: Name of relation on this application :param str remote_relation: Name of relation on the other application in the form '<application>[:<relation_name>]' """ if ':' not in local_relation: local_relation = '{}:{}'.format(self.name, local_relation) app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Destroying relation %s <-> %s', local_relation, remote_relation) return await app_facade.DestroyRelation([ local_relation, remote_relation])
python
async def destroy_relation(self, local_relation, remote_relation): if ':' not in local_relation: local_relation = '{}:{}'.format(self.name, local_relation) app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Destroying relation %s <-> %s', local_relation, remote_relation) return await app_facade.DestroyRelation([ local_relation, remote_relation])
[ "async", "def", "destroy_relation", "(", "self", ",", "local_relation", ",", "remote_relation", ")", ":", "if", "':'", "not", "in", "local_relation", ":", "local_relation", "=", "'{}:{}'", ".", "format", "(", "self", ".", "name", ",", "local_relation", ")", ...
Remove a relation to another application. :param str local_relation: Name of relation on this application :param str remote_relation: Name of relation on the other application in the form '<application>[:<relation_name>]'
[ "Remove", "a", "relation", "to", "another", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L184-L201
26,731
juju/python-libjuju
juju/application.py
Application.destroy
async def destroy(self): """Remove this application from the model. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Destroying %s', self.name) return await app_facade.Destroy(self.name)
python
async def destroy(self): app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Destroying %s', self.name) return await app_facade.Destroy(self.name)
[ "async", "def", "destroy", "(", "self", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Destroying %s'", ",", "self", ".", "name", ")", "return", "awa...
Remove this application from the model.
[ "Remove", "this", "application", "from", "the", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L211-L220
26,732
juju/python-libjuju
juju/application.py
Application.expose
async def expose(self): """Make this application publicly available over the network. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Exposing %s', self.name) return await app_facade.Expose(self.name)
python
async def expose(self): app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Exposing %s', self.name) return await app_facade.Expose(self.name)
[ "async", "def", "expose", "(", "self", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Exposing %s'", ",", "self", ".", "name", ")", "return", "await"...
Make this application publicly available over the network.
[ "Make", "this", "application", "publicly", "available", "over", "the", "network", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L223-L232
26,733
juju/python-libjuju
juju/application.py
Application.get_config
async def get_config(self): """Return the configuration settings dict for this application. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Getting config for %s', self.name) return (await app_facade.Get(self.name)).config
python
async def get_config(self): app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Getting config for %s', self.name) return (await app_facade.Get(self.name)).config
[ "async", "def", "get_config", "(", "self", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Getting config for %s'", ",", "self", ".", "name", ")", "retu...
Return the configuration settings dict for this application.
[ "Return", "the", "configuration", "settings", "dict", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L234-L243
26,734
juju/python-libjuju
juju/application.py
Application.get_constraints
async def get_constraints(self): """Return the machine constraints dict for this application. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Getting constraints for %s', self.name) result = (await app_facade.Get(self.name)).constraints return vars(result) if result else result
python
async def get_constraints(self): app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Getting constraints for %s', self.name) result = (await app_facade.Get(self.name)).constraints return vars(result) if result else result
[ "async", "def", "get_constraints", "(", "self", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Getting constraints for %s'", ",", "self", ".", "name", ")...
Return the machine constraints dict for this application.
[ "Return", "the", "machine", "constraints", "dict", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L245-L255
26,735
juju/python-libjuju
juju/application.py
Application.get_actions
async def get_actions(self, schema=False): """Get actions defined for this application. :param bool schema: Return the full action schema :return dict: The charms actions, empty dict if none are defined. """ actions = {} entity = [{"tag": self.tag}] action_facade = client.ActionFacade.from_connection(self.connection) results = ( await action_facade.ApplicationsCharmsActions(entity)).results for result in results: if result.application_tag == self.tag and result.actions: actions = result.actions break if not schema: actions = {k: v['description'] for k, v in actions.items()} return actions
python
async def get_actions(self, schema=False): actions = {} entity = [{"tag": self.tag}] action_facade = client.ActionFacade.from_connection(self.connection) results = ( await action_facade.ApplicationsCharmsActions(entity)).results for result in results: if result.application_tag == self.tag and result.actions: actions = result.actions break if not schema: actions = {k: v['description'] for k, v in actions.items()} return actions
[ "async", "def", "get_actions", "(", "self", ",", "schema", "=", "False", ")", ":", "actions", "=", "{", "}", "entity", "=", "[", "{", "\"tag\"", ":", "self", ".", "tag", "}", "]", "action_facade", "=", "client", ".", "ActionFacade", ".", "from_connecti...
Get actions defined for this application. :param bool schema: Return the full action schema :return dict: The charms actions, empty dict if none are defined.
[ "Get", "actions", "defined", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L257-L274
26,736
juju/python-libjuju
juju/application.py
Application.get_resources
async def get_resources(self): """Return resources for this application. Returns a dict mapping resource name to :class:`~juju._definitions.CharmResource` instances. """ facade = client.ResourcesFacade.from_connection(self.connection) response = await facade.ListResources([client.Entity(self.tag)]) resources = dict() for result in response.results: for resource in result.charm_store_resources or []: resources[resource.name] = resource for resource in result.resources or []: if resource.charmresource: resource = resource.charmresource resources[resource.name] = resource return resources
python
async def get_resources(self): facade = client.ResourcesFacade.from_connection(self.connection) response = await facade.ListResources([client.Entity(self.tag)]) resources = dict() for result in response.results: for resource in result.charm_store_resources or []: resources[resource.name] = resource for resource in result.resources or []: if resource.charmresource: resource = resource.charmresource resources[resource.name] = resource return resources
[ "async", "def", "get_resources", "(", "self", ")", ":", "facade", "=", "client", ".", "ResourcesFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "response", "=", "await", "facade", ".", "ListResources", "(", "[", "client", ".", "Entity",...
Return resources for this application. Returns a dict mapping resource name to :class:`~juju._definitions.CharmResource` instances.
[ "Return", "resources", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L276-L293
26,737
juju/python-libjuju
juju/application.py
Application.run
async def run(self, command, timeout=None): """Run command on all units for this application. :param str command: The command to run :param int timeout: Time to wait before command is considered failed """ action = client.ActionFacade.from_connection(self.connection) log.debug( 'Running `%s` on all units of %s', command, self.name) # TODO this should return a list of Actions return await action.Run( [self.name], command, [], timeout, [], )
python
async def run(self, command, timeout=None): action = client.ActionFacade.from_connection(self.connection) log.debug( 'Running `%s` on all units of %s', command, self.name) # TODO this should return a list of Actions return await action.Run( [self.name], command, [], timeout, [], )
[ "async", "def", "run", "(", "self", ",", "command", ",", "timeout", "=", "None", ")", ":", "action", "=", "client", ".", "ActionFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Running `%s` on all units of %s'...
Run command on all units for this application. :param str command: The command to run :param int timeout: Time to wait before command is considered failed
[ "Run", "command", "on", "all", "units", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L295-L314
26,738
juju/python-libjuju
juju/application.py
Application.set_config
async def set_config(self, config): """Set configuration options for this application. :param config: Dict of configuration to set """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Setting config for %s: %s', self.name, config) return await app_facade.Set(self.name, config)
python
async def set_config(self, config): app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Setting config for %s: %s', self.name, config) return await app_facade.Set(self.name, config)
[ "async", "def", "set_config", "(", "self", ",", "config", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Setting config for %s: %s'", ",", "self", ".", ...
Set configuration options for this application. :param config: Dict of configuration to set
[ "Set", "configuration", "options", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L332-L342
26,739
juju/python-libjuju
juju/application.py
Application.reset_config
async def reset_config(self, to_default): """ Restore application config to default values. :param list to_default: A list of config options to be reset to their default value. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Restoring default config for %s: %s', self.name, to_default) return await app_facade.Unset(self.name, to_default)
python
async def reset_config(self, to_default): app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Restoring default config for %s: %s', self.name, to_default) return await app_facade.Unset(self.name, to_default)
[ "async", "def", "reset_config", "(", "self", ",", "to_default", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Restoring default config for %s: %s'", ",", ...
Restore application config to default values. :param list to_default: A list of config options to be reset to their default value.
[ "Restore", "application", "config", "to", "default", "values", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L344-L356
26,740
juju/python-libjuju
juju/application.py
Application.set_constraints
async def set_constraints(self, constraints): """Set machine constraints for this application. :param dict constraints: Dict of machine constraints """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Setting constraints for %s: %s', self.name, constraints) return await app_facade.SetConstraints(self.name, constraints)
python
async def set_constraints(self, constraints): app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Setting constraints for %s: %s', self.name, constraints) return await app_facade.SetConstraints(self.name, constraints)
[ "async", "def", "set_constraints", "(", "self", ",", "constraints", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Setting constraints for %s: %s'", ",", "...
Set machine constraints for this application. :param dict constraints: Dict of machine constraints
[ "Set", "machine", "constraints", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L358-L369
26,741
juju/python-libjuju
juju/application.py
Application.unexpose
async def unexpose(self): """Remove public availability over the network for this application. """ app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Unexposing %s', self.name) return await app_facade.Unexpose(self.name)
python
async def unexpose(self): app_facade = client.ApplicationFacade.from_connection(self.connection) log.debug( 'Unexposing %s', self.name) return await app_facade.Unexpose(self.name)
[ "async", "def", "unexpose", "(", "self", ")", ":", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "log", ".", "debug", "(", "'Unexposing %s'", ",", "self", ".", "name", ")", "return", "aw...
Remove public availability over the network for this application.
[ "Remove", "public", "availability", "over", "the", "network", "for", "this", "application", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L388-L397
26,742
juju/python-libjuju
juju/client/facade.py
write_client
def write_client(captures, options): """ Write the TypeFactory classes to _client.py, along with some imports and tables so that we can look up versioned Facades. """ with open("{}/_client.py".format(options.output_dir), "w") as f: f.write(HEADER) f.write("from juju.client._definitions import *\n\n") clients = ", ".join("_client{}".format(v) for v in captures) f.write("from juju.client import " + clients + "\n\n") f.write(CLIENT_TABLE.format(clients=",\n ".join( ['"{}": _client{}'.format(v, v) for v in captures]))) f.write(LOOKUP_FACADE) f.write(TYPE_FACTORY) for key in sorted([k for k in factories.keys() if "Facade" in k]): print(factories[key], file=f)
python
def write_client(captures, options): with open("{}/_client.py".format(options.output_dir), "w") as f: f.write(HEADER) f.write("from juju.client._definitions import *\n\n") clients = ", ".join("_client{}".format(v) for v in captures) f.write("from juju.client import " + clients + "\n\n") f.write(CLIENT_TABLE.format(clients=",\n ".join( ['"{}": _client{}'.format(v, v) for v in captures]))) f.write(LOOKUP_FACADE) f.write(TYPE_FACTORY) for key in sorted([k for k in factories.keys() if "Facade" in k]): print(factories[key], file=f)
[ "def", "write_client", "(", "captures", ",", "options", ")", ":", "with", "open", "(", "\"{}/_client.py\"", ".", "format", "(", "options", ".", "output_dir", ")", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "HEADER", ")", "f", ".", "wr...
Write the TypeFactory classes to _client.py, along with some imports and tables so that we can look up versioned Facades.
[ "Write", "the", "TypeFactory", "classes", "to", "_client", ".", "py", "along", "with", "some", "imports", "and", "tables", "so", "that", "we", "can", "look", "up", "versioned", "Facades", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/facade.py#L733-L749
26,743
juju/python-libjuju
juju/client/facade.py
KindRegistry.lookup
def lookup(self, name, version=None): """If version is omitted, max version is used""" versions = self.get(name) if not versions: return None if version: return versions[version] return versions[max(versions)]
python
def lookup(self, name, version=None): versions = self.get(name) if not versions: return None if version: return versions[version] return versions[max(versions)]
[ "def", "lookup", "(", "self", ",", "name", ",", "version", "=", "None", ")", ":", "versions", "=", "self", ".", "get", "(", "name", ")", "if", "not", "versions", ":", "return", "None", "if", "version", ":", "return", "versions", "[", "version", "]", ...
If version is omitted, max version is used
[ "If", "version", "is", "omitted", "max", "version", "is", "used" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/facade.py#L110-L117
26,744
cloudify-cosmo/wagon
wagon.py
install_package
def install_package(package, wheels_path, venv=None, requirement_files=None, upgrade=False, install_args=None): """Install a Python package. Can specify a specific version. Can specify a prerelease. Can specify a venv to install in. Can specify a list of paths or urls to requirement txt files. Can specify a local wheels_path to use for offline installation. Can request an upgrade. """ requirement_files = requirement_files or [] logger.info('Installing %s...', package) if venv and not os.path.isdir(venv): raise WagonError('virtualenv {0} does not exist'.format(venv)) pip_command = _construct_pip_command( package, wheels_path, venv, requirement_files, upgrade, install_args) if IS_VIRTUALENV and not venv: logger.info('Installing within current virtualenv') result = _run(pip_command) if not result.returncode == 0: raise WagonError('Could not install package: {0} ({1})'.format( package, result.aggr_stderr))
python
def install_package(package, wheels_path, venv=None, requirement_files=None, upgrade=False, install_args=None): requirement_files = requirement_files or [] logger.info('Installing %s...', package) if venv and not os.path.isdir(venv): raise WagonError('virtualenv {0} does not exist'.format(venv)) pip_command = _construct_pip_command( package, wheels_path, venv, requirement_files, upgrade, install_args) if IS_VIRTUALENV and not venv: logger.info('Installing within current virtualenv') result = _run(pip_command) if not result.returncode == 0: raise WagonError('Could not install package: {0} ({1})'.format( package, result.aggr_stderr))
[ "def", "install_package", "(", "package", ",", "wheels_path", ",", "venv", "=", "None", ",", "requirement_files", "=", "None", ",", "upgrade", "=", "False", ",", "install_args", "=", "None", ")", ":", "requirement_files", "=", "requirement_files", "or", "[", ...
Install a Python package. Can specify a specific version. Can specify a prerelease. Can specify a venv to install in. Can specify a list of paths or urls to requirement txt files. Can specify a local wheels_path to use for offline installation. Can request an upgrade.
[ "Install", "a", "Python", "package", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L247-L282
26,745
cloudify-cosmo/wagon
wagon.py
_get_platform_for_set_of_wheels
def _get_platform_for_set_of_wheels(wheels_path): """For any set of wheel files, extracts a single platform. Since a set of wheels created or downloaded on one machine can only be for a single platform, if any wheel in the set has a platform which is not `any`, it will be used with one exception: In Linux, a wagon can contain wheels for both manylinux1 and linux. If, at any point we find that a wheel has `linux` as a platform, it will be used since it means it doesn't cross-fit all distros. If a platform other than `any` was not found, `any` will be assumed """ real_platform = '' for wheel in _get_downloaded_wheels(wheels_path): platform = _get_platform_from_wheel_name( os.path.join(wheels_path, wheel)) if 'linux' in platform and 'manylinux' not in platform: # Means either linux_x64_86 or linux_i686 on all wheels # If, at any point, a wheel matches this, it will be # returned so it'll only match that platform. return platform elif platform != ALL_PLATFORMS_TAG: # Means it can be either Windows, OSX or manylinux1 on all wheels real_platform = platform return real_platform or ALL_PLATFORMS_TAG
python
def _get_platform_for_set_of_wheels(wheels_path): real_platform = '' for wheel in _get_downloaded_wheels(wheels_path): platform = _get_platform_from_wheel_name( os.path.join(wheels_path, wheel)) if 'linux' in platform and 'manylinux' not in platform: # Means either linux_x64_86 or linux_i686 on all wheels # If, at any point, a wheel matches this, it will be # returned so it'll only match that platform. return platform elif platform != ALL_PLATFORMS_TAG: # Means it can be either Windows, OSX or manylinux1 on all wheels real_platform = platform return real_platform or ALL_PLATFORMS_TAG
[ "def", "_get_platform_for_set_of_wheels", "(", "wheels_path", ")", ":", "real_platform", "=", "''", "for", "wheel", "in", "_get_downloaded_wheels", "(", "wheels_path", ")", ":", "platform", "=", "_get_platform_from_wheel_name", "(", "os", ".", "path", ".", "join", ...
For any set of wheel files, extracts a single platform. Since a set of wheels created or downloaded on one machine can only be for a single platform, if any wheel in the set has a platform which is not `any`, it will be used with one exception: In Linux, a wagon can contain wheels for both manylinux1 and linux. If, at any point we find that a wheel has `linux` as a platform, it will be used since it means it doesn't cross-fit all distros. If a platform other than `any` was not found, `any` will be assumed
[ "For", "any", "set", "of", "wheel", "files", "extracts", "a", "single", "platform", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L377-L404
26,746
cloudify-cosmo/wagon
wagon.py
_get_os_properties
def _get_os_properties(): """Retrieve distribution properties. **Note that platform.linux_distribution and platform.dist are deprecated and will be removed in Python 3.7. By that time, distro will become mandatory. """ if IS_DISTRO_INSTALLED: return distro.linux_distribution(full_distribution_name=False) return platform.linux_distribution(full_distribution_name=False)
python
def _get_os_properties(): if IS_DISTRO_INSTALLED: return distro.linux_distribution(full_distribution_name=False) return platform.linux_distribution(full_distribution_name=False)
[ "def", "_get_os_properties", "(", ")", ":", "if", "IS_DISTRO_INSTALLED", ":", "return", "distro", ".", "linux_distribution", "(", "full_distribution_name", "=", "False", ")", "return", "platform", ".", "linux_distribution", "(", "full_distribution_name", "=", "False",...
Retrieve distribution properties. **Note that platform.linux_distribution and platform.dist are deprecated and will be removed in Python 3.7. By that time, distro will become mandatory.
[ "Retrieve", "distribution", "properties", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L416-L425
26,747
cloudify-cosmo/wagon
wagon.py
_get_env_bin_path
def _get_env_bin_path(env_path): """Return the bin path for a virtualenv This provides a fallback for a situation in which you're trying to use the script and create a virtualenv from within a virtualenv in which virtualenv isn't installed and so is not importable. """ if IS_VIRTUALENV_INSTALLED: path = virtualenv.path_locations(env_path)[3] else: path = os.path.join(env_path, 'Scripts' if IS_WIN else 'bin') return r'{0}'.format(path)
python
def _get_env_bin_path(env_path): if IS_VIRTUALENV_INSTALLED: path = virtualenv.path_locations(env_path)[3] else: path = os.path.join(env_path, 'Scripts' if IS_WIN else 'bin') return r'{0}'.format(path)
[ "def", "_get_env_bin_path", "(", "env_path", ")", ":", "if", "IS_VIRTUALENV_INSTALLED", ":", "path", "=", "virtualenv", ".", "path_locations", "(", "env_path", ")", "[", "3", "]", "else", ":", "path", "=", "os", ".", "path", ".", "join", "(", "env_path", ...
Return the bin path for a virtualenv This provides a fallback for a situation in which you're trying to use the script and create a virtualenv from within a virtualenv in which virtualenv isn't installed and so is not importable.
[ "Return", "the", "bin", "path", "for", "a", "virtualenv" ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L428-L440
26,748
cloudify-cosmo/wagon
wagon.py
_generate_metadata_file
def _generate_metadata_file(workdir, archive_name, platform, python_versions, package_name, package_version, build_tag, package_source, wheels): """Generate a metadata file for the package. """ logger.debug('Generating Metadata...') metadata = { 'created_by_wagon_version': _get_wagon_version(), 'archive_name': archive_name, 'supported_platform': platform, 'supported_python_versions': python_versions, 'build_server_os_properties': { 'distribution': None, 'distribution_version': None, 'distribution_release': None, }, 'package_name': package_name, 'package_version': package_version, 'package_build_tag': build_tag, 'package_source': package_source, 'wheels': wheels, } if IS_LINUX and platform != ALL_PLATFORMS_TAG: distribution, version, release = _get_os_properties() metadata.update( {'build_server_os_properties': { 'distribution': distribution.lower(), 'distribution_version': version.lower(), 'distribution_release': release.lower() }}) formatted_metadata = json.dumps(metadata, indent=4, sort_keys=True) if is_verbose(): logger.debug('Metadata is: %s', formatted_metadata) output_path = os.path.join(workdir, METADATA_FILE_NAME) with open(output_path, 'w') as f: logger.debug('Writing metadata to file: %s', output_path) f.write(formatted_metadata)
python
def _generate_metadata_file(workdir, archive_name, platform, python_versions, package_name, package_version, build_tag, package_source, wheels): logger.debug('Generating Metadata...') metadata = { 'created_by_wagon_version': _get_wagon_version(), 'archive_name': archive_name, 'supported_platform': platform, 'supported_python_versions': python_versions, 'build_server_os_properties': { 'distribution': None, 'distribution_version': None, 'distribution_release': None, }, 'package_name': package_name, 'package_version': package_version, 'package_build_tag': build_tag, 'package_source': package_source, 'wheels': wheels, } if IS_LINUX and platform != ALL_PLATFORMS_TAG: distribution, version, release = _get_os_properties() metadata.update( {'build_server_os_properties': { 'distribution': distribution.lower(), 'distribution_version': version.lower(), 'distribution_release': release.lower() }}) formatted_metadata = json.dumps(metadata, indent=4, sort_keys=True) if is_verbose(): logger.debug('Metadata is: %s', formatted_metadata) output_path = os.path.join(workdir, METADATA_FILE_NAME) with open(output_path, 'w') as f: logger.debug('Writing metadata to file: %s', output_path) f.write(formatted_metadata)
[ "def", "_generate_metadata_file", "(", "workdir", ",", "archive_name", ",", "platform", ",", "python_versions", ",", "package_name", ",", "package_version", ",", "build_tag", ",", "package_source", ",", "wheels", ")", ":", "logger", ".", "debug", "(", "'Generating...
Generate a metadata file for the package.
[ "Generate", "a", "metadata", "file", "for", "the", "package", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L513-L556
26,749
cloudify-cosmo/wagon
wagon.py
_set_archive_name
def _set_archive_name(package_name, package_version, python_versions, platform, build_tag=''): """Set the format of the output archive file. We should aspire for the name of the archive to be as compatible as possible with the wheel naming convention described here: https://www.python.org/dev/peps/pep-0491/#file-name-convention, as we're basically providing a "wheel" of our package. """ package_name = package_name.replace('-', '_') python_versions = '.'.join(python_versions) archive_name_tags = [ package_name, package_version, python_versions, 'none', platform, ] if build_tag: archive_name_tags.insert(2, build_tag) archive_name = '{0}.wgn'.format('-'.join(archive_name_tags)) return archive_name
python
def _set_archive_name(package_name, package_version, python_versions, platform, build_tag=''): package_name = package_name.replace('-', '_') python_versions = '.'.join(python_versions) archive_name_tags = [ package_name, package_version, python_versions, 'none', platform, ] if build_tag: archive_name_tags.insert(2, build_tag) archive_name = '{0}.wgn'.format('-'.join(archive_name_tags)) return archive_name
[ "def", "_set_archive_name", "(", "package_name", ",", "package_version", ",", "python_versions", ",", "platform", ",", "build_tag", "=", "''", ")", ":", "package_name", "=", "package_name", ".", "replace", "(", "'-'", ",", "'_'", ")", "python_versions", "=", "...
Set the format of the output archive file. We should aspire for the name of the archive to be as compatible as possible with the wheel naming convention described here: https://www.python.org/dev/peps/pep-0491/#file-name-convention, as we're basically providing a "wheel" of our package.
[ "Set", "the", "format", "of", "the", "output", "archive", "file", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L559-L587
26,750
cloudify-cosmo/wagon
wagon.py
get_source_name_and_version
def get_source_name_and_version(source): """Retrieve the source package's name and version. If the source is a path, the name and version will be retrieved by querying the setup.py file in the path. If the source is PACKAGE_NAME==PACKAGE_VERSION, they will be used as the name and version. If the source is PACKAGE_NAME, the version will be extracted from the wheel of the latest version. """ if os.path.isfile(os.path.join(source, 'setup.py')): package_name, package_version = \ _get_name_and_version_from_setup(source) # TODO: maybe we don't want to be that explicit and allow using >= # elif any(symbol in source for symbol in ['==', '>=', '<=']): elif '==' in source: base_name, package_version = source.split('==') package_name = _get_package_info_from_pypi(base_name)['name'] else: package_info = _get_package_info_from_pypi(source) package_name = package_info['name'] package_version = package_info['version'] return package_name, package_version
python
def get_source_name_and_version(source): if os.path.isfile(os.path.join(source, 'setup.py')): package_name, package_version = \ _get_name_and_version_from_setup(source) # TODO: maybe we don't want to be that explicit and allow using >= # elif any(symbol in source for symbol in ['==', '>=', '<=']): elif '==' in source: base_name, package_version = source.split('==') package_name = _get_package_info_from_pypi(base_name)['name'] else: package_info = _get_package_info_from_pypi(source) package_name = package_info['name'] package_version = package_info['version'] return package_name, package_version
[ "def", "get_source_name_and_version", "(", "source", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "source", ",", "'setup.py'", ")", ")", ":", "package_name", ",", "package_version", "=", "_get_name_and_version_f...
Retrieve the source package's name and version. If the source is a path, the name and version will be retrieved by querying the setup.py file in the path. If the source is PACKAGE_NAME==PACKAGE_VERSION, they will be used as the name and version. If the source is PACKAGE_NAME, the version will be extracted from the wheel of the latest version.
[ "Retrieve", "the", "source", "package", "s", "name", "and", "version", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L590-L614
26,751
cloudify-cosmo/wagon
wagon.py
get_source
def get_source(source): """Return a pip-installable source If the source is a url to a package's tar file, this will download the source and extract it to a temporary directory. If the source is neither a url nor a local path, and is not provided as PACKAGE_NAME==PACKAGE_VERSION, the provided source string will be regarded as the source, which, by default, will assume that the string is a name of a package in PyPI. """ def extract_source(source, destination): if tarfile.is_tarfile(source): _untar(source, destination) elif zipfile.is_zipfile(source): _unzip(source, destination) else: raise WagonError( 'Failed to extract {0}. Please verify that the ' 'provided file is a valid zip or tar.gz ' 'archive'.format(source)) source = os.path.join( destination, [d for d in next(os.walk(destination))[1]][0]) return source logger.debug('Retrieving source...') if '://' in source: split = source.split('://') schema = split[0] if schema in ['file', 'http', 'https']: tmpdir = tempfile.mkdtemp() fd, tmpfile = tempfile.mkstemp() os.close(fd) try: _download_file(source, tmpfile) source = extract_source(tmpfile, tmpdir) finally: os.remove(tmpfile) else: raise WagonError('Source URL type {0} is not supported'.format( schema)) elif os.path.isfile(source): tmpdir = tempfile.mkdtemp() source = extract_source(source, tmpdir) elif os.path.isdir(os.path.expanduser(source)): source = os.path.expanduser(source) elif '==' in source: base_name, version = source.split('==') source = _get_package_info_from_pypi(base_name)['name'] source = '{0}=={1}'.format(source, version) else: source = _get_package_info_from_pypi(source)['name'] logger.debug('Source is: %s', source) return source
python
def get_source(source): def extract_source(source, destination): if tarfile.is_tarfile(source): _untar(source, destination) elif zipfile.is_zipfile(source): _unzip(source, destination) else: raise WagonError( 'Failed to extract {0}. Please verify that the ' 'provided file is a valid zip or tar.gz ' 'archive'.format(source)) source = os.path.join( destination, [d for d in next(os.walk(destination))[1]][0]) return source logger.debug('Retrieving source...') if '://' in source: split = source.split('://') schema = split[0] if schema in ['file', 'http', 'https']: tmpdir = tempfile.mkdtemp() fd, tmpfile = tempfile.mkstemp() os.close(fd) try: _download_file(source, tmpfile) source = extract_source(tmpfile, tmpdir) finally: os.remove(tmpfile) else: raise WagonError('Source URL type {0} is not supported'.format( schema)) elif os.path.isfile(source): tmpdir = tempfile.mkdtemp() source = extract_source(source, tmpdir) elif os.path.isdir(os.path.expanduser(source)): source = os.path.expanduser(source) elif '==' in source: base_name, version = source.split('==') source = _get_package_info_from_pypi(base_name)['name'] source = '{0}=={1}'.format(source, version) else: source = _get_package_info_from_pypi(source)['name'] logger.debug('Source is: %s', source) return source
[ "def", "get_source", "(", "source", ")", ":", "def", "extract_source", "(", "source", ",", "destination", ")", ":", "if", "tarfile", ".", "is_tarfile", "(", "source", ")", ":", "_untar", "(", "source", ",", "destination", ")", "elif", "zipfile", ".", "is...
Return a pip-installable source If the source is a url to a package's tar file, this will download the source and extract it to a temporary directory. If the source is neither a url nor a local path, and is not provided as PACKAGE_NAME==PACKAGE_VERSION, the provided source string will be regarded as the source, which, by default, will assume that the string is a name of a package in PyPI.
[ "Return", "a", "pip", "-", "installable", "source" ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L628-L682
26,752
cloudify-cosmo/wagon
wagon.py
create
def create(source, requirement_files=None, force=False, keep_wheels=False, archive_destination_dir='.', python_versions=None, validate_archive=False, wheel_args='', archive_format='zip', build_tag=''): """Create a Wagon archive and returns its path. Package name and version are extracted from the setup.py file of the `source` or from the PACKAGE_NAME==PACKAGE_VERSION if the source is a PyPI package. Supported `python_versions` must be in the format e.g [33, 27, 2, 3].. `force` will remove any excess dirs or archives before creation. `requirement_files` can be either a link/local path to a requirements.txt file or just `.`, in which case requirement files will be automatically extracted from either the GitHub archive URL or the local path provided provided in `source`. """ if validate_archive: _assert_virtualenv_is_installed() logger.info('Creating archive for %s...', source) processed_source = get_source(source) if os.path.isdir(processed_source) and not \ os.path.isfile(os.path.join(processed_source, 'setup.py')): raise WagonError( 'Source directory must contain a setup.py file') package_name, package_version = get_source_name_and_version( processed_source) tempdir = tempfile.mkdtemp() workdir = os.path.join(tempdir, package_name) wheels_path = os.path.join(workdir, DEFAULT_WHEELS_PATH) try: wheels = wheel( processed_source, requirement_files, wheels_path, wheel_args) finally: if processed_source != source: shutil.rmtree(processed_source, ignore_errors=True) platform = _get_platform_for_set_of_wheels(wheels_path) if is_verbose(): logger.debug('Platform is: %s', platform) python_versions = _set_python_versions(python_versions) if not os.path.isdir(archive_destination_dir): os.makedirs(archive_destination_dir) archive_name = _set_archive_name( package_name, package_version, python_versions, platform, build_tag) archive_path = os.path.join(archive_destination_dir, archive_name) _handle_output_file(archive_path, force) _generate_metadata_file( workdir, archive_name, platform, python_versions, package_name, package_version, build_tag, source, wheels) _create_wagon_archive(workdir, archive_path, archive_format) if not keep_wheels: logger.debug('Removing work directory...') shutil.rmtree(tempdir, ignore_errors=True) if validate_archive: validate(archive_path) logger.info('Wagon created successfully at: %s', archive_path) return archive_path
python
def create(source, requirement_files=None, force=False, keep_wheels=False, archive_destination_dir='.', python_versions=None, validate_archive=False, wheel_args='', archive_format='zip', build_tag=''): if validate_archive: _assert_virtualenv_is_installed() logger.info('Creating archive for %s...', source) processed_source = get_source(source) if os.path.isdir(processed_source) and not \ os.path.isfile(os.path.join(processed_source, 'setup.py')): raise WagonError( 'Source directory must contain a setup.py file') package_name, package_version = get_source_name_and_version( processed_source) tempdir = tempfile.mkdtemp() workdir = os.path.join(tempdir, package_name) wheels_path = os.path.join(workdir, DEFAULT_WHEELS_PATH) try: wheels = wheel( processed_source, requirement_files, wheels_path, wheel_args) finally: if processed_source != source: shutil.rmtree(processed_source, ignore_errors=True) platform = _get_platform_for_set_of_wheels(wheels_path) if is_verbose(): logger.debug('Platform is: %s', platform) python_versions = _set_python_versions(python_versions) if not os.path.isdir(archive_destination_dir): os.makedirs(archive_destination_dir) archive_name = _set_archive_name( package_name, package_version, python_versions, platform, build_tag) archive_path = os.path.join(archive_destination_dir, archive_name) _handle_output_file(archive_path, force) _generate_metadata_file( workdir, archive_name, platform, python_versions, package_name, package_version, build_tag, source, wheels) _create_wagon_archive(workdir, archive_path, archive_format) if not keep_wheels: logger.debug('Removing work directory...') shutil.rmtree(tempdir, ignore_errors=True) if validate_archive: validate(archive_path) logger.info('Wagon created successfully at: %s', archive_path) return archive_path
[ "def", "create", "(", "source", ",", "requirement_files", "=", "None", ",", "force", "=", "False", ",", "keep_wheels", "=", "False", ",", "archive_destination_dir", "=", "'.'", ",", "python_versions", "=", "None", ",", "validate_archive", "=", "False", ",", ...
Create a Wagon archive and returns its path. Package name and version are extracted from the setup.py file of the `source` or from the PACKAGE_NAME==PACKAGE_VERSION if the source is a PyPI package. Supported `python_versions` must be in the format e.g [33, 27, 2, 3].. `force` will remove any excess dirs or archives before creation. `requirement_files` can be either a link/local path to a requirements.txt file or just `.`, in which case requirement files will be automatically extracted from either the GitHub archive URL or the local path provided provided in `source`.
[ "Create", "a", "Wagon", "archive", "and", "returns", "its", "path", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L691-L773
26,753
cloudify-cosmo/wagon
wagon.py
install
def install(source, venv=None, requirement_files=None, upgrade=False, ignore_platform=False, install_args=''): """Install a Wagon archive. This can install in a provided `venv` or in the current virtualenv in case one is currently active. `upgrade` is merely pip's upgrade. `ignore_platform` will allow to ignore the platform check, meaning that if an archive was created for a specific platform (e.g. win32), and the current platform is different, it will still attempt to install it. Platform check will fail on the following: If not linux and no platform match (e.g. win32 vs. darwin) If linux and: architecture doesn't match (e.g. manylinux1_x86_64 vs. linux_i686) wheel not manylinux and no platform match (linux_x86_64 vs. linux_i686) """ requirement_files = requirement_files or [] logger.info('Installing %s', source) processed_source = get_source(source) metadata = _get_metadata(processed_source) def raise_unsupported_platform(machine_platform): # TODO: Print which platform is supported? raise WagonError( 'Platform unsupported for wagon ({0})'.format( machine_platform)) try: supported_platform = metadata['supported_platform'] if not ignore_platform and supported_platform != ALL_PLATFORMS_TAG: logger.debug( 'Validating Platform %s is supported...', supported_platform) machine_platform = get_platform() if not _is_platform_supported( supported_platform, machine_platform): raise_unsupported_platform(machine_platform) wheels_path = os.path.join(processed_source, DEFAULT_WHEELS_PATH) install_package( metadata['package_name'], wheels_path, venv, requirement_files, upgrade, install_args) finally: # Install can only be done on local or remote archives. # This means that a temporary directory is always created # with the sources to install within it. This is why we can allow # ourselves to delete the parent dir without worrying. # TODO: Make this even less dangerous by changing `get_source` # to return the directory to delete instead. Much safer. if processed_source != source: shutil.rmtree(os.path.dirname( processed_source), ignore_errors=True)
python
def install(source, venv=None, requirement_files=None, upgrade=False, ignore_platform=False, install_args=''): requirement_files = requirement_files or [] logger.info('Installing %s', source) processed_source = get_source(source) metadata = _get_metadata(processed_source) def raise_unsupported_platform(machine_platform): # TODO: Print which platform is supported? raise WagonError( 'Platform unsupported for wagon ({0})'.format( machine_platform)) try: supported_platform = metadata['supported_platform'] if not ignore_platform and supported_platform != ALL_PLATFORMS_TAG: logger.debug( 'Validating Platform %s is supported...', supported_platform) machine_platform = get_platform() if not _is_platform_supported( supported_platform, machine_platform): raise_unsupported_platform(machine_platform) wheels_path = os.path.join(processed_source, DEFAULT_WHEELS_PATH) install_package( metadata['package_name'], wheels_path, venv, requirement_files, upgrade, install_args) finally: # Install can only be done on local or remote archives. # This means that a temporary directory is always created # with the sources to install within it. This is why we can allow # ourselves to delete the parent dir without worrying. # TODO: Make this even less dangerous by changing `get_source` # to return the directory to delete instead. Much safer. if processed_source != source: shutil.rmtree(os.path.dirname( processed_source), ignore_errors=True)
[ "def", "install", "(", "source", ",", "venv", "=", "None", ",", "requirement_files", "=", "None", ",", "upgrade", "=", "False", ",", "ignore_platform", "=", "False", ",", "install_args", "=", "''", ")", ":", "requirement_files", "=", "requirement_files", "or...
Install a Wagon archive. This can install in a provided `venv` or in the current virtualenv in case one is currently active. `upgrade` is merely pip's upgrade. `ignore_platform` will allow to ignore the platform check, meaning that if an archive was created for a specific platform (e.g. win32), and the current platform is different, it will still attempt to install it. Platform check will fail on the following: If not linux and no platform match (e.g. win32 vs. darwin) If linux and: architecture doesn't match (e.g. manylinux1_x86_64 vs. linux_i686) wheel not manylinux and no platform match (linux_x86_64 vs. linux_i686)
[ "Install", "a", "Wagon", "archive", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L791-L855
26,754
cloudify-cosmo/wagon
wagon.py
validate
def validate(source): """Validate a Wagon archive. Return True if succeeds, False otherwise. It also prints a list of all validation errors. This will test that some of the metadata is solid, that the required wheels are present within the archives and that the package is installable. Note that if the metadata file is corrupted, validation of the required wheels will be corrupted as well, since validation checks that the required wheels exist vs. the list of wheels supplied in the `wheels` key. """ _assert_virtualenv_is_installed() logger.info('Validating %s', source) processed_source = get_source(source) metadata = _get_metadata(processed_source) wheels_path = os.path.join(processed_source, DEFAULT_WHEELS_PATH) validation_errors = [] logger.debug('Verifying that all required files exist...') for wheel in metadata['wheels']: if not os.path.isfile(os.path.join(wheels_path, wheel)): validation_errors.append( '{0} is missing from the archive'.format(wheel)) logger.debug('Testing package installation...') tmpenv = _make_virtualenv() try: install(source=processed_source, venv=tmpenv) if not _check_installed(metadata['package_name'], tmpenv): validation_errors.append( '{0} failed to install (Reason unknown)'.format( metadata['package_name'])) finally: shutil.rmtree(tmpenv) if validation_errors: logger.info('Validation failed!') for error in validation_errors: logger.info(error) logger.info('Source can be found at: %s', processed_source) else: logger.info('Validation Passed!') if processed_source != source: shutil.rmtree(processed_source) return validation_errors
python
def validate(source): _assert_virtualenv_is_installed() logger.info('Validating %s', source) processed_source = get_source(source) metadata = _get_metadata(processed_source) wheels_path = os.path.join(processed_source, DEFAULT_WHEELS_PATH) validation_errors = [] logger.debug('Verifying that all required files exist...') for wheel in metadata['wheels']: if not os.path.isfile(os.path.join(wheels_path, wheel)): validation_errors.append( '{0} is missing from the archive'.format(wheel)) logger.debug('Testing package installation...') tmpenv = _make_virtualenv() try: install(source=processed_source, venv=tmpenv) if not _check_installed(metadata['package_name'], tmpenv): validation_errors.append( '{0} failed to install (Reason unknown)'.format( metadata['package_name'])) finally: shutil.rmtree(tmpenv) if validation_errors: logger.info('Validation failed!') for error in validation_errors: logger.info(error) logger.info('Source can be found at: %s', processed_source) else: logger.info('Validation Passed!') if processed_source != source: shutil.rmtree(processed_source) return validation_errors
[ "def", "validate", "(", "source", ")", ":", "_assert_virtualenv_is_installed", "(", ")", "logger", ".", "info", "(", "'Validating %s'", ",", "source", ")", "processed_source", "=", "get_source", "(", "source", ")", "metadata", "=", "_get_metadata", "(", "process...
Validate a Wagon archive. Return True if succeeds, False otherwise. It also prints a list of all validation errors. This will test that some of the metadata is solid, that the required wheels are present within the archives and that the package is installable. Note that if the metadata file is corrupted, validation of the required wheels will be corrupted as well, since validation checks that the required wheels exist vs. the list of wheels supplied in the `wheels` key.
[ "Validate", "a", "Wagon", "archive", ".", "Return", "True", "if", "succeeds", "False", "otherwise", ".", "It", "also", "prints", "a", "list", "of", "all", "validation", "errors", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L866-L914
26,755
cloudify-cosmo/wagon
wagon.py
show
def show(source): """Merely returns the metadata for the provided archive. """ if is_verbose(): logger.info('Retrieving Metadata for: %s', source) processed_source = get_source(source) metadata = _get_metadata(processed_source) shutil.rmtree(processed_source) return metadata
python
def show(source): if is_verbose(): logger.info('Retrieving Metadata for: %s', source) processed_source = get_source(source) metadata = _get_metadata(processed_source) shutil.rmtree(processed_source) return metadata
[ "def", "show", "(", "source", ")", ":", "if", "is_verbose", "(", ")", ":", "logger", ".", "info", "(", "'Retrieving Metadata for: %s'", ",", "source", ")", "processed_source", "=", "get_source", "(", "source", ")", "metadata", "=", "_get_metadata", "(", "pro...
Merely returns the metadata for the provided archive.
[ "Merely", "returns", "the", "metadata", "for", "the", "provided", "archive", "." ]
9876d33a0aece01df2421a87e3b398d13f660fe6
https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L917-L925
26,756
scottjbarr/bitfinex
bitfinex/client.py
Client._convert_to_floats
def _convert_to_floats(self, data): """ Convert all values in a dict to floats """ for key, value in data.items(): data[key] = float(value) return data
python
def _convert_to_floats(self, data): for key, value in data.items(): data[key] = float(value) return data
[ "def", "_convert_to_floats", "(", "self", ",", "data", ")", ":", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", "data", "[", "key", "]", "=", "float", "(", "value", ")", "return", "data" ]
Convert all values in a dict to floats
[ "Convert", "all", "values", "in", "a", "dict", "to", "floats" ]
03f7c71615fe38c2e28be0ebb761d3106ef0a51a
https://github.com/scottjbarr/bitfinex/blob/03f7c71615fe38c2e28be0ebb761d3106ef0a51a/bitfinex/client.py#L497-L504
26,757
intuition-io/intuition
intuition/api/portfolio.py
PortfolioFactory.update
def update(self, portfolio, date, perfs=None): ''' Actualizes the portfolio universe with the alog state ''' # Make the manager aware of current simulation self.portfolio = portfolio self.perfs = perfs self.date = date
python
def update(self, portfolio, date, perfs=None): ''' Actualizes the portfolio universe with the alog state ''' # Make the manager aware of current simulation self.portfolio = portfolio self.perfs = perfs self.date = date
[ "def", "update", "(", "self", ",", "portfolio", ",", "date", ",", "perfs", "=", "None", ")", ":", "# Make the manager aware of current simulation", "self", ".", "portfolio", "=", "portfolio", "self", ".", "perfs", "=", "perfs", "self", ".", "date", "=", "dat...
Actualizes the portfolio universe with the alog state
[ "Actualizes", "the", "portfolio", "universe", "with", "the", "alog", "state" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/portfolio.py#L77-L84
26,758
intuition-io/intuition
intuition/api/portfolio.py
PortfolioFactory.trade_signals_handler
def trade_signals_handler(self, signals): ''' Process buy and sell signals from the simulation ''' alloc = {} if signals['buy'] or signals['sell']: # Compute the optimal portfolio allocation, # Using user defined function try: alloc, e_ret, e_risk = self.optimize( self.date, signals['buy'], signals['sell'], self._optimizer_parameters) except Exception, error: raise PortfolioOptimizationFailed( reason=error, date=self.date, data=signals) return _remove_useless_orders(alloc)
python
def trade_signals_handler(self, signals): ''' Process buy and sell signals from the simulation ''' alloc = {} if signals['buy'] or signals['sell']: # Compute the optimal portfolio allocation, # Using user defined function try: alloc, e_ret, e_risk = self.optimize( self.date, signals['buy'], signals['sell'], self._optimizer_parameters) except Exception, error: raise PortfolioOptimizationFailed( reason=error, date=self.date, data=signals) return _remove_useless_orders(alloc)
[ "def", "trade_signals_handler", "(", "self", ",", "signals", ")", ":", "alloc", "=", "{", "}", "if", "signals", "[", "'buy'", "]", "or", "signals", "[", "'sell'", "]", ":", "# Compute the optimal portfolio allocation,", "# Using user defined function", "try", ":",...
Process buy and sell signals from the simulation
[ "Process", "buy", "and", "sell", "signals", "from", "the", "simulation" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/portfolio.py#L86-L102
26,759
intuition-io/intuition
intuition/data/remote.py
historical_pandas_yahoo
def historical_pandas_yahoo(symbol, source='yahoo', start=None, end=None): ''' Fetch from yahoo! finance historical quotes ''' #NOTE Panel for multiple symbols ? #NOTE Adj Close column name not cool (a space) return DataReader(symbol, source, start=start, end=end)
python
def historical_pandas_yahoo(symbol, source='yahoo', start=None, end=None): ''' Fetch from yahoo! finance historical quotes ''' #NOTE Panel for multiple symbols ? #NOTE Adj Close column name not cool (a space) return DataReader(symbol, source, start=start, end=end)
[ "def", "historical_pandas_yahoo", "(", "symbol", ",", "source", "=", "'yahoo'", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "#NOTE Panel for multiple symbols ?", "#NOTE Adj Close column name not cool (a space)", "return", "DataReader", "(", "symbol", ...
Fetch from yahoo! finance historical quotes
[ "Fetch", "from", "yahoo!", "finance", "historical", "quotes" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/remote.py#L26-L32
26,760
intuition-io/intuition
intuition/finance.py
average_returns
def average_returns(ts, **kwargs): ''' Compute geometric average returns from a returns time serie''' average_type = kwargs.get('type', 'net') if average_type == 'net': relative = 0 else: relative = -1 # gross #start = kwargs.get('start', ts.index[0]) #end = kwargs.get('end', ts.index[len(ts.index) - 1]) #delta = kwargs.get('delta', ts.index[1] - ts.index[0]) period = kwargs.get('period', None) if isinstance(period, int): pass #else: #ts = reIndexDF(ts, start=start, end=end, delta=delta) #period = 1 avg_ret = 1 for idx in range(len(ts.index)): if idx % period == 0: avg_ret *= (1 + ts[idx] + relative) return avg_ret - 1
python
def average_returns(ts, **kwargs): ''' Compute geometric average returns from a returns time serie''' average_type = kwargs.get('type', 'net') if average_type == 'net': relative = 0 else: relative = -1 # gross #start = kwargs.get('start', ts.index[0]) #end = kwargs.get('end', ts.index[len(ts.index) - 1]) #delta = kwargs.get('delta', ts.index[1] - ts.index[0]) period = kwargs.get('period', None) if isinstance(period, int): pass #else: #ts = reIndexDF(ts, start=start, end=end, delta=delta) #period = 1 avg_ret = 1 for idx in range(len(ts.index)): if idx % period == 0: avg_ret *= (1 + ts[idx] + relative) return avg_ret - 1
[ "def", "average_returns", "(", "ts", ",", "*", "*", "kwargs", ")", ":", "average_type", "=", "kwargs", ".", "get", "(", "'type'", ",", "'net'", ")", "if", "average_type", "==", "'net'", ":", "relative", "=", "0", "else", ":", "relative", "=", "-", "1...
Compute geometric average returns from a returns time serie
[ "Compute", "geometric", "average", "returns", "from", "a", "returns", "time", "serie" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/finance.py#L116-L136
26,761
intuition-io/intuition
intuition/finance.py
returns
def returns(ts, **kwargs): ''' Compute returns on the given period @param ts : time serie to process @param kwargs.type: gross or simple returns @param delta : period betweend two computed returns @param start : with end, will return the return betweend this elapsed time @param period : delta is the number of lines/periods provided @param end : so said @param cumulative: compute cumulative returns ''' returns_type = kwargs.get('type', 'net') cumulative = kwargs.get('cumulative', False) if returns_type == 'net': relative = 0 else: relative = 1 # gross start = kwargs.get('start', None) end = kwargs.get('end', dt.datetime.today()) #delta = kwargs.get('delta', None) period = kwargs.get('period', 1) if isinstance(start, dt.datetime): log.debug('{} / {} -1'.format(ts[end], ts[start])) return ts[end] / ts[start] - 1 + relative #elif isinstance(delta, pd.DateOffset) or isinstance(delta, dt.timedelta): #FIXME timezone problem #FIXME reIndexDF is deprecated #ts = reIndexDF(ts, delta=delta) #period = 1 rets_df = ts / ts.shift(period) - 1 + relative if cumulative: return rets_df.cumprod() return rets_df[1:]
python
def returns(ts, **kwargs): ''' Compute returns on the given period @param ts : time serie to process @param kwargs.type: gross or simple returns @param delta : period betweend two computed returns @param start : with end, will return the return betweend this elapsed time @param period : delta is the number of lines/periods provided @param end : so said @param cumulative: compute cumulative returns ''' returns_type = kwargs.get('type', 'net') cumulative = kwargs.get('cumulative', False) if returns_type == 'net': relative = 0 else: relative = 1 # gross start = kwargs.get('start', None) end = kwargs.get('end', dt.datetime.today()) #delta = kwargs.get('delta', None) period = kwargs.get('period', 1) if isinstance(start, dt.datetime): log.debug('{} / {} -1'.format(ts[end], ts[start])) return ts[end] / ts[start] - 1 + relative #elif isinstance(delta, pd.DateOffset) or isinstance(delta, dt.timedelta): #FIXME timezone problem #FIXME reIndexDF is deprecated #ts = reIndexDF(ts, delta=delta) #period = 1 rets_df = ts / ts.shift(period) - 1 + relative if cumulative: return rets_df.cumprod() return rets_df[1:]
[ "def", "returns", "(", "ts", ",", "*", "*", "kwargs", ")", ":", "returns_type", "=", "kwargs", ".", "get", "(", "'type'", ",", "'net'", ")", "cumulative", "=", "kwargs", ".", "get", "(", "'cumulative'", ",", "False", ")", "if", "returns_type", "==", ...
Compute returns on the given period @param ts : time serie to process @param kwargs.type: gross or simple returns @param delta : period betweend two computed returns @param start : with end, will return the return betweend this elapsed time @param period : delta is the number of lines/periods provided @param end : so said @param cumulative: compute cumulative returns
[ "Compute", "returns", "on", "the", "given", "period" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/finance.py#L151-L184
26,762
intuition-io/intuition
intuition/finance.py
daily_returns
def daily_returns(ts, **kwargs): ''' re-compute ts on a daily basis ''' relative = kwargs.get('relative', 0) return returns(ts, delta=BDay(), relative=relative)
python
def daily_returns(ts, **kwargs): ''' re-compute ts on a daily basis ''' relative = kwargs.get('relative', 0) return returns(ts, delta=BDay(), relative=relative)
[ "def", "daily_returns", "(", "ts", ",", "*", "*", "kwargs", ")", ":", "relative", "=", "kwargs", ".", "get", "(", "'relative'", ",", "0", ")", "return", "returns", "(", "ts", ",", "delta", "=", "BDay", "(", ")", ",", "relative", "=", "relative", ")...
re-compute ts on a daily basis
[ "re", "-", "compute", "ts", "on", "a", "daily", "basis" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/finance.py#L187-L190
26,763
Callidon/pyHDT
setup.py
list_files
def list_files(path, extension=".cpp", exclude="S.cpp"): """List paths to all files that ends with a given extension""" return ["%s/%s" % (path, f) for f in listdir(path) if f.endswith(extension) and (not f.endswith(exclude))]
python
def list_files(path, extension=".cpp", exclude="S.cpp"): return ["%s/%s" % (path, f) for f in listdir(path) if f.endswith(extension) and (not f.endswith(exclude))]
[ "def", "list_files", "(", "path", ",", "extension", "=", "\".cpp\"", ",", "exclude", "=", "\"S.cpp\"", ")", ":", "return", "[", "\"%s/%s\"", "%", "(", "path", ",", "f", ")", "for", "f", "in", "listdir", "(", "path", ")", "if", "f", ".", "endswith", ...
List paths to all files that ends with a given extension
[ "List", "paths", "to", "all", "files", "that", "ends", "with", "a", "given", "extension" ]
8b18c950ee98ab554d34d9fddacab962d3989b55
https://github.com/Callidon/pyHDT/blob/8b18c950ee98ab554d34d9fddacab962d3989b55/setup.py#L15-L17
26,764
intuition-io/intuition
intuition/cli.py
intuition
def intuition(args): ''' Main simulation wrapper Load the configuration, run the engine and return the analyze. ''' # Use the provided context builder to fill: # - config: General behavior # - strategy: Modules properties # - market: The universe we will trade on with setup.Context(args['context']) as context: # Backtest or live engine. # Registers configuration and setups data client simulation = Simulation() # Intuition building blocks modules = context['config']['modules'] # Prepare benchmark, timezone, trading calendar simulation.configure_environment( context['config']['index'][-1], context['market'].benchmark, context['market'].timezone) # Wire togetether modules and initialize them simulation.build(args['session'], modules, context['strategy']) # Build data generator # NOTE How can I use several sources ? data = {'universe': context['market'], 'index': context['config']['index']} # Add user settings data.update(context['strategy']['data']) # Load backtest and / or live module(s) if 'backtest' in modules: data['backtest'] = utils.intuition_module(modules['backtest']) if 'live' in modules: data['live'] = utils.intuition_module(modules['live']) # Run the simulation and return an intuition.core.analyzes object return simulation(datafeed.HybridDataFactory(**data), args['bot'])
python
def intuition(args): ''' Main simulation wrapper Load the configuration, run the engine and return the analyze. ''' # Use the provided context builder to fill: # - config: General behavior # - strategy: Modules properties # - market: The universe we will trade on with setup.Context(args['context']) as context: # Backtest or live engine. # Registers configuration and setups data client simulation = Simulation() # Intuition building blocks modules = context['config']['modules'] # Prepare benchmark, timezone, trading calendar simulation.configure_environment( context['config']['index'][-1], context['market'].benchmark, context['market'].timezone) # Wire togetether modules and initialize them simulation.build(args['session'], modules, context['strategy']) # Build data generator # NOTE How can I use several sources ? data = {'universe': context['market'], 'index': context['config']['index']} # Add user settings data.update(context['strategy']['data']) # Load backtest and / or live module(s) if 'backtest' in modules: data['backtest'] = utils.intuition_module(modules['backtest']) if 'live' in modules: data['live'] = utils.intuition_module(modules['live']) # Run the simulation and return an intuition.core.analyzes object return simulation(datafeed.HybridDataFactory(**data), args['bot'])
[ "def", "intuition", "(", "args", ")", ":", "# Use the provided context builder to fill:", "# - config: General behavior", "# - strategy: Modules properties", "# - market: The universe we will trade on", "with", "setup", ".", "Context", "(", "args", "[", "'context'", "]", ...
Main simulation wrapper Load the configuration, run the engine and return the analyze.
[ "Main", "simulation", "wrapper", "Load", "the", "configuration", "run", "the", "engine", "and", "return", "the", "analyze", "." ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/cli.py#L25-L68
26,765
intuition-io/intuition
intuition/api/algorithm.py
TradingFactory._is_interactive
def _is_interactive(self): ''' Prevent middlewares and orders to work outside live mode ''' return not ( self.realworld and (dt.date.today() > self.datetime.date()))
python
def _is_interactive(self): ''' Prevent middlewares and orders to work outside live mode ''' return not ( self.realworld and (dt.date.today() > self.datetime.date()))
[ "def", "_is_interactive", "(", "self", ")", ":", "return", "not", "(", "self", ".", "realworld", "and", "(", "dt", ".", "date", ".", "today", "(", ")", ">", "self", ".", "datetime", ".", "date", "(", ")", ")", ")" ]
Prevent middlewares and orders to work outside live mode
[ "Prevent", "middlewares", "and", "orders", "to", "work", "outside", "live", "mode" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/algorithm.py#L46-L49
26,766
intuition-io/intuition
intuition/api/algorithm.py
TradingFactory.use
def use(self, func, when='whenever'): ''' Append a middleware to the algorithm ''' #NOTE A middleware Object ? # self.use() is usually called from initialize(), so no logger yet print('registering middleware {}'.format(func.__name__)) self.middlewares.append({ 'call': func, 'name': func.__name__, 'args': func.func_code.co_varnames, 'when': when })
python
def use(self, func, when='whenever'): ''' Append a middleware to the algorithm ''' #NOTE A middleware Object ? # self.use() is usually called from initialize(), so no logger yet print('registering middleware {}'.format(func.__name__)) self.middlewares.append({ 'call': func, 'name': func.__name__, 'args': func.func_code.co_varnames, 'when': when })
[ "def", "use", "(", "self", ",", "func", ",", "when", "=", "'whenever'", ")", ":", "#NOTE A middleware Object ?", "# self.use() is usually called from initialize(), so no logger yet", "print", "(", "'registering middleware {}'", ".", "format", "(", "func", ".", "__name__",...
Append a middleware to the algorithm
[ "Append", "a", "middleware", "to", "the", "algorithm" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/algorithm.py#L51-L61
26,767
intuition-io/intuition
intuition/api/algorithm.py
TradingFactory.process_orders
def process_orders(self, orderbook): ''' Default and costant orders processor. Overwrite it for more sophisticated strategies ''' for stock, alloc in orderbook.iteritems(): self.logger.info('{}: Ordered {} {} stocks'.format( self.datetime, stock, alloc)) if isinstance(alloc, int): self.order(stock, alloc) elif isinstance(alloc, float) and \ alloc >= -1 and alloc <= 1: self.order_percent(stock, alloc) else: self.logger.warning( '{}: invalid order for {}: {})' .format(self.datetime, stock, alloc))
python
def process_orders(self, orderbook): ''' Default and costant orders processor. Overwrite it for more sophisticated strategies ''' for stock, alloc in orderbook.iteritems(): self.logger.info('{}: Ordered {} {} stocks'.format( self.datetime, stock, alloc)) if isinstance(alloc, int): self.order(stock, alloc) elif isinstance(alloc, float) and \ alloc >= -1 and alloc <= 1: self.order_percent(stock, alloc) else: self.logger.warning( '{}: invalid order for {}: {})' .format(self.datetime, stock, alloc))
[ "def", "process_orders", "(", "self", ",", "orderbook", ")", ":", "for", "stock", ",", "alloc", "in", "orderbook", ".", "iteritems", "(", ")", ":", "self", ".", "logger", ".", "info", "(", "'{}: Ordered {} {} stocks'", ".", "format", "(", "self", ".", "d...
Default and costant orders processor. Overwrite it for more sophisticated strategies
[ "Default", "and", "costant", "orders", "processor", ".", "Overwrite", "it", "for", "more", "sophisticated", "strategies" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/algorithm.py#L114-L128
26,768
intuition-io/intuition
intuition/api/algorithm.py
TradingFactory._call_one_middleware
def _call_one_middleware(self, middleware): ''' Evaluate arguments and execute the middleware function ''' args = {} for arg in middleware['args']: if hasattr(self, arg): # same as eval() but safer for arbitrary code execution args[arg] = reduce(getattr, arg.split('.'), self) self.logger.debug('calling middleware event {}' .format(middleware['name'])) middleware['call'](**args)
python
def _call_one_middleware(self, middleware): ''' Evaluate arguments and execute the middleware function ''' args = {} for arg in middleware['args']: if hasattr(self, arg): # same as eval() but safer for arbitrary code execution args[arg] = reduce(getattr, arg.split('.'), self) self.logger.debug('calling middleware event {}' .format(middleware['name'])) middleware['call'](**args)
[ "def", "_call_one_middleware", "(", "self", ",", "middleware", ")", ":", "args", "=", "{", "}", "for", "arg", "in", "middleware", "[", "'args'", "]", ":", "if", "hasattr", "(", "self", ",", "arg", ")", ":", "# same as eval() but safer for arbitrary code execut...
Evaluate arguments and execute the middleware function
[ "Evaluate", "arguments", "and", "execute", "the", "middleware", "function" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/algorithm.py#L130-L139
26,769
intuition-io/intuition
intuition/api/algorithm.py
TradingFactory._call_middlewares
def _call_middlewares(self): ''' Execute the middleware stack ''' for middleware in self.middlewares: if self._check_condition(middleware['when']): self._call_one_middleware(middleware)
python
def _call_middlewares(self): ''' Execute the middleware stack ''' for middleware in self.middlewares: if self._check_condition(middleware['when']): self._call_one_middleware(middleware)
[ "def", "_call_middlewares", "(", "self", ")", ":", "for", "middleware", "in", "self", ".", "middlewares", ":", "if", "self", ".", "_check_condition", "(", "middleware", "[", "'when'", "]", ")", ":", "self", ".", "_call_one_middleware", "(", "middleware", ")"...
Execute the middleware stack
[ "Execute", "the", "middleware", "stack" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/algorithm.py#L146-L150
26,770
intuition-io/intuition
intuition/data/loader.py
LiveBenchmark.normalize_date
def normalize_date(self, test_date): ''' Same function as zipline.finance.trading.py''' test_date = pd.Timestamp(test_date, tz='UTC') return pd.tseries.tools.normalize_date(test_date)
python
def normalize_date(self, test_date): ''' Same function as zipline.finance.trading.py''' test_date = pd.Timestamp(test_date, tz='UTC') return pd.tseries.tools.normalize_date(test_date)
[ "def", "normalize_date", "(", "self", ",", "test_date", ")", ":", "test_date", "=", "pd", ".", "Timestamp", "(", "test_date", ",", "tz", "=", "'UTC'", ")", "return", "pd", ".", "tseries", ".", "tools", ".", "normalize_date", "(", "test_date", ")" ]
Same function as zipline.finance.trading.py
[ "Same", "function", "as", "zipline", ".", "finance", ".", "trading", ".", "py" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/loader.py#L32-L35
26,771
intuition-io/intuition
intuition/data/universe.py
Market._load_market_scheme
def _load_market_scheme(self): ''' Load market yaml description ''' try: self.scheme = yaml.load(open(self.scheme_path, 'r')) except Exception, error: raise LoadMarketSchemeFailed(reason=error)
python
def _load_market_scheme(self): ''' Load market yaml description ''' try: self.scheme = yaml.load(open(self.scheme_path, 'r')) except Exception, error: raise LoadMarketSchemeFailed(reason=error)
[ "def", "_load_market_scheme", "(", "self", ")", ":", "try", ":", "self", ".", "scheme", "=", "yaml", ".", "load", "(", "open", "(", "self", ".", "scheme_path", ",", "'r'", ")", ")", "except", "Exception", ",", "error", ":", "raise", "LoadMarketSchemeFail...
Load market yaml description
[ "Load", "market", "yaml", "description" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/universe.py#L44-L49
26,772
intuition-io/intuition
intuition/data/quandl.py
DataQuandl.fetch
def fetch(self, code, **kwargs): ''' Quandl entry point in datafeed object ''' log.debug('fetching QuanDL data (%s)' % code) # This way you can use your credentials even if # you didn't provide them to the constructor if 'authtoken' in kwargs: self.quandl_key = kwargs.pop('authtoken') # Harmonization: Quandl call start trim_start if 'start' in kwargs: kwargs['trim_start'] = kwargs.pop('start') if 'end' in kwargs: kwargs['trim_end'] = kwargs.pop('end') try: data = Quandl.get(code, authtoken=self.quandl_key, **kwargs) # FIXME With a symbol not found, insert a not_found column data.index = data.index.tz_localize(pytz.utc) except Exception, error: log.error('unable to fetch {}: {}'.format(code, error)) data = pd.DataFrame() return data
python
def fetch(self, code, **kwargs): ''' Quandl entry point in datafeed object ''' log.debug('fetching QuanDL data (%s)' % code) # This way you can use your credentials even if # you didn't provide them to the constructor if 'authtoken' in kwargs: self.quandl_key = kwargs.pop('authtoken') # Harmonization: Quandl call start trim_start if 'start' in kwargs: kwargs['trim_start'] = kwargs.pop('start') if 'end' in kwargs: kwargs['trim_end'] = kwargs.pop('end') try: data = Quandl.get(code, authtoken=self.quandl_key, **kwargs) # FIXME With a symbol not found, insert a not_found column data.index = data.index.tz_localize(pytz.utc) except Exception, error: log.error('unable to fetch {}: {}'.format(code, error)) data = pd.DataFrame() return data
[ "def", "fetch", "(", "self", ",", "code", ",", "*", "*", "kwargs", ")", ":", "log", ".", "debug", "(", "'fetching QuanDL data (%s)'", "%", "code", ")", "# This way you can use your credentials even if", "# you didn't provide them to the constructor", "if", "'authtoken'"...
Quandl entry point in datafeed object
[ "Quandl", "entry", "point", "in", "datafeed", "object" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/quandl.py#L90-L113
26,773
intuition-io/intuition
intuition/core/analyzes.py
Analyze.rolling_performances
def rolling_performances(self, timestamp='one_month'): ''' Filters self.perfs ''' # TODO Study the impact of month choice # TODO Check timestamp in an enumeration # TODO Implement other benchmarks for perf computation # (zipline issue, maybe expected) if self.metrics: perfs = {} length = range(len(self.metrics[timestamp])) index = self._get_index(self.metrics[timestamp]) perf_keys = self.metrics[timestamp][0].keys() perf_keys.pop(perf_keys.index('period_label')) perfs['period'] = np.array( [pd.datetime.date(date) for date in index]) for key in perf_keys: perfs[key] = self._to_perf_array(timestamp, key, length) else: # TODO Get it from DB if it exists raise NotImplementedError() return pd.DataFrame(perfs, index=index)
python
def rolling_performances(self, timestamp='one_month'): ''' Filters self.perfs ''' # TODO Study the impact of month choice # TODO Check timestamp in an enumeration # TODO Implement other benchmarks for perf computation # (zipline issue, maybe expected) if self.metrics: perfs = {} length = range(len(self.metrics[timestamp])) index = self._get_index(self.metrics[timestamp]) perf_keys = self.metrics[timestamp][0].keys() perf_keys.pop(perf_keys.index('period_label')) perfs['period'] = np.array( [pd.datetime.date(date) for date in index]) for key in perf_keys: perfs[key] = self._to_perf_array(timestamp, key, length) else: # TODO Get it from DB if it exists raise NotImplementedError() return pd.DataFrame(perfs, index=index)
[ "def", "rolling_performances", "(", "self", ",", "timestamp", "=", "'one_month'", ")", ":", "# TODO Study the impact of month choice", "# TODO Check timestamp in an enumeration", "# TODO Implement other benchmarks for perf computation", "# (zipline issue, maybe expected)", "if", "self"...
Filters self.perfs
[ "Filters", "self", ".", "perfs" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/core/analyzes.py#L87-L109
26,774
intuition-io/intuition
intuition/core/analyzes.py
Analyze.overall_metrics
def overall_metrics(self, timestamp='one_month', metrics=None): ''' Use zipline results to compute some performance indicators ''' perfs = dict() # If no rolling perfs provided, computes it if metrics is None: metrics = self.rolling_performances(timestamp=timestamp) riskfree = np.mean(metrics['treasury_period_return']) perfs['sharpe'] = qstk_get_sharpe_ratio( metrics['algorithm_period_return'].values, risk_free=riskfree) perfs['algorithm_period_return'] = ( ((metrics['algorithm_period_return'] + 1).cumprod()) - 1)[-1] perfs['max_drawdown'] = max(metrics['max_drawdown']) perfs['algo_volatility'] = np.mean(metrics['algo_volatility']) perfs['beta'] = np.mean(metrics['beta']) perfs['alpha'] = np.mean(metrics['alpha']) perfs['benchmark_period_return'] = ( ((metrics['benchmark_period_return'] + 1).cumprod()) - 1)[-1] return perfs
python
def overall_metrics(self, timestamp='one_month', metrics=None): ''' Use zipline results to compute some performance indicators ''' perfs = dict() # If no rolling perfs provided, computes it if metrics is None: metrics = self.rolling_performances(timestamp=timestamp) riskfree = np.mean(metrics['treasury_period_return']) perfs['sharpe'] = qstk_get_sharpe_ratio( metrics['algorithm_period_return'].values, risk_free=riskfree) perfs['algorithm_period_return'] = ( ((metrics['algorithm_period_return'] + 1).cumprod()) - 1)[-1] perfs['max_drawdown'] = max(metrics['max_drawdown']) perfs['algo_volatility'] = np.mean(metrics['algo_volatility']) perfs['beta'] = np.mean(metrics['beta']) perfs['alpha'] = np.mean(metrics['alpha']) perfs['benchmark_period_return'] = ( ((metrics['benchmark_period_return'] + 1).cumprod()) - 1)[-1] return perfs
[ "def", "overall_metrics", "(", "self", ",", "timestamp", "=", "'one_month'", ",", "metrics", "=", "None", ")", ":", "perfs", "=", "dict", "(", ")", "# If no rolling perfs provided, computes it", "if", "metrics", "is", "None", ":", "metrics", "=", "self", ".", ...
Use zipline results to compute some performance indicators
[ "Use", "zipline", "results", "to", "compute", "some", "performance", "indicators" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/core/analyzes.py#L111-L133
26,775
intuition-io/intuition
intuition/api/context.py
ContextFactory._normalize_data_types
def _normalize_data_types(self, strategy): ''' some contexts only retrieves strings, giving back right type ''' for k, v in strategy.iteritems(): if not isinstance(v, str): # There is probably nothing to do continue if v == 'true': strategy[k] = True elif v == 'false' or v is None: strategy[k] = False else: try: if v.find('.') > 0: strategy[k] = float(v) else: strategy[k] = int(v) except ValueError: pass
python
def _normalize_data_types(self, strategy): ''' some contexts only retrieves strings, giving back right type ''' for k, v in strategy.iteritems(): if not isinstance(v, str): # There is probably nothing to do continue if v == 'true': strategy[k] = True elif v == 'false' or v is None: strategy[k] = False else: try: if v.find('.') > 0: strategy[k] = float(v) else: strategy[k] = int(v) except ValueError: pass
[ "def", "_normalize_data_types", "(", "self", ",", "strategy", ")", ":", "for", "k", ",", "v", "in", "strategy", ".", "iteritems", "(", ")", ":", "if", "not", "isinstance", "(", "v", ",", "str", ")", ":", "# There is probably nothing to do", "continue", "if...
some contexts only retrieves strings, giving back right type
[ "some", "contexts", "only", "retrieves", "strings", "giving", "back", "right", "type" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/context.py#L86-L103
26,776
intuition-io/intuition
intuition/core/engine.py
Simulation._get_benchmark_handler
def _get_benchmark_handler(self, last_trade, freq='minutely'): ''' Setup a custom benchmark handler or let zipline manage it ''' return LiveBenchmark( last_trade, frequency=freq).surcharge_market_data \ if utils.is_live(last_trade) else None
python
def _get_benchmark_handler(self, last_trade, freq='minutely'): ''' Setup a custom benchmark handler or let zipline manage it ''' return LiveBenchmark( last_trade, frequency=freq).surcharge_market_data \ if utils.is_live(last_trade) else None
[ "def", "_get_benchmark_handler", "(", "self", ",", "last_trade", ",", "freq", "=", "'minutely'", ")", ":", "return", "LiveBenchmark", "(", "last_trade", ",", "frequency", "=", "freq", ")", ".", "surcharge_market_data", "if", "utils", ".", "is_live", "(", "last...
Setup a custom benchmark handler or let zipline manage it
[ "Setup", "a", "custom", "benchmark", "handler", "or", "let", "zipline", "manage", "it" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/core/engine.py#L64-L70
26,777
intuition-io/intuition
intuition/core/engine.py
Simulation.configure_environment
def configure_environment(self, last_trade, benchmark, timezone): ''' Prepare benchmark loader and trading context ''' if last_trade.tzinfo is None: last_trade = pytz.utc.localize(last_trade) # Setup the trading calendar from market informations self.benchmark = benchmark self.context = TradingEnvironment( bm_symbol=benchmark, exchange_tz=timezone, load=self._get_benchmark_handler(last_trade))
python
def configure_environment(self, last_trade, benchmark, timezone): ''' Prepare benchmark loader and trading context ''' if last_trade.tzinfo is None: last_trade = pytz.utc.localize(last_trade) # Setup the trading calendar from market informations self.benchmark = benchmark self.context = TradingEnvironment( bm_symbol=benchmark, exchange_tz=timezone, load=self._get_benchmark_handler(last_trade))
[ "def", "configure_environment", "(", "self", ",", "last_trade", ",", "benchmark", ",", "timezone", ")", ":", "if", "last_trade", ".", "tzinfo", "is", "None", ":", "last_trade", "=", "pytz", ".", "utc", ".", "localize", "(", "last_trade", ")", "# Setup the tr...
Prepare benchmark loader and trading context
[ "Prepare", "benchmark", "loader", "and", "trading", "context" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/core/engine.py#L72-L83
26,778
intuition-io/intuition
intuition/data/utils.py
apply_mapping
def apply_mapping(raw_row, mapping): ''' Override this to hand craft conversion of row. ''' row = {target: mapping_func(raw_row[source_key]) for target, (mapping_func, source_key) in mapping.fget().items()} return row
python
def apply_mapping(raw_row, mapping): ''' Override this to hand craft conversion of row. ''' row = {target: mapping_func(raw_row[source_key]) for target, (mapping_func, source_key) in mapping.fget().items()} return row
[ "def", "apply_mapping", "(", "raw_row", ",", "mapping", ")", ":", "row", "=", "{", "target", ":", "mapping_func", "(", "raw_row", "[", "source_key", "]", ")", "for", "target", ",", "(", "mapping_func", ",", "source_key", ")", "in", "mapping", ".", "fget"...
Override this to hand craft conversion of row.
[ "Override", "this", "to", "hand", "craft", "conversion", "of", "row", "." ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/utils.py#L25-L32
26,779
intuition-io/intuition
intuition/data/utils.py
invert_dataframe_axis
def invert_dataframe_axis(fct): ''' Make dataframe index column names, and vice et versa ''' def inner(*args, **kwargs): df_to_invert = fct(*args, **kwargs) return pd.DataFrame(df_to_invert.to_dict().values(), index=df_to_invert.to_dict().keys()) return inner
python
def invert_dataframe_axis(fct): ''' Make dataframe index column names, and vice et versa ''' def inner(*args, **kwargs): df_to_invert = fct(*args, **kwargs) return pd.DataFrame(df_to_invert.to_dict().values(), index=df_to_invert.to_dict().keys()) return inner
[ "def", "invert_dataframe_axis", "(", "fct", ")", ":", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "df_to_invert", "=", "fct", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "pd", ".", "DataFrame", "(", "df_to_inver...
Make dataframe index column names, and vice et versa
[ "Make", "dataframe", "index", "column", "names", "and", "vice", "et", "versa" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/utils.py#L35-L44
26,780
intuition-io/intuition
intuition/data/utils.py
use_google_symbol
def use_google_symbol(fct): ''' Removes ".PA" or other market indicator from yahoo symbol convention to suit google convention ''' def decorator(symbols): google_symbols = [] # If one symbol string if isinstance(symbols, str): symbols = [symbols] symbols = sorted(symbols) for symbol in symbols: dot_pos = symbol.find('.') google_symbols.append( symbol[:dot_pos] if (dot_pos > 0) else symbol) data = fct(google_symbols) #NOTE Not very elegant data.columns = [s for s in symbols if s.split('.')[0] in data.columns] return data return decorator
python
def use_google_symbol(fct): ''' Removes ".PA" or other market indicator from yahoo symbol convention to suit google convention ''' def decorator(symbols): google_symbols = [] # If one symbol string if isinstance(symbols, str): symbols = [symbols] symbols = sorted(symbols) for symbol in symbols: dot_pos = symbol.find('.') google_symbols.append( symbol[:dot_pos] if (dot_pos > 0) else symbol) data = fct(google_symbols) #NOTE Not very elegant data.columns = [s for s in symbols if s.split('.')[0] in data.columns] return data return decorator
[ "def", "use_google_symbol", "(", "fct", ")", ":", "def", "decorator", "(", "symbols", ")", ":", "google_symbols", "=", "[", "]", "# If one symbol string", "if", "isinstance", "(", "symbols", ",", "str", ")", ":", "symbols", "=", "[", "symbols", "]", "symbo...
Removes ".PA" or other market indicator from yahoo symbol convention to suit google convention
[ "Removes", ".", "PA", "or", "other", "market", "indicator", "from", "yahoo", "symbol", "convention", "to", "suit", "google", "convention" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/utils.py#L48-L70
26,781
intuition-io/intuition
intuition/data/ystockquote.py
get_sector
def get_sector(symbol): ''' Uses BeautifulSoup to scrape stock sector from Yahoo! Finance website ''' url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol soup = BeautifulSoup(urlopen(url).read()) try: sector = soup.find('td', text='Sector:').\ find_next_sibling().string.encode('utf-8') except: sector = '' return sector
python
def get_sector(symbol): ''' Uses BeautifulSoup to scrape stock sector from Yahoo! Finance website ''' url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol soup = BeautifulSoup(urlopen(url).read()) try: sector = soup.find('td', text='Sector:').\ find_next_sibling().string.encode('utf-8') except: sector = '' return sector
[ "def", "get_sector", "(", "symbol", ")", ":", "url", "=", "'http://finance.yahoo.com/q/pr?s=%s+Profile'", "%", "symbol", "soup", "=", "BeautifulSoup", "(", "urlopen", "(", "url", ")", ".", "read", "(", ")", ")", "try", ":", "sector", "=", "soup", ".", "fin...
Uses BeautifulSoup to scrape stock sector from Yahoo! Finance website
[ "Uses", "BeautifulSoup", "to", "scrape", "stock", "sector", "from", "Yahoo!", "Finance", "website" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/ystockquote.py#L465-L476
26,782
intuition-io/intuition
intuition/data/ystockquote.py
get_industry
def get_industry(symbol): ''' Uses BeautifulSoup to scrape stock industry from Yahoo! Finance website ''' url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol soup = BeautifulSoup(urlopen(url).read()) try: industry = soup.find('td', text='Industry:').\ find_next_sibling().string.encode('utf-8') except: industry = '' return industry
python
def get_industry(symbol): ''' Uses BeautifulSoup to scrape stock industry from Yahoo! Finance website ''' url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol soup = BeautifulSoup(urlopen(url).read()) try: industry = soup.find('td', text='Industry:').\ find_next_sibling().string.encode('utf-8') except: industry = '' return industry
[ "def", "get_industry", "(", "symbol", ")", ":", "url", "=", "'http://finance.yahoo.com/q/pr?s=%s+Profile'", "%", "symbol", "soup", "=", "BeautifulSoup", "(", "urlopen", "(", "url", ")", ".", "read", "(", ")", ")", "try", ":", "industry", "=", "soup", ".", ...
Uses BeautifulSoup to scrape stock industry from Yahoo! Finance website
[ "Uses", "BeautifulSoup", "to", "scrape", "stock", "industry", "from", "Yahoo!", "Finance", "website" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/ystockquote.py#L479-L490
26,783
intuition-io/intuition
intuition/data/ystockquote.py
get_type
def get_type(symbol): ''' Uses BeautifulSoup to scrape symbol category from Yahoo! Finance website ''' url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol soup = BeautifulSoup(urlopen(url).read()) if soup.find('span', text='Business Summary'): return 'Stock' elif soup.find('span', text='Fund Summary'): asset_type = 'Fund' elif symbol.find('^') == 0: asset_type = 'Index' else: pass return asset_type
python
def get_type(symbol): ''' Uses BeautifulSoup to scrape symbol category from Yahoo! Finance website ''' url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol soup = BeautifulSoup(urlopen(url).read()) if soup.find('span', text='Business Summary'): return 'Stock' elif soup.find('span', text='Fund Summary'): asset_type = 'Fund' elif symbol.find('^') == 0: asset_type = 'Index' else: pass return asset_type
[ "def", "get_type", "(", "symbol", ")", ":", "url", "=", "'http://finance.yahoo.com/q/pr?s=%s+Profile'", "%", "symbol", "soup", "=", "BeautifulSoup", "(", "urlopen", "(", "url", ")", ".", "read", "(", ")", ")", "if", "soup", ".", "find", "(", "'span'", ",",...
Uses BeautifulSoup to scrape symbol category from Yahoo! Finance website
[ "Uses", "BeautifulSoup", "to", "scrape", "symbol", "category", "from", "Yahoo!", "Finance", "website" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/ystockquote.py#L493-L507
26,784
intuition-io/intuition
intuition/data/ystockquote.py
get_historical_prices
def get_historical_prices(symbol, start_date, end_date): """ Get historical prices for the given ticker symbol. Date format is 'YYYY-MM-DD' Returns a nested dictionary (dict of dicts). outer dict keys are dates ('YYYY-MM-DD') """ params = urlencode({ 's': symbol, 'a': int(start_date[5:7]) - 1, 'b': int(start_date[8:10]), 'c': int(start_date[0:4]), 'd': int(end_date[5:7]) - 1, 'e': int(end_date[8:10]), 'f': int(end_date[0:4]), 'g': 'd', 'ignore': '.csv', }) url = 'http://ichart.yahoo.com/table.csv?%s' % params req = Request(url) resp = urlopen(req) content = str(resp.read().decode('utf-8').strip()) daily_data = content.splitlines() hist_dict = dict() keys = daily_data[0].split(',') for day in daily_data[1:]: day_data = day.split(',') date = day_data[0] hist_dict[date] = \ {keys[1]: day_data[1], keys[2]: day_data[2], keys[3]: day_data[3], keys[4]: day_data[4], keys[5]: day_data[5], keys[6]: day_data[6]} return hist_dict
python
def get_historical_prices(symbol, start_date, end_date): params = urlencode({ 's': symbol, 'a': int(start_date[5:7]) - 1, 'b': int(start_date[8:10]), 'c': int(start_date[0:4]), 'd': int(end_date[5:7]) - 1, 'e': int(end_date[8:10]), 'f': int(end_date[0:4]), 'g': 'd', 'ignore': '.csv', }) url = 'http://ichart.yahoo.com/table.csv?%s' % params req = Request(url) resp = urlopen(req) content = str(resp.read().decode('utf-8').strip()) daily_data = content.splitlines() hist_dict = dict() keys = daily_data[0].split(',') for day in daily_data[1:]: day_data = day.split(',') date = day_data[0] hist_dict[date] = \ {keys[1]: day_data[1], keys[2]: day_data[2], keys[3]: day_data[3], keys[4]: day_data[4], keys[5]: day_data[5], keys[6]: day_data[6]} return hist_dict
[ "def", "get_historical_prices", "(", "symbol", ",", "start_date", ",", "end_date", ")", ":", "params", "=", "urlencode", "(", "{", "'s'", ":", "symbol", ",", "'a'", ":", "int", "(", "start_date", "[", "5", ":", "7", "]", ")", "-", "1", ",", "'b'", ...
Get historical prices for the given ticker symbol. Date format is 'YYYY-MM-DD' Returns a nested dictionary (dict of dicts). outer dict keys are dates ('YYYY-MM-DD')
[ "Get", "historical", "prices", "for", "the", "given", "ticker", "symbol", ".", "Date", "format", "is", "YYYY", "-", "MM", "-", "DD" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/ystockquote.py#L524-L560
26,785
intuition-io/intuition
intuition/data/forex.py
_fx_mapping
def _fx_mapping(raw_rates): ''' Map raw output to clearer labels ''' return {pair[0].lower(): { 'timeStamp': pair[1], 'bid': float(pair[2] + pair[3]), 'ask': float(pair[4] + pair[5]), 'high': float(pair[6]), 'low': float(pair[7]) } for pair in map(lambda x: x.split(','), raw_rates)}
python
def _fx_mapping(raw_rates): ''' Map raw output to clearer labels ''' return {pair[0].lower(): { 'timeStamp': pair[1], 'bid': float(pair[2] + pair[3]), 'ask': float(pair[4] + pair[5]), 'high': float(pair[6]), 'low': float(pair[7]) } for pair in map(lambda x: x.split(','), raw_rates)}
[ "def", "_fx_mapping", "(", "raw_rates", ")", ":", "return", "{", "pair", "[", "0", "]", ".", "lower", "(", ")", ":", "{", "'timeStamp'", ":", "pair", "[", "1", "]", ",", "'bid'", ":", "float", "(", "pair", "[", "2", "]", "+", "pair", "[", "3", ...
Map raw output to clearer labels
[ "Map", "raw", "output", "to", "clearer", "labels" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/forex.py#L29-L37
26,786
intuition-io/intuition
intuition/data/forex.py
TrueFX.query_rates
def query_rates(self, pairs=[]): ''' Perform a request against truefx data ''' # If no pairs, TrueFx will use the ones given the last time payload = {'id': self._session} if pairs: payload['c'] = _clean_pairs(pairs) response = requests.get(self._api_url, params=payload) mapped_data = _fx_mapping(response.content.split('\n')[:-2]) return Series(mapped_data) if len(mapped_data) == 1 \ else DataFrame(mapped_data)
python
def query_rates(self, pairs=[]): ''' Perform a request against truefx data ''' # If no pairs, TrueFx will use the ones given the last time payload = {'id': self._session} if pairs: payload['c'] = _clean_pairs(pairs) response = requests.get(self._api_url, params=payload) mapped_data = _fx_mapping(response.content.split('\n')[:-2]) return Series(mapped_data) if len(mapped_data) == 1 \ else DataFrame(mapped_data)
[ "def", "query_rates", "(", "self", ",", "pairs", "=", "[", "]", ")", ":", "# If no pairs, TrueFx will use the ones given the last time", "payload", "=", "{", "'id'", ":", "self", ".", "_session", "}", "if", "pairs", ":", "payload", "[", "'c'", "]", "=", "_cl...
Perform a request against truefx data
[ "Perform", "a", "request", "against", "truefx", "data" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/forex.py#L75-L85
26,787
intuition-io/intuition
intuition/utils.py
next_tick
def next_tick(date, interval=15): ''' Only return when we reach given datetime ''' # Intuition works with utc dates, conversion are made for I/O now = dt.datetime.now(pytz.utc) live = False # Sleep until we reach the given date while now < date: time.sleep(interval) # Update current time now = dt.datetime.now(pytz.utc) # Since we're here, we waited a future date, so this is live trading live = True return live
python
def next_tick(date, interval=15): ''' Only return when we reach given datetime ''' # Intuition works with utc dates, conversion are made for I/O now = dt.datetime.now(pytz.utc) live = False # Sleep until we reach the given date while now < date: time.sleep(interval) # Update current time now = dt.datetime.now(pytz.utc) # Since we're here, we waited a future date, so this is live trading live = True return live
[ "def", "next_tick", "(", "date", ",", "interval", "=", "15", ")", ":", "# Intuition works with utc dates, conversion are made for I/O", "now", "=", "dt", ".", "datetime", ".", "now", "(", "pytz", ".", "utc", ")", "live", "=", "False", "# Sleep until we reach the g...
Only return when we reach given datetime
[ "Only", "return", "when", "we", "reach", "given", "datetime" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/utils.py#L26-L40
26,788
intuition-io/intuition
intuition/utils.py
intuition_module
def intuition_module(location): ''' Build the module path and import it ''' path = location.split('.') # Get the last field, i.e. the object name in the file obj = path.pop(-1) return dna.utils.dynamic_import('.'.join(path), obj)
python
def intuition_module(location): ''' Build the module path and import it ''' path = location.split('.') # Get the last field, i.e. the object name in the file obj = path.pop(-1) return dna.utils.dynamic_import('.'.join(path), obj)
[ "def", "intuition_module", "(", "location", ")", ":", "path", "=", "location", ".", "split", "(", "'.'", ")", "# Get the last field, i.e. the object name in the file", "obj", "=", "path", ".", "pop", "(", "-", "1", ")", "return", "dna", ".", "utils", ".", "d...
Build the module path and import it
[ "Build", "the", "module", "path", "and", "import", "it" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/utils.py#L43-L48
26,789
intuition-io/intuition
intuition/utils.py
build_trading_timeline
def build_trading_timeline(start, end): ''' Build the daily-based index we will trade on ''' EMPTY_DATES = pd.date_range('2000/01/01', periods=0, tz=pytz.utc) now = dt.datetime.now(tz=pytz.utc) if not start: if not end: # Live trading until the end of the day bt_dates = EMPTY_DATES live_dates = pd.date_range( start=now, end=normalize_date_format('23h59')) else: end = normalize_date_format(end) if end < now: # Backtesting since a year before end bt_dates = pd.date_range( start=end - 360 * pd.datetools.day, end=end) live_dates = EMPTY_DATES elif end > now: # Live trading from now to end bt_dates = EMPTY_DATES live_dates = pd.date_range(start=now, end=end) else: start = normalize_date_format(start) if start < now: if not end: # Backtest for a year or until now end = start + 360 * pd.datetools.day if end > now: end = now - pd.datetools.day live_dates = EMPTY_DATES bt_dates = pd.date_range( start=start, end=end) else: end = normalize_date_format(end) if end < now: # Nothing to do, backtest from start to end live_dates = EMPTY_DATES bt_dates = pd.date_range(start=start, end=end) elif end > now: # Hybrid timeline, backtest from start to end, live # trade from now to end bt_dates = pd.date_range( start=start, end=now - pd.datetools.day) live_dates = pd.date_range(start=now, end=end) elif start > now: if not end: # Live trading from start to the end of the day bt_dates = EMPTY_DATES live_dates = pd.date_range( start=start, end=normalize_date_format('23h59')) else: # Live trading from start to end end = normalize_date_format(end) bt_dates = EMPTY_DATES live_dates = pd.date_range(start=start, end=end) return bt_dates + live_dates
python
def build_trading_timeline(start, end): ''' Build the daily-based index we will trade on ''' EMPTY_DATES = pd.date_range('2000/01/01', periods=0, tz=pytz.utc) now = dt.datetime.now(tz=pytz.utc) if not start: if not end: # Live trading until the end of the day bt_dates = EMPTY_DATES live_dates = pd.date_range( start=now, end=normalize_date_format('23h59')) else: end = normalize_date_format(end) if end < now: # Backtesting since a year before end bt_dates = pd.date_range( start=end - 360 * pd.datetools.day, end=end) live_dates = EMPTY_DATES elif end > now: # Live trading from now to end bt_dates = EMPTY_DATES live_dates = pd.date_range(start=now, end=end) else: start = normalize_date_format(start) if start < now: if not end: # Backtest for a year or until now end = start + 360 * pd.datetools.day if end > now: end = now - pd.datetools.day live_dates = EMPTY_DATES bt_dates = pd.date_range( start=start, end=end) else: end = normalize_date_format(end) if end < now: # Nothing to do, backtest from start to end live_dates = EMPTY_DATES bt_dates = pd.date_range(start=start, end=end) elif end > now: # Hybrid timeline, backtest from start to end, live # trade from now to end bt_dates = pd.date_range( start=start, end=now - pd.datetools.day) live_dates = pd.date_range(start=now, end=end) elif start > now: if not end: # Live trading from start to the end of the day bt_dates = EMPTY_DATES live_dates = pd.date_range( start=start, end=normalize_date_format('23h59')) else: # Live trading from start to end end = normalize_date_format(end) bt_dates = EMPTY_DATES live_dates = pd.date_range(start=start, end=end) return bt_dates + live_dates
[ "def", "build_trading_timeline", "(", "start", ",", "end", ")", ":", "EMPTY_DATES", "=", "pd", ".", "date_range", "(", "'2000/01/01'", ",", "periods", "=", "0", ",", "tz", "=", "pytz", ".", "utc", ")", "now", "=", "dt", ".", "datetime", ".", "now", "...
Build the daily-based index we will trade on
[ "Build", "the", "daily", "-", "based", "index", "we", "will", "trade", "on" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/utils.py#L52-L113
26,790
phn/jdcal
jdcal.py
is_leap
def is_leap(year): """Leap year or not in the Gregorian calendar.""" x = math.fmod(year, 4) y = math.fmod(year, 100) z = math.fmod(year, 400) # Divisible by 4 and, # either not divisible by 100 or divisible by 400. return not x and (y or not z)
python
def is_leap(year): x = math.fmod(year, 4) y = math.fmod(year, 100) z = math.fmod(year, 400) # Divisible by 4 and, # either not divisible by 100 or divisible by 400. return not x and (y or not z)
[ "def", "is_leap", "(", "year", ")", ":", "x", "=", "math", ".", "fmod", "(", "year", ",", "4", ")", "y", "=", "math", ".", "fmod", "(", "year", ",", "100", ")", "z", "=", "math", ".", "fmod", "(", "year", ",", "400", ")", "# Divisible by 4 and,...
Leap year or not in the Gregorian calendar.
[ "Leap", "year", "or", "not", "in", "the", "Gregorian", "calendar", "." ]
1e65e9be80a9d38b5f9001161b49c52a0a6f05e6
https://github.com/phn/jdcal/blob/1e65e9be80a9d38b5f9001161b49c52a0a6f05e6/jdcal.py#L56-L64
26,791
phn/jdcal
jdcal.py
gcal2jd
def gcal2jd(year, month, day): """Gregorian calendar date to Julian date. The input and output are for the proleptic Gregorian calendar, i.e., no consideration of historical usage of the calendar is made. Parameters ---------- year : int Year as an integer. month : int Month as an integer. day : int Day as an integer. Returns ------- jd1, jd2: 2-element tuple of floats When added together, the numbers give the Julian date for the given Gregorian calendar date. The first number is always MJD_0 i.e., 2451545.5. So the second is the MJD. Examples -------- >>> gcal2jd(2000,1,1) (2400000.5, 51544.0) >>> 2400000.5 + 51544.0 + 0.5 2451545.0 >>> year = [-4699, -2114, -1050, -123, -1, 0, 1, 123, 1678.0, 2000, ....: 2012, 2245] >>> month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> day = [1, 12, 23, 14, 25, 16, 27, 8, 9, 10, 11, 31] >>> x = [gcal2jd(y, m, d) for y, m, d in zip(year, month, day)] >>> for i in x: print i (2400000.5, -2395215.0) (2400000.5, -1451021.0) (2400000.5, -1062364.0) (2400000.5, -723762.0) (2400000.5, -679162.0) (2400000.5, -678774.0) (2400000.5, -678368.0) (2400000.5, -633797.0) (2400000.5, -65812.0) (2400000.5, 51827.0) (2400000.5, 56242.0) (2400000.5, 141393.0) Negative months and days are valid. For example, 2000/-2/-4 => 1999/+12-2/-4 => 1999/10/-4 => 1999/9/30-4 => 1999/9/26. >>> gcal2jd(2000, -2, -4) (2400000.5, 51447.0) >>> gcal2jd(1999, 9, 26) (2400000.5, 51447.0) >>> gcal2jd(2000, 2, -1) (2400000.5, 51573.0) >>> gcal2jd(2000, 1, 30) (2400000.5, 51573.0) >>> gcal2jd(2000, 3, -1) (2400000.5, 51602.0) >>> gcal2jd(2000, 2, 28) (2400000.5, 51602.0) Month 0 becomes previous month. >>> gcal2jd(2000, 0, 1) (2400000.5, 51513.0) >>> gcal2jd(1999, 12, 1) (2400000.5, 51513.0) Day number 0 becomes last day of previous month. >>> gcal2jd(2000, 3, 0) (2400000.5, 51603.0) >>> gcal2jd(2000, 2, 29) (2400000.5, 51603.0) If `day` is greater than the number of days in `month`, then it gets carried over to the next month. >>> gcal2jd(2000,2,30) (2400000.5, 51604.0) >>> gcal2jd(2000,3,1) (2400000.5, 51604.0) >>> gcal2jd(2001,2,30) (2400000.5, 51970.0) >>> gcal2jd(2001,3,2) (2400000.5, 51970.0) Notes ----- The returned Julian date is for mid-night of the given date. To find the Julian date for any time of the day, simply add time as a fraction of a day. For example Julian date for mid-day can be obtained by adding 0.5 to either the first part or the second part. The latter is preferable, since it will give the MJD for the date and time. BC dates should be given as -(BC - 1) where BC is the year. For example 1 BC == 0, 2 BC == -1, and so on. Negative numbers can be used for `month` and `day`. For example 2000, -1, 1 is the same as 1999, 11, 1. The Julian dates are proleptic Julian dates, i.e., values are returned without considering if Gregorian dates are valid for the given date. The input values are truncated to integers. """ year = int(year) month = int(month) day = int(day) a = ipart((month - 14) / 12.0) jd = ipart((1461 * (year + 4800 + a)) / 4.0) jd += ipart((367 * (month - 2 - 12 * a)) / 12.0) x = ipart((year + 4900 + a) / 100.0) jd -= ipart((3 * x) / 4.0) jd += day - 2432075.5 # was 32075; add 2400000.5 jd -= 0.5 # 0 hours; above JD is for midday, switch to midnight. return MJD_0, jd
python
def gcal2jd(year, month, day): year = int(year) month = int(month) day = int(day) a = ipart((month - 14) / 12.0) jd = ipart((1461 * (year + 4800 + a)) / 4.0) jd += ipart((367 * (month - 2 - 12 * a)) / 12.0) x = ipart((year + 4900 + a) / 100.0) jd -= ipart((3 * x) / 4.0) jd += day - 2432075.5 # was 32075; add 2400000.5 jd -= 0.5 # 0 hours; above JD is for midday, switch to midnight. return MJD_0, jd
[ "def", "gcal2jd", "(", "year", ",", "month", ",", "day", ")", ":", "year", "=", "int", "(", "year", ")", "month", "=", "int", "(", "month", ")", "day", "=", "int", "(", "day", ")", "a", "=", "ipart", "(", "(", "month", "-", "14", ")", "/", ...
Gregorian calendar date to Julian date. The input and output are for the proleptic Gregorian calendar, i.e., no consideration of historical usage of the calendar is made. Parameters ---------- year : int Year as an integer. month : int Month as an integer. day : int Day as an integer. Returns ------- jd1, jd2: 2-element tuple of floats When added together, the numbers give the Julian date for the given Gregorian calendar date. The first number is always MJD_0 i.e., 2451545.5. So the second is the MJD. Examples -------- >>> gcal2jd(2000,1,1) (2400000.5, 51544.0) >>> 2400000.5 + 51544.0 + 0.5 2451545.0 >>> year = [-4699, -2114, -1050, -123, -1, 0, 1, 123, 1678.0, 2000, ....: 2012, 2245] >>> month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> day = [1, 12, 23, 14, 25, 16, 27, 8, 9, 10, 11, 31] >>> x = [gcal2jd(y, m, d) for y, m, d in zip(year, month, day)] >>> for i in x: print i (2400000.5, -2395215.0) (2400000.5, -1451021.0) (2400000.5, -1062364.0) (2400000.5, -723762.0) (2400000.5, -679162.0) (2400000.5, -678774.0) (2400000.5, -678368.0) (2400000.5, -633797.0) (2400000.5, -65812.0) (2400000.5, 51827.0) (2400000.5, 56242.0) (2400000.5, 141393.0) Negative months and days are valid. For example, 2000/-2/-4 => 1999/+12-2/-4 => 1999/10/-4 => 1999/9/30-4 => 1999/9/26. >>> gcal2jd(2000, -2, -4) (2400000.5, 51447.0) >>> gcal2jd(1999, 9, 26) (2400000.5, 51447.0) >>> gcal2jd(2000, 2, -1) (2400000.5, 51573.0) >>> gcal2jd(2000, 1, 30) (2400000.5, 51573.0) >>> gcal2jd(2000, 3, -1) (2400000.5, 51602.0) >>> gcal2jd(2000, 2, 28) (2400000.5, 51602.0) Month 0 becomes previous month. >>> gcal2jd(2000, 0, 1) (2400000.5, 51513.0) >>> gcal2jd(1999, 12, 1) (2400000.5, 51513.0) Day number 0 becomes last day of previous month. >>> gcal2jd(2000, 3, 0) (2400000.5, 51603.0) >>> gcal2jd(2000, 2, 29) (2400000.5, 51603.0) If `day` is greater than the number of days in `month`, then it gets carried over to the next month. >>> gcal2jd(2000,2,30) (2400000.5, 51604.0) >>> gcal2jd(2000,3,1) (2400000.5, 51604.0) >>> gcal2jd(2001,2,30) (2400000.5, 51970.0) >>> gcal2jd(2001,3,2) (2400000.5, 51970.0) Notes ----- The returned Julian date is for mid-night of the given date. To find the Julian date for any time of the day, simply add time as a fraction of a day. For example Julian date for mid-day can be obtained by adding 0.5 to either the first part or the second part. The latter is preferable, since it will give the MJD for the date and time. BC dates should be given as -(BC - 1) where BC is the year. For example 1 BC == 0, 2 BC == -1, and so on. Negative numbers can be used for `month` and `day`. For example 2000, -1, 1 is the same as 1999, 11, 1. The Julian dates are proleptic Julian dates, i.e., values are returned without considering if Gregorian dates are valid for the given date. The input values are truncated to integers.
[ "Gregorian", "calendar", "date", "to", "Julian", "date", "." ]
1e65e9be80a9d38b5f9001161b49c52a0a6f05e6
https://github.com/phn/jdcal/blob/1e65e9be80a9d38b5f9001161b49c52a0a6f05e6/jdcal.py#L67-L195
26,792
phn/jdcal
jdcal.py
jd2gcal
def jd2gcal(jd1, jd2): """Julian date to Gregorian calendar date and time of day. The input and output are for the proleptic Gregorian calendar, i.e., no consideration of historical usage of the calendar is made. Parameters ---------- jd1, jd2: int Sum of the two numbers is taken as the given Julian date. For example `jd1` can be the zero point of MJD (MJD_0) and `jd2` can be the MJD of the date and time. But any combination will work. Returns ------- y, m, d, f : int, int, int, float Four element tuple containing year, month, day and the fractional part of the day in the Gregorian calendar. The first three are integers, and the last part is a float. Examples -------- >>> jd2gcal(*gcal2jd(2000,1,1)) (2000, 1, 1, 0.0) >>> jd2gcal(*gcal2jd(1950,1,1)) (1950, 1, 1, 0.0) Out of range months and days are carried over to the next/previous year or next/previous month. See gcal2jd for more examples. >>> jd2gcal(*gcal2jd(1999,10,12)) (1999, 10, 12, 0.0) >>> jd2gcal(*gcal2jd(2000,2,30)) (2000, 3, 1, 0.0) >>> jd2gcal(*gcal2jd(-1999,10,12)) (-1999, 10, 12, 0.0) >>> jd2gcal(*gcal2jd(2000, -2, -4)) (1999, 9, 26, 0.0) >>> gcal2jd(2000,1,1) (2400000.5, 51544.0) >>> jd2gcal(2400000.5, 51544.0) (2000, 1, 1, 0.0) >>> jd2gcal(2400000.5, 51544.5) (2000, 1, 1, 0.5) >>> jd2gcal(2400000.5, 51544.245) (2000, 1, 1, 0.24500000000261934) >>> jd2gcal(2400000.5, 51544.1) (2000, 1, 1, 0.099999999998544808) >>> jd2gcal(2400000.5, 51544.75) (2000, 1, 1, 0.75) Notes ----- The last element of the tuple is the same as (hh + mm / 60.0 + ss / 3600.0) / 24.0 where hh, mm, and ss are the hour, minute and second of the day. See Also -------- gcal2jd """ from math import modf jd1_f, jd1_i = modf(jd1) jd2_f, jd2_i = modf(jd2) jd_i = jd1_i + jd2_i f = jd1_f + jd2_f # Set JD to noon of the current date. Fractional part is the # fraction from midnight of the current date. if -0.5 < f < 0.5: f += 0.5 elif f >= 0.5: jd_i += 1 f -= 0.5 elif f <= -0.5: jd_i -= 1 f += 1.5 l = jd_i + 68569 n = ipart((4 * l) / 146097.0) l -= ipart(((146097 * n) + 3) / 4.0) i = ipart((4000 * (l + 1)) / 1461001) l -= ipart((1461 * i) / 4.0) - 31 j = ipart((80 * l) / 2447.0) day = l - ipart((2447 * j) / 80.0) l = ipart(j / 11.0) month = j + 2 - (12 * l) year = 100 * (n - 49) + i + l return int(year), int(month), int(day), f
python
def jd2gcal(jd1, jd2): from math import modf jd1_f, jd1_i = modf(jd1) jd2_f, jd2_i = modf(jd2) jd_i = jd1_i + jd2_i f = jd1_f + jd2_f # Set JD to noon of the current date. Fractional part is the # fraction from midnight of the current date. if -0.5 < f < 0.5: f += 0.5 elif f >= 0.5: jd_i += 1 f -= 0.5 elif f <= -0.5: jd_i -= 1 f += 1.5 l = jd_i + 68569 n = ipart((4 * l) / 146097.0) l -= ipart(((146097 * n) + 3) / 4.0) i = ipart((4000 * (l + 1)) / 1461001) l -= ipart((1461 * i) / 4.0) - 31 j = ipart((80 * l) / 2447.0) day = l - ipart((2447 * j) / 80.0) l = ipart(j / 11.0) month = j + 2 - (12 * l) year = 100 * (n - 49) + i + l return int(year), int(month), int(day), f
[ "def", "jd2gcal", "(", "jd1", ",", "jd2", ")", ":", "from", "math", "import", "modf", "jd1_f", ",", "jd1_i", "=", "modf", "(", "jd1", ")", "jd2_f", ",", "jd2_i", "=", "modf", "(", "jd2", ")", "jd_i", "=", "jd1_i", "+", "jd2_i", "f", "=", "jd1_f",...
Julian date to Gregorian calendar date and time of day. The input and output are for the proleptic Gregorian calendar, i.e., no consideration of historical usage of the calendar is made. Parameters ---------- jd1, jd2: int Sum of the two numbers is taken as the given Julian date. For example `jd1` can be the zero point of MJD (MJD_0) and `jd2` can be the MJD of the date and time. But any combination will work. Returns ------- y, m, d, f : int, int, int, float Four element tuple containing year, month, day and the fractional part of the day in the Gregorian calendar. The first three are integers, and the last part is a float. Examples -------- >>> jd2gcal(*gcal2jd(2000,1,1)) (2000, 1, 1, 0.0) >>> jd2gcal(*gcal2jd(1950,1,1)) (1950, 1, 1, 0.0) Out of range months and days are carried over to the next/previous year or next/previous month. See gcal2jd for more examples. >>> jd2gcal(*gcal2jd(1999,10,12)) (1999, 10, 12, 0.0) >>> jd2gcal(*gcal2jd(2000,2,30)) (2000, 3, 1, 0.0) >>> jd2gcal(*gcal2jd(-1999,10,12)) (-1999, 10, 12, 0.0) >>> jd2gcal(*gcal2jd(2000, -2, -4)) (1999, 9, 26, 0.0) >>> gcal2jd(2000,1,1) (2400000.5, 51544.0) >>> jd2gcal(2400000.5, 51544.0) (2000, 1, 1, 0.0) >>> jd2gcal(2400000.5, 51544.5) (2000, 1, 1, 0.5) >>> jd2gcal(2400000.5, 51544.245) (2000, 1, 1, 0.24500000000261934) >>> jd2gcal(2400000.5, 51544.1) (2000, 1, 1, 0.099999999998544808) >>> jd2gcal(2400000.5, 51544.75) (2000, 1, 1, 0.75) Notes ----- The last element of the tuple is the same as (hh + mm / 60.0 + ss / 3600.0) / 24.0 where hh, mm, and ss are the hour, minute and second of the day. See Also -------- gcal2jd
[ "Julian", "date", "to", "Gregorian", "calendar", "date", "and", "time", "of", "day", "." ]
1e65e9be80a9d38b5f9001161b49c52a0a6f05e6
https://github.com/phn/jdcal/blob/1e65e9be80a9d38b5f9001161b49c52a0a6f05e6/jdcal.py#L198-L296
26,793
phn/jdcal
jdcal.py
jcal2jd
def jcal2jd(year, month, day): """Julian calendar date to Julian date. The input and output are for the proleptic Julian calendar, i.e., no consideration of historical usage of the calendar is made. Parameters ---------- year : int Year as an integer. month : int Month as an integer. day : int Day as an integer. Returns ------- jd1, jd2: 2-element tuple of floats When added together, the numbers give the Julian date for the given Julian calendar date. The first number is always MJD_0 i.e., 2451545.5. So the second is the MJD. Examples -------- >>> jcal2jd(2000, 1, 1) (2400000.5, 51557.0) >>> year = [-4699, -2114, -1050, -123, -1, 0, 1, 123, 1678, 2000, ...: 2012, 2245] >>> month = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12] >>> day = [1, 12, 23, 14, 25, 16, 27, 8, 9, 10, 11, 31] >>> x = [jcal2jd(y, m, d) for y, m, d in zip(year, month, day)] >>> for i in x: print i (2400000.5, -2395252.0) (2400000.5, -1451039.0) (2400000.5, -1062374.0) (2400000.5, -723765.0) (2400000.5, -679164.0) (2400000.5, -678776.0) (2400000.5, -678370.0) (2400000.5, -633798.0) (2400000.5, -65772.0) (2400000.5, 51871.0) (2400000.5, 56285.0) Notes ----- Unlike `gcal2jd`, negative months and days can result in incorrect Julian dates. """ year = int(year) month = int(month) day = int(day) jd = 367 * year x = ipart((month - 9) / 7.0) jd -= ipart((7 * (year + 5001 + x)) / 4.0) jd += ipart((275 * month) / 9.0) jd += day jd += 1729777 - 2400000.5 # Return 240000.5 as first part of JD. jd -= 0.5 # Convert midday to midnight. return MJD_0, jd
python
def jcal2jd(year, month, day): year = int(year) month = int(month) day = int(day) jd = 367 * year x = ipart((month - 9) / 7.0) jd -= ipart((7 * (year + 5001 + x)) / 4.0) jd += ipart((275 * month) / 9.0) jd += day jd += 1729777 - 2400000.5 # Return 240000.5 as first part of JD. jd -= 0.5 # Convert midday to midnight. return MJD_0, jd
[ "def", "jcal2jd", "(", "year", ",", "month", ",", "day", ")", ":", "year", "=", "int", "(", "year", ")", "month", "=", "int", "(", "month", ")", "day", "=", "int", "(", "day", ")", "jd", "=", "367", "*", "year", "x", "=", "ipart", "(", "(", ...
Julian calendar date to Julian date. The input and output are for the proleptic Julian calendar, i.e., no consideration of historical usage of the calendar is made. Parameters ---------- year : int Year as an integer. month : int Month as an integer. day : int Day as an integer. Returns ------- jd1, jd2: 2-element tuple of floats When added together, the numbers give the Julian date for the given Julian calendar date. The first number is always MJD_0 i.e., 2451545.5. So the second is the MJD. Examples -------- >>> jcal2jd(2000, 1, 1) (2400000.5, 51557.0) >>> year = [-4699, -2114, -1050, -123, -1, 0, 1, 123, 1678, 2000, ...: 2012, 2245] >>> month = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12] >>> day = [1, 12, 23, 14, 25, 16, 27, 8, 9, 10, 11, 31] >>> x = [jcal2jd(y, m, d) for y, m, d in zip(year, month, day)] >>> for i in x: print i (2400000.5, -2395252.0) (2400000.5, -1451039.0) (2400000.5, -1062374.0) (2400000.5, -723765.0) (2400000.5, -679164.0) (2400000.5, -678776.0) (2400000.5, -678370.0) (2400000.5, -633798.0) (2400000.5, -65772.0) (2400000.5, 51871.0) (2400000.5, 56285.0) Notes ----- Unlike `gcal2jd`, negative months and days can result in incorrect Julian dates.
[ "Julian", "calendar", "date", "to", "Julian", "date", "." ]
1e65e9be80a9d38b5f9001161b49c52a0a6f05e6
https://github.com/phn/jdcal/blob/1e65e9be80a9d38b5f9001161b49c52a0a6f05e6/jdcal.py#L299-L363
26,794
CEA-COSMIC/ModOpt
modopt/base/wrappers.py
add_args_kwargs
def add_args_kwargs(func): """Add Args and Kwargs This wrapper adds support for additional arguments and keyword arguments to any callable function Parameters ---------- func : function Callable function Returns ------- function wrapper """ @wraps(func) def wrapper(*args, **kwargs): props = argspec(func) # if 'args' not in props: if isinstance(props[1], type(None)): args = args[:len(props[0])] if ((not isinstance(props[2], type(None))) or (not isinstance(props[3], type(None)))): return func(*args, **kwargs) else: return func(*args) return wrapper
python
def add_args_kwargs(func): @wraps(func) def wrapper(*args, **kwargs): props = argspec(func) # if 'args' not in props: if isinstance(props[1], type(None)): args = args[:len(props[0])] if ((not isinstance(props[2], type(None))) or (not isinstance(props[3], type(None)))): return func(*args, **kwargs) else: return func(*args) return wrapper
[ "def", "add_args_kwargs", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "props", "=", "argspec", "(", "func", ")", "# if 'args' not in props:", "if", "isinstance", "(", "pr...
Add Args and Kwargs This wrapper adds support for additional arguments and keyword arguments to any callable function Parameters ---------- func : function Callable function Returns ------- function wrapper
[ "Add", "Args", "and", "Kwargs" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/wrappers.py#L19-L55
26,795
CEA-COSMIC/ModOpt
modopt/interface/log.py
set_up_log
def set_up_log(filename, verbose=True): """Set up log This method sets up a basic log. Parameters ---------- filename : str Log file name Returns ------- logging.Logger instance """ # Add file extension. filename += '.log' if verbose: print('Preparing log file:', filename) # Capture warnings. logging.captureWarnings(True) # Set output format. formatter = logging.Formatter(fmt='%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S') # Create file handler. fh = logging.FileHandler(filename=filename, mode='w') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) # Create log. log = logging.getLogger(filename) log.setLevel(logging.DEBUG) log.addHandler(fh) # Send opening message. log.info('The log file has been set-up.') return log
python
def set_up_log(filename, verbose=True): # Add file extension. filename += '.log' if verbose: print('Preparing log file:', filename) # Capture warnings. logging.captureWarnings(True) # Set output format. formatter = logging.Formatter(fmt='%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S') # Create file handler. fh = logging.FileHandler(filename=filename, mode='w') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) # Create log. log = logging.getLogger(filename) log.setLevel(logging.DEBUG) log.addHandler(fh) # Send opening message. log.info('The log file has been set-up.') return log
[ "def", "set_up_log", "(", "filename", ",", "verbose", "=", "True", ")", ":", "# Add file extension.", "filename", "+=", "'.log'", "if", "verbose", ":", "print", "(", "'Preparing log file:'", ",", "filename", ")", "# Capture warnings.", "logging", ".", "captureWarn...
Set up log This method sets up a basic log. Parameters ---------- filename : str Log file name Returns ------- logging.Logger instance
[ "Set", "up", "log" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/interface/log.py#L16-L58
26,796
CEA-COSMIC/ModOpt
modopt/base/observable.py
Observable.add_observer
def add_observer(self, signal, observer): """Add an observer to the object. Raise an exception if the signal is not allowed. Parameters ---------- signal : str a valid signal. observer : @func a function that will be called when the signal is emitted. """ self._is_allowed_signal(signal) self._add_observer(signal, observer)
python
def add_observer(self, signal, observer): self._is_allowed_signal(signal) self._add_observer(signal, observer)
[ "def", "add_observer", "(", "self", ",", "signal", ",", "observer", ")", ":", "self", ".", "_is_allowed_signal", "(", "signal", ")", "self", ".", "_add_observer", "(", "signal", ",", "observer", ")" ]
Add an observer to the object. Raise an exception if the signal is not allowed. Parameters ---------- signal : str a valid signal. observer : @func a function that will be called when the signal is emitted.
[ "Add", "an", "observer", "to", "the", "object", "." ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L51-L66
26,797
CEA-COSMIC/ModOpt
modopt/base/observable.py
Observable.remove_observer
def remove_observer(self, signal, observer): """Remove an observer from the object. Raise an eception if the signal is not allowed. Parameters ---------- signal : str a valid signal. observer : @func an obervation function to be removed. """ self._is_allowed_event(signal) self._remove_observer(signal, observer)
python
def remove_observer(self, signal, observer): self._is_allowed_event(signal) self._remove_observer(signal, observer)
[ "def", "remove_observer", "(", "self", ",", "signal", ",", "observer", ")", ":", "self", ".", "_is_allowed_event", "(", "signal", ")", "self", ".", "_remove_observer", "(", "signal", ",", "observer", ")" ]
Remove an observer from the object. Raise an eception if the signal is not allowed. Parameters ---------- signal : str a valid signal. observer : @func an obervation function to be removed.
[ "Remove", "an", "observer", "from", "the", "object", "." ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L68-L83
26,798
CEA-COSMIC/ModOpt
modopt/base/observable.py
Observable.notify_observers
def notify_observers(self, signal, **kwargs): """ Notify observers of a given signal. Parameters ---------- signal : str a valid signal. kwargs : dict the parameters that will be sent to the observers. Returns ------- out: bool False if a notification is in progress, otherwise True. """ # Check if a notification if in progress if self._locked: return False # Set the lock self._locked = True # Create a signal object signal_to_be_notified = SignalObject() setattr(signal_to_be_notified, "object", self) setattr(signal_to_be_notified, "signal", signal) for name, value in kwargs.items(): setattr(signal_to_be_notified, name, value) # Notify all the observers for observer in self._observers[signal]: observer(signal_to_be_notified) # Unlock the notification process self._locked = False
python
def notify_observers(self, signal, **kwargs): # Check if a notification if in progress if self._locked: return False # Set the lock self._locked = True # Create a signal object signal_to_be_notified = SignalObject() setattr(signal_to_be_notified, "object", self) setattr(signal_to_be_notified, "signal", signal) for name, value in kwargs.items(): setattr(signal_to_be_notified, name, value) # Notify all the observers for observer in self._observers[signal]: observer(signal_to_be_notified) # Unlock the notification process self._locked = False
[ "def", "notify_observers", "(", "self", ",", "signal", ",", "*", "*", "kwargs", ")", ":", "# Check if a notification if in progress", "if", "self", ".", "_locked", ":", "return", "False", "# Set the lock", "self", ".", "_locked", "=", "True", "# Create a signal ob...
Notify observers of a given signal. Parameters ---------- signal : str a valid signal. kwargs : dict the parameters that will be sent to the observers. Returns ------- out: bool False if a notification is in progress, otherwise True.
[ "Notify", "observers", "of", "a", "given", "signal", "." ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L85-L118
26,799
CEA-COSMIC/ModOpt
modopt/base/observable.py
Observable._is_allowed_signal
def _is_allowed_signal(self, signal): """Check if a signal is valid. Raise an exception if the signal is not allowed. Parameters ---------- signal: str a signal. """ if signal not in self._allowed_signals: raise Exception("Signal '{0}' is not allowed for '{1}'.".format( signal, type(self)))
python
def _is_allowed_signal(self, signal): if signal not in self._allowed_signals: raise Exception("Signal '{0}' is not allowed for '{1}'.".format( signal, type(self)))
[ "def", "_is_allowed_signal", "(", "self", ",", "signal", ")", ":", "if", "signal", "not", "in", "self", ".", "_allowed_signals", ":", "raise", "Exception", "(", "\"Signal '{0}' is not allowed for '{1}'.\"", ".", "format", "(", "signal", ",", "type", "(", "self",...
Check if a signal is valid. Raise an exception if the signal is not allowed. Parameters ---------- signal: str a signal.
[ "Check", "if", "a", "signal", "is", "valid", "." ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L137-L151