code
stringlengths
1
18.2k
def is_readable(path): """ Returns if given path is readable. :param path: Path to check access. :type path: unicode :return: Is path writable. :rtype: bool """ if os.access(path, os.R_OK): LOGGER.debug("> '{0}' path is readable.".format(path)) return True else: LOGGER.debug("> '{0}' path is not readable.".format(path)...
def is_writable(path): """ Returns if given path is writable. :param path: Path to check access. :type path: unicode :return: Is path writable. :rtype: bool """ if os.access(path, os.W_OK): LOGGER.debug("> '{0}' path is writable.".format(path)) return True else: LOGGER.debug("> '{0}' path is not writable.".format(path)...
def is_binary_file(file): """ Returns if given file is a binary file. :param file: File path. :type file: unicode :return: Is file binary. :rtype: bool """ file_handle = open(file, "rb") try: chunk_size = 1024 while True: chunk = file_handle.read(chunk_size) if chr(0) in chunk: return True if len(chunk) < chunk_size: b...
def path(self, value): """ Setter for **self.__path** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format("path", value) self.__path = value
def content(self, value): """ Setter for **self.__content** attribute. :param value: Attribute value. :type value: list """ if value is not None: assert type(value) is list, "'{0}' attribute: '{1}' type is not 'list'!".format("content", value) self.__content = value
def cache(self, mode="r", encoding=Constants.default_codec, errors=Constants.codec_error): """ Reads given file content and stores it in the content cache. :param mode: File read mode. :type mode: unicode :param encoding: File encoding codec. :type encoding: unicode :param errors: File encoding errors handling. :type e...
def uncache(self): """ Uncaches the cached content. :return: Method success. :rtype: bool """ LOGGER.debug("> Uncaching '{0}' file content.".format(self.__path)) self.__content = [] return True
def append(self, mode="a", encoding=Constants.default_codec, errors=Constants.codec_error): """ Appends content to defined file. :param mode: File write mode. :type mode: unicode :param encoding: File encoding codec. :type encoding: unicode :param errors: File encoding errors handling. :type errors: unicode :return: Me...
def clear(self, encoding=Constants.default_codec): """ Clears the defined file content. :param encoding: File encoding codec. :type encoding: unicode :return: Method success. :rtype: bool """ if foundations.strings.is_website(self.__path): raise foundations.exceptions.UrlWriteError( "!> {0} | '{1}' url is not writable!...
def cpp_best_split_full_model(X, Uy, C, S, U, noderange, delta, save_memory=False): """wrappe calling cpp splitting function""" return CSP.best_split_full_model(X, Uy, C, S, U, noderange, delta)
def route(self, environ, start_response): """Route :param environ: :param start_response: """ urls = self.url_map.bind_to_environ(environ) request = WsgiRequest(environ) try: endpoint, args = urls.match() except HTTPException as e: return self.error(e.code, request)(environ, start_response) else: procedure = getattr(se...
def rpc(self, request, args): """RPC :param request: :args ???: """ if request.method != 'POST': return self.error(405, request) payload = request.get_data(as_text=True) or '{}' request_method = request.args.get('method') if not request_method: return self.error( 400, request, message="A query string parameter method= ...
self.error(400, request, message=str(e)) method_error_types = self.service.__nirum_method_error_types__ if not callable(method_error_types): # generated by older compiler method_error_types = method_error_types.get method_error = method_error_types(method_facial_name, ()) try: result = service_method(**arguments) excep...
def error(self, status_code, request, message=None): """Handle error response. :param int status_code: :param request: :return: """ status_code_text = HTTP_STATUS_CODES.get(status_code, 'http error') status_error_tag = status_code_text.lower().replace(' ', '_') custom_response_map = { 404: self.make_error_response( sta...
def auth_pair(self, force_console=False): """Return username/password tuple, possibly prompting the user for them.""" if not self.auth_valid(): self._get_auth(force_console) return (self.user, self.password)
def _get_auth(self, force_console=False): """Try to get login auth from known sources.""" if not self.target: raise ValueError("Unspecified target ({!r})".format(self.target)) elif not force_console and self.URL_RE.match(self.target): auth_url = urlparse(self.target) source = 'url' if auth_url.username: self.user = aut...
def _get_auth_from_console(self, realm): """Prompt for the user and password.""" self.user, self.password = self.AUTH_MEMOIZE_INPUT.get(realm, (self.user, None)) if not self.auth_valid(): if not self.user: login = getpass.getuser() self.user = self._raw_input('Username for "{}" [{}]: '.format(realm, login)) or login se...
def _get_auth_from_netrc(self, hostname): """Try to find login auth in ``~/.netrc``.""" try: hostauth = netrc(self.NETRC_FILE) except IOError as cause: if cause.errno != errno.ENOENT: raise return None except NetrcParseError as cause: raise # TODO: Map to common base class, so caller has to handle less error types? # T...
def _get_auth_from_keyring(self): """Try to get credentials using `keyring <https://github.com/jaraco/keyring>`_.""" if not keyring: return None # Take user from URL if available, else the OS login name password = self._get_password_from_keyring(self.user or getpass.getuser()) if password is not None: self.user = self....
def factory(container, name=None): """A decorator to register a factory on the container. For more information see :meth:`Container.add_factory`. """ def register(factory): container.add_factory(factory, name) return factory return register
def service(container, name=None): """A decorator to register a service on a container. For more information see :meth:`Container.add_service`. """ def register(service): container.add_service(service, name) return service return register
def provider(container, cache, name=None): """A decorator to register a provider on a container. For more information see :meth:`Container.add_provider`. """ def register(provider): container.add_provider(provider, cache, name) return provider return register
def provide(self, name): """Gets the value registered with ``name`` and determines whether the value is a provider or a configuration setting. The ``KeyError`` is raised when the ``name`` is not found. The registered value is interpreted as a provider if it's callable. The provider is called with a single argument, the...
def add_provider(self, provider, cache, name=None): """Registers a provider on the container. :param provider: Anything that's callable and expects exactly one argument, the :class:`Container` object. :param cache: Whether to cache the return value of the provider. :param name: Alternative name of the provider. Default...
def is_cached(self, name): """Determines if the return value is cached. Always returns false if the registered value is not an instance of :class:`FunctionCache`. :param name: The name of the provider. """ try: cached = super(Container, self).get(name).cached except AttributeError: cached = False return cached
def copy_content(origin, dstPath, blockSize, mode): ''' copy the content of `origin` to `dstPath` in a safe manner. this function will first copy the content to a temporary file and then move it atomically to the requested destination. if some error occurred during content copy or file movement the temporary file will ...
platform.system() is 'Windows' and e.errno is errno.EEXIST: pass else: raise except: os.remove(tmpPath) raise
def execute(self): """Execute the test batch """ try: # START SELENIUM GRID if BROME_CONFIG['grid_runner']['start_selenium_server']: self.start_selenium_server() # Get all the browsers id self.browsers_id = BROME_CONFIG['runner_args']['remote_runner'].split(',') # noqa # Start all the instances instance_threads = [] fo...
= [] self.instances[browser_id].append( saucelabs_instance.SauceLabsInstance() ) # BROWSERSTACK elif browser_config.location == 'browserstack': if not self.instances.get(browser_id): self.instances[browser_id] = [] self.instances[browser_id].append( browserstack_instance.BrowserstackInstance() ) # LOCALHOST elif browse...
%s" % str(tb) ) raise finally: try: self.tear_down_instances() # MILESTONE with DbSessionContext(BROME_CONFIG['database']['mongo_database_name']) as session: # noqa test_batch = session.query(Testbatch)\ .filter(Testbatch.mongo_id == self.test_batch_id)\ .one() test_batch.add_milestone('InstanceTearDownCompleted') sess...
def run(self): """Run all the test in the test batch """ executed_tests = [] try: active_thread = 0 start_thread = True current_index = 0 active_thread_by_browser_id = {} test_index_by_browser_id = {} for browser_id in self.browsers_id: test_index_by_browser_id[browser_id] = 0 self.kill_test_batch_if_necessary() while ...
test_.pdriver.embed_disabled = True thread = TestThread(test_) thread.start() executed_tests.append(test_) active_thread = len([tn for tn in threading.enumerate() if type(tn) != threading._MainThread and hasattr(tn, 'test')]) # noqa # self.info_log("active_thread=%s" % active_thread) if active_thread: try: active_threa...
def tear_down_instances(self): """Tear down all instances """ self.info_log('Tearing down all instances...') for instance in self.alive_instances: instance.tear_down() self.info_log('[Done]Tearing down all instances')
def start_selenium_server(self): """Start the selenium server """ ip = BROME_CONFIG['grid_runner']['selenium_server_ip'] port = BROME_CONFIG['grid_runner']['selenium_server_port'] def is_selenium_server_is_running(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = s.connect_ex((ip, port)) s.close() retur...
# noqa test_batch.add_milestone( 'SeleniumServerStarted' ) session.save(test_batch, safe=True) return True sleep(2) raise Exception("Selenium server did not start!")
def validate_config(self): """Validate that the browser config contains all the needed config """ # LOCALHOST if self.location == 'localhost': if 'browserName' not in self.config.keys(): msg = "Add the 'browserName' in your local_config: e.g.: 'Firefox', 'Chrome', 'Safari'" # noqa self.runner.critical_log(msg) raise Br...
def validate_ec2_browser_config(self): """Validate that the ec2 config is conform """ if self.config.get('launch', True): required_keys = [ 'browserName', 'platform', 'ssh_key_path', 'username', 'amiid', 'region', 'instance_type', 'security_group_ids', 'selenium_command' ] else: required_keys = [ 'browserName', 'platfo...
def load_contents(self): """ Loads contents of the tables into database. """ with open(METADATA_FILE) as f: lines = f.readlines() lines = map(lambda x: x.strip(), lines) exclude_strings = ['<begin_table>', '<end_table>'] list_of_databases_and_columns = filter( lambda x: not x[0] in exclude_strings, [ list(value) for ke...
def store_contents(self): """ Stores the contents of tables into file. """ string_buffer = os.linesep.join( map( lambda x: os.linesep.join( ["<begin_table>"] + [x.name] + x.columns + ["<end_table>"] ), self.tables ) ) with open(METADATA_FILE, "w") as f: f.write(string_buffer) for i in self.tables: i.store_contents()
def delete_table(self, tablename): """ Deletes a table from the database. """ self.tables = filter(lambda x: x.name != tablename, self.tables)
def get_table(self, tablename): """ Returns the table whoose name is tablename. """ temp = filter(lambda x: x.name == tablename, self.tables) if temp == list(): raise Exception("No such table") return temp[0]
def get_column_list_prefixed(self): """ Returns a list of columns """ return map( lambda x: ".".join([self.name, x]), self.columns )
def get_column(self, column): """ Return the values having of column. """ if "(" in str(column): temp_list = column.split("(") key = temp_list[1].strip("()") func = temp_list[0].lower() else: key = column func = None if "." not in key: for i in self.columns: if i.split(".")[1] == key: key = i break col = map( lambda x:...
def delete_row(self, key, value): """ Deletes the rows where key = value. """ self.rows = filter(lambda x: x.get(key) != value, self.rows)
def invert_delete_row(self, key, value): """ Inverts delete_row and returns the rows where key = value """ self.rows = filter(lambda x: x.get(key) == value, self.rows)
def invert_delete_row2(self, key, value): """ Invert of type two where there are two columns given """ self.rows = filter(lambda x: x.get(key) == x.get(value), self.rows)
def load_contents(self): """ Loads contents of Database from a filename database.csv. """ with open(self.name + ".csv") as f: list_of_rows = f.readlines() list_of_rows = map( lambda x: x.strip(), map( lambda x: x.replace("\"", ""), list_of_rows ) ) for row in list_of_rows: self.put_row(make_row(self.columns, row.split(...
def store_contents(self): """ Stores contests of the Database into a filename database.csv. """ string_buffer = os.linesep.join( map( lambda x: ",".join(x), map( lambda x: map( str, x.values() ), self.rows ) ) ) with open(self.name + ".csv", "w") as f: f.write(string_buffer)
def print_contents(self): """ Prints Contents of Table. """ print "\t\t\t".join(self.columns) temp_list = [] for i in self.columns: temp_list.append(self.get_column(i)) for i in zip(*(temp_list)): print "\t\t\t".join(map(str, i))
def formfield_for_foreignkey(self, db_field, request=None, **kwargs): """ Limit canned reply options to those with same site as comment. """ field = super(CommentReplyAdmin, self).\ formfield_for_foreignkey(db_field, request, **kwargs) comment_id = request.GET.get(self.fk_name, None) if db_field.name == 'canned_reply' ...
def queryset(self, request): """ Exclude replies from listing since they are displayed inline as part of listing. For proxy models with cls apptribute limit comments to those classified as cls. """ qs = super(CommentAdmin, self).queryset(request) qs = qs.filter( Q(user__is_staff=False) | Q(user__isnull=True), is_remove...
def moderate_view(self, request, object_id, extra_context=None): """ Handles moderate object tool through a somewhat hacky changelist view whose queryset is altered via CommentAdmin.get_changelist to only list comments for the object under review. """ opts = self.model._meta app_label = opts.app_label view = CommentAdm...
def bootstrap_alert(visitor, items): """ Format: [[alert(class=error)]]: message """ txt = [] for x in items: cls = x['kwargs'].get('class', '') if cls: cls = 'alert-%s' % cls txt.append('<div class="alert %s">' % cls) if 'close' in x['kwargs']: txt.append('<button class="close" data-dismiss="alert">&times;</button>') ...
def new_bootstrap_alert(visitor, block): """ Format: {% alert class=error %} message {% endalert %} """ if 'new' in block: txt = [] cls = block['kwargs'].get('class', '') if cls: cls = 'alert-%s' % cls txt.append('<div class="alert %s">' % cls) if 'close' in block['kwargs']: txt.append('<button class="close" data-dismi...
def execute(self): """Execute the test batch """ self.browser_config = BrowserConfig( runner=self, browser_id=BROME_CONFIG['runner_args']['localhost_runner'], browsers_config=BROME_CONFIG['browsers_config'] ) try: self.run() except KeyboardInterrupt: self.info_log("Test batch interrupted") except: tb = traceback.format...
def run(self): """Run the test batch """ self.info_log("The test batch is ready.") self.executed_tests = [] for test in self.tests: localhost_instance = LocalhostInstance( runner=self, browser_config=self.browser_config, test_name=test.Test.name ) localhost_instance.startup() with DbSessionContext(BROME_CONFIG['databas...
def terminate(self): """Terminate the test batch """ self.info_log('The test batch is finished.') with DbSessionContext(BROME_CONFIG['database']['mongo_database_name']) as session: # noqa test_batch = session.query(Testbatch)\ .filter(Testbatch.mongo_id == self.test_batch_id).one() test_batch.ending_timestamp = utcnow(...
def idaunpack(buf): """ Special data packing format, used in struct definitions, and .id2 files sdk functions: pack_dd etc. """ buf = bytearray(buf) def nextval(o): val = buf[o] ; o += 1 if val == 0xff: # 32 bit value val, = struct.unpack_from(">L", buf, o) o += 4 return val, o if val < 0x80: # 7 bit value return val, ...
return values
def binary_search(a, k): """ Do a binary search in an array of objects ordered by '.key' returns the largest index for which: a[i].key <= k like c++: a.upperbound(k)-- """ first, last = 0, len(a) while first < last: mid = (first + last) >> 1 if k < a[mid].key: last = mid else: first = mid + 1 return first - 1
def getsectioninfo(self, i): """ Returns a tuple with section parameters by index. The parameteres are: * compression flag * data offset * data size * data checksum Sections are stored in a fixed order: id0, id1, nam, seg, til, id2 """ if not 0 <= i < len(self.offsets): return 0, 0, 0, 0 if self.offsets[i] == 0: return...
def getpart(self, ix): """ Returns a fileobject for the specified section. This method optionally decompresses the data found in the .idb file, and returns a file-like object, with seek, read, tell. """ if self.offsets[ix] == 0: return comp, ofs, size, checksum = self.getsectioninfo(ix) fh = FileSection(self.fh, ofs, o...
def find(self, rel, key): """ Searches for a record with the specified relation to the key A cursor object is returned, the user can call getkey, getval on the cursor to retrieve the actual value. or call cursor.next() / cursor.prev() to enumerate values. 'eq' -> record equal to the key, None when not found 'le' -> las...
raise Exception("b-tree corrupted") cursor = BTree.Cursor(self, stack) # now correct for what was actually asked. if act == rel: pass elif rel == 'eq' and act != 'eq': return None elif rel in ('ge', 'le') and act == 'eq': pass elif rel in ('gt', 'ge') and act == 'lt': cursor.next() elif rel == 'gt' and act == 'eq': cur...
def dump(self): """ raw dump of all records in the b-tree """ print("pagesize=%08x, reccount=%08x, pagecount=%08x" % (self.pagesize, self.reccount, self.pagecount)) self.dumpfree() self.dumptree(self.firstindex)
def dumpfree(self): """ list all free pages """ fmt = "L" if self.version > 15 else "H" hdrsize = 8 if self.version > 15 else 4 pn = self.firstfree if pn == 0: print("no free pages") return while pn: self.fh.seek(pn * self.pagesize) data = self.fh.read(self.pagesize) if len(data) == 0: print("could not read FREE data a...
def dumpindented(self, pn, indent=0): """ Dump all nodes of the current page with keys indented, showing how the `indent` feature works """ page = self.readpage(pn) print(" " * indent, page) if page.isindex(): print(" " * indent, end="") self.dumpindented(page.preceeding, indent + 1) for p in range(len(page.index)): pr...
def dumptree(self, pn): """ Walks entire tree, dumping all records on each page in sequential order """ page = self.readpage(pn) print("%06x: preceeding = %06x, reccount = %04x" % (pn, page.preceeding, page.count)) for ent in page.index: print(" %s" % ent) if page.preceeding: self.dumptree(page.preceeding) for ent in p...
def pagedump(self): """ dump the contents of all pages, ignoring links between pages, this will enable you to view contents of pages which have become lost due to datacorruption. """ self.fh.seek(self.pagesize) pn = 1 while True: try: pagedata = self.fh.read(self.pagesize) if len(pagedata) == 0: break elif len(pagedata...
def prettykey(self, key): """ returns the key in a readable format. """ f = list(self.decodekey(key)) f[0] = f[0].decode('utf-8') if len(f) > 2 and type(f[2]) == bytes: f[2] = f[2].decode('utf-8') if f[0] == '.': if len(f) == 2: return "%s%16x" % tuple(f) elif len(f) == 3: return "%s%16x %s" % tuple(f) elif len(f) == 4...
def prettyval(self, val): """ returns the value in a readable format. """ if len(val) == self.wordsize and val[-1:] in (b'\x00', b'\xff'): return "%x" % struct.unpack("<" + self.fmt, val) if len(val) == self.wordsize and re.search(b'[\x00-\x08\x0b\x0c\x0e-\x1f]', val, re.DOTALL): return "%x" % struct.unpack("<" + self....
def nodeByName(self, name): """ Return a nodeid by name """ # note: really long names are encoded differently: # 'N'+'\x00'+pack('Q', nameid) => ofs # and (ofs, 'N') -> nameid # at nodebase ( 0xFF000000, 'S', 0x100*nameid ) there is a series of blobs for max 0x80000 sized names. cur = self.btree.find('eq', self.namekey...
def makekey(self, *args): """ return a binary key for the nodeid, tag and optional value """ if len(args) > 1: args = args[:1] + (args[1].encode('utf-8'),) + args[2:] if len(args) == 3 and type(args[-1]) == str: # node.tag.string type keys return struct.pack(self.keyfmt[:1 + len(args)], b'.', *args[:-1]) + args[-1].enc...
def decodekey(self, key): """ splits a key in a tuple, one of: ( [ 'N', 'n', '$' ], 0, bignameid ) ( [ 'N', 'n', '$' ], name ) ( '-', id ) ( '.', id ) ( '.', id, tag ) ( '.', id, tag, value ) ( '.', id, 'H', name ) """ if key[:1] in (b'n', b'N', b'$'): if key[1:2] == b"\x00" and len(key) == 2 + self.wordsize: return st...
self.wordsize + 1: f = struct.unpack_from(self.keyfmt[:4], key) return f + (key[2 + self.wordsize:], ) raise Exception("unknown key format")
def bytes(self, *args): """ return a raw value for the given arguments """ if len(args) == 1 and isinstance(args[0], BTree.Cursor): cur = args[0] else: cur = self.btree.find('eq', self.makekey(*args)) if cur: return cur.getval()
def int(self, *args): """ Return the integer stored in the specified node. Any type of integer will be decoded: byte, short, long, long long """ data = self.bytes(*args) if data is not None: if len(data) == 1: return struct.unpack("<B", data)[0] if len(data) == 2: return struct.unpack("<H", data)[0] if len(data) == 4: ...
def string(self, *args): """ return string stored in node """ data = self.bytes(*args) if data is not None: return data.rstrip(b"\x00").decode('utf-8')
def name(self, id): """ resolves a name, both short and long names. """ data = self.bytes(id, 'N') if not data: print("%x has no name" % id) return if data[:1] == b'\x00': nameid, = struct.unpack_from(">" + self.fmt, data, 1) nameblob = self.blob(self.nodebase, 'S', nameid * 256, nameid * 256 + 32) return nameblob.rstr...
def blob(self, nodeid, tag, start=0, end=0xFFFFFFFF): """ Blobs are stored in sequential nodes with increasing index values. most blobs, like scripts start at index 0, long names start at a specified offset. """ startkey = self.makekey(nodeid, tag, start) endkey = self.makekey(nodeid, tag, end) cur = self.btree.find('g...
def dump(self): """ print first and last bits for each segment """ for seg in self.seglist: print("==== %08x-%08x" % (seg.startea, seg.endea)) if seg.endea - seg.startea < 30: for ea in range(seg.startea, seg.endea): print(" %08x: %08x" % (ea, self.getFlags(ea))) else: for ea in range(seg.startea, seg.startea + 10): pr...
def find_segment(self, ea): """ do a linear search for the given address in the segment list """ for seg in self.seglist: if seg.startea <= ea < seg.endea: return seg
def _num_vowel_to_acc(vowel, tone): """Convert a numbered vowel to an accented vowel.""" try: return VOWEL_MAP[vowel + str(tone)] except IndexError: raise ValueError("Vowel must be one of '{}' and tone must be a tone.".format(VOWELS))
def numbered_syllable_to_accented(syllable): """Convert a numbered pinyin syllable to an accented pinyin syllable. Implements the following algorithm, modified from https://github.com/tsroten/zhon: 1. If the syllable has an 'a' or 'e', put the tone over that vowel. 2. If the syllable has 'ou', place the tone over the '...
index. return keep_case_replace(syl, last_vowel, _num_vowel_to_acc(last_vowel, tone))
def to_unicode(data, encoding=Constants.default_codec, errors=Constants.codec_error): """ Converts given data to unicode string using package default settings, fighting **The Hell**! Usage:: >>> to_unicode("myData") u'myData' >>> to_unicode("汉字/漢字") u'\u6c49\u5b57/\u6f22\u5b57' :param data: Data to convert. :type data:...
def _LogRecord_msg(): """ Overrides logging.LogRecord.msg attribute to ensure variable content is stored as unicode. """ def _LogRecord_msgProperty(self): return self.__msg def _LogRecord_msgSetter(self, value): self.__msg = to_unicode(value) logging.LogRecord.msg = property(_LogRecord_msgProperty, _LogRecord_msgSetter...
def tracer(object): """ | Traces execution. | Any method / definition decorated will have it's execution traced through debug messages. | Both object entry and exit are logged. Entering in an object:: INFO : ---> foundations.environment.get_user_application_data_directory() <<<--- Exiting from an object:: INFO : <--- f...
kwargs] nameless_args = map(repr, args[args_count:]) keyword_args = map(foundations.trace.format_argument, kwargs.items()) TRACER_LOGGING_FUNCTION(indent_message("---> {0}({1}) <---".format(trace_name, ", ".join(itertools.chain(positional_args, defaulted_args, nameless_args, keyword_args))))) INDENT_LEVEL += 1 value = ...
def install_logger(logger=None, module=None): """ Installs given logger in given module or default logger in caller introspected module. :param logger: Logger to install. :type logger: Logger :param module: Module. :type module: ModuleType :return: Logger. :rtype: Logger """ logger = logging.getLogger(Constants.logger)...
def uninstall_logger(logger=None, module=None): """ Uninstalls given logger in given module or default logger in caller introspected module. :param logger: Logger to uninstall. :type logger: Logger :param module: Module. :type module: ModuleType :return: Definition success. :rtype: bool """ logger = logging.getLogger(C...
def get_logging_console_handler(logger=None, formatter=LOGGING_DEFAULT_FORMATTER): """ Adds a logging console handler to given logger or default logger. :param logger: Logger to add the handler to. :type logger: Logger :param formatter: Handler formatter. :type formatter: Formatter :return: Added handler. :rtype: Handl...
def get_logging_file_handler(logger=None, file=None, formatter=LOGGING_DEFAULT_FORMATTER): """ Adds a logging file handler to given logger or default logger using given file. :param logger: Logger to add the handler to. :type logger: Logger :param file: File to verbose into. :type file: unicode :param formatter: Handle...
def get_logging_stream_handler(logger=None, formatter=LOGGING_DEFAULT_FORMATTER): """ Adds a logging stream handler to given logger or default logger using given file. :param logger: Logger to add the handler to. :type logger: Logger :param file: File to verbose into. :type file: unicode :param formatter: Handler forma...
def remove_logging_handler(handler, logger=None): """ Removes given logging handler from given logger. :param handler: Handler. :type handler: Handler :param logger: Handler logger. :type logger: Logger :return: Definition success. :rtype: bool """ logger = LOGGER if logger is None else logger logger.handlers and LOGGE...
def set_verbosity_level(verbosity_level=3, logger=None): """ Defines logging verbosity level. Available verbosity levels:: 0: Critical. 1: Error. 2: Warning. 3: Info. 4: Debug. :param verbosity_level: Verbosity level. :type verbosity_level: int :param logger: Logger to set the verbosity level to. :type logger: Logger :...
def stream(self, value): """ Setter for **self.__stream** attribute. :param value: Attribute value. :type value: list """ if value is not None: assert type(value) is list, "'{0}' attribute: '{1}' type is not 'list'!".format("stream", value) self.__stream = value
def write(self, message): """ Writes given message to logger handlers. :param message: Message. :type message: unicode :return: Method success. :rtype: bool """ for handler in self.__logger.__dict__["handlers"]: handler.stream.write(message) return True
def _do_write(self): """ Check commit counter and do a commit if need be """ with self.lock: self._commit_counter += 1 if self._commit_counter >= self._commit_every: self._db.commit() self._commit_counter = 0
def register_type(env_type, alias=None): """Registers environment type. :param str|unicode|Environment env_type: Environment type or its alias (for already registered types). :param str|unicode alias: Alias to register type under. If not set type name is used. :rtype: Environment """ if isinstance(env_type, string_type...