code
stringlengths
1
18.2k
def trades(self, pair, limit=150, ignore_invalid=0): """ This method provides the information about the last trades. :param str or iterable pair: pair (ex. 'btc_usd' or ['btc_usd', 'eth_usd']) :param limit: how many orders should be displayed (150 by default, max 5000) :param int ignore_invalid: ignore non-existing pai...
def trade(self, pair, type_, rate, amount): """ The basic method that can be used for creating orders and trading on the exchange. To use this method you need an API key privilege to trade. You can only create limit orders using this method, but you can emulate market orders using rate parameters. E.g. using rate=0.1 y...
amount you need to buy/sell """ return self._trade_api_call('Trade', pair=pair, type_=type_, rate=rate, amount=amount)
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 starts (default 0) :param int or None count: the numbe...
""" return self._trade_api_call( 'TradeHistory', from_=from_, count=count, from_id=from_id, end_id=end_id, order=order, since=since, end=end, pair=pair )
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 display starts (default 0) :param int or None count: ...
end=end )
def withdraw_coin(self, coin_name, amount, address): """ The method is designed for cryptocurrency withdrawals. Please note: You need to have the privilege of the Withdraw key to be able to use this method. You can make a request for enabling this privilege by submitting a ticket to Support. You need to create the API ...
coin_name: currency (ex. 'BTC') :param int amount: withdrawal amount :param str address: withdrawal address """ return self._trade_api_call('WithdrawCoin', coinName=coin_name, amount=amount, address=address)
def create_coupon(self, currency, amount, receiver): """ This method allows you to create Coupons. Please, note: In order to use this method, you need the Coupon key privilege. You can make a request to enable it by submitting a ticket to Support.. You need to create the API key that you are going to use for this metho...
have enabled the Withdraw privilege for it. :param str currency: currency (ex. 'BTC') :param int amount: withdrawal amount :param str receiver: name of user who is allowed to redeem the code """ return self._trade_api_call('CreateCoupon', currency=currency, amount=amount, receiver=receiver)
def playerJoin(config, agentCallBack, lobbyTimeout=c.INITIAL_TIMEOUT, debug=True): """cause an agent to join an already hosted game""" FLAGS(sys.argv) # ignore pysc2 command-line handling (eww) log = protocol.logging.logging log.disable(log.CRITICAL) # disable pysc2 logging amHosting = not bool(config.host) thisPlayer ...
same machine, this subsequent process closes! controller = ClientController() controller.connect(url=selectedIP, port=selectPort, timeout=lobbyTimeout) # establish socket connection if amHosting: if debug: print("[%s] Starcraft2 host application is live. (%s)"%(operType, controller.status)) # status: launched print("[%...
# SC2APIProtocol.RequestJoinGame print("[%s] connection to %s:%d was successful. Game is starting! (%s)"%(operType, selectedIP, selectPort, controller.status)) # status: in_game thisPlayer.playerID = int(joinResp.player_id) # update playerID; repsponse to join game request is authority if debug: print("[%s] joined matc...
startWaitTime = now() while True: # wait for game to end while players/bots do their thing obs = getGameState() result = obs.player_result if result: # match end condition was supplied by the client finalResult = rh.idPlayerResults(config, result) break try: agentCallBack(obs) # do developer's creative stuff except Exc...
# state was previously in game and then exited that state finalResult = rh.playerSurrendered(config) # rage quit is losing else: finalResult = rh.playerDisconnected(config) print("%s Connection to game host has ended, even intentionally by agent. Message:%s%s"%(type(e), os.linesep, e)) except KeyboardInterrupt: if debu...
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]]))
def _raise_unrecoverable_error_payplug(self, exception): """ Raises an exceptions.ClientError with a message telling that the error probably comes from PayPlug. :param exception: Exception that caused the ClientError. :type exception: Exception :raise exceptions.ClientError """ message = ('There was an unrecoverable er...
def _raise_unrecoverable_error_client(self, exception): """ Raises an exceptions.ClientError with a message telling that the error probably comes from the client configuration. :param exception: Exception that caused the ClientError :type exception: Exception :raise exceptions.ClientError """ message = ('There was an u...
def do_request(self, http_verb, url, headers, data=None): """ :see :func:`~HttpRequest.do_request` """ if data: data = json.dumps(data) try: response = requests.request(http_verb, url, headers=headers, data=data, verify=config.CACERT_PATH) except (requests.exceptions.Timeout, requests.exceptions.TooManyRedirects) as ex...
def do_request(self, http_verb, url, headers, data=None): """ :see :func:`~HttpRequest.do_request` """ if data: data = json.dumps(data) request = urllib.request.Request(url, data, headers) request.get_method = lambda: http_verb try: response = urllib.request.urlopen(request) except urllib.error.HTTPError as response_: ...
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 :param url: the path to the resource queried :type ur...
= response.decode('utf-8') if not 200 <= status < 300: raise exceptions.HttpError.map_http_status_to_exception(status)(http_response=response, http_status=status) try: response_object = json.loads(response) except ValueError: raise exceptions.UnexpectedAPIResponseException(http_response=response, http_status=status) re...
def coerce_author(value): """ Coerce strings to :class:`Author` objects. :param value: A string or :class:`Author` object. :returns: An :class:`Author` object. :raises: :exc:`~exceptions.ValueError` when `value` isn't a string or :class:`Author` object. """ # Author objects pass through untouched. if isinstance(value, ...
def coerce_feature_branch(value): """ Convert a string to a :class:`FeatureBranchSpec` object. :param value: A string or :class:`FeatureBranchSpec` object. :returns: A :class:`FeatureBranchSpec` object. """ # Repository objects pass through untouched. if isinstance(value, FeatureBranchSpec): return value # We expect a ...
def coerce_repository(value, context=None): """ Convert a string (taken to be a repository name or location) to a :class:`Repository` object. :param value: The name or location of a repository (a string) or a :class:`Repository` object. :param context: An execution context created by :mod:`executor.contexts` (defaults ...
If the value is a string that starts with a known VCS type prefix (e.g. ``hg+https://bitbucket.org/ianb/virtualenv``) the prefix is removed from the string and a :class:`Repository` object is returned: - If the resulting string points to an existing local directory it will be used to set :attr:`~Repository.local`. - Ot...
be used to set :attr:`~Repository.local`. - Otherwise the value is used to set :attr:`~Repository.remote`. """ # Coerce the context argument. context = context or LocalContext() # Repository objects pass through untouched. if isinstance(value, Repository): return value # We expect a string with a name or URL. if not is...
the type of an existing local repository. for cls in load_backends(): if cls.contains_repository(context, value): return repository_factory(cls, context=context, local=value) # Check for locations that end with `.git' (a common idiom for remote # git repositories) even if the location isn't prefixed with `git+'. if val...
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(), urlparse.quote(remote, safe=''))
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 given repository name doesn't match...
``hg`` (``mercurial`` is also accepted), ``git`` and ``bzr`` (``bazaar`` is also accepted). """ parser = configparser.RawConfigParser() for config_file in [SYSTEM_CONFIG_FILE, USER_CONFIG_FILE]: config_file = parse_path(config_file) if os.path.isfile(config_file): logger.debug("Loading configuration file (%s) ..", form...
None) if bare is not None: # Default to bare=None but enable configuration # file(s) to enforce bare=True or bare=False. kw['bare'] = coerce_boolean(bare) # Process the `remote', `release_scheme' and `release_filter' options. for name in 'remote', 'release-scheme', 'release-filter': value = options.get(name) if value i...
def repository_factory(vcs_type, **kw): """ Instantiate a :class:`Repository` object based on the given type and arguments. :param vcs_type: One of the strings 'bazaar', 'bzr', 'git', 'hg' or 'mercurial' or a subclass of :class:`Repository`. :param kw: The keyword arguments to :func:`Repository.__init__()`. :returns: A...
logger.debug("Generated repository cache key: %r", cache_key) if cache_key in loaded_repositories: logger.debug("Repository previously constructed, returning cached instance ..") else: logger.debug("Repository not yet constructed, creating new instance ..") loaded_repositories[cache_key] = vcs_type(**kw) return loaded_...
def sum_revision_numbers(arguments): """ Sum revision numbers of multiple repository/revision pairs. :param arguments: A list of strings with repository names and revision strings. :returns: A single integer containing the summed revision numbers. This is useful when you're building a package based on revisions from mu...
def location(self): """The location of the repository that contains :attr:`revision` (a string or :data:`None`).""" location, _, revision = self.expression.partition('#') return location if location and revision else None
def revision(self): """The name of the feature branch (a string).""" location, _, revision = self.expression.partition('#') return revision if location and revision else self.expression
def contains_repository(cls, context, directory): """ Check whether the given directory contains a local repository. :param directory: The pathname of a directory (a string). :returns: :data:`True` if the directory contains a local repository, :data:`False` otherwise. By default :func:`contains_repository()` just check...
def branches(self): """ A dictionary that maps branch names to :class:`Revision` objects. Here's an example based on a mirror of the git project's repository: >>> from pprint import pprint >>> from vcs_repo_mgr.backends.git import GitRepo >>> repository = GitRepo(remote='https://github.com/git/git.git') >>> pprint(repo...
def last_updated(self): """ The date and time when `vcs-repo-mgr` last checked for updates (an integer). Used internally by :func:`pull()` when used in combination with :class:`limit_vcs_updates`. The value is a UNIX time stamp (0 for remote repositories that don't have a local clone yet). """ try: if self.context.exis...
def release_branches(self): """A dictionary that maps branch names to :class:`Release` objects.""" self.ensure_release_scheme('branches') return dict((r.revision.branch, r) for r in self.releases.values())
def release_filter(self, value): """Validate the release filter.""" compiled_pattern = coerce_pattern(value) if compiled_pattern.groups > 1: raise ValueError(compact(""" Release filter regular expression pattern is expected to have zero or one capture group, but it has {count} instead! """, count=compiled_pattern.group...
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, 'release_scheme', value)
def releases(self): r""" A dictionary that maps release identifiers to :class:`Release` objects. Here's an example based on a mirror of the git project's repository which shows the last ten releases based on tags, where each release identifier captures a tag without its 'v' prefix: >>> from pprint import pprint >>> fro...
a capturing group we # set the release identifier to the captured substring # instead of the complete tag/branch identifier. captures = match.groups() if captures: identifier = captures[0] available_releases[identifier] = Release( revision=revision, identifier=identifier, ) return available_releases
def tags(self): """ A dictionary that maps tag names to :class:`Revision` objects. Here's an example based on a mirror of the git project's repository: >>> from pprint import pprint >>> from vcs_repo_mgr.backends.git import GitRepo >>> repository = GitRepo(remote='https://github.com/git/git.git') >>> pprint(repository....
def add_files(self, *filenames, **kw): """ Include added and/or removed files in the working tree in the next commit. :param filenames: The filenames of the files to include in the next commit (zero or more strings). If no arguments are given all untracked files are added. :param kw: Keyword arguments are ignored (inst...
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 changes in the working tree, :data:`False` otherwise. """ # Ma...
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 handling). """ # Make sure the local repository exists and supports a working t...
def create(self): """ Create the local repository (if it doesn't already exist). :returns: :data:`True` if the local repository was just created, :data:`False` if it already existed. What :func:`create()` does depends on the situation: - When :attr:`exists` is :data:`True` nothing is done. - When the :attr:`local` repo...
local %s repository (%s) by cloning %s ..", self.friendly_name, format_path(self.local), self.remote) else: logger.info("Creating local %s repository (%s) ..", self.friendly_name, format_path(self.local)) self.context.execute(*self.get_create_command()) logger.debug("Took %s to %s local %s repository.", timer, "clone" ...
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 commit has been made on the branch. """ # ...
def create_release_branch(self, branch_name): """ Create a new release branch. :param branch_name: The name of the release branch to create (a string). :raises: The following exceptions can be raised: - :exc:`~exceptions.TypeError` when :attr:`release_scheme` isn't set to 'branches'. - :exc:`~exceptions.ValueError` whe...
correct parent release branch. candidates = natsort([r.revision.branch for r in self.ordered_releases] + [branch_name]) index = candidates.index(branch_name) - 1 if index < 0: msg = "Failed to determine suitable parent branch for release branch '%s'!" raise ValueError(msg % branch_name) parent_branch = candidates[index...
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() # Create the new tag in the local repository. logger.inf...
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 commit (a string or :data:`None`, defaults to the string ...
def ensure_clean(self): """ Make sure the working tree is clean (contains no changes to tracked files). :raises: :exc:`~vcs_repo_mgr.exceptions.WorkingTreeNotCleanError` when the working tree contains changes to tracked files. """ if not self.is_clean: raise WorkingTreeNotCleanError(compact(""" The repository's local w...
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 ValueError(msg % (self.friendly_name, format_path(self.local)))
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 string. :raises: :exc:`~exceptions.ValueError`...
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 release scheme. """ if self.release_scheme != expected_...
def ensure_working_tree(self): """ Make sure the local repository has working tree support. :raises: :exc:`~vcs_repo_mgr.exceptions.MissingWorkingTreeError` when the local repository doesn't support a working tree. """ if not self.supports_working_tree: raise MissingWorkingTreeError(compact(""" A working tree is requir...
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`, defaults to :attr:`default_revision`). """ # Make sure we'r...
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 (a string or :data:`None`). :param role: A role that the rem...
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`). :returns: A tuple with two strings: The name of the field a...
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 merge conflicts (and as such the merge error doesn't...
give you a chance to interactively fix the merge conflict(s) in order to avoid propagating the merge error. Please mark or stage your changes but don't commit the result just yet (it will be done for you). """)) while True: if prompt_for_confirmation("Ignore merge error because you've resolved all conflicts?"): if self...
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. This method is used by :func:`merge_up()` to dete...
branch names. return False elif self.release_scheme == 'branches' and branch_name in self.release_branches: # Release branches are not feature branches. return False else: # Other valid branches are considered feature branches. return True
def merge(self, revision=None): """ Merge a revision into the current branch (without committing the result). :param revision: The revision to merge in (a string or :data:`None`, defaults to :attr:`default_revision`). :raises: The following exceptions can be raised: - :exc:`~vcs_repo_mgr.exceptions.MergeConflictError` ...
except ExternalCommandFailed as e: # Check for merge conflicts. conflicts = self.merge_conflicts if conflicts: # Always warn about merge conflicts and log the relevant filenames. explanation = format("Merge failed due to conflicts in %s! (%s)", pluralize(len(conflicts), "file"), concatenate(sorted(conflicts))) logger.w...
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 string or :data:`None`, defaults to :attr:`current_branch...
:func:`merge_up()` and `feature_branch` isn't given then :data:`None` is returned. :raises: The following exceptions can be raised: - :exc:`~exceptions.TypeError` when `target_branch` and :attr:`current_branch` are both :data:`None`. - :exc:`~exceptions.ValueError` when the given target branch doesn't exist (based on :...
Checkout or create the target branch. logger.debug("Checking if target branch exists (%s) ..", target_branch) if target_branch in self.branches: self.checkout(revision=target_branch) # Get the global revision id of the release branch we're about to merge. revision_to_merge = self.find_revision_id(target_branch) elif no...
there's nothing to merge up). if target_branch != self.default_revision: # Find the release branches in the repository. release_branches = [release.revision.branch for release in self.ordered_releases] logger.debug("Found %s: %s", pluralize(len(release_branches), "release branch", "release branches"), concatenate(relea...
if we need to delete or close the feature branch. if delete and feature_branch and self.is_feature_branch(feature_branch.revision): # Delete or close the feature branch. self.delete_branch( branch_name=feature_branch.revision, message="Closing feature branch %s" % feature_branch.revision, ) # Update the working tree to...
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 combination with :class:`limit_vcs_updates` ...
to perform a redundant pull. update_limit = int(os.environ.get(UPDATE_VARIABLE, '0')) if update_limit and self.last_updated >= update_limit: logger.info("Skipping pull due to update limit.") return # Pull the changes from the remote repository. timer = Timer() logger.info("Pulling changes from %s into local %s reposito...
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:: Depending on the version control backend the...
= Timer() logger.info("Pushing changes from %s to %s ..", format_path(self.local), remote or self.remote or "default remote") self.context.execute(*self.get_push_command(remote, revision)) logger.debug("Took %s to push changes to remote repository.", timer)
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 'branches'. """ self.ensure_release_sche...
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 'tags'. """ self.ensure_release_scheme('tags') re...
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 string). :returns: The identifier of the selected release (a string). :raises: :exc:`~vc...
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` will be set to :attr:`local`. This is to ens...
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 this product id :type product_i...
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 :type data: str/bytes :param report_id: The Report ID...
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 default reads are non-blocking, i.e. the method...
-1 if timeout_ms: rv = hidapi.hid_read_timeout(self._device, bufp, length, timeout_ms) else: rv = hidapi.hid_read(self._device, bufp, length) if rv == -1: raise IOError("Failed to read from HID device: {0}" .format(self._get_last_error_string())) elif rv == 0: return None else: return ffi.buffer(bufp, rv)[:]
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, str_p, 255) if rv == -1: raise IOError("Failed to read manufact...
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) if rv == -1: raise IOError("Failed to read product string from HID devi...
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._device, str_p, 255) if rv == -1: raise IOError("Failed to read seri...
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 to send to :type report_id: int """ self._check_device_status() bu...
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_status() bufp = ffi.new("unsigned char[]", length+1) buf = ffi.buffer(bufp, length+1)...
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.new("wchar_t*") rv = hidapi.hid_get_indexed_string(self._device, idx, bufp...
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
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 be removed for rule in file.iter_lines(): raw_rules.append(rule.strip()) # lines +...
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 = AdblockRules(raw_rules) return rules
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, stream=True)) as response: response.raise_for_status() response_url = respon...
def check_color(cls, raw_image): """ Just check if raw_image is completely white. http://stackoverflow.com/questions/14041562/python-pil-detect-if-an-image-is-completely-black-or-white """ # sum(img.convert("L").getextrema()) in (0, 2) extrema = raw_image.convert("L").getextrema() if extrema == (255, 255): # all white ...
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