code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
full = kwargs.get('full', None)
if not full:
full = self.full(filetype, **kwargs)
return os.path.dirname(full) | def dir(self, filetype, **kwargs) | Return the directory containing a file of a given type.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
dir : str
Directory containing the file. | 4.135348 | 4.52222 | 0.914451 |
full = kwargs.get('full', None)
if not full:
full = self.full(filetype, **kwargs)
return os.path.basename(full) | def name(self, filetype, **kwargs) | Return the directory containing a file of a given type.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
name : str
Name of a file with no directory information. | 4.023557 | 4.61096 | 0.872607 |
'''Checks if the given type of file exists locally
Parameters
----------
filetype : str
File type parameter.
remote : bool
If True, checks for remote existence of the file
Returns
-------
exists : bool
Boolean indicat... | def exists(self, filetype, remote=None, **kwargs) | Checks if the given type of file exists locally
Parameters
----------
filetype : str
File type parameter.
remote : bool
If True, checks for remote existence of the file
Returns
-------
exists : bool
Boolean indicating if the ... | 3.667606 | 2.537589 | 1.445312 |
''' Expand a wildcard path locally
Parameters
----------
filetype : str
File type parameter.
as_url: bool
Boolean to return SAS urls
refine: str
Regular expression string to filter the list of files by
before random selec... | def expand(self, filetype, **kwargs) | Expand a wildcard path locally
Parameters
----------
filetype : str
File type parameter.
as_url: bool
Boolean to return SAS urls
refine: str
Regular expression string to filter the list of files by
before random selection
... | 5.795582 | 2.664865 | 2.174812 |
''' Checks if the local directory contains any of the type of file
Parameters
----------
filetype : str
File type parameter.
Returns
-------
any : bool
Boolean indicating if the any files exist in the expanded path on disk.
'''
... | def any(self, filetype, **kwargs) | Checks if the local directory contains any of the type of file
Parameters
----------
filetype : str
File type parameter.
Returns
-------
any : bool
Boolean indicating if the any files exist in the expanded path on disk. | 6.9112 | 2.279712 | 3.031611 |
''' Returns random one of the given type of file
Parameters
----------
filetype : str
File type parameter.
as_url: bool
Boolean to return SAS urls
refine: str
Regular expression string to filter the list of files by
befor... | def one(self, filetype, **kwargs) | Returns random one of the given type of file
Parameters
----------
filetype : str
File type parameter.
as_url: bool
Boolean to return SAS urls
refine: str
Regular expression string to filter the list of files by
before random sel... | 9.560908 | 2.039105 | 4.688776 |
''' Returns random number of the given type of file
Parameters
----------
filetype : str
File type parameter.
num : int
The number of files to return
as_url: bool
Boolean to return SAS urls
refine: str
Regular ex... | def random(self, filetype, **kwargs) | Returns random number of the given type of file
Parameters
----------
filetype : str
File type parameter.
num : int
The number of files to return
as_url: bool
Boolean to return SAS urls
refine: str
Regular expression str... | 8.03632 | 2.734424 | 2.938944 |
''' Returns a list of files filterd by a regular expression
Parameters
----------
filelist : list
A list of files to filter on.
regex : str
The regular expression string to filter your list
filterdir: {'in', 'out'}
Indicates the filt... | def refine(self, filelist, regex, filterdir='out', **kwargs) | Returns a list of files filterd by a regular expression
Parameters
----------
filelist : list
A list of files to filter on.
regex : str
The regular expression string to filter your list
filterdir: {'in', 'out'}
Indicates the filter to be inc... | 3.850196 | 2.023996 | 1.902274 |
# check if full already in kwargs
if 'full' in kwargs:
return kwargs.get('full')
# check for filetype in template
assert filetype in self.templates, ('No entry {0} found. Filetype must '
'be one of the designated template... | def full(self, filetype, **kwargs) | Return the full name of a given type of file.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
full : str
The full path to the file. | 5.002981 | 4.874219 | 1.026417 |
''' Call the special functions found in a template path
Calls special functions indicated by %methodname found in the
sdss_paths.ini template file, and replaces the %location in the path
with the returned content.
Parameters:
filetype (str):
template... | def _call_special_functions(self, filetype, template, **kwargs) | Call the special functions found in a template path
Calls special functions indicated by %methodname found in the
sdss_paths.ini template file, and replaces the %location in the path
with the returned content.
Parameters:
filetype (str):
template name of fil... | 6.747405 | 2.139413 | 3.153858 |
full = kwargs.get('full', None)
if not full:
full = self.full(filetype, **kwargs)
self.set_base_dir(base_dir=base_dir)
location = full[len(self.base_dir):] if full and full.startswith(self.base_dir) else None
if location and '//' in location:
l... | def location(self, filetype, base_dir=None, **kwargs) | Return the location of the relative sas path of a given type of file.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
full : str
The relative sas path to the file. | 2.988414 | 2.918332 | 1.024014 |
location = self.location(filetype, **kwargs)
return join(self.remote_base, sasdir, location) if self.remote_base and location else None | def url(self, filetype, base_dir=None, sasdir='sas', **kwargs) | Return the url of a given type of file.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
full : str
The sas url to the file. | 5.507352 | 7.17537 | 0.767536 |
plateid = int(kwargs['plateid'])
if plateid < 10000:
return "{:0>6d}".format(plateid)
else:
return "{:d}".format(plateid) | def plateid6(self, filetype, **kwargs) | Print plate ID, accounting for 5-6 digit plate IDs.
Parameters
----------
filetype : str
File type parameter.
plateid : int or str
Plate ID number. Will be converted to int internally.
Returns
-------
plateid6 : str
Plate ID ... | 2.773865 | 3.139606 | 0.883507 |
plateid = int(kwargs['plateid'])
plateid100 = plateid // 100
subdir = "{:0>4d}".format(plateid100) + "XX"
return os.path.join(subdir, "{:0>6d}".format(plateid)) | def platedir(self, filetype, **kwargs) | Returns plate subdirectory in :envvar:`PLATELIST_DIR` of the form: ``NNNNXX/NNNNNN``.
Parameters
----------
filetype : str
File type parameter.
plateid : int or str
Plate ID number. Will be converted to int internally.
Returns
-------
pl... | 4.007422 | 4.1266 | 0.97112 |
if str(kwargs['run2d']) in ('26', '103', '104'):
return os.environ['SPECTRO_REDUX']
else:
return os.environ['BOSS_SPECTRO_REDUX'] | def spectrodir(self, filetype, **kwargs) | Returns :envvar:`SPECTRO_REDUX` or :envvar:`BOSS_SPECTRO_REDUX`
depending on the value of `run2d`.
Parameters
----------
filetype : str
File type parameter.
run2d : int or str
2D Reduction ID.
Returns
-------
spectrodir : str
... | 6.045127 | 3.327359 | 1.816794 |
designid = int(kwargs['designid'])
designid100 = designid // 100
subdir = "{:0>4d}".format(designid100) + "XX"
return subdir | def definitiondir(self, filetype, **kwargs) | Returns definition subdirectory in :envvar:`PLATELIST_DIR` of the form: ``NNNNXX``.
Parameters
----------
filetype : str
File type parameter.
designid : int or str
Design ID number. Will be converted to int internally.
Returns
-------
de... | 7.409497 | 5.502841 | 1.346486 |
if logger is not None:
logger.debug(command)
status = 0
out = ''
err = ''
if not test:
if outname is None:
outfile = TemporaryFile()
else:
outfile = open(outname, 'w+')
if errname is None:
... | def foreground_run(self, command, test=False, logger=None, logall=False, message=None, outname=None, errname=None) | A convenient wrapper to log and perform system calls.
Parameters
----------
command : str
The system command to run. It will be split internally by shlex.split().
test : bool, optional
Set this to true to not actually run the commands.
logger : logging.l... | 1.98923 | 2.046537 | 0.971998 |
if repo[None].branch() != "default":
raise hg_util.Abort("cannot run hg undo outside default branch")
err = clpatch_or_undo(ui, repo, clname, opts, mode="undo")
if err:
raise hg_util.Abort(err) | def undo(ui, repo, clname, **opts) | undo the effect of a CL
Creates a new CL that undoes an earlier CL.
After creating the CL, opens the CL text for editing so that
you can add the reason for the undo to the description. | 5.130927 | 6.536974 | 0.784908 |
c = repo[None]
if not releaseBranch:
raise hg_util.Abort("no active release branches")
if c.branch() != releaseBranch:
if c.modified() or c.added() or c.removed():
raise hg_util.Abort("uncommitted local changes - cannot switch branches")
err = hg_clean(repo, releaseBranch)
if err:
raise hg_util.Abort... | def release_apply(ui, repo, clname, **opts) | apply a CL to the release branch
Creates a new CL copying a previously committed change
from the main branch to the release branch.
The current client must either be clean or already be in
the release branch.
The release branch must be created by starting with a
clean client, disabling the code review plugin, ... | 4.062899 | 4.406975 | 0.921925 |
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
cl, vers, patch, err = DownloadCL(ui, repo, clname)
if err != "":
return err
ui.write(cl.EditorText() + "\n")
ui.write(patch + "\n")
return | def download(ui, repo, clname, **opts) | download a change from the code review server
Download prints a description of the given change list
followed by its diff, downloaded from the code review server. | 7.05212 | 7.265011 | 0.970696 |
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
pats = tuple([pat] + list(pats))
if not GoodCLName(clname):
return "invalid CL name " + clname
dirty = {}
cl, err = LoadCL(ui, repo, clname, web=False)
if err != '':
return err
if not cl.local:
return "cannot change non-local CL " + cln... | def file(ui, repo, clname, pat, *pats, **opts) | assign files to or remove files from a change list
Assign files to or (with -d) remove files from a change list.
The -d option only removes files from the change list.
It does not edit them or remove them from the repository. | 3.161312 | 3.252319 | 0.972018 |
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
files = ChangedExistingFiles(ui, repo, pats, opts)
files = gofmt_required(files)
if not files:
ui.status("no modified go files\n")
return
cwd = os.getcwd()
files = [RelativePath(repo.root + '/' + f, cwd) for f in files]
try:
cmd = ["gofm... | def gofmt(ui, repo, *pats, **opts) | apply gofmt to modified files
Applies gofmt to the modified files in the repository that match
the given patterns. | 4.045626 | 4.137889 | 0.977703 |
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
cl, err = CommandLineCL(ui, repo, pats, opts, op="mail", defaultcc=defaultcc)
if err != "":
raise hg_util.Abort(err)
cl.Upload(ui, repo, gofmt_just_warn=True)
if not cl.reviewer:
# If no reviewer is listed, assign the review to defaultcc.
... | def mail(ui, repo, *pats, **opts) | mail a change for review
Uploads a patch to the code review server and then sends mail
to the reviewer and CC list asking for a review. | 6.821495 | 6.645969 | 1.026411 |
opts['short'] = True
return pending(ui, repo, *pats, **opts) | def ps(ui, repo, *pats, **opts) | alias for hg p --short | 7.287304 | 3.888248 | 1.874187 |
opts['quick'] = True
return pending(ui, repo, *pats, **opts) | def pq(ui, repo, *pats, **opts) | alias for hg p --quick | 6.484474 | 4.22391 | 1.535183 |
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
quick = opts.get('quick', False)
short = opts.get('short', False)
m = LoadAllCL(ui, repo, web=not quick and not short)
names = m.keys()
names.sort()
for name in names:
cl = m[name]
if short:
ui.write(name + "\t" + line1(cl.desc) + "\n")... | def pending(ui, repo, *pats, **opts) | show pending changes
Lists pending changes followed by a list of unassigned but modified files. | 4.00733 | 4.056423 | 0.987898 |
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
if not opts["local"]:
# If there are incoming CLs, pull -u will do the update.
# If there are no incoming CLs, do hg update to make sure
# that an update always happens regardless. This is less
# surprising than update depending on incoming... | def sync(ui, repo, **opts) | synchronize with remote repository
Incorporates recent changes from the remote repository
into the local repository. | 7.017138 | 7.275985 | 0.964424 |
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
repo.ui.quiet = True
cl, err = LoadCL(ui, repo, name, web=True)
if err != "":
raise hg_util.Abort(err)
if not cl.local:
raise hg_util.Abort("cannot upload non-local change")
cl.Upload(ui, repo)
print "%s%s\n" % (server_url_base, cl.name)
... | def upload(ui, repo, name, **opts) | upload diffs to the code review server
Uploads the current modifications for a given change to the server. | 5.052567 | 5.095277 | 0.991618 |
try:
return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs)
except Exception, e:
if type(e) != urllib2.HTTPError or e.code != 500: # only retry on HTTP 500 error
raise
print >>sys.stderr, "Loading "+request_path+": "+ExceptionDetail()+"; trying again in 2 seconds."
time.sleep(... | def MySend(request_path, payload=None,
content_type="application/octet-stream",
timeout=None, force_auth=True,
**kwargs) | Run MySend1 maybe twice, because Rietveld is unreliable. | 2.78563 | 2.558003 | 1.088986 |
# TODO: Don't require authentication. Let the server say
# whether it is necessary.
global rpc
if rpc == None:
rpc = GetRpcServer(upload_options)
self = rpc
if not self.authenticated and force_auth:
self._Authenticate()
if request_path is None:
return
if timeout is None:
timeout = 30 # seconds
old_... | def MySend1(request_path, payload=None,
content_type="application/octet-stream",
timeout=None, force_auth=True,
**kwargs) | Sends an RPC and returns the response.
Args:
request_path: The path to send the request to, eg /api/appversion/create.
payload: The body of the request, or None to send an empty request.
content_type: The Content-Type header to use.
timeout: timeout in seconds; default None i.e. no timeout.
(Note: for larg... | 3.034701 | 3.038166 | 0.998859 |
last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
last_email = ""
if os.path.exists(last_email_file_name):
try:
last_email_file = open(last_email_file_name, "r")
last_email = last_email_file.readline().strip("\n")
last_email_file.close()
prompt += " [%s]" % last_email
ex... | def GetEmail(prompt) | Prompts the user for their email address and returns it.
The last used email address is saved to a file and offered up as a suggestion
to the user. If the user presses enter without typing in anything the last
used email address is used. If the user enters a new address, it is saved
for next time we prompt. | 1.746863 | 1.734072 | 1.007376 |
rpc_server_class = HttpRpcServer
def GetUserCredentials():
# Disable status prints so they don't obscure the password prompt.
global global_status
st = global_status
global_status = None
email = options.email
if email is None:
email = GetEmail("Email (login for uploading to %s)" % options.serve... | def GetRpcServer(options) | Returns an instance of an AbstractRpcServer.
Returns:
A new AbstractRpcServer, on which RPC calls can be made. | 4.250047 | 4.323679 | 0.98297 |
BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
CRLF = '\r\n'
lines = []
for (key, value) in fields:
typecheck(key, str)
typecheck(value, str)
lines.append('--' + BOUNDARY)
lines.append('Content-Disposition: form-data; name="%s"' % key)
lines.append('')
lines.append(value)
for (key, filename, value) in fi... | def EncodeMultipartFormData(fields, files) | Encode form fields for multipart/form-data.
Args:
fields: A sequence of (name, value) elements for regular form fields.
files: A sequence of (name, filename, value) elements for data to be
uploaded as files.
Returns:
(content_type, body) ready for httplib.HTTP instance.
Source:
http://aspn.activestate... | 1.434166 | 1.495636 | 0.9589 |
logging.info("Running %s", command)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=use_shell, universal_newlines=universal_newlines, env=env)
if print_output:
output_array = []
while True:
line = p.stdout.readline()
if not line:
break
print line.strip("\n")
... | def RunShellWithReturnCode(command, print_output=False,
universal_newlines=True, env=os.environ) | Executes a command and returns the output from stdout and the return code.
Args:
command: Command to execute.
print_output: If True, the output is printed to stdout.
If False, both stdout and stderr are ignored.
universal_newlines: Use universal_newlines flag (default: True).
Returns:
Tuple (output, retu... | 1.785058 | 1.891881 | 0.943536 |
patches = []
filename = None
diff = []
for line in data.splitlines(True):
new_filename = None
if line.startswith('Index:'):
unused, new_filename = line.split(':', 1)
new_filename = new_filename.strip()
elif line.startswith('Property changes on:'):
unused, temp_filename = line.split(':', 1)
# Whe... | def SplitPatch(data) | Splits a patch into separate pieces for each file.
Args:
data: A string containing the output of svn diff.
Returns:
A list of 2-tuple (filename, text) where text is the svn diff output
pertaining to filename. | 3.538067 | 3.276546 | 1.079816 |
patches = SplitPatch(data)
rv = []
for patch in patches:
set_status("uploading patch for " + patch[0])
if len(patch[1]) > MAX_UPLOAD_SIZE:
print ("Not uploading the patch for " + patch[0] +
" because the file is too large.")
continue
form_fields = [("filename", patch[0])]
if not options.download_... | def UploadSeparatePatches(issue, rpc_server, patchset, data, options) | Uploads a separate patch for each file in the diff output.
Returns a list of [patch_key, filename] for each file. | 3.358387 | 3.263928 | 1.02894 |
logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
req = urllib2.Request(url, data=data)
if self.host_override:
req.add_header("Host", self.host_override)
for key, value in self.extra_headers.iteritems():
req.add_header(key, value)
return req | def _CreateRequest(self, url, data=None) | Creates a new urllib request. | 2.480083 | 2.493039 | 0.994803 |
account_type = "GOOGLE"
if self.host.endswith(".google.com") and not force_google_account:
# Needed for use inside Google.
account_type = "HOSTED"
req = self._CreateRequest(
url="https://www.google.com/accounts/ClientLogin",
data=urllib.urlencode({
"Email": email,
"Passwd": password,
... | def _GetAuthToken(self, email, password) | Uses ClientLogin to authenticate the user, returning an auth token.
Args:
email: The user's email address
password: The user's password
Raises:
ClientLoginError: If there was an error authenticating with ClientLogin.
HTTPError: If there was some other form of HTTP error.
Returns:
The authenti... | 2.447375 | 2.559371 | 0.956241 |
# This is a dummy value to allow us to identify when we're successful.
continue_location = "http://localhost/"
args = {"continue": continue_location, "auth": auth_token}
req = self._CreateRequest("https://%s/_ah/login?%s" % (self.host, urllib.urlencode(args)))
try:
response = self.opener.open(req)
exc... | def _GetAuthCookie(self, auth_token) | Fetches authentication cookies for an authentication token.
Args:
auth_token: The authentication token returned by ClientLogin.
Raises:
HTTPError: If there was an error fetching the authentication cookies. | 3.103782 | 3.150339 | 0.985222 |
for i in range(3):
credentials = self.auth_function()
try:
auth_token = self._GetAuthToken(credentials[0], credentials[1])
except ClientLoginError, e:
if e.msg == "BadAuthentication":
print >>sys.stderr, "Invalid username or password."
continue
if e.msg == "CaptchaRequired":
pri... | def _Authenticate(self) | Authenticates the user.
The authentication process works as follows:
1) We get a username and password from the user
2) We use ClientLogin to obtain an AUTH token for the user
(see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
3) We pass the auth token to /_ah/login on the server to obta... | 2.2514 | 2.177104 | 1.034126 |
# TODO: Don't require authentication. Let the server say
# whether it is necessary.
if not self.authenticated:
self._Authenticate()
old_timeout = socket.getdefaulttimeout()
socket.setdefaulttimeout(timeout)
try:
tries = 0
while True:
tries += 1
args = dict(kwargs)
url = "https://%s... | def Send(self, request_path, payload=None,
content_type="application/octet-stream",
timeout=None,
**kwargs) | Sends an RPC and returns the response.
Args:
request_path: The path to send the request to, eg /api/appversion/create.
payload: The body of the request, or None to send an empty request.
content_type: The Content-Type header to use.
timeout: timeout in seconds; default None i.e. no timeout.
(Note: fo... | 2.275232 | 2.332753 | 0.975342 |
super(HttpRpcServer, self)._Authenticate()
if self.save_cookies:
StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
self.cookie_jar.save() | def _Authenticate(self) | Save the cookie jar after authentication. | 6.449836 | 5.199589 | 1.240451 |
opener = urllib2.OpenerDirector()
opener.add_handler(urllib2.ProxyHandler())
opener.add_handler(urllib2.UnknownHandler())
opener.add_handler(urllib2.HTTPHandler())
opener.add_handler(urllib2.HTTPDefaultErrorHandler())
opener.add_handler(urllib2.HTTPSHandler())
opener.add_handler(urllib2.HTTPErrorProces... | def _GetOpener(self) | Returns an OpenerDirector that supports cookies and ignores redirects.
Returns:
A urllib2.OpenerDirector object. | 2.210734 | 2.266009 | 0.975607 |
unknown_files = self.GetUnknownFiles()
if unknown_files:
print "The following files are not added to version control:"
for line in unknown_files:
print line
prompt = "Are you sure to continue?(y/N) "
answer = raw_input(prompt).strip()
if answer != "y":
ErrorExit("User aborted") | def CheckForUnknownFiles(self) | Show an "are you sure?" prompt if there are unknown files. | 3.41372 | 3.168386 | 1.077432 |
files = {}
for line in diff.splitlines(True):
if line.startswith('Index:') or line.startswith('Property changes on:'):
unused, filename = line.split(':', 1)
# On Windows if a file has property changes its filename uses '\'
# instead of '/'.
filename = to_slash(filename.strip())
files[filen... | def GetBaseFiles(self, diff) | Helper that calls GetBase file for each file in the patch.
Returns:
A dictionary that maps from filename to GetBaseFile's tuple. Filenames
are retrieved based on lines that start with "Index:" or
"Property changes on:". | 4.568229 | 3.695603 | 1.236126 |
def UploadFile(filename, file_id, content, is_binary, status, is_base):
set_status("uploading " + filename)
file_too_large = False
if is_base:
type = "base"
else:
type = "current"
if len(content) > MAX_UPLOAD_SIZE:
print ("Not uploading the %s file for %s because it's too large." %
... | def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
files) | Uploads the base files (and if necessary, the current ones as well). | 2.646237 | 2.64187 | 1.001653 |
mimetype = mimetypes.guess_type(filename)[0]
if not mimetype:
return False
return mimetype.startswith("image/") | def IsImage(self, filename) | Returns true if the filename has an image extension. | 2.757561 | 2.795107 | 0.986567 |
mimetype = mimetypes.guess_type(filename)[0]
if not mimetype:
return False # e.g. README, "real" binaries usually have an extension
# special case for text files which don't start with text/
if mimetype in TEXT_MIMETYPES:
return False
return not mimetype.startswith("text/") | def IsBinary(self, filename) | Returns true if the guessed mimetyped isnt't in text group. | 5.439786 | 5.251136 | 1.035925 |
assert filename.startswith(self.subdir), (filename, self.subdir)
return filename[len(self.subdir):].lstrip(r"\/") | def _GetRelPath(self, filename) | Get relative path of a file according to the current directory,
given its logical path in the repo. | 4.454809 | 4.853711 | 0.917815 |
args = []
status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
silent_ok=True)
unknown_files = []
for line in status.splitlines():
st, fn = line.split(" ", 1)
if st == "?":
unknown_files.append(fn)
return unknown_files | def GetUnknownFiles(self) | Return a list of files unknown to the VCS. | 4.318121 | 4.118052 | 1.048583 |
try:
v = int(s, 16)
except ValueError:
v = -1
if len(s) < 4 or len(s) > 6 or v < 0 or v > _RUNE_MAX:
raise InputError("invalid Unicode value %s" % (s,))
return v | def _UInt(s) | Converts string to Unicode code point ('263A' => 0x263a).
Args:
s: string to convert
Returns:
Unicode code point
Raises:
InputError: the string is not a valid Unicode value. | 4.548389 | 3.664402 | 1.241236 |
a = s.split("..")
if len(a) == 1:
return [_UInt(a[0])]
if len(a) == 2:
lo = _UInt(a[0])
hi = _UInt(a[1])
if lo < hi:
return range(lo, hi + 1)
raise InputError("invalid Unicode range %s" % (s,)) | def _URange(s) | Converts string to Unicode range.
'0001..0003' => [1, 2, 3].
'0001' => [1].
Args:
s: string to convert
Returns:
Unicode range
Raises:
InputError: the string is not a valid Unicode range. | 2.69616 | 2.540007 | 1.061478 |
match = re.match("<(.*), (First|Last)>", s)
if match is not None:
return match.groups()
return (s, None) | def _ParseContinue(s) | Parses a Unicode continuation field.
These are of the form '<Name, First>' or '<Name, Last>'.
Instead of giving an explicit range in a single table entry,
some Unicode tables use two entries, one for the first
code value in the range and one for the last.
The first entry's description is '<Name, First>' inst... | 7.726033 | 3.788352 | 2.039418 |
if nfields < 2:
raise InputError("invalid number of fields %d" % (nfields,))
if type(filename) == str:
if filename.startswith("http://"):
fil = urllib2.urlopen(filename)
else:
fil = open(filename, "r")
else:
fil = filename
first = None # first code in multiline range
e... | def ReadUnicodeTable(filename, nfields, doline) | Generic Unicode table text file reader.
The reader takes care of stripping out comments and also
parsing the two different ways that the Unicode tables specify
code ranges (using the .. notation and splitting the range across
multiple lines).
Each non-comment line in the table is expected to have the given
... | 3.945069 | 3.508339 | 1.124483 |
# Dict mapping lowercase code point to fold-equivalent group.
togroup = {}
def DoLine(codes, fields):
(_, foldtype, lower, _) = fields
if foldtype not in ("C", "S"):
return
lower = _UInt(lower)
togroup.setdefault(lower, [lower]).extend(codes)
ReadUnicodeTable(unicode_dir+"/CaseF... | def CaseGroups(unicode_dir=_UNICODE_DIR) | Returns list of Unicode code groups equivalent under case folding.
Each group is a sorted list of code points,
and the list of groups is sorted by first code point
in the group.
Args:
unicode_dir: Unicode data directory
Returns:
list of Unicode code groups | 8.587099 | 8.694222 | 0.987679 |
scripts = {}
def DoLine(codes, fields):
(_, name) = fields
scripts.setdefault(name, []).extend(codes)
ReadUnicodeTable(unicode_dir+"/Scripts.txt", 2, DoLine)
return scripts | def Scripts(unicode_dir=_UNICODE_DIR) | Returns dict mapping script names to code lists.
Args:
unicode_dir: Unicode data directory
Returns:
dict mapping script names to code lists | 10.622231 | 10.688947 | 0.993758 |
categories = {}
def DoLine(codes, fields):
category = fields[2]
categories.setdefault(category, []).extend(codes)
# Add codes from Lu into L, etc.
if len(category) > 1:
short = category[0]
categories.setdefault(short, []).extend(codes)
ReadUnicodeTable(unicode_dir+"/UnicodeD... | def Categories(unicode_dir=_UNICODE_DIR) | Returns dict mapping category names to code lists.
Args:
unicode_dir: Unicode data directory
Returns:
dict mapping category names to code lists | 7.270544 | 7.255011 | 1.002141 |
if interest_date is None:
interest_date = now().date()
bal = None
cur_date = None
daily_rate = rate_pct / Decimal(36500)
accum_interest = Decimal('0.00')
done = False
entries_list = list(entries)
nentries = len(entries_list)
if nentries > 0:
# make sure we calc... | def calculate_simple_interest(entries, rate_pct: Decimal, interest_date: date or None=None, begin: date or None=None) -> Decimal | Calculates simple interest of specified entries over time.
Does not accumulate interest to interest.
:param entries: AccountEntry iterable (e.g. list/QuerySet) ordered by timestamp (ascending)
:param rate_pct: Interest rate %, e.g. 8.00 for 8%
:param interest_date: Interest end date. Default is current ... | 2.756198 | 2.718678 | 1.013801 |
''' Creates a list-table directive
for a set of defined environment variables
Parameters:
name (str):
The name of the config section
command (object):
The sdss_access path instance
templates (dict):
A dictionary of the path templates
Yields:... | def _format_templates(name, command, templates) | Creates a list-table directive
for a set of defined environment variables
Parameters:
name (str):
The name of the config section
command (object):
The sdss_access path instance
templates (dict):
A dictionary of the path templates
Yields:
... | 4.437982 | 2.064835 | 2.149316 |
# the source name
source_name = name
# Title
section = nodes.section(
'',
nodes.title(text=name),
ids=[nodes.make_id(name)],
names=[nodes.fully_normalize_name(name)])
# Summarize
result = statemachine.ViewList()
... | def _generate_nodes(self, name, command, templates=None) | Generate the relevant Sphinx nodes.
Generates a section for the Tree datamodel. Formats a tree section
as a list-table directive.
Parameters:
name (str):
The name of the config to be documented, e.g. 'sdsswork'
command (object):
The load... | 4.23338 | 3.925857 | 1.078333 |
if a+1 == b:
if a%2 == 0:
return 'EvenOdd'
else:
return 'OddEven'
if a == b+1:
if a%2 == 0:
return 'OddEven'
else:
return 'EvenOdd'
return b - a | def _Delta(a, b) | Compute the delta for b - a. Even/odd and odd/even
are handled specially, as described above. | 3.107361 | 2.726908 | 1.139518 |
if type(delta) == int:
return a+delta
if delta == 'EvenOdd':
if a%2 == 0:
return a+1
else:
return a-1
if delta == 'OddEven':
if a%2 == 1:
return a+1
else:
return a-1
print >>sys.stderr, "Bad Delta: ", delta
raise "Bad Delta" | def _AddDelta(a, delta) | Return a + delta, handling EvenOdd and OddEven specially. | 2.766025 | 2.28902 | 1.208388 |
ranges = []
last = -100
def evenodd(last, a, b, r):
if a != last+1 or b != _AddDelta(a, r[2]):
return False
r[1] = a
return True
def evenoddpair(last, a, b, r):
if a != last+2:
return False
delta = r[2]
d = delta
if type(delta) is not str:
return False
if d... | def _MakeRanges(pairs) | Turn a list like [(65,97), (66, 98), ..., (90,122)]
into [(65, 90, +32)]. | 3.192197 | 3.209626 | 0.99457 |
rows = []
col_len = []
for line in lines:
line = str(line)
cols = []
for col_index, col in enumerate(line.split(column_separator)):
col = str(col).strip()
cols.append(col)
if col_index >= len(col_len):
col_len.append(0)
... | def align_lines(lines: list, column_separator: str='|') -> list | Pads lines so that all rows in single column match. Columns separated by '|' in every line.
:param lines: list of lines
:param column_separator: column separator. default is '|'
:return: list of lines | 1.731415 | 1.707266 | 1.014145 |
user = request.user
assert isinstance(user, User)
for obj in queryset:
assert isinstance(obj, Invoice)
admin_log([obj, user], 'Invoice id={invoice} marked for re-sending'.format(invoice=obj.id), who=user)
queryset.update(sent=None) | def resend_invoices(modeladmin, request: HttpRequest, queryset: QuerySet) | Marks invoices with as un-sent.
:param modeladmin:
:param request:
:param queryset:
:return: | 6.288842 | 6.502186 | 0.967189 |
for form in self.forms:
obj = form.instance
assert isinstance(obj, AccountEntry)
obj.account = account
obj.source_invoice = source_invoice
obj.settled_invoice = settled_invoice
if obj.parent:
if obj.amount is None:
... | def clean_entries(self, source_invoice: Invoice or None, settled_invoice: Invoice or None, account: Account, **kw) | This needs to be called from a derived class clean().
:param source_invoice:
:param settled_invoice:
:param account:
:return: None | 2.969046 | 2.938363 | 1.010442 |
if obj is None:
return ''
if isinstance(obj, datetime):
obj = obj.date()
return date_format(obj, 'SHORT_DATE_FORMAT') | def _format_date(self, obj) -> str | Short date format.
:param obj: date or datetime or None
:return: str | 3.361158 | 2.848626 | 1.179922 |
res = qs.aggregate(b=Sum(key))['b']
return default if res is None else res | def sum_queryset(qs: QuerySet, key: str= 'amount', default=Decimal(0)) -> Decimal | Returns aggregate sum of queryset 'amount' field.
:param qs: QuerySet
:param key: Field to sum (default: 'amount')
:param default: Default value if no results
:return: Sum of 'amount' field values (coalesced 0 if None) | 5.791281 | 8.050976 | 0.719327 |
self.blueprint_name, self.blueprint = build_blueprint(self, url_prefix)
return self.blueprint | def build_blueprint(self, url_prefix='') | Build a blueprint that contains the endpoints for callback URLs of
the current subscriber. Only call this once per instance. Arguments:
- url_prefix; this allows you to prefix the callback URLs in your app. | 4.818503 | 6.892134 | 0.699131 |
request = self.get_active_subscription(callback_id)
request['mode'] = 'unsubscribe'
self.subscribe_impl(callback_id, **request) | def unsubscribe(self, callback_id) | Ask the hub to cancel the subscription for callback_id, then delete
it from the local database if successful. | 7.466523 | 7.56695 | 0.986728 |
subscriptions = self.storage.close_to_expiration(margin_in_seconds)
for subscription in subscriptions:
try:
self.subscribe_impl(**subscription)
except SubscriberError as e:
warn(RENEW_FAILURE % (subscription['topic_url'],
... | def renew_close_to_expiration(self, margin_in_seconds=A_DAY) | Automatically renew subscriptions that are close to expiring, or
have already expired. margin_in_seconds determines if a subscription is
in fact close to expiring. By default, said margin is set to be a
single day (24 hours).
This is a long-running method for any non-trivial usage of th... | 7.833009 | 7.125381 | 1.099311 |
resp = get_content({'REQUEST_TIMEOUT': timeout}, url)
parser = LinkParser()
parser.hub_url = (resp.links.get('hub') or {}).get('url')
parser.topic_url = (resp.links.get('self') or {}).get('url')
try:
parser.updated()
for chunk in resp.iter_content(chunk_size=None, decode_unicod... | def discover(url, timeout=None) | Discover the hub url and topic url of a given url. Firstly, by inspecting
the page's headers, secondarily by inspecting the content for link tags.
timeout determines how long to wait for the url to load. It defaults to 3. | 4.554668 | 4.154113 | 1.096424 |
containing_dir = os.path.dirname(file_path)
fh = None
try:
if 'w' in mode:
os.chmod(containing_dir, mode=0o755)
fh = open(file_path, mode)
except OSError as e:
if 'w' in mode:
os.makedirs(containing_dir, mode=0o755, exist_ok=True)
os.chmo... | def open_tls_file(file_path, mode, private=True) | Context to ensure correct file permissions for certs and directories
Ensures:
- A containing directory with appropriate permissions
- Correct file permissions based on what the file is (0o600 for keys
and 0o644 for certs) | 2.057732 | 2.064089 | 0.99692 |
private = self.is_private()
with open_tls_file(self.file_path, 'r', private=private) as fh:
if private:
self.x509 = crypto.load_privatekey(self.encoding, fh.read())
else:
self.x509 = crypto.load_certificate(self.encoding, fh.read())
... | def load(self) | Load from a file and return an x509 object | 3.407449 | 3.117424 | 1.093034 |
self.x509 = x509
with open_tls_file(self.file_path, 'w',
private=self.is_private()) as fh:
fh.write(str(self)) | def save(self, x509) | Persist this x509 object to disk | 5.532141 | 5.270124 | 1.049717 |
for file_type in TLSFileType:
if file_type.value in files:
file_path = files[file_type.value]
setattr(self, file_type.value,
TLSFile(file_path, file_type=file_type)) | def _setup_tls_files(self, files) | Initiates TLSFIle objects with the paths given to this bundle | 3.365731 | 2.885369 | 1.166482 |
for file_type in TLSFileType:
if file_type.value in x509s:
x509 = x509s[file_type.value]
if file_type is not TLSFileType.CA:
# persist this key or cert to disk
tlsfile = getattr(self, file_type.value)
... | def save_x509s(self, x509s) | Saves the x509 objects to the paths known by this bundle | 4.072903 | 4.040936 | 1.007911 |
tf_list = [getattr(self, k, None) for k in
[_.value for _ in TLSFileType]]
# If a cert isn't defined in this bundle, remove it
tf_list = filter(lambda x: x, tf_list)
files = {tf.file_type.value: tf.file_path for tf in tf_list}
self.record['files'] = f... | def to_record(self) | Create a CertStore record from this TLSFileBundle | 7.35603 | 4.988144 | 1.474703 |
self.record = record
self._setup_tls_files(self.record['files'])
return self | def from_record(self, record) | Build a bundle from a CertStore record | 13.45565 | 11.300593 | 1.190703 |
with open(self.store_file_path, 'w') as fh:
fh.write(json.dumps(self.store, indent=4)) | def save(self) | Write the store dict to a file specified by store_file_path | 4.360605 | 2.515253 | 1.733665 |
with open(self.store_file_path, 'r') as fh:
self.store = json.loads(fh.read()) | def load(self) | Read the store dict from file | 4.918026 | 3.285191 | 1.497029 |
try:
record = self.store[common_name]
return record
except KeyError as e:
raise CertNotFoundError(
"Unable to find record of {name}"
.format(name=common_name), errors=e) | def get_record(self, common_name) | Return the record associated with this common name
In most cases, all that's really needed to use an existing cert are
the file paths to the files that make up that cert. This method
returns just that and doesn't bother loading the associated files. | 5.425533 | 4.843543 | 1.120158 |
record = self.get_record(common_name)
return TLSFileBundle(common_name).from_record(record) | def get_files(self, common_name) | Return a bundle of TLS files associated with a common name | 10.215303 | 5.98145 | 1.707831 |
if not overwrite:
try:
self.get_record(common_name)
raise CertExistsError(
"Certificate {name} already exists!"
" Set overwrite=True to force add."
.format(name=common_name))
except Cert... | def add_record(self, common_name, serial=0, parent_ca='',
signees=None, files=None, record=None,
is_ca=False, overwrite=False) | Manually create a record of certs
Generally, Certipy can be left to manage certificate locations and
storage, but it is occasionally useful to keep track of a set of
certs that were created externally (for example, let's encrypt) | 2.502714 | 2.552964 | 0.980317 |
if common_name in self.store and not overwrite:
raise CertExistsError(
"Certificate {name} already exists!"
" Set overwrite=True to force add."
.format(name=common_name))
elif common_name in self.store and overwrite:
recor... | def add_files(self, common_name, x509s, files=None, parent_ca='',
is_ca=False, signees=None, serial=0, overwrite=False) | Add a set files comprising a certificate to Certipy
Used with all the defaults, Certipy will manage creation of file paths
to be used to store these files to disk and automatically calls save
on all TLSFiles that it creates (and where it makes sense to). | 2.838991 | 2.918473 | 0.972766 |
ca_record = self.get_record(ca_name)
signee_record = self.get_record(signee_name)
signees = ca_record['signees'] or {}
signees = Counter(signees)
if signee_name in signees:
signees[signee_name] = 0
ca_record['signees'] = signees
signe... | def remove_sign_link(self, ca_name, signee_name) | Removes signee_name to the signee list for ca_name | 2.825988 | 2.814323 | 1.004145 |
record = self.get_record(common_name)
if fields is not None:
for field, value in fields:
record[field] = value
self.save()
return record | def update_record(self, common_name, **fields) | Update fields in an existing record | 3.608545 | 3.308322 | 1.090748 |
bundle = self.get_files(common_name)
num_signees = len(Counter(bundle.record['signees']))
if bundle.is_ca() and num_signees > 0:
raise CertificateAuthorityInUseError(
"Authority {name} has signed {x} certificates"
.format(name=common_name, x=... | def remove_record(self, common_name) | Delete the record associated with this common name | 4.865865 | 4.806912 | 1.012264 |
record = self.remove_record(common_name)
if delete_dir:
delete_dirs = []
if 'files' in record:
key_containing_dir = os.path.dirname(record['files']['key'])
delete_dirs.append(key_containing_dir)
cert_containing_dir = os.pa... | def remove_files(self, common_name, delete_dir=False) | Delete files and record associated with this common name | 2.728071 | 2.640906 | 1.033006 |
pkey = crypto.PKey()
pkey.generate_key(cert_type, bits)
return pkey | def create_key_pair(self, cert_type, bits) | Create a public/private key pair.
Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA
bits - Number of bits to use in the key
Returns: The public/private key pair in a PKey object | 3.685787 | 3.613722 | 1.019942 |
issuer_cert, issuer_key = issuer_cert_key
not_before, not_after = validity_period
cert = crypto.X509()
cert.set_serial_number(serial)
cert.gmtime_adj_notBefore(not_before)
cert.gmtime_adj_notAfter(not_after)
cert.set_issuer(issuer_cert.get_subject())
... | def sign(self, req, issuer_cert_key, validity_period, digest="sha256",
extensions=None, serial=0) | Generate a certificate given a certificate request.
Arguments: req - Certificate request to use
issuer_cert - The certificate of the issuer
issuer_key - The private key of the issuer
not_before - Timestamp (relative to now) when the
... | 1.631563 | 1.664853 | 0.980005 |
records = [rec for name, rec
in self.store.store.items() if name in names]
return self.create_bundle(
bundle_name, names=[r['parent_ca'] for r in records]) | def create_ca_bundle_for_names(self, bundle_name, names) | Create a CA bundle to trust only certs defined in names | 9.102063 | 9.378524 | 0.970522 |
if not names:
if ca_only:
names = []
for name, record in self.store.store.items():
if record['is_ca']:
names.append(name)
else:
names = self.store.store.keys()
out_file_path = o... | def create_bundle(self, bundle_name, names=None, ca_only=True) | Create a bundle of public certs for trust distribution
This will create a bundle of both CAs and/or regular certificates.
Arguments: names - The names of certs to include in the bundle
bundle_name - The name of the bundle file to output
Returns: Path to the bundle fil... | 2.776759 | 2.721346 | 1.020363 |
# Ensure there are CAs backing all graph components
def distinct_components(graph):
components = set(graph.keys())
for trusts in graph.values():
components |= set(trusts)
return components
# Default to creating a CA (inc... | def trust_from_graph(self, graph) | Create a set of trust bundles from a relationship graph.
Components in this sense are defined by unique CAs. This method assists
in setting up complicated trust between various components that need
to do TLS auth.
Arguments: graph - dict component:list(components)
Returns: dic... | 7.554822 | 6.28217 | 1.202582 |
cakey = self.create_key_pair(cert_type, bits)
req = self.create_request(cakey, CN=name)
signing_key = cakey
signing_cert = req
parent_ca = ''
if ca_name:
ca_bundle = self.store.get_files(ca_name)
signing_key = ca_bundle.key.load()
... | def create_ca(self, name, ca_name='', cert_type=crypto.TYPE_RSA, bits=2048,
alt_names=None, years=5, serial=0, pathlen=0,
overwrite=False) | Create a certificate authority
Arguments: name - The name of the CA
cert_type - The type of the cert. TYPE_RSA or TYPE_DSA
bits - The number of bits to use
alt_names - An array of alternative names in the format:
IP... | 3.064349 | 3.118761 | 0.982553 |
key = self.create_key_pair(cert_type, bits)
req = self.create_request(key, CN=name)
extensions = [
crypto.X509Extension(
b"extendedKeyUsage", True, b"serverAuth, clientAuth"),
]
if alt_names:
extensions.append(
cr... | def create_signed_pair(self, name, ca_name, cert_type=crypto.TYPE_RSA,
bits=2048, years=5, alt_names=None, serial=0,
overwrite=False) | Create a key-cert pair
Arguments: name - The name of the key-cert pair
ca_name - The name of the CA to sign this cert
cert_type - The type of the cert. TYPE_RSA or TYPE_DSA
bits - The number of bits to use
alt_names - An arra... | 3.419922 | 3.537856 | 0.966665 |
if updated_content:
body = base64.b64decode(updated_content['content'])
else:
body, updated_content = get_new_content(hub.config, topic_url)
b64_body = updated_content['content']
headers = updated_content['headers']
link_header = headers.get('Link', '')
if 'rel="hub"' not ... | def send_change_notification(hub, topic_url, updated_content=None) | 7. Content Distribution | 3.770018 | 3.685259 | 1.022999 |
for validate in hub.validators:
error = validate(callback_url, topic_url, lease_seconds, secret,
endpoint_hook_data)
if error:
send_denied(hub, callback_url, topic_url, error)
return
if intent_verified(hub, callback_url, 'subscribe', topic_... | def subscribe(hub, callback_url, topic_url, lease_seconds, secret,
endpoint_hook_data) | 5.2 Subscription Validation | 3.617283 | 3.41898 | 1.058001 |
challenge = uuid4()
params = {
'hub.mode': mode,
'hub.topic': topic_url,
'hub.challenge': challenge,
'hub.lease_seconds': lease_seconds,
}
try:
response = request_url(hub.config, 'GET', callback_url, params=params)
assert response.status_code == 200 ... | def intent_verified(hub, callback_url, mode, topic_url, lease_seconds) | 5.3 Hub Verifies Intent of the Subscriber | 3.15349 | 3.107328 | 1.014856 |
count = next(self.counter)
def task_with_hub(f, **opts):
@functools.wraps(f)
def wrapper(*args, **kwargs):
return f(self, *args, **kwargs)
# Make sure newer instances don't overwride older ones.
wrapper.__name__ = wrapper.__name_... | def init_celery(self, celery) | Registers the celery tasks on the hub object. | 4.105958 | 4.010879 | 1.023706 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.