Python loguru.logger.warning() Examples
The following are 30
code examples of loguru.logger.warning().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
loguru.logger
, or try the search function
.
Example #1
Source File: operations.py From ScaffoldGraph with MIT License | 6 votes |
def write_scaffold(self, scaffold): subscaffolds = ', '.join([str(s.id) for s in scaffold.subscaffolds]) if self.args.sdf: molecule = MolFromSmiles(scaffold.smiles) if molecule is not None: molecule.SetProp('_Name', str(scaffold.id)) molecule.SetIntProp('HIERARCHY', scaffold.hierarchy) molecule.SetProp('SMILES', scaffold.smiles) molecule.SetProp('SUBSCAFFOLDS', subscaffolds) self.output.write(molecule) else: logger.warning(f'Failed to parse scaffold: {scaffold.smiles}') else: self.output.write('{0}\t{1}\t{2}\t{3}\n'.format( scaffold.id, scaffold.hierarchy, scaffold.smiles, subscaffolds))
Example #2
Source File: classifier.py From CharGer with GNU General Public License v3.0 | 6 votes |
def _read_pp2_gene_list(self) -> None: """Read gene list for PP2 module. Load :attr:`pp2_genes` from :attr:`self.config.PP2_gene_list <.CharGerConfig.PP2_gene_list>`. Skip PP2 module if not provided. """ gene_list_pth = self.config.PP2_gene_list # Disable PP2 module if no list is provided if gene_list_pth is None: logger.warning( "CharGer cannot make PP2 calls without the given gene list. " "Disable PP2 module" ) self._acmg_module_availability["PP2"] = ModuleAvailability.INVALID_SETUP return logger.info(f"Read PP2 gene list from {gene_list_pth}") self.pp2_genes = set(l.strip() for l in read_lines(gene_list_pth)) logger.info(f"Marked {len(self.pp2_genes):,d} genes for PP2")
Example #3
Source File: classifier.py From CharGer with GNU General Public License v3.0 | 6 votes |
def _read_bp1_gene_list(self) -> None: """Read gene list for BP1 module. Load :attr:`bp1_genes` from :attr:`self.config.BP1_gene_list <.CharGerConfig.BP1_gene_list>`. Skip BP1 module if not provided. """ gene_list_pth = self.config.BP1_gene_list # Disable BP1 module if no list is provided if gene_list_pth is None: logger.warning( "CharGer cannot make BP1 calls without the given gene list. " "Disable BP1 module" ) self._acmg_module_availability["BP1"] = ModuleAvailability.INVALID_SETUP return logger.info(f"Read BP1 gene list from {gene_list_pth}") self.bp1_genes = set(l.strip() for l in read_lines(gene_list_pth)) logger.info(f"Marked {len(self.bp1_genes):,d} genes for BP1")
Example #4
Source File: backend.py From veros with MIT License | 6 votes |
def init_backends(): init_environment() # populate available backend modules global BACKENDS BACKENDS = {} import numpy if numpy.__name__ == 'bohrium': logger.warning('Running veros with "python -m bohrium" is discouraged ' '(use "--backend bohrium" instead)') import numpy_force numpy = numpy_force BACKENDS['numpy'] = numpy try: import bohrium except ImportError: logger.warning('Could not import Bohrium (Bohrium backend will be unavailable)') BACKENDS['bohrium'] = None else: BACKENDS['bohrium'] = bohrium
Example #5
Source File: snapshot.py From veros with MIT License | 6 votes |
def read_restart(self, vs, infile): restart_vars = {var: vs.variables[var] for var in self.restart_variables} restart_data = {var: getattr(vs, var) for var in self.restart_variables} attributes, variables = self.read_h5_restart(vs, restart_vars, infile) for key, arr in restart_data.items(): try: restart_var = variables[key] except KeyError: logger.warning('Not reading restart data for variable {}: ' 'no matching data found in restart file' .format(key)) continue if not arr.shape == restart_var.shape: logger.warning('Not reading restart data for variable {}: ' 'restart data dimensions do not match model ' 'grid'.format(key)) continue arr[...] = restart_var for attr in self.restart_attributes: try: setattr(vs, attr, attributes[attr]) except KeyError: logger.warning('Not reading restart data for attribute {}: ' 'attribute not found in restart file' .format(attr))
Example #6
Source File: streamfunction_init.py From veros with MIT License | 6 votes |
def _get_solver_class(): ls = rs.linear_solver def _get_best_solver(): if rst.proc_num > 1: try: from .solvers.petsc import PETScSolver except ImportError: logger.warning('PETSc linear solver not available, falling back to SciPy') else: return PETScSolver from .solvers.scipy import SciPySolver return SciPySolver if ls == 'best': return _get_best_solver() elif ls == 'petsc': from .solvers.petsc import PETScSolver return PETScSolver elif ls == 'scipy': from .solvers.scipy import SciPySolver return SciPySolver raise ValueError('unrecognized linear solver %s' % ls)
Example #7
Source File: cli.py From bot with MIT License | 6 votes |
def auto_reload_mixin(func): @click.option( "--autoreload", is_flag=True, default=False, help="Reload application on file changes" ) @functools.wraps(func) def wrapper(autoreload: bool, *args, **kwargs): if autoreload and aiohttp_autoreload: logger.warning( "Application started in live-reload mode. Please disable it in production!" ) aiohttp_autoreload.start() elif autoreload and not aiohttp_autoreload: click.echo("`aiohttp_autoreload` is not installed.", err=True) return func(*args, **kwargs) return wrapper
Example #8
Source File: tc.py From TrafficToll with GNU General Public License v3.0 | 6 votes |
def _get_free_qdisc_id(device: str) -> int: process = run( f"tc qdisc show dev {device}", stdout=subprocess.PIPE, universal_newlines=True, ) ids = set() for line in process.stdout.splitlines(): match = QDISC_ID_REGEX.match(line) if not match: logger.warning("Failed to parse line: {!r}", line) continue id_string = match.group(1) try: id_ = int(id_string) except ValueError: # This should only happen for the ingress QDisc logger.debug( "Failed to parse QDisc ID as base 10 integer on line: {!r}", line ) id_ = int(id_string, 16) ids.add(id_) return _find_free_id(ids)
Example #9
Source File: tc.py From TrafficToll with GNU General Public License v3.0 | 6 votes |
def _get_free_class_id(device: str, qdisc_id: int) -> int: process = run( f"tc class show dev {device}", stdout=subprocess.PIPE, universal_newlines=True, ) ids = set() for line in process.stdout.splitlines(): match = CLASS_ID_REGEX.match(line) if not match: logger.warning("Failed to parse line: {!r}", line) continue groups = match.groupdict() if int(groups["qdisc_id"]) == qdisc_id: ids.add(int(groups["class_id"])) return _find_free_id(ids)
Example #10
Source File: superuser.py From bot with MIT License | 6 votes |
def create_super_user(user_id: int, remove: bool) -> bool: user = await User.query.where(User.id == user_id).gino.first() if not user: logger.error("User is not registered in bot") raise ValueError("User is not registered in bot") logger.info( "Loaded user {user}. It's registered at {register_date}.", user=user.id, register_date=user.created_at, ) await user.update(is_superuser=not remove).apply() if remove: logger.warning("User {user} now IS NOT superuser", user=user_id) else: logger.warning("User {user} now IS superuser", user=user_id) return True
Example #11
Source File: operations.py From ScaffoldGraph with MIT License | 6 votes |
def write_scaffold(self, scaffold): subscaffolds = ', '.join([str(s.id) for s in scaffold.subscaffolds]) if self.args.sdf: molecule = MolFromSmiles(scaffold.smiles) if molecule is not None: molecule.SetProp('_Name', str(scaffold.id)) molecule.SetIntProp('HIERARCHY', scaffold.hierarchy) molecule.SetProp('SMILES', scaffold.smiles) molecule.SetProp('SUBSCAFFOLDS', subscaffolds) self.output.write(molecule) else: logger.warning(f'Failed to parse scaffold: {scaffold.smiles}') else: self.output.write('{0}\t{1}\t{2}\t{3}\n'.format( scaffold.id, scaffold.hierarchy, scaffold.smiles, subscaffolds))
Example #12
Source File: dataframe.py From ScaffoldGraph with MIT License | 6 votes |
def __next__(self): smiles, name = next(self.supplier) try: mol = MolFromSmiles(smiles) mol.SetProp('_Name', str(name)) except AttributeError: logger.warning('Molecule {} : {} could not be parsed'.format( self.cursor, smiles )) self.cursor += 1 return None self.cursor += 1 return mol
Example #13
Source File: cli.py From aria2p with ISC License | 6 votes |
def subcommand_autopurge(api: API) -> int: """ Autopurge subcommand. Parameters: api: the API instance to use. Returns: int: 0 if all success, 1 if one failure. """ version = get_version() if version.major == 0 and 9 > version.minor >= 7: print( "Future change warning: command 'autopurge' will be renamed 'purge' in version 0.9.0, " "with an 'autoremove' alias.", file=sys.stderr, ) if api.autopurge(): return 0 return 1
Example #14
Source File: downloads.py From aria2p with ISC License | 6 votes |
def followed_by(self): """ List of downloads generated as the result of this download. Returns a list of instances of [`Download`][aria2p.downloads.Download]. """ if self._followed_by is None: result = [] for gid in self.followed_by_ids: try: result.append(self.api.get_download(gid)) except ClientException as error: logger.warning(f"Can't find download with GID {gid}, try to update download {self.gid} ({id(self)}") logger.opt(exception=True).trace(error) self._followed_by = result return self._followed_by
Example #15
Source File: downloads.py From aria2p with ISC License | 6 votes |
def belongs_to(self): """ Parent download. Returns an instance of [`Download`][aria2p.downloads.Download]. """ if not self._belongs_to: belongs_to_id = self.belongs_to_id if belongs_to_id: try: self._belongs_to = self.api.get_download(belongs_to_id) except ClientException as error: logger.warning( f"Can't find download with GID {belongs_to_id}, try to update download {self.gid} ({id(self)})" ) logger.opt(exception=True).trace(error) self._belongs_to = None return self._belongs_to
Example #16
Source File: test_contextualize.py From loguru with MIT License | 6 votes |
def test_contextualize_reset(): contexts = [] output = [] def sink(message): contexts.append(message.record["extra"]) output.append(str(message)) logger.add(sink, format="{level} {message}") logger.info("A") with logger.contextualize(abc="def"): logger.debug("B") logger.warning("C") logger.info("D") assert contexts == [{}, {"abc": "def"}, {"abc": "def"}, {}] assert output == ["INFO A\n", "DEBUG B\n", "WARNING C\n", "INFO D\n"]
Example #17
Source File: module_base.py From video_analyst with MIT License | 6 votes |
def load_model_param(self, checkpoint_state_dict): model_state_dict = self.state_dict() for k in list(checkpoint_state_dict.keys()): if k in model_state_dict: shape_model = tuple(model_state_dict[k].shape) shape_checkpoint = tuple(checkpoint_state_dict[k].shape) if shape_model != shape_checkpoint: logger.warning( "'{}' has shape {} in the checkpoint but {} in the " "model! Skipped.".format(k, shape_checkpoint, shape_model)) checkpoint_state_dict.pop(k) # pyre-ignore incompatible = self.load_state_dict(checkpoint_state_dict, strict=False) if incompatible.missing_keys: missing_keys = filter_reused_missing_keys(self, incompatible.missing_keys) if missing_keys: logger.warning(get_missing_parameters_message(missing_keys)) if incompatible.unexpected_keys: logger.warning( get_unexpected_parameters_message(incompatible.unexpected_keys))
Example #18
Source File: csq.py From CharGer with GNU General Public License v3.0 | 6 votes |
def rank_consequence_type(self) -> int: """Rank the severeness of its consequence type (CSQ column ``Consequence``). Severe consequence type has smaller rank (smallest being 0). Ranking is based on the order in :attr:`ALL_CONSEQUENCE_TYPES`. When the CSQ has multiple consequence types separated by ``&``, return the smallest rank of all the types. When the consequence type is not known, return the biggest possible rank + 1. """ ranks: List[int] = [] for ct in self.consequence_types: try: rank = ALL_CONSEQUENCE_TYPES.index(ct) except ValueError: # Assign unknown consequence type to the lowest rank rank = len(ALL_CONSEQUENCE_TYPES) logger.warning( "Got unknown consequence type: {ct}; assign its rank = {rank}", ct=ct, rank=rank, ) ranks.append(rank) return min(ranks)
Example #19
Source File: Base_Logging.py From makemework with MIT License | 6 votes |
def write(self,msg,level='info'): "Write out a message" fname = inspect.stack()[2][3] #May be use a entry-exit decorator instead d = {'caller_func': fname} if level.lower()== 'debug': logger.debug("{module} | {msg}",module=d['caller_func'],msg=msg) elif level.lower()== 'info': logger.info("{module} | {msg}",module=d['caller_func'],msg=msg) elif level.lower()== 'warn' or level.lower()=='warning': logger.warning("{module} | {msg}",module=d['caller_func'],msg=msg) elif level.lower()== 'error': logger.error("{module} | {msg}",module=d['caller_func'],msg=msg) elif level.lower()== 'critical': logger.critical("{module} | {msg}",module=d['caller_func'],msg=msg) else: logger.critical("Unknown level passed for the msg: {}", msg)
Example #20
Source File: cut_result.py From stagesepx with MIT License | 6 votes |
def range_diff( range_list_1: typing.List[VideoCutRange], range_list_2: typing.List[VideoCutRange], *args, **kwargs, ) -> typing.Dict: # 1. stage length compare self_stable_range_count = len(range_list_1) another_stable_range_count = len(range_list_2) if self_stable_range_count != another_stable_range_count: logger.warning( f"stage counts not equal: {self_stable_range_count} & {another_stable_range_count}" ) # 2. stage content compare # TODO will load these pictures in memory at the same time data = dict() for self_id, each_self_range in enumerate(range_list_1): temp = dict() for another_id, another_self_range in enumerate(range_list_2): temp[another_id] = each_self_range.diff( another_self_range, *args, **kwargs ) data[self_id] = temp return data
Example #21
Source File: values.py From vivarium with GNU General Public License v3.0 | 6 votes |
def on_post_setup(self, _): """Finalizes dependency structure for the pipelines.""" # Unsourced pipelines might occur when generic components register # modifiers to values that aren't required in a simulation. unsourced_pipelines = [p for p, v in self._pipelines.items() if not v.source] if unsourced_pipelines: logger.warning(f"Unsourced pipelines: {unsourced_pipelines}") # register_value_producer and register_value_modifier record the # dependency structure for the pipeline source and pipeline modifiers, # respectively. We don't have enough information to record the # dependency structure for the pipeline itself until now, where # we say the pipeline value depends on its source and all its # modifiers. for name, pipe in self._pipelines.items(): dependencies = [] if pipe.source: dependencies += [f'value_source.{name}'] else: dependencies += [f'missing_value_source.{name}'] for i, m in enumerate(pipe.mutators): mutator_name = self._get_modifier_name(m) dependencies.append(f'value_modifier.{name}.{i+1}.{mutator_name}') self.resources.add_resources('value', [name], pipe._call, dependencies)
Example #22
Source File: compat.py From httprunner with Apache License 2.0 | 6 votes |
def ensure_cli_args(args: List) -> List: """ ensure compatibility with deprecated cli args in v2 """ # remove deprecated --failfast if "--failfast" in args: logger.warning(f"remove deprecated argument: --failfast") args.pop(args.index("--failfast")) # convert --report-file to --html if "--report-file" in args: logger.warning(f"replace deprecated argument --report-file with --html") index = args.index("--report-file") args[index] = "--html" args.append("--self-contained-html") # keep compatibility with --save-tests in v2 if "--save-tests" in args: logger.warning( f"generate conftest.py keep compatibility with --save-tests in v2" ) args.pop(args.index("--save-tests")) _generate_conftest_for_summary(args) return args
Example #23
Source File: make.py From httprunner with Apache License 2.0 | 6 votes |
def format_pytest_with_black(*python_paths: Text) -> NoReturn: logger.info("format pytest cases with black ...") try: if is_support_multiprocessing() or len(python_paths) <= 1: subprocess.run(["black", *python_paths]) else: logger.warning( f"this system does not support multiprocessing well, format files one by one ..." ) [subprocess.run(["black", path]) for path in python_paths] except subprocess.CalledProcessError as ex: capture_exception(ex) logger.error(ex) sys.exit(1) except FileNotFoundError: err_msg = """ missing dependency tool: black install black manually and try again: $ pip install black """ logger.error(err_msg) sys.exit(1)
Example #24
Source File: svm.py From stagesepx with MIT License | 5 votes |
def predict_with_object(self, frame: np.ndarray) -> str: """ predict a single object :param frame: :return: """ pic_object = self.feature_func(frame) pic_object = pic_object.reshape(1, -1) # scores for each stages # IMPORTANT: # these scores are not always precise # at the most of time, we used a tiny train data set for training # which may causes 'liblinear failed to converge' # actually, it can know which one is the target class # but the calculated value may becomes weird scores = self._model.decision_function(pic_object)[0] logger.debug(f"scores: {scores}") # in the binary case, return type is different (wtf ...) # for more effective i think if len(self._model.classes_) == 2: # scores is a float # confidence score for self.classes_[1] where >0 means this # class would be predicted return self._model.classes_[1 if scores > 0 else 0] # unknown if max(scores) < self.score_threshold: logger.warning( f"max score is lower than {self.score_threshold}, unknown class" ) return self.UNKNOWN_STAGE_NAME return self._model.classes_[np.argmax(scores)]
Example #25
Source File: graph.py From ScaffoldGraph with MIT License | 5 votes |
def _construct(self, molecules, ring_cutoff=10, progress=False, annotate=True): """ Private method for graph construction, called by constructors Parameters ---------- molecules: iterable of rdkit molecules for processing ring_cutoff: ignore molecules with more than the specified number of rings to avoid extended processing times (default: 10) annotate: if True write an annotated murcko scaffold SMILES string to each molecule edge (molecule --> scaffold) progress: if True show a progress bar monitoring progress (default: False) """ rdlogger.setLevel(4) # Suppress the RDKit logs progress = progress is False desc = self.__class__.__name__ for molecule in tqdm(molecules, disable=progress, desc=desc, miniters=1, dynamic_ncols=True): if molecule is None: # logged in suppliers continue init_molecule_name(molecule) if CalcNumRings(molecule) > ring_cutoff: name = molecule.GetProp('_Name') logger.warning(f'Molecule {name} filtered (> {ring_cutoff} rings)') continue rdmolops.RemoveStereochemistry(molecule) scaffold = Scaffold(get_murcko_scaffold(molecule)) if scaffold: # Checks that a scaffold has at least 1 atom annotation = None if annotate: annotation = get_annotated_murcko_scaffold(molecule, scaffold.mol, False) self.add_scaffold_node(scaffold) self.add_molecule_node(molecule) self.add_molecule_edge(molecule, scaffold, annotation=annotation) if scaffold.rings.count > 1: self._recursive_constructor(scaffold) else: name = molecule.GetProp('_Name') logger.warning(f'No top level scaffold for molecule {name}') rdlogger.setLevel(3) # Enable the RDKit logs
Example #26
Source File: supplier.py From ScaffoldGraph with MIT License | 5 votes |
def __next__(self): mol = next(self.supplier) if mol is None: logger.warning('Molecule {} could not be parsed'.format( self.cursor )) self.cursor += 1 return mol
Example #27
Source File: base.py From stagesepx with MIT License | 5 votes |
def last(self, stage_name: str) -> SingleClassifierResult: for each in self.data[::-1]: if each.stage == stage_name: logger.debug(f"last frame of {stage_name}: {each}") return each logger.warning(f"no stage named {stage_name} found")
Example #28
Source File: cli.py From aria2p with ISC License | 5 votes |
def _changed_name(name, func): def _new_func(*args, **kwargs): logger.warning( f"Deprecation warning: function {name} was renamed {name}s in version 0.6.0," f"and will be removed in version 0.9.0." ) return func(*args, **kwargs) return _new_func
Example #29
Source File: api.py From aria2p with ISC License | 5 votes |
def autopurge(self) -> bool: """ Purge completed, removed or failed downloads from the queue. Returns: Success or failure of the operation. """ version = get_version() if version.major == 0 and 9 > version.minor >= 7: logger.warning("Future change warning: API method 'autopurge' will be renamed 'purge' in version 0.9.0.") return self.client.purge_download_result()
Example #30
Source File: downloads.py From aria2p with ISC License | 5 votes |
def root_files_paths(self): """ Return the unique set of directories/files for this download. Instead of returning all the leaves like self.files, return the relative root directories if any, and relative root files. This property is useful when we need to list the directories and files in order to move or copy them. We don't want to copy files one by one, but rather entire directories at once when possible. Examples: # download dir is /a/b. >>> self.files ["/a/b/c/1.txt", "/a/b/c/2.txt", "/a/b/3.txt"] >>> self.root_files_paths ["/a/b/c", "/a/b/3.txt"] """ if not self._root_files_paths: paths = [] for file in self.files: if file.is_metadata: continue try: relative_path = file.path.relative_to(self.dir) except ValueError as error: logger.warning(f"Can't determine file path '{file.path}' relative to '{self.dir}'") logger.opt(exception=True).trace(error) else: path = self.dir / relative_path.parts[0] if path not in paths: paths.append(path) self._root_files_paths = paths return self._root_files_paths