Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def token_perplexity_micro(eval_data, predictions, scores, learner='ignored'): ''' Return the micro-averaged per-token perplexity `exp(-score / num_tokens)` computed over the entire corpus, as a length-1 list of floats. The log scores in `scores` should be ba...
[]
Please provide a description of the function:def aic(eval_data, predictions, scores, learner): ''' Return Akaike information criterion (AIC) scores for the given `learner` producing the given `scores` (log likelihoods in base e): aic = 2 * learner.num_params - 2 * sum(log_2(exp(scores))) The r...
[]
Please provide a description of the function:def aic_averaged(eval_data, predictions, scores, learner): ''' Return Akaike information criterion (AIC) scores for the given `learner` producing the given `scores` (log likelihoods in base e): aic = 2 * learner.num_params - 2 * sum(log_2(exp(scores))) ...
[]
Please provide a description of the function:def encrypt_variable(variable, build_repo, *, tld='.org', public_key=None, travis_token=None, **login_kwargs): if not isinstance(variable, bytes): raise TypeError("variable should be bytes") if not b"=" in variable: raise ValueError("variabl...
[ "\n Encrypt an environment variable for ``build_repo`` for Travis\n\n ``variable`` should be a bytes object, of the form ``b'ENV=value'``.\n\n ``build_repo`` is the repo that ``doctr deploy`` will be run from. It\n should be like 'drdoctr/doctr'.\n\n ``tld`` should be ``'.org'`` for travis-ci.org and...
Please provide a description of the function:def encrypt_to_file(contents, filename): if not filename.endswith('.enc'): raise ValueError("%s does not end with .enc" % filename) key = Fernet.generate_key() fer = Fernet(key) encrypted_file = fer.encrypt(contents) with open(filename, 'w...
[ "\n Encrypts ``contents`` and writes it to ``filename``.\n\n ``contents`` should be a bytes string. ``filename`` should end with\n ``.enc``.\n\n Returns the secret key used for the encryption.\n\n Decrypt the file with :func:`doctr.travis.decrypt_file`.\n\n " ]
Please provide a description of the function:def GitHub_login(*, username=None, password=None, OTP=None, headers=None): if not username: username = input("What is your GitHub username? ") if not password: password = getpass("Enter the GitHub password for {username}: ".format(username=usern...
[ "\n Login to GitHub.\n\n If no username, password, or OTP (2-factor authentication code) are\n provided, they will be requested from the command line.\n\n Returns a dict of kwargs that can be passed to functions that require\n authenticated connections to GitHub.\n " ]
Please provide a description of the function:def GitHub_raise_for_status(r): # This will happen if the doctr session has been running too long and the # OTP code gathered from GitHub_login has expired. # TODO: Refactor the code to re-request the OTP without exiting. if r.status_code == 401 and r.h...
[ "\n Call instead of r.raise_for_status() for GitHub requests\n\n Checks for common GitHub response issues and prints messages for them.\n ", "\\\nYour GitHub API rate limit has been hit. GitHub allows {limit} {un}authenticated\nrequests per hour. See {documentation_url}\nfor more information.\n", "\nNo...
Please provide a description of the function:def GitHub_post(data, url, *, auth, headers): r = requests.post(url, auth=auth, headers=headers, data=json.dumps(data)) GitHub_raise_for_status(r) return r.json()
[ "\n POST the data ``data`` to GitHub.\n\n Returns the json response from the server, or raises on error status.\n\n " ]
Please provide a description of the function:def get_travis_token(*, GitHub_token=None, **login_kwargs): _headers = { 'Content-Type': 'application/json', 'User-Agent': 'MyClient/1.0.0', } headersv2 = {**_headers, **Travis_APIv2} token_id = None try: if not GitHub_token: ...
[ "\n Generate a temporary token for authenticating with Travis\n\n The GitHub token can be passed in to the ``GitHub_token`` keyword\n argument. If no token is passed in, a GitHub token is generated\n temporarily, and then immediately deleted.\n\n This is needed to activate a private repo\n\n Retur...
Please provide a description of the function:def generate_GitHub_token(*, note="Doctr token for pushing to gh-pages from Travis", scopes=None, **login_kwargs): if scopes is None: scopes = ['public_repo'] AUTH_URL = "https://api.github.com/authorizations" data = { "scopes": scopes, ...
[ "\n Generate a GitHub token for pushing from Travis\n\n The scope requested is public_repo.\n\n If no password or OTP are provided, they will be requested from the\n command line.\n\n The token created here can be revoked at\n https://github.com/settings/tokens.\n " ]
Please provide a description of the function:def delete_GitHub_token(token_id, *, auth, headers): r = requests.delete('https://api.github.com/authorizations/{id}'.format(id=token_id), auth=auth, headers=headers) GitHub_raise_for_status(r)
[ "Delete a temporary GitHub token" ]
Please provide a description of the function:def upload_GitHub_deploy_key(deploy_repo, ssh_key, *, read_only=False, title="Doctr deploy key for pushing to gh-pages from Travis", **login_kwargs): DEPLOY_KEY_URL = "https://api.github.com/repos/{deploy_repo}/keys".format(deploy_repo=deploy_repo) data = {...
[ "\n Uploads a GitHub deploy key to ``deploy_repo``.\n\n If ``read_only=True``, the deploy_key will not be able to write to the\n repo.\n " ]
Please provide a description of the function:def generate_ssh_key(): key = rsa.generate_private_key( backend=default_backend(), public_exponent=65537, key_size=4096 ) private_key = key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.PK...
[ "\n Generates an SSH deploy public and private key.\n\n Returns (private key, public key), a tuple of byte strings.\n " ]
Please provide a description of the function:def check_repo_exists(deploy_repo, service='github', *, auth=None, headers=None, ask=False): headers = headers or {} if deploy_repo.count("/") != 1: raise RuntimeError('"{deploy_repo}" should be in the form username/repo'.format(deploy_repo=deploy_re...
[ "\n Checks that the repository exists on GitHub.\n\n This should be done before attempting generate a key to deploy to that\n repo.\n\n Raises ``RuntimeError`` if the repo is not valid.\n\n Returns a dictionary with the following keys:\n\n - 'private': Indicates whether or not the repo requires au...
Please provide a description of the function:def guess_github_repo(): p = subprocess.run(['git', 'ls-remote', '--get-url', 'origin'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) if p.stderr or p.returncode: return False url = p.stdout.decode('utf-8').strip() m = GI...
[ "\n Guesses the github repo for the current directory\n\n Returns False if no guess can be made.\n " ]
Please provide a description of the function:def make_parser_with_config_adder(parser, config): def internal(arg, **kwargs): invert = { 'store_true':'store_false', 'store_false':'store_true', } if arg.startswith('--no-'): key = arg[5:] else: ...
[ "factory function for a smarter parser:\n\n return an utility function that pull default from the config as well.\n\n Pull the default for parser not only from the ``default`` kwarg,\n but also if an identical value is find in ``config`` where leading\n ``--`` or ``--no`` is removed.\n\n If the optio...
Please provide a description of the function:def get_parser(config=None): # This uses RawTextHelpFormatter so that the description (the docstring of # this module) is formatted correctly. Unfortunately, that means that # parser help is not text wrapped (but all other help is). parser = argparse.Arg...
[ "\n return a parser suitable to parse CL arguments.\n\n Parameters\n ----------\n\n config: dict\n Default values to fall back on, if not given.\n\n Returns\n -------\n\n An argparse parser configured to parse the command lines arguments of\n sys.argv which will default on val...
Please provide a description of the function:def get_config(): p = Path('.travis.yml') if not p.exists(): return {} with p.open() as f: travis_config = yaml.safe_load(f.read()) config = travis_config.get('doctr', {}) if not isinstance(config, dict): raise ValueError('c...
[ "\n This load some configuration from the ``.travis.yml``, if file is present,\n ``doctr`` key if present.\n " ]
Please provide a description of the function:def get_deploy_key_repo(deploy_repo, keypath, key_ext=''): # deploy key of the original repo has write access to the wiki deploy_key_repo = deploy_repo[:-5] if deploy_repo.endswith('.wiki') else deploy_repo # Automatically determine environment variable and...
[ "\n Return (repository of which deploy key is used, environment variable to store\n the encryption key of deploy key, path of deploy key file)\n " ]
Please provide a description of the function:def configure(args, parser): if not args.force and on_travis(): parser.error(red("doctr appears to be running on Travis. Use " "doctr configure --force to run anyway.")) if not args.authenticate: args.upload_key = False if args....
[ "\n Color guide\n\n - red: Error and warning messages\n - green: Welcome messages (use sparingly)\n - blue: Default values\n - bold_magenta: Action items\n - bold_black: Parts of code to be run or copied that should be modified\n ", "\\\n Welcome to Doctr.\n\n We need to ask you a few q...
Please provide a description of the function:def decrypt_file(file, key): if not file.endswith('.enc'): raise ValueError("%s does not end with .enc" % file) fer = Fernet(key) with open(file, 'rb') as f: decrypted_file = fer.decrypt(f.read()) with open(file[:-4], 'wb') as f: ...
[ "\n Decrypts the file ``file``.\n\n The encrypted file is assumed to end with the ``.enc`` extension. The\n decrypted file is saved to the same location without the ``.enc``\n extension.\n\n The permissions on the decrypted file are automatically set to 0o600.\n\n See also :func:`doctr.local.encry...
Please provide a description of the function:def setup_deploy_key(keypath='github_deploy_key', key_ext='.enc', env_name='DOCTR_DEPLOY_ENCRYPTION_KEY'): key = os.environ.get(env_name, os.environ.get("DOCTR_DEPLOY_ENCRYPTION_KEY", None)) if not key: raise RuntimeError("{env_name} or DOCTR_DEPLOY_ENCR...
[ "\n Decrypts the deploy key and configures it with ssh\n\n The key is assumed to be encrypted as keypath + key_ext, and the\n encryption key is assumed to be set in the environment variable\n ``env_name``. If ``env_name`` is not set, it falls back to\n ``DOCTR_DEPLOY_ENCRYPTION_KEY`` for backwards co...
Please provide a description of the function:def get_token(): token = os.environ.get("GH_TOKEN", None) if not token: token = "GH_TOKEN environment variable not set" token = token.encode('utf-8') return token
[ "\n Get the encrypted GitHub token in Travis.\n\n Make sure the contents this variable do not leak. The ``run()`` function\n will remove this from the output, so always use it.\n " ]
Please provide a description of the function:def run(args, shell=False, exit=True): if "GH_TOKEN" in os.environ: token = get_token() else: token = b'' if not shell: command = ' '.join(map(shlex.quote, args)) else: command = args command = command.replace(token.d...
[ "\n Run the command ``args``.\n\n Automatically hides the secret GitHub token from the output.\n\n If shell=False (recommended for most commands), args should be a list of\n strings. If shell=True, args should be a string of the command to run.\n\n If exit=True, it exits on nonzero returncode. Otherw...
Please provide a description of the function:def get_current_repo(): remote_url = subprocess.check_output(['git', 'config', '--get', 'remote.origin.url']).decode('utf-8') # Travis uses the https clone url _, org, git_repo = remote_url.rsplit('.git', 1)[0].rsplit('/', 2) return (org + '/' +...
[ "\n Get the GitHub repo name for the current directory.\n\n Assumes that the repo is in the ``origin`` remote.\n " ]
Please provide a description of the function:def get_travis_branch(): if os.environ.get("TRAVIS_PULL_REQUEST", "") == "true": return os.environ.get("TRAVIS_PULL_REQUEST_BRANCH", "") else: return os.environ.get("TRAVIS_BRANCH", "")
[ "Get the name of the branch that the PR is from.\n\n Note that this is not simply ``$TRAVIS_BRANCH``. the ``push`` build will\n use the correct branch (the branch that the PR is from) but the ``pr``\n build will use the _target_ of the PR (usually master). So instead, we ask\n for ``$TRAVIS_PULL_REQUEST...
Please provide a description of the function:def setup_GitHub_push(deploy_repo, *, auth_type='deploy_key', full_key_path='github_deploy_key.enc', require_master=None, branch_whitelist=None, deploy_branch='gh-pages', env_name='DOCTR_DEPLOY_ENCRYPTION_KEY', build_tags=False): # Set to the name of the...
[ "\n Setup the remote to push to GitHub (to be run on Travis).\n\n ``auth_type`` should be either ``'deploy_key'`` or ``'token'``.\n\n For ``auth_type='token'``, this sets up the remote with the token and\n checks out the gh-pages branch. The token to push to GitHub is assumed to be in the ``GH_TOKEN`` e...
Please provide a description of the function:def set_git_user_email(): username = subprocess.run(shlex.split('git config user.name'), stdout=subprocess.PIPE).stdout.strip().decode('utf-8') if not username or username == "Travis CI User": run(['git', 'config', '--global', 'user.name', "Doctr (Travis...
[ "\n Set global user and email for git user if not already present on system\n " ]
Please provide a description of the function:def checkout_deploy_branch(deploy_branch, canpush=True): # Create an empty branch with .nojekyll if it doesn't already exist create_deploy_branch(deploy_branch, push=canpush) remote_branch = "doctr_remote/{}".format(deploy_branch) print("Checking out doc...
[ "\n Checkout the deploy branch, creating it if it doesn't exist.\n " ]
Please provide a description of the function:def deploy_branch_exists(deploy_branch): remote_name = 'doctr_remote' branch_names = subprocess.check_output(['git', 'branch', '-r']).decode('utf-8').split() return '{}/{}'.format(remote_name, deploy_branch) in branch_names
[ "\n Check if there is a remote branch with name specified in ``deploy_branch``.\n\n Note that default ``deploy_branch`` is ``gh-pages`` for regular repos and\n ``master`` for ``github.io`` repos.\n\n This isn't completely robust. If there are multiple remotes and you have a\n ``deploy_branch`` branch...
Please provide a description of the function:def create_deploy_branch(deploy_branch, push=True): if not deploy_branch_exists(deploy_branch): print("Creating {} branch on doctr_remote".format(deploy_branch)) clear_working_branch() run(['git', 'checkout', '--orphan', DOCTR_WORKING_BRANCH]...
[ "\n If there is no remote branch with name specified in ``deploy_branch``,\n create one.\n\n Note that default ``deploy_branch`` is ``gh-pages`` for regular\n repos and ``master`` for ``github.io`` repos.\n\n Return True if ``deploy_branch`` was created, False if not.\n " ]
Please provide a description of the function:def find_sphinx_build_dir(): build = glob.glob('**/*build/html', recursive=True) if not build: raise RuntimeError("Could not find Sphinx build directory automatically") build_folder = build[0] return build_folder
[ "\n Find build subfolder within sphinx docs directory.\n\n This is called by :func:`commit_docs` if keyword arg ``built_docs`` is not\n specified on the command line.\n " ]
Please provide a description of the function:def copy_to_tmp(source): tmp_dir = tempfile.mkdtemp() # Use pathlib because os.path.basename is different depending on whether # the path ends in a / p = pathlib.Path(source) dirname = p.name or 'temp' new_dir = os.path.join(tmp_dir, dirname) ...
[ "\n Copies ``source`` to a temporary directory, and returns the copied\n location.\n\n If source is a file, the copied location is also a file.\n " ]
Please provide a description of the function:def is_subdir(a, b): a, b = map(os.path.abspath, [a, b]) return os.path.commonpath([a, b]) == b
[ "\n Return true if a is a subdirectory of b\n " ]
Please provide a description of the function:def sync_from_log(src, dst, log_file, exclude=()): from os.path import join, exists, isdir exclude = [os.path.normpath(i) for i in exclude] added, removed = [], [] if not exists(log_file): # Assume this is the first run print("%s doesn...
[ "\n Sync the files in ``src`` to ``dst``.\n\n The files that are synced are logged to ``log_file``. If ``log_file``\n exists, the files in ``log_file`` are removed first.\n\n Returns ``(added, removed)``, where added is a list of all files synced from\n ``src`` (even if it already existed in ``dst``)...
Please provide a description of the function:def commit_docs(*, added, removed): TRAVIS_BUILD_NUMBER = os.environ.get("TRAVIS_BUILD_NUMBER", "<unknown>") TRAVIS_BRANCH = os.environ.get("TRAVIS_BRANCH", "<unknown>") TRAVIS_COMMIT = os.environ.get("TRAVIS_COMMIT", "<unknown>") TRAVIS_REPO_SLUG = os.e...
[ "\n Commit the docs to the current branch\n\n Assumes that :func:`setup_GitHub_push`, which sets up the ``doctr_remote``\n remote, has been run.\n\n Returns True if changes were committed and False if no changes were\n committed.\n ", "\\\nUpdate docs after building Travis build {TRAVIS_BUILD_NU...
Please provide a description of the function:def push_docs(deploy_branch='gh-pages', retries=5): code = 1 while code and retries: print("Pulling") code = run(['git', 'pull', '-s', 'recursive', '-X', 'ours', 'doctr_remote', deploy_branch], exit=False) print("Pushing comm...
[ "\n Push the changes to the branch named ``deploy_branch``.\n\n Assumes that :func:`setup_GitHub_push` has been run and returned True, and\n that :func:`commit_docs` has been run. Does not push anything if no changes\n were made.\n\n " ]
Please provide a description of the function:def determine_push_rights(*, branch_whitelist, TRAVIS_BRANCH, TRAVIS_PULL_REQUEST, TRAVIS_TAG, build_tags, fork): canpush = True if TRAVIS_TAG: if not build_tags: print("The docs are not pushed on tag builds. To push on future tag builds...
[ "Check if Travis is running on ``master`` (or a whitelisted branch) to\n determine if we can/should push the docs to the deploy repo\n " ]
Please provide a description of the function:def clean_path(p): p = os.path.expanduser(p) p = os.path.expandvars(p) p = os.path.abspath(p) return p
[ " Clean a path by expanding user and environment variables and\n ensuring absolute path.\n " ]
Please provide a description of the function:def guess_organization(): try: stdout = subprocess.check_output('git config --get user.name'.split()) org = stdout.strip().decode("UTF-8") except: org = getpass.getuser() if sys.version_info[0] == 2: # only decode when...
[ " Guess the organization from `git config`. If that can't be found,\n fall back to $USER environment variable.\n " ]
Please provide a description of the function:def load_file_template(path): template = StringIO() if not os.path.exists(path): raise ValueError("path does not exist: %s" % path) with open(clean_path(path), "rb") as infile: # opened as binary for line in infile: template.writ...
[ " Load template from the specified filesystem path.\n " ]
Please provide a description of the function:def load_package_template(license, header=False): content = StringIO() filename = 'template-%s-header.txt' if header else 'template-%s.txt' with resource_stream(__name__, filename % license) as licfile: for line in licfile: content.write(...
[ " Load license template distributed with package.\n " ]
Please provide a description of the function:def extract_vars(template): keys = set() for match in re.finditer(r"\{\{ (?P<key>\w+) \}\}", template.getvalue()): keys.add(match.groups()[0]) return sorted(list(keys))
[ " Extract variables from template. Variables are enclosed in\n double curly braces.\n " ]
Please provide a description of the function:def generate_license(template, context): out = StringIO() content = template.getvalue() for key in extract_vars(template): if key not in context: raise ValueError("%s is missing from the template context" % key) content = content....
[ " Generate a license by extracting variables from the template and\n replacing them with the corresponding values in the given context.\n " ]
Please provide a description of the function:def format_license(template, lang): if not lang: lang = 'txt' out = StringIO() template.seek(0) # from the start of the buffer out.write(LANG_CMT[LANGS[lang]][0] + u'\n') for line in template.readlines(): out.write(LANG_CMT[LANGS[lan...
[ " Format the StringIO template object for specified lang string:\n return StringIO object formatted\n " ]
Please provide a description of the function:def get_suffix(name): a = name.count(".") if a: ext = name.split(".")[-1] if ext in LANGS.keys(): return ext return False else: return False
[ "Check if file name have valid suffix for formatting.\n if have suffix return it else return False.\n " ]
Please provide a description of the function:def coerce(cls, key, value): "Convert plain dictionaries to MutableDict." if not isinstance(value, MutableDict): if isinstance(value, dict): return MutableDict(value) # this call will raise ValueError retu...
[]
Please provide a description of the function:def _raise_for_status(response): message = '' if 400 <= response.status < 500: message = '%s Client Error: %s' % (response.status, response.reason) elif 500 <= response.status < 600: message = '%s Server Error: %s' % (response.status, respons...
[ " make sure that only crate.exceptions are raised that are defined in\n the DB-API specification " ]
Please provide a description of the function:def _server_url(server): if not _HTTP_PAT.match(server): server = 'http://%s' % server parsed = urlparse(server) url = '%s://%s' % (parsed.scheme, parsed.netloc) return url
[ "\n Normalizes a given server string to an url\n\n >>> print(_server_url('a'))\n http://a\n >>> print(_server_url('a:9345'))\n http://a:9345\n >>> print(_server_url('https://a:9345'))\n https://a:9345\n >>> print(_server_url('https://a'))\n https://a\n >>> print(_server_url('demo.crate...
Please provide a description of the function:def request(self, method, path, data=None, stream=False, headers=None, username=None, password=None, schema=None, **kwargs): ...
[ "Send a request\n\n Always set the Content-Length and the Content-Type header.\n " ]
Please provide a description of the function:def sql(self, stmt, parameters=None, bulk_parameters=None): if stmt is None: return None data = _create_sql_payload(stmt, parameters, bulk_parameters) logger.debug( 'Sending request to %s with payload: %s', self.path,...
[ "\n Execute SQL stmt against the crate server.\n " ]
Please provide a description of the function:def blob_put(self, table, digest, data): response = self._request('PUT', _blob_path(table, digest), data=data) if response.status == 201: # blob created return True if response.status =...
[ "\n Stores the contents of the file like @data object in a blob under the\n given table and digest.\n " ]
Please provide a description of the function:def blob_get(self, table, digest, chunk_size=1024 * 128): response = self._request('GET', _blob_path(table, digest), stream=True) if response.status == 404: raise DigestNotFoundException(table, digest) _raise_for_status(response) ...
[ "\n Returns a file like object representing the contents of the blob\n with the given digest.\n " ]
Please provide a description of the function:def blob_exists(self, table, digest): response = self._request('HEAD', _blob_path(table, digest)) if response.status == 200: return True elif response.status == 404: return False _raise_for_status(response)
[ "\n Returns true if the blob with the given digest exists\n under the given table.\n " ]
Please provide a description of the function:def _request(self, method, path, server=None, **kwargs): while True: next_server = server or self._get_server() try: response = self.server_pool[next_server].request( method, path, username=self.use...
[ "Execute a request to the cluster\n\n A server is selected from the server pool.\n " ]
Please provide a description of the function:def _json_request(self, method, path, data): response = self._request(method, path, data=data) _raise_for_status(response) if len(response.data) > 0: return _json_from_response(response) return response.data
[ "\n Issue request against the crate HTTP API.\n " ]
Please provide a description of the function:def _get_server(self): with self._lock: inactive_server_count = len(self._inactive_servers) for i in range(inactive_server_count): try: ts, server, message = heapq.heappop(self._inactive_servers) ...
[ "\n Get server to use for request.\n Also process inactive server list, re-add them after given interval.\n " ]
Please provide a description of the function:def _drop_server(self, server, message): try: self._active_servers.remove(server) except ValueError: pass else: heapq.heappush(self._inactive_servers, (time(), server, message)) logger.warning("...
[ "\n Drop server from active list and adds it to the inactive ones.\n " ]
Please provide a description of the function:def match(column, term, match_type=None, options=None): return Match(column, term, match_type, options)
[ "Generates match predicate for fulltext search\n\n :param column: A reference to a column or an index, or a subcolumn, or a\n dictionary of subcolumns with boost values.\n\n :param term: The term to match against. This string is analyzed and the\n resulting tokens are compared to the index.\n\n :pa...
Please provide a description of the function:def put(self, f, digest=None): if digest: actual_digest = digest else: actual_digest = self._compute_digest(f) created = self.conn.client.blob_put(self.container_name, actu...
[ "\n Upload a blob\n\n :param f:\n File object to be uploaded (required to support seek if digest is\n not provided).\n :param digest:\n Optional SHA-1 hex digest of the file contents. Gets computed\n before actual upload if not provided, which require...
Please provide a description of the function:def get(self, digest, chunk_size=1024 * 128): return self.conn.client.blob_get(self.container_name, digest, chunk_size)
[ "\n Return the contents of a blob\n\n :param digest: the hex digest of the blob to return\n :param chunk_size: the size of the chunks returned on each iteration\n :return: generator returning chunks of data\n " ]
Please provide a description of the function:def delete(self, digest): return self.conn.client.blob_del(self.container_name, digest)
[ "\n Delete a blob\n\n :param digest: the hex digest of the blob to be deleted\n :return: True if blob existed\n " ]
Please provide a description of the function:def exists(self, digest): return self.conn.client.blob_exists(self.container_name, digest)
[ "\n Check if a blob exists\n\n :param digest: Hex digest of the blob\n :return: Boolean indicating existence of the blob\n " ]
Please provide a description of the function:def execute(self, sql, parameters=None, bulk_parameters=None): if self.connection._closed: raise ProgrammingError("Connection closed") if self._closed: raise ProgrammingError("Cursor closed") self._result = self.conn...
[ "\n Prepare and execute a database operation (query or command).\n " ]
Please provide a description of the function:def executemany(self, sql, seq_of_parameters): row_counts = [] durations = [] if self.connection.lowest_server_version >= BULK_INSERT_MIN_VERSION: self.execute(sql, bulk_parameters=seq_of_parameters) for result in self...
[ "\n Prepare a database operation (query or command) and then execute it\n against all parameter sequences or mappings found in the sequence\n ``seq_of_parameters``.\n " ]
Please provide a description of the function:def fetchmany(self, count=None): if count is None: count = self.arraysize if count == 0: return self.fetchall() result = [] for i in range(count): try: result.append(self.next()) ...
[ "\n Fetch the next set of rows of a query result, returning a sequence of\n sequences (e.g. a list of tuples). An empty sequence is returned when\n no more rows are available.\n " ]
Please provide a description of the function:def fetchall(self): result = [] iterate = True while iterate: try: result.append(self.next()) except StopIteration: iterate = False return result
[ "\n Fetch all (remaining) rows of a query result, returning them as a\n sequence of sequences (e.g. a list of tuples). Note that the cursor's\n arraysize attribute can affect the performance of this operation.\n " ]
Please provide a description of the function:def rowcount(self): if (self._closed or not self._result or "rows" not in self._result): return -1 return self._result.get("rowcount", -1)
[ "\n This read-only attribute specifies the number of rows that the last\n .execute*() produced (for DQL statements like ``SELECT``) or affected\n (for DML statements like ``UPDATE`` or ``INSERT``).\n " ]
Please provide a description of the function:def next(self): if self.rows is None: raise ProgrammingError( "No result available. " + "execute() or executemany() must be called first." ) elif not self._closed: return next(self.r...
[ "\n Return the next row of a query result set, respecting if cursor was\n closed.\n " ]
Please provide a description of the function:def description(self): if self._closed: return description = [] for col in self._result["cols"]: description.append((col, None, None, ...
[ "\n This read-only attribute is a sequence of 7-item sequences.\n " ]
Please provide a description of the function:def duration(self): if self._closed or \ not self._result or \ "duration" not in self._result: return -1 return self._result.get("duration", 0)
[ "\n This read-only attribute specifies the server-side duration of a query\n in milliseconds.\n " ]
Please provide a description of the function:def connect(servers=None, timeout=None, client=None, verify_ssl_cert=False, ca_cert=None, error_trace=False, cert_file=None, key_file=None, username=None, password=Non...
[ " Create a :class:Connection object\n\n :param servers:\n either a string in the form of '<hostname>:<port>'\n or a list of servers in the form of ['<hostname>:<port>', '...']\n :param timeout:\n (optional)\n define the retry timeout for unreachable servers in seconds\n :param c...
Please provide a description of the function:def rewrite_update(clauseelement, multiparams, params): newmultiparams = [] _multiparams = multiparams[0] if len(_multiparams) == 0: return clauseelement, multiparams, params for _params in _multiparams: newparams = {} for key, va...
[ " change the params to enable partial updates\n\n sqlalchemy by default only supports updates of complex types in the form of\n\n \"col = ?\", ({\"x\": 1, \"y\": 2}\n\n but crate supports\n\n \"col['x'] = ?, col['y'] = ?\", (1, 2)\n\n by using the `Craty` (`MutableDict`) type.\n The update...
Please provide a description of the function:def visit_insert(self, insert_stmt, asfrom=False, **kw): self.stack.append( {'correlate_froms': set(), "asfrom_froms": set(), "selectable": insert_stmt}) self.isinsert = True crud_params = crud._get_cru...
[ "\n used to compile <sql.expression.Insert> expressions.\n\n this function wraps insert_from_select statements inside\n parentheses to be conform with earlier versions of CreateDB.\n " ]
Please provide a description of the function:def visit_update(self, update_stmt, **kw): if not update_stmt.parameters and \ not hasattr(update_stmt, '_crate_specific'): return super(CrateCompiler, self).visit_update(update_stmt, **kw) self.isupdate = True ...
[ "\n used to compile <sql.expression.Update> expressions\n Parts are taken from the SQLCompiler base class.\n " ]
Please provide a description of the function:def _get_crud_params(compiler, stmt, **kw): compiler.postfetch = [] compiler.insert_prefetch = [] compiler.update_prefetch = [] compiler.returning = [] # no parameters in the statement, no parameters in the # compile...
[ " extract values from crud parameters\n\n taken from SQLAlchemy's crud module (since 1.0.x) and\n adapted for Crate dialect" ]
Please provide a description of the function:def get_tgt_for(user): if not settings.CAS_PROXY_CALLBACK: raise CasConfigException("No proxy callback set in settings") try: return Tgt.objects.get(username=user.username) except ObjectDoesNotExist: logger.warning('No ticket found f...
[ "\n Fetch a ticket granting ticket for a given user.\n\n :param user: UserObj\n\n :return: TGT or Exepction\n " ]
Please provide a description of the function:def delete_old_tickets(**kwargs): sender = kwargs.get('sender', None) now = datetime.now() expire = datetime(now.year, now.month, now.day - 2) sender.objects.filter(created__lt=expire).delete()
[ "\n Delete tickets if they are over 2 days old\n kwargs = ['raw', 'signal', 'instance', 'sender', 'created']\n\n " ]
Please provide a description of the function:def get_proxy_ticket_for(self, service): if not settings.CAS_PROXY_CALLBACK: raise CasConfigException("No proxy callback set in settings") params = {'pgt': self.tgt, 'targetService': service} url = (urljoin(settings.CAS_SERVER_...
[ "\n Verifies CAS 2.0+ XML-based authentication ticket.\n\n :param: service\n\n Returns username on success and None on failure.\n " ]
Please provide a description of the function:def _verify_cas1(ticket, service): params = {'ticket': ticket, 'service': service} url = (urljoin(settings.CAS_SERVER_URL, 'validate') + '?' + urlencode(params)) page = urlopen(url) try: verified = page.readline().strip() if ...
[ "\n Verifies CAS 1.0 authentication ticket.\n\n :param: ticket\n :param: service\n\n Returns username on success and None on failure.\n " ]
Please provide a description of the function:def _internal_verify_cas(ticket, service, suffix): params = {'ticket': ticket, 'service': service} if settings.CAS_PROXY_CALLBACK: params['pgtUrl'] = settings.CAS_PROXY_CALLBACK url = (urljoin(settings.CAS_SERVER_URL, suffix) + '?' + url...
[ "Verifies CAS 2.0 and 3.0 XML-based authentication ticket.\n\n Returns username on success and None on failure.\n " ]
Please provide a description of the function:def verify_proxy_ticket(ticket, service): params = {'ticket': ticket, 'service': service} url = (urljoin(settings.CAS_SERVER_URL, 'proxyValidate') + '?' + urlencode(params)) page = urlopen(url) try: response = page.read() t...
[ "\n Verifies CAS 2.0+ XML-based proxy ticket.\n\n :param: ticket\n :param: service\n\n Returns username on success and None on failure.\n " ]
Please provide a description of the function:def _get_pgtiou(pgt): pgtIou = None retries_left = 5 if not settings.CAS_PGT_FETCH_WAIT: retries_left = 1 while not pgtIou and retries_left: try: return PgtIOU.objects.get(tgt=pgt) except PgtIOU.DoesNotExist: ...
[ "\n Returns a PgtIOU object given a pgt.\n\n The PgtIOU (tgt) is set by the CAS server in a different request\n that has completed before this call, however, it may not be found in\n the database by this calling thread, hence the attempt to get the\n ticket is retried for up to 5 seconds. This should...
Please provide a description of the function:def authenticate(self, request, ticket, service): User = get_user_model() username = _verify(ticket, service) if not username: return None try: user = User.objects.get(username__iexact=username) exce...
[ "\n Verifies CAS ticket and gets or creates User object\n NB: Use of PT to identify proxy\n " ]
Please provide a description of the function:def gateway(): if settings.CAS_GATEWAY == False: raise ImproperlyConfigured('CAS_GATEWAY must be set to True') def wrap(func): def wrapped_f(*args): from cas.views import login request = args[0] try: ...
[ "\n Authenticates single sign on session if ticket is available,\n but doesn't redirect to sign in url otherwise.\n " ]
Please provide a description of the function:def _service_url(request, redirect_to=None, gateway=False): if settings.CAS_FORCE_SSL_SERVICE_URL: protocol = 'https://' else: protocol = ('http://', 'https://')[request.is_secure()] host = request.get_host() service = protocol + host + ...
[ "\n Generates application service URL for CAS\n\n :param: request Request Object\n :param: redirect_to URL to redriect to\n :param: gateway Should this be a gatewayed pass through\n\n ", " If gateway, capture params and reencode them before returning a url " ]
Please provide a description of the function:def _redirect_url(request): next = request.GET.get(REDIRECT_FIELD_NAME) if not next: if settings.CAS_IGNORE_REFERER: next = settings.CAS_REDIRECT_URL else: next = request.META.get('HTTP_REFERER', settings.CAS_REDIRECT_UR...
[ "\n Redirects to referring page, or CAS_REDIRECT_URL if no referrer is\n set.\n\n :param: request RequestObj\n\n " ]
Please provide a description of the function:def _login_url(service, ticket='ST', gateway=False): LOGINS = {'ST': 'login', 'PT': 'proxyValidate'} if gateway: params = {'service': service, 'gateway': 'true'} else: params = {'service': service} if settings.CAS_EXTRA_LO...
[ "\n Generates CAS login URL\n\n :param: service Service URL\n :param: ticket Ticket\n :param: gateway Gatewayed\n\n " ]
Please provide a description of the function:def _logout_url(request, next_page=None): url = urlparse.urljoin(settings.CAS_SERVER_URL, 'logout') if next_page and getattr(settings, 'CAS_PROVIDE_URL_TO_LOGOUT', True): parsed_url = urlparse.urlparse(next_page) if parsed_url.scheme: #If next_...
[ "\n Generates CAS logout URL\n\n :param: request RequestObj\n :param: next_page Page to redirect after logout.\n\n " ]
Please provide a description of the function:def login(request, next_page=None, required=False, gateway=False): if not next_page: next_page = _redirect_url(request) try: # use callable for pre-django 2.0 is_authenticated = request.user.is_authenticated() except TypeError: ...
[ "\n Forwards to CAS login URL or verifies CAS ticket\n\n :param: request RequestObj\n :param: next_page Next page to redirect after login\n :param: required\n :param: gateway Gatewayed response\n\n " ]
Please provide a description of the function:def logout(request, next_page=None): auth.logout(request) if not next_page: next_page = _redirect_url(request) if settings.CAS_LOGOUT_COMPLETELY: return HttpResponseRedirect(_logout_url(request, next_page)) else: return HttpRes...
[ "\n Redirects to CAS logout page\n\n :param: request RequestObj\n :param: next_page Page to redirect to\n\n " ]
Please provide a description of the function:def proxy_callback(request): pgtIou = request.GET.get('pgtIou') tgt = request.GET.get('pgtId') if not (pgtIou and tgt): logger.info('No pgtIou or tgt found in request.GET') return HttpResponse('No pgtIOO', content_type="text/plain") tr...
[ "Handles CAS 2.0+ XML-based proxy callback call.\n Stores the proxy granting ticket in the database for\n future use.\n\n NB: Use created and set it in python in case database\n has issues with setting up the default timestamp value\n " ]
Please provide a description of the function:def process_view(self, request, view_func, view_args, view_kwargs): if view_func == login: return cas_login(request, *view_args, **view_kwargs) elif view_func == logout: return cas_logout(request, *view_args, **view_kwargs) ...
[ "\n Forwards unauthenticated requests to the admin page to the CAS\n login URL, as well as calls to django.contrib.auth.views.login and\n logout.\n " ]
Please provide a description of the function:def process_exception(self, request, exception): if isinstance(exception, CasTicketException): do_logout(request) # This assumes that request.path requires authentication. return HttpResponseRedirect(request.path) ...
[ "\n When we get a CasTicketException, that is probably caused by the ticket timing out.\n So logout/login and get the same page again.\n " ]
Please provide a description of the function:def objectify(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: payload = func(*args, **kwargs) except requests.exceptions.ConnectionError as e: raise InternetConnectionError(e) return EventbriteObj...
[ " Converts the returned value from a models.Payload to\n a models.EventbriteObject. Used by the access methods\n of the client.Eventbrite object\n " ]
Please provide a description of the function:def get_category(self, id, **data): return self.get("/categories/{0}/".format(id), data=data)
[ "\n GET /categories/:id/\n Gets a :format:`category` by ID as ``category``.\n " ]
Please provide a description of the function:def get_subcategory(self, id, **data): return self.get("/subcategories/{0}/".format(id), data=data)
[ "\n GET /subcategories/:id/\n Gets a :format:`subcategory` by ID as ``subcategory``.\n " ]
Please provide a description of the function:def get_event(self, id, **data): return self.get("/events/{0}/".format(id), data=data)
[ "\n GET /events/:id/\n Returns an :format:`event` for the specified event. Many of Eventbrite’s API use cases revolve around pulling details\n of a specific event within an Eventbrite account. Does not support fetching a repeating event series parent\n (see :ref:`get-series-by-id`).\n ...
Please provide a description of the function:def post_event(self, id, **data): return self.post("/events/{0}/".format(id), data=data)
[ "\n POST /events/:id/\n Updates an event. Returns an :format:`event` for the specified event. Does not support updating a repeating event\n series parent (see POST /series/:id/).\n " ]
Please provide a description of the function:def post_event_publish(self, id, **data): return self.post("/events/{0}/publish/".format(id), data=data)
[ "\n POST /events/:id/publish/\n Publishes an event if it has not already been deleted. In order for publish to be permitted, the event must have all\n necessary information, including a name and description, an organizer, at least one ticket, and valid payment options.\n This API endpoin...