Search is not available for this dataset
text
stringlengths
75
104k
def wait_for_datacenter(client, data_center_id): ''' Poll the data center to become available (for the next provisionig job) ''' total_sleep_time = 0 seconds = 5 while True: state = client.get_datacenter(data_center_id)['metadata']['state'] if verbose: print("datacent...
def main(argv=None): '''Command line options.''' if argv is None: argv = sys.argv else: sys.argv.extend(argv) program_name = os.path.basename(sys.argv[0]) program_version = "v%s" % __version__ program_build_date = str(__updated__) program_version_message = '%%(prog)s %s (%s...
def getLogin(filename, user, passwd): ''' write user/passwd to login file or get them from file. This method is not Py3 safe (byte vs. str) ''' if filename is None: return (user, passwd) if os.path.exists(filename): print("Using file {} for Login".format(filename)) with o...
def wait_for_request(pbclient, request_id, timeout=0, initial_wait=5, scaleup=10): ''' Waits for a request to finish until timeout. timeout==0 is interpreted as infinite wait time. Returns a tuple (return code, request status, message) where return code 0 : request successful ...
def main(argv=None): '''Parse command line options and create a server/volume composite.''' if argv is None: argv = sys.argv else: sys.argv.extend(argv) program_name = os.path.basename(sys.argv[0]) program_version = "v%s" % __version__ program_build_date = str(__updated__) ...
def main(argv=None): '''Command line options.''' if argv is None: argv = sys.argv else: sys.argv.extend(argv) program_name = os.path.basename(sys.argv[0]) program_version = "v%s" % __version__ program_build_date = str(__updated__) program_version_message = '%%(prog)s %s (%s...
def get_dc_inventory(pbclient, dc=None): ''' gets inventory of one data center''' if pbclient is None: raise ValueError("argument 'pbclient' must not be None") if dc is None: raise ValueError("argument 'dc' must not be None") dc_inv = [] # inventory list to return dcid = dc['id'] ...
def get_dc_network(pbclient, dc=None): ''' gets inventory of one data center''' if pbclient is None: raise ValueError("argument 'pbclient' must not be None") if dc is None: raise ValueError("argument 'dc' must not be None") print("getting networks..") dcid = dc['id'] # dc_data co...
def main(argv=None): # IGNORE:C0111 '''Command line options.''' if argv is None: argv = sys.argv else: sys.argv.extend(argv) program_name = os.path.basename(sys.argv[0]) program_version = "v%s" % __version__ program_build_date = str(__updated__) program_versi...
def main(argv=None): '''Parse command line options and dump a datacenter to snapshots and file.''' if argv is None: argv = sys.argv else: sys.argv.extend(argv) program_name = os.path.basename(sys.argv[0]) program_version = "v%s" % __version__ program_build_date = str(__updated_...
def get_self(session, user_details=None): """ Get details about the currently authenticated user """ # Set compact to true if user_details: user_details['compact'] = True response = make_get_request(session, 'self', params_data=user_details) json_data = response.json() if respons...
def get_user_by_id(session, user_id, user_details=None): """ Get details about specific user """ if user_details: user_details['compact'] = True response = make_get_request( session, 'users/{}'.format(user_id), params_data=user_details) json_data = response.json() if response...
def get_self_user_id(session): """ Get the currently authenticated user ID """ response = make_get_request(session, 'self') if response.status_code == 200: return response.json()['result']['id'] else: raise UserIdNotRetrievedException( 'Error retrieving user id: %s' %...
def add_user_jobs(session, job_ids): """ Add a list of jobs to the currently authenticated user """ jobs_data = { 'jobs[]': job_ids } response = make_post_request(session, 'self/jobs', json_data=jobs_data) json_data = response.json() if response.status_code == 200: return...
def set_user_jobs(session, job_ids): """ Replace the currently authenticated user's list of jobs with a new list of jobs """ jobs_data = { 'jobs[]': job_ids } response = make_put_request(session, 'self/jobs', json_data=jobs_data) json_data = response.json() if response.status...
def delete_user_jobs(session, job_ids): """ Remove a list of jobs from the currently authenticated user """ jobs_data = { 'jobs[]': job_ids } response = make_delete_request(session, 'self/jobs', json_data=jobs_data) json_data = response.json() if response.status_code == 200: ...
def get_users(session, query): """ Get one or more users """ # GET /api/users/0.1/users response = make_get_request(session, 'users', params_data=query) json_data = response.json() if response.status_code == 200: return json_data['result'] else: raise UsersNotFoundExcepti...
def create_project(session, title, description, currency, budget, jobs): """ Create a project """ project_data = {'title': title, 'description': description, 'currency': currency, 'budget': budget, 'jobs':...
def create_hireme_project(session, title, description, currency, budget, jobs, hireme_initial_bid): """ Create a fixed project """ jobs.append(create_job_object(id=417)) # Hire Me job, required project_data = {'title': title, 'description': description...
def get_projects(session, query): """ Get one or more projects """ # GET /api/projects/0.1/projects response = make_get_request(session, 'projects', params_data=query) json_data = response.json() if response.status_code == 200: return json_data['result'] else: raise Proje...
def get_project_by_id(session, project_id, project_details=None, user_details=None): """ Get a single project by ID """ # GET /api/projects/0.1/projects/<int:project_id> query = {} if project_details: query.update(project_details) if user_details: query.update(user_details) ...
def search_projects(session, query, search_filter=None, project_details=None, user_details=None, limit=10, offset=0, active_only=None): """ Search for all projects """ ...
def place_project_bid(session, project_id, bidder_id, description, amount, period, milestone_percentage): """ Place a bid on a project """ bid_data = { 'project_id': project_id, 'bidder_id': bidder_id, 'description': description, 'amount': amount, ...
def get_bids(session, project_ids=[], bid_ids=[], limit=10, offset=0): """ Get the list of bids """ get_bids_data = {} if bid_ids: get_bids_data['bids[]'] = bid_ids if project_ids: get_bids_data['projects[]'] = project_ids get_bids_data['limit'] = limit get_bids_data['off...
def get_milestones(session, project_ids=[], milestone_ids=[], user_details=None, limit=10, offset=0): """ Get the list of milestones """ get_milestones_data = {} if milestone_ids: get_milestones_data['milestones[]'] = milestone_ids if project_ids: get_milestones_data['projects[]'...
def get_milestone_by_id(session, milestone_id, user_details=None): """ Get a specific milestone """ # GET /api/projects/0.1/milestones/{milestone_id}/ endpoint = 'milestones/{}'.format(milestone_id) response = make_get_request(session, endpoint, params_data=user_details) json_data = respons...
def award_project_bid(session, bid_id): """ Award a bid on a project """ headers = { 'Content-Type': 'application/x-www-form-urlencoded' } bid_data = { 'action': 'award' } # POST /api/projects/0.1/bids/{bid_id}/?action=award endpoint = 'bids/{}'.format(bid_id) res...
def revoke_project_bid(session, bid_id): """ Revoke a bid on a project """ headers = { 'Content-Type': 'application/x-www-form-urlencoded' } bid_data = { 'action': 'revoke' } # POST /api/projects/0.1/bids/{bid_id}/?action=revoke endpoint = 'bids/{}'.format(bid_id) ...
def accept_project_bid(session, bid_id): """ Accept a bid on a project """ headers = { 'Content-Type': 'application/x-www-form-urlencoded' } bid_data = { 'action': 'accept' } # POST /api/projects/0.1/bids/{bid_id}/?action=revoke endpoint = 'bids/{}'.format(bid_id) ...
def retract_project_bid(session, bid_id): """ Retract a bid on a project """ headers = { 'Content-Type': 'application/x-www-form-urlencoded' } bid_data = { 'action': 'retract' } # POST /api/projects/0.1/bids/{bid_id}/?action=revoke endpoint = 'bids/{}'.format(bid_id) ...
def highlight_project_bid(session, bid_id): """ Highlight a bid on a project """ headers = { 'Content-Type': 'application/x-www-form-urlencoded' } bid_data = { 'action': 'highlight' } # POST /api/projects/0.1/bids/{bid_id}/?action=revoke endpoint = 'bids/{}'.format(bi...
def create_milestone_payment(session, project_id, bidder_id, amount, reason, description): """ Create a milestone payment """ milestone_data = { 'project_id': project_id, 'bidder_id': bidder_id, 'amount': amount, 'reason': reason, 'des...
def post_track(session, user_id, project_id, latitude, longitude): """ Start tracking a project by creating a track """ tracking_data = { 'user_id': user_id, 'project_id': project_id, 'track_point': { 'latitude': latitude, 'longitude': longitude } ...
def update_track(session, track_id, latitude, longitude, stop_tracking=False): """ Updates the current location by creating a new track point and appending it to the given track """ tracking_data = { 'track_point': { 'latitude': latitude, 'longitude': longitude, ...
def get_track_by_id(session, track_id, track_point_limit=None, track_point_offset=None): """ Gets a specific track """ tracking_data = {} if track_point_limit: tracking_data['track_point_limit'] = track_point_limit if track_point_offset: tracking_data['track_point_offset'] = tra...
def release_milestone_payment(session, milestone_id, amount): """ Release a milestone payment """ params_data = { 'action': 'release', } milestone_data = { 'amount': amount, } # PUT /api/projects/0.1/milestones/{milestone_id}/?action=release endpoint = 'milestones/{}'...
def request_release_milestone_payment(session, milestone_id): """ Release a milestone payment """ params_data = { 'action': 'request_release', } # PUT /api/projects/0.1/milestones/{milestone_id}/?action=release endpoint = 'milestones/{}'.format(milestone_id) response = make_put_r...
def cancel_milestone_payment(session, milestone_id): """ Release a milestone payment """ params_data = { 'action': 'cancel', } # PUT /api/projects/0.1/milestones/{milestone_id}/?action=release endpoint = 'milestones/{}'.format(milestone_id) response = make_put_request(session, en...
def create_milestone_request(session, project_id, bid_id, description, amount): """ Create a milestone request """ milestone_request_data = { 'project_id': project_id, 'bid_id': bid_id, 'description': description, 'amount': amount, } # POST /api/projects/0.1/miles...
def accept_milestone_request(session, milestone_request_id): """ Accept a milestone request """ params_data = { 'action': 'accept', } # POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action= # accept endpoint = 'milestone_requests/{}'.format(milestone_request_i...
def reject_milestone_request(session, milestone_request_id): """ Reject a milestone request """ params_data = { 'action': 'reject', } # POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action= # reject endpoint = 'milestone_requests/{}'.format(milestone_request_i...
def delete_milestone_request(session, milestone_request_id): """ Delete a milestone request """ params_data = { 'action': 'delete', } # POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action= # delete endpoint = 'milestone_requests/{}'.format(milestone_request_i...
def post_review(session, review): """ Post a review """ # POST /api/projects/0.1/reviews/ response = make_post_request(session, 'reviews', json_data=review) json_data = response.json() if response.status_code == 200: return json_data['status'] else: raise ReviewNotPostedE...
def get_jobs(session, job_ids, seo_details, lang): """ Get a list of jobs """ get_jobs_data = { 'jobs[]': job_ids, 'seo_details': seo_details, 'lang': lang, } # GET /api/projects/0.1/jobs/ response = make_get_request(session, 'jobs', params_data=get_jobs_data) jso...
def create_thread(session, member_ids, context_type, context, message): """ Create a thread """ headers = { 'Content-Type': 'application/x-www-form-urlencoded' } thread_data = { 'members[]': member_ids, 'context_type': context_type, 'context': context, 'me...
def create_project_thread(session, member_ids, project_id, message): """ Create a project thread """ return create_thread(session, member_ids, 'project', project_id, message)
def post_message(session, thread_id, message): """ Add a message to a thread """ headers = { 'Content-Type': 'application/x-www-form-urlencoded' } message_data = { 'message': message, } # POST /api/messages/0.1/threads/{thread_id}/messages/ endpoint = 'threads/{}/mes...
def post_attachment(session, thread_id, attachments): """ Add a message to a thread """ files = [] filenames = [] for attachment in attachments: files.append(attachment['file']) filenames.append(attachment['filename']) message_data = { 'attachments[]': filenames, ...
def get_messages(session, query, limit=10, offset=0): """ Get one or more messages """ query['limit'] = limit query['offset'] = offset # GET /api/messages/0.1/messages response = make_get_request(session, 'messages', params_data=query) json_data = response.json() if response.status_...
def search_messages(session, thread_id, query, limit=20, offset=0, message_context_details=None, window_above=None, window_below=None): """ Search for messages """ query = { 'thread_id': thread_id, 'query': query, 'limit': limit, 'o...
def get_threads(session, query): """ Get one or more threads """ # GET /api/messages/0.1/threads response = make_get_request(session, 'threads', params_data=query) json_data = response.json() if response.status_code == 200: return json_data['result'] else: raise ThreadsNo...
def _clean(zipcode, valid_length=_valid_zipcode_length): """ Assumes zipcode is of type `str` """ zipcode = zipcode.split("-")[0] # Convert #####-#### to ##### if len(zipcode) != valid_length: raise ValueError( 'Invalid format, zipcode must be of the format: "#####" or "#####-####"' ...
def similar_to(partial_zipcode, zips=_zips): """ List of zipcode dicts where zipcode prefix matches `partial_zipcode` """ return [z for z in zips if z["zip_code"].startswith(partial_zipcode)]
def filter_by(zips=_zips, **kwargs): """ Use `kwargs` to select for desired attributes from list of zipcode dicts """ return [z for z in zips if all([k in z and z[k] == v for k, v in kwargs.items()])]
def is_valid_identifier(name): """Pedantic yet imperfect. Test to see if "name" is a valid python identifier """ if not isinstance(name, str): return False if '\n' in name: return False if name.strip() != name: return False try: code = compile('\n{0}=None'.format(...
def from_config( cls, cfg, default_fg=DEFAULT_FG_16, default_bg=DEFAULT_BG_16, default_fg_hi=DEFAULT_FG_256, default_bg_hi=DEFAULT_BG_256, max_colors=2**24 ): """ Build a palette definition from either a simple string or a dictionary, filling i...
def get_passphrase(passphrase=None): """Return a passphrase as found in a passphrase.ghost file Lookup is done in three locations on non-Windows systems and two on Windows All: `cwd/passphrase.ghost` `~/.ghost/passphrase.ghost` Only non-Windows: `/etc/ghost/passphrase.ghost` ...
def migrate(src_path, src_passphrase, src_backend, dst_path, dst_passphrase, dst_backend): """Migrate all keys in a source stash to a destination stash The migration process will decrypt all keys using the source stash's passphrase and then encryp...
def generate_passphrase(size=12): """Return a generate string `size` long based on lowercase, uppercase, and digit chars """ chars = string.ascii_lowercase + string.ascii_uppercase + string.digits return str(''.join(random.choice(chars) for _ in range(size)))
def _build_dict_from_key_value(keys_and_values): """Return a dict from a list of key=value pairs """ key_dict = {} for key_value in keys_and_values: if '=' not in key_value: raise GhostError('Pair {0} is not of `key=value` format'.format( key_value)) key, valu...
def _prettify_dict(key): """Return a human readable format of a key (dict). Example: Description: My Wonderful Key Uid: a54d6de1-922a-4998-ad34-cb838646daaa Created_At: 2016-09-15T12:42:32 Metadata: owner=me; Modified_At: 2016-09-15T12:42:32 Value: secret_...
def _prettify_list(items): """Return a human readable format of a list. Example: Available Keys: - my_first_key - my_second_key """ assert isinstance(items, list) keys_list = 'Available Keys:' for item in items: keys_list += '\n - {0}'.format(item) return keys_lis...
def init_stash(stash_path, passphrase, passphrase_size, backend): r"""Init a stash `STASH_PATH` is the path to the storage endpoint. If this isn't supplied, a default path will be used. In the path, you can specify a name for the stash (which, if omitted, will default to `ghost`) like so: `ghost in...
def put_key(key_name, value, description, meta, modify, add, lock, key_type, stash, passphrase, backend): """Insert a key to the stash `KEY_NAME` is the name of the key to insert `VALUE`...
def lock_key(key_name, stash, passphrase, backend): """Lock a key to prevent it from being deleted, purged or modified `KEY_NAME` is the name of the key to lock """ stash = _get_stash(backend, stash, passphrase) try: click.echo('Locking key...') ...
def unlock_key(key_name, stash, passphrase, backend): """Unlock a key to allow it to be modified, deleted or purged `KEY_NAME` is the name of the key to unlock """ stash = _get_stash(backend, stash, passphrase) try: click.echo('Unlocking key...'...
def get_key(key_name, value_name, jsonify, no_decrypt, stash, passphrase, backend): """Retrieve a key from the stash \b `KEY_NAME` is the name of the key to retrieve `VALUE_NAME` is a single value to retrieve e.g. if the value ...
def delete_key(key_name, stash, passphrase, backend): """Delete a key from the stash `KEY_NAME` is the name of the key to delete You can provide that multiple times to delete multiple keys at once """ stash = _get_stash(backend, stash, passphrase) for key in key_name: try: ...
def list_keys(key_name, max_suggestions, cutoff, jsonify, locked, key_type, stash, passphrase, backend): """List all keys in the stash If `KEY_NAME` is provided, will look for keys containing `KEY_NA...
def purge_stash(force, stash, passphrase, backend): """Purge the stash from all of its keys """ stash = _get_stash(backend, stash, passphrase) try: click.echo('Purging stash...') stash.purge(force) # Maybe we should verify that the list is empty # afterwards? cli...
def export_keys(output_path, stash, passphrase, backend): """Export all keys to a file """ stash = _get_stash(backend, stash, passphrase) try: click.echo('Exporting stash to {0}...'.format(output_path)) stash.export(output_path=output_path) click.echo('Export complete!') exc...
def load_keys(key_file, origin_passphrase, stash, passphrase, backend): """Load all keys from an exported key file to the stash `KEY_FILE` is the exported stash file to load keys from """ stash = _get_stash(backend, stash, passphrase) click.echo('Importing all keys from {0}...'.format(key_file)) ...
def migrate_stash(source_stash_path, source_passphrase, source_backend, destination_stash_path, destination_passphrase, destination_backend): """Migrate all keys from a source stash to a destination stash. `SOURCE_STASH_P...
def ssh(key_name, no_tunnel, stash, passphrase, backend): """Use an ssh type key to connect to a machine via ssh Note that trying to use a key of the wrong type (e.g. `secret`) will result in an error. `KEY_NAME` is the key to use. For additional information on the different configuration options...
def _build_ssh_command(conn_info, no_tunnel=False): """ # TODO: Document clearly IndetityFile="~/.ssh/id_rsa" ProxyCommand="ssh -i ~/.ssh/id_rsa proxy_IP nc HOST_IP HOST_PORT" """ command = ['ssh', '-i', conn_info['ssh_key_path'], conn_info['conn']] if conn_info.get('tunnel') and not no_tun...
def put(self, name, value=None, modify=False, metadata=None, description='', encrypt=True, lock=False, key_type='secret', add=False): """Put a key inside the stash if key exists and modify true: ...
def get(self, key_name, decrypt=True): """Return a key with its parameters if it was found. """ self._assert_valid_stash() key = self._storage.get(key_name).copy() if not key.get('value'): return None if decrypt: key['value'] = self._decrypt(key['...
def list(self, key_name=None, max_suggestions=100, cutoff=0.5, locked_only=False, key_type=None): """Return a list of all keys. """ self._assert_valid_stash() key_list = [k for k in self._storage.list() ...
def delete(self, key_name): """Delete a key if it exists. """ self._assert_valid_stash() if key_name == 'stored_passphrase': raise GhostError( '`stored_passphrase` is a reserved ghost key name ' 'which cannot be deleted') # TODO: Opti...
def purge(self, force=False, key_type=None): """Purge the stash from all keys """ self._assert_valid_stash() if not force: raise GhostError( "The `force` flag must be provided to perform a stash purge. " "I mean, you don't really want to just ...
def export(self, output_path=None, decrypt=False): """Export all keys in the stash to a list or a file """ self._assert_valid_stash() all_keys = [] for key in self.list(): # We `dict` this as a precaution as tinydb returns # a tinydb.database.Element inst...
def load(self, origin_passphrase, keys=None, key_file=None): """Import keys to the stash from either a list of keys or a file `keys` is a list of dictionaries created by `self.export` `stash_path` is a path to a file created by `self.export` """ # TODO: Handle keys not dict or k...
def _encrypt(self, value): """Turn a json serializable value into an jsonified, encrypted, hexa string. """ value = json.dumps(value) with warnings.catch_warnings(): warnings.simplefilter("ignore") encrypted_value = self.cipher.encrypt(value.encode('utf8')...
def _decrypt(self, hexified_value): """The exact opposite of _encrypt """ encrypted_value = binascii.unhexlify(hexified_value) with warnings.catch_warnings(): warnings.simplefilter("ignore") jsonified_value = self.cipher.decrypt( encrypted_value).d...
def get(self, key_name): """Return a dictionary consisting of the key itself e.g. {u'created_at': u'2016-10-10 08:31:53', u'description': None, u'metadata': None, u'modified_at': u'2016-10-10 08:31:53', u'name': u'aws', u'uid': u'459f12c0-f341-413e-9...
def delete(self, key_name): """Delete the key and return true if the key was deleted, else false """ self.db.remove(Query().name == key_name) return self.get(key_name) == {}
def _construct_key(self, values): """Return a dictionary representing a key from a list of columns and a tuple of values """ key = {} for column, value in zip(self.keys.columns, values): key.update({column.name: value}) return key
def put(self, key): """Put and return the only unique identifier possible, its url """ self._consul_request('PUT', self._key_url(key['name']), json=key) return key['name']
def put(self, key): """Put and return the only unique identifier possible, its path """ self.client.write(self._key_path(key['name']), **key) return self._key_path(key['name'])
def init(self): """Create an Elasticsearch index if necessary """ # ignore 400 (IndexAlreadyExistsException) when creating an index self.es.indices.create(index=self.params['index'], ignore=400)
def init(self): """Create a bucket. """ try: self.client.create_bucket( Bucket=self.db_path, CreateBucketConfiguration=self.bucket_configuration) except botocore.exceptions.ClientError as e: # If the bucket already exists ...
def put(self, key): """Insert the key :return: Key name """ self.client.put_object( Body=json.dumps(key), Bucket=self.db_path, Key=key['name']) return key['name']
def list(self): """Lists the keys :return: Returns a list of all keys (not just key names, but rather the keys themselves). """ response = self.client.list_objects_v2(Bucket=self.db_path) if u'Contents' in response: # Filter out everything but the key names ...
def get(self, key_name): """Gets the key. :return: The key itself in a dictionary """ try: obj = self.client.get_object( Bucket=self.db_path, Key=key_name)['Body'].read().decode("utf-8") return json.loads(obj) except botoco...
def delete(self, key_name): """Delete the key. :return: True if it was deleted, False otherwise """ self.client.delete_object( Bucket=self.db_path, Key=key_name) return self.get(key_name) == {}
def is_initialized(self): """Check if bucket exists. :return: True if initialized, False otherwise """ try: return self.client.head_bucket( Bucket=self.db_path)['ResponseMetadata']['HTTPStatusCode'] \ == 200 except botocore.exception...
def terminal(port=default_port(), baud='9600'): """Launch minterm from pyserial""" testargs = ['nodemcu-uploader', port, baud] # TODO: modifying argv is no good sys.argv = testargs # resuse miniterm on main function miniterm.main()
def __set_baudrate(self, baud): """setting baudrate if supported""" log.info('Changing communication to %s baud', baud) self.__writeln(UART_SETUP.format(baud=baud)) # Wait for the string to be sent before switching baud time.sleep(0.1) try: self._port.setBaudr...
def set_timeout(self, timeout): """Set the timeout for the communication with the device.""" timeout = int(timeout) # will raise on Error self._timeout = timeout == 0 and 999999 or timeout
def __clear_buffers(self): """Clears the input and output buffers""" try: self._port.reset_input_buffer() self._port.reset_output_buffer() except AttributeError: #pySerial 2.7 self._port.flushInput() self._port.flushOutput()