code
stringlengths
1
18.2k
def sanitize_tex(original_text): """Sanitize TeX text. :param original_text: the text to sanitize for LaTeX. :type original_text: str :returns: the sanitize text. Text is sanitized by following these steps: 1. Replaces ``\\` by ``\\textbackslash`` 2. Escapes certain characters (such as ``$``, ``%``, ``_``, ``}``, ``{``...
def main(self, symbol): """ :param symbol: Bit to modulate :return: Modulated signal in baseband :rtype: Complex """ if symbol: phase_step = self.sensitivity_pos else: phase_step = self.sensitivity_neg cout = self.nco.main(phase_step) return cout
def contextMenuEvent(self, event): """ Add menu action: * 'Show line numbers' * 'Save to file' """ menu = QtWidgets.QPlainTextEdit.createStandardContextMenu(self) mg = self.getGlobalsMenu() a0 = menu.actions()[0] menu.insertMenu(a0, mg) menu.insertSeparator(a0) menu.addSeparator() a = QtWidgets.QAction('Show line numbe...
def saveToFile(self): """ Save the current text to file """ filename = self.codeEditor.dialog.getSaveFileName() if filename and filename != '.': with open(filename, 'w') as f: f.write(self.toPlainText()) print('saved script under %s' % filename)
def _updateNumbers(self, linenumers): """ add/remove line numbers """ b = self.blockCount() c = b - linenumers if c > 0: # remove lines numbers for _ in range(c): # remove last line: self.setFocus() storeCursorPos = self.textCursor() self.moveCursor( QtGui.QTextCursor.End, QtGui.QTextCursor.MoveAnchor) self.moveCursor(...
def publish(self, payload): '''Publish payload to the topic .. note:: If you publishes just after creating Publisher instance, it will causes lost of message. You have to add sleep if you just want to publish once. >>> pub = jps.Publisher('topic') >>> time.sleep(0.1) >>> pub.publish('{data}') :param payload: data to be...
def formatrow(self, types, values, wanttupledate): """ Internal function used to clean up the incoming excel data """ ## Data Type Codes: ## EMPTY 0 ## TEXT 1 a Unicode string ## NUMBER 2 float ## DATE 3 float ## BOOLEAN 4 int; 1 means TRUE, 0 means FALSE ## ERROR 5 returnrow = [] for i in range(len(types)): type,value...
value = "%04d-%02d-%02d" % datetuple[:3] else: # full date value = "%04d-%02d-%02d %02d:%02d:%02d" % datetuple elif type == 5: value = xlrd.error_text_from_code[value] returnrow.append(value) return returnrow
def main(self, input): """ :type input: Complex :rtype: Sfix """ demod = self.demod.main(input) match = self.match.main(demod) return match
def connect(self, hostname, family, hostaddr): """ Log new connections. """ self.client_ip = hostaddr[0] self.client_port = hostaddr[1] self.time_start = time.time() logger.debug('<{}> Connect from {}[{}]:{}'.format( self.id, hostname, self.client_ip, self.client_port)) return Milter.CONTINUE
def envrcpt(self, rcpt, *params): """ Send all recipients to DSPAM. """ if rcpt.startswith('<'): rcpt = rcpt[1:] if rcpt.endswith('>'): rcpt = rcpt[:-1] if self.recipient_delimiter_re: rcpt = self.recipient_delimiter_re.sub('', rcpt) if rcpt not in self.recipients: self.recipients.append(rcpt) logger.debug('<{}> Receiv...
def header(self, name, value): """ Store all message headers, optionally clean them up. This simply stores all message headers so we can send them to DSPAM. Additionally, headers that have the same prefix as the ones we're about to add are deleted. """ self.message += "{}: {}\r\n".format(name, value) logger.debug('<{}>...
def body(self, block): """ Store message body. """ self.message += block logger.debug('<{}> Received {} bytes of message body'.format( self.id, len(block))) return Milter.CONTINUE
def eom(self): """ Send the message to DSPAM for classification and a return a milter response based on the results. If <DspamMilter>.static_user is set, that single DSPAM user account will be used for processing the message. If it is unset, all envelope recipients will be passed to DSPAM, and the final decision is bas...
error ocurred while connecting to DSPAM: {}'.format( self.id, err)) return Milter.TEMPFAIL try: self.dspam.mailfrom(client_args='--process --deliver=summary') if self.static_user: self.dspam.rcptto((self.static_user,)) else: self.dspam.rcptto(self.recipients) self.dspam.data(self.message) except DspamClientError as err...
logger.info( '<{0}> Rejecting message with queue id {1} based on DSPAM ' 'results: user={2[user]} class={2[class]} ' 'confidence={2[confidence]}'.format( self.id, queue_id, final_results)) self.setreply('550', '5.7.1', 'Message is {0[class]}'.format( final_results)) return Milter.REJECT elif final_verdict == self.VERDI...
def close(self): """ Log disconnects. """ time_spent = time.time() - self.time_start logger.debug( '<{}> Disconnect from [{}]:{}, time spent {:.3f} seconds'.format( self.id, self.client_ip, self.client_port, time_spent)) return Milter.CONTINUE
def compute_verdict(self, results): """ Match results to the configured reject, quarantine and accept classes, and return a verdict based on that. The verdict classes are matched in the order: reject_classes, quarantine_classes, accept_classes. This means that you can configure different verdicts for different confiden...
threshold: logger.debug( '<{0}> Suggesting to quarantine the message based on ' 'DSPAM results: user={1[user]}, class={1[class]}, ' 'confidence={1[confidence]}'.format(self.id, results)) return self.VERDICT_QUARANTINE if results['class'] in self.accept_classes: threshold = self.accept_classes[results['class']] if float...
def add_dspam_headers(self, results): """ Format DSPAM headers with passed results, and add them to the message. Args: results -- A results dictionary from DspamClient. """ for header in self.headers: hname = self.header_prefix + header if header.lower() in results: hvalue = results[header.lower()] logger.debug( '<{}> ...
def configure(self, config_file): """ Parse configuration, and setup objects to use it. """ cfg = configparser.RawConfigParser() try: cfg.readfp(open(config_file)) except IOError as err: logger.critical( 'Error while reading config file {}: {}'.format( config_file, err.strerror)) sys.exit(1) logger.info('Parsed config ...
'reject_classes', 'quarantine_classes', 'accept_classes' ] for option in cfg.options(section): # Kludge: static_user needs to be set on the milter, # not on the client if section == 'dspam' and option == 'static_user': value = cfg.get('dspam', 'static_user') DspamMilter.static_user = value logger.debug( 'Config option ...
def list_instances( deployment_name='', cloud_name='EC2 us-east-1', view='tiny', ): """ Returns a list of instances from your account. :param str deployment_name: If provided, only lists servers in the specified deployment. :param str cloud_name: The friendly name for a RightScale-supported cloud. E.g. ``EC2 us-east-1`...
def run_script_on_server( script_name, server_name, inputs=None, timeout_s=10, output=sys.stdout ): """ Runs a RightScript and polls for status. Sample usage:: from rightscale import run_script_on_server run_script_on_server( 'my cool bob lol script', 'some server', inputs={'BOB': 'blah blah', 'LOL': 'fubar'}, ) Sample...
status = api.client.get(status_path).json() summary = status.get('summary', '') output.write('status: %s\n' % summary) if summary.startswith('completed'): return time.sleep(1) output.write('Done waiting. Poll %s for status.\n' % status_path)
def get_by_path(path, first=False): """ Search for resources using colon-separated path notation. E.g.:: path = 'deployments:production:servers:haproxy' haproxies = get_by_path(path) :param bool first: Always use the first returned match for all intermediate searches along the path. If this is ``False`` and an intermed...
def Rizk(mp, dp, rhog, D): r'''Calculates saltation velocity of the gas for pneumatic conveying, according to [1]_ as described in [2]_ and many others. .. math:: \mu=\left(\frac{1}{10^{1440d_p+1.96}}\right)\left(Fr_s\right)^{1100d_p+2.5} Fr_s = \frac{V_{salt}}{\sqrt{gD}} \mu = \frac{m_p}{\frac{\pi}{4}D^2V \rho_f} Para...
(1973) .. [2] Klinzing, G. E., F. Rizk, R. Marcus, and L. S. Leung. Pneumatic Conveying of Solids: A Theoretical and Practical Approach. Springer, 2013. .. [3] Rhodes, Martin J. Introduction to Particle Technology. Wiley, 2013. ''' alpha = 1440*dp + 1.96 beta = 1100*dp + 2.5 term1 = 1./10**alpha Frs_sorta = 1/(g*D)**0....
def Matsumoto_1977(mp, rhop, dp, rhog, D, Vterminal=1): r'''Calculates saltation velocity of the gas for pneumatic conveying, according to [1]_ and reproduced in [2]_, [3]_, and [4]_. First equation is used if third equation yeilds d* higher than dp. Otherwise, use equation 2. .. math:: \mu = 5560\left(\frac{d_p}{D}\ri...
explicit in terms of saltation velocity internally. Examples -------- Example is only a self-test. Course routine, terminal velocity input is from example in [2]. >>> Matsumoto_1977(mp=1., rhop=1000., dp=1E-3, rhog=1.2, D=0.1, Vterminal=5.24) 16.64284834446686 References ---------- .. [1] Matsumoto, Shigeru, Makoto Kik...
[4] Rabinovich, Evgeny, and Haim Kalman. "Threshold Velocities of Particle-Fluid Flows in Horizontal Pipes and Ducts: Literature Review." Reviews in Chemical Engineering 27, no. 5-6 (January 1, 2011). doi:10.1515/REVCE.2011.011. ''' limit = 1.39*D*(rhop/rhog)**-0.74 A = pi/4*D**2 if limit < dp: # Corase routine Frp = V...
def Weber(mp, rhop, dp, rhog, D, Vterminal=4): r'''Calculates saltation velocity of the gas for pneumatic conveying, according to [1]_ as described in [2]_, [3]_, [4]_, and [5]_. If Vterminal is under 3 m/s, use equation 1; otherwise, equation 2. .. math:: Fr_s = \left(7 + \frac{8}{3}V_{terminal}\right)\mu^{0.25} \left...
-------- Examples are only a self-test. >>> Weber(mp=1, rhop=1000., dp=1E-3, rhog=1.2, D=0.1, Vterminal=4) 15.227445436331474 References ---------- .. [1] Weber, M. 1981. Principles of hydraulic and pneumatic conveying in pipes. Bulk Solids Handling 1: 57-63. .. [2] Rabinovich, Evgeny, and Haim Kalman. "Threshold Veloc...
[5] Gomes, L. M., and A. L. Amarante Mesquita. "On the Prediction of Pickup and Saltation Velocities in Pneumatic Conveying." Brazilian Journal of Chemical Engineering 31, no. 1 (March 2014): 35-46. doi:10.1590/S0104-66322014000100005 ''' if Vterminal <= 3: term1 = (7 + 8/3.*Vterminal)*(dp/D)**0.1 else: term1 = 15.*(dp...
def Geldart_Ling(mp, rhog, D, mug): r'''Calculates saltation velocity of the gas for pneumatic conveying, according to [1]_ as described in [2]_ and [3]_. if Gs/D < 47000, use equation 1, otherwise use equation 2. .. math:: V_{salt} = 1.5G_s^{0.465}D^{-0.01} \mu^{0.055}\rho_f^{-0.42} V_{salt} = 8.7G_s^{0.302}D^{0.153} ...
and pneumatic conveying in pipes. Bulk Solids Handling 1: 57-63. .. [2] Rabinovich, Evgeny, and Haim Kalman. "Threshold Velocities of Particle-Fluid Flows in Horizontal Pipes and Ducts: Literature Review." Reviews in Chemical Engineering 27, no. 5-6 (January 1, 2011). doi:10.1515/REVCE.2011.011. .. [3] Gomes, L. M., an...
def plot(x, y, z, ax=None, **kwargs): r""" Plot iso-probability mass function, converted to sigmas. Parameters ---------- x, y, z : numpy arrays Same as arguments to :func:`matplotlib.pyplot.contour` ax: axes object, optional :class:`matplotlib.axes._subplots.AxesSubplot` to plot the contours onto. If unsupplied, then ...
True) rasterize_contours: bool, optional Rasterize the contours while keeping the lines, text etc in vector format. Useful for reducing file size bloat and making printing easier when you have dense contours. (Default: False) Returns ------- cbar: color bar :class:`matplotlib.contour.QuadContourSet` Colors to create a ...
smooth% if smooth: sigma = smooth*numpy.array(z.shape)/100.0 z = scipy.ndimage.gaussian_filter(z, sigma=sigma, order=0) # Plot the filled contours onto the axis ax cbar = ax.contourf(x, y, z, cmap=colors, levels=contour_color_levels) # Rasterize contours (the rest of the figure stays in vector format) if rasterize_cont...
def plot_lines(x, fsamps, ax=None, downsample=100, **kwargs): """ Plot function samples as a set of line plots. Parameters ---------- x: 1D array-like x values to plot fsamps: 2D array-like set of functions to plot at each x. As returned by :func:`fgivenx.compute_samples` ax: axes object :class:`matplotlib.pyplot.ax` t...
def add_content(self, more_content): """Add content from source docs and user.""" sourcename = self.get_sourcename() if self.object.docs: self.add_line('', sourcename) for line in self.object.docs.splitlines(): self.add_line(line, sourcename) # add additional content (e.g. from document), if present if more_content: se...
def document_members(self, all_members=False): # type: (bool) -> None """Generate reST for member documentation. If *all_members* is True, do all members, else those given by *self.options.members*. """ sourcename = self.get_sourcename() want_all = all_members or self.options.members is ALL if not want_all and not self...
self.options.exclude_members.remove('constructor') should_exclude_constructor = True expr = SolidityObject.name.not_in(self.options.exclude_members) subexpr = SolidityObject.name.is_null(True) if should_exclude_fallback: subexpr &= (SolidityObject.objtype != 'function') if should_exclude_constructor: subexpr &= (Solidi...
def generate(self, more_content=None, all_members=False): # type: (Any, str, bool, bool) -> None """Generate reST for the object given by *self.name*, and possibly for its members. If *more_content* is given, include that content. If *all_members* is True, document all members. """ directive = getattr(self, 'directivet...
expressions.append(SolidityObject.contract_name == contract_name) if paramtypes: expressions.append(SolidityObject.paramtypes == paramtypes) # get associated object query = SolidityObject.select().where(*expressions) sol_objects = tuple(query) if len(sol_objects) == 0: logger.warning('{} {} could not be found via query...
content is indented # TODO: consider adding a source unit directive self.indent += self.content_indent # add all content (from docstrings, attribute docs etc.) self.add_content(more_content) # document members, if possible if directive in ('contract', 'interface', 'library'): self.add_line('', sourcename) self.document...
def addParameter( self, k, r ): """Add a parameter to the experiment's parameter space. k is the parameter name, and r is its range. :param k: parameter name :param r: parameter range""" if isinstance(r, six.string_types) or not isinstance(r, collections.Iterable): # range is a single value (where a string constitutes ...
def _crossProduct( self, ls ): """Internal method to generate the cross product of all parameter values, creating the parameter space for the experiment. :param ls: an array of parameter names :returns: list of dicts""" p = ls[0] ds = [] if len(ls) == 1: # last parameter, convert range to a dict for i in self._paramete...
def parameterSpace( self ): """Return the parameter space of the experiment as a list of dicts, with each dict mapping each parameter name to a value. :returns: the parameter space as a list of dicts""" ps = self.parameters() if len(ps) == 0: return [] else: return self._crossProduct(ps)
def runExperiment( self, e ): """Run an experiment over all the points in the parameter space. The results will be stored in the notebook. :param e: the experiment""" # create the parameter space ps = self.parameterSpace() # run the experiment at each point nb = self.notebook() for p in ps: #print "Running {p}".format(...
def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True): """Evaluates by creating an Index containing evaluated data. See `LazyResult` Returns ------- Index Index with evaluated data. """ if self.start == 0 and self.stop == 0: evaluated_data = np.empty(0, dtype=np.int64) else...
def _getsetting(setting, default): """Get `setting` if set, fallback to `default` if not This method tries to return the value of the specified setting from Django's settings module, after prefixing the name with _DJANGO_SETTING_PREFIX. If this fails for any reason, the value supplied in `default` will be returned inst...
def _setsetting(setting, default): """Dynamically sets the variable named in `setting` This method uses `_getsetting()` to either fetch the setting from Django's settings module, or else fallback to the default value; it then sets a variable in this module with the returned value. """ value = _getsetting(setting, defau...
def runPlink(options): """Run Plink with the ``mind`` option. :param options: the options. :type options: argparse.Namespace """ # The plink command plinkCommand = [ "plink", "--noweb", "--bfile" if options.is_bfile else "--tfile", options.ifile, "--mind", str(options.mind), "--make-bed", "--out", options.out, ] output...
def checkArgs(args): """Checks the arguments and options. :param args: a object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to th...
% args.mind raise ProgramError(msg) return True
def hash_key(*args, **kwargs): """Return a cache key for the specified hashable arguments.""" if kwargs: return cachetools.keys._HashedTuple(args + _kwargs_mark + tuple(itertools.chain(sorted(kwargs.items())))) else: return cachetools.keys._HashedTuple(args)
def typed_hash_key(*args, **kwargs): """Return a typed cache key for the specified hashable arguments.""" key = hash_key(*args, **kwargs) key += tuple(type(v) for v in args) key += tuple(type(v) for _, v in sorted(kwargs.items())) return key
def attribute_dependend_key(key_function, *dependencies): """Return a cache key for the specified hashable arguments with additional dependent arguments.""" def dependend_key_function(self, *args, **kwargs): key = hash_key(*args, **kwargs) if len(dependencies) > 0: dependecies_dict = {} for dependency in dependencies: ...
def raw(func, **func_args): """Decorator for eager functions checking input array and stripping away the weld_type. Stripping the weld_type is required to keep the same code in Series.apply and because Numpy functions don't (all) have kwargs. Passing weld_type to NumPy functions is unexpected and raises ValueError. Par...
if isinstance(array, WeldObject): raise TypeError('Can only perform operation on raw data') return func(array, **func_args) return wrapper
def AssertRC(self, rc=0): """ Assert used for testing on certain RC values :raises: ``AssertionError`` """ assert self.rc == rc, "Command `%s` failed. $? expected: %d, $? given: %d" % (self.command, rc, self.rc)
def command(cls, command, stdin=None, shell=False): """ Runs specified command. The command can be fed with data on stdin with parameter ``stdin``. The command can also be treated as a shell command with parameter ``shell``. Please refer to subprocess.Popen on how does this stuff work :returns: Run() instance with resu...
def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental_transforms=True): """Evaluate the stored expression. Parameters ---------- verbose : bool, optional Whether to print output for each Weld compilation step. decode : bool, optional Whether to decode the result passes : list, op...
def numpy_to_weld_type(np_dtype): """Convert from NumPy dtype to Weld type. Note that support for strings is intended to be only for Python 2 str and Python 3 bytes. No unicode. Parameters ---------- np_dtype : numpy.dtype or str NumPy dtype. Returns ------- WeldType Corresponding WeldType. Examples -------- >>> import...
def run(filepath, wsgiapp, host, port, reload, interval, static, static_root, static_dirs, lineprof, lineprof_file, validate): """ Runs a development server for WSGI Application. Usage: $ wsgicli run hello.py app -h 0.0.0.0 -p 5000 --reload $ wsgicli run hello.py app --static --static-root /static/ --static-dirs ./stat...
host=host, port=port)
def insert_import_path_to_sys_modules(import_path): """ When importing a module, Python references the directories in sys.path. The default value of sys.path varies depending on the system, But: When you start Python with a script, the directory of the script is inserted into sys.path[0]. So we have to replace sys.path...
def shell(filepath, wsgiapp, interpreter, models): """ Runs a python shell. Usage: $ wsgicli shell app.py app -i ipython """ model_base_classes = get_model_base_classes() imported_objects = {} if models and model_base_classes: insert_import_path_to_sys_modules(filepath) for module in find_modules_from_path(filepath): f...
def kadd(self, key, value): """Adds the given key/value to all elements. Single values for a key are stored directly, as key:value, multiple values for the same key are stored as key,set(values). """ for item in self: try: # Use the key as a set item[key].add(value) except KeyError: # This happens if the key is not pre...
def kreplace(self, key, value): """Replaces the given key/value for each element. If the key is not present silently passes. """ for item in self: if key in item: item[key] = value
def kremove(self, key, value=None): """Removes the given key/value from all elements. If value is not specified, the whole key is removed. If value is not None and the key is present but with a different value, or if the key is not present, silently passes. """ for item in self: if value is None: # Just pop the key if ...
a set # and shall be removed only if values match if item[key] == value: item.pop(key)
def dfilter(self, **kwds): """Returns a DictRegister which contains only the elements that match the given specifications. """ starting_list = self[:] filtered_list = [] for key, value in six.iteritems(kwds): for item in starting_list: if self._match(item, key, value): filtered_list.append(item) starting_list = filtere...
def dpop(self, **kwds): """Pops and returns the first element that matches the given specification. If no elements are found raises IndexError. """ item = self.dget(**kwds) self.remove(item) return item
def dremove(self, **kwds): """Removes from the object any element that matches the given specification. """ filtered_dr = self.dfilter(**kwds) for item in filtered_dr: self.remove(item) return filtered_dr
def dremove_copy(self, **kwds): """Returns a copy of the object without any element that matches the given specification. """ copy_dr = DictRegister(self) copy_dr.dremove(**kwds) return copy_dr
def get_media_with_naming (output_dir, media_url, uuid, size): """ Download a media file to a directory and name it based on the input parameters. 'output_dir' controls where the download is placed. 'media_url' is the url / link to the media that will be downloaded. 'uuid' is used to uniquely identify the output filena...
form: {mediarecord_uuid}_{SIZE}.jpg local_filepath = os.path.join(output_dir, uuid + '_' + SIZE + '.jpg') try: with open(local_filepath, 'wb') as out_file: shutil.copyfileobj(response.raw, out_file) return True except: return False
def main(args=sys.argv[1:]): """Run the commandline script""" usage = "%prog --help" parser = OptionParser(usage, add_help_option=False) parser.add_option('-c', '--config', help="Configuration file to use", action='store', type='string', dest='config_file') parser.add_option('-h', '-H', '--host', help=("Hostname of the...
overrides config file settings if options.host: client = trovebox.Trovebox(host=options.host) else: try: client = trovebox.Trovebox(config_file=options.config_file) except IOError as error: print(error) print(CONFIG_ERROR) print(error) sys.exit(1) if options.method == "GET": result = client.get(options.endpoint, proces...
def extract_files(params): """ Extract filenames from the "photo" parameter so they can be uploaded, returning (updated_params, files). Uses the same technique as the Trovebox PHP commandline tool: * Filename can only be in the "photo" parameter * Filename must be prefixed with "@" * Filename must exist ...otherwise th...
def extend_webfont_settings(webfont_settings): """ Validate a webfont settings and optionally fill missing ``csspart_path`` option. Args: webfont_settings (dict): Webfont settings (an item value from ``settings.ICOMOON_WEBFONTS``). Returns: dict: Webfont settings """ if not webfont_settings.get('fontdir_path', False): ...
def main(url, lamson_host, lamson_port, lamson_debug): """ Create, connect, and block on the Lamson worker. """ try: worker = LamsonWorker(url=url, lamson_host=lamson_host, lamson_port=lamson_port, lamson_debug=lamson_debug) worker.connect() worker.run_forever() except KeyboardInterrupt: worker.close()
def received_new(self, msg): """ As new messages arrive, deliver them to the lamson relay. """ logger.info("Receiving msg, delivering to Lamson...") logger.debug("Relaying msg to lamson: From: %s, To: %s", msg['From'], msg['To']) self._relay.deliver(msg)
def validate(**vkargs): """ Validates and manipulates keyword arguments by user defined callables. Handles ValueError and missing arguments by raising HTTPError(403). """ depr('Use route wildcard filters instead.') def decorator(func): @functools.wraps(func) def wrapper(*args, **kargs): for key, value in vkargs.items()...
def mount(self, prefix, app, **options): ''' Mount an application (:class:`Bottle` or plain WSGI) to a specific URL prefix. Example:: root_app.mount('/admin/', admin_app) :param prefix: path prefix or `mount-point`. If it ends in a slash, that slash is mandatory. :param app: an instance of :class:`Bottle` or a WSGI app...
return HTTPResponse(rs.body, rs.status_code, rs.headers) finally: request.path_shift(-path_depth) if not prefix.endswith('/'): self.route('/' + '/'.join(parts), callback=mountpoint, **options)
def query(self): ''' The :attr:`query_string` parsed into a :class:`FormsDict`. These values are sometimes called "URL arguments" or "GET parameters", but not to be confused with "URL wildcards" as they are provided by the :class:`Router`. ''' pairs = parse_qsl(self.query_string, keep_blank_values=True) get = self.envi...
def forms(self): """ Form values parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The result is retuned as a :class:`FormsDict`. All keys and values are strings. File uploads are stored separately in :attr:`files`. """ forms = FormsDict() for name, item in self.POST.allitems(): if...
def files(self): """ File uploads parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The values are instances of :class:`cgi.FieldStorage`. The most important attributes are: filename The filename, if specified; otherwise None; this is the client side filename, *not* the file name o...
def iter_headers(self): ''' Yield (header, value) tuples, skipping headers that are not allowed with the current response status code. ''' headers = self._headers.items() bad_headers = self.bad_headers.get(self._status_code) if bad_headers: headers = [h for h in headers if h[0] not in bad_headers] for name, values in h...
def add_path(self, path, base=None, index=None, create=False): ''' Add a new path to the list of search paths. Return False if it does not exist. :param path: The new search path. Relative paths are turned into an absolute and normalized form. If the path looks like a file (not ending in `/`), the filename is stripped ...
+= os.sep if path in self.path: self.path.remove(path) if create and not os.path.isdir(path): os.mkdirs(path) if index is None: self.path.append(path) else: self.path.insert(index, path) self.cache.clear()
def publish(self, json_msg): ''' json_msg = '{"topic1": 1.0, "topic2": {"x": 0.1}}' ''' pyobj = json.loads(json_msg) for topic, value in pyobj.items(): msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value)) self._pub.publish(msg)
def add_file_handler_to_root(log_fn): """Adds a file handler to the root logging. :param log_fn: the name of the log file. :type log_fn: str """ file_handler = logging.FileHandler(log_fn, mode="w") file_handler.setFormatter(logging.Formatter( fmt="[%(asctime)s %(name)s %(levelname)s] %(message)s", datefmt="%Y-%m-%d %H:...
def register(reg_signal=signal.SIGQUIT, reg_unhandled=True, commands=[]): """ Registers exconsole hooks :param reg_signal: if not None, register signal handler (default: ``signal.SIGQUIT``) :param reg_unhandled: if ``True``, register unhandled exception hook (``sys.excepthook``) :param commands: list of custom commands...
def launch(exception=None, extraceback=None, signalnum=None, frame=None): """ Launches an emergency console :param exception: unhandled exception value :param extraceback: unhandled exception traceback :param signalnum: interrupting signal number :param frame: interrupting signal frame """ print('\n') print('Activating...
inspect.getsourcelines(frame) s += '%s:%i' % (inspect.getfile(frame), frame.f_lineno) s += '\n' + ' ' * 10 if frame.f_lineno - current_line < len(lines): s += lines[frame.f_lineno - current_line].strip('\n') print(s) index += 1 def _cmd_help(): print(( "Exconsole interactive emergency console\n" "Builtin commands:\n" "...
in launch.commands: locals[command[0]] = command[2] print('On frame %i' % index) print('Source:') lines, current_line = inspect.getsourcelines(frame) print(''.join( ' ' + ('>>' if lines.index(line) == frame.f_lineno - current_line else ' ') + ' ' + line for line in lines )) active_frame = len(stack) - 1 _cmd_stack() _c...