_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q45700
authenticate
train
def authenticate(): """ Authenticate the user and store the 'token' for further use Return the authentication 'token' """ print LOGIN_INIT_MESSAGE username = raw_input('{0}: '.format(LOGIN_USER_MESSAGE)) password = None while password is None: password = getpass('Password for ...
python
{ "resource": "" }
q45701
community_colors
train
def community_colors(n): """ Returns a list of visually separable colors according to total communities """ if (n > 0): colors = cl.scales['12']['qual']['Paired'] shuffle(colors) return colors[:n] else: return choice(cl.scales['12']['qual']['Paired'])
python
{ "resource": "" }
q45702
login_as_bot
train
def login_as_bot(): """ Login as the bot account "octogrid", if user isn't authenticated on Plotly """ plotly_credentials_file = join( join(expanduser('~'), PLOTLY_DIRECTORY), PLOTLY_CREDENTIALS_FILENAME) if isfile(plotly_credentials_file): with open(plotly_credentials_file, 'r') as f: credentials = lo...
python
{ "resource": "" }
q45703
SlurmProvider.submit
train
def submit(self, command, blocksize, job_name="parsl.auto"): """Submit the command as a slurm job of blocksize parallel elements. Parameters ---------- command : str Command to be made on the remote side. blocksize : int Not implemented. job_name ...
python
{ "resource": "" }
q45704
upload_to
train
def upload_to(instance, filename, prefix=None): """ Auto upload function for File and Image fields. """ ext = path.splitext(filename)[1] name = str(instance.pk or time()) + filename # We think that we use utf8 based OS file system filename = md5(name.encode('utf8')).hexdigest() + ext basedi...
python
{ "resource": "" }
q45705
reverse_toctree
train
def reverse_toctree(app, doctree, docname): """Reverse the order of entries in the root toctree if 'glob' is used.""" if docname == "changes": for node in doctree.traverse(): if node.tagname == "toctree" and node.get("glob"): node["entries"].reverse() break
python
{ "resource": "" }
q45706
treat
train
def treat(request_body): """ Treat a notification and guarantee its authenticity. :param request_body: The request body in plain text. :type request_body: string :return: A safe APIResource :rtype: APIResource """ # Python 3+ support if isinstance(request_body, six.binary_type): ...
python
{ "resource": "" }
q45707
LocalChannel.execute_no_wait
train
def execute_no_wait(self, cmd, walltime, envs={}): ''' Synchronously execute a commandline string on the shell. Args: - cmd (string) : Commandline string to execute - walltime (int) : walltime in seconds, this is not really used now. Returns: - retcode : Ret...
python
{ "resource": "" }
q45708
Client.trade_history
train
def trade_history( self, from_=None, count=None, from_id=None, end_id=None, order=None, since=None, end=None, pair=None ): """ Returns trade history. To use this method you need a privilege of the info key. :param int or None from_: trade ID, from which the display s...
python
{ "resource": "" }
q45709
Client.trans_history
train
def trans_history( self, from_=None, count=None, from_id=None, end_id=None, order=None, since=None, end=None ): """ Returns the history of transactions. To use this method you need a privilege of the info key. :param int or None from_: transaction ID, from which the ...
python
{ "resource": "" }
q45710
_get_python_version_string
train
def _get_python_version_string(): """ Returns a string representation of the Python version. :return: "2.7.8" if python version is 2.7.8. :rtype string """ version_info = sys.version_info return '.'.join(map(str, [version_info[0], version_info[1], version_info[2]]))
python
{ "resource": "" }
q45711
HttpClient._request
train
def _request(self, http_verb, url, data=None, authenticated=True): """ Perform an HTTP request. See https://docs.python.org/3/library/json.html#json-to-py-table for the http response object. :param http_verb: the HTTP verb (GET, POST, PUT, …) :type http_verb: string :pa...
python
{ "resource": "" }
q45712
find_cache_directory
train
def find_cache_directory(remote): """ Find the directory where temporary local checkouts are to be stored. :returns: The absolute pathname of a directory (a string). """ return os.path.join('/var/cache/vcs-repo-mgr' if os.access('/var/cache', os.W_OK) else tempfile.gettempdir(), ...
python
{ "resource": "" }
q45713
find_configured_repository
train
def find_configured_repository(name): """ Find a version control repository defined by the user in a configuration file. :param name: The name of the repository (a string). :returns: A :class:`Repository` object. :raises: :exc:`~vcs_repo_mgr.exceptions.NoSuchRepositoryError` when the g...
python
{ "resource": "" }
q45714
Repository.release_scheme
train
def release_scheme(self, value): """Validate the release scheme.""" if value not in KNOWN_RELEASE_SCHEMES: msg = "Release scheme %r is not supported! (valid options are %s)" raise ValueError(msg % (value, concatenate(map(repr, KNOWN_RELEASE_SCHEMES)))) set_property(self, ...
python
{ "resource": "" }
q45715
Repository.checkout
train
def checkout(self, revision=None, clean=False): """ Update the working tree of the local repository to the specified revision. :param revision: The revision to check out (a string, defaults to :attr:`default_revision`). :param clean: :data:`True` to discard chan...
python
{ "resource": "" }
q45716
Repository.commit
train
def commit(self, message, author=None): """ Commit changes to tracked files in the working tree. :param message: The commit message (a string). :param author: Override :attr:`author` (refer to :func:`coerce_author()` for details on argument ...
python
{ "resource": "" }
q45717
Repository.create_branch
train
def create_branch(self, branch_name): """ Create a new branch based on the working tree's revision. :param branch_name: The name of the branch to create (a string). This method automatically checks out the new branch, but note that the new branch may not actually exist until a ...
python
{ "resource": "" }
q45718
Repository.create_tag
train
def create_tag(self, tag_name): """ Create a new tag based on the working tree's revision. :param tag_name: The name of the tag to create (a string). """ # Make sure the local repository exists and supports a working tree. self.create() self.ensure_working_tree()...
python
{ "resource": "" }
q45719
Repository.delete_branch
train
def delete_branch(self, branch_name, message=None, author=None): """ Delete or close a branch in the local repository. :param branch_name: The name of the branch to delete or close (a string). :param message: The message to use when closing the branch requires a ...
python
{ "resource": "" }
q45720
Repository.ensure_exists
train
def ensure_exists(self): """ Make sure the local repository exists. :raises: :exc:`~exceptions.ValueError` when the local repository doesn't exist yet. """ if not self.exists: msg = "The local %s repository %s doesn't exist!" raise ValueE...
python
{ "resource": "" }
q45721
Repository.ensure_hexadecimal_string
train
def ensure_hexadecimal_string(self, value, command=None): """ Make sure the given value is a hexadecimal string. :param value: The value to check (a string). :param command: The command that produced the value (a string or :data:`None`). :returns: The validated hexadecimal strin...
python
{ "resource": "" }
q45722
Repository.ensure_release_scheme
train
def ensure_release_scheme(self, expected_scheme): """ Make sure the release scheme is correctly configured. :param expected_scheme: The expected release scheme (a string). :raises: :exc:`~exceptions.TypeError` when :attr:`release_scheme` doesn't match the expected relea...
python
{ "resource": "" }
q45723
Repository.export
train
def export(self, directory, revision=None): """ Export the complete tree from the local version control repository. :param directory: The directory where the tree should be exported (a string). :param revision: The revision to export (a string or :data:`None`, ...
python
{ "resource": "" }
q45724
Repository.find_remote
train
def find_remote(self, default=False, name=None, role=None): """ Find a remote repository connected to the local repository. :param default: :data:`True` to only look for default remotes, :data:`False` otherwise. :param name: The name of the remote to look for ...
python
{ "resource": "" }
q45725
Repository.generate_control_field
train
def generate_control_field(self, revision=None): """ Generate a Debian control file field referring for this repository and revision. :param revision: A reference to a revision, most likely the name of a branch (a string, defaults to :attr:`default_revision`). :...
python
{ "resource": "" }
q45726
Repository.interactive_merge_conflict_handler
train
def interactive_merge_conflict_handler(self, exception): """ Give the operator a chance to interactively resolve merge conflicts. :param exception: An :exc:`~executor.ExternalCommandFailed` object. :returns: :data:`True` if the operator has interactively resolved any m...
python
{ "resource": "" }
q45727
Repository.is_feature_branch
train
def is_feature_branch(self, branch_name): """ Try to determine whether a branch name refers to a feature branch. :param branch_name: The name of a branch (a string). :returns: :data:`True` if the branch name appears to refer to a feature branch, :data:`False` otherwise...
python
{ "resource": "" }
q45728
Repository.merge_up
train
def merge_up(self, target_branch=None, feature_branch=None, delete=True, create=True): """ Merge a change into one or more release branches and the default branch. :param target_branch: The name of the release branch where merging of the feature branch starts (a st...
python
{ "resource": "" }
q45729
Repository.pull
train
def pull(self, remote=None, revision=None): """ Pull changes from a remote repository into the local repository. :param remote: The location of a remote repository (a string or :data:`None`). :param revision: A specific revision to pull (a string or :data:`None`). If used in co...
python
{ "resource": "" }
q45730
Repository.push
train
def push(self, remote=None, revision=None): """ Push changes from the local repository to a remote repository. :param remote: The location of a remote repository (a string or :data:`None`). :param revision: A specific revision to push (a string or :data:`None`). .. warning:: De...
python
{ "resource": "" }
q45731
Repository.release_to_branch
train
def release_to_branch(self, release_id): """ Shortcut to translate a release identifier to a branch name. :param release_id: A :attr:`Release.identifier` value (a string). :returns: A branch name (a string). :raises: :exc:`~exceptions.TypeError` when :attr:`release_scheme` isn't...
python
{ "resource": "" }
q45732
Repository.release_to_tag
train
def release_to_tag(self, release_id): """ Shortcut to translate a release identifier to a tag name. :param release_id: A :attr:`Release.identifier` value (a string). :returns: A tag name (a string). :raises: :exc:`~exceptions.TypeError` when :attr:`release_scheme` isn't ...
python
{ "resource": "" }
q45733
Repository.select_release
train
def select_release(self, highest_allowed_release): """ Select the newest release that is not newer than the given release. :param highest_allowed_release: The identifier of the release that sets the upper bound for the selection (a ...
python
{ "resource": "" }
q45734
Repository.update_context
train
def update_context(self): """ Try to ensure that external commands are executed in the local repository. What :func:`update_context()` does depends on whether the directory given by :attr:`local` exists: - If :attr:`local` exists then the working directory of :attr:`context` ...
python
{ "resource": "" }
q45735
enumerate
train
def enumerate(vendor_id=0, product_id=0): """ Enumerate the HID Devices. Returns a generator that yields all of the HID devices attached to the system. :param vendor_id: Only return devices which match this vendor id :type vendor_id: int :param product_id: Only return devices which match...
python
{ "resource": "" }
q45736
Device.write
train
def write(self, data, report_id=b'\0'): """ Write an Output report to a HID device. This will send the data on the first OUT endpoint, if one exists. If it does not, it will be sent the data through the Control Endpoint (Endpoint 0). :param data: The data to be sent ...
python
{ "resource": "" }
q45737
Device.read
train
def read(self, length, timeout_ms=0, blocking=False): """ Read an Input report from a HID device with timeout. Input reports are returned to the host through the `INTERRUPT IN` endpoint. The first byte will contain the Report number if the device uses numbered reports. By defaul...
python
{ "resource": "" }
q45738
Device.get_manufacturer_string
train
def get_manufacturer_string(self): """ Get the Manufacturer String from the HID device. :return: The Manufacturer String :rtype: unicode """ self._check_device_status() str_p = ffi.new("wchar_t[]", 255) rv = hidapi.hid_get_manufacturer_string(self._device...
python
{ "resource": "" }
q45739
Device.get_product_string
train
def get_product_string(self): """ Get the Product String from the HID device. :return: The Product String :rtype: unicode """ self._check_device_status() str_p = ffi.new("wchar_t[]", 255) rv = hidapi.hid_get_product_string(self._device, str_p, 255) ...
python
{ "resource": "" }
q45740
Device.get_serial_number_string
train
def get_serial_number_string(self): """ Get the Serial Number String from the HID device. :return: The Serial Number String :rtype: unicode """ self._check_device_status() str_p = ffi.new("wchar_t[]", 255) rv = hidapi.hid_get_serial_number_string(self._de...
python
{ "resource": "" }
q45741
Device.send_feature_report
train
def send_feature_report(self, data, report_id=0x0): """ Send a Feature report to the device. Feature reports are sent over the Control endpoint as a Set_Report transfer. :param data: The data to send :type data: str/bytes :param report_id: The Report ID...
python
{ "resource": "" }
q45742
Device.get_feature_report
train
def get_feature_report(self, report_id, length): """ Get a feature report from the device. :param report_id: The Report ID of the report to be read :type report_id: int :return: The report data :rtype: str/bytes """ self._check_device...
python
{ "resource": "" }
q45743
Device.get_indexed_string
train
def get_indexed_string(self, idx): """ Get a string from the device, based on its string index. :param idx: The index of the string to get :type idx: int :return: The string at the index :rtype: unicode """ self._check_device_status() bufp = ffi....
python
{ "resource": "" }
q45744
Device.close
train
def close(self): """ Close connection to HID device. Automatically run when a Device object is garbage-collected, though manual invocation is recommended. """ self._check_device_status() hidapi.hid_close(self._device) self._device = None
python
{ "resource": "" }
q45745
AdblockURLFilterMeta.load_raw_rules
train
def load_raw_rules(cls, url): "Load raw rules from url or package file." raw_rules = [] filename = url.split('/')[-1] # e.g.: easylist.txt try: with closing(request.get(url, stream=True)) as file: file.raise_for_status() # lines = 0 # to...
python
{ "resource": "" }
q45746
AdblockURLFilterMeta.get_all_rules
train
def get_all_rules(cls): "Load all available Adblock rules." from adblockparser import AdblockRules raw_rules = [] for url in [ config.ADBLOCK_EASYLIST_URL, config.ADBLOCK_EXTRALIST_URL]: raw_rules.extend(cls.load_raw_rules(url)) rules = ...
python
{ "resource": "" }
q45747
NoImageFilter.get_image
train
def get_image(cls, url): """ Returned Image instance has response url. This might be different than the url param because of redirects. """ from PIL.ImageFile import Parser as PILParser length = 0 raw_image = None with closing(request.get(url, st...
python
{ "resource": "" }
q45748
FormatImageFilter.check_animated
train
def check_animated(cls, raw_image): "Checks whether the gif is animated." try: raw_image.seek(1) except EOFError: isanimated= False else: isanimated= True raise cls.AnimatedImageException
python
{ "resource": "" }
q45749
valid_options
train
def valid_options(kwargs, allowed_options): """ Checks that kwargs are valid API options""" diff = set(kwargs) - set(allowed_options) if diff: print("Invalid option(s): ", ', '.join(diff)) return False return True
python
{ "resource": "" }
q45750
Course.create
train
def create(self, fullname, shortname, category_id, **kwargs): """ Create a new course :param string fullname: The course's fullname :param string shortname: The course's shortname :param int category_id: The course's category :keyword string idnumber: (optional) Course ...
python
{ "resource": "" }
q45751
Course.delete
train
def delete(self): """ Deletes a specified courses Example Usage:: >>> import muddle >>> muddle.course(10).delete() """ params = {'wsfunction': 'core_course_delete_courses', 'courseids[0]': self.course_id} params.update(self.request_par...
python
{ "resource": "" }
q45752
Course.contents
train
def contents(self): """ Returns entire contents of course page :returns: response object Example Usage:: >>> import muddle >>> muddle.course(10).content() """ params = self.request_params params.update({'wsfunction': 'core_course_get_contents',...
python
{ "resource": "" }
q45753
Course.export_data
train
def export_data(self, export_to, delete_content=False): """ Export course data to another course. Does not include any user data. :param bool delete_content: (optional) Delete content \ from source course. Example Usage:: >>> import muddle >>> muddl...
python
{ "resource": "" }
q45754
Category.details
train
def details(self): """ Returns details for given category :returns: category response object Example Usage:: >>> import muddle >>> muddle.category(10).details() """ params = {'wsfunction': 'core_course_get_categories', 'criteria[0][key...
python
{ "resource": "" }
q45755
check_path
train
def check_path(path): """Check that a path is legal. :return: the path if all is OK :raise ValueError: if the path is illegal """ if path is None or path == b'' or path.startswith(b'/'): raise ValueError("illegal path '%s'" % path) if ( (sys.version_info[0] >= 3 and not isinsta...
python
{ "resource": "" }
q45756
format_path
train
def format_path(p, quote_spaces=False): """Format a path in utf8, quoting it if necessary.""" if b'\n' in p: p = re.sub(b'\n', b'\\n', p) quote = True else: quote = p[0] == b'"' or (quote_spaces and b' ' in p) if quote: extra = GIT_FAST_IMPORT_NEEDS_EXTRA_SPACE_AFTER_QUOT...
python
{ "resource": "" }
q45757
format_who_when
train
def format_who_when(fields): """Format a tuple of name,email,secs-since-epoch,utc-offset-secs as a string.""" offset = fields[3] if offset < 0: offset_sign = b'-' offset = abs(offset) else: offset_sign = b'+' offset_hours = offset // 3600 offset_minutes = offset // 60 - o...
python
{ "resource": "" }
q45758
ImportCommand.dump_str
train
def dump_str(self, names=None, child_lists=None, verbose=False): """Dump fields as a string. For debugging. :param names: the list of fields to include or None for all public fields :param child_lists: dictionary of child command names to fields for that child c...
python
{ "resource": "" }
q45759
CommitCommand.iter_files
train
def iter_files(self): """Iterate over files.""" # file_iter may be a callable or an iterator if callable(self.file_iter): return self.file_iter() return iter(self.file_iter)
python
{ "resource": "" }
q45760
_open_repo
train
def _open_repo(args, path_key='<path>'): """Open and return the repository containing the specified file. The file is specified by looking up `path_key` in `args`. This value or `None` is passed to `open_repository`. Returns: A `Repository` instance. Raises: ExitError: If there is a probl...
python
{ "resource": "" }
q45761
_get_anchor
train
def _get_anchor(repo, id_prefix): """Get an anchor by ID, or a prefix of its id. """ result = None for anchor_id, anchor in repo.items(): if anchor_id.startswith(id_prefix): if result is not None: raise ExitError( ExitCode.DATA_ERR, ...
python
{ "resource": "" }
q45762
_launch_editor
train
def _launch_editor(starting_text=''): "Launch editor, let user write text, then return that text." # TODO: What is a reasonable default for windows? Does this approach even # make sense on windows? editor = os.environ.get('EDITOR', 'vim') with tempfile.TemporaryDirectory() as dirname: filen...
python
{ "resource": "" }
q45763
gdate_to_jdn
train
def gdate_to_jdn(date): """ Compute Julian day from Gregorian day, month and year. Algorithm from wikipedia's julian_day article. Return: The julian day number """ not_jan_or_feb = (14 - date.month) // 12 year_since_4800bc = date.year + 4800 - not_jan_or_feb month_since_4800bc = date.mo...
python
{ "resource": "" }
q45764
hdate_to_jdn
train
def hdate_to_jdn(date): """ Compute Julian day from Hebrew day, month and year. Return: julian day number, 1 of tishrey julians, 1 of tishrey julians next year """ day = date.day month = date.month if date.month == 13: month = 6 if date.month == 14: ...
python
{ "resource": "" }
q45765
jdn_to_gdate
train
def jdn_to_gdate(jdn): """ Convert from the Julian day to the Gregorian day. Algorithm from 'Julian and Gregorian Day Numbers' by Peter Meyer. Return: day, month, year """ # pylint: disable=invalid-name # The algorithm is a verbatim copy from Peter Meyer's article # No explanation in t...
python
{ "resource": "" }
q45766
jdn_to_hdate
train
def jdn_to_hdate(jdn): """Convert from the Julian day to the Hebrew day.""" # calculate Gregorian date date = jdn_to_gdate(jdn) # Guess Hebrew year is Gregorian year + 3760 year = date.year + 3760 jdn_tishrey1 = hdate_to_jdn(HebrewDate(year, 1, 1)) jdn_tishrey1_next_year = hdate_to_jdn(Heb...
python
{ "resource": "" }
q45767
update
train
def update(anchor, handle=None): """Update an anchor based on the current contents of its source file. Args: anchor: The `Anchor` to be updated. handle: File-like object containing contents of the anchor's file. If `None`, then this function will open the file and read it. Retu...
python
{ "resource": "" }
q45768
get
train
def get(context, tags: List[str], version: int, verbose: bool, bundle: str): """Get files.""" store = Store(context.obj['database'], context.obj['root']) files = store.files(bundle=bundle, tags=tags, version=version) for file_obj in files: if verbose: tags = ', '.join(tag.name for ta...
python
{ "resource": "" }
q45769
ProgressBar._get_callargs
train
def _get_callargs(self, *args, **kwargs): """ Retrieve all arguments that `self.func` needs and return a dictionary with call arguments. """ callargs = getcallargs(self.func, *args, **kwargs) return callargs
python
{ "resource": "" }
q45770
GitHubUser.export
train
def export(self): """Export all attributes of the user to a dict. :return: attributes of the user. :rtype: dict. """ data = {} data["name"] = self.name data["contributions"] = self.contributions data["avatar"] = self.avatar data["followers"] = sel...
python
{ "resource": "" }
q45771
GitHubUser.__getContributions
train
def __getContributions(self, web): """Scrap the contributions from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ contributions_raw = web.find_all('h2', {'class': 'f4 text-normal mb-2'}) try: ...
python
{ "resource": "" }
q45772
GitHubUser.__getAvatar
train
def __getAvatar(self, web): """Scrap the avatar from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ try: self.avatar = web.find("img", {"class": "avatar"})['src'][:-10] except IndexError as error: print("There was an ...
python
{ "resource": "" }
q45773
GitHubUser.__getNumberOfRepositories
train
def __getNumberOfRepositories(self, web): """Scrap the number of repositories from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ counters = web.find_all('span', {'class': 'Counter'}) try: if 'k' not in counters[0].text: ...
python
{ "resource": "" }
q45774
GitHubUser.__getNumberOfFollowers
train
def __getNumberOfFollowers(self, web): """Scrap the number of followers from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ counters = web.find_all('span', {'class': 'Counter'}) try: if 'k' not in counters[2].text: ...
python
{ "resource": "" }
q45775
GitHubUser.__getLocation
train
def __getLocation(self, web): """Scrap the location from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ try: self.location = web.find("span", {"class": "p-label"}).text except AttributeError as error: print("There was...
python
{ "resource": "" }
q45776
GitHubUser.__getJoin
train
def __getJoin(self, web): """Scrap the join date from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ join = web.findAll("a", {"class": "dropdown-item"}) for j in join: try: if "Joined GitHub" in j.text: ...
python
{ "resource": "" }
q45777
GitHubUser.__getBio
train
def __getBio(self, web): """Scrap the bio from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ bio = web.find_all("div", {"class": "user-profile-bio"}) if bio: try: bio = bio[0].text if bio and Git...
python
{ "resource": "" }
q45778
GitHubUser.__getOrganizations
train
def __getOrganizations(self, web): """Scrap the number of organizations from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ orgsElements = web.find_all("a", {"class": "avatar-group-item"}) self.organizations = len(orgsElements)
python
{ "resource": "" }
q45779
GitHubUser.getData
train
def getData(self): """Get data of the GitHub user.""" url = self.server + self.name data = GitHubUser.__getDataFromURL(url) web = BeautifulSoup(data, "lxml") self.__getContributions(web) self.__getLocation(web) self.__getAvatar(web) self.__getNumberOfRepos...
python
{ "resource": "" }
q45780
GitHubUser.__getDataFromURL
train
def __getDataFromURL(url): """Read HTML data from an user GitHub profile. :param url: URL of the webpage to download. :type url: str. :return: webpage donwloaded. :rtype: str. """ code = 0 while code != 200: req = Request(url) try...
python
{ "resource": "" }
q45781
Settings.clean
train
def clean(self, settings): """ Filter given settings to keep only key names available in ``DEFAULT_SETTINGS``. Args: settings (dict): Loaded settings. Returns: dict: Settings object filtered. """ return {k: v for k, v in settings.items()...
python
{ "resource": "" }
q45782
Settings.set_settings
train
def set_settings(self, settings): """ Set every given settings as object attributes. Args: settings (dict): Dictionnary of settings. """ for k, v in settings.items(): setattr(self, k, v)
python
{ "resource": "" }
q45783
Settings.update
train
def update(self, settings): """ Update object attributes from given settings Args: settings (dict): Dictionnary of elements to update settings. Returns: dict: Dictionnary of all current saved settings. """ settings = self.clean(settings) ...
python
{ "resource": "" }
q45784
BasenwcParser._fetch_output_files
train
def _fetch_output_files(self, retrieved): """ Checks the output folder for standard output and standard error files, returns their absolute paths on success. :param retrieved: A dictionary of retrieved nodes, as obtained from the parser. """ from aiida.common.d...
python
{ "resource": "" }
q45785
ContentExtractor._tidy
train
def _tidy(self, html, smart_tidy): """ Tidy HTML if we have a tidy method. This fixes problems with some sites which would otherwise trouble DOMDocument's HTML parsing. Although sometimes it makes the problem worse, which is why we can override it in site config files. ...
python
{ "resource": "" }
q45786
ContentExtractor._parse_html
train
def _parse_html(self): """ Load the parser and parse `self.html`. """ if self.config.parser != 'lxml': raise NotImplementedError('%s parser not implemented' % self.config.parser) self.parser = etree.HTMLParser() try: self.p...
python
{ "resource": "" }
q45787
ContentExtractor._extract_next_page_link
train
def _extract_next_page_link(self): """ Try to get next page link. """ # HEADS UP: we do not abort if next_page_link is already set: # we try to find next (eg. find 3 if already at page 2). for pattern in self.config.next_page_link: items = self.parsed_tree.xpath(p...
python
{ "resource": "" }
q45788
ContentExtractor._extract_date
train
def _extract_date(self): """ Extract date from HTML. """ if self.date: return found = False for pattern in self.config.date: items = self.parsed_tree.xpath(pattern) if isinstance(items, basestring): # In case xpath returns only one...
python
{ "resource": "" }
q45789
ContentExtractor._extract_body
train
def _extract_body(self): """ Extract the body content from HTML. """ def is_descendant_node(parent, node): node = node.getparent() while node is not None: if node == parent: return True node = node.getparent() retur...
python
{ "resource": "" }
q45790
ContentExtractor._auto_extract_if_failed
train
def _auto_extract_if_failed(self): """ Try to automatically extract as much as possible. """ if not self.config.autodetect_on_failure: return readabilitized = Document(self.html) if self.title is None: if bool(self.config.title): self.failures.a...
python
{ "resource": "" }
q45791
ContentExtractor.process
train
def process(self, html, url=None, smart_tidy=True): u""" Process HTML content or URL. For automatic extraction patterns and cleanups, :mod:`readability-lxml` is used, to stick as much as possible to the original PHP implementation and produce at least similar results with the same ...
python
{ "resource": "" }
q45792
DatalakeRecord.list_from_url
train
def list_from_url(cls, url): '''return a list of DatalakeRecords for the specified url''' key = cls._get_key(url) metadata = cls._get_metadata_from_key(key) ct = cls._get_create_time(key) time_buckets = cls.get_time_buckets_from_metadata(metadata) return [cls(url, metadat...
python
{ "resource": "" }
q45793
DatalakeRecord.list_from_metadata
train
def list_from_metadata(cls, url, metadata): '''return a list of DatalakeRecords for the url and metadata''' key = cls._get_key(url) metadata = Metadata(**metadata) ct = cls._get_create_time(key) time_buckets = cls.get_time_buckets_from_metadata(metadata) return [cls(url, ...
python
{ "resource": "" }
q45794
DatalakeRecord.get_time_buckets_from_metadata
train
def get_time_buckets_from_metadata(metadata): '''return a list of time buckets in which the metadata falls''' start = metadata['start'] end = metadata.get('end') or start buckets = DatalakeRecord.get_time_buckets(start, end) if len(buckets) > DatalakeRecord.MAXIMUM_BUCKET_SPAN: ...
python
{ "resource": "" }
q45795
DatalakeRecord.get_time_buckets
train
def get_time_buckets(start, end): '''get the time buckets spanned by the start and end times''' d = DatalakeRecord.TIME_BUCKET_SIZE_IN_MS first_bucket = start / d last_bucket = end / d return list(range( int(first_bucket), int(last_bucket) + 1))
python
{ "resource": "" }
q45796
write_pdb
train
def write_pdb(residues, chain_id=' ', alt_states=False, strip_states=False): """Writes a pdb file for a list of residues. Parameters ---------- residues : list List of Residue objects. chain_id : str String of the chain id, defaults to ' '. alt_states : bool, optional If...
python
{ "resource": "" }
q45797
BaseAmpal.centre_of_mass
train
def centre_of_mass(self): """Returns the centre of mass of AMPAL object. Notes ----- All atoms are included in calculation, call `centre_of_mass` manually if another selection is require. Returns ------- centre_of_mass : numpy.array 3D coordi...
python
{ "resource": "" }
q45798
Monomer.get_atoms
train
def get_atoms(self, inc_alt_states=False): """Returns all atoms in the `Monomer`. Parameters ---------- inc_alt_states : bool, optional If `True`, will return `Atoms` for alternate states. """ if inc_alt_states: return itertools.chain(*[x[1].value...
python
{ "resource": "" }
q45799
Monomer.close_monomers
train
def close_monomers(self, group, cutoff=4.0): """Returns a list of Monomers from within a cut off distance of the Monomer Parameters ---------- group: BaseAmpal or Subclass Group to be search for Monomers that are close to this Monomer. cutoff: float Dista...
python
{ "resource": "" }