code stringlengths 1 18.2k |
|---|
def set_volume(percentage): '''Set the volume. Sets the volume to a given percentage (integer between 0 and 100). Args: percentage (int): The percentage (as a 0 to 100 integer) to set the volume to. Raises: ValueError: if the percentage is >100 or <0. ''' if percentage > 100 or percentage < 0: raise ValueError('percent... |
def get_volume(): '''Get the volume. Get the current volume. Returns: int: The current volume (percentage, between 0 and 100). ''' if system.get_name() == 'windows': # TODO: Implement volume for Windows. Looks like WinAPI is the # solution... pass elif system.get_name() == 'mac': volume = system.get_cmd_out( ['osascrip... |
def increase_volume(percentage): '''Increase the volume. Increase the volume by a given percentage. Args: percentage (int): The percentage (as an integer between 0 and 100) to increase the volume by. Raises: ValueError: if the percentage is >100 or <0. ''' if percentage > 100 or percentage < 0: raise ValueError('percen... |
def mute(): '''Mute the volume. Mutes the volume. ''' # NOTE: mute != 0 volume if system.get_name() == 'windows': # TODO: Implement volume for Windows. Looks like WinAPI is the # solution... pass elif system.get_name() == 'mac': sp.Popen(['osascript', '-e', 'set volume output muted true']).wait() else: # Linux/Unix if ... |
def unmute(): '''Unmute the volume. Unmutes the system volume. Note: On some systems, volume is restored to its previous level after unmute, or set to 100. ''' if system.get_name() == 'windows': # TODO: Implement volume for Windows. Looks like WinAPI is the # solution... pass elif system.get_name() == 'mac': sp.Popen([... |
def _setup_serializers(self): """ Auto set the return serializer based on Accept headers http://docs.webob.org/en/latest/reference.html#header-getters Intersection of requested types and supported types tells us if we can in fact respond in one of the request formats """ acceptable_offers = self.request.accept.acceptab... |
def forwards(self, orm): "Write your forwards methods here." rows = db.execute("select distinct feature_type from content_content") for row in rows: feature_type = row[0] try: ft = orm.FeatureType.objects.get(slug=slugify(feature_type)) except orm.FeatureType.DoesNotExist: ft = orm.FeatureType.objects.create( name=feat... |
def query_by_login(self, login_id, end_time=None, start_time=None): """ Query by login. List authentication events for a given login. """ path = {} data = {} params = {} # REQUIRED - PATH - login_id """ID""" path["login_id"] = login_id # OPTIONAL - start_time """The beginning of the time range from which you want event... |
def query_by_account(self, account_id, end_time=None, start_time=None): """ Query by account. List authentication events for a given account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - start_time """The beginning of the time range from which ... |
def query_by_user(self, user_id, end_time=None, start_time=None): """ Query by user. List authentication events for a given user. """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # OPTIONAL - start_time """The beginning of the time range from which you want events.""" i... |
def _items(self, type_filter=None, name=None): """ Args: type_filter(list): Optional iterable of types to return (GroupDict only) name(str): Only return key by this name Alternative generator for items() method """ if name: if type_filter and self._key_attr == 'type': if name in type_filter and name in self: yield name... |
def _filter(self, blacklist=None, newest_only=False, type_filter=None, **kwargs): """ Args: blacklist(tuple): Iterable of of BlacklistEntry objects newest_only(bool): Only the newest version of each plugin is returned type(str): Plugin type to retrieve name(str): Plugin name to retrieve version(str): Plugin version to ... |
plugin_blacklist.append(entry) if not skip: # pylint: disable=protected-access result = val._filter(plugin_blacklist, newest_only=newest_only, **kwargs) if result or not self._skip_empty: plugins[key] = result if filtered_name: return plugins.get(filtered_name, None) return plugins |
def _sorted_keys(self): """ Return list of keys sorted by version Sorting is done based on :py:func:`pkg_resources.parse_version` """ try: keys = self._cache['sorted_keys'] except KeyError: keys = self._cache['sorted_keys'] = sorted(self.keys(), key=parse_version) return keys |
def _process_blacklist(self, blacklist): """ Process blacklist into set of excluded versions """ # Assume blacklist is correct format since it is checked by PluginLoader blacklist_cache = {} blacklist_cache_old = self._cache.get('blacklist', {}) for entry in blacklist: blackkey = (entry.version, entry.operator) if blac... |
def _filter(self, blacklist=None, newest_only=False, **kwargs): """ Args: blacklist(tuple): Iterable of of BlacklistEntry objects newest_only(bool): Only the newest version of each plugin is returned version(str): Specific version to retrieve Returns dictionary of plugins If a blacklist is supplied, plugins are evaluat... |
self[self._sorted_keys()[-1]] else: rtn = dict(self) return rtn |
def OSGB36toWGS84(E, N): """ Accept The Ordnance Survey National Grid eastings and northings. Return latitude and longitude coordinates. Usage: >>> from bng_to_latlon import OSGB36toWGS84 >>> OSGB36toWGS84(538890, 177320) (51.47779538331092, -0.0014016837826672265) >>> OSGB36toWGS84(352500.2, 401400) (53.50712984310419... |
M1 = (1 + n + (5./4)*n**2 + (5./4)*n**3) * (lat-lat0) M2 = (3*n + 3*n**2 + (21./8)*n**3) * sin(lat-lat0) * cos(lat+lat0) M3 = ((15./8)*n**2 + (15./8)*n**3) * sin(2*(lat-lat0)) * cos(2*(lat+lat0)) M4 = (35./24)*n**3 * sin(3*(lat-lat0)) * cos(3*(lat+lat0)) # meridional arc M = b * F0 * (M1 - M2 + M3 - M4) # transverse ra... |
XI*dE**3 + XII*dE**5 - XIIA*dE**7 # Want to convert to the GRS80 ellipsoid. # First convert to cartesian from spherical polar coordinates H = 0 # Third spherical coord. x_1 = (nu/F0 + H)*cos(lat_1)*cos(lon_1) y_1 = (nu/F0 + H)*cos(lat_1)*sin(lon_1) z_1 = ((1-e2)*nu/F0 + H)*sin(lat_1) # Perform Helmut transform (to go b... |
(-rz)*y_1 + (ry)*z_1 y_2 = ty + (rz)*x_1 + (1+s)*y_1 + (-rx)*z_1 z_2 = tz + (-ry)*x_1 + (rx)*y_1 + (1+s)*z_1 # Back to spherical polar coordinates from cartesian # Need some of the characteristics of the new ellipsoid # The GSR80 semi-major and semi-minor axes used for WGS84(m) a_2, b_2 = 6378137.000, 6356752.3141 e2_2... |
if you want to print the results # print([(lat-lat_1)*180/pi, (lon - lon_1)*180/pi]) # Convert to degrees lat = lat*180/pi lon = lon*180/pi # Job's a good'n. return lat, lon |
def find(pred, items): """ Find the index of the first element in items for which pred returns True >>> find(lambda x: x > 3, range(100)) 4 >>> find(lambda x: x < -3, range(100)) is None True """ for i, item in enumerate(items): if pred(item): return i |
def reset_less_significant(self, significant_version): """ Reset to zero all version info less significant than the indicated version. >>> ver = SummableVersion('3.1.2') >>> ver.reset_less_significant(SummableVersion('0.1')) >>> str(ver) '3.1' """ def nonzero(x): return x != 0 version_len = 3 # strict versions are alwa... |
def as_number(self): """ >>> round(SummableVersion('1.9.3').as_number(), 12) 1.93 """ def combine(subver, ver): return subver / 10 + ver return reduce(combine, reversed(self.version)) |
def get_tagged_version(self): """ Get the version of the local working set as a StrictVersion or None if no viable tag exists. If the local working set is itself the tagged commit and the tip and there are no local modifications, use the tag on the parent changeset. """ tags = list(self.get_tags()) if 'tip' in tags and... |
def get_current_version(self, increment=None): """ Return as a string the version of the current state of the repository -- a tagged version, if present, or the next version based on prior tagged releases. """ ver = ( self.get_tagged_version() or str(self.get_next_version(increment)) + '.dev0' ) return str(ver) |
def get_next_version(self, increment=None): """ Return the next version based on prior tagged releases. """ increment = increment or self.increment return self.infer_next_version(self.get_latest_version(), increment) |
def infer_next_version(last_version, increment): """ Given a simple application version (as a StrictVersion), and an increment (1.0, 0.1, or 0.0.1), guess the next version. Set up a shorthand for examples >>> def VM_infer(*params): ... return str(VersionManagement.infer_next_version(*params)) >>> VM_infer('3.2', '0.0.1... |
def create_global_notification(self, account_id, account_notification_end_at, account_notification_subject, account_notification_message, account_notification_start_at, account_notification_icon=None, account_notification_roles=None): """ Create a global notification. Create and return a new global notification for an ... |
None: self._validate_enum(account_notification_icon, ["warning", "information", "question", "error", "calendar"]) data["account_notification[icon]"] = account_notification_icon # OPTIONAL - account_notification_roles """The role(s) to send global notification to. Note: ommitting this field will send to everyone Example... |
def adapt_persistent_instance(persistent_object, target_rest_class=None, attribute_filter=None): """ Adapts a single persistent instance to a REST model; at present this is a common method for all persistent backends. Refer to: https://groups.google.com/forum/#!topic/prestans-discuss/dO1yx8f60as for discussion on this ... |
def adapt_persistent_to_rest(self, persistent_object, attribute_filter=None): """ adapts a persistent model to a rest model by inspecting """ # convert filter to immutable if it isn't already if isinstance(attribute_filter, parser.AttributeFilter): attribute_filter = attribute_filter.as_immutable() rest_model_instance ... |
TypeError('Attribute %s, %s' % (attribute_key, str(exp))) continue # ignore class methods elif inspect.ismethod(getattr(persistent_object, attribute_key)): import logging logging.error("ignoring method: "+attribute_key) continue # handles prestans array population from SQLAlchemy relationships elif isinstance(rest_attr... |
= None if isinstance(attribute_filter, (parser.AttributeFilter, parser.AttributeFilterImmutable)) and \ attribute_key in attribute_filter: sub_attribute_filter = getattr(attribute_filter, attribute_key) adapted_rest_model = model_adapter.adapt_persistent_to_rest( persistent_attr_value, sub_attribute_filter ) setattr(re... |
def register_persistent_rest_pair(self, persistent_model_class, rest_model_class): """ :param persistent_model_class: :param rest_model_class: """ self.register_adapter(ModelAdapter( rest_model_class=rest_model_class, persistent_model_class=persistent_model_class )) |
def get_adapter_for_persistent_model(self, persistent_model, rest_model=None): """ :param persistent_model: instance of persistent model :param rest_model: specific REST model :return: the matching model adapter :rtype: ModelAdapter """ persistent_signature = self.generate_signature(persistent_model) if persistent_sign... |
def get_adapter_for_rest_model(self, rest_model): """ :param rest_model: instance of REST model :return: the matching model adapter :rtype: ModelAdapter """ class_signature = self.generate_signature(rest_model) if class_signature not in self._rest_map: raise TypeError("No registered Data Adapter for class %s" % class_s... |
def popular_content(**kwargs): """ Use the get_popular_ids() to retrieve trending content objects. Return recent content on failure. """ limit = kwargs.get("limit", DEFAULT_LIMIT) popular_ids = get_popular_ids(limit=limit) if not popular_ids: # Return most recent content return Content.search_objects.search().extra(siz... |
def _send_solr_command(self, core_url, json_command): """ Sends JSON string to Solr instance """ # Check document language and dispatch to correct core url = _get_url(core_url, "update") try: response = self.req_session.post(url, data=json_command, headers={'Content-Type': 'application/json'}) response.raise_for_status... |
def add(self, documents, boost=None): """ Adds documents to Solr index documents - Single item or list of items to add """ if not isinstance(documents, list): documents = [documents] documents = [{'doc': d} for d in documents] if boost: for d in documents: d['boost'] = boost self._add_batch.extend(documents) if len(sel... |
def _addFlushBatch(self): """ Sends all waiting documents to Solr """ if len(self._add_batch) > 0: language_batches = {} # Create command JSONs for each of language endpoints for lang in self.endpoints: # Append documents with languages without endpoint to default endpoint document_jsons = ["\"add\":" + json.dumps(data... |
def deleteAll(self): """ Deletes whole Solr index. Use with care. """ for core in self.endpoints: self._send_solr_command(self.endpoints[core], "{\"delete\": { \"query\" : \"*:*\"}}") |
def delete(self, id): """ Deletes document with ID on all Solr cores """ for core in self.endpoints: self._send_solr_command(self.endpoints[core], "{\"delete\" : { \"id\" : \"%s\"}}" % (id,)) |
def commit(self): """ Flushes all pending changes and commits Solr changes """ self._addFlushBatch() for core in self.endpoints: self._send_solr_command(self.endpoints[core], "{ \"commit\":{} }") |
def _get_shards(self): """ Returns comma separated list of configured Solr cores """ if self._shards is None: endpoints = [] for endpoint in self.endpoints: # We need to remove and http:// prefixes from URLs url = urlparse.urlparse(self.endpoints[endpoint]) endpoints.append("/".join([url.netloc, url.path])) self._shard... |
def _parse_response(self, results): """ Parses result dictionary into a SolrResults object """ dict_response = results.get("response") result_obj = SolrResults() result_obj.query_time = results.get("responseHeader").get("QTime", None) result_obj.results_count = dict_response.get("numFound", 0) result_obj.start_index = ... |
the params, keep "before" and "after" fields for other if type == "facet_dates" and \ (facet == "gap" or facet == "between" or facet == "start" or facet == "end"): continue result_obj.facets[field].append((facet, value)) # Process highlights if "highlighting" in results: for key, value in results.get("highlighting").it... |
def query(self, query, filters=None, columns=None, sort=None, start=0, rows=30): """ Queries Solr and returns results query - Text query to search for filters - dictionary of filters to apply when searching in form of { "field":"filter_value" } columns - columns to return, list of strings sort - list of fields to sort ... |
active if len(self.endpoints) > 1: fields["shards"] = self._get_shards() # Prepare filters if not filters is None: filter_list = [] for filter_field, value in filters.items(): filter_list.append("%s:%s" % (filter_field, value)) fields["fq"] = " AND ".join(filter_list) # Append sorting parameters if not sort is None: fi... |
def more_like_this(self, query, fields, columns=None, start=0, rows=30): """ Retrieves "more like this" results for a passed query document query - query for a document on which to base similar documents fields - fields on which to base similarity estimation (either comma delimited string or a list) columns - columns t... |
results = self._send_solr_query(request_url, fields) if not results: return None assert "responseHeader" in results # Check for response status if not results.get("responseHeader").get("status") == 0: logger.error("Server error while retrieving results: %s", results) return None assert "response" in results result_obj ... |
def run_suite(case, config, summary): """ Run the full suite of numerics tests """ m = importlib.import_module(config['module']) m.set_up() config["name"] = case analysis_data = {} bundle = livvkit.numerics_model_module model_dir = os.path.join(livvkit.model_dir, config['data_dir'], case) bench_dir = os.path.join(livvk... |
_summarize_result(m, analysis_data, config) _print_summary(m, case, summary[case]) functions.create_page_from_template("numerics.html", os.path.join(livvkit.index_dir, "numerics", case + ".html")) functions.write_json(result, os.path.join(livvkit.output_dir, "numerics"), case + ".json") |
def run_ahead(self, time, framerate): """Run the particle system for the specified time frame at the specified framerate to move time forward as quickly as possible. Useful for "warming up" the particle system to reach a steady-state before anything is drawn or to simply "skip ahead" in time. time -- The amount of simu... |
def get_html_column(self): """ Get a HTML column for this panel. """ panel_id = "panel_{}".format(self.name) return ["<h2>{}</h2>".format(self.title) + '<a href="{}">Download data</a>'.format(self.tar_fn())] + [ # list of links (" <br />" + os.linesep).join( [ """ <strong>{bam_name}:</strong> <a onclick="document.getEl... |
def create_gp(self): """ Create GnuPlot file. """ nb_bams = len(self.bams) gp_parts = [ textwrap.dedent( """\ set log x set log x2 #set format x "10^{{%L}}" set format x2 "10^{{%L}}" set x2tics unset xtics """ ), os.linesep.join([self._gp_style_func(i, nb_bams) for i in range(nb_bams)]), textwrap.dedent( """\ set forma... |
def create_graphics(self): """Create images related to this panel.""" if len(self._svg_fns) > 0: rnftools.utils.shell('"{}" "{}"'.format("gnuplot", self._gp_fn)) if self.render_pdf_method is not None: for svg_fn in self._svg_fns: pdf_fn = re.sub(r'\.svg$', r'.pdf', svg_fn) svg42pdf(svg_fn, pdf_fn, method=self.render_pd... |
def create_tar(self): """Create a tar file with all the files.""" def add_file_to_tar(tar, orig_fn, new_fn, func=None): tf = tarfile.TarInfo(name=new_fn) with open(orig_fn) as f: tfs = f.read() if func is not None: tfs = func(tfs) tf.size = len(tfs) tfs = io.BytesIO(tfs.encode('utf8')) tar.addfile(tarinfo=tf, fileobj=t... |
x: strip_lines(x.replace(roc_fn, t_roc_fn).replace(svg_fn, t_svg_fn)) ) gp_fn = self._gp_fn t_gp_fn = os.path.basename(gp_fn) svg_dir = os.path.join(self.panel_dir, "graphics") + "/" roc_dir = os.path.join(self.panel_dir, "roc") + "/" add_file_to_tar(tar, gp_fn, t_gp_fn, lambda x: strip_lines(x.replace(svg_dir, "").rep... |
def merge_dicts(dict1, dict2): """ Merge two dictionaries and return the result """ tmp = dict1.copy() tmp.update(dict2) return tmp |
def parse_gptl(file_path, var_list): """ Read a GPTL timing file and extract some data. Args: file_path: the path to the GPTL timing file var_list: a list of strings to look for in the file Returns: A dict containing key-value pairs of the livvkit and the times associated with them """ timing_result = dict() if os.path... |
def find_file(search_dir, file_pattern): """ Search for a file in a directory, and return the first match. If the file is not found return an empty string Args: search_dir: The root directory to search in file_pattern: A unix-style wildcard pattern representing the file to find Returns: The path to the file if it was f... |
def create_page_from_template(template_file, output_path): """ Copy the correct html template file to the output directory """ mkdir_p(os.path.dirname(output_path)) shutil.copy(os.path.join(livvkit.resource_dir, template_file), output_path) |
def read_json(file_path): """ Read in a json file and return a dictionary representation """ try: with open(file_path, 'r') as f: config = json_tricks.load(f) except ValueError: print(' '+'!'*58) print(' Woops! Looks the JSON syntax is not valid in:') print(' {}'.format(file_path)) print(' Note: commonly this is a resu... |
def write_json(data, path, file_name): """ Write out data to a json file. Args: data: A dictionary representation of the data to write out path: The directory to output the file in file_name: The name of the file to write out """ if os.path.exists(path) and not os.path.isdir(path): return elif not os.path.exists(path):... |
def collect_cases(data_dir): """ Find all cases and subcases of a particular run type """ cases = {} for root, dirs, files in os.walk(data_dir): if not dirs: split_case = os.path.relpath(root, data_dir).split(os.path.sep) if split_case[0] not in cases: cases[split_case[0]] = [] cases[split_case[0]].append("-".join(spli... |
def setup_output(cssd=None, jsd=None, imgd=None): """ Set up the directory structure for the output. Copies old run data into a timestamped directory and sets up the new directory """ # Check if we need to back up an old run if os.path.isdir(livvkit.index_dir): print("---------------------------------------------------... |
"imgs"), os.path.join(livvkit.index_dir, "imgs")) # Get the index template from the resource directory shutil.copy(os.path.join(livvkit.resource_dir, "index.html"), os.path.join(livvkit.index_dir, "index.html")) # Record when this data was recorded so we can make nice backups with open(os.path.join(livvkit.index_dir, "... |
def prepare_query_params(**kwargs): """ Prepares given parameters to be used in querystring. """ return [ (sub_key, sub_value) for key, value in kwargs.items() for sub_key, sub_value in expand(value, key) if sub_value is not None ] |
def prepend_model(self, value, model): """ Prepends model name if it is not already prepended. For example model is "Offer": key -> Offer.key -key -> -Offer.key Offer.key -> Offer.key -Offer.key -> -Offer.key """ if '.' not in value: direction = '' if value.startswith('-'): value = value[1:] direction = '-' value = '%s... |
def on_draw(): global yrot win.clear() glLoadIdentity() glTranslatef(0, 0, -100) glRotatef(yrot, 0.0, 1.0, 0.0) default_system.draw() ''' glBindTexture(GL_TEXTURE_2D, 1) glEnable(GL_TEXTURE_2D) glEnable(GL_POINT_SPRITE) glPointSize(100); glBegin(GL_POINTS) glVertex2f(0,0) glEnd() glBindTexture(GL_TEXTURE_2D, 2) glEnabl... |
def cleanup_callbackredirect(max_age=300): """ Delete old :model:`esi.CallbackRedirect` models. Accepts a max_age parameter, in seconds (default 300). """ max_age = timezone.now() - timedelta(seconds=max_age) logger.debug("Deleting all callback redirects created before {0}".format(max_age.strftime("%b %d %Y %H:%M:%S"))... |
def send_token_email(self, request, queryset): """ Sends token email(s) for the selected users. """ for token in queryset: if not token.expired: forward_token(token) |
def count(cls, slug): """get the number of objects in the cache for a given slug :param slug: cache key :return: `int` """ from .models import Content # Gets the count for a tag, hopefully form an in-memory cache. cnt = cls._cache.get(slug) if cnt is None: cnt = Content.search_objects.search(tags=[slug]).count() cls._c... |
def is_varchar(self): """Determine if a data record is of the type VARCHAR.""" dt = DATA_TYPES['varchar'] if type(self.data) is dt['type'] and len(self.data) < dt['max']: self.type = 'VARCHAR' self.len = len(self.data) return True |
def _is_text_data(self, data_type): """Private method for testing text data types.""" dt = DATA_TYPES[data_type] if type(self.data) is dt['type'] and len(self.data) < dt['max'] and all(type(char) == str for char in self.data): self.type = data_type.upper() self.len = len(self.data) return True |
def bind_key_name(self, function, object_name): """Bind a key to an object name""" for funcname, name in self.name_map.items(): if funcname == function: self.name_map[ funcname] = object_name |
def bind_keys(self, objects): """Configure name map: My goal here is to associate a named object with a specific function""" for object in objects: if object.keys != None: for key in object.keys: if key != None: self.bind_key_name(key, object.name) |
def configure_keys(self): """Configure key map""" self.active_functions = set() self.key2func = {} for funcname, key in self.key_map.items(): self.key2func[key] = getattr(self, funcname) |
def _parse_module_list(module_list): '''Loop through all the modules and parse them.''' for module_meta in module_list: name = module_meta['module'] # Import & parse module module = import_module(name) output = parse_module(module) # Assign to meta.content module_meta['content'] = output |
def _build_module_list(source_module, index_filename, ignore_modules): '''Builds a list of python modules in the current directory.''' out = [] dirs_with_init = set() module_prefix = '' if source_module == '.' else source_module for root, _, filenames in walk('.'): root = root[2:] module_root = root.replace('/', '.') f... |
output_name = '{}.md'.format(filename) if root: output_name = '{}/{}'.format(root, output_name) out.append({ 'directory': root, 'file': filename, 'module': module_name, 'output': output_name, 'source': source_name }) return out |
def _write_docs(module_list, output_dir): '''Write the document meta to our output location.''' for module_meta in module_list: directory = module_meta['directory'] # Ensure target directory if directory and not path.isdir(directory): makedirs(directory) # Write the file file = open(module_meta['output'], 'w') file.wri... |
def build( root, source_module, output_dir, json_dump=False, ignore_modules=None, index_filename='index' ): ''' Build markdown documentation from a directory and/or python module. # ignore_modules: takes a list of module names to ignore # index_filename: __init__.py output (default index.md), use README.md for github i... |
_build_module_list( source_module, index_filename=index_filename, ignore_modules=ignore_modules ) # Cd back to old directory chdir(root) # And parse all the modules _parse_module_list(module_list) # Cd inot the target directory chdir(output_dir) # Finally, write the module list to our output dir _write_docs(module_list... |
def main(): '''Main in a function in case you place a build.py for pydocs inside the root directory.''' options = ''' pydocs Usage: pydocs SOURCE OUTPUT_DIR pydocs SOURCE OUTPUT_DIR [--json] [--index NAME] [--ignore FILE,NAMES] pydocs --help Options: SOURCE Source module, or . for current directory. OUTPUT_DIR The loca... |
def read_stats(self): """ Reads the statistics view from IXN and saves it in statistics dictionary. """ captions, rows = self._get_pages() name_caption_index = captions.index(self.name_caption) captions.pop(name_caption_index) self.captions = captions self.statistics = OrderedDict() for row in rows: name = row.pop(name... |
def get_all_stats(self): """ :returns: all statistics values for all objects. """ all_stats = OrderedDict() for obj_name in self.statistics: all_stats[obj_name] = dict(zip(self.captions, self.statistics[obj_name])) return all_stats |
def get_object_stats(self, obj_name): """ :param obj_name: requested object name :returns: all statistics values for the requested object. """ return dict(zip(self.captions, self.statistics[obj_name])) |
def get_stats(self, stat_name): """ :param stat_name: requested statistics name. :returns: all values of the requested statistic for all objects. """ return [self.get_stat(r, stat_name) for r in self.statistics.keys()] |
def get_stat(self, obj_name, stat_name): """ :param obj_name: requested object name. :param stat_name: requested statistics name. :return: str, the value of the requested statics for the requested object. """ return self.statistics[obj_name][self.captions.index(stat_name)] |
def check_cmake_exists(cmake_command): """ Check whether CMake is installed. If not, print informative error message and quits. """ from subprocess import Popen, PIPE p = Popen( '{0} --version'.format(cmake_command), shell=True, stdin=PIPE, stdout=PIPE) if not ('cmake version' in p.communicate()[0].decode('UTF-8')): sy... |
def setup_build_path(build_path): """ Create build directory. If this already exists, print informative error message and quit. """ if os.path.isdir(build_path): fname = os.path.join(build_path, 'CMakeCache.txt') if os.path.exists(fname): sys.stderr.write('aborting setup\n') sys.stderr.write( 'build directory {0} which... |
def run_cmake(command, build_path, default_build_path): """ Execute CMake command. """ from subprocess import Popen, PIPE from shutil import rmtree topdir = os.getcwd() p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout_coded, stderr_coded = p.communicate() stdout = stdout_coded.decode('UTF-8')... |
stdout build_files_written = '-- Build files have been written to' in stdout configuration_successful = configuring_done and generating_done and build_files_written if configuration_successful: save_setup_command(sys.argv, build_path) print_build_help(build_path, default_build_path) else: if (build_path == default_buil... |
def print_build_help(build_path, default_build_path): """ Print help text after configuration step is done. """ print(' configure step is done') print(' now you need to compile the sources:') if (build_path == default_build_path): print(' $ cd build') else: print(' $ cd ' + build_path) print(' $ make') |
def save_setup_command(argv, build_path): """ Save setup command to a file. """ file_name = os.path.join(build_path, 'setup_command') with open(file_name, 'w') as f: f.write(' '.join(argv[:]) + '\n') |
def configure(root_directory, build_path, cmake_command, only_show): """ Main configure function. """ default_build_path = os.path.join(root_directory, 'build') # check that CMake is available, if not stop check_cmake_exists('cmake') # deal with build path if build_path is None: build_path = default_build_path if not o... |
def generate_hash(self): """ Create a unique SHA token/hash using the project SECRET_KEY, URL, email address and current datetime. """ from django.utils.hashcompat import sha_constructor hash = sha_constructor(settings.SECRET_KEY + self.url + self.email + unicode(datetime.now()) ).hexdigest() return hash[::2] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.