code
stringlengths
1
18.2k
def set_display_label(self, display_label): """Seta a display label. arg: display_label (string): the new display label raise: InvalidArgument - ``display_label`` is invalid raise: NoAccess - ``display_label`` cannot be modified raise: NullArgument - ``display_label`` is ``null`` *compliance: mandatory -- This method m...
def clear_display_label(self): """Clears the display label. raise: NoAccess - ``display_label`` cannot be modified *compliance: mandatory -- This method must be implemented.* """ if (self.get_display_label_metadata().is_read_only() or self.get_display_label_metadata().is_required()): raise errors.NoAccess() self._my_ma...
def set_description(self, description): """Sets a description. arg: description (string): the new description raise: InvalidArgument - ``description`` is invalid raise: NoAccess - ``description`` cannot be modified raise: NullArgument - ``description`` is ``null`` *compliance: mandatory -- This method must be implement...
def clear_description(self): """Clears the description. raise: NoAccess - ``description`` cannot be modified *compliance: mandatory -- This method must be implemented.* """ if (self.get_domain_metadata().is_read_only() or self.get_domain_metadata().is_required()): raise errors.NoAccess() self._my_map['domain'] = self._...
def set_domain(self, domain): """Sets a domain. arg: domain (string): the new domain raise: InvalidArgument - ``domain`` is invalid raise: NoAccess - ``domain`` cannot be modified raise: NullArgument - ``domain`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ if self.get_domain_metadata().i...
def get_next_relationship(self): """Gets the next ``Relationship`` in this list. return: (osid.relationship.Relationship) - the next ``Relationship`` in this list. The ``has_next()`` method should be used to test that a next ``Relationship`` is available before calling this method. raise: IllegalState - no more element...
def get_next_relationships(self, n=None): """Gets the next set of ``Relationships`` elements in this list. The specified amount must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``Relationship`` elements requested which must be less than or equal to ``available()`` return: ...
next_list.append(next(self)) except Exception: # Need to specify exceptions here! raise # OperationFailed() x = x + 1 return next_list
def get_next_family(self): """Gets the next ``Family`` in this list. return: (osid.relationship.Family) - the next ``Family`` in this list. The ``has_next()`` method should be used to test that a next ``Family`` is available before calling this method. raise: IllegalState - no more elements available in this list raise...
def read_laminaprop(laminaprop=None, rho=None): """Returns a ``MatLamina`` object based on an input ``laminaprop`` tuple Parameters ---------- laminaprop : list or tuple Tuple containing the folliwing entries: (e1, e2, nu12, g12, g13, g23, e3, nu13, nu23) for othotropic materials the user can only supply: (e1, e2, nu12...
= (e1, e2, nu12, g12, g13, g23, e3, nu13, nu23) if laminaprop == None: error('laminaprop must be a tuple in the following format:\n\t' +'(e1, e2, nu12, g12, g13, g23, e3, nu13, nu23)') if len(laminaprop) == 3: #ISOTROPIC e = laminaprop[0] nu = laminaprop[2] g = e/(2*(1+nu)) laminaprop = (e, e, nu, g, g, g, e, nu, nu) n...
def myanimelist(username): """ Retrieve a users' animelist scores from MAL. Only anime scored > 0 will be returned, and all PTW entries are ignored, even if they are scored. :param str username: MAL username :return: `id`, `score` pairs :rtype: list """ params = { "u": username, "status": "all", "type": "anime" } resp ...
not exist" .format(username)) scores = [] for anime in all_anime: # See if anime is on their PTW and move on if so. # This makes sure rated anime that the user hasn't # seen does not get added to `scores`. # Why do people even do this? # PTW == status "6" if anime.my_status.string == "6": continue id = anime.series_ani...
def _generate_signature(url_path, secret_key, query_args, digest=None, encoder=None): # type: (str, bytes, Dict[str, str], Callable, Callable) -> str """ Generate signature from pre-parsed URL. """ digest = digest or DEFAULT_DIGEST encoder = encoder or DEFAULT_ENCODER msg = "%s?%s" % (url_path, '&'.join('%s=%s' % i for...
def sign_url_path(url, secret_key, expire_in=None, digest=None): # type: (str, bytes, int, Callable) -> str """ Sign a URL (excluding the domain and scheme). :param url: URL to sign :param secret_key: Secret key :param expire_in: Expiry time. :param digest: Specify the digest function to use; default is sha256 from has...
def verify_url_path(url_path, query_args, secret_key, salt_arg='_', max_expiry=None, digest=None): # type: (str, Dict[str, str], bytes, str, int, Callable) -> bool """ Verify a URL path is correctly signed. :param url_path: URL path :param secret_key: Signing key :param query_args: Arguments that make up the query stri...
Validate signature signature = _generate_signature(url_path, secret_key, query_args, digest) if not hmac.compare_digest(signature, supplied_signature): raise SigningError('Signature not valid.') # Check expiry try: expiry_time = int(query_args.pop('expires')) except KeyError: pass # URL doesn't have an expire time exce...
def verify_url(url, secret_key, **kwargs): """ Verify a signed URL (excluding the domain and scheme). :param url: URL to sign :param secret_key: Secret key :rtype: bool :raises: URLError """ result = urlparse(url) query_args = MultiValueDict(parse_qs(result.query)) return verify_url_path(result.path, query_args, secret...
def _unfold_map(self, display_text_map): """Parses a display text dictionary map.""" from ..type.primitives import Type lt_identifier = Id(display_text_map['languageTypeId']).get_identifier() st_identifier = Id(display_text_map['scriptTypeId']).get_identifier() ft_identifier = Id(display_text_map['formatTypeId']).get_i...
def choice(self,arr): """Uniform random selection of a member of an list :param arr: list you want to select an element from :type arr: list :return: one element from the list """ ind = self.randint(0,len(arr)-1) return arr[ind]
def different_random_nt(self,nt): global nts """generate a random nucleotide change. uniform random. will never return itself :param nt: current nucleotide :type nt: char :return: new nucleotide :rtype: char """ return self._random.choice([x for x in nts if x != nt.upper()])
def get_weighted_random_index(self,weights): """Return an index of an array based on the weights if a random number between 0 and 1 is less than an index return the lowest index :param weights: a list of floats for how to weight each index [w1, w2, ... wN] :type weights: list :return: index :rtype: int """ tot = float(...
def uuid4(self): """Make an id in the format of UUID4, but keep in mind this could very well be pseudorandom, and if it is you'll not be truely random, and can regenerate same id if same seed""" return ''.join([hexchars[self.randint(0,15)] for x in range(0,8)]) + '-' +\ ''.join([hexchars[self.randint(0,15)] for x in ra...
def get_assets_by_search(self, asset_query, asset_search): """Pass through to provider AssetSearchSession.get_assets_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): raise PermissionDenied() return self._provider_ses...
def get_compositions_by_search(self, composition_query, composition_search): """Pass through to provider CompositionSearchSession.get_compositions_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): raise PermissionDeni...
def get_next_types(self, n=None): """Gets the next set of ``Types`` in this list. The specified amount must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``Type`` elements requested which must be less than or equal to ``available()`` return: (osid.type.Type) - an array of ``...
except: # Need to specify exceptions here raise OperationFailed() i += 1 return next_list
def extract_wav(datafile, target=None): """ Get LPCM 16bit audio stream from mediafile. If `target` is a directory, create a .wav with the same basename as the input. If target is empty, write to the directory of the source file. Otherwise, use it directly as the target filename. """ if datafile.endswith(".wav"): retur...
def to_wav(mediafile): """ Context manager providing a temporary WAV file created from the given media file. """ if mediafile.endswith(".wav"): yield mediafile else: wavfile = tempfile.mktemp(__name__) + ".wav" try: extract_wav(mediafile, wavfile) yield wavfile finally: if os.path.exists(wavfile): os.remove(wavfile)
def get_comment_mdata(): """Return default mdata map for Comment""" return { 'text': { 'element_label': { 'text': 'text', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'enter no more than 256 characters.', '...
object', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'required': False, 'read_only': False, 'linked': False, 'array': False, 'default_id_values': [''], 'syntax': 'ID', 'id_set': [], }, }
def b64_hmac_md5(key, data): """ return base64-encoded HMAC-MD5 for key and data, with trailing '=' stripped. """ bdigest = base64.b64encode(hmac.new(key, data, _md5).digest()).strip().decode("utf-8") return re.sub('=+$', '', bdigest)
def extract_domain(host): """ Domain name extractor. Turns host names into domain names, ported from pwdhash javascript code""" host = re.sub('https?://', '', host) host = re.match('([^/]+)', host).groups()[0] domain = '.'.join(host.split('.')[-2:]) if domain in _domains: domain = '.'.join(host.split('.')[-3:]) return ...
def generate(password, uri): """ generate the pwdhash password for master password and uri or domain name. """ realm = extract_domain(uri) if password.startswith(_password_prefix): password = password[len(_password_prefix):] password_hash = b64_hmac_md5(password.encode("utf-8"), realm.encode("utf-8")) size = len(passwo...
def apply_constraints(phash, size, nonalphanumeric): """ Fiddle with the password a bit after hashing it so that it will get through most website filters. We require one upper and lower case, one digit, and we look at the user's password to determine if there should be at least one alphanumeric or not. """ starting_siz...
!= 0 and nonalphanumeric: result += next(extra_chars) else: result += '+' while len(nonword.findall(result)) != 0 and not nonalphanumeric: result = nonword.sub(next_between('A', 'Z'), result, 1) amount = next(extras) % len(result) result = result[amount:] + result[0:amount] return result
def title(self): """ Title for the first header. """ if self._title is None: self._title = self.get_title() return self._title
def get_title(self): """ Get title line from .rst file. **中文文档** 从一个 ``_filename`` 所指定的 .rst 文件中, 找到顶级标题. 也就是第一个 ``====`` 或 ``----`` 或 ``~~~~`` 上面一行. """ header_bar_char_list = "=-~+*#^" cursor_previous_line = None for cursor_line in textfile.readlines(self.rst_path, strip="both"): for header_bar_char in header_bar_cha...
def sub_article_folders(self): """ Returns all valid ArticleFolder sitting inside of :attr:`ArticleFolder.dir_path`. """ l = list() for p in Path.sort_by_fname( Path(self.dir_path).select_dir(recursive=False) ): af = ArticleFolder(dir_path=p.abspath) try: if af.title is not None: l.append(af) except: pass return l
def toc_directive(self, maxdepth=1): """ Generate toctree directive text. :param table_of_content_header: :param header_bar_char: :param header_line_length: :param maxdepth: :return: """ articles_directive_content = TC.toc.render( maxdepth=maxdepth, article_list=self.sub_article_folders, ) return articles_directive_con...
def fly(cls, conf_path, docname, source, maxdepth=1): # pragma: no cover """ Generate toctree directive for rst file. :param conf_path: conf.py file absolute path :param docname: the rst file relpath from conf.py directory. :param source: rst content. :param maxdepth: int, max toc tree depth. """ msg = ("``.. articles:...
def get_assessment_data(self, queryset, total_count, user_id): """ Calculates and sets the following data for the supplied queryset: data = { 'count': <the number of items in the queryset> 'percentage': <percentage of total_count queryset represents> 'is_user_call': <true if user made this call, false otherwise> 'users...
def static(request): "Shorthand static URLs. In debug mode, the JavaScript is not minified." static_url = settings.STATIC_URL prefix = 'src' if settings.DEBUG else 'min' return { 'CSS_URL': os.path.join(static_url, 'stylesheets/css'), 'IMAGES_URL': os.path.join(static_url, 'images'), 'JAVASCRIPT_URL': os.path.join(stat...
def get_agent_id(self): """Gets the ``Id`` of the ``Agent`` identified in this authentication credential. return: (osid.id.Id) - the ``Agent Id`` *compliance: mandatory -- This method must be implemented.* *implementation notes*: The Agent should be determined at the time this credential is created. """ if self._django...
def get_assessment_part(self): """Gets the parent assessment. return: (osid.assessment.authoring.AssessmentPart) - the parent assessment part raise: IllegalState - ``has_parent_part()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ if no...
def get_child_assessment_parts(self): """Gets any child assessment parts. return: (osid.assessment.authoring.AssessmentPartList) - the child assessment parts raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ if not self.has_children(): raise errors.Illeg...
def get_items(self): """This is out of spec, but required for adaptive assessment parts?""" ils = get_item_lookup_session(runtime=self._runtime, proxy=self._proxy) ils.use_federated_bank_view() items = [] if self.has_items(): for idstr in self._my_map['itemIds']: items.append(ils.get_item(Id(idstr))) return ItemList(it...
def get_item_ids(self): """This is out of spec, but required for adaptive assessment parts?""" item_ids = [] if self.has_items(): for idstr in self._my_map['itemIds']: item_ids.append(idstr) return IdList(item_ids)
def get_next_assessment_part_id(self, assessment_part_id): """This supports the basic simple sequence case. Can be overriden in a record for other cases""" if self.has_next_assessment_part(assessment_part_id): return Id(self._my_map['childIds'][self._my_map['childIds'].index(str(assessment_part_id)) + 1])
def _get_assessment_part_lookup_session(self): """need to account for magic parts""" section = getattr(self, '_assessment_section', None) session = get_assessment_part_lookup_session(self._runtime, self._proxy, section) session.use_unsequestered_assessment_part_view() session.use_federated_bank_view() return session
def _init_metadata(self, **kwargs): """Initialize form metadata""" osid_objects.OsidContainableForm._init_metadata(self) osid_objects.OsidOperableForm._init_metadata(self) osid_objects.OsidObjectForm._init_metadata(self, **kwargs) if 'assessment_part_id' not in kwargs: # Only "Section" Parts are allowed directly under ...
def _init_map(self, record_types=None, **kwargs): """Initialize form map""" osid_objects.OsidContainableForm._init_map(self) osid_objects.OsidOperableForm._init_map(self) osid_objects.OsidObjectForm._init_map(self, record_types=record_types) if 'assessment_part_id' in kwargs: self._my_map['assessmentPartId'] = str(kwar...
def get_weight_metadata(self): """Gets the metadata for the weight. return: (osid.Metadata) - metadata for the weight *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._mdata['weight']) metadata.upd...
def get_allocated_time_metadata(self): """Gets the metadata for the allocated time. return: (osid.Metadata) - metadata for the allocated time *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._mdata...
def set_allocated_time(self, time): """Sets the allocated time. arg: time (osid.calendaring.Duration): the allocated time raise: InvalidArgument - ``time`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for o...
def clear_allocated_time(self): """Clears the allocated time. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.assessment.AssessmentOfferedForm.clear_duration_template if (self.get_al...
def get_assessment_part_id(self): """Gets the assessment part ``Id`` to which this rule belongs. return: (osid.id.Id) - ``Id`` of an assessment part *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective_id if not bool(self._my_map['assessmen...
def get_assessment_part(self): """Gets the assessment part to which this rule belongs. return: (osid.assessment.authoring.AssessmentPart) - an assessment part raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning...
def _init_metadata(self, **kwargs): """Initialize form metadata""" osid_objects.OsidObjectForm._init_metadata(self, **kwargs) self._cumulative_default = self._mdata['cumulative']['default_boolean_values'][0] self._minimum_score_default = self._mdata['minimum_score']['default_cardinal_values'][0] self._maximum_score_def...
def _init_map(self, record_types=None, **kwargs): """Initialize form map""" osid_objects.OsidObjectForm._init_map(self, record_types=record_types) self._my_map['nextAssessmentPartId'] = str(kwargs['next_assessment_part_id']) self._my_map['cumulative'] = self._cumulative_default self._my_map['minimumScore'] = self._mini...
def get_minimum_score_metadata(self): """Gets the metadata for the minimum score. return: (osid.Metadata) - metadata for the minimum score *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._mdata['m...
def get_maximum_score_metadata(self): """Gets the metadata for the maximum score. return: (osid.Metadata) - metadata for the maximum score *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._mdata['m...
def get_cumulative_metadata(self): """Gets the metadata for the cumulative flag. return: (osid.Metadata) - metadata for the cumulative flag *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._mdata['...
def set_cumulative(self, cumulative): """Applies this rule to all previous assessment parts. arg: cumulative (boolean): ``true`` to apply to all previous assessment parts. ``false`` to apply to the immediate previous assessment part raise: InvalidArgument - ``cumulative`` is invalid raise: NoAccess - ``Metadata.isReadO...
def get_parcellation(atlas, parcel_param): "Placeholder to insert your own function to return parcellation in reference space." parc_path = os.path.join(atlas, 'parcellation_param{}.mgh'.format(parcel_param)) parcel = nibabel.freesurfer.io.read_geometry(parc_path) return parcel
def get_features(subject_id): "Placeholder to insert your own function to read subject-wise features." features_path = os.path.join(my_project,'base_features', subject_id, 'features.txt') feature_vector = np.loadtxt(features_path) return feature_vector
def get_type(self, namespace=None, identifier=None, authority=None): """Gets a Type by its string representation which is a combination of the authority and identifier. This method only returns the Type if it is known by the given identification components. arg: namespace (string): the identifier namespace arg: identif...
'/handcar/services/learning/types/' + type_identifier try: result = self._get_request(url_path) except NotFound: result = None for t in types.TYPES: if t['id'] == type_identifier: result = t if result is None: raise NotFound() return Type(result)
def has_type(self, type_=None): """Tests if the given Type is known. arg: type (osid.type.Type): the Type to look for return: (boolean) - true if the given Type is known, false otherwise raise: NullArgument - type is null raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failur...
def get_types(self): """Gets all the known Types. return: (osid.type.TypeList) - the list of all known Types raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure compliance: mandatory - This method must be implemented. """ from . import types url_path = '/handcar/services/...
def get_display_name(self): """Creates a display name""" return DisplayText(text=self.id_.get_identifier(), language_type=DEFAULT_LANGUAGE_TYPE, script_type=DEFAULT_SCRIPT_TYPE, format_type=DEFAULT_FORMAT_TYPE,)
def get_description(self): """Creates a description""" return DisplayText(text='Agent representing ' + str(self.id_), language_type=DEFAULT_LANGUAGE_TYPE, script_type=DEFAULT_SCRIPT_TYPE, format_type=DEFAULT_FORMAT_TYPE,)
def empty(val): """ Checks if value is empty. All unknown data types considered as empty values. @return: bool """ if val == None: return True if isinstance(val,str) and len(val) > 0: return False return True
def docs(): """ Create documentation. """ from epydoc import cli path('build').exists() or path('build').makedirs() # get storage path docs_dir = options.docs.get('docs_dir', 'docs/apidocs') # clean up previous docs (path(docs_dir) / "epydoc.css").exists() and path(docs_dir).rmtree() # set up excludes try: exclude_name...
def release(): """ Check release before upload to PyPI. """ sh("paver bdist_egg") # Check that source distribution can be built and is complete print print "~" * 78 print "TESTING SOURCE BUILD" sh( "{ cd dist/ && unzip -q %s-%s.zip && cd %s-%s/" " && /usr/bin/python setup.py sdist >/dev/null" " && if { unzip -ql ../%s-...
to prepare an API documentation upload"
def lint(): """ Report pylint results. """ from pylint import lint as linter # report according to file extension reporters = { ".html": linter.HTMLReporter, ".log": linter.ParseableTextReporter, ".txt": linter.TextReporter, } lint_build_dir = path("build/lint") lint_build_dir.exists() or lint_build_dir.makedirs() argv...
usage error (internal error in this code) sys.stderr.write("paver::lint - Usage error, bad arguments %r?!\n" % (argv,)) raise else: bits = { 1: "fatal", 2: "error", 4: "warning", 8: "refactor", 16: "convention", } sys.stderr.write("paver::lint - Some %s message(s) issued.\n" % ( ", ".join([text for bit, text in bits.it...
def indicator(self): """Produce the spinner.""" while self.run: try: size = self.work_q.qsize() except Exception: note = 'Please wait ' else: note = 'Number of Jobs in Queue = %s ' % size if self.msg: note = '%s %s' % (note, self.msg) for item in ['|', '/', '-', '\\']: sys.stdout.write('\rProcessing - [ %s ] - %s ' % (...
def start(self): """Indicate that we are performing work in a thread. :returns: multiprocessing job object """ if self.run is True: self.job = multiprocessing.Process(target=self.indicator) self.job.start() return self.job
def stop(self): """Stop the indicator process.""" if self.run is True and all([self.job, self.job.is_alive()]): print('Done.') self.job.terminate()
def remove_comments(css): """Remove all CSS comment blocks.""" iemac = False preserve = False comment_start = css.find("/*") while comment_start >= 0: # Preserve comments that look like `/*!...*/`. # Slicing is used to make sure we don"t get an IndexError. preserve = css[comment_start + 2:comment_start + 3] == "!" comm...
= css.find("/*", comment_start) return css
def remove_unnecessary_whitespace(css): """Remove unnecessary whitespace characters.""" def pseudoclasscolon(css): """ Prevents 'p :link' from becoming 'p:link'. Translates 'p :link' into 'p ___PSEUDOCLASSCOLON___link'; this is translated back again later. """ regex = re.compile(r"(^|\})(([^\{\:])+\:)+([^\{]*\{)") matc...
= re.sub(r"([!{}:;>+\(\[,])\s+", r"\1", css) return css
def normalize_rgb_colors_to_hex(css): """Convert `rgb(51,102,153)` to `#336699`.""" regex = re.compile(r"rgb\s*\(\s*([0-9,\s]+)\s*\)") match = regex.search(css) while match: colors = [s.strip() for s in match.group(1).split(",")] hexcolor = '#%.2x%.2x%.2x' % tuple(map(int, colors)) css = css.replace(match.group(), hexc...
def condense_multidimensional_zeros(css): """Replace `:0 0 0 0;`, `:0 0 0;` etc. with `:0;`.""" css = css.replace(":0 0 0 0;", ":0;") css = css.replace(":0 0 0;", ":0;") css = css.replace(":0 0;", ":0;") # Revert `background-position:0;` to the valid `background-position:0 0;`. css = css.replace("background-position:0;...
def condense_hex_colors(css): """Shorten colors from #AABBCC to #ABC where possible.""" regex = re.compile(r"([^\"'=\s])(\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])") match = regex.search(css) while match: first = match.group(3) + match.group(5) + match.group(7) second = match.gr...
def wrap_css_lines(css, line_length): """Wrap the lines of the given CSS to an approximate length.""" lines = [] line_start = 0 for i, char in enumerate(css): # It's safe to break after `}` characters. if char == '}' and (i - line_start >= line_length): lines.append(css[line_start:i + 1]) line_start = i + 1 if line_sta...
def get_log_entry_mdata(): """Return default mdata map for LogEntry""" return { 'priority': { 'element_label': { 'text': 'priority', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'accepts an osid.type.Type o...
'array': False, 'default_id_values': [''], 'syntax': 'ID', 'id_set': [], }, }
def get_changeset(args): """Dump the changeset objects as JSON, reading the provided bundle YAML. The YAML can be provided either from stdin or by passing a file path as first argument. """ # Parse the arguments. parser = argparse.ArgumentParser(description=get_changeset.__doc__) parser.add_argument( 'infile', nargs='?...
def build_items(self): """ get the items from STATS QUEUE calculate self.stats make new items from self.stats put the new items for ITEM QUEUE """ while not self.stats_queue.empty(): item = self.stats_queue.get() self.calculate(item) for key, value in self.stats.iteritems(): if 'blackbird.queue.length' == key: value = ...
def check(module): global passed, failed ''' apply pylint to the file specified if it is a *.py file ''' module_name = module.rsplit('/', 1)[1] if module[-3:] == ".py" and module_name not in IGNORED_FILES: print ("CHECKING ", module) pout = os.popen('pylint %s'% module, 'r') for line in pout: if "Your code has been rat...
def and_filter(self, filter_or_string, *args, **kwargs): """ Convenience method to delegate to the root_filter to generate an :class:`~es_fluent.filters.core.And` clause. :return: :class:`~es_fluent.builder.QueryBuilder` """ self.root_filter.and_filter(filter_or_string, *args, **kwargs) return self
def or_filter(self, filter_or_string, *args, **kwargs): """ Convenience method to delegate to the root_filter to generate an `or` clause. :return: :class:`~es_fluent.builder.QueryBuilder` """ self.root_filter.or_filter(filter_or_string, *args, **kwargs) return self
def add_filter(self, filter_or_string, *args, **kwargs): """ Adds a filter to the query builder's filters. :return: :class:`~es_fluent.builder.QueryBuilder` """ self.root_filter.add_filter(filter_or_string, *args, **kwargs) return self
def sort(self, field, direction="asc"): """ Adds sort criteria. """ if not isinstance(field, basestring): raise ValueError("Field should be a string") if direction not in ["asc", "desc"]: raise ValueError("Sort direction should be `asc` or `desc`") self.sorts.append({field: direction})
def remove_sort(self, field_name): """ Clears sorting criteria affecting ``field_name``. """ self.sorts = [dict(field=value) for field, value in self.sorts if field is not field_name]
def matchPrefix(text): """ This is silver bullet, cornerstone and magic wand of speed of this algorithm it filters patterns using manually selected rules. Yes, yes, it's "dirty" code and it could be beautified in many ways but this library intended to be fast, not beautiful. Without matching is x1.3 slower so let it be...