code
stringlengths
1
18.2k
def search(self, **kwargs): """Get movies that match the search query string from the API. Args: q (optional): plain text search query; remember to URI encode page_limit (optional): number of search results to show per page, default=30 page (optional): results page number, default=1 Returns: A dict respresentation of t...
def cast(self, **kwargs): """Get the cast for a movie specified by id from the API. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_id_path('cast') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
def clips(self, **kwargs): """Get related clips and trailers for a movie specified by id from the API. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_id_path('clips') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
def debug(value): """ Simple tag to debug output a variable; Usage: {% debug request %} """ print("%s %s: " % (type(value), value)) print(dir(value)) print('\n\n') return ''
def get_sample_data(sample_file): """Read and returns sample data to fill form with default sample sequence. """ sequence_sample_in_fasta = None with open(sample_file) as handle: sequence_sample_in_fasta = handle.read() return sequence_sample_in_fasta
def blast_records_to_object(blast_records): """Transforms biopython's blast record into blast object defined in django-blastplus app. """ # container for transformed objects blast_objects_list = [] for blast_record in blast_records: br = BlastRecord(**{'query': blast_record.query, 'version': blast_record.version, 'expe...
def run_blast_commands(ncbicommandline_method, **keywords): """Runs blastplus/tblastn search, collects result and pass as a xml temporary file. """ # temporary files for output blast_out_tmp = tempfile.NamedTemporaryFile(mode="w+",delete=False) keywords['out'] = blast_out_tmp.name # unpack query temp file object query_...
def get_annotation(db_path, db_list): """ Checks if database is set as annotated. """ annotated = False for db in db_list: if db["path"] == db_path: annotated = db["annotated"] break return annotated
def find_usbserial(vendor, product): """Find the tty device for a given usbserial devices identifiers. Args: vendor: (int) something like 0x0000 product: (int) something like 0x0000 Returns: String, like /dev/ttyACM0 or /dev/tty.usb... """ if platform.system() == 'Linux': vendor, product = [('%04x' % (x)).strip() for x...
def create_fields(self, base_model=models.Model, base_manager=models.Manager): """ This method will create a model which will hold field types defined at runtime for each ContentType. :param base_model: base model class to inherit from :return: """ CONTENT_TYPES = self.content_types_query class CustomContentTypeFieldMa...
= CustomContentTypeFieldManager() class Meta: verbose_name = _('custom field') verbose_name_plural = _('custom fields') abstract = True def save(self, *args, **kwargs): super(CustomContentTypeField, self).save(*args, **kwargs) def clean(self): # if field is required must issue a initial value if self.required: # TODO -...
already defined for content type %(model_name)s') % {'model_name': model.__name__},) }) def __str__(self): return "%s" % self.name return CustomContentTypeField
def create_values(self, base_model=models.Model, base_manager=models.Manager): """ This method will create a model which will hold field values for field types of custom_field_model. :param base_model: :param base_manager: :return: """ _builder = self class CustomContentTypeFieldValueManager(base_manager): def create(s...
models.NullBooleanField(blank=True) objects = CustomContentTypeFieldValueManager() def _get_value(self): return getattr(self, 'value_%s' % self.custom_field.data_type) def _set_value(self, new_value): setattr(self, 'value_%s' % self.custom_field.data_type, new_value) value = property(_get_value, _set_value) class Meta:...
def create_manager(self, base_manager=models.Manager): """ This will create the custom Manager that will use the fields_model and values_model respectively. :param base_manager: the base manager class to inherit from :return: """ _builder = self class CustomManager(base_manager): def search(self, search_data, custom_ar...
Q(**{ str('%s__in' % self.model._meta.pk.name): [obj.object_id for obj in found] }) if query is None: return self.get_queryset().none() return self.get_queryset().filter(query) return CustomManager
def create_mixin(self): """ This will create the custom Model Mixin to attach to your custom field enabled model. :return: """ _builder = self class CustomModelMixin(object): @cached_property def _content_type(self): return ContentType.objects.get_for_model(self) @classmethod def get_model_custom_fields(cls): """ Retur...
= _builder.values_model_class.objects.get(custom_field__name=name, # content_type=self._content_type, # object_id=self.pk) # return obj.value # except ObjectDoesNotExist: # pass # return super(CustomModelMixin, self).__getattr__(name) return CustomModelMixin
def create_modelform(self, base_form=forms.ModelForm, field_types=settings.CUSTOM_FIELD_TYPES, widget_types=settings.CUSTOM_WIDGET_TYPES): """ This creates the class that implements a ModelForm that knows about the custom fields :param base_form: :param field_types: :param widget_types: :return: """ _builder = self cla...
in fields: name = str(f.name) initial = f.initial self.fields[name] = self.get_formfield_for_field(f) self.fields[name].is_custom = True self.fields[name].label = f.label self.fields[name].required = f.required self.fields[name].widget = self.get_widget_for_field(f) if self.instance and self.instance.pk: value = self.s...
type instance of the model this ``ModelForm`` is referring to """ return ContentType.objects.get_for_model(self.get_model()) def get_formfield_for_field(self, field): """ Returns the defined formfield instance built from the type of the field :param field: custom field instance :return: the formfield instance """ field...
= date.DateTimePickerWidget() pass elif field.data_type == CUSTOM_TYPE_BOOLEAN: pass field_type = import_class(field_types[field.data_type]) return field_type(**field_attrs) def get_widget_for_field(self, field, attrs={}): """ Returns the defined widget type instance built from the type of the field :param field: custo...
is referring to :return: CustomFieldValue queryset """ return _builder.values_model_class.objects.filter(custom_field=field, content_type=content_type, object_id=object_id) def create_value_for_field(self, field, object_id, value): """ Create a value for a given field of an object Example implementation: return MyCusto...
def create_modeladmin(self, base_admin=admin.ModelAdmin): """ This creates the class that implements a ModelForm that knows about the custom fields :param base_admin: :return: """ _builder = self class CustomFieldModelBaseAdmin(base_admin): def __init__(self, *args, **kwargs): super(CustomFieldModelBaseAdmin, self).__i...
def bytes_iter(obj): """Turn a complex object into an iterator of byte strings. The resulting iterator can be used for caching. """ if obj is None: return elif isinstance(obj, six.binary_type): yield obj elif isinstance(obj, six.string_types): yield obj elif isinstance(obj, (date, datetime)): yield obj.isoformat() elif...
def hash_data(obj): """Generate a SHA1 from a complex object.""" collect = sha1() for text in bytes_iter(obj): if isinstance(text, six.text_type): text = text.encode('utf-8') collect.update(text) return collect.hexdigest()
def triples(self, words): """ Generates triples from the given data string. So if our string were "What a lovely day", we'd generate (What, a, lovely) and then (a, lovely, day). """ if len(words) < 3: return for i in range(len(words) - 2): yield (words[i], words[i+1], words[i+2])
def ast_imports(file_path): """get list of import from python module :return: (list - tuple) (module, name, asname, level) """ with open(file_path, 'r') as fp: text = fp.read() mod_ast = ast.parse(text, file_path) finder = _ImportsFinder() finder.visit(mod_ast) return finder.imports
def visit_Import(self, node): """callback for 'import' statement""" self.imports.extend((None, n.name, n.asname, None) for n in node.names) ast.NodeVisitor.generic_visit(self, node)
def visit_ImportFrom(self, node): """callback for 'import from' statement""" self.imports.extend((node.module, n.name, n.asname, node.level) for n in node.names) ast.NodeVisitor.generic_visit(self, node)
def _get_fqn(cls, path): """get full qualified name as list of strings :return: (list - str) of path segments from top package to given path """ name_list = [path.stem] current_path = path # move to parent path until parent path is a python package while cls.is_pkg(current_path.parent): name_list.append(current_path.pa...
def _get_imported_module(self, module_name): """try to get imported module reference by its name""" # if imported module on module_set add to list imp_mod = self.by_name.get(module_name) if imp_mod: return imp_mod # last part of import section might not be a module # remove last section no_obj = module_name.rsplit('.',...
def get_imports(self, module, return_fqn=False): """return set of imported modules that are in self :param module: PyModule :return: (set - str) of path names """ # print('####', module.fqn) # print(self.by_name.keys(), '\n\n') imports = set() raw_imports = ast_imports(module.path) for import_entry in raw_imports: # jo...
def generate_random_string(cls, length): """ Generatesa a [length] characters alpha numeric secret """ # avoid things that could be mistaken ex: 'I' and '1' letters = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ" return "".join([random.choice(letters) for _ in range(length)])
def run_airbnb_demo(data_dir): """HyperTransfomer will transform back and forth data airbnb data.""" # Setup meta_file = os.path.join(data_dir, 'Airbnb_demo_meta.json') transformer_list = ['NumberTransformer', 'DTTransformer', 'CatTransformer'] ht = HyperTransformer(meta_file) # Run transformed = ht.fit_transform(trans...
def eventlog(self, path): """Iterates over the Events contained within the log at the given path. For each Event, yields a XML string. """ self.logger.debug("Parsing Event log file %s.", path) with NamedTemporaryFile(buffering=0) as tempfile: self._filesystem.download(path, tempfile.name) file_header = FileHeader(tempf...
def publish_message_to_centrifugo(sender, instance, created, **kwargs): """ Publishes each saved message to Centrifugo. """ if created is True: client = Client("{0}api/".format(getattr(settings, "CENTRIFUGE_ADDRESS")), getattr(settings, "CENTRIFUGE_SECRET")) # we ensure the client is still in the thread (he may have le...
def publish_participation_to_thread(sender, instance, created, **kwargs): """ Warns users everytime a thread including them is published. This is done via channel subscription. """ if kwargs.get('created_and_add_participants') is True: request_participant_id = kwargs.get('request_participant_id') if request_participant...
def getFileAndName(self, *args, **kwargs): ''' Give a requested page (note: the arguments for this call are forwarded to getpage()), return the content at the target URL and the filename for the target content as a 2-tuple (pgctnt, hName) for the content at the target URL. The filename specified in the content-disposit...
def getFileNameMime(self, requestedUrl, *args, **kwargs): ''' Give a requested page (note: the arguments for this call are forwarded to getpage()), return the content at the target URL, the filename for the target content, and the mimetype for the content at the target URL, as a 3-tuple (pgctnt, hName, mime). The filen...
else: hName = info['Content-Disposition'].split('filename=')[1] # Unquote filename if it's quoted. if ((hName.startswith("'") and hName.endswith("'")) or hName.startswith('"') and hName.endswith('"')) and len(hName) >= 2: hName = hName[1:-1] mime = info.get_content_type() if not hName.strip(): requestedUrl = pghandle.g...
def __check_suc_cookie(self, components): ''' This is only called if we're on a known sucuri-"protected" site. As such, if we do *not* have a sucuri cloudproxy cookie, we can assume we need to do the normal WAF step-through. ''' netloc = components.netloc.lower() for cookie in self.cj: if cookie.domain_specified and (c...
def __pre_check(self, requestedUrl): ''' Allow the pre-emptive fetching of sites with a full browser if they're known to be dick hosters. ''' components = urllib.parse.urlsplit(requestedUrl) netloc_l = components.netloc.lower() if netloc_l in Domain_Constants.SUCURI_GARBAGE_SITE_NETLOCS: self.__check_suc_cookie(compone...
def __decompressContent(self, coding, pgctnt): """ This is really obnoxious """ #preLen = len(pgctnt) if coding == 'deflate': compType = "deflate" bits_opts = [ -zlib.MAX_WBITS, # deflate zlib.MAX_WBITS, # zlib zlib.MAX_WBITS | 16, # gzip zlib.MAX_WBITS | 32, # "automatic header detection" 0, # Try to guess from header...
err having thrown. raise err elif coding == 'gzip': compType = "gzip" buf = io.BytesIO(pgctnt) f = gzip.GzipFile(fileobj=buf) pgctnt = f.read() elif coding == "sdch": raise Exceptions.ContentTypeError("Wait, someone other then google actually supports SDCH compression (%s)?" % pgreq) else: compType = "none" return comp...
def addSeleniumCookie(self, cookieDict): ''' Install a cookie exported from a selenium webdriver into the active opener ''' # print cookieDict cookie = http.cookiejar.Cookie( version = 0, name = cookieDict['name'], value = cookieDict['value'], port = None, port_specified = False, domain = cookieDict['domain'], domain_s...
def mail_on_500(app, recipients, sender='noreply@localhost'): '''Main function for setting up Flask-ErrorMail to send e-mails when 500 errors occur. :param app: Flask Application Object :type app: flask.Flask :param recipients: List of recipient email addresses. :type recipients: list or tuple :param sender: Email addr...
recipients=recipients) msg_contents = [ 'Traceback:', '='*80, traceback.format_exc(), ] msg_contents.append('\n') msg_contents.append('Request Information:') msg_contents.append('='*80) environ = __request.environ environkeys = sorted(environ.keys()) for key in environkeys: msg_contents.append('%s: %s' % (key, environ....
def command_dependents(options): """Command launched by CLI.""" dependents = dependencies(options.package, options.recursive, options.info) if dependents: print(*dependents, sep='\n')
def dependencies(dist, recursive=False, info=False): """Yield distribution's dependencies.""" def case_sorted(items): """Return unique list sorted in case-insensitive order.""" return sorted(set(items), key=lambda i: i.lower()) def requires(distribution): """Return the requirements for a distribution.""" if recursive: ...
def user_group_perms_processor(request): """ return context variables with org permissions to the user. """ org = None group = None if hasattr(request, "user"): if request.user.is_anonymous: group = None else: group = request.user.get_org_group() org = request.user.get_org() if group: context = dict(org_perms=GroupPerm...
def set_org_processor(request): """ Simple context processor that automatically sets 'org' on the context if it is present in the request. """ if getattr(request, "org", None): org = request.org pattern_bg = org.backgrounds.filter(is_active=True, background_type="P") pattern_bg = pattern_bg.order_by("-pk").first() bann...
def _getresult(self, captcha_id, timeout=None): """ Poll until a captcha `captcha_id` has been solved, or the poll times out. The timeout is the default 60 seconds, unless overridden by `timeout` (which is in seconds). Polling is done every 8 seconds. """ timeout = timeout if not timeout: timeout = self.waittime poll_i...
def _submit(self, pathfile, filedata, filename): ''' Submit either a file from disk, or a in-memory file to the solver service, and return the request ID associated with the new captcha task. ''' if pathfile and os.path.exists(pathfile): files = {'file': open(pathfile, 'rb')} elif filedata: assert filename files = {'fi...
def solve_simple_captcha(self, pathfile=None, filedata=None, filename=None): """ Upload a image (from disk or a bytearray), and then block until the captcha has been solved. Return value is the captcha result. either pathfile OR filedata AND filename should be specified. Failure will result in a subclass of WebRequest....
def solve_recaptcha(self, google_key, page_url, timeout = 15 * 60): ''' Solve a recaptcha on page `page_url` with the input value `google_key`. Timeout is `timeout` seconds, defaulting to 60 seconds. Return value is either the `g-recaptcha-response` value, or an exceptionj is raised (generally `CaptchaSolverFailure`) '...
def search(query=None, params=None, callback=None, mine_ids=None, info_only=None, **kwargs): """Mine Archive.org search results. :param query: (optional) The Archive.org search query to yield results for. Refer to https://archive.org/advancedsearch.php#raw for help formatting your query. If no query is given, all index...
info_only: bool :param \*\*kwargs: (optional) Arguments that ``get_miner`` takes. """ query = '(*:*)' if not query else query params = params if params else {} mine_ids = True if mine_ids else False info_only = True if info_only else False miner = SearchMiner(**kwargs) if info_only: params = miner.get_search_params(que...
def mine_urls(urls, params=None, callback=None, **kwargs): """Concurrently retrieve URLs. :param urls: A set of URLs to concurrently retrieve. :type urls: iterable :param params: (optional) The URL parameters to send with each request. :type params: dict :param callback: (optional) A callback function to be called on e...
def mine_items(identifiers, params=None, callback=None, **kwargs): """Concurrently retrieve metadata from Archive.org items. :param identifiers: A set of Archive.org item identifiers to mine. :type identifiers: iterable :param params: (optional) The URL parameters to send with each request. :type params: dict :param ca...
def configure(username=None, password=None, overwrite=None, config_file=None): """Configure IA Mine with your Archive.org credentials.""" username = input('Email address: ') if not username else username password = getpass('Password: ') if not password else password _config_file = write_config_file(username, password, ...
def __get_time_range(self, startDate, endDate): """Return time range """ today = date.today() start_date = today - timedelta(days=today.weekday(), weeks=1) end_date = start_date + timedelta(days=4) startDate = startDate if startDate else str(start_date) endDate = endDate if endDate else str(end_date) return startDate, ...
def get_current_info(self, symbolList, columns=None): """get_current_info() uses the yahoo.finance.quotes datatable to get all of the stock information presented in the main table on a typical stock page and a bunch of data from the key statistics page. """ response = self.select('yahoo.finance.quotes',columns).where([...
def get_news_feed(self, symbol): """get_news_feed() uses the rss data table to get rss feeds under the Headlines and Financial Blogs headings on a typical stock page. """ rss_url='http://finance.yahoo.com/rss/headline?s={0}'.format(symbol) response = self.select('rss',['title','link','description'],limit=2).where(['url...
def get_historical_info(self, symbol,items=None, startDate=None, endDate=None, limit=None): """get_historical_info() uses the csv datatable to retrieve all available historical data on a typical historical prices page """ startDate, endDate = self.__get_time_range(startDate, endDate) response = self.select('yahoo.finan...
def get_options_info(self, symbol, items=None, expiration=''): """get_options_data() uses the yahoo.finance.options table to retrieve call and put options from the options page. """ response = self.select('yahoo.finance.options',items).where(['symbol','=',symbol],[] if not expiration else ['expiration','=',expiration])...
def get_industry_index(self, index_id,items=None): """retrieves all symbols that belong to an industry. """ response = self.select('yahoo.finance.industry',items).where(['id','=',index_id]) return response
def get_xchange_rate(self, pairs, items=None): """Retrieves currency exchange rate data for given pair(s). Accepts both where pair='eurusd, gbpusd' and where pair in ('eurusd', 'gpbusd, usdaud') """ response = self.select('yahoo.finance.xchange', items).where(['pair', 'in', pairs]) return response
def get_dividendhistory(self, symbol, startDate, endDate, items=None): """Retrieves divident history """ startDate, endDate = self.__get_time_range(startDate, endDate) response = self.select('yahoo.finance.dividendhistory', items).where(['symbol', '=', symbol], ['startDate', '=', startDate], ['endDate', '=', endDate]) ...
def get_symbols(self, name): """Retrieves all symbols belonging to a company """ url = "http://autoc.finance.yahoo.com/autoc?query={0}&callback=YAHOO.Finance.SymbolSuggest.ssCallback".format(name) response = requests.get(url) json_data = re.match("YAHOO\.Finance\.SymbolSuggest.ssCallback\((.*)\)", response.text) try: j...
def pip(filename): '''Parse pip requirement file and transform it to setuptools requirements''' requirements = [] for line in open(os.path.join('requirements', filename)).readlines(): match = RE_REQUIREMENT.match(line) if match: requirements.extend(pip(match.group('filename'))) else: requirements.append(line) return re...
def pointlist(points, sr): """Convert a list of the form [[x, y] ...] to a list of Point instances with the given x, y coordinates.""" assert all(isinstance(pt, Point) or len(pt) == 2 for pt in points), "Point(s) not in [x, y] form" return [coord if isinstance(coord, Point) else Point(coord[0], coord[1], sr) for coord ...
def fromJson(struct, attributes=None): "Convert a JSON struct to a Geometry based on its structure" if isinstance(struct, basestring): struct = json.loads(struct) indicative_attributes = { 'x': Point, 'wkid': SpatialReference, 'paths': Polyline, 'rings': Polygon, 'points': Multipoint, 'xmin': Envelope } # bbox string i...
def fromGeoJson(struct, attributes=None): "Convert a GeoJSON-like struct to a Geometry based on its structure" if isinstance(struct, basestring): struct = json.loads(struct) type_map = { 'Point': Point, 'MultiLineString': Polyline, 'LineString': Polyline, 'Polygon': Polygon, 'MultiPolygon': Polygon, 'MultiPoint': Multi...
instance.attributes = {} for k, v in attributes.iteritems(): instance.attributes[k] = v i.append(instance) if i: if len(i) > 1: return i return i[0] raise ValueError("Unconvertible to geometry")
def name(): "Get/view the name for the well known ID of a Projection" if self.wkid in projected: return projected[self.wkid] elif self.wkid in geographic: return geographic[self.wkid] else: raise KeyError("Not a known WKID.")
def contains(self, pt): "Tests if the provided point is in the polygon." if isinstance(pt, Point): ptx, pty = pt.x, pt.y assert (self.spatialReference is None or \ self.spatialReference.wkid is None) or \ (pt.spatialReference is None or \ pt.spatialReference.wkid is None) or \ self.spatialReference == pt.spatialReferen...
not in_shape elif (((pi[1] < pty and pj[1] >= pty) or (pj[1] < pty and pi[1] >= pty)) and (pi[0] + (pty - pi[1]) / (pj[1] - pi[1]) * (pj[0] - pi[0]) < ptx)): in_shape = not in_shape return in_shape
def bbox(self): "Return the envelope as a Bound Box string compatible with (bb) params" return ",".join(str(attr) for attr in (self.xmin, self.ymin, self.xmax, self.ymax))
def stalecheck(web3, **kwargs): ''' Use to require that a function will run only of the blockchain is recently updated. If the chain is old, raise a StaleBlockchain exception Define how stale the chain can be with keyword arguments from datetime.timedelta, like stalecheck(web3, days=2) Turn off the staleness check at r...
def scan(self, concurrency=1): """Iterates over the applications installed within the disk and queries the CVE DB to determine whether they are vulnerable. Concurrency controls the amount of concurrent queries against the CVE DB. For each vulnerable application the method yields a namedtuple: VulnApp(name -> applicatio...
def execute_ping(host_list, remote_user, remote_pass, sudo=False, sudo_user=None, sudo_pass=None): ''' Execute ls on some hosts ''' runner = spam.ansirunner.AnsibleRunner() result, failed_hosts = runner.ansible_perform_operation( host_list=host_list, remote_user=remote_user, remote_pass=remote_pass, sudo=sudo, sudo_pas...
def execute_ls(host_list, remote_user, remote_pass): ''' Execute any adhoc command on the hosts. ''' runner = spam.ansirunner.AnsibleRunner() result, failed_hosts = runner.ansible_perform_operation( host_list=host_list, remote_user=remote_user, remote_pass=remote_pass, module="command", module_args="ls -1") print "Resu...
def main(): ''' Simple examples ''' args = parse_arguments() if args.askpass: password = getpass.getpass("Password: ") else: password = None if args.asksudopass: sudo = True sudo_pass = getpass.getpass("Sudo password[default ssh password]: ") if len(sudo_pass) == 0: sudo_pass = password sudo_user = 'root' else: sudo = ...
def compiler_preprocessor_verbose(compiler, extraflags): """Capture the compiler preprocessor stage in verbose mode """ lines = [] with open(os.devnull, 'r') as devnull: cmd = [compiler, '-E'] cmd += extraflags cmd += ['-', '-v'] p = Popen(cmd, stdin=devnull, stdout=PIPE, stderr=PIPE) p.wait() p.stdout.close() lines = ...
def transform(self, col): """Prepare the transformer to convert data and return the processed table. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame """ out = pd.DataFrame(index=col.index) out[self.col_name] = col.apply(self.get_val, axis=1) if self.subtype == 'int': out[self.col_name] = out[s...
def reverse_transform(self, col): """Converts data back into original format. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame """ output = pd.DataFrame(index=col.index) output[self.col_name] = col.apply(self.safe_round, axis=1) if self.subtype == 'int': output[self.col_name] = output[self.col_...
def get_val(self, x): """Converts to int.""" try: if self.subtype == 'integer': return int(round(x[self.col_name])) else: if np.isnan(x[self.col_name]): return self.default_val return x[self.col_name] except (ValueError, TypeError): return self.default_val
def safe_round(self, x): """Returns a converter that takes in a value and turns it into an integer, if necessary. Args: col_name(str): Name of the column. subtype(str): Numeric subtype of the values. Returns: function """ val = x[self.col_name] if np.isposinf(val): val = sys.maxsize elif np.isneginf(val): val = -sys.ma...
def rados_df(self, host_list=None, remote_user=None, remote_pass=None): ''' Invoked the rados df command and return output to user ''' result, failed_hosts = self.runner.ansible_perform_operation( host_list=host_list, remote_user=remote_user, remote_pass=remote_pass, module="command", module_args="rados df") parsed_res...
def rados_parse_df(self, result): ''' Parse the result from ansirunner module and save it as a json object ''' parsed_results = [] HEADING = r".*(pool name) *(category) *(KB) *(objects) *(clones)" + \ " *(degraded) *(unfound) *(rd) *(rd KB) *(wr) *(wr KB)" HEADING_RE = re.compile(HEADING, re.IGNORECASE) dict_keys = ["p...
def update_roles_gce(use_cache=True, cache_expiration=86400, cache_path="~/.gcetools/instances", group_name=None, region=None, zone=None): """ Dynamically update fabric's roles by using assigning the tags associated with each machine in Google Compute Engine. use_cache - will store a local cache in ~/.gcetools/ cache_e...
to the name of one of the tags associated with the instances you wish to work with """ data = _get_data(use_cache, cache_expiration, group_name=group_name, region=region, zone=zone) roles = _get_roles(data) env.roledefs.update(roles) _data_loaded = True return INSTANCES_CACHE
def eventsource_connect(url, io_loop=None, callback=None, connect_timeout=None): """Client-side eventsource support. Takes a url and returns a Future whose result is a `EventSourceClient`. """ if io_loop is None: io_loop = IOLoop.current() if isinstance(url, httpclient.HTTPRequest): assert connect_timeout is None reque...
def handle_stream(self, message): """ Acts on message reception :param message: string of an incoming message parse all the fields and builds an Event object that is passed to the callback function """ logging.debug("handle_stream(...)") event = Event() for line in message.strip().splitlines(): (field, value) = line.sp...
def printout(*args, **kwargs): """ Print function with extra options for formating text in terminals. """ # TODO(Lukas): conflicts with function names color = kwargs.pop('color', {}) style = kwargs.pop('style', {}) prefx = kwargs.pop('prefix', '') suffx = kwargs.pop('suffix', '') ind = kwargs.pop('indent', 0) print_arg...
def colorize(txt, fg=None, bg=None): """ Print escape codes to set the terminal color. fg and bg are indices into the color palette for the foreground and background colors. """ setting = '' setting += _SET_FG.format(fg) if fg else '' setting += _SET_BG.format(bg) if bg else '' return setting + str(txt) + _STYLE_RESET
def stylize(txt, bold=False, underline=False): """ Changes style of the text. """ setting = '' setting += _SET_BOLD if bold is True else '' setting += _SET_UNDERLINE if underline is True else '' return setting + str(txt) + _STYLE_RESET
def indent(txt, spacing=4): """ Indent given text using custom spacing, default is set to 4. """ return prefix(str(txt), ''.join([' ' for _ in range(spacing)]))
def rgb(red, green, blue): """ Calculate the palette index of a color in the 6x6x6 color cube. The red, green and blue arguments may range from 0 to 5. """ for value in (red, green, blue): if value not in range(6): raise ColorError('Value must be within 0-5, was {}.'.format(value)) return 16 + (red * 36) + (green * 6) ...