text
stringlengths
18
773k
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...
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 ...
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 ...
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. """ # check if full alre...
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. ...
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 ...
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. """ ...
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 -...
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 inte...
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. ...
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...
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.s...
def change(ui, repo, *pats, **opts): """create, edit or delete a change list Create, edit or delete a change list. A change list is a group of files to be reviewed and submitted together, plus a textual description of the change. Change lists are referred to by simple alphanumeric names. Changes must be reviewe...
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. """ if repo[None].branch() != "default": raise hg_util.Abort("cannot run hg undo outsi...
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 ...
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. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) cl, vers, patch, err = DownloadCL(u...
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. """ if codereview_disabled: raise...
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. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) files = ChangedExistingFiles(ui, repo, pats, opts) files = gofmt_required(files) if n...
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. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) cl, err = CommandLineCL(ui, repo, pats, opts, op="mail", defaultcc=...
def ps(ui, repo, *pats, **opts): """alias for hg p --short """ opts['short'] = True return pending(ui, repo, *pats, **opts)
def pq(ui, repo, *pats, **opts): """alias for hg p --quick """ opts['quick'] = True return pending(ui, repo, *pats, **opts)
def pending(ui, repo, *pats, **opts): """show pending changes Lists pending changes followed by a list of unassigned but modified files. """ 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...
def submit(ui, repo, *pats, **opts): """submit change to remote repository Submits change to remote repository. Bails out if the local repository is not in sync with the remote one. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) # We already called this on startup but sometimes Mercurial...
def sync(ui, repo, **opts): """synchronize with remote repository Incorporates recent changes from the remote repository into the local repository. """ 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...
def upload(ui, repo, name, **opts): """upload diffs to the code review server Uploads the current modifications for a given change to the server. """ 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....
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.""" try: return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs) except Exception, e: if type(e) !=...
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 emp...
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 n...
def GetRpcServer(options): """Returns an instance of an AbstractRpcServer. Returns: A new AbstractRpcServer, on which RPC calls can be made. """ rpc_server_class = HttpRpcServer def GetUserCredentials(): """Prompts the user for a username and password.""" # Disable status prints so they don't obscure the ...
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.HT...
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 igno...
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. """ patches = [] filename = None diff = [] for line in data.splitline...
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. """ patches = SplitPatch(data) rv = [] for patch in patches: set_status("uploading patch for " + patch[0]) if len(patch[1...
def _CreateRequest(self, url, data=None): """Creates a new urllib request.""" 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(): ...
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 ...
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. """ # This is a dummy value to allow us to identify whe...
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 /_...
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 requ...
def _Authenticate(self): """Save the cookie jar after authentication.""" super(HttpRpcServer, self)._Authenticate() if self.save_cookies: StatusUpdate("Saving authentication cookies to %s" % self.cookie_file) self.cookie_jar.save()
def _GetOpener(self): """Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object. """ opener = urllib2.OpenerDirector() opener.add_handler(urllib2.ProxyHandler()) opener.add_handler(urllib2.UnknownHandler()) opener.add_handler(urllib2.HTTPHandler...
def CheckForUnknownFiles(self): """Show an "are you sure?" prompt if there are unknown files.""" 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) " a...
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:". """ files = {} for line in diff.splitlines(Tru...
def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options, files): """Uploads the base files (and if necessary, the current ones as well).""" def UploadFile(filename, file_id, content, is_binary, status, is_base): """Uploads a file to the server.""" set_status("uploading " + filen...
def IsImage(self, filename): """Returns true if the filename has an image extension.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False return mimetype.startswith("image/")
def IsBinary(self, filename): """Returns true if the guessed mimetyped isnt't in text group.""" 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...
def _GetRelPath(self, filename): """Get relative path of a file according to the current directory, given its logical path in the repo.""" assert filename.startswith(self.subdir), (filename, self.subdir) return filename[len(self.subdir):].lstrip(r"\/")
def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" 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) re...
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. """ try: v = int(s, 16) except ValueError: v = -1 if len(s) < 4 or len(s) > 6 or v < 0 or...
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. """ a = s.split("..") if len(a) == 1: return [_UInt(a[0])] if len(a) =...
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 descrip...
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-co...
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 gr...
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 """ scripts = {} def DoLine(codes, fields): """Process single Scripts.txt line, updating scripts.""" (_, n...
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 """ categories = {} def DoLine(codes, fields): """Process single UnicodeData.txt line, updating categor...
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...
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): ...
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...
def _Delta(a, b): """Compute the delta for b - a. Even/odd and odd/even are handled specially, as described above.""" 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 _AddDelta(a, delta): """Return a + delta, handling EvenOdd and OddEven specially.""" 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...
def _MakeRanges(pairs): """Turn a list like [(65,97), (66, 98), ..., (90,122)] into [(65, 90, +32)].""" 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: ...
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 """ rows = [] col_...
def resend_invoices(modeladmin, request: HttpRequest, queryset: QuerySet): """ Marks invoices with as un-sent. :param modeladmin: :param request: :param queryset: :return: """ user = request.user assert isinstance(user, User) for obj in queryset: assert isinstance(obj, In...
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 """ f...
def _format_date(self, obj) -> str: """ Short date format. :param obj: date or datetime or None :return: str """ if obj is None: return '' if isinstance(obj, datetime): obj = obj.date() return date_format(obj, 'SHORT_DATE_FORMAT')
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...
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. """ self.blueprint_name, s...
def unsubscribe(self, callback_id): """Ask the hub to cancel the subscription for callback_id, then delete it from the local database if successful. """ request = self.get_active_subscription(callback_id) request['mode'] = 'unsubscribe' self.subscribe_impl(callback_id, *...
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...
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. """ resp = get_content({'REQUEST_TIMEOUT...
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) """ ...
def load(self): """Load from a file and return an x509 object""" 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: sel...
def save(self, x509): """Persist this x509 object to disk""" self.x509 = x509 with open_tls_file(self.file_path, 'w', private=self.is_private()) as fh: fh.write(str(self))
def _setup_tls_files(self, files): """Initiates TLSFIle objects with the paths given to this bundle""" for file_type in TLSFileType: if file_type.value in files: file_path = files[file_type.value] setattr(self, file_type.value, TLSFile...
def save_x509s(self, x509s): """Saves the x509 objects to the paths known by this bundle""" 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 ...
def to_record(self): """Create a CertStore record from this TLSFileBundle""" 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_...
def from_record(self, record): """Build a bundle from a CertStore record""" self.record = record self._setup_tls_files(self.record['files']) return self
def save(self): """Write the store dict to a file specified by store_file_path""" with open(self.store_file_path, 'w') as fh: fh.write(json.dumps(self.store, indent=4))
def load(self): """Read the store dict from file""" with open(self.store_file_path, 'r') as fh: self.store = json.loads(fh.read())
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....
def get_files(self, common_name): """Return a bundle of TLS files associated with a common name""" record = self.get_record(common_name) return TLSFileBundle(common_name).from_record(record)
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 occasi...
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 file...
def remove_sign_link(self, ca_name, signee_name): """Removes signee_name to the signee list for ca_name""" 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 ...
def update_record(self, common_name, **fields): """Update fields in an existing record""" record = self.get_record(common_name) if fields is not None: for field, value in fields: record[field] = value self.save() return record
def remove_record(self, common_name): """Delete the record associated with this common name""" bundle = self.get_files(common_name) num_signees = len(Counter(bundle.record['signees'])) if bundle.is_ca() and num_signees > 0: raise CertificateAuthorityInUseError( ...
def remove_files(self, common_name, delete_dir=False): """Delete files and record associated with this common name""" record = self.remove_record(common_name) if delete_dir: delete_dirs = [] if 'files' in record: key_containing_dir = os.path.dirname(recor...
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 """ pkey...
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 ...
def create_ca_bundle_for_names(self, bundle_name, names): """Create a CA bundle to trust only certs defined in names """ records = [rec for name, rec in self.store.store.items() if name in names] return self.create_bundle( bundle_name, names=[r['parent_ca'...
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 ...
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 com...
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 ...
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 ...
def send_change_notification(hub, topic_url, updated_content=None): """7. Content Distribution""" 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'] heade...
def subscribe(hub, callback_url, topic_url, lease_seconds, secret, endpoint_hook_data): """5.2 Subscription Validation""" for validate in hub.validators: error = validate(callback_url, topic_url, lease_seconds, secret, endpoint_hook_data) if error: ...
def intent_verified(hub, callback_url, mode, topic_url, lease_seconds): """ 5.3 Hub Verifies Intent of the Subscriber""" challenge = uuid4() params = { 'hub.mode': mode, 'hub.topic': topic_url, 'hub.challenge': challenge, 'hub.lease_seconds': lease_seconds, } try: ...
def init_celery(self, celery): """Registers the celery tasks on the hub object.""" 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 in...
def init_publisher(app): """Calling this with your flask app as argument is required for the publisher decorator to work. """ @app.context_processor def inject_links(): return { 'websub_self_url': stack.top.websub_self_url, 'websub_hub_url': stack.top.websub_hub_url,...
def publisher(self_url=None, hub_url=None): """This decorator makes it easier to implement a websub publisher. You use it on an endpoint, and Link headers will automatically be added. To also include these links in your template html/atom/rss (and you should!) you can use the following to get the raw li...
def count_results(cube, q): """ Get the count of records matching the query. """ q = select(columns=[func.count(True)], from_obj=q.alias()) return cube.engine.execute(q).scalar()