text
stringlengths
81
112k
Open TCP socket and set it as escpos device def open(self): """ Open TCP socket and set it as escpos device """ self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.device.connect((self.host, self.port)) if self.device is None: print "Could not open socket f...
Generate pinyin for chars, if char is not chinese character, itself will be returned. Chars must be unicode list. def _pinyin_generator(chars, format): """Generate pinyin for chars, if char is not chinese character, itself will be returned. Chars must be unicode list. """ for char in chars:...
Return pinyin of string, the string must be unicode def get(s, delimiter='', format="diacritical"): """Return pinyin of string, the string must be unicode """ return delimiter.join(_pinyin_generator(u(s), format=format))
Return the 1st char of pinyin of string, the string must be unicode def get_initial(s, delimiter=' '): """Return the 1st char of pinyin of string, the string must be unicode """ initials = (p[0] for p in _pinyin_generator(u(s), format="strip")) return delimiter.join(initials)
We build word search trees, where we walk down the letters of a word. For example: 你 Good 你好 Hello Would build the tree 你 / \ You 好 \ Hello def _add_to_tree(tree, word, meaning): ''' We build word search trees, where we walk down the let...
Load in the Chinese-English dictionary. This takes 1-2 seconds. It is done when the other functions are used, but this is public since preloading sometimes makes sense. def init(): ''' Load in the Chinese-English dictionary. This takes 1-2 seconds. It is done when the other functions are used, but ...
Return the set of translations for a single character or word, if available. def translate_word(word, dictionary=['simplified']): ''' Return the set of translations for a single character or word, if available. ''' if not dictionaries: init() for d in dictionary: if word in ...
We return all portions of the tree corresponding to the beginning of `word`. This is used recursively, so we pass the prefix so we can return meaningful words+translations. def _words_at_the_beginning(word, tree, prefix=""): ''' We return all portions of the tree corresponding to the beginning of `...
Return the set of translations for all possible words in a full phrase. Chinese is sometimes ambiguous. We do not attempt to disambiguate, or handle unknown letters especially well. Full parsing is left to upstream logic. def all_phrase_translations(phrase): ''' Return the set of translations for a...
Processing is triggered by field's pre_save method. It will be executed if field's value has been changed (known through descriptor and stashing logic) or if model instance has never been saved before, i.e. no pk set, because there is a chance that field was initialized through model's `...
Generates a key used to set a status on a field def get_status_key(self, instance): """Generates a key used to set a status on a field""" key_id = "inst_%s" % id(instance) if instance.pk is None else instance.pk return "%s.%s-%s-%s" % (instance._meta.app_label, g...
Retrives a status of a field from cache. Fields in state 'error' and 'complete' will not retain the status after the call. def get_status(self, instance): """Retrives a status of a field from cache. Fields in state 'error' and 'complete' will not retain the status after the call. """ ...
Sets the field status for up to 5 minutes. def set_status(self, instance, status): """Sets the field status for up to 5 minutes.""" status_key = self.get_status_key(instance) cache.set(status_key, status, timeout=300)
Returns output mode. If `mode` not set it will try to guess best mode, or next best mode comparing to old mode def get_mode(self, old_mode=None): """Returns output mode. If `mode` not set it will try to guess best mode, or next best mode comparing to old mode """ if self.mode i...
Find the token present at the passed position in the code buffer :return (tuple): a pair (token, start_position) def token_at_cursor(code, pos=0): """ Find the token present at the passed position in the code buffer :return (tuple): a pair (token, start_position) """ l = len(code) end = s...
Send a response to the frontend and return an execute message @param data: response to send @param msg_type (str): message type: 'ok', 'raw', 'error', 'multi' @param silent (bool): suppress output @return (dict): the return value for the kernel def _send(self, data, msg_type='ok', s...
Method called to execute a cell def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False): """ Method called to execute a cell """ self._klog.info("[%.30s] [%d] [%s]", code, silent, user_expressions) # Split lines and re...
Method called on help requests def do_inspect(self, code, cursor_pos, detail_level=0): """ Method called on help requests """ self._klog.info("{%s}", code[cursor_pos:cursor_pos+10]) # Find the token for which help is requested token, start = token_at_cursor(code, cursor...
Method called on autocompletion requests def do_complete(self, code, cursor_pos): """ Method called on autocompletion requests """ self._klog.info("{%s}", code[cursor_pos:cursor_pos+10]) token, start = token_at_cursor(code, cursor_pos) tkn_low = token.lower() if...
The body of the tread: read lines and put them on the queue. def run(self): '''The body of the tread: read lines and put them on the queue.''' for line in iter(self._fd.readline, ''): self._queue.put(line)
Ensure a string does not contain HTML-reserved characters (including double quotes) Optionally also insert a linebreak if the string is too long def escape( x, lb=False ): """ Ensure a string does not contain HTML-reserved characters (including double quotes) Optionally also insert a linebreak ...
Create & return an HTML <div> element by wrapping the passed text buffer. @param txt (basestring): the text buffer to use @param *args (list): if present, \c txt is considered a Python format string, and the arguments are formatted into it @param kwargs (dict): the \c css field can contain the...
Return a Jupyter display_data message, in both HTML & text formats, by joining together all passed messages. @param msglist (iterable): an iterable containing a list of tuples (message, css_style) Each message is either a text string, or a list. In the latter case it is assumed to be ...
Return a Jupyter display_data message, in both HTML & text formats, by formatting a given single message. The passed message may be: * An exception (including a KrnlException): will generate an error message * A list of messages (with \c mtype equal to \c multi) * A single message @param m...
Copy a resource file to a destination def copyresource( resource, filename, destdir ): """ Copy a resource file to a destination """ data = pkgutil.get_data(resource, os.path.join('resources',filename) ) #log.info( "Installing %s", os.path.join(destdir,filename) ) with open( os.path.join(destdi...
Copy the resource files to the kernelspec folder. def install_kernel_resources( destdir, resource=PKGNAME, files=None ): """ Copy the resource files to the kernelspec folder. """ if files is None: files = ['logo-64x64.png', 'logo-32x32.png'] for filename in files: try: c...
Add the kernel CSS to custom.css def install_custom_css( destdir, cssfile, resource=PKGNAME ): """ Add the kernel CSS to custom.css """ ensure_dir_exists( destdir ) custom = os.path.join( destdir, 'custom.css' ) prefix = css_frame_prefix(resource) # Check if custom.css already includes it....
Remove the kernel CSS from custom.css def remove_custom_css(destdir, resource=PKGNAME ): """ Remove the kernel CSS from custom.css """ # Remove the inclusion in the main CSS if not os.path.isdir( destdir ): return False custom = os.path.join( destdir, 'custom.css' ) copy = True ...
Format a result element as an HTML table cell. @param e (list): a pair \c (value,type) @param ct (str): cell type (th or td) @param withtype (bool): add an additional cell with the element type def html_elem(e, ct, withtype=False): """ Format a result element as an HTML table cell. @par...
Return a double iterable as an HTML table @param data (iterable): the data to format @param header (bool): if the first row is a header row @param limit (int): maximum number of rows to render (excluding header) @param withtype (bool): if columns are to have an alternating CSS class (eve...
Return the a string with the data type of a value, for JSON data def jtype(c): """ Return the a string with the data type of a value, for JSON data """ ct = c['type'] return ct if ct != 'literal' else '{}, {}'.format(ct, c.get('xml:lang'))
Return the a string with the data type of a value, for Graph data def gtype(n): """ Return the a string with the data type of a value, for Graph data """ t = type(n).__name__ return str(t) if t != 'Literal' else 'Literal, {}'.format(n.language)
Find if the JSON row contains acceptable language data def lang_match_json(row, hdr, accepted_languages): '''Find if the JSON row contains acceptable language data''' if not accepted_languages: return True languages = set([row[c].get('xml:lang') for c in hdr if c in row and row...
Find if the RDF triple contains acceptable language data def lang_match_rdf(triple, accepted_languages): '''Find if the RDF triple contains acceptable language data''' if not accepted_languages: return True languages = set([n.language for n in triple if isinstance(n, Literal)]) return (not lang...
Find if the XML row contains acceptable language data def lang_match_xml(row, accepted_languages): '''Find if the XML row contains acceptable language data''' if not accepted_languages: return True column_languages = set() for elem in row: lang = elem[0].attrib.get(XML_LANG, None) ...
Convert a JSON response into a double iterable, by rows and columns Optionally add element type, and filter triples by language (on literals) def json_iterator(hdr, rowlist, lang, add_vtype=False): """ Convert a JSON response into a double iterable, by rows and columns Optionally add element type, and ...
Convert a Graph response into a double iterable, by triples and elements. Optionally add element type, and filter triples by language (on literals) def rdf_iterator(graph, lang, add_vtype=False): """ Convert a Graph response into a double iterable, by triples and elements. Optionally add element type, ...
Render to output a result in JSON format def render_json(result, cfg, **kwargs): """ Render to output a result in JSON format """ result = json.loads(result.decode('utf-8')) head = result['head'] if 'results' not in result: if 'boolean' in result: r = u'Result: {}'.format(re...
Generator for an XML row def xml_row(row, lang): ''' Generator for an XML row ''' for elem in row: name = elem.get('name') child = elem[0] ftype = re.sub(r'\{[^}]+\}', '', child.tag) if ftype == 'literal': ftype = '{}, {}'.format(ftype, child.attrib.get(XML_L...
Convert an XML response into a double iterable, by rows and columns Options are: filter triples by language (on literals), add element type def xml_iterator(columns, rowlist, lang, add_vtype=False): """ Convert an XML response into a double iterable, by rows and columns Options are: filter triples by l...
Render to output a result in XML format def render_xml(result, cfg, **kwargs): """ Render to output a result in XML format """ # Raw mode if cfg.dis == 'raw': return {'data': {'text/plain': result.decode('utf-8')}, 'metadata': {}} # Table try: import xml.etre...
Render to output a result that can be parsed as an RDF graph def render_graph(result, cfg, **kwargs): """ Render to output a result that can be parsed as an RDF graph """ # Mapping from MIME types to formats accepted by RDFlib rdflib_formats = {'text/rdf+n3': 'n3', 'text/turtl...
Read and process magics @param line (str): the full line containing a magic @return (list): a tuple (output-message,css-class), where the output message can be a single string or a list (containing a Python format string and its arguments) def magic(self, line): """ ...
Launch an SPARQL query, process & convert results and return them def query(self, query, num=0, silent=False): """ Launch an SPARQL query, process & convert results and return them """ if self.srv is None: raise KrnlException('no endpoint defined') # Add to the quer...
Set a logging configuration, with a rolling file appender. If passed a filename, use it as the logfile, else use a default name. The default logfile is \c sparqlkernel.log, placed in the directory given by (in that order) the \c LOGDIR environment variable, the logdir specified upon kernel installation...
A way to find out a status of a filed. def smartfields_get_field_status(self, field_name): """A way to find out a status of a filed.""" manager = self._smartfields_managers.get(field_name, None) if manager is not None: return manager.get_status(self) return {'state': 'ready'...
Returns new file extension based on a processor's `format` parameter. Overwrite if different extension should be set ex: `'.txt'` or `None` if this processor does not change file's extension. def get_ext(self, format=None, **kwargs): """Returns new file extension based on a processor's `format...
Creates a temporary file. With regular `FileSystemStorage` it does not need to be deleted, instaed file is safely moved over. With other cloud based storage it is a good idea to set `delete=True`. def get_output_file(self, in_file, instance, field, **kwargs): """Creates a temporary file. With ...
@param x : graph entity @param gr (Graph): RDF graph @param preferred_languages (iterable) Return the best available label in the graph for the passed entity. If a set of preferred languages is given, try them in order. If none is found, an arbitrary language will be chosen def label(x, gr, pr...
Convert the RDF graph to DOT Write the dot output to the stream def rdf2dot( g, stream, opts={} ): """ Convert the RDF graph to DOT Write the dot output to the stream """ accept_lang = set( opts.get('lang',[]) ) do_literal = opts.get('literal') nodes = {} links = [] def node_i...
Draw an RDF graph as an image def draw_graph( g, fmt='svg', prg='dot', options={} ): """ Draw an RDF graph as an image """ # Convert RDF to Graphviz buf = StringIO() rdf2dot( g, buf, options ) gv_options = options.get('graphviz',[]) if fmt == 'png': gv_options += [ '-Gdpi=220',...
Compute the scattering matrices for the given PSD and geometries. Returns: The new amplitude (S) and phase (Z) matrices. def get_SZ(self, psd, geometry): """ Compute the scattering matrices for the given PSD and geometries. Returns: The new amplitude (S) and ph...
Initialize the scattering lookup tables. Initialize the scattering lookup tables for the different geometries. Before calling this, the following attributes must be set: num_points, m_func, axis_ratio_func, D_max, geometries and additionally, all the desired attributes of the...
Save the scattering lookup tables. Save the state of the scattering lookup tables to a file. This can be loaded later with load_scatter_table. Other variables will not be saved, but this does not matter because the results of the computations are based only on the contents ...
Load the scattering lookup tables. Load the scattering lookup tables saved with save_scatter_table. Args: fn: The name of the scattering table file. def load_scatter_table(self, fn): """Load the scattering lookup tables. Load the scattering lookup tables s...
Gaussian PDF for orientation averaging. Args: std: The standard deviation in degrees of the Gaussian PDF mean: The mean in degrees of the Gaussian PDF. This should be a number in the interval [0, 180) Returns: pdf(x), a function that returns the value of the spherical Jacobi...
Uniform PDF for orientation averaging. Returns: pdf(x), a function that returns the value of the spherical Jacobian- normalized uniform PDF. It is normalized for the interval [0, 180]. def uniform_pdf(): """Uniform PDF for orientation averaging. Returns: pdf(x), a function that re...
Compute the T-matrix using variable orientation scatterers. This method uses a very slow adaptive routine and should mainly be used for reference purposes. Uses the set particle orientation PDF, ignoring the alpha and beta attributes. Args: tm: TMatrix (or descendant) instance Returns...
Compute the T-matrix using variable orientation scatterers. This method uses a fast Gaussian quadrature and is suitable for most use. Uses the set particle orientation PDF, ignoring the alpha and beta attributes. Args: tm: TMatrix (or descendant) instance. Returns: The amplitu...
A convenience function to set the geometry variables. Args: geom: A tuple containing (thet0, thet, phi0, phi, alpha, beta). See the Scatterer class documentation for a description of these angles. def set_geometry(self, geom): """A convenience function to set the ge...
A convenience function to get the geometry variables. Returns: A tuple containing (thet0, thet, phi0, phi, alpha, beta). See the Scatterer class documentation for a description of these angles. def get_geometry(self): """A convenience function to get the geometry va...
Initialize the T-matrix. def _init_tmatrix(self): """Initialize the T-matrix. """ if self.radius_type == Scatterer.RADIUS_MAXIMUM: # Maximum radius is not directly supported in the original # so we convert it to equal volume radius radius_type = Scatterer.RA...
Retrieve the quadrature points and weights if needed. def _init_orient(self): """Retrieve the quadrature points and weights if needed. """ if self.orient == orientation.orient_averaged_fixed: (self.beta_p, self.beta_w) = quadrature.get_points_and_weights( self.or_pdf...
Mark the amplitude and scattering matrices as up to date. def _set_scatter_signature(self): """Mark the amplitude and scattering matrices as up to date. """ self._scatter_signature = (self.thet0, self.thet, self.phi0, self.phi, self.alpha, self.beta, self.orient)
Get the S and Z matrices for a single orientation. def get_SZ_single(self, alpha=None, beta=None): """Get the S and Z matrices for a single orientation. """ if alpha == None: alpha = self.alpha if beta == None: beta = self.beta tm_outdated = self._tm_sig...
Get the S and Z matrices using the specified orientation averaging. def get_SZ_orient(self): """Get the S and Z matrices using the specified orientation averaging. """ tm_outdated = self._tm_signature != (self.radius, self.radius_type, self.wavelength, self.m, self.axis_ratio, sel...
Get the S and Z matrices using the current parameters. def get_SZ(self): """Get the S and Z matrices using the current parameters. """ if self.psd_integrator is None: (self._S, self._Z) = self.get_SZ_orient() else: scatter_outdated = self._scatter_signature != (s...
Quadratude points and weights for a weighting function. Points and weights for approximating the integral I = \int_left^right f(x) w(x) dx given the weighting function w(x) using the approximation I ~ w_i f(x_i) Args: w_func: The weighting function w(x). Must be a function that ta...
Scattering intensity (phase function) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The differential scattering cross section. def sca_intensity(scatterer, ...
Linear depolarizarion ratio (LDR) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), return LDR_h. If False, return LDR_v. Returns: The LDR. def ldr(scatterer, h_pol=True): """ Linear depolarizarion ratio (LDR) for the current setup....
Scattering cross section for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The scattering cross section. def sca_xsect(scatterer, h_pol=True)...
Extinction cross section for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The extinction cross section. def ext_xsect(scatterer, h_pol=True)...
Single-scattering albedo for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The single-scattering albedo. def ssa(scatterer, h_pol=True): ...
Asymmetry parameter for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The asymmetry parameter. def asym(scatterer, h_pol=True): """Asymme...
Radar cross section for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The radar cross section. def radar_xsect(scatterer, h_pol=True): """Radar cross sectio...
Reflectivity (with number concentration N=1) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The reflectivity. NOTE: To compute reflectivity in dBZ, give the ...
Delta_hv for the current setup. Args: scatterer: a Scatterer instance. Returns: Delta_hv [rad]. def delta_hv(scatterer): """ Delta_hv for the current setup. Args: scatterer: a Scatterer instance. Returns: Delta_hv [rad]. """ Z = scatterer.get_Z() ...
Copolarized correlation (rho_hv) for the current setup. Args: scatterer: a Scatterer instance. Returns: rho_hv. def rho_hv(scatterer): """ Copolarized correlation (rho_hv) for the current setup. Args: scatterer: a Scatterer instance. Returns: rho_hv. """ ...
Specific differential phase (K_dp) for the current setup. Args: scatterer: a Scatterer instance. Returns: K_dp [deg/km]. NOTE: This only returns the correct value if the particle diameter and wavelength are given in [mm]. The scatterer object should be set to forward scattering g...
Maxwell-Garnett EMA for the refractive index. Args: m: Tuple of the complex refractive indices of the media. mix: Tuple of the volume fractions of the media, len(mix)==len(m) (if sum(mix)!=1, these are taken relative to sum(mix)) Returns: The Maxwell-Garnett approximation for ...
Bruggeman EMA for the refractive index. For instructions, see mg_refractive in this module, except this routine only works for two components. def bruggeman_refractive(m, mix): """Bruggeman EMA for the refractive index. For instructions, see mg_refractive in this module, except this routine only ...
Interpolator for the refractive indices of ice. Inputs: File to read the refractive index lookup table from. This is supplied as "ice_refr.dat", retrieved from http://www.atmos.washington.edu/ice_optical_constants/ Returns: A callable object that takes as parameters the wavelength ...
Drop shape relationship function from Thurai2007 (http://dx.doi.org/10.1175/JTECH2051.1) paper. Arguments: D_eq: Drop volume-equivalent diameter (mm) Returns: r: The vertical-to-horizontal drop axis ratio. Note: the Scatterer class expects horizontal to vertical, so you should pass ...
Get and order feature importances from a scikit-learn model or from an array-like structure. If data is a scikit-learn model with sub-estimators (e.g. RandomForest, AdaBoost) the function will compute the standard deviation of each feature. Parameters ---------- data : sklearn model or arr...
Group objects in data using a function or a key def _group_by(data, criteria): """ Group objects in data using a function or a key """ if isinstance(criteria, str): criteria_str = criteria def criteria(x): return x[criteria_str] res = defaultdict(list) for elem...
Given an iterator (k1, k2), returns a function that when called with an object obj returns a tuple of the form: ((k1, obj.parameters[k1]), (k2, obj.parameters[k2])) def _get_params_value(params): """ Given an iterator (k1, k2), returns a function that when called with an object obj ...
Perform the product between two objects even if they don't support iteration def _product(k, v): """ Perform the product between two objects even if they don't support iteration """ if not _can_iterate(k): k = [k] if not _can_iterate(v): v = [v] return list(p...
Convert a mapping object (such as a dictionary) to tuple pairs, using its keys and values to generate the pairs and then generating all possible combinations between those e.g. {1: (1,2,3)} -> (((1, 1),), ((1, 2),), ((1, 3),)) def _mapping_to_tuple_pairs(d): """ Convert a mapping ob...
Plot a learning curve Plot a metric vs number of examples for the training and test set Parameters ---------- train_scores : array-like Scores for the training set test_scores : array-like Scores for the test set train_sizes : array-like Relative or absolute numbers of ...
Plot precision-recall curve. Parameters ---------- y_true : array-like, shape = [n_samples] Correct target values (ground truth). y_score : array-like, shape = [n_samples] or [n_samples, 2] for binary classification or [n_samples, n_classes] for multiclass Target scores (...
Plot precision-recall curve. Parameters ---------- y_true : array-like, shape = [n_samples] Correct target values (ground truth). y_score : array-like, shape = [n_samples] Target scores (estimator predictions). ax : matplotlib Axes Axes object to draw the plot onto, otherwis...
Plot precision-recall curve. Parameters ---------- y_true : array-like, shape = [n_samples, n_classes] Correct target values (ground truth). y_score : array-like, shape = [n_samples, n_classes] Target scores (estimator predictions). ax : matplotlib Axes Axes object to draw t...
Calculates precision at a given proportion. Only supports binary classification. def precision_at(y_true, y_score, proportion, ignore_nas=False): ''' Calculates precision at a given proportion. Only supports binary classification. ''' # Sort scores in descending order scores_sorted = np.sor...
Precision metric tolerant to unlabeled data in y_true, NA values are ignored for the precision calculation def __precision(y_true, y_pred): ''' Precision metric tolerant to unlabeled data in y_true, NA values are ignored for the precision calculation ''' # make copies of the arrays ...
Return the number of labels encountered in the top X proportion def labels_at(y_true, y_score, proportion, normalize=False): ''' Return the number of labels encountered in the top X proportion ''' # Get indexes of scores sorted in descending order indexes = np.argsort(y_score)[::-1] # So...
Plot a validation curve Plot a metric vs hyperpameter values for the training and test set Parameters ---------- train_scores : array-like Scores for the training set test_scores : array-like Scores for the test set param_range : array-like Hyperparameter values used to...
Plot confustion matrix. Parameters ---------- y_true : array-like, shape = [n_samples] Correct target values (ground truth). y_pred : array-like, shape = [n_samples] Target predicted classes (estimator predictions). target_names : list List containing the names of the target...
Get and order feature importances from a scikit-learn model or from an array-like structure. If data is a scikit-learn model with sub-estimators (e.g. RandomForest, AdaBoost) the function will compute the standard deviation of each feature. Parameters ---------- data : sklearn model or array-li...
Plot precision values at different proportions. Parameters ---------- y_true : array-like Correct target values (ground truth). y_score : array-like Target scores (estimator predictions). ax : matplotlib Axes Axes object to draw the plot onto, otherwise uses current Axes ...
Get and order feature importances from a scikit-learn model or from an array-like structure. If data is a scikit-learn model with sub-estimators (e.g. RandomForest, AdaBoost) the function will compute the standard deviation of each feature. Parameters ---------- data : sklearn model or arr...