Search is not available for this dataset
text
stringlengths
75
104k
def matched_file_count(self, dataset_id, glob=".", is_dir=False): """ Returns the number of files matching a pattern in a dataset. :param dataset_id: The ID of the dataset to search for files. :type dataset_id: int :param glob: A pattern which will be matched against files in th...
def get_ingest_status(self, dataset_id): """ Returns the current status of dataset ingestion. If any file uploaded to a dataset is in an error/failure state this endpoint will return error/failure. If any files are still processing, will return processing. :param dataset_id: Dataset i...
def get_dataset_files(self, dataset_id, glob=".", is_dir=False, version_number=None): """ Retrieves URLs for the files matched by a glob or a path to a directory in a given dataset. :param dataset_id: The id of the dataset to retrieve files from :type dataset_id: int :pa...
def get_dataset_file(self, dataset_id, file_path, version = None): """ Retrieves a dataset file matching a provided file path :param dataset_id: The id of the dataset to retrieve file from :type dataset_id: int :param file_path: The file path within the dataset :type fil...
def download_files(self, dataset_files, destination='.'): """ Downloads file(s) to a local destination. :param dataset_files: :type dataset_files: list of :class: `DatasetFile` :param destination: The path to the desired local download destination :type destination: str ...
def get_pif(self, dataset_id, uid, dataset_version = None): """ Retrieves a PIF from a given dataset. :param dataset_id: The id of the dataset to retrieve PIF from :type dataset_id: int :param uid: The uid of the PIF to retrieve :type uid: str :param dataset_vers...
def create_dataset(self, name=None, description=None, public=False): """ Create a new data set. :param name: name of the dataset :type name: str :param description: description for the dataset :type description: str :param public: A boolean indicating whether or ...
def update_dataset(self, dataset_id, name=None, description=None, public=None): """ Update a data set. :param dataset_id: The ID of the dataset to update :type dataset_id: int :param name: name of the dataset :type name: str :param description: description for th...
def create_dataset_version(self, dataset_id): """ Create a new data set version. :param dataset_id: The ID of the dataset for which the version must be bumped. :type dataset_id: int :return: The new dataset version. :rtype: :class:`DatasetVersion` """ fai...
def get_available_columns(self, dataset_ids): """ Retrieves the set of columns from the combination of dataset ids given :param dataset_ids: The id of the dataset to retrieve columns from :type dataset_ids: list of int :return: A list of column names from the dataset ids given. ...
def __generate_search_template(self, dataset_ids): """ Generates a default search templates from the available columns in the dataset ids given. :param dataset_ids: The id of the dataset to retrieve files from :type dataset_ids: list of int :return: A search template based on th...
def __prune_search_template(self, extract_as_keys, search_template): """ Returns a new search template, but the new template has only the extract_as_keys given. :param extract_as_keys: List of extract as keys to keep :param search_template: The search template to prune :return: ...
def default(self, obj): """ Convert an object to a form ready to dump to json. :param obj: Object being serialized. The type of this object must be one of the following: None; a single object derived from the Pio class; or a list of objects, each derived from the Pio class. :return: Lis...
def _keys_to_camel_case(self, obj): """ Make a copy of a dictionary with all keys converted to camel case. This is just calls to_camel_case on each of the keys in the dictionary and returns a new dictionary. :param obj: Dictionary to convert keys to camel case. :return: Dictionary with ...
def validate(self, ml_template): """ Runs the template against the validation endpoint, returns a message indicating status of the templte :param ml_template: Template to validate :return: OK or error message if validation failed """ data = { "ml_template": ...
def _validate_course_key(course_key): """ Validation helper """ if not validators.course_key_is_valid(course_key): exceptions.raise_exception( "CourseKey", course_key, exceptions.InvalidCourseKeyException )
def _validate_organization_data(organization_data): """ Validation helper """ if not validators.organization_data_is_valid(organization_data): exceptions.raise_exception( "Organization", organization_data, exceptions.InvalidOrganizationException )
def add_organization_course(organization_data, course_key): """ Adds a organization-course link to the system """ _validate_course_key(course_key) _validate_organization_data(organization_data) data.create_organization_course( organization=organization_data, course_key=course_key...
def remove_organization_course(organization, course_key): """ Removes the specfied course from the specified organization """ _validate_organization_data(organization) _validate_course_key(course_key) return data.delete_organization_course(course_key=course_key, organization=organization)
def raise_exception(entity_type, entity, exception): """ Exception helper """ raise exception( u'The {} you have provided is not valid: {}'.format(entity_type, entity).encode('utf-8') )
def course_key_is_valid(course_key): """ Course key object validation """ if course_key is None: return False try: CourseKey.from_string(text_type(course_key)) except (InvalidKeyError, UnicodeDecodeError): return False return True
def organization_data_is_valid(organization_data): """ Organization data validation """ if organization_data is None: return False if 'id' in organization_data and not organization_data.get('id'): return False if 'name' in organization_data and not organization_data.get('name'): ...
def _activate_organization(organization): """ Activates an inactivated (soft-deleted) organization as well as any inactive relationships """ [_activate_organization_course_relationship(record) for record in internal.OrganizationCourse.objects.filter(organization_id=organization.id, active=False)] ...
def _inactivate_organization(organization): """ Inactivates an activated organization as well as any active relationships """ [_inactivate_organization_course_relationship(record) for record in internal.OrganizationCourse.objects.filter(organization_id=organization.id, active=True)] [_inactiva...
def _activate_organization_course_relationship(relationship): # pylint: disable=invalid-name """ Activates an inactive organization-course relationship """ # If the relationship doesn't exist or the organization isn't active we'll want to raise an error relationship = internal.OrganizationCourse.ob...
def _inactivate_organization_course_relationship(relationship): # pylint: disable=invalid-name """ Inactivates an active organization-course relationship """ relationship = internal.OrganizationCourse.objects.get( id=relationship.id, active=True ) _inactivate_record(relationship...
def create_organization(organization): """ Inserts a new organization into app/local state given the following dictionary: { 'name': string, 'description': string } Returns an updated dictionary including a new 'id': integer field/value """ # Trust, but verify... if not o...
def update_organization(organization): """ Updates an existing organization in app/local state Returns a dictionary representation of the object """ organization_obj = serializers.deserialize_organization(organization) try: organization = internal.Organization.objects.get(id=organization...
def fetch_organization(organization_id): """ Retrieves a specific organization from app/local state Returns a dictionary representation of the object """ organization = {'id': organization_id} if not organization_id: exceptions.raise_exception("organization", organization, exceptions.Inv...
def fetch_organization_by_short_name(organization_short_name): """ Retrieves a specific organization from app/local state by short name Returns a dictionary representation of the object """ organization = {'short_name': organization_short_name} if not organization_short_name: exceptions....
def create_organization_course(organization, course_key): """ Inserts a new organization-course relationship into app/local state No response currently defined for this operation """ organization_obj = serializers.deserialize_organization(organization) try: relationship = internal.Organi...
def delete_organization_course(organization, course_key): """ Removes an existing organization-course relationship from app/local state No response currently defined for this operation """ try: relationship = internal.OrganizationCourse.objects.get( organization=organization['id'...
def fetch_organization_courses(organization): """ Retrieves the set of courses currently linked to the specified organization """ organization_obj = serializers.deserialize_organization(organization) queryset = internal.OrganizationCourse.objects.filter( organization=organization_obj, ...
def fetch_course_organizations(course_key): """ Retrieves the organizations linked to the specified course """ queryset = internal.OrganizationCourse.objects.filter( course_id=text_type(course_key), active=True ).select_related('organization') return [serializers.serialize_organi...
def delete_course_references(course_key): """ Inactivates references to course keys within this app (ref: receivers.py and api.py) """ [_inactivate_record(record) for record in internal.OrganizationCourse.objects.filter( course_id=text_type(course_key), active=True )]
def serialize_organization(organization): """ Organization object-to-dict serialization """ return { 'id': organization.id, 'name': organization.name, 'short_name': organization.short_name, 'description': organization.description, 'logo': organization.logo }
def serialize_organization_with_course(organization_course): """ OrganizationCourse serialization (composite object) """ return { 'id': organization_course.organization.id, 'name': organization_course.organization.name, 'short_name': organization_course.organization.short_name, ...
def deserialize_organization(organization_dict): """ Organization dict-to-object serialization """ return models.Organization( id=organization_dict.get('id'), name=organization_dict.get('name', ''), short_name=organization_dict.get('short_name', ''), description=organizat...
def check_large_images(self, node, parent_depth_level, sibling_depth_level): """\ although slow the best way to determine the best image is to download them and check the actual dimensions of the image when on disk so we'll go through a phased approach... 1. get a list of ALL ima...
def is_banner_dimensions(width, height): """\ returns true if we think this is kind of a bannery dimension like 600 / 100 = 6 may be a fishy dimension for a good image """ if width == height: return False if width > height: diff = float(width / he...
def is_valid_filename(self, image_node): """\ will check the image src against a list of bad image files we know of like buttons, etc... """ src = self.parser.getAttribute(image_node, attr='src') if not src: return False if self.badimages_names_re.se...
def get_images_bytesize_match(self, images): """\ loop through all the images and find the ones that have the best bytez to even make them a candidate """ cnt = 0 max_bytes_size = 15728640 good_images = [] for image in images: if cnt > 30: ...
def check_link_tag(self): """\ checks to see if we were able to find open link_src on this page """ node = self.article.raw_doc meta = self.parser.getElementsByTag(node, tag='link', attr='rel', value='image_src') for item in meta: src = self.parser.get...
def check_known_schemas(self): """\ checks to see if we were able to find the image via known schemas: Supported Schemas - Open Graph - schema.org """ if 'image' in self.article.opengraph: return self.get_image(self.article.opengraph["image"], ...
def get_local_image(self, src): """\ returns the bytes of the image file on disk """ return ImageUtils.store_image(self.fetcher, self.article.link_hash, src, self.config)
def build_image_path(self, src): """\ This method will take an image path and build out the absolute path to that image * using the initial url we crawled so we can find a link to the image if they use relative urls like ../myimage.jpg """ o = urlparse...
def get_video(self, node): """ Create a video object from a video embed """ video = Video() video._embed_code = self.get_embed_code(node) video._embed_type = self.get_embed_type(node) video._width = self.get_width(node) video._height = self.get_height(node...
def get_encodings_from_content(content): """ Code from: https://github.com/sigmavirus24/requests-toolbelt/blob/master/requests_toolbelt/utils/deprecated.py Return encodings from given content string. :param content: string to extract encodings from. """ if isinstance(content, bytes): ...
def store_image(cls, http_client, link_hash, src, config): """\ Writes an image src http string to disk as a temporary file and returns the LocallyStoredImage object that has the info you should need on the image """ # check for a cache hit already on disk image =...
def known_context_patterns(self, val): ''' val must be an ArticleContextPattern, a dictionary, or list of \ dictionaries e.g., {'attr': 'class', 'value': 'my-article-class'} or [{'attr': 'class', 'value': 'my-article-class'}, {'attr': 'id', 'value': 'm...
def known_publish_date_tags(self, val): ''' val must be a dictionary or list of dictionaries e.g., {'attrribute': 'name', 'value': 'my-pubdate', 'content': 'datetime'} or [{'attrribute': 'name', 'value': 'my-pubdate', 'content': 'datetime'}, {'attrribute': 'proper...
def known_author_patterns(self, val): ''' val must be a dictionary or list of dictionaries e.g., {'attrribute': 'name', 'value': 'my-pubdate', 'content': 'datetime'} or [{'attrribute': 'name', 'value': 'my-pubdate', 'content': 'datetime'}, {'attrribute': 'property...
def get_siblings_content(self, current_sibling, baselinescore_siblings_para): """ adds any siblings that may have a decent score to this node """ if current_sibling.tag == 'p' and self.parser.getText(current_sibling): tmp = current_sibling if tmp.tail: ...
def is_highlink_density(self, element): """ checks the density of links within a node, is there not much text and most of it contains linky shit? if so it's no good """ links = self.parser.getElementsByTag(element, tag='a') if not links: return False ...
def nodes_to_check(self, docs): """\ returns a list of nodes we want to search on like paragraphs and tables """ nodes_to_check = [] for doc in docs: for tag in ['p', 'pre', 'td']: items = self.parser.getElementsByTag(doc, tag=tag) ...
def post_cleanup(self): """\ remove any divs that looks like non-content, clusters of links, or paras with no gusto """ parse_tags = ['p'] if self.config.parse_lists: parse_tags.extend(['ul', 'ol']) if self.config.parse_headers: parse_tags....
def infos(self): ''' dict: The summation of all data available about the extracted article Note: Read only ''' data = { "meta": { "description": self.meta_description, "lang": self.meta_lang, "keywords": self.meta_k...
def clean_title(self, title): """Clean title with the use of og:site_name in this case try to get rid of site name and use TITLE_SPLITTERS to reformat title """ # check if we have the site name in opengraph data if "site_name" in list(self.article.opengraph.keys()): ...
def get_title(self): """\ Fetch the article title and analyze it """ title = '' # rely on opengraph in case we have the data if "title" in list(self.article.opengraph.keys()): return self.clean_title(self.article.opengraph['title']) elif self.article....
def get_canonical_link(self): """ if the article has meta canonical link set in the url """ if self.article.final_url: kwargs = {'tag': 'link', 'attr': 'rel', 'value': 'canonical'} meta = self.parser.getElementsByTag(self.article.doc, **kwargs) if meta...
def make_list_elms_pretty(self): """ make any list element read like a list """ for elm in self.parser.getElementsByTag(self.top_node, tag='li'): elm.text = r'• {}'.format(elm.text)
def close(self): ''' Close the network connection and perform any other required cleanup Note: Auto closed when using goose as a context manager or when garbage collected ''' if self.fetcher is not None: self.shutdown_network() self.finalizer.atexit = Fal...
def extract(self, url=None, raw_html=None): ''' Extract the most likely article content from the html page Args: url (str): URL to pull and parse raw_html (str): String representation of the HTML page Returns: Article: Representation of th...
def __crawl(self, crawl_candidate): ''' wrap the crawling functionality ''' def crawler_wrapper(parser, parsers_lst, crawl_candidate): try: crawler = Crawler(self.config, self.fetcher) article = crawler.crawl(crawl_candidate) except (UnicodeDecodeE...
def smart_unicode(string, encoding='utf-8', strings_only=False, errors='strict'): """ Returns a unicode object representing 's'. Treats bytestrings using the 'encoding' codec. If strings_only is True, don't convert (some) non-string-like objects. """ # if isinstance(s, Promise): # # The...
def force_unicode(string, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_unicode, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common ca...
def smart_str(string, encoding='utf-8', strings_only=False, errors='strict'): """ Returns a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. """ if strings_only and isinstance(string, (type(None), int)): re...
def get_urls(self): """Add URLs needed to handle image uploads.""" urls = patterns( '', url(r'^upload/$', self.admin_site.admin_view(self.handle_upload), name='quill-file-upload'), ) return urls + super(QuillAdmin, self).get_urls()
def handle_upload(self, request): """Handle file uploads from WYSIWYG.""" if request.method != 'POST': raise Http404 if request.is_ajax(): try: filename = request.GET['quillUploadFile'] data = request is_raw = True ...
def render(self, name, value, attrs={}): """Render the Quill WYSIWYG.""" if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) quill_app = apps.get_app_config('quill') quill_config = getattr(quill_app, self.config) return mark_safe(ren...
def formfield(self, **kwargs): """Get the form for field.""" defaults = { 'form_class': RichTextFormField, 'config': self.config, } defaults.update(kwargs) return super(RichTextField, self).formfield(**defaults)
def render_toolbar(context, config): """Render the toolbar for the given config.""" quill_config = getattr(quill_app, config) t = template.loader.get_template(quill_config['toolbar_template']) return t.render(context)
def get_meta_image_url(request, image): """ Resize an image for metadata tags, and return an absolute URL to it. """ rendition = image.get_rendition(filter='original') return request.build_absolute_uri(rendition.url)
def read(self, filename=None): """Read and parse mdp file *filename*.""" self._init_filename(filename) def BLANK(i): return "B{0:04d}".format(i) def COMMENT(i): return "C{0:04d}".format(i) data = odict() iblank = icomment = 0 with open(se...
def write(self, filename=None, skipempty=False): """Write mdp file to *filename*. :Keywords: *filename* output mdp file; default is the filename the mdp was read from *skipempty* : boolean ``True`` removes any parameter lines from outpu...
def find_gromacs_command(commands): """Return *driver* and *name* of the first command that can be found on :envvar:`PATH`""" # We could try executing 'name' or 'driver name' but to keep things lean we # just check if the executables can be found and then hope for the best. commands = utilities.asiter...
def check_mdrun_success(logfile): """Check if ``mdrun`` finished successfully. Analyses the output from ``mdrun`` in *logfile*. Right now we are simply looking for the line "Finished mdrun on node" in the last 1kb of the file. (The file must be seeakable.) :Arguments: *logfile* : filename ...
def get_double_or_single_prec_mdrun(): """Return double precision ``mdrun`` or fall back to single precision. This convenience function tries :func:`gromacs.mdrun_d` first and if it cannot run it, falls back to :func:`gromacs.mdrun` (without further checking). .. versionadded:: 0.5.1 """ t...
def commandline(self, **mpiargs): """Returns simple command line to invoke mdrun. If :attr:`mpiexec` is set then :meth:`mpicommand` provides the mpi launcher command that prefixes the actual ``mdrun`` invocation: :attr:`mpiexec` [*mpiargs*] :attr:`mdrun` [*mdrun-args*] The...
def mpicommand(self, *args, **kwargs): """Return a list of the mpi command portion of the commandline. Only allows primitive mpi at the moment: *mpiexec* -n *ncores* *mdrun* *mdrun-args* (This is a primitive example for OpenMP. Override it for more complicated cases.) ...
def run(self, pre=None, post=None, mdrunargs=None, **mpiargs): """Execute the mdrun command (possibly as a MPI command) and run the simulation. :Keywords: *pre* a dictionary containing keyword arguments for the :meth:`prehook` *post* a dictionary containing...
def run_check(self, **kwargs): """Run :program:`mdrun` and check if run completed when it finishes. This works by looking at the mdrun log file for 'Finished mdrun on node'. It is useful to implement robust simulation techniques. :Arguments: *kwargs* are keyword argu...
def prehook(self, **kwargs): """Launch local smpd.""" cmd = ['smpd', '-s'] logger.info("Starting smpd: "+" ".join(cmd)) rc = subprocess.call(cmd) return rc
def _define_canned_commands(): """Define functions for the top level name space. Definitions are collected here so that they can all be wrapped in a try-except block that avoids code failing when the Gromacs tools are not available --- in some cases they are not necessary to use parts of GromacsWra...
def trj_fitandcenter(xy=False, **kwargs): """Center everything and make a compact representation (pass 1) and fit the system to a reference (pass 2). :Keywords: *s* input structure file (tpr file required to make molecule whole); if a list or tuple is provided then s[0] is used for...
def cat(prefix="md", dirname=os.path.curdir, partsdir="parts", fulldir="full", resolve_multi="pass"): """Concatenate all parts of a simulation. The xtc, trr, and edr files in *dirname* such as prefix.xtc, prefix.part0002.xtc, prefix.part0003.xtc, ... are 1) moved to the *partsdir* (under *d...
def glob_parts(prefix, ext): """Find files from a continuation run""" if ext.startswith('.'): ext = ext[1:] files = glob.glob(prefix+'.'+ext) + glob.glob(prefix+'.part[0-9][0-9][0-9][0-9].'+ext) files.sort() # at least some rough sorting... return files
def grompp_qtot(*args, **kwargs): """Run ``gromacs.grompp`` and return the total charge of the system. :Arguments: The arguments are the ones one would pass to :func:`gromacs.grompp`. :Returns: The total charge as reported Some things to keep in mind: * The stdout output of grompp ...
def _mdp_include_string(dirs): """Generate a string that can be added to a mdp 'include = ' line.""" include_paths = [os.path.expanduser(p) for p in dirs] return ' -I'.join([''] + include_paths)
def add_mdp_includes(topology=None, kwargs=None): """Set the mdp *include* key in the *kwargs* dict. 1. Add the directory containing *topology*. 2. Add all directories appearing under the key *includes* 3. Generate a string of the form "-Idir1 -Idir2 ..." that is stored under the key *include* (...
def filter_grompp_options(**kwargs): """Returns one dictionary only containing valid :program:`grompp` options and everything else. Option list is hard coded and nased on :class:`~gromacs.tools.grompp` 4.5.3. :Returns: ``(grompp_dict, other_dict)`` .. versionadded:: 0.2.4 """ grompp_options =...
def create_portable_topology(topol, struct, **kwargs): """Create a processed topology. The processed (or portable) topology file does not contain any ``#include`` statements and hence can be easily copied around. It also makes it possible to re-grompp without having any special itp files available....
def get_volume(f): """Return the volume in nm^3 of structure file *f*. (Uses :func:`gromacs.editconf`; error handling is not good) """ fd, temp = tempfile.mkstemp('.gro') try: rc,out,err = gromacs.editconf(f=f, o=temp, stdout=False) finally: os.unlink(temp) return [float(x.s...
def edit_mdp(mdp, new_mdp=None, extend_parameters=None, **substitutions): """Change values in a Gromacs mdp file. Parameters and values are supplied as substitutions, eg ``nsteps=1000``. By default the template mdp file is **overwritten in place**. If a parameter does not exist in the template then i...
def edit_txt(filename, substitutions, newname=None): """Primitive text file stream editor. This function can be used to edit free-form text files such as the topology file. By default it does an **in-place edit** of *filename*. If *newname* is supplied then the edited file is written to *newname*. ...
def remove_molecules_from_topology(filename, **kwargs): """Remove autogenerated [ molecules ] entries from *filename*. Valid entries in ``[ molecules ]`` below the default *marker* are removed. For example, a topology file such as :: [ molecules ] Protein 1 SOL 213 ; Th...
def make_ndx_captured(**kwargs): """make_ndx that captures all output Standard :func:`~gromacs.make_ndx` command with the input and output pre-set in such a way that it can be conveniently used for :func:`parse_ndxlist`. Example:: ndx_groups = parse_ndxlist(make_ndx_captured(n=ndx)[0]) ...
def get_ndx_groups(ndx, **kwargs): """Return a list of index groups in the index file *ndx*. :Arguments: - *ndx* is a Gromacs index file. - kwargs are passed to :func:`make_ndx_captured`. :Returns: list of groups as supplied by :func:`parse_ndxlist` Alternatively, load the in...
def parse_ndxlist(output): """Parse output from make_ndx to build list of index groups:: groups = parse_ndxlist(output) output should be the standard output from ``make_ndx``, e.g.:: rc,output,junk = gromacs.make_ndx(..., input=('', 'q'), stdout=False, stderr=True) (or simply use rc...
def parse_groups(output): """Parse ``make_ndx`` output and return groups as a list of dicts.""" groups = [] for line in output.split('\n'): m = NDXGROUP.match(line) if m: d = m.groupdict() groups.append({'name': d['GROUPNAME'], 'nr': int(d['...