_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q255800
_add_active_assets
validation
def _add_active_assets(specs): """ This function adds an assets key to the specs, which is filled in with a dictionary of all assets defined by apps and libs in the specs """ specs['assets'] = {} for spec in specs.get_apps_and_libs(): for asset in spec['assets']:
python
{ "resource": "" }
q255801
_get_expanded_active_specs
validation
def _get_expanded_active_specs(specs): """ This function removes any unnecessary bundles, apps, libs, and services that aren't needed by the activated_bundles. It also expands inside specs.apps.depends.libs all libs that are needed indirectly by each app """
python
{ "resource": "" }
q255802
get_repo_of_app_or_library
validation
def get_repo_of_app_or_library(app_or_library_name): """ This function takes an app or library name and will return the corresponding repo for that app or library""" specs = get_specs()
python
{ "resource": "" }
q255803
get_same_container_repos_from_spec
validation
def get_same_container_repos_from_spec(app_or_library_spec): """Given the spec of an app or library, returns all repos that are guaranteed to live in the same container""" repos = set() app_or_lib_repo = get_repo_of_app_or_library(app_or_library_spec.name) if app_or_lib_repo is not None:
python
{ "resource": "" }
q255804
get_same_container_repos
validation
def get_same_container_repos(app_or_library_name): """Given the name of an app or library, returns all repos that are guaranteed to live in the same container""" specs = get_expanded_libs_specs()
python
{ "resource": "" }
q255805
_dusty_hosts_config
validation
def _dusty_hosts_config(hosts_specs): """Return a string of all host rules required to match the given spec. This string is wrapped in the Dusty hosts header and footer so it can be easily removed later."""
python
{ "resource": "" }
q255806
update_hosts_file_from_port_spec
validation
def update_hosts_file_from_port_spec(port_spec): """Given a port spec, update the hosts file specified at constants.HOST_PATH to contain the port mappings specified in the spec. Any existing Dusty configurations are replaced.""" logging.info('Updating hosts file to match port spec') hosts_specs = port_spec['hosts_file']
python
{ "resource": "" }
q255807
_move_temp_binary_to_path
validation
def _move_temp_binary_to_path(tmp_binary_path): """Moves the temporary binary to the location of the binary that's currently being run. Preserves owner, group, and permissions of original binary""" # pylint: disable=E1101 binary_path = _get_binary_location()
python
{ "resource": "" }
q255808
parallel_task_queue
validation
def parallel_task_queue(pool_size=multiprocessing.cpu_count()): """Context manager for setting up a TaskQueue. Upon leaving the context manager, all tasks that were enqueued will be executed in parallel subject to `pool_size`
python
{ "resource": "" }
q255809
_nginx_location_spec
validation
def _nginx_location_spec(port_spec, bridge_ip): """This will output the nginx location config string for specific port spec """ location_string_spec = "\t \t location / { \n" for location_setting in ['proxy_http_version 1.1;', 'proxy_set_header Upgrade $http_upgrade;', 'proxy_set_header Connection "upgrade";', 'proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;',
python
{ "resource": "" }
q255810
_nginx_http_spec
validation
def _nginx_http_spec(port_spec, bridge_ip): """This will output the nginx HTTP config string for specific port spec """ server_string_spec = "\t server {\n" server_string_spec += "\t \t {}\n".format(_nginx_max_file_size_string()) server_string_spec += "\t \t {}\n".format(_nginx_listen_string(port_spec)) server_string_spec += "\t \t {}\n".format(_nginx_server_name_string(port_spec))
python
{ "resource": "" }
q255811
_nginx_stream_spec
validation
def _nginx_stream_spec(port_spec, bridge_ip): """This will output the nginx stream config string for specific port spec """ server_string_spec = "\t server {\n" server_string_spec += "\t \t {}\n".format(_nginx_listen_string(port_spec)) server_string_spec += "\t \t
python
{ "resource": "" }
q255812
get_nginx_configuration_spec
validation
def get_nginx_configuration_spec(port_spec_dict, docker_bridge_ip): """This function will take in a port spec as specified by the port_spec compiler and will output an nginx web proxy config string. This string can then be written to a file and used running nginx """ nginx_http_config, nginx_stream_config = "", "" for port_spec in port_spec_dict['nginx']: if port_spec['type'] == 'http':
python
{ "resource": "" }
q255813
_load_ssh_auth_post_yosemite
validation
def _load_ssh_auth_post_yosemite(mac_username): """Starting with Yosemite, launchd was rearchitected and now only one launchd process runs for all users. This allows us to much more easily impersonate a user through launchd and extract the environment variables from their running processes."""
python
{ "resource": "" }
q255814
_load_ssh_auth_pre_yosemite
validation
def _load_ssh_auth_pre_yosemite(): """For OS X versions before Yosemite, many launchd processes run simultaneously under different users and different permission models. The simpler `asuser` trick we use in Yosemite doesn't work, since it gets routed to the wrong launchd. We instead need to find the running ssh-agent process and use its PID to navigate ourselves to the correct launchd.""" for process in psutil.process_iter(): if process.name() == 'ssh-agent':
python
{ "resource": "" }
q255815
check_and_load_ssh_auth
validation
def check_and_load_ssh_auth(): """ Will check the mac_username config value; if it is present, will load that user's SSH_AUTH_SOCK environment variable to the current environment. This allows git clones to behave the same for the daemon as they do for the user """ mac_username = get_config_value(constants.CONFIG_MAC_USERNAME_KEY) if not mac_username: logging.info("Can't setup ssh authorization; no mac_username specified") return if
python
{ "resource": "" }
q255816
_cleanup_path
validation
def _cleanup_path(path): """Recursively delete a path upon exiting this context manager. Supports targets that are files or directories.""" try: yield finally: if os.path.exists(path):
python
{ "resource": "" }
q255817
copy_between_containers
validation
def copy_between_containers(source_name, source_path, dest_name, dest_path): """Copy a file from the source container to an intermediate staging area on the local filesystem, then from that staging area to the destination container. These moves take place without demotion for two reasons: 1. There should be no permissions vulnerabilities with copying between containers because it is assumed the non-privileged user has full access to all Dusty containers. 2. The temp dir created by mkdtemp is owned by the owner of the Dusty daemon process, so if we demoted our moves to/from that location they would encounter permission errors.""" if
python
{ "resource": "" }
q255818
copy_from_local
validation
def copy_from_local(local_path, remote_name, remote_path, demote=True): """Copy a path from the local filesystem to a path inside a Dusty container. The files on the local filesystem must be accessible by the user specified in mac_username.""" if not os.path.exists(local_path): raise RuntimeError('ERROR: Path {} does not exist'.format(local_path))
python
{ "resource": "" }
q255819
copy_to_local
validation
def copy_to_local(local_path, remote_name, remote_path, demote=True): """Copy a path from inside a Dusty container to a path on the local filesystem. The path on the local filesystem must be wrist-accessible by the user specified in mac_username.""" if not container_path_exists(remote_name, remote_path):
python
{ "resource": "" }
q255820
_mount_repo
validation
def _mount_repo(repo, wait_for_server=False): """ This function will create the VM directory where a repo will be mounted, if it doesn't exist. If wait_for_server is set, it will wait up to 10 seconds for the nfs server to start, by retrying mounts that fail with 'Connection Refused'. If wait_for_server is not set, it will attempt to run the mount command once """ check_call_on_vm('sudo mkdir -p {}'.format(repo.vm_path)) if wait_for_server:
python
{ "resource": "" }
q255821
get_port_spec_document
validation
def get_port_spec_document(expanded_active_specs, docker_vm_ip): """ Given a dictionary containing the expanded dusty DAG specs this function will return a dictionary containing the port mappings needed by downstream methods. Currently this includes docker_compose, virtualbox, nginx and hosts_file.""" forwarding_port = 65000 port_spec = {'docker_compose':{}, 'nginx':[], 'hosts_file':[]} host_full_addresses, host_names, stream_host_ports = set(), set(), set() # No matter the order of apps in expanded_active_specs, we want to produce a consistent # port_spec with respect to the apps and the ports they are outputted on for app_name in sorted(expanded_active_specs['apps'].keys()): app_spec = expanded_active_specs['apps'][app_name] if 'host_forwarding' not in app_spec: continue port_spec['docker_compose'][app_name] = [] for host_forwarding_spec in app_spec['host_forwarding']:
python
{ "resource": "" }
q255822
init_yaml_constructor
validation
def init_yaml_constructor(): """ This dark magic is used to make yaml.safe_load encode all strings as utf-8, where otherwise python unicode strings would be returned for non-ascii chars """ def utf_encoding_string_constructor(loader, node):
python
{ "resource": "" }
q255823
registry_from_image
validation
def registry_from_image(image_name): """Returns the Docker registry host associated with a given image name.""" if '/' not in image_name: # official image return constants.PUBLIC_DOCKER_REGISTRY prefix = image_name.split('/')[0]
python
{ "resource": "" }
q255824
get_authed_registries
validation
def get_authed_registries(): """Reads the local Docker client config for the current user and returns all registries to which the user may be logged in. This is intended to be run client-side, not by the daemon.""" result = set() if not os.path.exists(constants.DOCKER_CONFIG_PATH): return result config = json.load(open(constants.DOCKER_CONFIG_PATH, 'r')) for registry in config.get('auths', {}).iterkeys(): try: parsed = urlparse(registry) except Exception: log_to_client('Error parsing registry {} from Docker config, will skip this registry').format(registry) # This logic assumes the auth is either
python
{ "resource": "" }
q255825
streaming_to_client
validation
def streaming_to_client(): """Puts the client logger into streaming mode, which sends unbuffered input through to the socket one character at a time. We also disable propagation so the root logger does not receive many one-byte emissions. This context handler was originally created for streaming Compose up's terminal output through to the client and should only be used for similarly complex circumstances.""" for handler in client_logger.handlers: if hasattr(handler, 'append_newlines'): break else: handler = None old_propagate = client_logger.propagate
python
{ "resource": "" }
q255826
pty_fork
validation
def pty_fork(*args): """Runs a subprocess with a PTY attached via fork and exec. The output from the PTY is streamed through log_to_client. This should not be necessary for most subprocesses, we built this to handle Compose up which only streams pull progress if it is attached to a TTY.""" updated_env = copy(os.environ) updated_env.update(get_docker_env()) args += (updated_env,) executable = args[0]
python
{ "resource": "" }
q255827
_compile_docker_commands
validation
def _compile_docker_commands(app_name, assembled_specs, port_spec): """ This is used to compile the command that will be run when the docker container starts up. This command has to install any libs that the app uses, run the `always` command, and run the `once` command if the container is being launched for the first time """ app_spec = assembled_specs['apps'][app_name] commands = ['set -e'] commands += _lib_install_commands_for_app(app_name, assembled_specs) if app_spec['mount']: commands.append("cd {}".format(container_code_path(app_spec)))
python
{ "resource": "" }
q255828
_increase_file_handle_limit
validation
def _increase_file_handle_limit(): """Raise the open file handles permitted by the Dusty daemon process and its child processes. The number we choose here needs to be within the OS X default kernel hard limit, which is 10240.""" logging.info('Increasing
python
{ "resource": "" }
q255829
_start_http_server
validation
def _start_http_server(): """Start the daemon's HTTP server on a separate thread. This server is only used for servicing container status requests from Dusty's custom 502 page.""" logging.info('Starting HTTP server at {}:{}'.format(constants.DAEMON_HTTP_BIND_IP,
python
{ "resource": "" }
q255830
get_docker_client
validation
def get_docker_client(): """Ripped off and slightly modified based on docker-py's kwargs_from_env utility function.""" env = get_docker_env() host, cert_path, tls_verify = env['DOCKER_HOST'], env['DOCKER_CERT_PATH'], env['DOCKER_TLS_VERIFY'] params = {'base_url': host.replace('tcp://', 'https://'), 'timeout': None, 'version': 'auto'} if tls_verify and cert_path: params['tls'] = docker.tls.TLSConfig( client_cert=(os.path.join(cert_path, 'cert.pem'),
python
{ "resource": "" }
q255831
get_dusty_containers
validation
def get_dusty_containers(services, include_exited=False): """Get a list of containers associated with the list of services. If no services are provided, attempts to return all containers associated with Dusty.""" client = get_docker_client() if services:
python
{ "resource": "" }
q255832
configure_nfs_server
validation
def configure_nfs_server(): """ This function is used with `dusty up`. It will check all active repos to see if they are exported. If any are missing, it will replace current dusty exports with exports that are needed for currently active repos, and restart the nfs server
python
{ "resource": "" }
q255833
_ensure_managed_repos_dir_exists
validation
def _ensure_managed_repos_dir_exists(): """ Our exports file will be invalid if this folder doesn't exist, and the NFS server will not run correctly. """
python
{ "resource": "" }
q255834
register_consumer
validation
def register_consumer(): """Given a hostname and port attempting to be accessed, return a unique consumer ID for accessing logs from the referenced container.""" global _consumers hostname, port = request.form['hostname'], request.form['port'] app_name = _app_name_from_forwarding_info(hostname, port) containers = get_dusty_containers([app_name], include_exited=True) if not containers: raise ValueError('No container exists for app {}'.format(app_name)) container = containers[0] new_id
python
{ "resource": "" }
q255835
consume
validation
def consume(consumer_id): """Given an existing consumer ID, return any new lines from the log since the last time the consumer was consumed.""" global _consumers consumer = _consumers[consumer_id] client = get_docker_client() try: status = client.inspect_container(consumer.container_id)['State']['Status'] except Exception as e: status = 'unknown' new_logs = client.logs(consumer.container_id, stdout=True, stderr=True, stream=False, timestamps=False, since=calendar.timegm(consumer.offset.timetuple()))
python
{ "resource": "" }
q255836
get_app_volume_mounts
validation
def get_app_volume_mounts(app_name, assembled_specs, test=False): """ This returns a list of formatted volume specs for an app. These mounts declared in the apps' spec and mounts declared in all lib specs the app depends on""" app_spec = assembled_specs['apps'][app_name] volumes = [get_command_files_volume_mount(app_name, test=test)] volumes.append(get_asset_volume_mount(app_name))
python
{ "resource": "" }
q255837
get_lib_volume_mounts
validation
def get_lib_volume_mounts(base_lib_name, assembled_specs): """ Returns a list of the formatted volume specs for a lib""" volumes = [_get_lib_repo_volume_mount(assembled_specs['libs'][base_lib_name])] volumes.append(get_command_files_volume_mount(base_lib_name, test=True))
python
{ "resource": "" }
q255838
_get_app_libs_volume_mounts
validation
def _get_app_libs_volume_mounts(app_name, assembled_specs): """ Returns a list of the formatted volume mounts for all libs that an app uses """ volumes = [] for lib_name in assembled_specs['apps'][app_name]['depends']['libs']: lib_spec =
python
{ "resource": "" }
q255839
_dusty_vm_exists
validation
def _dusty_vm_exists(): """We use VBox directly instead of Docker Machine because it shaves about 0.5 seconds off the runtime of this check."""
python
{ "resource": "" }
q255840
_init_docker_vm
validation
def _init_docker_vm(): """Initialize the Dusty VM if it does not already exist.""" if not _dusty_vm_exists(): log_to_client('Initializing new Dusty VM with Docker Machine') machine_options = ['--driver', 'virtualbox', '--virtualbox-cpu-count', '-1', '--virtualbox-boot2docker-url', constants.CONFIG_BOOT2DOCKER_URL, '--virtualbox-memory', str(get_config_value(constants.CONFIG_VM_MEM_SIZE)),
python
{ "resource": "" }
q255841
_start_docker_vm
validation
def _start_docker_vm(): """Start the Dusty VM if it is not already running.""" is_running = docker_vm_is_running() if not is_running: log_to_client('Starting docker-machine VM {}'.format(constants.VM_MACHINE_NAME)) _apply_nat_dns_host_resolver()
python
{ "resource": "" }
q255842
docker_vm_is_running
validation
def docker_vm_is_running(): """Using VBoxManage is 0.5 seconds or so faster than Machine.""" running_vms = check_output_demoted(['VBoxManage', 'list',
python
{ "resource": "" }
q255843
_get_localhost_ssh_port
validation
def _get_localhost_ssh_port(): """Something in the VM chain, either VirtualBox or Machine, helpfully sets up localhost-to-VM forwarding on port 22. We can inspect this rule to determine the port on localhost which gets forwarded to 22 in the VM.""" for line in _get_vm_config(): if line.startswith('Forwarding'): spec = line.split('=')[1].strip('"')
python
{ "resource": "" }
q255844
_get_host_only_mac_address
validation
def _get_host_only_mac_address(): """Returns the MAC address assigned to the host-only adapter, using output from VBoxManage. Returned MAC address has no colons and is lower-cased.""" # Get the number of the host-only adapter vm_config = _get_vm_config() for line in vm_config:
python
{ "resource": "" }
q255845
_ip_for_mac_from_ip_addr_show
validation
def _ip_for_mac_from_ip_addr_show(ip_addr_show, target_mac): """Given the rather-complex output from an 'ip addr show' command on the VM, parse the output to determine the IP address assigned to the interface with the given MAC.""" return_next_ip = False for line in ip_addr_show.splitlines(): line = line.strip() if line.startswith('link/ether'):
python
{ "resource": "" }
q255846
_get_host_only_ip
validation
def _get_host_only_ip(): """Determine the host-only IP of the Dusty VM through Virtualbox and SSH directly, bypassing Docker Machine. We do this because Docker Machine is much slower, taking about 600ms total. We are basically doing the same flow Docker Machine does in its own code."""
python
{ "resource": "" }
q255847
create_local_copy
validation
def create_local_copy(cookie_file): """Make a local copy of the sqlite cookie database and return the new filename. This is necessary in case this database is still being written to while the user browses to avoid sqlite locking errors. """ # if type of cookie_file is a list, use the first element in the list
python
{ "resource": "" }
q255848
create_cookie
validation
def create_cookie(host, path, secure, expires, name, value): """Shortcut function to create a cookie """ return
python
{ "resource": "" }
q255849
load
validation
def load(domain_name=""): """Try to load cookies from all supported browsers and return combined cookiejar Optionally pass in a domain name to only load cookies from the specified domain """ cj = http.cookiejar.CookieJar() for cookie_fn in [chrome, firefox]: try:
python
{ "resource": "" }
q255850
Chrome.load
validation
def load(self): """Load sqlite cookies into a cookiejar """ con = sqlite3.connect(self.tmp_cookie_file) cur = con.cursor() try: # chrome <=55 cur.execute('SELECT host_key, path, secure, expires_utc, name, value, encrypted_value ' 'FROM cookies WHERE host_key like "%{}%";'.format(self.domain_name)) except sqlite3.OperationalError: # chrome >=56 cur.execute('SELECT host_key, path, is_secure, expires_utc, name, value, encrypted_value ' 'FROM cookies WHERE host_key like "%{}%";'.format(self.domain_name))
python
{ "resource": "" }
q255851
Chrome._decrypt
validation
def _decrypt(self, value, encrypted_value): """Decrypt encoded cookies """ if sys.platform == 'win32': return self._decrypt_windows_chrome(value, encrypted_value) if value or (encrypted_value[:3] != b'v10'): return value # Encrypted cookies should be prefixed with 'v10' according to the # Chromium code. Strip it off. encrypted_value = encrypted_value[3:]
python
{ "resource": "" }
q255852
_randone
validation
def _randone(d, limit=20, grouprefs=None): if grouprefs is None: grouprefs = {} """docstring for _randone""" ret = '' for i in d: if i[0] == sre_parse.IN: ret += choice(_in(i[1])) elif i[0] == sre_parse.LITERAL: ret += unichr(i[1]) elif i[0] == sre_parse.CATEGORY: ret += choice(CATEGORIES.get(i[1], [''])) elif i[0] == sre_parse.ANY: ret += choice(CATEGORIES['category_any']) elif i[0] == sre_parse.MAX_REPEAT or i[0] == sre_parse.MIN_REPEAT: if i[1][1] + 1 - i[1][0] >= limit: min, max = i[1][0], i[1][0] + limit - 1 else: min, max = i[1][0], i[1][1] for _ in range(randint(min, max)): ret += _randone(list(i[1][2]), limit, grouprefs) elif i[0] == sre_parse.BRANCH: ret += _randone(choice(i[1][1]), limit, grouprefs) elif i[0] == sre_parse.SUBPATTERN or i[0] == sre_parse.ASSERT: subexpr = i[1][1] if IS_PY36_OR_GREATER and i[0] == sre_parse.SUBPATTERN: subexpr = i[1][3]
python
{ "resource": "" }
q255853
parse
validation
def parse(s): """Regular expression parser :param s: Regular expression :type s: str :rtype: list """ if IS_PY3:
python
{ "resource": "" }
q255854
ib64_patched
validation
def ib64_patched(self, attrsD, contentparams): """ Patch isBase64 to prevent Base64 encoding of JSON content """ if attrsD.get("mode", "") == "base64": return 0 if self.contentparams["type"].startswith("text/"):
python
{ "resource": "" }
q255855
cleanwrap
validation
def cleanwrap(func): """ Wrapper for Zotero._cleanup """ def enc(self, *args, **kwargs): """ Send each item to _cleanup() """
python
{ "resource": "" }
q255856
ss_wrap
validation
def ss_wrap(func): """ ensure that a SavedSearch object exists """ def wrapper(self, *args, **kwargs): if not self.savedsearch:
python
{ "resource": "" }
q255857
error_handler
validation
def error_handler(req): """ Error handler for HTTP requests """ error_codes = { 400: ze.UnsupportedParams, 401: ze.UserNotAuthorised, 403: ze.UserNotAuthorised, 404: ze.ResourceNotFound, 409: ze.Conflict, 412: ze.PreConditionFailed, 413: ze.RequestEntityTooLarge, 428: ze.PreConditionRequired, 429: ze.TooManyRequests, } def err_msg(req): """ Return a nicely-formatted error message """ return "\nCode: %s\nURL: %s\nMethod: %s\nResponse: %s" % ( req.status_code, # error.msg, req.url, req.request.method, req.text, ) if error_codes.get(req.status_code): # check to see whether its 429 if req.status_code == 429: # call our back-off function delay = backoff.delay if delay > 32: # we've waited a total of 62 seconds (2 + 4 … + 32), so give up
python
{ "resource": "" }
q255858
Zotero.default_headers
validation
def default_headers(self): """ It's always OK to include these headers """ _headers = { "User-Agent": "Pyzotero/%s" % __version__, "Zotero-API-Version": "%s" % __api_version__, }
python
{ "resource": "" }
q255859
Zotero._cache
validation
def _cache(self, response, key): """ Add a retrieved template to the cache for 304 checking accepts a dict and key name, adds the retrieval time, and adds both to self.templates as a new dict using the specified key """ # cache template and retrieval time for subsequent calls
python
{ "resource": "" }
q255860
Zotero._cleanup
validation
def _cleanup(self, to_clean, allow=()): """ Remove keys we added for internal use """ # this item's been retrieved from the API, we only need the 'data' # entry if to_clean.keys() == ["links", "library", "version", "meta", "key", "data"]: to_clean = to_clean["data"] return dict(
python
{ "resource": "" }
q255861
Zotero._retrieve_data
validation
def _retrieve_data(self, request=None): """ Retrieve Zotero items via the API Combine endpoint and request to access the specific resource Returns a JSON document """ full_url = "%s%s" % (self.endpoint, request) # The API doesn't return this any more, so we have to cheat self.self_link = request
python
{ "resource": "" }
q255862
Zotero._extract_links
validation
def _extract_links(self): """ Extract self, first, next, last links from a request response """ extracted = dict() try: for key, value in self.request.links.items(): parsed = urlparse(value["url"]) fragment = "{path}?{query}".format(path=parsed[2], query=parsed[4]) extracted[key] = fragment # add a 'self' link parsed = list(urlparse(self.self_link)) # strip 'format' query parameter stripped = "&".join( [ "%s=%s" % (p[0], p[1]) for p in parse_qsl(parsed[4]) if p[0] != "format" ]
python
{ "resource": "" }
q255863
Zotero._build_query
validation
def _build_query(self, query_string, no_params=False): """ Set request parameters. Will always add the user ID if it hasn't been specifically set by an API method """ try: query = quote(query_string.format(u=self.library_id, t=self.library_type)) except KeyError as err: raise ze.ParamNotPassed("There's a request parameter missing: %s" % err)
python
{ "resource": "" }
q255864
Zotero.publications
validation
def publications(self): """ Return the contents of My Publications """ if self.library_type != "users": raise ze.CallDoesNotExist( "This API call does not exist for group libraries"
python
{ "resource": "" }
q255865
Zotero.num_collectionitems
validation
def num_collectionitems(self, collection): """ Return the total number of items in the specified collection """ query = "/{t}/{u}/collections/{c}/items".format(
python
{ "resource": "" }
q255866
Zotero.num_tagitems
validation
def num_tagitems(self, tag): """ Return the total number of items for the specified tag """ query = "/{t}/{u}/tags/{ta}/items".format(
python
{ "resource": "" }
q255867
Zotero._totals
validation
def _totals(self, query): """ General method for returning total counts """ self.add_parameters(limit=1) query = self._build_query(query) self._retrieve_data(query)
python
{ "resource": "" }
q255868
Zotero.key_info
validation
def key_info(self, **kwargs): """ Retrieve info about the permissions associated with the key associated to the given Zotero instance
python
{ "resource": "" }
q255869
Zotero.fulltext_item
validation
def fulltext_item(self, itemkey, **kwargs): """ Get full-text content for an item""" query_string =
python
{ "resource": "" }
q255870
Zotero.last_modified_version
validation
def last_modified_version(self, **kwargs): """ Get the last modified version """ self.items(**kwargs)
python
{ "resource": "" }
q255871
Zotero.file
validation
def file(self, item, **kwargs): """ Get the file from an specific item """ query_string = "/{t}/{u}/items/{i}/file".format(
python
{ "resource": "" }
q255872
Zotero.dump
validation
def dump(self, itemkey, filename=None, path=None): """ Dump a file attachment to disk, with optional filename and path """ if not filename: filename = self.item(itemkey)["data"]["filename"] if path: pth = os.path.join(path, filename) else:
python
{ "resource": "" }
q255873
Zotero.all_collections
validation
def all_collections(self, collid=None): """ Retrieve all collections and subcollections. Works for top-level collections or for a specific collection. Works at all collection depths. """ all_collections = [] def subcoll(clct): """ recursively add collections to a flat master list """ all_collections.append(clct) if clct["meta"].get("numCollections", 0) > 0:
python
{ "resource": "" }
q255874
Zotero.collections_sub
validation
def collections_sub(self, collection, **kwargs): """ Get subcollections for a specific collection """ query_string =
python
{ "resource": "" }
q255875
Zotero.everything
validation
def everything(self, query): """ Retrieve all items in the library for a particular query This method will override the 'limit' parameter if it's been set """ try: items = []
python
{ "resource": "" }
q255876
Zotero._json_processor
validation
def _json_processor(self, retrieved): """ Format and return data from API calls which return Items """ json_kwargs = {} if self.preserve_json_order: json_kwargs["object_pairs_hook"] = OrderedDict # send entries to _tags_data if there's no JSON try:
python
{ "resource": "" }
q255877
Zotero._csljson_processor
validation
def _csljson_processor(self, retrieved): """ Return a list of dicts which are dumped CSL JSON """ items = [] json_kwargs = {} if self.preserve_json_order:
python
{ "resource": "" }
q255878
Zotero._bib_processor
validation
def _bib_processor(self, retrieved): """ Return a list of strings formatted as HTML bibliography entries """ items = [] for bib in retrieved.entries:
python
{ "resource": "" }
q255879
Zotero._citation_processor
validation
def _citation_processor(self, retrieved): """ Return a list of strings formatted as HTML citation entries """ items = [] for cit in retrieved.entries:
python
{ "resource": "" }
q255880
Zotero.item_template
validation
def item_template(self, itemtype): """ Get a template for a new item """ # if we have a template and it hasn't been updated since we stored it template_name = "item_template_" + itemtype query_string = "/items/new?itemType={i}".format(i=itemtype) if self.templates.get(template_name) and not self._updated( query_string, self.templates[template_name], template_name
python
{ "resource": "" }
q255881
Zotero._attachment
validation
def _attachment(self, payload, parentid=None): """ Create attachments accepts a list of one or more attachment template dicts and an optional parent Item ID. If this is specified, attachments are created under this ID
python
{ "resource": "" }
q255882
Zotero.show_condition_operators
validation
def show_condition_operators(self, condition): """ Show available operators for a given saved search condition """ # dict keys of allowed operators for the current condition permitted_operators = self.savedsearch.conditions_operators.get(condition) #
python
{ "resource": "" }
q255883
Zotero.delete_saved_search
validation
def delete_saved_search(self, keys): """ Delete one or more saved searches by passing a list of one or more unique search keys """ headers = {"Zotero-Write-Token": token()} headers.update(self.default_headers()) req = requests.delete( url=self.endpoint + "/{t}/{u}/searches".format(t=self.library_type, u=self.library_id),
python
{ "resource": "" }
q255884
Zotero.add_tags
validation
def add_tags(self, item, *tags): """ Add one or more tags to a retrieved item, then update it on the server Accepts a dict, and one or more tags to add to it Returns the updated item from the server """ # Make sure there's a tags field, or add one try: assert item["data"]["tags"] except AssertionError: item["data"]["tags"] = list()
python
{ "resource": "" }
q255885
Zotero.fields_types
validation
def fields_types(self, tname, qstring, itemtype): """ Retrieve item fields or creator types """ # check for a valid cached version template_name = tname + itemtype query_string = qstring.format(i=itemtype) if self.templates.get(template_name) and not self._updated( query_string, self.templates[template_name], template_name ):
python
{ "resource": "" }
q255886
Zotero.item_fields
validation
def item_fields(self): """ Get all available item fields """ # Check for a valid cached version if self.templates.get("item_fields") and not self._updated( "/itemFields", self.templates["item_fields"], "item_fields" ): return self.templates["item_fields"]["tmplt"] query_string = "/itemFields"
python
{ "resource": "" }
q255887
Zotero.update_item
validation
def update_item(self, payload, last_modified=None): """ Update an existing item Accepts one argument, a dict containing Item data """ to_send = self.check_items([payload])[0] if last_modified is None: modified = payload["version"] else: modified = last_modified ident = payload["key"] headers = {"If-Unmodified-Since-Version": str(modified)} headers.update(self.default_headers()) req = requests.patch( url=self.endpoint + "/{t}/{u}/items/{id}".format(
python
{ "resource": "" }
q255888
Zotero.update_items
validation
def update_items(self, payload): """ Update existing items Accepts one argument, a list of dicts containing Item data """ to_send = [self.check_items([p])[0] for p in payload] headers = {} headers.update(self.default_headers()) # the API only accepts 50 items at a time, so we have to split # anything longer for chunk in chunks(to_send, 50): req = requests.post( url=self.endpoint
python
{ "resource": "" }
q255889
SavedSearch._validate
validation
def _validate(self, conditions): """ Validate saved search conditions, raising an error if any contain invalid operators """ allowed_keys = set(self.searchkeys) operators_set = set(self.operators.keys()) for condition in conditions: if set(condition.keys()) != allowed_keys: raise ze.ParamNotPassed( "Keys must be all of: %s" % ", ".join(self.searchkeys) ) if condition.get("operator") not in operators_set: raise ze.ParamNotPassed( "You have specified an unknown operator: %s" % condition.get("operator") ) # dict keys of allowed operators for the current condition permitted_operators = self.conditions_operators.get( condition.get("condition") ) # transform these into values permitted_operators_list = set(
python
{ "resource": "" }
q255890
Zupload.upload
validation
def upload(self): """ File upload functionality Goes through upload steps 0 - 3 (private class methods), and returns a dict noting success, failure, or unchanged (returning the payload entries with that property as a list for each status) """ result = {"success": [], "failure": [], "unchanged": []} self._create_prelim() for item in self.payload: if "key" not in item: result["failure"].append(item) continue
python
{ "resource": "" }
q255891
split_multiline
validation
def split_multiline(value): """Split a multiline string into a list, excluding blank lines.""" return [element for
python
{ "resource": "" }
q255892
split_elements
validation
def split_elements(value): """Split a string with comma or space-separated elements into a
python
{ "resource": "" }
q255893
eval_environ
validation
def eval_environ(value): """Evaluate environment markers.""" def eval_environ_str(value): parts = value.split(';') if len(parts) < 2: return value expr = parts[1].lstrip() if not re.match("^((\\w+(\\.\\w+)?|'.*?'|\".*?\")\\s+" '(in|==|!=|not in)\\s+' "(\\w+(\\.\\w+)?|'.*?'|\".*?\")" '(\\s+(or|and)\\s+)?)+$', expr): raise ValueError('bad environment marker: %r' % expr) expr = re.sub(r"(platform\.\w+)", r"\1()", expr) return parts[0] if eval(expr) else ''
python
{ "resource": "" }
q255894
get_cfg_value
validation
def get_cfg_value(config, section, option): """Get configuration value.""" try: value = config[section][option] except KeyError: if (section, option) in MULTI_OPTIONS: return [] else:
python
{ "resource": "" }
q255895
set_cfg_value
validation
def set_cfg_value(config, section, option, value): """Set configuration value."""
python
{ "resource": "" }
q255896
cfg_to_args
validation
def cfg_to_args(config): """Compatibility helper to use setup.cfg in setup.py.""" kwargs = {} opts_to_args = { 'metadata': [ ('name', 'name'), ('author', 'author'), ('author-email', 'author_email'), ('maintainer', 'maintainer'), ('maintainer-email', 'maintainer_email'), ('home-page', 'url'), ('summary', 'description'), ('description', 'long_description'), ('download-url', 'download_url'), ('classifier', 'classifiers'), ('platform', 'platforms'), ('license', 'license'), ('keywords', 'keywords'), ], 'files': [ ('packages_root', 'package_dir'), ('packages', 'packages'), ('modules', 'py_modules'), ('scripts', 'scripts'), ('package_data', 'package_data'), ('data_files', 'data_files'), ], } opts_to_args['metadata'].append(('requires-dist', 'install_requires')) if IS_PY2K and not which('3to2'): kwargs['setup_requires'] = ['3to2'] kwargs['zip_safe'] = False for section in opts_to_args: for option, argname in opts_to_args[section]: value = get_cfg_value(config, section, option)
python
{ "resource": "" }
q255897
run_3to2
validation
def run_3to2(args=None): """Convert Python files using lib3to2.""" args = BASE_ARGS_3TO2 if args is None else BASE_ARGS_3TO2 + args try: proc = subprocess.Popen(['3to2'] + args, stderr=subprocess.PIPE) except OSError: for path in glob.glob('*.egg'): if os.path.isdir(path) and path not in sys.path: sys.path.append(path) try: from lib3to2.main import main as lib3to2_main except ImportError: raise OSError('3to2 script is unavailable.') else: if lib3to2_main('lib3to2.fixes', args): raise Exception('lib3to2
python
{ "resource": "" }
q255898
write_py2k_header
validation
def write_py2k_header(file_list): """Write Python 2 shebang and add encoding cookie if needed.""" if not isinstance(file_list, list): file_list = [file_list] python_re = re.compile(br"^(#!.*\bpython)(.*)([\r\n]+)$") coding_re = re.compile(br"coding[:=]\s*([-\w.]+)") new_line_re = re.compile(br"([\r\n]+)$") version_3 = LooseVersion('3') for file in file_list: if not os.path.getsize(file): continue rewrite_needed = False python_found = False coding_found = False lines = [] f = open(file, 'rb') try: while len(lines) < 2: line = f.readline() match = python_re.match(line) if match: python_found = True version = LooseVersion(match.group(2).decode() or '2') try: version_test = version >= version_3 except TypeError: version_test = True if version_test: line = python_re.sub(br"\g<1>2\g<3>", line) rewrite_needed = True elif coding_re.search(line): coding_found = True lines.append(line)
python
{ "resource": "" }
q255899
get_version
validation
def get_version(): """Get LanguageTool version.""" version = _get_attrib().get('version') if not version:
python
{ "resource": "" }